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
|
lcnbeapp/beapp-master
|
MARA.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/plugins/MARA-master/MARA.m
| 12,568 |
utf_8
|
5127d8f931932b5c0760a9a61a0d0b6e
|
% MARA() - Automatic classification of multiple artifact components
% Classies artifactual ICs based on 6 features from the time domain,
% the frequency domain, and the pattern
%
% Usage:
% >> [artcomps, info] = MARA(EEG);
%
% Inputs:
% EEG - input EEG structure
%
% Outputs:
% artcomps - array containing the numbers of the artifactual
% components
% info - struct containing more information about MARA classification
% .posterior_artefactprob : posterior probability for each
% IC of being an artefact
% .normfeats : <6 x nIC > features computed by MARA for each IC,
% normalized by the training data
% The features are: (1) Current Density Norm, (2) Range
% in Pattern, (3) Local Skewness of the Time Series,
% (4) Lambda, (5) 8-13 Hz, (6) FitError.
%
% For more information see:
% I. Winkler, S. Haufe, and M. Tangermann, Automatic classification of artifactual ICA-components
% for artifact removal in EEG signals, Behavioral and Brain Functions, 7, 2011.
%
% See also: processMARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [artcomps, info] = MARA(EEG)
try
%%%%%%%%%%%%%%%%%%%%
%% Calculate features from the pattern (component map)
%%%%%%%%%%%%%%%%%%%%
% extract channel labels
clab = {};
for i=1:length(EEG.chanlocs)
clab{i} = EEG.chanlocs(i).labels;
end
% cut to channel labels common with training data
load('fv_training_MARA'); %load struct fv_tr
[clab_common i_te i_tr ] = intersect(upper(clab), upper(fv_tr.clab));
clab_common = fv_tr.clab(i_tr);
if length(clab_common) == 0
error(['There were no matching channeldescriptions found.' , ...
'MARA needs channel labels of the form Cz, Oz, F3, F4, Fz, etc. Aborting.'])
end
patterns = (EEG.icawinv(i_te,:));
[M100 idx] = get_M100_ADE(clab_common); %needed for Current Density Norm
disp('MARA is computing features. Please wait');
%standardize patterns
patterns = patterns./repmat(std(patterns,0,1),length(patterns(:,1)),1);
%compute current density norm
feats(1,:) = log(sqrt(sum((M100*patterns(idx,:)).^2)));
%compute spatial range
feats(2,:) = log(max(patterns) - min(patterns));
%%%%%%%%%%%%%%%%%%%%
%% Calculate time and frequency features
%%%%%%%%%%%%%%%%%%%%
%compute time and frequency features (Current Density Norm, Range Within Pattern,
%Average Local Skewness, Band Power 8 - 13 Hz)
feats(3:6,:) = extract_time_freq_features(EEG);
disp('Features ready');
%%%%%%%%%%%%%%%%%%%%%%
%% Adapt train features to clab
%%%%%%%%%%%%%%%%%%%%
fv_tr.pattern = fv_tr.pattern(i_tr, :);
fv_tr.pattern = fv_tr.pattern./repmat(std(fv_tr.pattern,0,1),length(fv_tr.pattern(:,1)),1);
fv_tr.x(2,:) = log(max(fv_tr.pattern) - min(fv_tr.pattern));
fv_tr.x(1,:) = log(sqrt(sum((M100 * fv_tr.pattern).^2)));
%%%%%%%%%%%%%%%%%%%%
%% Classification
%%%%%%%%%%%%%%%%%%%%
[C, foo, posterior] = classify(feats',fv_tr.x',fv_tr.labels(1,:));
artcomps = find(C == 0)';
info.posterior_artefactprob = posterior(:, 1)';
info.normfeats = (feats - repmat(mean(fv_tr.x, 2), 1, size(feats, 2)))./ ...
repmat(std(fv_tr.x,0, 2), 1, size(feats, 2));
catch
eeglab_error;
artcomps = [];
end
end
function features = extract_time_freq_features(EEG)
% - 1st row: Average Local Skewness
% - 2nd row: lambda
% - 3rd row: Band Power 8 - 13 Hz
% - 4rd row: Fit Error
%
data = EEG.data;
fs = EEG.srate; %sampling frequency
% transform epoched data into continous data
if length(size(data)) == 3
s = size(data);
data = reshape(data, [EEG.nbchan, prod(s(2:3))]);
end
%downsample (to 100-200Hz)
factor = max(floor(EEG.srate/100),1);
data = data(:, 1:factor:end);
fs = round(fs/factor);
%compute icaactivation and standardise variance to 1
icacomps = (EEG.icaweights * EEG.icasphere * data)';
icacomps = icacomps./repmat(std(icacomps,0,1),length(icacomps(:,1)),1);
icacomps = icacomps';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Calculate featues
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for ic=1:length(icacomps(:,1)) %for each component
fprintf('.');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Proc Spectrum for Channel
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[pxx, freq] = pwelch(icacomps(ic,:), ones(1, fs), [], fs, fs);
pxx = 10*log10(pxx * fs/2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The average log band power between 8 and 13 Hz
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
p = 0;
for i = 8:13
p = p + pxx(find(freq == i,1));
end
Hz8_13 = p / (13-8+1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% lambda and FitError: deviation of a component's spectrum from
% a protoptypical 1/frequency curve
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
p1.x = 2; %first point: value at 2 Hz
p1.y = pxx(find(freq == p1.x,1));
p2.x = 3; %second point: value at 3 Hz
p2.y = pxx(find(freq == p2.x,1));
%third point: local minimum in the band 5-13 Hz
p3.y = min(pxx(find(freq == 5,1):find(freq == 13,1)));
p3.x = freq(find(pxx == p3.y,1));
%fourth point: min - 1 in band 5-13 Hz
p4.x = p3.x - 1;
p4.y = pxx(find(freq == p4.x,1));
%fifth point: local minimum in the band 33-39 Hz
p5.y = min(pxx(find(freq == 33,1):find(freq == 39,1)));
p5.x = freq(find(pxx == p5.y,1));
%sixth point: min + 1 in band 33-39 Hz
p6.x = p5.x + 1;
p6.y = pxx(find(freq == p6.x,1));
pX = [p1.x; p2.x; p3.x; p4.x; p5.x; p6.x];
pY = [p1.y; p2.y; p3.y; p4.y; p5.y; p6.y];
myfun = @(x,xdata)(exp(x(1))./ xdata.^exp(x(2))) - x(3);
xstart = [4, -2, 54];
try
fittedmodel = lsqcurvefit(myfun,xstart,double(pX),double(pY), [], [], optimset('Display', 'off'));
catch
try
% If the optimization toolbox is missing we try with the CurveFit toolbox
opt = fitoptions('Method','NonlinearLeastSquares','Startpoint',xstart);
myfun = fittype('exp(x1)./x.^exp(x2) - x3;','options',opt);
fitobject = fit(double(pX),double(pY),myfun);
fittedmodel = [fitobject.x1, fitobject.x2, fitobject.x3];
catch
% If the CurveFit toolbox is also missing we try with the Statistitcs toolbox
myfun = @(p,xdata)(exp(p(1))./ xdata.^exp(p(2))) - p(3);
mdl = NonLinearModel.fit(double(pX),double(pY),myfun,xstart);
fittedmodel = mdl.Coefficients.Estimate(:)';
end
end
%FitError: mean squared error of the fit to the real spectrum in the band 2-40 Hz.
ts_8to15 = freq(find(freq == 8) : find(freq == 15));
fs_8to15 = pxx(find(freq == 8) : find(freq == 15));
fiterror = log(norm(myfun(fittedmodel, ts_8to15)-fs_8to15)^2);
%lambda: parameter of the fit
lambda = fittedmodel(2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Averaged local skewness 15s
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
interval = 15;
abs_local_scewness = [];
for i=1:interval:length(icacomps(ic,:))/fs-interval
abs_local_scewness = [abs_local_scewness, abs(skewness(icacomps(ic, i * fs:(i+interval) * fs)))];
end
if isempty(abs_local_scewness)
error('MARA needs at least 15ms long ICs to compute its features.')
else
mean_abs_local_scewness_15 = log(mean(abs_local_scewness));
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Append Features
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
features(:,ic)= [mean_abs_local_scewness_15, lambda, Hz8_13, fiterror];
end
disp('.');
end
function [M100, idx_clab_desired] = get_M100_ADE(clab_desired)
% [M100, idx_clab_desired] = get_M100_ADEC(clab_desired)
%
% IN clab_desired - channel setup for which M100 should be calculated
% OUT M100
% idx_clab_desired
% M100 is the matrix such that feature = norm(M100*ica_pattern(idx_clab_desired), 'fro')
%
% (c) Stefan Haufe
lambda = 100;
load inv_matrix_icbm152; %L (forward matrix 115 x 2124 x 3), clab (channel labels)
[cl_ ia idx_clab_desired] = intersect(clab, clab_desired);
F = L(ia, :, :); %forward matrix for desired channels labels
[n_channels m foo] = size(F); %m = 2124, number of dipole locations
F = reshape(F, n_channels, 3*m);
%H - matrix that centralizes the pattern, i.e. mean(H*pattern) = 0
H = eye(n_channels) - ones(n_channels, n_channels)./ n_channels;
%W - inverse of the depth compensation matrix Lambda
W = sloreta_invweights(L);
L = H*F*W;
%We have inv(L'L +lambda eye(size(L'*L))* L' = L'*inv(L*L' + lambda
%eye(size(L*L')), which is easier to calculate as number of dimensions is
%much smaller
%calulate the inverse of L*L' + lambda * eye(size(L*L')
[U D] = eig(L*L');
d = diag(D);
di = d+lambda;
di = 1./di;
di(d < 1e-10) = 0;
inv1 = U*diag(di)*U'; %inv1 = inv(L*L' + lambda *eye(size(L*L'))
%get M100
M100 = L'*inv1*H;
end
function W = sloreta_invweights(LL)
% inverse sLORETA-based weighting
%
% Synopsis:
% W = sloreta_invweights(LL);
%
% Arguments:
% LL: [M N 3] leadfield tensor
%
% Returns:
% W: [3*N 3*N] block-diagonal matrix of weights
%
% Stefan Haufe, 2007, 2008
%
% License
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see http://www.gnu.org/licenses/.
[M N NDUM]=size(LL);
L=reshape(permute(LL, [1 3 2]), M, N*NDUM);
L = L - repmat(mean(L, 1), M, 1);
T = L'*pinv(L*L');
W = spalloc(N*NDUM, N*NDUM, N*NDUM*NDUM);
for ivox = 1:N
W(NDUM*(ivox-1)+(1:NDUM), NDUM*(ivox-1)+(1:NDUM)) = (T(NDUM*(ivox-1)+(1:NDUM), :)*L(:, NDUM*(ivox-1)+(1:NDUM)))^-.5;
end
ind = [];
for idum = 1:NDUM
ind = [ind idum:NDUM:N*NDUM];
end
W = W(ind, ind);
end
function [i_te, i_tr] = findconvertedlabels(pos_3d, chanlocs)
% IN pos_3d - 3d-positions of training channel labels
% chanlocs - EEG.chanlocs structure of data to be classified
%compute spherical coordinates theta and phi for the training channel
%label
[theta, phi, r] = cart2sph(pos_3d(1,:),pos_3d(2,:), pos_3d(3,:));
theta = theta - pi/2;
theta(theta < -pi) = theta(theta < -pi) + 2*pi;
theta = theta*180/pi;
phi = phi * 180/pi;
theta(find(pos_3d(1,:) == 0 & pos_3d(2,:) == 0)) = 0; %exception for Cz
clab_common = {};
i_te = [];
i_tr = [];
%For each channel in EEG.chanlocs, try to find matching channel in
%training data
for chan = 1:length(chanlocs)
if not(isempty(chanlocs(chan).sph_phi))
idx = find((theta <= chanlocs(chan).sph_theta + 6) ...
& (theta >= chanlocs(chan).sph_theta - 6) ...
& (phi <= chanlocs(chan).sph_phi + 6) ...
& (phi >= chanlocs(chan).sph_phi - 6));
if not(isempty(idx))
i_tr = [i_tr, idx(1)];
i_te = [i_te, chan];
end
end
end
end
|
github
|
lcnbeapp/beapp-master
|
pop_selectcomps_MARA.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/plugins/MARA-master/pop_selectcomps_MARA.m
| 7,617 |
utf_8
|
3df13de5291a735a3ae902eb9b7b4349
|
% pop_selectcomps_MARA() - Display components with checkbox to label
% them for artifact rejection
%
% Usage:
% >> EEG = pop_selectcomps_MARA(EEG, gcompreject_old);
%
% Inputs:
% EEG - Input dataset with rejected components (saved in
% EEG.reject.gcompreject)
%
% Optional Input:
% gcompreject_old - gcompreject to revert to in case the "Cancel"
% button is pressed
%
% Output:
% EEG - Output dataset with updated rejected components
%
% See also: processMARA(), pop_selectcomps()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, com] = pop_selectcomps_MARA(EEG, varargin)
if isempty(EEG.reject.gcompreject)
EEG.reject.gcompreject = zeros(size(EEG.icawinv,2));
end
if not(isempty(varargin))
gcompreject_old = varargin{1};
com = [ 'pop_selectcomps_MARA(' inputname(1) ',' inputname(2) ');'];
else
gcompreject_old = EEG.reject.gcompreject;
com = [ 'pop_selectcomps_MARA(' inputname(1) ');'];
end
try
set(0,'units','pixels');
resolution = get(0, 'Screensize');
width = resolution(3);
height = resolution(4);
panelsettings = {};
panelsettings.completeNumber = length(EEG.reject.gcompreject);
panelsettings.rowsize = 250;
panelsettings.columnsize = 300;
panelsettings.column = floor(width/panelsettings.columnsize);
panelsettings.rows = floor(height/panelsettings.rowsize);
panelsettings.numberPerPage = panelsettings.column * panelsettings.rows;
panelsettings.pages = ceil(length(EEG.reject.gcompreject)/ panelsettings.numberPerPage);
panelsettings.incy = 110;
panelsettings.incx = 110;
% display components on a number of different pages
for page=1:panelsettings.pages
EEG = selectcomps_1page(EEG, page, panelsettings, gcompreject_old);
end;
checks = findall(0, 'style', 'checkbox');
for i = 1: length(checks)
set(checks(i), 'Enable', 'on')
end
catch
eeglab_error
end
function EEG = selectcomps_1page(EEG, page, panelsettings, gcompreject_old)
% Display components with checkbox to label them for artifact rejection
try, icadefs;
catch,
BACKCOLOR = [0.8 0.8 0.8];
GUIBUTTONCOLOR = [0.8 0.8 0.8];
end;
% compute components (for plotting the spectrum)
if length(size(EEG.data)) == 3
s = size(EEG.data);
data = reshape(EEG.data, [EEG.nbchan, prod(s(2:3))]);
icacomps = EEG.icaweights * EEG.icasphere * data;
else
icacomps = EEG.icaweights * EEG.icasphere * EEG.data;
end
% set up the figure
% %%%%%%%%%%%%%%%%
if ~exist('fig')
mainFig = figure('name', [ 'MARA on dataset: ' EEG.setname ''], 'numbertitle', 'off', 'tag', 'ADEC - Plot');
set(mainFig, 'Color', BACKCOLOR)
set(gcf,'MenuBar', 'none');
pos = get(gcf,'Position');
set(gcf,'Position', [20 20 panelsettings.columnsize*panelsettings.column panelsettings.rowsize*panelsettings.rows]);
panelsettings.sizewx = 50/panelsettings.column;
panelsettings.sizewy = 80/panelsettings.rows;
pos = get(gca,'position'); % plot relative to current axes
hh = gca;
panelsettings.q = [pos(1) pos(2) 0 0];
panelsettings.s = [pos(3) pos(4) pos(3) pos(4)]./100;
axis off;
end;
% compute range of components to display
if page < panelsettings.pages
range = (1 + (panelsettings.numberPerPage * (page-1))) : (panelsettings.numberPerPage + ( panelsettings.numberPerPage * (page-1)));
else
range = (1 + (panelsettings.numberPerPage * (page-1))) : panelsettings.completeNumber;
end
data = struct;
data.gcompreject = EEG.reject.gcompreject;
data.gcompreject_old = gcompreject_old;
guidata(gcf, data);
% draw each component
% %%%%%%%%%%%%%%%%
count = 1;
for ri = range
% compute coordinates
X = mod(count-1, panelsettings.column)/panelsettings.column * panelsettings.incx-10;
Y = (panelsettings.rows-floor((count-1)/panelsettings.column))/panelsettings.rows * panelsettings.incy - panelsettings.sizewy*1.3;
% plot the head
if ~strcmp(get(gcf, 'tag'), 'ADEC - Plot');
disp('Aborting plot');
return;
end;
ha = axes('Units','Normalized', 'Position',[X Y panelsettings.sizewx*0.85 panelsettings.sizewy*0.85].*panelsettings.s+panelsettings.q);
topoplot( EEG.icawinv(:,ri), EEG.chanlocs, 'verbose', 'off', 'style' , 'fill');
axis square;
% plot the spectrum
ha = axes('Units','Normalized', 'Position',[X+1.05*panelsettings.sizewx Y-1 (panelsettings.sizewx*1.15)-1 panelsettings.sizewy-1].*panelsettings.s+panelsettings.q);
[pxx, freq] = pwelch(icacomps(ri,:), ones(1, EEG.srate), [], EEG.srate, EEG.srate);
pxx = 10*log10(pxx * EEG.srate/2);
plot(freq, pxx, 'LineWidth', 2)
xlim([0 50]);
grid on;
xlabel('Hz')
set(gca, 'Xtick', 0:10:50)
if isfield(EEG.reject, 'MARAinfo')
title(sprintf('Artifact Probability = %1.2f', ...
EEG.reject.MARAinfo.posterior_artefactprob(ri)));
end
uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[X+panelsettings.sizewx*0.5 Y+panelsettings.sizewy panelsettings.sizewx, ...
panelsettings.sizewy*0.2].*panelsettings.s+panelsettings.q, ...
'Enable', 'off','tag', ['check_' num2str(ri)], 'Value', EEG.reject.gcompreject(ri), ...
'String', ['IC' num2str(ri) ' - Artifact?'], ...
'Callback', {@callback_checkbox, ri});
drawnow;
count = count +1;
end;
% draw the botton buttons
% %%%%%%%%%%%%%%%%
if ~exist('fig')
% cancel button
cancelcommand = ['openplots = findall(0, ''tag'', ''ADEC - Plot'');', ...
'data = guidata(openplots(1)); close(openplots);', ...
'EEG.reject.gcompreject = data.gcompreject_old;'];
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'Cancel', ...
'Units','Normalized', 'BackgroundColor', GUIBUTTONCOLOR, ...
'Position',[-10 -11 15 panelsettings.sizewy*0.25].*panelsettings.s+panelsettings.q, ...
'callback', cancelcommand );
okcommand = ['data = guidata(gcf); EEG.reject.gcompreject = data.gcompreject; ' ...
'[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET); '...
'eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET);''); '...
'close(gcf);' ];
% ok button
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'OK', ...
'Units','Normalized', 'BackgroundColor', GUIBUTTONCOLOR, ...
'Position',[10 -11 15 panelsettings.sizewy*0.25].*panelsettings.s+panelsettings.q, ...
'callback', okcommand);
end;
function callback_checkbox(hObject,eventdata, position)
openplots = findall(0, 'tag', 'ADEC - Plot');
data = guidata(openplots(1));
data.gcompreject(position) = mod(data.gcompreject(position) + 1, 2);
%save changes in every plot
for i = 1: length(openplots)
guidata(openplots(i), data);
end
|
github
|
lcnbeapp/beapp-master
|
pop_processMARA.m
|
.m
|
beapp-master/Packages/eeglab14_1_2b/plugins/MARA-master/pop_processMARA.m
| 5,095 |
utf_8
|
7932742793cce3ca7b8caeb78ae22d82
|
% pop_processMARA() - graphical interface to select MARA's actions
%
% Usage:
% >> [ALLEEG,EEG,CURRENTSET,com] = pop_processMARA(ALLEEG,EEG,CURRENTSET );
%
% Inputs and Outputs:
% ALLEEG - array of EEG dataset structures
% EEG - current dataset structure or structure array
% (EEG.reject.gcompreject will be updated)
% CURRENTSET - index(s) of the current EEG dataset(s) in ALLEEG
%
%
% Output:
% com - last command, call to itself
%
% See also: processMARA(), pop_selectcomps_MARA(), MARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ALLEEG,EEG,CURRENTSET,com] = pop_processMARA (ALLEEG,EEG,CURRENTSET )
com = 'pop_processMARA ( ALLEEG,EEG,CURRENTSET )';
try, icadefs;
catch,
BACKCOLOR = [0.8 0.8 0.8];
GUIBUTTONCOLOR = [0.8 0.8 0.8];
end;
% set up the figure
% %%%%%%%%%%%%%%%%%
figure('name', 'MARA', ...
'numbertitle', 'off', 'tag', 'ADEC - Init');
set(gcf,'MenuBar', 'none', 'Color', BACKCOLOR);
pos = get(gcf,'Position');
set(gcf,'Position', [pos(1) 350 350 350]);
if ~strcmp(get(gcf, 'tag'), 'ADEC - Init');
disp('Aborting plot');
return;
end;
% set standards for options and store them with guidata()
% order: filter, run_ica, plot data, remove automatically
options = [0, 0, 0, 0, 0];
guidata(gcf, options);
% text
% %%%%%%%%%%%%%%%%%
text = uicontrol(gcf, 'Style', 'text', 'Units','Normalized', 'Position',...
[0 0.85 0.75 0.06],'BackGroundColor', BACKCOLOR, 'FontWeight', 'bold', ...
'String', 'Select preprocessing operations:');
text = uicontrol(gcf, 'Style', 'text', 'Units','Normalized', 'Position',...
[0 0.55 0.75 0.06],'BackGroundColor', BACKCOLOR, 'FontWeight', 'bold', ...
'String', 'After MARA classification:');
% checkboxes
% %%%%%%%%%%%%%%%%%
filterBox = uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[0.075 0.75 0.75 0.075], 'String', 'Filter the data', 'Callback', ...
'options = guidata(gcf); options(1) = mod(options(1) + 1, 2); guidata(gcf,options);');
icaBox = uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[0.075 0.65 0.75 0.075], 'String', 'Run ICA', 'Callback', ...
'options = guidata(gcf); options(2) = mod(options(2) + 1, 2); guidata(gcf,options);');
% radio button group
% %%%%%%%%%%%%%%%%%
vizBox = uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[0.2 0.2 0.9 0.2], 'String', 'Visualize Classifcation Features', 'Enable', 'Off', ...
'tag', 'vizBox');
h = uibuttongroup('visible','off','Units','Normalized','Position',[0.075 0.15 0.9 0.35]);
% Create two radio buttons in the button group.
radNothing = uicontrol('Style','radiobutton','String','Continue using EEGLab functions',...
'Units','Normalized','Position',[0.02 0.8 0.9 0.2],'parent',h,'HandleVisibility','off','tag', 'radNothing');
radPlot = uicontrol('Style','radiobutton','String','Plot and select components for removal',...
'Units','Normalized','Position',[0.02 0.5 0.9 0.2],'parent',h,'HandleVisibility','off',...
'tag', 'radPlot');
radAuto = uicontrol('Style','radiobutton','String','Automatically remove components',...
'Units','Normalized','Position',[0.02 0.1 0.9 0.2],'parent',h,'HandleVisibility','off','tag', 'radAuto');
set(h,'SelectedObject',radNothing,'Visible','on', 'tag', 'h','BackGroundColor', BACKCOLOR);
set(h, 'SelectionChangeFcn',['s = guihandles(gcf); if get(s.h, ''SelectedObject'') == s.radPlot; ' ...
'set(s.vizBox,''Enable'', ''on''); else; set(s.vizBox,''Enable'', ''off''); end;']);
% bottom buttons
% %%%%%%%%%%%%%%%%%
cancel = uicontrol(gcf, 'Style', 'pushbutton', 'Units','Normalized', 'Position',...
[0.075 0.05 0.4 0.08],'String', 'Cancel','BackgroundColor', GUIBUTTONCOLOR,...
'Callback', 'close(gcf);');
ok = uicontrol(gcf, 'Style', 'pushbutton', 'Units','Normalized', 'Position',...
[0.5 0.05 0.4 0.08],'String', 'Ok','BackgroundColor', GUIBUTTONCOLOR, ...
'Callback', ['options = guidata(gcf);' ...
's = guihandles(gcf); if get(s.h, ''SelectedObject'') == s.radPlot; options(3) = 1; end; '...
'options(4) = get(s.vizBox, ''Value''); ' ...
'if get(s.h, ''SelectedObject'') == s.radAuto; options(5) = 1; end;' ...
'close(gcf); pause(eps); [ALLEEG, EEG, CURRENTSET] = processMARA(ALLEEG,EEG,CURRENTSET, options);']);
|
github
|
lcnbeapp/beapp-master
|
fooof_group.m
|
.m
|
beapp-master/Packages/fooof-master/fooof_mat-master/matlab_wrapper/fooof_group.m
| 1,475 |
utf_8
|
974a8666887be9f1b2a2c5bdc3238423
|
% fooof_group() run the fooof model on a group of neural power spectra
%
% Usage:
% fooof_results = fooof_group(freqs, psds, f_range, settings);
%
% Inputs:
% freqs = row vector of frequency values
% psds = matrix of power values, which each row representing a spectrum
% f_range = fitting range (Hz)
% settings = fooof model settings, in a struct, including:
% settings.peak_width_limts
% settings.max_n_peaks
% settings.min_peak_amplitude
% settings.peak_threshold
% settings.background_mode
% settings.verbose
%
% Outputs:
% fooof_results = fooof model ouputs, in a struct, including:
% fooof_results.background_params
% fooof_results.peak_params
% fooof_results.gaussian_params
% fooof_results.error
% fooof_results.r_squared
%
% Notes
% Not all settings need to be set. Any settings that are not
% provided as set to default values. To run with all defaults,
% input settings as an empty struct.
function fooof_results = fooof_group(freqs, psds, f_range, settings)
% Check settings - get defaults for those not provided
settings = fooof_check_settings(settings);
% Initialize object to collect FOOOF results
fooof_results = [];
% Run FOOOF across the group of power spectra
for psd = psds
cur_results = fooof(freqs, psd', f_range, settings);
fooof_results = [fooof_results, cur_results];
end
end
|
github
|
lcnbeapp/beapp-master
|
fooof_check_settings.m
|
.m
|
beapp-master/Packages/fooof-master/fooof_mat-master/matlab_wrapper/fooof_check_settings.m
| 735 |
utf_8
|
1288684349fda0893e8d12f386f68e6c
|
% Check fooof settings, provided as a struct
% Any settings not specified are set to default values
function settings = fooof_check_settings(settings)
if ~isfield(settings, 'peak_width_limits')
settings.peak_width_limits = [0.5, 12];
end
if ~isfield(settings, 'max_n_peaks')
settings.max_n_peaks = Inf;
end
if ~isfield(settings, 'min_peak_amplitude')
settings.min_peak_amplitude = 0.0;
end
if ~isfield(settings, 'peak_threshold')
settings.peak_threshold = 2.0;
end
if ~isfield(settings, 'background_mode')
settings.background_mode = 'fixed';
end
if ~isfield(settings, 'verbose')
settings.verbose = true;
end
end
|
github
|
lcnbeapp/beapp-master
|
fooof_unpack_results.m
|
.m
|
beapp-master/Packages/fooof-master/fooof_mat-master/matlab_wrapper/fooof_unpack_results.m
| 941 |
utf_8
|
3bc34ef5c084798af19241baef790402
|
% Unpack fooof_results python object into matlab struct
function results_out = fooof_unpack_results(results_in)
results_out = struct();
results_out.background_params = ...
double(py.array.array('d', results_in.background_params));
temp = double(py.array.array('d', results_in.peak_params.ravel));
results_out.peak_params = ...
transpose(reshape(temp, 3, length(temp) / 3));
temp = double(py.array.array('d', results_in.gaussian_params.ravel));
results_out.gaussian_params = ...
transpose(reshape(temp, 3, length(temp) / 3));
results_out.error = ...
double(py.array.array('d', py.numpy.nditer(results_in.error)));
% Note: for reasons unknown, r_squared seems to come out as float...
results_out.r_squared = results_in.r_squared;
%results_out.r_squared = ...
% double(py.array.array('d', py.numpy.nditer(results_in.r_squared)));
end
|
github
|
lcnbeapp/beapp-master
|
load_fooof_results.m
|
.m
|
beapp-master/Packages/fooof-master/fooof_mat-master/mat_py_mat/utils/load_fooof_results.m
| 771 |
utf_8
|
ae210cf78ec635a9a8eab78a8de4c6ef
|
% load_fooof_results () - load results from a json file (as saved out by FOOOF)
%
% Usage:
% >> fooof_results = load_fooof_results(file_name)
%
% Inputs:
% file_name = file name of the fooof-format json file to load
%
% Ouputs:
% fooof_results = fooof model ouputs, in a struct, including:
% fooof_results.background_params
% fooof_results.peak_params
% fooof_results.gaussian_params
% fooof_results.error
% fooof_results.r_squared
%
% Notes
% This function uses the json support added to Matlab in r2016b.
function fooof_results = load_fooof_results(file_name)
dat = importdata(file_name);
fooof_results = [];
for ind = 1:length(dat)
fooof_results = [fooof_results, jsondecode(dat{ind})];
end
end
|
github
|
lcnbeapp/beapp-master
|
REST.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/REST.m
| 22,825 |
utf_8
|
940d9f3ff2cc3e996ef7d99fee778dd5
|
function varargout = REST(varargin)
% REST M-untitled_1 for REST.fig
% REST, by itself, creates a new REST or raises the existing
% singleton*.
%
% H = REST returns the handle to a new REST or the handle to
% the existing singleton*.
%
% REST('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in REST.M with the given input arguments.
%
% REST('Property','Value',...) creates a new REST or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before REST_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to REST_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Copyright 2002-2003 The MathWorks, Inc.
% Edit the above text to modify the response to help REST
% Last Modified by GUIDE v2.5 18-Mar-2017 21:56:06
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @REST_OpeningFcn, ...
'gui_OutputFcn', @REST_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
% -------------------------------------------------------------------------
% add the paths
% -------------
RESTpath = which('REST.m');
RESTpath = RESTpath(1:end-length('REST.m'));
if strcmpi(RESTpath, './') || strcmpi(RESTpath, '.\'),
RESTpath = [ pwd filesep ];
end;
% test for local SCCN copy
% ------------------------
if ~isNITdeployed2
addpath(RESTpath);
if exist( fullfile( RESTpath, 'function') ) ~= 7
warning('REST subfolders not found');
end;
end;
% add paths
% ---------
if ~isNITdeployed2
% myaddpath( NITpath, 'BrainMask_61x73x61.img','Mask');
myaddpath( RESTpath, 'REST_Version.m', ['function', filesep, 'Loading']);
else
warning('REST subfolders not added !!!');
end;
% -------------------------------------------------------------------------
% End initialization code - DO NOT EDIT
% --- Executes just before REST is made visible.
function REST_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 REST (see VARARGIN)
% Choose default command line output for REST
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = REST_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns popupmenu1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu1
% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function figure1_CreateFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
global File_List;
File_List = {};
% --- Executes on selection change in listbox_files.
function listbox_files_Callback(hObject, eventdata, handles)
% hObject handle to listbox_files (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns listbox_files contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox_files
% --- Executes during object creation, after setting all properties.
function listbox_files_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox_files (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --------------------------------------------------------------------
function Untitled_1_Callback(hObject, eventdata, handles)
% hObject handle to Untitled_1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function Data_load_Callback(hObject, eventdata, handles)
% hObject handle to Data_load (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global File_List;
global pathname;
global cur_data;
% [filename, pathname] = uigetfile('*.mat', 'Pick an M-untitled_1', 'MultiSelect', 'on');
[filename, pathname] = uigetfile({'*.mat;*.cnt;*.vhdr',...
'Data Files (*.mat;*.cnt;*.vhdr)';...
'*.mat', 'Matlab Data (*.mat)';...
'*.cnt', 'Neuroscan Data (*.cnt)';...
'*.vhdr', 'Brain Products Data (*.vhdr)';...
'*.*', 'All Files (*.*)';}, ....
'Select data file', ...
'MultiSelect', 'on');
if isequal(filename,0)
return;
end
if iscell(filename)
for i = 1:length(filename)
File_List{i} = strcat(pathname,filename{i});
end
else
File_List{1} = strcat(pathname,filename);
end
%----------- Data Loading -------------
for i = 1:length(File_List)
set(handles.listbox_files, 'Value', i);
try
cur_file = File_List{i};
[pathstr, name, exe] = fileparts(cur_file);
switch exe
case '.cnt'
% cur_data{i} = loadcnt(cur_file);
if length(File_List) == 1
cur_data{i} = pop_loadcnt(filename);
else
cur_data{i} = pop_loadcnt(filename{i});
end
case '.mat'
cur_data{i} = load(cur_file);
case '.vhdr'
cur_data{i} = pop_loadbv(pathname, [name exe]);
end
catch
disp(['error occuring for ' File_List{i}]);
end
end
if ~isempty(cur_data)
msgbox('Data has been successully imported.', 'Data');
set(handles.listbox_files, 'String', File_List);
set(handles.listbox_files, 'Value', 1);
else
errordlg('Error occuring for data importing !!!','Error');
end
% --------------------------------------------------------------------
function REST_Reference_Callback(hObject, eventdata, handles)
% hObject handle to REST_Reference (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global File_List;
global Lead_Field;
global cur_data;
if ~isempty(File_List)
if ~isempty(Lead_Field)
if (size(Lead_Field, 2) == size(cur_data{1}.data, 1))
G = Lead_Field;
G = G';
G_ave = mean(G);
G_ave = G-repmat(G_ave,size(G,1),1);
Ra = G*pinv(G_ave,0.05); %the value 0.05 is for real data; for simulated data, it may be set as zero.
clear G G_ave;
for i = 1:length(File_List)
set(handles.listbox_files, 'Value', i);
try
cur_file = File_List{i};
[pathstr, name, exe] = fileparts(cur_file);
save_dir = strcat(pathstr,filesep);
save_dir = strcat(save_dir,name);
save_dir = strcat(save_dir,'_REST_Ref.mat');
current_data = cur_data{i};
Fields_list = fields(current_data);
%---------------------
Ref_data = [];
for k = 1:length(Fields_list)
if strcmp(Fields_list{k}, 'data')
cur_var = current_data.(Fields_list{k});
cur_ave = mean(cur_var);
cur_var1 = cur_var - repmat(cur_ave,size(cur_var,1),1);
cur_var = Ra * cur_var1;
cur_var = cur_var1 + repmat(mean(cur_var),size(cur_var,1),1); % edit by Li Dong (2017.8.28)
% Vr = V_avg + AVG(V_0)
Ref_data.(Fields_list{k}) = cur_var;
else
Ref_data.(Fields_list{k}) = current_data.(Fields_list{k});
end
end
save(save_dir, '-struct', 'Ref_data');
catch
disp(['error occuring for ' File_List{i}]);
end
end
msgbox('Calculation completed', 'REST');
else
errordlg('Wrong Leadfield has been imported, please import the right Leadfield !!!','Error');
return;
end
else
errordlg('No Leadfield has been imported, please import Leadfield !!!','Error');
return;
end
else
errordlg('No EEG data has been imported, please import data !!!','Error');
return
end
% --------------------------------------------------------------------
function Load_exsiting_Callback(hObject, eventdata, handles)
% hObject handle to Load_exsiting (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global cur_data;
global File_List;
[ProgramPath, ~, ~] = fileparts(which('REST.m'));
cur_data{1} = pop_loadbv([ProgramPath,filesep, 'sample_data'], 'sample.vhdr');
File_List{1} = [ProgramPath, filesep, 'sample_data', filesep, 'sample.vhdr'];
if ~isempty(cur_data)
msgbox('Sample data has been successully imported.', 'Data');
set(handles.listbox_files, 'String', File_List);
set(handles.listbox_files, 'Value', 1);
else
errordlg('Error occuring for sample data importing !!!','Error');
end
% --------------------------------------------------------------------
function Clear_space_Callback(hObject, eventdata, handles)
% hObject handle to Clear_space (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global File_List;
if isempty(File_List)
errordlg('No EEG data has been imported, please import data !!!','Error');
return
else
set(handles.listbox_files,'string','')
clear all
clc
end
% --------------------------------------------------------------------
function Quit_Callback(hObject, eventdata, handles)
% hObject handle to Quit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
clear all
close all
clc
% --------------------------------------------------------------------
function Untitled_2_Callback(hObject, eventdata, handles)
% hObject handle to Untitled_2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function Data_plot_Callback(hObject, eventdata, handles)
% hObject handle to Data_plot (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global File_List;
global cur_data;
if ~isempty(cur_data)
for i = 1:length(File_List)
[pathstr, name{i}, exe] = fileparts(File_List{i});
end
name = name';
data_plot = pop_chansel(cellstr(name));
if ~isempty(data_plot)
Fields_list = fields(cur_data{data_plot});
for ii = 1:length(Fields_list)
if strcmp(Fields_list{ii}, 'srate')
sratelabel(ii) = 1;
else
sratelabel(ii) = 0;
end
end
sratenum = find(sratelabel == 1);
for ii = 1:length(Fields_list)
if strcmp(Fields_list{ii}, 'chanlocs')
chanlocslabel(ii) = 1;
else
chanlocslabel(ii) = 0;
end
end
chanlocsnum = find(chanlocslabel == 1);
if ~isempty(sratenum)
if ~isempty(chanlocsnum)
eegplot(cur_data{data_plot}.data, 'srate', cur_data{data_plot}.srate, 'eloc_file', ...
cur_data{data_plot}.chanlocs);
else
eegplot(cur_data{data_plot}.data, 'srate', cur_data{data_plot}.srate);
end
else
srate = inputdlg('Please input the srate');
eegplot(cur_data{data_plot}.data, 'srate', str2num(cell2mat(srate)));
end
else
errordlg('No subject has been slected, please select one subject !!!','Error');
end
else
errordlg('No EEG data has been imported, please import data !!!','Error');
end
% --------------------------------------------------------------------
function Untitled_3_Callback(hObject, eventdata, handles)
% hObject handle to Untitled_3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function Exclude_channels1_Callback(hObject, eventdata, handles)
% hObject handle to Exclude_channels1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global File_List;
global cur_data;
if ~isempty(File_List)
cur_file = File_List{1};
[pathstr, name, exe] = fileparts(cur_file);
current_data = cur_data{1};
if ~strcmp(exe, '.mat')
if ~isempty(current_data)
if isempty(current_data.chanlocs)
Nchanns = size(current_data.data,1);
chanlist = pop_chansel(cellstr(num2str((1:Nchanns)')),'withindex','off');
else
chanlist = pop_chansel({current_data.chanlocs.labels},'withindex','on');
end
if isempty(chanlist)
errordlg('No channel would be removed !!!','Error');
else
msgbox('The selected channels have been excluded', 'Channels');
fprintf('%d channel has been removed ! \n', chanlist)
end
else
errordlg('No EEG data has been imported, please import data !!!','Error');
return;
end
else
if ~isempty(current_data)
Fields_list = fields(current_data);
for ii = 1:length(Fields_list)
if strcmp(Fields_list{ii}, 'chanlocs')
chanlocslabel(ii) = 1;
else
chanlocslabel(ii) = 0;
end
end
numbe = find(chanlocslabel == 1);
if isempty(numbe)
Nchanns = size(current_data.data,1);
chanlist = pop_chansel(cellstr(num2str((1:Nchanns)')),'withindex','off');
else
if ~isempty(current_data.chanlocs)
chanlist = pop_chansel({current_data.chanlocs.labels},'withindex','on');
else
Nchanns = size(current_data.data,1);
chanlist = pop_chansel(cellstr(num2str((1:Nchanns)')),'withindex','off');
end
end
if isempty(chanlist)
errordlg('No channel would be removed !!!','Error');
else
msgbox('The selected channels have been excluded', 'Channels');
fprintf('%d channel has been removed ! \n', chanlist)
end
else
errordlg('No EEG data has been imported, please import data !!!','Error');
return;
end
end
for i = 1:length(cur_data)
Fields_list = fields(cur_data{i});
for ii = 1:length(Fields_list)
if strcmp(Fields_list{ii}, 'data')
cur_data{i}.data(chanlist, :) = [];
elseif strcmp(Fields_list{ii}, 'nbchan')
cur_data{i}.nbchan = cur_data{i}.nbchan-length(chanlist);
elseif strcmp(Fields_list{ii}, 'chanlocs')
cur_data{i}.chanlocs(:, chanlist) = [];
else
continue;
end
end
end
else
errordlg('No EEG data has been imported, please import data !!!','Error');
return;
end
% --------------------------------------------------------------------
function Untitled_4_Callback(hObject, eventdata, handles)
% hObject handle to Untitled_4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function Leadfield_Calculation_Callback(hObject, eventdata, handles)
% hObject handle to Leadfield_Calculation (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[ProgramPath, ~, ~] = fileparts(which('REST.m'));
eval(['!',[ProgramPath,filesep, 'function', filesep, 'LeadField', filesep],'LeadField.exe']);
% --------------------------------------------------------------------
function Load_Leadfield_Callback(hObject, eventdata, handles)
% hObject handle to Load_Leadfield (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global Lead_Field;
global File_List;
if isempty(File_List)
errordlg('No EEG data has been imported, please import data !!!','Error');
return
else
[Name_lf, pathname_lf] = uigetfile({'*.dat',...
'Leadfield Files (*.dat)';'*.*', 'All Files (*.*)';}, ...
'Select leadfield file');
if (Name_lf == 0)
errordlg('Leadfield matrix is not imported, please import Leadfield matrix !!!','Error');
else
Lead_Field = load([pathname_lf, Name_lf]);
msgbox('Successfully import .', 'Lead Field');
end
end
% --------------------------------------------------------------------
function Untitled_5_Callback(hObject, eventdata, handles)
% hObject handle to Untitled_5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function About_REST_Callback(hObject, eventdata, handles)
% hObject handle to About_REST (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
msgbox({' This GUI is used to do the REST transformation processing for EEG data.';...
' ';...
' [1]. Calculate leadfield matrix;';...
' [2]. Import data;';...
' [3]. Plot data (optional);';...
' [4]. Exclude channels (e.g., ECG, EKG, and bad channels, etc);';...
' [5]. Import corresponding leadfield matrix;';...
' [6]. Run REST & export data;';...
' [7]. Clear dataset(s) (optioanl);';...
' [8]. Quit;';...
}, 'About REST')
% --------------------------------------------------------------------
function Manual_Callback(hObject, eventdata, handles)
% hObject handle to Manual (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[ProgramPath, ~, ~] = fileparts(which('REST.m'));
open([ProgramPath, filesep,'docs', filesep, 'Userguide.pdf']);
% --------------------------------------------------------------------
function Website_Callback(hObject, eventdata, handles)
% hObject handle to Website (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
web('http://www.neuro.uestc.edu.cn/REST/');
% -------------------------------------------------------------------------
% find a function path and add path if not present
function myaddpath(NITpath, functionname, pathtoadd)
tmpp = which(functionname);
tmpnewpath = [ NITpath pathtoadd ];
if ~isempty(tmpp)
tmpp = tmpp(1:end-length(functionname));
if length(tmpp) > length(tmpnewpath), tmpp = tmpp(1:end-1); end; % remove trailing filesep
if length(tmpp) > length(tmpnewpath), tmpp = tmpp(1:end-1); end; % remove trailing filesep
%disp([ tmpp ' | ' tmpnewpath '(' num2str(~strcmpi(tmpnewpath, tmpp)) ')' ]);
if ~strcmpi(tmpnewpath, tmpp)
warning('off', 'MATLAB:dispatcher:nameConflict');
addpath(tmpnewpath);
warning('on', 'MATLAB:dispatcher:nameConflict');
end;
else
%disp([ 'Adding new path ' tmpnewpath ]);
addpath(tmpnewpath);
end;
function addpathexist(p)
if exist(p) == 7
addpath(p);
end;
function val = isNITdeployed2
%val = 1; return;
if exist('isdeployed')
val = isdeployed;
else val = 0;
end;
|
github
|
lcnbeapp/beapp-master
|
iseeglabdeployed.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/iseeglabdeployed.m
| 154 |
utf_8
|
cb8716ae372b37132bb2a58c54d09cd0
|
% iseeglabdeployed - true for EEGLAB compile version and false otherwise
function val = iseeglabdeployed
try
val = isdeployed;
catch
val = 0;
end
|
github
|
lcnbeapp/beapp-master
|
pop_editeventvals.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/pop_editeventvals.m
| 25,793 |
utf_8
|
de89caf08acbbceb7572ea96a994e688
|
% pop_editeventvals() - Edit events contained in an EEG dataset structure.
% If the dataset is the only input, a window pops up
% allowing the user to insert the relevant parameter values.
%
% Usage: >> EEGOUT = pop_editeventvals( EEG, 'key1', value1, ...
% 'key2', value2, ... );
% Input:
% EEG - EEG dataset
%
% Optional inputs:
% 'sort' - { field1 dir1 field2 dir2 } Sort events based on field1
% then on optional field2. Arg dir1 indicates the sort
% direction (0 = increasing, 1 = decreasing).
% 'changefield' - {num field value} Insert the given value into the specified
% field in event num. (Ex: {34 'latency' 320.4})
% 'changeevent' - {num value1 value2 value3 ...} Change the values of
% all fields in event num.
% 'add','append','insert' - {num value1 value2 value3 ...} Insert event
% before or at event num, and assign value to structure
% fields. Note that the latency field must be in second
% and will be converted to data sample. Note also that
% the index of the event is often irrelevant, as events
% will be automatically resorted by latencies.
% 'delete' - vector of indices of events to delete
%
% Outputs:
% EEGOUT - EEG dataset with the selected events only
%
% Ex: EEG = pop_editeventvals(EEG,'changefield', { 1 'type' 'target'});
% % set field type of event number 1 to 'target'
%
% Author: Arnaud Delorme & Hilit Serby, SCCN, UCSD, 15 March 2002
%
% See also: pop_selectevent(), pop_importevent()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 15 March 2002, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 03-16-02 text interface editing -sm & ad
% 03-18-02 automatic latency switching display (epoch/continuous) - ad & sm
% 03-18-02 debug soring order - ad
% 03-18-02 put latencies in ms - ad, lf & sm
% 03-29-02 debug latencies in ms - ad & sm
% 04-02-02 debuging test - ad & sm
function [EEG, com] = pop_editeventvals(EEG, varargin);
com ='';
if nargin < 1
help pop_editeventvals;
return;
end;
if nargin >= 2 | isstr(EEG) % interpreting command from GUI or command line
if isstr(EEG) % GUI
gui = 1;
varargin = { EEG varargin{:} };
% user data
% ---------
userdata = get(gcf, 'userdata');
EEG = userdata{1};
oldcom = userdata{2};
allfields = fieldnames(EEG.event);
tmpind = strmatch('urevent', allfields);
allfields(tmpind) = [];
% current event
% -------------
objevent = findobj('parent', gcf, 'tag', 'numval');
valnum = str2num(get(objevent, 'string'));
shift = 0;
else % command line
gui = 0;
if isempty(EEG.event)
disp('Getevent: cannot deal with empty event structure');
return;
end;
allfields = fieldnames(EEG.event);
tmpind = strmatch('urevent', allfields);
allfields(tmpind) = [];
end;
% retinterpret inputs (fix BUG 454)
% --------------------------------
if ~gui
newvararg = {};
for indfield = 1:2:length(varargin)
com = varargin{ indfield };
tmpargs = varargin{ indfield+1 };
newvararg = { newvararg{:} com };
if any(strcmpi({'add','insert','append'},com))
evtind = tmpargs{1};
fields = fieldnames(EEG.event);
emptycells = cell(1,length(fields)-1);
newvararg = { newvararg{:}, { evtind emptycells{:} } };
if strcmpi(com, 'append'), evtind = evtind+1; end;
for ind = 2:length( tmpargs )
if ~strcmpi(fields{ind-1}, 'urevent')
newvararg = { newvararg{:},'changefield',{ evtind fields{ind-1} tmpargs{ind} } };
end;
end;
else
newvararg = { newvararg{:} tmpargs };
end;
end;
varargin = newvararg;
end;
% scan inputs
% -----------
for indfield = 1:2:length(varargin)
if length(varargin) >= indfield+1
tmparg = varargin{ indfield+1 };
end;
switch lower(varargin{indfield})
case 'goto', % ******************** GUI ONLY ***********************
% shift time
% ----------
shift = tmparg;
valnum = valnum + shift;
if valnum < 1, valnum = 1; end;
if valnum > length(EEG.event), valnum = length(EEG.event); end;
set(objevent, 'string', num2str(valnum,5));
% update fields
% -------------
for index = 1:length(allfields)
enable = 'on';
if isfield(EEG.event, 'type')
if strcmpi(EEG.event(valnum).type, 'boundary'), enable = 'off'; end;
end;
if strcmp( allfields{index}, 'latency') & ~isempty(EEG.event(valnum).latency)
if isfield(EEG.event, 'epoch')
value = eeg_point2lat( EEG.event(valnum).latency, EEG.event(valnum).epoch, ...
EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3);
else value = (EEG.event(valnum).latency-1)/EEG.srate+EEG.xmin;
end;
elseif strcmp( allfields{index}, 'duration') & ~isempty(EEG.event(valnum).duration)
if isfield(EEG.event, 'epoch')
value = EEG.event(valnum).duration/EEG.srate*1000; % milliseconds
else value = EEG.event(valnum).duration/EEG.srate; % seconds
end;
else
value = getfield( EEG.event(valnum), allfields{index});
end;
% update interface
% ----------------
tmpobj = findobj('parent', gcf, 'tag', allfields{index});
set(tmpobj, 'string', num2str(value,5), 'enable', enable);
end;
% update original
% ---------------
tmpobj = findobj('parent', gcf, 'tag', 'original');
if isfield(EEG.event, 'urevent') & EEG.event(valnum).urevent ~= valnum
set(tmpobj, 'string', [ 'originally ' int2str(EEG.event(valnum).urevent)], ...
'horizontalalignment', 'center');
else set(tmpobj, 'string', ' ');
end;
return; % NO NEED TO SAVE ANYTHING
case { 'append' 'insert' 'add' }, % **********************************************************
if gui
shift = tmparg; % shift is for adding before or after the event
% add epoch number if data epoch
% ------------------------------
tmpcell = cell(1,1+length(fieldnames(EEG.event)));
tmpcell{1} = valnum;
if EEG.trials > 1
indepoch = strmatch('epoch', fieldnames(EEG.event), 'exact');
if valnum > 1, tmpprevval = valnum-1;
else tmpprevval = valnum+1;
end;
if tmpprevval <= length(EEG.event)
tmpcell{indepoch+1} = EEG.event(tmpprevval).epoch;
end;
end;
% update commands
% ---------------
if shift
oldcom = { oldcom{:} 'append', tmpcell };
else
oldcom = { oldcom{:} 'insert', tmpcell };
end;
else
if strcmpi(lower(varargin{indfield}), 'append') % not 'add' for backward compatibility
shift = 1;
else shift = 0;
end;
valnum = tmparg{1};
end;
% find ur index
% -------------
valnum = valnum + shift;
if isfield(EEG.event, 'epoch'), curepoch = EEG.event(valnum).epoch; end;
if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent')
% find non empty urvalnum
urvalnum = [];
count = 0;
while isempty(urvalnum)
tmpindex = mod(valnum+count-1, length(EEG.event)+1)+1;
urvalnum = EEG.event(valnum+count).urevent;
count = count+1;
end;
if isfield(EEG.urevent, 'epoch'), urcurepoch = EEG.urevent(urvalnum).epoch; end;
urvalnum = urvalnum;
end;
% update urevents
% ---------------
if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent')
EEG.urevent(end+3) = EEG.urevent(end);
EEG.urevent(urvalnum+1:end-2) = EEG.urevent(urvalnum:end-3);
EEG.urevent(urvalnum) = EEG.urevent(end-1);
EEG.urevent = EEG.urevent(1:end-2);
if isfield(EEG.urevent, 'epoch'), EEG.urevent(urvalnum).epoch = urcurepoch; end;
end;
% update events
% -------------
EEG.event(end+3) = EEG.event(end);
EEG.event(valnum+1:end-2) = EEG.event(valnum:end-3);
EEG.event(valnum) = EEG.event(end-1);
EEG.event = EEG.event(1:end-2);
if isfield(EEG.event, 'epoch'), EEG.event(valnum).epoch = curepoch; end;
if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent')
EEG.event(valnum).urevent = urvalnum;
for index = valnum+1:length(EEG.event)
EEG.event(index).urevent = EEG.event(index).urevent+1;
end;
end;
% update type field
% -----------------
for tmpind = 1:length(allfields)
EEG.event = checkconsistency(EEG.event, valnum, allfields{tmpind});
end;
case 'delete', % **********************************************************
if ~gui
valnum = tmparg;
end
EEG.event(valnum) = [];
if gui,
valnum = min(valnum,length(EEG.event));
set(objevent, 'string', num2str(valnum));
% update commands
% ---------------
oldcom = { oldcom{:} 'delete', valnum };
end;
case { 'assign' 'changefield' }, % **********************************************************
if gui, % GUI case
field = tmparg;
objfield = findobj('parent', gcf, 'tag', field);
editval = get(objfield, 'string');
if ~isempty(editval) & ~isempty(str2num(editval)), editval = str2num(editval); end;
% update history
% --------------
oldcom = { oldcom{:},'changefield',{ valnum field editval }};
else % command line case
valnum = tmparg{1};
field = tmparg{2};
editval = tmparg{3};
end;
% latency and duration case
% -------------------------
if strcmp( field, 'latency') & ~isempty(editval)
if isfield(EEG.event, 'epoch')
editval = eeg_lat2point( editval, EEG.event(valnum).epoch, ...
EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3);
else editval = (editval- EEG.xmin)*EEG.srate+1;
end;
end;
if strcmp( field, 'duration') & ~isempty(editval)
if isfield(EEG.event, 'epoch')
editval = editval/1000*EEG.srate; % milliseconds
else editval = editval*EEG.srate; % seconds
end;
end;
% adapt to other formats
% ----------------------
EEG.event(valnum) = setfield(EEG.event(valnum), field, editval);
EEG.event = checkconsistency(EEG.event, valnum, field);
% update urevents
% ---------------
if isfield(EEG, 'urevent') & isfield(EEG.event, 'urevent')
urvalnum = EEG.event(valnum).urevent;
% latency case
% ------------
if strcmp( field, 'latency') & ~isempty(editval)
if isfield(EEG.urevent, 'epoch')
urepoch = EEG.urevent(urvalnum).epoch;
% find closest event latency
% --------------------------
if valnum<length(EEG.event)
if EEG.event(valnum+1).epoch == urepoch
urlatency = EEG.urevent(EEG.event(valnum+1).urevent).latency;
latency = EEG.event(valnum+1).latency;
end;
end;
if valnum>1
if EEG.event(valnum-1).epoch == urepoch
urlatency = EEG.urevent(EEG.event(valnum-1).urevent).latency;
latency = EEG.event(valnum-1).latency;
end;
end;
% update event
% ------------
if exist('urlatency') ~=1
disp('Urevent not updated: could not find other event in the epoch');
else
editval = urlatency - ( latency - editval ); % new latency value
end;
else
editval = eeg_urlatency(EEG.event, EEG.event(valnum).latency);
end;
elseif strcmp( field, 'latency') % empty editval
EEG.event(valnum).latency = NaN;
end;
% duration case
% ------------
if strcmp( field, 'duration') & ~isempty(editval)
if isfield(EEG.event, 'epoch')
editval = editval/1000*EEG.srate; % milliseconds -> point
else editval = editval*EEG.srate; % seconds -> point
end;
end;
EEG.urevent = setfield(EEG.urevent, {urvalnum}, field, editval);
end;
case 'sort', % **********************************************************
if gui % retrieve data
field1 = get(findobj('parent', gcf, 'tag', 'listbox1'), 'value');
field2 = get(findobj('parent', gcf, 'tag', 'listbox2'), 'value');
dir1 = get(findobj('parent', gcf, 'tag', 'order1'), 'value');
dir2 = get(findobj('parent', gcf, 'tag', 'order2'), 'value');
if field1 > 1, field1 = allfields{field1-1}; else return; end;
if field2 > 1, field1 = allfields{field2-1}; else field2 = []; end;
% update history
% --------------
oldcom = { oldcom{:},'sort',{ field1 dir1 field2 dir2 } };
else % command line
field1 = tmparg{1};
if length(tmparg) < 2, dir1 = 0;
else dir1 = tmparg{2};
end;
if length(tmparg) < 3, field2 = [];
else field2 = tmparg{3};
end;
if length(tmparg) < 4, dir2 = 0;
else dir2 = tmparg{4};
end;
end;
% Toby edit 11/16/2005 This section is scrambling the eeg.event
% fields. Requires further investigation.
if ~isempty(field2)
tmpevent = EEG.event;
if ~ischar(EEG.event(1).(field2))
tmparray = [ tmpevent.(field2) ];
else tmparray = { tmpevent.(field2) };
end
% Commented out 11/18/2005, Toby
% These lines were incorrectly sorting the event.latency field in
% units of time (seconds) relevant to each event's relative
% latency time as measured from the start of each epoch. It is
% possible that there are occasions when it is desirable to do
% so, but in the case of pop_mergset() it is not.
%if strcmp(field2, 'latency') & EEG.trials > 1
% tmparray = eeg_point2lat(tmparray, {EEG.event.epoch}, EEG.srate, [EEG.xmin EEG.xmax], 1);
%end;
[X I] = mysort( tmparray );
if dir2 == 1, I = I(end:-1:1); end;
events = EEG.event(I);
else
events = EEG.event;
end;
tmpevent = EEG.event;
if ~ischar(EEG.event(1).(field1))
tmparray = [ tmpevent.(field1) ];
else tmparray = { tmpevent.(field1) };
end
% Commented out 11/18/2005, Toby
%if strcmp( field1, 'latency') & EEG.trials > 1
% tmparray = eeg_point2lat(tmparray, {events.epoch}, EEG.srate, [EEG.xmin EEG.xmax], 1);
%end;
[X I] = mysort( tmparray );
if dir1 == 1, I = I(end:-1:1); end;
EEG.event = events(I);
if gui
% warn user
% ---------
warndlg2('Sorting done');
else
noeventcheck = 1; % otherwise infinite recursion with eeg_checkset
end;
end; % end switch
end; % end loop
% save userdata
% -------------
if gui
userdata{1} = EEG;
userdata{2} = oldcom;
set(gcf, 'userdata', userdata);
pop_editeventvals('goto', shift);
else
if ~exist('noeventcheck','var')
EEG = eeg_checkset(EEG, 'eventconsistency');
EEG = eeg_checkset(EEG, 'checkur');
end;
end;
return;
end;
% ----------------------
% graphic interface part
% ----------------------
if isempty(EEG.event)
disp('Getevent: cannot deal with empty event structure');
return;
end;
allfields = fieldnames(EEG.event);
tmpind = strmatch('urevent', allfields);
allfields(tmpind) = [];
if nargin<2
% add field values
% ----------------
geometry = { [2 0.5] };
tmpstr = sprintf('Edit event field values (currently %d events)',length(EEG.event));
uilist = { { 'Style', 'text', 'string', tmpstr, 'fontweight', 'bold' } ...
{ 'Style', 'pushbutton', 'string', 'Delete event', 'callback', 'pop_editeventvals(''delete'');' }};
for index = 1:length(allfields)
geometry = { geometry{:} [1 1 1 1] };
% input string
% ------------
if strcmp( allfields{index}, 'latency') | strcmp( allfields{index}, 'duration')
if EEG.trials > 1
inputstr = [ allfields{index} ' (ms)'];
else inputstr = [ allfields{index} ' (sec)'];
end;
else inputstr = allfields{index};
end;
% callback for displaying help
% ----------------------------
if index <= length( EEG.eventdescription )
tmptext = EEG.eventdescription{ index };
if ~isempty(tmptext)
if size(tmptext,1) > 15, stringtext = [ tmptext(1,1:15) '...' ];
else stringtext = tmptext(1,:);
end;
else stringtext = 'no-description'; tmptext = 'no-description';
end;
else stringtext = 'no-description'; tmptext = 'no-description';
end;
cbbutton = ['questdlg2(' vararg2str(tmptext) ...
',''Description of field ''''' allfields{index} ''''''', ''OK'', ''OK'');' ];
% create control
% --------------
cbedit = [ 'pop_editeventvals(''assign'', ''' allfields{index} ''');' ];
uilist = { uilist{:}, { }, ...
{ 'Style', 'pushbutton', 'string', inputstr, 'callback',cbbutton }, ...
{ 'Style', 'edit', 'tag', allfields{index}, 'string', '', 'callback', cbedit } ...
{ } };
end;
% add buttons
% -----------
geometry = { geometry{:} [1] [1.2 0.6 0.6 1 0.6 0.6 1.2] [1.2 0.6 0.6 1 0.6 0.6 1.2] [2 1 2] };
tpappend = 'Append event after the current event';
tpinsert = 'Insert event before the current event';
tporigin = 'Original index of the event (in EEG.urevent table)';
uilist = { uilist{:}, ...
{ }, ...
{ },{ },{ }, {'Style', 'text', 'string', 'Event Num', 'fontweight', 'bold' }, { },{ },{ }, ...
{ 'Style', 'pushbutton', 'string', 'Insert event', 'callback', 'pop_editeventvals(''append'', 0);', 'tooltipstring', tpinsert }, ...
{ 'Style', 'pushbutton', 'string', '<<', 'callback', 'pop_editeventvals(''goto'', -10);' }, ...
{ 'Style', 'pushbutton', 'string', '<', 'callback', 'pop_editeventvals(''goto'', -1);' }, ...
{ 'Style', 'edit', 'string', '1', 'callback', 'pop_editeventvals(''goto'', 0);', 'tag', 'numval' }, ...
{ 'Style', 'pushbutton', 'string', '>', 'callback', 'pop_editeventvals(''goto'', 1);' }, ...
{ 'Style', 'pushbutton', 'string', '>>', 'callback', 'pop_editeventvals(''goto'', 10);' }, ...
{ 'Style', 'pushbutton', 'string', 'Append event', 'callback', 'pop_editeventvals(''append'', 1);', 'tooltipstring', tpappend }, ...
{ }, { 'Style', 'text', 'string', ' ', 'tag', 'original' 'horizontalalignment' 'center' 'tooltipstring' tporigin } { } };
% add sorting options
% -------------------
listboxtext = 'No field selected';
for index = 1:length(allfields)
listboxtext = [ listboxtext '|' allfields{index} ];
end;
geometry = { geometry{:} [1] [1 1 1] [1 1 1] [1 1 1] };
uilist = { uilist{:}, ...
{ 'Style', 'text', 'string', 'Re-order events (for review only)', 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', 'Main sorting field:' }, ...
{ 'Style', 'popupmenu', 'string', listboxtext, 'tag', 'listbox1' }, ...
{ 'Style', 'checkbox', 'string', 'Click for decreasing order', 'tag', 'order1' } ...
{ 'Style', 'text', 'string', 'Secondary sorting field:' }, ...
{ 'Style', 'popupmenu', 'string', listboxtext, 'tag', 'listbox2' }, ...
{ 'Style', 'checkbox', 'string', 'Click for decreasing order', 'tag', 'order2' }, ...
{ } { 'Style', 'pushbutton', 'string', 'Re-sort', 'callback', 'pop_editeventvals(''sort'');' }, ...
{ } };
userdata = { EEG {} };
inputgui( geometry, uilist, 'pophelp(''pop_editeventvals'');', ...
'Edit event values -- pop_editeventvals()', userdata, 'plot');
pop_editeventvals('goto', 0);
% wait for figure
% ---------------
fig = gcf;
waitfor( findobj('parent', fig, 'tag', 'ok'), 'userdata');
try, userdata = get(fig, 'userdata'); close(fig); % figure still exist ?
catch, return; end;
% transfer events
% ---------------
if ~isempty(userdata{2})
com = sprintf('%s = pop_editeventvals(%s,%s);', inputname(1), inputname(1), vararg2str(userdata{2}));
end;
if isempty(findstr('''sort''', com))
if ~isempty(userdata{2}) % some modification have been done
EEG = userdata{1};
disp('Checking event consistency...');
EEG = eeg_checkset(EEG, 'eventconsistency');
EEG = eeg_checkset(EEG, 'checkur');
end;
else
com = '';
disp('WARNING: all edits discarded because of event resorting. The EEGLAB event structure');
disp(' must contain events sorted by latency (you may obtain an event structure');
disp(' with resorted event by calling this function from the command line).');
end;
return;
end;
return;
% format the output field
% -----------------------
function strval = reformat( val, latencycondition, trialcondition, eventnum)
if latencycondition
if trialcondition
strval = ['eeg_lat2point(' num2str(val) ', EEG.event(' int2str(eventnum) ').epoch, EEG.srate,[EEG.xmin EEG.xmax]*1000, 1E-3);' ];
else
strval = [ '(' num2str(val) '-EEG.xmin)*EEG.srate+1;' ];
end;
else
if isstr(val), strval = [ '''' val '''' ];
else strval = num2str(val);
end;
end;
% sort also empty values
% ----------------------
function [X, I] = mysort(tmparray);
if iscell(tmparray)
if all(cellfun('isreal', tmparray))
tmpempty = cellfun('isempty', tmparray);
tmparray(tmpempty) = { 0 };
tmparray = [ tmparray{:} ];
end;
end;
try,
[X I] = sort(tmparray);
catch,
disp('Sorting failed. Check that selected fields contain uniform value format.');
X = tmparray;
I = 1:length(X);
end;
% checkconsistency of new event
% -----------------------------
function eventtmp = checkconsistency(eventtmp, valnum, field)
otherval = mod(valnum+1, length(eventtmp))+1;
if isstr(getfield(eventtmp(valnum), field)) & ~isstr(getfield(eventtmp(otherval), field))
eventtmp(valnum) = setfield(eventtmp(valnum), field, str2num(getfield(eventtmp(valnum), field)));
end;
if ~isstr(getfield(eventtmp(valnum), field)) & isstr(getfield(eventtmp(otherval), field))
eventtmp(valnum) = setfield(eventtmp(valnum), field, num2str(getfield(eventtmp(valnum), field)));
end;
if strcmpi(field, 'latency') & isempty(getfield(eventtmp(valnum), field))
eventtmp(valnum).latency = NaN;
end;
|
github
|
lcnbeapp/beapp-master
|
readlocs.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/readlocs.m
| 33,881 |
utf_8
|
7e1d85669932dffeca11a8fad52e02ca
|
% readlocs() - read electrode location coordinates and other information from a file.
% Several standard file formats are supported. Users may also specify
% a custom column format. Defined format examples are given below
% (see File Formats).
% Usage:
% >> eloc = readlocs( filename );
% >> EEG.chanlocs = readlocs( filename, 'key', 'val', ... );
% >> [eloc, labels, theta, radius, indices] = ...
% readlocs( filename, 'key', 'val', ... );
% Inputs:
% filename - Name of the file containing the electrode locations
% {default: 2-D polar coordinates} (see >> help topoplot )
%
% Optional inputs:
% 'filetype' - ['loc'|'sph'|'sfp'|'xyz'|'asc'|'polhemus'|'besa'|'chanedit'|'custom']
% Type of the file to read. By default the file type is determined
% using the file extension (see below under File Formats),
% 'loc' an EEGLAB 2-D polar coordinates channel locations file
% Coordinates are theta and radius (see definitions below).
% 'sph' Matlab spherical coordinates (Note: spherical
% coordinates used by Matlab functions are different
% from spherical coordinates used by BESA - see below).
% 'sfp' EGI Cartesian coordinates (NOT Matlab Cartesian - see below).
% 'xyz' Matlab/EEGLAB Cartesian coordinates (NOT EGI Cartesian).
% z is toward nose; y is toward left ear; z is toward vertex
% 'asc' Neuroscan polar coordinates.
% 'polhemus' or 'polhemusx' - Polhemus electrode location file recorded
% with 'X' on sensor pointing to subject (see below and readelp()).
% 'polhemusy' - Polhemus electrode location file recorded with
% 'Y' on sensor pointing to subject (see below and readelp()).
% 'besa' BESA-'.elp' spherical coordinates. (Not MATLAB spherical -
% see below).
% 'chanedit' - EEGLAB channel location file created by pop_chanedit().
% 'custom' - Ascii file with columns in user-defined 'format' (see below).
% 'importmode' - ['eeglab'|'native'] for location files containing 3-D cartesian electrode
% coordinates, import either in EEGLAB format (nose pointing toward +X).
% This may not always be possible since EEGLAB might not be able to
% determine the nose direction for scanned electrode files. 'native' import
% original carthesian coordinates (user can then specify the position of
% the nose when calling the topoplot() function; in EEGLAB the position
% of the nose is stored in the EEG.chaninfo structure). {default 'eeglab'}
% 'format' - [cell array] Format of a 'custom' channel location file (see above).
% {default: if no file type is defined. The cell array contains
% labels defining the meaning of each column of the input file.
% 'channum' [positive integer] channel number.
% 'labels' [string] channel name (no spaces).
% 'theta' [real degrees] 2-D angle in polar coordinates.
% positive => rotating from nose (0) toward left ear
% 'radius' [real] radius for 2-D polar coords; 0.5 is the head
% disk radius and limit for topoplot() plotting).
% 'X' [real] Matlab-Cartesian X coordinate (to nose).
% 'Y' [real] Matlab-Cartesian Y coordinate (to left ear).
% 'Z' [real] Matlab-Cartesian Z coordinate (to vertex).
% '-X','-Y','-Z' Matlab-Cartesian coordinates pointing opposite
% to the above.
% 'sph_theta' [real degrees] Matlab spherical horizontal angle.
% positive => rotating from nose (0) toward left ear.
% 'sph_phi' [real degrees] Matlab spherical elevation angle.
% positive => rotating from horizontal (0) upwards.
% 'sph_radius' [real] distance from head center (unused).
% 'sph_phi_besa' [real degrees] BESA phi angle from vertical.
% positive => rotating from vertex (0) towards right ear.
% 'sph_theta_besa' [real degrees] BESA theta horiz/azimuthal angle.
% positive => rotating from right ear (0) toward nose.
% 'ignore' ignore column}.
% The input file may also contain other channel information fields.
% 'type' channel type: 'EEG', 'MEG', 'EMG', 'ECG', others ...
% 'calib' [real near 1.0] channel calibration value.
% 'gain' [real > 1] channel gain.
% 'custom1' custom field #1.
% 'custom2', 'custom3', 'custom4', etc. more custom fields
% 'skiplines' - [integer] Number of header lines to skip (in 'custom' file types only).
% Note: Characters on a line following '%' will be treated as comments.
% 'readchans' - [integer array] indices of electrodes to read. {default: all}
% 'center' - [(1,3) real array or 'auto'] center of xyz coordinates for conversion
% to spherical or polar, Specify the center of the sphere here, or 'auto'.
% This uses the center of the sphere that best fits all the electrode
% locations read. {default: [0 0 0]}
% Outputs:
% eloc - structure containing the channel names and locations (if present).
% It has three fields: 'eloc.labels', 'eloc.theta' and 'eloc.radius'
% identical in meaning to the EEGLAB struct 'EEG.chanlocs'.
% labels - cell array of strings giving the names of the electrodes. NOTE: Unlike the
% three outputs below, includes labels of channels *without* location info.
% theta - vector (in degrees) of polar angles of the electrode locations.
% radius - vector of polar-coordinate radii (arc_lengths) of the electrode locations
% indices - indices, k, of channels with non-empty 'locs(k).theta' coordinate
%
% File formats:
% If 'filetype' is unspecified, the file extension determines its type.
%
% '.loc' or '.locs' or '.eloc':
% polar coordinates. Notes: angles in degrees:
% right ear is 90; left ear -90; head disk radius is 0.5.
% Fields: N angle radius label
% Sample: 1 -18 .511 Fp1
% 2 18 .511 Fp2
% 3 -90 .256 C3
% 4 90 .256 C4
% ...
% Note: In previous releases, channel labels had to contain exactly
% four characters (spaces replaced by '.'). This format still works,
% though dots are no longer required.
% '.sph':
% Matlab spherical coordinates. Notes: theta is the azimuthal/horizontal angle
% in deg.: 0 is toward nose, 90 rotated to left ear. Following this, performs
% the elevation (phi). Angles in degrees.
% Fields: N theta phi label
% Sample: 1 18 -2 Fp1
% 2 -18 -2 Fp2
% 3 90 44 C3
% 4 -90 44 C4
% ...
% '.elc':
% Cartesian 3-D electrode coordinates scanned using the EETrak software.
% See readeetraklocs().
% '.elp':
% Polhemus-.'elp' Cartesian coordinates. By default, an .elp extension is read
% as PolhemusX-elp in which 'X' on the Polhemus sensor is pointed toward the
% subject. Polhemus files are not in columnar format (see readelp()).
% '.elp':
% BESA-'.elp' spherical coordinates: Need to specify 'filetype','besa'.
% The elevation angle (phi) is measured from the vertical axis. Positive
% rotation is toward right ear. Next, perform azimuthal/horizontal rotation
% (theta): 0 is toward right ear; 90 is toward nose, -90 toward occiput.
% Angles are in degrees. If labels are absent or weights are given in
% a last column, readlocs() adjusts for this. Default labels are E1, E2, ...
% Fields: Type label phi theta
% Sample: EEG Fp1 -92 -72
% EEG Fp2 92 72
% EEG C3 -46 0
% EEG C4 46 0
% ...
% '.xyz':
% Matlab/EEGLAB Cartesian coordinates. Here. x is towards the nose,
% y is towards the left ear, and z towards the vertex. Note that the first
% column (x) is -Y in a Matlab 3-D plot, the second column (y) is X in a
% matlab 3-D plot, and the third column (z) is Z.
% Fields: channum x y z label
% Sample: 1 .950 .308 -.035 Fp1
% 2 .950 -.308 -.035 Fp2
% 3 0 .719 .695 C3
% 4 0 -.719 .695 C4
% ...
% '.asc', '.dat':
% Neuroscan-.'asc' or '.dat' Cartesian polar coordinates text file.
% '.sfp':
% BESA/EGI-xyz Cartesian coordinates. Notes: For EGI, x is toward right ear,
% y is toward the nose, z is toward the vertex. EEGLAB converts EGI
% Cartesian coordinates to Matlab/EEGLAB xyz coordinates.
% Fields: label x y z
% Sample: Fp1 -.308 .950 -.035
% Fp2 .308 .950 -.035
% C3 -.719 0 .695
% C4 .719 0 .695
% ...
% '.ced':
% ASCII file saved by pop_chanedit(). Contains multiple MATLAB/EEGLAB formats.
% Cartesian coordinates are as in the 'xyz' format (above).
% Fields: channum label theta radius x y z sph_theta sph_phi ...
% Sample: 1 Fp1 -18 .511 .950 .308 -.035 18 -2 ...
% 2 Fp2 18 .511 .950 -.308 -.035 -18 -2 ...
% 3 C3 -90 .256 0 .719 .695 90 44 ...
% 4 C4 90 .256 0 -.719 .695 -90 44 ...
% ...
% The last columns of the file may contain any other defined fields (gain,
% calib, type, custom).
%
% Fieldtrip structure:
% If a Fieltrip structure is given as input, an EEGLAB
% chanlocs structure is returned
%
% Author: Arnaud Delorme, Salk Institute, 8 Dec 2002
%
% See also: readelp(), writelocs(), topo2sph(), sph2topo(), sph2cart()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 28 Feb 2002
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [eloc, labels, theta, radius, indices] = readlocs( filename, varargin );
if nargin < 1
help readlocs;
return;
end;
% NOTE: To add a new channel format:
% ----------------------------------
% 1) Add a new element to the structure 'chanformat' (see 'ADD NEW FORMATS HERE' below):
% 2) Enter a format 'type' for the new file format,
% 3) Enter a (short) 'typestring' description of the format
% 4) Enter a longer format 'description' (possibly multiline, see ex. (1) below)
% 5) Enter format file column labels in the 'importformat' field (see ex. (2) below)
% 6) Enter the number of header lines to skip (if any) in the 'skipline' field
% 7) Document the new channel format in the help message above.
% 8) After testing, please send the new version of readloca.m to us
% at [email protected] with a sample locs file.
% The 'chanformat' structure is also used (automatically) by the writelocs()
% and pop_readlocs() functions. You do not need to edit these functions.
chanformat(1).type = 'polhemus';
chanformat(1).typestring = 'Polhemus native .elp file';
chanformat(1).description = [ 'Polhemus native coordinate file containing scanned electrode positions. ' ...
'User must select the direction ' ...
'for the nose after importing the data file.' ];
chanformat(1).importformat = 'readelp() function';
% ---------------------------------------------------------------------------------------------------
chanformat(2).type = 'besa';
chanformat(2).typestring = 'BESA spherical .elp file';
chanformat(2).description = [ 'BESA spherical coordinate file. Note that BESA spherical coordinates ' ...
'are different from Matlab spherical coordinates' ];
chanformat(2).skipline = 0; % some BESA files do not have headers
chanformat(2).importformat = { 'type' 'labels' 'sph_theta_besa' 'sph_phi_besa' 'sph_radius' };
% ---------------------------------------------------------------------------------------------------
chanformat(3).type = 'xyz';
chanformat(3).typestring = 'Matlab .xyz file';
chanformat(3).description = [ 'Standard 3-D cartesian coordinate files with electrode labels in ' ...
'the first column and X, Y, and Z coordinates in columns 2, 3, and 4' ];
chanformat(3).importformat = { 'channum' '-Y' 'X' 'Z' 'labels'};
% ---------------------------------------------------------------------------------------------------
chanformat(4).type = 'sfp';
chanformat(4).typestring = 'BESA or EGI 3-D cartesian .sfp file';
chanformat(4).description = [ 'Standard BESA 3-D cartesian coordinate files with electrode labels in ' ...
'the first column and X, Y, and Z coordinates in columns 2, 3, and 4.' ...
'Coordinates are re-oriented to fit the EEGLAB standard of having the ' ...
'nose along the +X axis.' ];
chanformat(4).importformat = { 'labels' '-Y' 'X' 'Z' };
chanformat(4).skipline = 0;
% ---------------------------------------------------------------------------------------------------
chanformat(5).type = 'loc';
chanformat(5).typestring = 'EEGLAB polar .loc file';
chanformat(5).description = [ 'EEGLAB polar .loc file' ];
chanformat(5).importformat = { 'channum' 'theta' 'radius' 'labels' };
% ---------------------------------------------------------------------------------------------------
chanformat(6).type = 'sph';
chanformat(6).typestring = 'Matlab .sph spherical file';
chanformat(6).description = [ 'Standard 3-D spherical coordinate files in Matlab format' ];
chanformat(6).importformat = { 'channum' 'sph_theta' 'sph_phi' 'labels' };
% ---------------------------------------------------------------------------------------------------
chanformat(7).type = 'asc';
chanformat(7).typestring = 'Neuroscan polar .asc file';
chanformat(7).description = [ 'Neuroscan polar .asc file, automatically recentered to fit EEGLAB standard' ...
'of having ''Cz'' at (0,0).' ];
chanformat(7).importformat = 'readneurolocs';
% ---------------------------------------------------------------------------------------------------
chanformat(8).type = 'dat';
chanformat(8).typestring = 'Neuroscan 3-D .dat file';
chanformat(8).description = [ 'Neuroscan 3-D cartesian .dat file. Coordinates are re-oriented to fit ' ...
'the EEGLAB standard of having the nose along the +X axis.' ];
chanformat(8).importformat = 'readneurolocs';
% ---------------------------------------------------------------------------------------------------
chanformat(9).type = 'elc';
chanformat(9).typestring = 'ASA .elc 3-D file';
chanformat(9).description = [ 'ASA .elc 3-D coordinate file containing scanned electrode positions. ' ...
'User must select the direction ' ...
'for the nose after importing the data file.' ];
chanformat(9).importformat = 'readeetraklocs';
% ---------------------------------------------------------------------------------------------------
chanformat(10).type = 'chanedit';
chanformat(10).typestring = 'EEGLAB complete 3-D file';
chanformat(10).description = [ 'EEGLAB file containing polar, cartesian 3-D, and spherical 3-D ' ...
'electrode locations.' ];
chanformat(10).importformat = { 'channum' 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' ...
'sph_radius' 'type' };
chanformat(10).skipline = 1;
% ---------------------------------------------------------------------------------------------------
chanformat(11).type = 'custom';
chanformat(11).typestring = 'Custom file format';
chanformat(11).description = 'Custom ASCII file format where user can define content for each file columns.';
chanformat(11).importformat = '';
% ---------------------------------------------------------------------------------------------------
% ----- ADD MORE FORMATS HERE -----------------------------------------------------------------------
% ---------------------------------------------------------------------------------------------------
listcolformat = { 'labels' 'channum' 'theta' 'radius' 'sph_theta' 'sph_phi' ...
'sph_radius' 'sph_theta_besa' 'sph_phi_besa' 'gain' 'calib' 'type' ...
'X' 'Y' 'Z' '-X' '-Y' '-Z' 'custom1' 'custom2' 'custom3' 'custom4' 'ignore' 'not def' };
% ----------------------------------
% special mode for getting the info
% ----------------------------------
if isstr(filename) & strcmp(filename, 'getinfos')
eloc = chanformat;
labels = listcolformat;
return;
end;
g = finputcheck( varargin, ...
{ 'filetype' 'string' {} '';
'importmode' 'string' { 'eeglab','native' } 'eeglab';
'defaultelp' 'string' { 'besa','polhemus' } 'polhemus';
'skiplines' 'integer' [0 Inf] [];
'elecind' 'integer' [1 Inf] [];
'format' 'cell' [] {} }, 'readlocs');
if isstr(g), error(g); end;
if ~isempty(g.format), g.filetype = 'custom'; end;
if isstr(filename)
% format auto detection
% --------------------
if strcmpi(g.filetype, 'autodetect'), g.filetype = ''; end;
g.filetype = strtok(g.filetype);
periods = find(filename == '.');
fileextension = filename(periods(end)+1:end);
g.filetype = lower(g.filetype);
if isempty(g.filetype)
switch lower(fileextension),
case {'loc' 'locs' 'eloc'}, g.filetype = 'loc'; % 5/27/2014 Ramon: 'eloc' option introduced.
case 'xyz', g.filetype = 'xyz';
fprintf( [ 'WARNING: Matlab Cartesian coord. file extension (".xyz") detected.\n' ...
'If importing EGI Cartesian coords, force type "sfp" instead.\n'] );
case 'sph', g.filetype = 'sph';
case 'ced', g.filetype = 'chanedit';
case 'elp', g.filetype = g.defaultelp;
case 'asc', g.filetype = 'asc';
case 'dat', g.filetype = 'dat';
case 'elc', g.filetype = 'elc';
case 'eps', g.filetype = 'besa';
case 'sfp', g.filetype = 'sfp';
otherwise, g.filetype = '';
end;
fprintf('readlocs(): ''%s'' format assumed from file extension\n', g.filetype);
else
if strcmpi(g.filetype, 'locs'), g.filetype = 'loc'; end
if strcmpi(g.filetype, 'eloc'), g.filetype = 'loc'; end
end;
% assign format from filetype
% ---------------------------
if ~isempty(g.filetype) & ~strcmpi(g.filetype, 'custom') ...
& ~strcmpi(g.filetype, 'asc') & ~strcmpi(g.filetype, 'elc') & ~strcmpi(g.filetype, 'dat')
indexformat = strmatch(lower(g.filetype), { chanformat.type }, 'exact');
g.format = chanformat(indexformat).importformat;
if isempty(g.skiplines)
g.skiplines = chanformat(indexformat).skipline;
end;
if isempty(g.filetype)
error( ['readlocs() error: The filetype cannot be detected from the \n' ...
' file extension, and custom format not specified']);
end;
end;
% import file
% -----------
if strcmp(g.filetype, 'asc') | strcmp(g.filetype, 'dat')
eloc = readneurolocs( filename );
eloc = rmfield(eloc, 'sph_theta'); % for the conversion below
eloc = rmfield(eloc, 'sph_theta_besa'); % for the conversion below
if isfield(eloc, 'type')
for index = 1:length(eloc)
type = eloc(index).type;
if type == 69, eloc(index).type = 'EEG';
elseif type == 88, eloc(index).type = 'REF';
elseif type >= 76 & type <= 82, eloc(index).type = 'FID';
else eloc(index).type = num2str(eloc(index).type);
end;
end;
end;
elseif strcmp(g.filetype, 'elc')
eloc = readeetraklocs( filename );
%eloc = read_asa_elc( filename ); % from fieldtrip
%eloc = struct('labels', eloc.label, 'X', mattocell(eloc.pnt(:,1)'), 'Y', ...
% mattocell(eloc.pnt(:,2)'), 'Z', mattocell(eloc.pnt(:,3)'));
eloc = convertlocs(eloc, 'cart2all');
eloc = rmfield(eloc, 'sph_theta'); % for the conversion below
eloc = rmfield(eloc, 'sph_theta_besa'); % for the conversion below
elseif strcmp(lower(g.filetype(1:end-1)), 'polhemus') | ...
strcmp(g.filetype, 'polhemus')
try,
[eloc labels X Y Z]= readelp( filename );
if strcmp(g.filetype, 'polhemusy')
tmp = X; X = Y; Y = tmp;
end;
for index = 1:length( eloc )
eloc(index).X = X(index);
eloc(index).Y = Y(index);
eloc(index).Z = Z(index);
end;
catch,
disp('readlocs(): Could not read Polhemus coords. Trying to read BESA .elp file.');
[eloc, labels, theta, radius, indices] = readlocs( filename, 'defaultelp', 'besa', varargin{:} );
end;
else
% importing file
% --------------
if isempty(g.skiplines), g.skiplines = 0; end;
if strcmpi(g.filetype, 'chanedit')
array = loadtxt( filename, 'delim', 9, 'skipline', g.skiplines, 'blankcell', 'off');
else
array = load_file_or_array( filename, g.skiplines);
end;
if size(array,2) < length(g.format)
fprintf(['readlocs() warning: Fewer columns in the input than expected.\n' ...
' See >> help readlocs\n']);
elseif size(array,2) > length(g.format)
fprintf(['readlocs() warning: More columns in the input than expected.\n' ...
' See >> help readlocs\n']);
end;
% removing lines BESA
% -------------------
if isempty(array{1,2})
disp('BESA header detected, skipping three lines...');
array = load_file_or_array( filename, g.skiplines-1);
if isempty(array{1,2})
array = load_file_or_array( filename, g.skiplines-1);
end;
end;
% xyz format, is the first col absent
% -----------------------------------
if strcmp(g.filetype, 'xyz')
if size(array, 2) == 4
array(:, 2:5) = array(:, 1:4);
end;
end;
% removing comments and empty lines
% ---------------------------------
indexbeg = 1;
while isempty(array{indexbeg,1}) | ...
(isstr(array{indexbeg,1}) & array{indexbeg,1}(1) == '%' )
indexbeg = indexbeg+1;
end;
array = array(indexbeg:end,:);
% converting file
% ---------------
for indexcol = 1:min(size(array,2), length(g.format))
[str mult] = checkformat(g.format{indexcol});
for indexrow = 1:size( array, 1)
if mult ~= 1
eval ( [ 'eloc(indexrow).' str '= -array{indexrow, indexcol};' ]);
else
eval ( [ 'eloc(indexrow).' str '= array{indexrow, indexcol};' ]);
end;
end;
end;
end;
% handling BESA coordinates
% -------------------------
if isfield(eloc, 'sph_theta_besa')
if isfield(eloc, 'type')
if isnumeric(eloc(1).type)
disp('BESA format detected ( Theta | Phi )');
for index = 1:length(eloc)
eloc(index).sph_phi_besa = eloc(index).labels;
eloc(index).sph_theta_besa = eloc(index).type;
eloc(index).labels = '';
eloc(index).type = '';
end;
eloc = rmfield(eloc, 'labels');
end;
end;
if isfield(eloc, 'labels')
if isnumeric(eloc(1).labels)
disp('BESA format detected ( Elec | Theta | Phi )');
for index = 1:length(eloc)
eloc(index).sph_phi_besa = eloc(index).sph_theta_besa;
eloc(index).sph_theta_besa = eloc(index).labels;
eloc(index).labels = eloc(index).type;
eloc(index).type = '';
eloc(index).radius = 1;
end;
end;
end;
try
eloc = convertlocs(eloc, 'sphbesa2all');
eloc = convertlocs(eloc, 'topo2all'); % problem with some EGI files (not BESA files)
catch, disp('Warning: coordinate conversion failed'); end;
fprintf('Readlocs: BESA spherical coords. converted, now deleting BESA fields\n');
fprintf(' to avoid confusion (these fields can be exported, though)\n');
eloc = rmfield(eloc, 'sph_phi_besa');
eloc = rmfield(eloc, 'sph_theta_besa');
% converting XYZ coordinates to polar
% -----------------------------------
elseif isfield(eloc, 'sph_theta')
try
eloc = convertlocs(eloc, 'sph2all');
catch, disp('Warning: coordinate conversion failed'); end;
elseif isfield(eloc, 'X')
try
eloc = convertlocs(eloc, 'cart2all');
catch, disp('Warning: coordinate conversion failed'); end;
else
try
eloc = convertlocs(eloc, 'topo2all');
catch, disp('Warning: coordinate conversion failed'); end;
end;
% inserting labels if no labels
% -----------------------------
if ~isfield(eloc, 'labels')
fprintf('readlocs(): Inserting electrode labels automatically.\n');
for index = 1:length(eloc)
eloc(index).labels = [ 'E' int2str(index) ];
end;
else
% remove trailing '.'
for index = 1:length(eloc)
if isstr(eloc(index).labels)
tmpdots = find( eloc(index).labels == '.' );
eloc(index).labels(tmpdots) = [];
end;
end;
end;
% resorting electrodes if number not-sorted
% -----------------------------------------
if isfield(eloc, 'channum')
if ~isnumeric(eloc(1).channum)
error('Channel numbers must be numeric');
end;
allchannum = [ eloc.channum ];
if any( sort(allchannum) ~= allchannum )
fprintf('readlocs(): Re-sorting channel numbers based on ''channum'' column indices\n');
[tmp newindices] = sort(allchannum);
eloc = eloc(newindices);
end;
eloc = rmfield(eloc, 'channum');
end;
else
if isstruct(filename)
% detect Fieldtrip structure and convert it
% -----------------------------------------
if isfield(filename, 'pnt')
neweloc = [];
for index = 1:length(filename.label)
neweloc(index).labels = filename.label{index};
neweloc(index).X = filename.pnt(index,1);
neweloc(index).Y = filename.pnt(index,2);
neweloc(index).Z = filename.pnt(index,3);
end;
eloc = neweloc;
eloc = convertlocs(eloc, 'cart2all');
else
eloc = filename;
end;
else
disp('readlocs(): input variable must be a string or a structure');
end;
end;
if ~isempty(g.elecind)
eloc = eloc(g.elecind);
end;
if nargout > 2
if isfield(eloc, 'theta')
tmptheta = { eloc.theta }; % check which channels have (polar) coordinates set
else tmptheta = cell(1,length(eloc));
end;
if isfield(eloc, 'theta')
tmpx = { eloc.X }; % check which channels have (polar) coordinates set
else tmpx = cell(1,length(eloc));
end;
indices = find(~cellfun('isempty', tmptheta));
indices = intersect_bc(find(~cellfun('isempty', tmpx)), indices);
indices = sort(indices);
indbad = setdiff_bc(1:length(eloc), indices);
tmptheta(indbad) = { NaN };
theta = [ tmptheta{:} ];
end;
if nargout > 3
if isfield(eloc, 'theta')
tmprad = { eloc.radius }; % check which channels have (polar) coordinates set
else tmprad = cell(1,length(eloc));
end;
tmprad(indbad) = { NaN };
radius = [ tmprad{:} ];
end;
%tmpnum = find(~cellfun('isclass', { eloc.labels }, 'char'));
%disp('Converting channel labels to string');
for index = 1:length(eloc)
if ~isstr(eloc(index).labels)
eloc(index).labels = int2str(eloc(index).labels);
end;
end;
labels = { eloc.labels };
if isfield(eloc, 'ignore')
eloc = rmfield(eloc, 'ignore');
end;
% process fiducials if any
% ------------------------
fidnames = { 'nz' 'lpa' 'rpa' 'nasion' 'left' 'right' 'nazion' 'fidnz' 'fidt9' 'fidt10' 'cms' 'drl' };
for index = 1:length(fidnames)
ind = strmatch(fidnames{index}, lower(labels), 'exact');
if ~isempty(ind), eloc(ind).type = 'FID'; end;
end;
return;
% interpret the variable name
% ---------------------------
function array = load_file_or_array( varname, skiplines );
if isempty(skiplines),
skiplines = 0;
end;
if exist( varname ) == 2
array = loadtxt(varname,'verbose','off','skipline',skiplines,'blankcell','off');
else % variable in the global workspace
% --------------------------
try, array = evalin('base', varname);
catch, error('readlocs(): cannot find the named file or variable, check syntax');
end;
end;
return;
% check field format
% ------------------
function [str, mult] = checkformat(str)
mult = 1;
if strcmpi(str, 'labels'), str = lower(str); return; end;
if strcmpi(str, 'channum'), str = lower(str); return; end;
if strcmpi(str, 'theta'), str = lower(str); return; end;
if strcmpi(str, 'radius'), str = lower(str); return; end;
if strcmpi(str, 'ignore'), str = lower(str); return; end;
if strcmpi(str, 'sph_theta'), str = lower(str); return; end;
if strcmpi(str, 'sph_phi'), str = lower(str); return; end;
if strcmpi(str, 'sph_radius'), str = lower(str); return; end;
if strcmpi(str, 'sph_theta_besa'), str = lower(str); return; end;
if strcmpi(str, 'sph_phi_besa'), str = lower(str); return; end;
if strcmpi(str, 'gain'), str = lower(str); return; end;
if strcmpi(str, 'calib'), str = lower(str); return; end;
if strcmpi(str, 'type') , str = lower(str); return; end;
if strcmpi(str, 'X'), str = upper(str); return; end;
if strcmpi(str, 'Y'), str = upper(str); return; end;
if strcmpi(str, 'Z'), str = upper(str); return; end;
if strcmpi(str, '-X'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, '-Y'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, '-Z'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, 'custom1'), return; end;
if strcmpi(str, 'custom2'), return; end;
if strcmpi(str, 'custom3'), return; end;
if strcmpi(str, 'custom4'), return; end;
error(['readlocs(): undefined field ''' str '''']);
|
github
|
lcnbeapp/beapp-master
|
pop_loadcnt.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/pop_loadcnt.m
| 9,941 |
utf_8
|
10cd7be4518af4743674c4648efd7912
|
% pop_loadcnt() - load a neuroscan CNT file (pop out window if no arguments).
%
% Usage:
% >> EEG = pop_loadcnt; % pop-up window mode
% >> EEG = pop_loadcnt( filename, 'key', 'val', ...);
%
% Graphic interface:
% "Data fomat" - [checkbox] 16-bits or 32-bits. We couldn't find in the
% data file where this information was stored. Command
% line equivalent in loadcnt() 'dataformat'.
% "Time interval in seconds" - [edit box] specify time interval [min max]
% to import portion of data. Command line equivalent
% in loadcnt: 't1' and 'lddur'
% "Import keystrokes" - [checkbox] set this option to import keystroke
% event types in dataset. Command line equivalent
% 'keystroke'.
% "loadcnt() 'key', 'val' params" - [edit box] Enter optional loadcnt()
% parameters.
%
% Inputs:
% filename - file name
%
% Optional inputs:
% 'keystroke' - ['on'|'off'] set the option to 'on' to import
% keystroke event types. Default is off.
% 'memmapfile' - ['memmapfile_name'] use this option if the .cnt file
% is too large to read in conventially. The suffix of
% the memmapfile_name must be .fdt. the memmapfile
% functions process files based on their suffix and an
% error will occur if you use a different suffix.
% Same as loadcnt() function.
%
% Outputs:
% EEG - EEGLAB data structure
%
% Note:
% 1) This function extract all non-null event from the CNT data structure.
% Null events are usually associated with internal signals (recalibrations...).
% 2) The "Average reference" edit box had been remove since the re-referencing
% menu of EEGLAB offers more options to re-reference data.
% 3) The 'blockread' has been disabled since we found where this information
% was stored in the file.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: loadcnt(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
function [EEG, command] = pop_loadcnt(filename, varargin);
global pathname;
command = '';
EEG = [];
if nargin < 1
% ask user
[filename, pathname] = uigetfile('*.CNT;*.cnt', 'Choose a CNT file -- pop_loadcnt()');
drawnow;
if filename == 0 return; end;
% popup window parameters
% -----------------------
callback16 = 'set(findobj(gcbf, ''tag'', ''B32''), ''value'', ~get(gcbo, ''value'')); set(findobj(gcbf, ''tag'', ''AD''), ''value'', ~get(gcbo, ''value''));';
callback32 = 'set(findobj(gcbf, ''tag'', ''B16''), ''value'', ~get(gcbo, ''value'')); set(findobj(gcbf, ''tag'', ''AD''), ''value'', ~get(gcbo, ''value''));';
callbackAD = 'set(findobj(gcbf, ''tag'', ''B16''), ''value'', ~get(gcbo, ''value'')); set(findobj(gcbf, ''tag'', ''B32''), ''value'', ~get(gcbo, ''value''));';
uigeom = { [1.3 0.5 0.5 0.5] [1 0.5] [1.09 0.13 0.4] [1 0.5] [1 0.5] 1 } ;
uilist = { { 'style' 'text' 'string' 'Data format 16 or 32 bit (Default = Autodetect)' } ...
{ 'style' 'checkbox' 'tag' 'B16' 'string' '16-bits' 'value' 0 'callback' callback16 } ...
{ 'style' 'checkbox' 'tag' 'B32' 'string' '32-bits' 'value' 0 'callback' callback32 } ...
{ 'style' 'checkbox' 'tag' 'AD' 'string' 'Autodetect' 'value' 1 'callback' callbackAD } ...
{ 'style' 'text' 'string' 'Time interval in s (i.e. [0 100]):' } ...
{ 'style' 'edit' 'string' '' 'callback' 'warndlg2([ ''Events latency might be innacurate when'' 10 ''importing time intervals (this is an open issue)'']);' } ...
{ 'style' 'text' 'string' 'Check to Import keystrokes:' } ...
{ 'style' 'checkbox' 'string' '' } { } ...
{ 'style' 'text' 'string' 'loadcnt() ''key'', ''val'' params' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'string' [ 'Large files, enter a file name for memory mapping (xxx.fdt)' ] } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'string' ' Note: requires to enable memory mapping in EEGLAB memory options and only works for 32-bit files' } };
result = inputgui( uigeom, uilist, 'pophelp(''pop_loadcnt'')', 'Load a CNT dataset');
if length( result ) == 0 return; end;
% decode parameters
% -----------------
options = [];
if result{1}, options = [ options ', ''dataformat'', ''int16''' ];
elseif result{2}, options = [ options ', ''dataformat'', ''int32''' ];
elseif result{3}, options = [ options ', ''dataformat'', ''auto''' ];
end;
if ~isempty(result{4}),
timer = eval( [ '[' result{4} ']' ]);
options = [ options ', ''t1'', ' num2str(timer(1)) ', ''lddur'', ' num2str(timer(2)-timer(1)) ];
end;
if result{5}, options = [ options ', ''keystroke'', ''on''' ]; end;
if ~isempty(result{6}), options = [ options ',' result{6} ]; end;
% Conditional pass if ~isempty(result{7}), options = ...
% [options ', ''memmapfile''', result{7} ] ; end ;
% Always pass the memmapfile paramter?
options = [ options ', ''memmapfile'', ''', result{7} '''' ] ;
else
options = vararg2str(varargin);
end;
% load datas
% ----------
EEG = eeg_emptyset;
if exist('filepath')
fullFileName = sprintf('%s%s', pathname, filename);
else
fullFileName = filename;
end;
if nargin > 0
if ~isempty(varargin)
r = loadcnt( fullFileName );
else
r = loadcnt( [pathname fullFileName] );
end;
else
eval( [ 'r = loadcnt( fullFileName ' options ');' ]);
end;
if isfield(r, 'dat')
error('pop_loadcnt is not compatible with current loadcnt version, please use latest loadcnt() version');
end;
% Check to see if data is in memory or in a file.
EEG.data = r.data;
EEG.comments = [ 'Original file: ' fullFileName ];
EEG.setname = 'CNT file';
EEG.nbchan = r.header.nchannels;
% inport events
% -------------
I = 1:length(r.event);
if ~isempty(I)
EEG.event(1:length(I),1) = [ r.event(I).stimtype ];
EEG.event(1:length(I),2) = [ r.event(I).offset ]+1;
EEG.event = eeg_eventformat (EEG.event, 'struct', { 'type' 'latency' });
end;
% modified by Andreas Widmann 2005/05/12 14:15:00
try, % this piece of code makes the function crash sometimes - Arnaud Delorme 2006/04/27
temp = find([r.event.accept_ev1] == 14 | [r.event.accept_ev1] == 11); % 14: Discontinuity, 11: DC reset
if ~isempty(temp)
disp('pop_loadcnt note: event field ''type'' set to ''boundary'' for data discontinuities');
for index = 1:length(temp)
EEG.event(temp(index)).type = 'boundary';
end;
end
catch, end;
% end modification
% process keyboard entries
% ------------------------
if ~isempty(findstr('keystroke', lower(options)))
tmpkbd = [ r.event(I).keyboard ];
tmpkbd2 = [ r.event(I).keypad_accept ];
for index = 1:length(EEG.event)
if EEG.event(index).type == 0
if r.event(index).keypad_accept,
EEG.event(index).type = [ 'keypad' num2str(r.event(index).keypad_accept) ];
else
EEG.event(index).type = [ 'keyboard' num2str(r.event(index).keyboard) ];
end;
end;
end;
else
% removeing keystroke events
% --------------------------
rmind = [];
for index = 1:length(EEG.event)
if EEG.event(index).type == 0
rmind = [rmind index];
end;
end;
if ~isempty(rmind)
fprintf('Ignoring %d keystroke events\n', length(rmind));
EEG.event(rmind) = [];
end;
end;
% import channel locations (Neuroscan coordinates are not wrong)
% ------------------------
%x = celltomat( { r.electloc.x_coord } );
%y = celltomat( { r.electloc.y_coord } );
for index = 1:length(r.electloc)
names{index} = deblank(char(r.electloc(index).lab'));
if size(names{index},1) > size(names{index},2), names{index} = names{index}'; end;
end;
EEG.chanlocs = struct('labels', names);
%EEG.chanlocs = readneurolocs( { names x y } );
%disp('WARNING: Electrode locations imported from CNT files may not reflect true locations');
% Check to see if data is in a file or in memory
% If in memory, leave alone
% If in a file, use values set in loadcnt.m for nbchan and pnts.
EEG.srate = r.header.rate;
EEG.nbchan = size(EEG.data,1) ;
EEG.nbchan = r.header.nchannels ;
% EEG.nbchan = size(EEG.data,1);
EEG.trials = 1;
EEG.pnts = r.ldnsamples ;
%size(EEG.data,2)
%EEG.pnts = r.header.pnts
%size(EEG.data,2);
EEG = eeg_checkset(EEG, 'eventconsistency');
EEG = eeg_checkset(EEG, 'makeur');
if ((size(EEG.data,1) ~= EEG.nbchan) && (size(EEG.data,2) ~= EEG.pnts))
% Assume a data file
EEG = eeg_checkset(EEG, 'loaddata');
end
% if length(options) > 2
% command = sprintf('EEG = pop_loadcnt(''%s'' %s);',fullFileName, options);
% else
% command = sprintf('EEG = pop_loadcnt(''%s'');',fullFileName);
% end;
return;
|
github
|
lcnbeapp/beapp-master
|
fastif.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/fastif.m
| 1,159 |
utf_8
|
ac76d723f5de7649f75655cbdb653c1a
|
% fastif() - fast if function.
%
% Usage:
% >> res = fastif(test, s1, s2);
%
% Input:
% test - logical test with result 0 or 1
% s1 - result if 1
% s2 - result if 0
%
% Output:
% res - s1 or s2 depending on the value of the test
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function res = fastif(s1, s2, s3);
if s1
res = s2;
else
res = s3;
end;
return;
|
github
|
lcnbeapp/beapp-master
|
vararg2str.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/vararg2str.m
| 6,803 |
utf_8
|
547476651c6901a530169197da722d2d
|
% vararg2str() - transform arguments into string for evaluation
% using the eval() command
%
% Usage:
% >> strout = vararg2str( allargs );
% >> strout = vararg2str( allargs, inputnames, inputnum, nostrconv );
%
% Inputs:
% allargs - Cell array containing all arguments
% inputnames - Cell array of input names for these arguments, if any.
% inputnum - Vector of indices for all inputs. If present, the
% string output may by replaced by varargin{num}.
% Include NaN in the vector to avoid specific parameters
% being converted in this way.
% nostrconv - Vector of 0s and 1s indicating where the string
% should be not be converted.
%
% Outputs:
% strout - output string
%
% Author: Arnaud Delorme, CNL / Salk Institute, 9 April 2002
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 9 April 2002
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function strout = vararg2str(allargs, inputnam, inputnum, int2str );
if nargin < 1
help vararg2str;
return;
end;
if isempty(allargs)
strout = '';
return;
end;
% default arguments
% -----------------
if nargin < 2
inputnam(1:length(allargs)) = {''};
else
if length(inputnam) < length(allargs)
inputnam(end+1:length(allargs)) = {''};
end;
end;
if nargin < 3
inputnum(1:length(allargs)) = NaN;
else
if length(inputnum) < length(allargs)
inputnum(end+1:length(allargs)) = NaN;
end;
end;
if nargin < 4
int2str(1:length(allargs)) = 0;
else
if length(int2str) < length(allargs)
int2str(end+1:length(allargs)) = 0;
end;
end;
if ~iscell( allargs )
allargs = { allargs };
end;
% actual conversion
% -----------------
strout = '';
for index = 1:length(allargs)
tmpvar = allargs{index};
if ~isempty(inputnam{index})
strout = [ strout ',' inputnam{index} ];
else
if isstr( tmpvar )
if int2str(index)
strout = [ strout ',' tmpvar ];
else
strout = [ strout ',' str2str( tmpvar ) ];
end;
elseif isnumeric( tmpvar ) | islogical( tmpvar )
strout = [ strout ',' array2str( tmpvar ) ];
elseif iscell( tmpvar )
tmpres = vararg2str( tmpvar );
comas = find( tmpres == ',' );
tmpres(comas) = ' ';
strout = [ strout ',{' tmpres '}' ];
elseif isstruct(tmpvar)
strout = [ strout ',' struct2str( tmpvar ) ];
else
error('Unrecognized input');
end;
end;
end;
if ~isempty(strout)
strout = strout(2:end);
end;
% convert string to string
% ------------------------
function str = str2str( array )
if isempty( array), str = ''''''; return; end;
str = '';
for index = 1:size(array,1)
tmparray = deblank(array(index,:));
if isempty(tmparray)
str = [ str ','' ''' ];
else
str = [ str ',''' doublequotes(tmparray) '''' ];
end;
end;
if size(array,1) > 1
str = [ 'strvcat(' str(2:end) ')'];
else
str = str(2:end);
end;
return;
% convert array to string
% -----------------------
function str = array2str( array )
if isempty( array), str = '[]'; return; end;
if prod(size(array)) == 1, str = num2str(array); return; end;
if size(array,1) == 1, str = [ '[' contarray(array) '] ' ]; return; end;
if size(array,2) == 1, str = [ '[' contarray(array') ']'' ' ]; return; end;
str = '';
for index = 1:size(array,1)
str = [ str ';' contarray(array(index,:)) ];
end;
str = [ '[' str(2:end) ']' ];
return;
% convert struct to string
% ------------------------
function str = struct2str( structure )
if isempty( structure )
str = 'struct([])'; return;
end;
str = '';
allfields = fieldnames( structure );
for index = 1:length( allfields )
strtmp = '';
eval( [ 'allcontent = { structure.' allfields{index} ' };' ] ); % getfield generates a bug
str = [ str, '''' allfields{index} ''',{' vararg2str( allcontent ) '},' ];
end;
str = [ 'struct(' str(1:end-1) ')' ];
return;
% double the quotes in strings
% ----------------------------
function str = doublequotes( str )
quoteloc = union_bc(findstr( str, ''''), union(findstr(str, '%'), findstr(str, '\')));
if ~isempty(quoteloc)
for index = length(quoteloc):-1:1
str = [ str(1:quoteloc(index)) str(quoteloc(index):end) ];
end;
end;
return;
% test continuous arrays
% ----------------------
function str = contarray( array )
array = double(array);
tmpind = find( round(array) ~= array );
if prod(size(array)) == 1
str = num2str(array);
return;
end;
if size(array,1) == 1 & size(array,2) == 2
str = [num2str(array(1)) ' ' num2str(array(2))];
return;
end;
if isempty(tmpind) | all(isnan(array(tmpind)))
str = num2str(array(1));
skip = 0;
indent = array(2) - array(1);
for index = 2:length(array)
if array(index) ~= array(index-1)+indent | indent == 0
if skip <= 1
if skip == 0
str = [str ' ' num2str(array(index))];
else
str = [str ' ' num2str(array(index-1)) ' ' num2str(array(index))];
end;
else
if indent == 1
str = [str ':' num2str(array(index-1)) ' ' num2str(array(index))];
else
str = [str ':' num2str(indent) ':' num2str(array(index-1)) ' ' num2str(array(index))];
end;
end;
skip = 0;
indent = array(index) - array(index-1);
else
skip = skip + 1;
end;
end;
if array(index) == array(index-1)+indent
if skip ~= 0
if indent == 1
str = [str ':' num2str(array(index)) ];
elseif indent == 0
str = [str ' ' num2str(array(index)) ];
else
str = [str ':' num2str(indent) ':' num2str(array(index)) ];
end;
end;
end;
else
if length(array) < 10
str = num2str(array(1));
for index = 2:length(array)
str = [str ' ' num2str(array(index)) ];
end;
else
str = num2str(double(array));
end;
end;
|
github
|
lcnbeapp/beapp-master
|
readbvconf.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/readbvconf.m
| 3,483 |
utf_8
|
046693797f9f7a29e1836365b45d5273
|
% readbvconf() - read Brain Vision Data Exchange format configuration
% file
%
% Usage:
% >> CONF = readbvconf(pathname, filename);
%
% Inputs:
% pathname - path to file
% filename - filename
%
% Outputs:
% CONF - structure configuration
%
% Author: Andreas Widmann, University of Leipzig, 2007
% Copyright (C) 2007 Andreas Widmann, University of Leipzig, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% $Id: readbvconf.m 44 2009-11-12 02:00:56Z arnodelorme $
function CONF = readbvconf(pathname, filename)
if nargin < 2
error('Not enough input arguments');
end
% Open and read file
[IN, message] = fopen(fullfile(pathname, filename), 'r');
if IN == -1
[IN, message] = fopen(fullfile(pathname, lower(filename)));
if IN == -1
error(message)
end;
end
raw={};
while ~feof(IN)
raw = [raw; {fgetl(IN)}];
end
fclose(IN);
% Remove comments and empty lines
raw(strmatch(';', raw)) = [];
raw(cellfun('isempty', raw) == true) = [];
% Find sections
sectionArray = [strmatch('[', raw)' length(raw) + 1];
for iSection = 1:length(sectionArray) - 1
% Convert section name
tmpstr = deblank(raw{sectionArray(iSection)});
fieldName = lower(tmpstr(2:end-1));
%fieldName = lower(char(strread(tmpstr(2:end), '[%s', 'delimiter', ']')));
fieldName(isspace(fieldName) == true) = [];
% Fill structure with parameter value pairs
switch fieldName
case {'commoninfos' 'binaryinfos' 'asciiinfos'}
for line = sectionArray(iSection) + 1:sectionArray(iSection + 1) - 1
splitArray = strfind(raw{line}, '=');
CONF.(fieldName).(lower(raw{line}(1:splitArray(1) - 1))) = raw{line}(splitArray(1) + 1:end);
end
case {'channelinfos' 'coordinates'}
for line = sectionArray(iSection) + 1:sectionArray(iSection + 1) - 1
splitArray = strfind(raw{line}, '=');
CONF.(fieldName)(str2double(raw{line}(3:splitArray(1) - 1))) = {raw{line}(splitArray(1) + 1:end)};
end
case {'markerinfos'} % Allow discontinuity for markers (but not channelinfos and coordinates!)
for line = sectionArray(iSection) + 1:sectionArray(iSection + 1) - 1
splitArray = strfind(raw{line}, '=');
CONF.(fieldName)(line - sectionArray(iSection), :) = {raw{line}(splitArray(1) + 1:end) str2double(raw{line}(3:splitArray(1) - 1))};
end
if ~all(1:size(CONF.(fieldName), 1) == [CONF.(fieldName){:, 2}])
warning('Marker number discontinuity.')
end
case 'comment'
CONF.(fieldName) = raw(sectionArray(iSection) + 1:sectionArray(iSection + 1) - 1);
otherwise
fprintf('Unrecognized entry: %s\n', fieldName);
end
end
|
github
|
lcnbeapp/beapp-master
|
eeg_eventformat.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/eeg_eventformat.m
| 3,014 |
utf_8
|
d06b550e78556cb151a924c2b32b19f9
|
% eeg_eventformat() - Convert the event information of a dataset from struct
% to array or vice versa.
%
% Usage: >> [eventout fields] = eeg_eventformat( event, 'format', fields );
%
% Inputs:
% event - event array or structure
% format - ['struct'|'array'] see below
% fields - [optional] cell array of strings containing the names of
% the event struct fields. If this field is empty, it uses
% the following list for
% the names of the fields { 'type' 'latency' 'var1' ...
% 'var2' ... }.
% Output:
% eventout - output event array or structure
% fields - output cell array with the name of the fields
%
% Event formats:
% struct - Events are organised as an array of structs with at
% least two fields ('type' and 'latency')
% (Ex: reaction_time may be type 1).
% array - events are organized as an array, the first column
% representing the type, the second the latency and the
% other ones user-defined variables.
%
% Note: 1) The event structure is defined only for continuous data
% or epoched data derived from continuous data.
% 2) The event 'struct' format is more comprehensible.
% For instance, to see all the properties of event 7,
% type >> EEG.event(7)
% Unfortunately, structures are awkward for expert users to deal
% with from the command line (Ex: To get an array of latencies,
% >> [ EEG.event(:).latency ] )
% In array format, the same information is obtained by typing
% >> EEG.event(:,2)
% 3) This function automatically updates the 'eventfield'
% cell array depending on the format.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 27 Jan 2002
%
% See also: eeglab(), pop_selectevent(), pop_importevent()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 27 Jan 2002, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 2/06/02 modifed header - sm & ad
% 2/08/02 add field input - ad
% 2/12/02 reprogrammed function using epochformat.m - ad
function [event, eventfield] = eeg_eventformat(event, format, fields);
if nargin < 2
help eeg_eventformat;
return;
end;
if exist('fields') ~= 1, fields = { 'type', 'latency' }; end;
[event eventfield] = eeg_epochformat( event, format, fields);
|
github
|
lcnbeapp/beapp-master
|
supergui.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/supergui.m
| 21,015 |
utf_8
|
7052cd3beac708d834c25d61e1f9a26c
|
% supergui() - a comprehensive gui automatic builder. This function help
% to create GUI very fast without bothering about the
% positions of the elements. After creating a geometry,
% elements just place themselves into the predefined
% locations. It is especially usefull for figure where you
% intend to put text button and descriptions.
%
% Usage:
% >> [handlers, width, height ] = ...
% supergui( 'key1', 'val1', 'key2', 'val2', ... );
%
% Inputs:
% 'fig' - figure handler, if not given, create a new figure.
% 'geom' - cell array of cell array of integer vector. Each cell
% array defines the coordinate of a given input in the following
% manner: { nb_row nb_col [x_topcorner y_topcorner]
% [x_bottomcorner y_bottomcorner] };
% 'geomhoriz' - integer vector or cell array of numerical vectors describing the
% geometry of the elements in the figure.
% - if integer vector, vector length is the number of rows and vector
% values are the number of 'uilist' elements in each row.
% For example, [2 3 2] means that the
% figures will have 3 rows, with 2 elements in the first
% and last row and 3 elements in the second row.
% - if cell array, each vector describes the relative widths
% of items in each row. For example, { [2 8] [1 2 3] } which means
% that figures will have 2 rows, the first one with 2
% elements of relative width 2 and 8 (20% and 80%). The
% second row will have 3 elements of relative size 1, 2
% and 3 (1/6 2/6 and 3/6).
% 'geomvert' - describting geometry for the rows. For instance
% [1 2 1] means that the second row will be twice the height
% of the other ones. If [], all the lines have the same height.
% 'uilist' - list of uicontrol lists describing elements properties
% { { ui1 }, { ui2 }... }, { 'uiX' } being GUI matlab
% uicontrol arguments such as { 'style', 'radiobutton',
% 'String', 'hello' }. See Matlab function uicontrol() for details.
% 'borders' - [left right top bottom] GUI internal borders in normalized
% units (0 to 1). Default values are
% 'title' - optional figure title
% 'userdata' - optional userdata input for the figure
% 'inseth' - horizontal space between elements. Default is 2%
% of window size.
% 'insetv' - vertical space between elements. Default is 2%
% of window height.
% 'spacing' - [horiz vert] spacing in normalized units. Default
% 'spacingtype' - ['absolute'|'proportional'] abolute means that the
% spacing values are fixed. Proportional means that they
% depend on the number of element in a line.
% 'minwidth' - [integer] minimal width in pixels. Default is none.
% 'screenpos' - [x y] position of the right top corner of the graphic
% interface. 'center' may also be used to center the GUI on
% the screen.
% 'adjustbuttonwidth' - ['on'|'off'] adjust button width in the GUI.
% Default is 'off'.
%
% Hint:
% use 'print -mfile filemane' to save a matlab file of the figure.
%
% Output:
% handlers - all the handler of the elements (in the same order as the
% uilist input).
% height - adviced widht for the figure (so the text look nice).
% height - adviced height for the figure (so the text look nice).
%
% Example:
% figure;
% supergui( 'geomhoriz', { 1 1 }, 'uilist', { ...
% { 'style', 'radiobutton', 'string', 'radio' }, ...
% { 'style', 'pushbutton' , 'string', 'push' } } );
%
% Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 2001-
%
% See also: eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [handlers, outheight, allhandlers] = supergui( varargin);
% handlers cell format
% allhandlers linear format
handlers = {};
outheight = 0;
if nargin < 2
help supergui;
return;
end;
% get version and
% set additional parameters
% -------------------------
v = version;
indDot = find(v == '.');
versnum = str2num(v(1:indDot(2)-1));
if versnum >= 7.14
addParamFont = { 'fontsize' 12 };
else addParamFont = { };
end;
warning off MATLAB:hg:uicontrol:ParameterValuesMustBeValid
% decoding input and backward compatibility
% -----------------------------------------
if isstr(varargin{1})
options = varargin;
else
options = { 'fig' varargin{1} 'geomhoriz' varargin{2} ...
'geomvert' varargin{3} 'uilist' varargin(4:end) };
end
g = finputcheck(options, { 'geomhoriz' 'cell' [] {};
'fig' 'real' [] 0;
'geom' 'cell' [] {};
'uilist' 'cell' [] {};
'title' 'string' [] '';
'userdata' '' [] [];
'adjustbuttonwidth' 'string' { 'on' 'off' } 'off';
'geomvert' 'real' [] [];
'screenpos' { 'real' 'string' } [] [];
'horizontalalignment' 'string' { 'left','right','center' } 'left';
'minwidth' 'real' [] 10;
'borders' 'real' [] [0.05 0.04 0.07 0.06];
'spacing' 'real' [] [0.02 0.01];
'inseth' 'real' [] 0.02; % x border absolute (5% of width)
'insetv' 'real' [] 0.02 }, 'supergui');
if isstr(g), error(g); end
if ~isempty(g.geomhoriz)
maxcount = sum(cellfun('length', g.geomhoriz));
if maxcount ~= length(g.uilist)
warning('Wrong size for ''geomhoriz'' input');
end;
if ~isempty(g.geomvert)
if length(g.geomvert) ~= length(g.geomhoriz)
warning('Wrong size for ''geomvert'' input');
end;
end;
g.insetv = g.insetv/length(g.geomhoriz);
end;
if ~isempty(g.geom)
if length(g.geom) ~= length(g.uilist)
warning('Wrong size for ''geom'' input');
end;
maxcount = length(g.geom);
end;
% create new figure
% -----------------
if g.fig == 0
g.fig = figure('visible','off');
end
% converting the geometry formats
% -------------------------------
if ~isempty(g.geomhoriz) & ~iscell( g.geomhoriz )
oldgeom = g.geomhoriz;
g.geomhoriz = {};
for row = 1:length(oldgeom)
g.geomhoriz = { g.geomhoriz{:} ones(1, oldgeom(row)) };
end;
end
if isempty(g.geomvert)
g.geomvert = ones(1, length(g.geomhoriz));
end
% converting to the new format
% ----------------------------
if isempty(g.geom)
count = 1;
incy = 0;
sumvert = sum(g.geomvert);
maxhoriz = 1;
for row = 1:length(g.geomhoriz)
incx = 0;
maxhoriz = max(maxhoriz, length(g.geomhoriz{row}));
ratio = length(g.geomhoriz{row})/sum(g.geomhoriz{row});
for column = 1:length(g.geomhoriz{row})
g.geom{count} = { length(g.geomhoriz{row}) sumvert [incx incy] [g.geomhoriz{row}(column)*ratio g.geomvert(row)] };
incx = incx+g.geomhoriz{row}(column)*ratio;
count = count+1;
end;
incy = incy+g.geomvert(row);
end;
g.borders(1:2) = g.borders(1:2)/maxhoriz*5;
g.borders(3:4) = g.borders(3:4)/sumvert*10;
g.spacing(1) = g.spacing(1)/maxhoriz*5;
g.spacing(2) = g.spacing(2)/sumvert*10;
end;
% disp new geometry
% -----------------
if 0
fprintf('{ ...\n');
for index = 1:length(g.geom)
fprintf('{ %g %g [%g %g] [%g %g] } ...\n', g.geom{index}{1}, g.geom{index}{2}, ...
g.geom{index}{3}(1), g.geom{index}{3}(2), g.geom{index}{4}(1), g.geom{index}{3}(2));
end;
fprintf('};\n');
end;
% get axis coordinates
% --------------------
try
set(g.fig, 'menubar', 'none', 'numbertitle', 'off');
catch
end
pos = [0 0 1 1]; % plot relative to current axes
q = [pos(1) pos(2) 0 0];
s = [pos(3) pos(4) pos(3) pos(4)]; % allow to use normalized position [0 100] for x and y
axis('off');
% creating guis
% -------------
row = 1; % count the elements
column = 1; % count the elements
factmultx = 0;
factmulty = 0; %zeros(length(g.geomhoriz));
for counter = 1:maxcount
% init
clear rowhandle;
gm = g.geom{counter};
[posx posy width height] = getcoord(gm{1}, gm{2}, gm{3}, gm{4}, g.borders, g.spacing);
try
currentelem = g.uilist{ counter };
catch
fprintf('Warning: not all boxes were filled\n');
return;
end;
if ~isempty(currentelem)
% decode metadata
% ---------------
if strcmpi(currentelem{1}, 'link2lines'),
currentelem(1) = [];
hf1 = 3.6/2-0.3;
hf2 = 0.7/2-0.3;
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx-width/2 posy+hf1*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', '');
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx-width/2 posy+hf2*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', '');
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx posy+hf2*height 0.005 (hf1-hf2+0.1)*height].*s+q, 'style', 'pushbutton', 'string', '');
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx posy+(hf1+hf2)/2*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', '');
allhandlers{counter} = 0;
else
if strcmpi(currentelem{1}, 'width'),
curwidth = currentelem{2};
currentelem(1:2) = [];
else curwidth = 0;
end;
if strcmpi(currentelem{1}, 'align'),
align = currentelem{2};
currentelem(1:2) = [];
else align = 'right';
end;
if strcmpi(currentelem{1}, 'stickto'),
stickto = currentelem{2};
currentelem(1:2) = [];
else stickto = 'none';
end;
if strcmpi(currentelem{1}, 'vertshift'), currentelem(1) = []; addvert = -height/2;
else addvert = 0;
end;
if strcmpi(currentelem{1}, 'vertexpand'), heightfactor = currentelem{2}; addvert = -(heightfactor-1)*height; currentelem(1:2) = [];
else heightfactor = 1;
end;
% position adjustment depending on GUI type
if isstr(currentelem{2}) && strcmpi(currentelem{2}, 'popupmenu')
posy = posy-height/10;
end;
if isstr(currentelem{2}) && strcmpi(currentelem{2}, 'text')
posy = posy+height/5;
end;
if strcmpi(currentelem{1}, 'function'),
% property grid argument
panel = uipanel('Title','','FontSize',12,'BackgroundColor','white','Position',[posx posy+addvert width height*heightfactor].*s+q);
allhandlers{counter} = arg_guipanel(panel, currentelem{:});
else
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx posy+addvert width height*heightfactor].*s+q, currentelem{:}, addParamFont{:});
% this simply compute a factor so that all uicontrol will be visible
% ------------------------------------------------------------------
style = get( allhandlers{counter}, 'style');
set( allhandlers{counter}, 'units', 'pixels');
curpos = get(allhandlers{counter}, 'position');
curext = get(allhandlers{counter}, 'extent');
if curwidth ~= 0
curwidth = curwidth/((factmultx-1)/1.85+1);
if strcmpi(align, 'right')
curpos(1) = curpos(1)+curpos(3)-curwidth;
elseif strcmpi(align, 'center')
curpos(1) = curpos(1)+curpos(3)/2-curwidth/2;
end;
set(allhandlers{counter}, 'position', [ curpos(1) curpos(2) curwidth curpos(4) ]);
if strcmpi(stickto, 'on')
set( allhandlers{counter-1}, 'units', 'pixels');
curpos2 = get(allhandlers{counter-1}, 'position');
set(allhandlers{counter-1}, 'position', [ curpos(1)-curpos2(3)-10 curpos2(2) curpos2(3) curpos2(4) ]);
set( allhandlers{counter-1}, 'units', 'normalized');
end;
curext(3) = curwidth;
end;
set( allhandlers{counter}, 'units', 'normalized');
end;
if ~strcmp(style, 'edit') && (~strcmp(style, 'pushbutton') || strcmpi(g.adjustbuttonwidth, 'on'))
%tmp = curext(3)/curpos(3);
%if tmp > 3*factmultx && factmultx > 0, adsfasd; end;
factmultx = max(factmultx, curext(3)/curpos(3));
if strcmp(style, 'pushbutton'), factmultx = factmultx*1.1; end;
end;
if ~strcmp(style, 'listbox')
factmulty = max(factmulty, curext(4)/curpos(4));
end;
% Uniformize button text aspect (first letter must be upercase)
% -----------------------------
if strcmp(style, 'pushbutton')
tmptext = get(allhandlers{counter}, 'string');
if length(tmptext) > 1
if upper(tmptext(1)) ~= tmptext(1) || lower(tmptext(2)) ~= tmptext(2) && ~strcmpi(tmptext, 'STATS')
tmptext = lower(tmptext);
try, tmptext(1) = upper(tmptext(1)); catch, end;
end;
end;
set(allhandlers{counter}, 'string', tmptext);
end;
end;
else
allhandlers{counter} = 0;
end;
end;
% adjustments
% -----------
factmultx = factmultx*1.02;% because some text was still hidden
%factmultx = factmultx*1.2;
if factmultx < 0.1
factmultx = 0.1;
end;
% for MAC (magnify figures that have edit fields)
% -------
warning off;
try,
comp = computer;
if length(comp) > 2 && strcmpi(comp(1:3), 'MAC')
factmulty = factmulty*1.5;
elseif ~isunix % windows
factmulty = factmulty*1.08;
end;
catch, end;
factmulty = factmulty*0.9; % global shinking
warning on;
% scale and replace the figure in the screen
% -----------------------------------------
pos = get(g.fig, 'position');
if factmulty > 1
pos(2) = max(0,pos(2)+pos(4)-pos(4)*factmulty);
end;
pos(1) = pos(1)+pos(3)*(1-factmultx)/2;
pos(3) = max(pos(3)*factmultx, g.minwidth);
pos(4) = pos(4)*factmulty;
set(g.fig, 'position', pos);
% vertical alignment to bottom for text
% ---------------------------------------
for index = 1:length(allhandlers)
if allhandlers{index} ~= 0 && isnumeric(allhandlers{index})
if strcmp(get(allhandlers{index}, 'style'), 'text')
set(allhandlers{index}, 'unit', 'pixel');
curpos = get(allhandlers{index}, 'position');
curext = get(allhandlers{index}, 'extent');
set(allhandlers{index}, 'position', [curpos(1) curpos(2)-4 curpos(3) curext(4)]);
set(allhandlers{index}, 'unit', 'normalized');
end;
end;
end;
% setting defaults colors
%------------------------
try, icadefs;
catch,
GUIBACKCOLOR = [.8 .8 .8];
GUIPOPBUTTONCOLOR = [.8 .8 .8];
GUITEXTCOLOR = [0 0 0];
end;
numobjects = cellfun(@isnumeric, allhandlers);
allhandlersnum = [ allhandlers{numobjects} ];
hh = findobj(allhandlersnum, 'parent', g.fig, 'style', 'text');
%set(hh, 'BackgroundColor', get(g.fig, 'color'), 'horizontalalignment', 'left');
set(hh, 'Backgroundcolor', GUIBACKCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
try
set(g.fig, 'color',GUIBACKCOLOR );
catch
end
set(hh, 'horizontalalignment', g.horizontalalignment);
hh = findobj(allhandlersnum, 'style', 'edit');
set(hh, 'BackgroundColor', [1 1 1]); %, 'horizontalalignment', 'right');
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'pushbutton');
comp = computer;
if length(comp) < 3 || ~strcmpi(comp(1:3), 'MAC') % this puts the wrong background on macs
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
end;
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'popupmenu');
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'checkbox');
set(hh, 'backgroundcolor', GUIBACKCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'listbox');
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'radio');
set(hh, 'foregroundcolor', GUITEXTCOLOR);
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(g.fig, 'visible', 'on');
% screen position
% ---------------
if ~isempty(g.screenpos)
pos = get(g.fig, 'position');
if isnumeric(g.screenpos)
set(g.fig, 'position', [ g.screenpos pos(3) pos(4)]);
else
screenSize = get(0, 'screensize');
pos(1) = (screenSize(3)-pos(3))/2;
pos(2) = (screenSize(4)-pos(4))/2+pos(4);
set(g.fig, 'position', pos);
end;
end;
% set userdata and title
% ----------------------
if ~isempty(g.userdata), set(g.fig, 'userdata', g.userdata); end;
if ~isempty(g.title ), set(g.fig, 'name', g.title ); end;
return;
function [posx posy width height] = getcoord(geom1, geom2, coord1, sz, borders, spacing);
coord2 = coord1+sz;
borders(1:2) = borders(1:2)-spacing(1);
borders(3:4) = borders(3:4)-spacing(2);
% absolute positions
posx = coord1(1)/geom1;
posy = coord1(2)/geom2;
posx2 = coord2(1)/geom1;
posy2 = coord2(2)/geom2;
width = posx2-posx;
height = posy2-posy;
% add spacing
posx = posx+spacing(1)/2;
width = max(posx2-posx-spacing(1), 0.001);
height = max(posy2-posy-spacing(2), 0.001);
posy = max(0, 1-posy2)+spacing(2)/2;
% add border
posx = posx*(1-borders(1)-borders(2))+borders(1);
posy = posy*(1-borders(3)-borders(4))+borders(4);
width = width*( 1-borders(1)-borders(2));
height = height*(1-borders(3)-borders(4));
function [posx posy width height] = getcoordold(geom1, geom2, coord1, sz);
coord2 = coord1+sz;
horiz_space = 0.05/geom1;
vert_space = 0.05/geom2;
horiz_border = min(0.1, 1/geom1)-horiz_space;
vert_border = min(0.2, 1.5/geom2)-vert_space;
% absolute positions
posx = coord1(1)/geom1;
posy = coord1(2)/geom2;
posx2 = coord2(1)/geom1;
posy2 = coord2(2)/geom2;
width = posx2-posx;
height = posy2-posy;
% add spacing
posx = posx+horiz_space/2;
width = max(posx2-posx-horiz_space, 0.001);
height = max(posy2-posy- vert_space, 0.001);
posy = max(0, 1-posy2)+vert_space/2;
% add border
posx = posx*(1-horiz_border)+horiz_border/2;
posy = posy*(1- vert_border)+vert_border/2;
width = width*(1-horiz_border);
height = height*(1-vert_border);
% posx = coord1(1)/geom1+horiz_border*1/geom1/2;
% posy = 1-(coord1(2)/geom2+vert_border*1/geom2/2)-1/geom2;
%
% posx2 = coord2(1)/geom1+horiz_border*1/geom1/2;
% posy2 = 1-(coord2(2)/geom2+vert_border*1/geom2/2)-1/geom2;
%
% width = posx2-posx;
% height = posy-posy2;
%h = axes('unit', 'normalized', 'position', [ posx posy width height ]);
%h = axes('unit', 'normalized', 'position', [ coordx/geom1 1-coordy/geom2-1/geom2 1/geom1 1/geom2 ]);
|
github
|
lcnbeapp/beapp-master
|
unique_bc.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/unique_bc.m
| 717 |
utf_8
|
1ac4b80ca073d969c0b6d0e7a0db1f3d
|
% unique_bc - unique backward compatible with Matlab versions prior to 2013a
function [C,IA,IB] = unique_bc(A,varargin);
errorFlag = error_bc;
v = version;
indp = find(v == '.');
v = str2num(v(1:indp(2)-1));
if v > 7.19, v = floor(v) + rem(v,1)/10; end;
if nargin > 2
ind = strmatch('legacy', varargin);
if ~isempty(ind)
varargin(ind) = [];
end;
end;
if v >= 7.14
[C,IA,IB] = unique(A,varargin{:},'legacy');
if errorFlag
[C2,IA2] = unique(A,varargin{:});
if ~isequal(C, C2) || ~isequal(IA, IA2) || ~isequal(IB, IB2)
warning('backward compatibility issue with call to unique function');
end;
end;
else
[C,IA,IB] = unique(A,varargin{:});
end;
|
github
|
lcnbeapp/beapp-master
|
pop_loadbv.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/pop_loadbv.m
| 14,131 |
utf_8
|
fa611f0f7f28f1958c48ab15c61fbe64
|
% pop_loadbv() - load Brain Vision Data Exchange format dataset and
% return EEGLAB EEG structure
%
% Usage:
% >> [EEG, com] = pop_loadbv; % pop-up window mode
% >> [EEG, com] = pop_loadbv(path, hdrfile);
% >> [EEG, com] = pop_loadbv(path, hdrfile, srange);
% >> [EEG, com] = pop_loadbv(path, hdrfile, [], chans);
% >> [EEG, com] = pop_loadbv(path, hdrfile, srange, chans);
%
% Optional inputs:
% path - path to files
% hdrfile - name of Brain Vision vhdr-file (incl. extension)
% srange - scalar first sample to read (up to end of file) or
% vector first and last sample to read (e.g., [7 42];
% default: all)
% chans - vector channels channels to read (e.g., [1:2 4];
% default: all)
%
% Outputs:
% EEG - EEGLAB EEG structure
% com - history string
%
% Author: Andreas Widmann & Arnaud Delorme, 2004-
% Copyright (C) 2004 Andreas Widmann, University of Leipzig, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% $Id: pop_loadbv.m 53 2010-05-22 21:57:38Z arnodelorme $
% Revision 1.5 2010/03/23 21:19:52 roy
% added some lines so that the function can deal with the space lines in the ASCII multiplexed data file
function [EEG, com] = pop_loadbv(path, hdrfile, srange, chans)
com = '';
EEG = [];
if nargin < 2
[hdrfile path] = uigetfile2('*.vhdr', 'Select Brain Vision vhdr-file - pop_loadbv()');
if hdrfile(1) == 0, return; end
drawnow;
uigeom = {[1 0.5] [1 0.5]};
uilist = {{ 'style' 'text' 'string' 'Interval (samples; e.g., [7 42]; default: all):'} ...
{ 'style' 'edit' 'string' ''} ...
{ 'style' 'text' 'string' 'Channels (e.g., [1:2 4]; default: all):'} ...
{ 'style' 'edit' 'string' ''}};
result = inputgui(uigeom, uilist, 'pophelp(''pop_loadbv'')', 'Load a Brain Vision Data Exchange format dataset');
if isempty(result), return, end
if ~isempty(result{1}),
srange = str2num(result{1});
end
if ~isempty(result{2}),
chans = str2num(result{2});
end
end
% Header file
disp('pop_loadbv(): reading header file');
hdr = readbvconf(path, hdrfile);
% Common Infos
try
EEG = eeg_emptyset;
catch
end
EEG.comments = ['Original file: ' hdr.commoninfos.datafile];
hdr.commoninfos.numberofchannels = str2double(hdr.commoninfos.numberofchannels);
EEG.srate = 1000000 / str2double(hdr.commoninfos.samplinginterval);
% Binary Infos
if strcmpi(hdr.commoninfos.dataformat, 'binary')
switch lower(hdr.binaryinfos.binaryformat)
case 'int_16', binformat = 'int16'; bps = 2;
case 'uint_16', binformat = 'uint16'; bps = 2;
case 'ieee_float_32', binformat = 'float32'; bps = 4;
otherwise, error('Unsupported binary format');
end
end
% Channel Infos
if ~exist('chans', 'var')
chans = 1:hdr.commoninfos.numberofchannels;
EEG.nbchan = hdr.commoninfos.numberofchannels;
elseif isempty(chans)
chans = 1:hdr.commoninfos.numberofchannels;
EEG.nbchan = hdr.commoninfos.numberofchannels;
else
EEG.nbchan = length(chans);
end
if any(chans < 1) || any(chans > hdr.commoninfos.numberofchannels)
error('chans out of available channel range');
end
if isfield(hdr, 'channelinfos')
for chan = 1:length(chans)
try
[EEG.chanlocs(chan).labels, chanlocs(chan).ref, chanlocs(chan).scale, chanlocs(chan).unit] = strread(hdr.channelinfos{chans(chan)}, '%s%s%s%s', 1, 'delimiter', ',');
catch % Octave compatible code below
str = hdr.channelinfos{chans(chan)};
[EEG.chanlocs(chan).labels str] = strtok(str, ',');
[chanlocs(chan).ref str] = strtok(str, ',');
[chanlocs(chan).scale str] = strtok(str, ',');
[chanlocs(chan).unit str] = strtok(str, ',');
end;
EEG.chanlocs(chan).labels = char(EEG.chanlocs(chan).labels);
chanlocs(chan).scale = str2double(char(chanlocs(chan).scale));
% chanlocs(chan).unit = native2unicode(double(char(chanlocs(chan).scale)), 'UTF-8');
% EEG.chanlocs(chan).datachan = chans(chan);
end
if isempty([chanlocs.scale])
chanlocs = rmfield(chanlocs, 'scale');
end
end;
% [EEG.chanlocs.type] = deal([]);
% Coordinates
if isfield(hdr, 'coordinates')
hdr.coordinates(end+1:length(chans)) = { [] };
onenon0channel = 0;
for chan = 1:length(chans)
if ~isempty(hdr.coordinates{chans(chan)})
if ismatlab,
[EEG.chanlocs(chan).sph_radius, theta, phi] = strread(hdr.coordinates{chans(chan)}, '%f%f%f', 'delimiter', ',');
else
str = hdr.coordinates{chans(chan)};
[EEG.chanlocs(chan).sph_radius str] = strtok(str, ','); EEG.chanlocs(chan).sph_radius = str2num(EEG.chanlocs(chan).sph_radius);
[theta str] = strtok(str, ','); theta = str2num(theta);
[phi str] = strtok(str, ','); phi = str2num(phi);
end;
if EEG.chanlocs(chan).sph_radius == 0 && theta == 0 && phi == 0
EEG.chanlocs(chan).sph_radius = [];
EEG.chanlocs(chan).sph_theta = [];
EEG.chanlocs(chan).sph_phi = [];
else
onenon0channel = 1;
EEG.chanlocs(chan).sph_theta = phi - 90 * sign(theta);
EEG.chanlocs(chan).sph_phi = -abs(theta) + 90;
end
end;
end
try,
if onenon0channel
[EEG.chanlocs, EEG.chaninfo] = pop_chanedit(EEG.chanlocs, 'convert', 'sph2topo');
[EEG.chanlocs, EEG.chaninfo] = pop_chanedit(EEG.chanlocs, 'convert', 'sph2cart');
end;
catch, end
end
% Open data file and find the number of data points
% -------------------------------------------------
disp('pop_loadbv(): reading EEG data');
[IN, message] = fopen(fullfile(path, hdr.commoninfos.datafile), 'r');
if IN == -1
[IN, message] = fopen(fullfile(path, lower(hdr.commoninfos.datafile)));
if IN == -1
error(message)
end;
end
if isfield(hdr.commoninfos, 'datapoints')
if isempty(hdr.commoninfos.datapoints)
fseek(IN, 0, 'eof');
hdr.commoninfos.datapoints = ftell(IN) / (hdr.commoninfos.numberofchannels * bps);
fseek(IN, 0, 'bof');
else
hdr.commoninfos.datapoints = str2double(hdr.commoninfos.datapoints);
end;
elseif strcmpi(hdr.commoninfos.dataformat, 'binary')
fseek(IN, 0, 'eof');
hdr.commoninfos.datapoints = ftell(IN) / (hdr.commoninfos.numberofchannels * bps);
fseek(IN, 0, 'bof');
else
hdr.commoninfos.datapoints = NaN;
end
if ~strcmpi(hdr.commoninfos.dataformat, 'binary') % ASCII
tmppoint = hdr.commoninfos.datapoints;
tmpchan = fscanf(IN, '%s', 1);
tmpdata = fscanf(IN, '%f', inf);
hdr.commoninfos.datapoints = length(tmpdata);
chanlabels = 1;
if isnan(str2double(tmpchan))
hdr.commoninfos.datapoints = hdr.commoninfos.datapoints+1;
chanlabels = 0;
end;
end;
% Sample range
if ~exist('srange', 'var') || isempty(srange)
srange = [ 1 hdr.commoninfos.datapoints];
EEG.pnts = hdr.commoninfos.datapoints;
elseif length(srange) == 1
EEG.pnts = hdr.commoninfos.datapoints - srange(1) + 1;
else
EEG.pnts = srange(2) - srange(1) + 1;
end
if any(srange < 1) || any(srange > hdr.commoninfos.datapoints)
error('srange out of available data range');
end
% Read data
if strcmpi(hdr.commoninfos.dataformat, 'binary')
switch lower(hdr.commoninfos.dataorientation)
case 'multiplexed'
if EEG.nbchan == hdr.commoninfos.numberofchannels % Read all channels
fseek(IN, (srange(1) - 1) * EEG.nbchan * bps, 'bof');
EEG.data = fread(IN, [EEG.nbchan, EEG.pnts], [binformat '=>float32']);
else % Read channel subset
EEG.data = repmat(single(0), [EEG.nbchan, EEG.pnts]); % Preallocate memory
for chan = 1:length(chans)
fseek(IN, (srange(1) - 1) * hdr.commoninfos.numberofchannels * bps + (chans(chan) - 1) * bps, 'bof');
EEG.data(chan, :) = fread(IN, [1, EEG.pnts], [binformat '=>float32'], (hdr.commoninfos.numberofchannels - 1) * bps);
end
end
case 'vectorized'
if isequal(EEG.pnts, hdr.commoninfos.datapoints) && EEG.nbchan == hdr.commoninfos.numberofchannels % Read entire file
EEG.data = fread(IN, [EEG.pnts, EEG.nbchan], [binformat '=>float32']).';
else % Read fraction of file
EEG.data = repmat(single(0), [EEG.nbchan, EEG.pnts]); % Preallocate memory
for chan = 1:length(chans)
fseek(IN, ((chans(chan) - 1) * hdr.commoninfos.datapoints + srange(1) - 1) * bps, 'bof');
EEG.data(chan, :) = fread(IN, [1, EEG.pnts], [binformat '=>float32']);
end
end
otherwise
error('Unsupported data orientation')
end
else % ASCII data
disp('If this function does not work, export your data in binary format');
EEG.data = repmat(single(0), [EEG.nbchan, EEG.pnts]);
if strcmpi(lower(hdr.commoninfos.dataorientation), 'vectorized')
count = 1;
fseek(IN, 0, 'bof');
len = inf;
for chan = 1:hdr.commoninfos.numberofchannels
if chanlabels, tmpchan = fscanf(IN, '%s', 1); end;
tmpdata = fscanf(IN, '%f', len); len = length(tmpdata);
if ismember(chan, chans)
EEG.data(count, :) = tmpdata(srange(1):srange(2))';
count = count + 1;
end;
end;
elseif strcmpi(lower(hdr.commoninfos.dataorientation), 'multiplexed')
% fclose(IN);
% error('ASCII multiplexed reading not implemeted yet; export as a different format');
if EEG.nbchan == hdr.commoninfos.numberofchannels % Read all channels
tmpchan= fgetl(IN);
count = 1;
while ~feof(IN)
tmpstr = fgetl(IN);
if ~isempty(tmpstr)
temp_ind = tmpstr==',';
tmpstr(temp_ind) = '.';
tmpdata = strread(tmpstr);
EEG.data(:,count) = tmpdata';
count = count + 1;
end;
end;
EEG.pnts = count - 1;
else
end;
end;
end;
fclose(IN);
EEG.trials = 1;
EEG.xmin = 0;
EEG.xmax = (EEG.pnts - 1) / EEG.srate;
% Convert to EEG.data to double for MATLAB < R14
if str2double(version('-release')) < 14
EEG.data = double(EEG.data);
end
% Scale data
if exist('chanlocs', 'var') && isfield(chanlocs, 'scale')
disp('pop_loadbv(): scaling EEG data');
for chan = 1:EEG.nbchan
if ~isnan(chanlocs(chan).scale)
EEG.data(chan, :) = EEG.data(chan, :) * chanlocs(chan).scale;
end;
end
end
% Marker file
if isfield(hdr.commoninfos, 'markerfile')
disp('pop_loadbv(): reading marker file');
MRK = readbvconf(path, hdr.commoninfos.markerfile);
if hdr.commoninfos.datafile ~= MRK.commoninfos.datafile
disp('pop_loadbv() warning: data files in header and marker files inconsistent.');
end
% Marker infos
if isfield(MRK, 'markerinfos')
EEG.event = parsebvmrk(MRK);
% Correct event latencies by first sample offset
tmpevent = EEG.event;
for index = 1:length(EEG.event)
tmpevent(index).latency = tmpevent(index).latency - srange(1) + 1;
end;
EEG.event = tmpevent;
% Remove unreferenced events
EEG.event = EEG.event([tmpevent.latency] >= 1 & [tmpevent.latency] <= EEG.pnts);
% Copy event structure to urevent structure
EEG.urevent = rmfield(EEG.event, 'urevent');
% find if boundaries at homogenous intervals
% ------------------------------------------
tmpevent = EEG.event;
boundaries = strmatch('boundary', {tmpevent.type});
boundlats = unique([tmpevent(boundaries).latency]);
if (isfield(hdr.commoninfos, 'segmentationtype') && (strcmpi(hdr.commoninfos.segmentationtype, 'markerbased') || strcmpi(hdr.commoninfos.segmentationtype, 'fixtime'))) && length(boundaries) > 1 && length(unique(diff([boundlats EEG.pnts + 1]))) == 1
EEG.trials = length(boundlats);
EEG.pnts = EEG.pnts / EEG.trials;
EEG.event(boundaries) = [];
% adding epoch field
% ------------------
tmpevent = EEG.event;
for index = 1:length(EEG.event)
EEG.event(index).epoch = ceil(tmpevent(index).latency / EEG.pnts);
end
% finding minimum time
% --------------------
tles = strmatch('time 0', lower({tmpevent.code}))';
if ~isempty(tles)
for iTLE = tles(:)'
EEG.event(iTLE).type ='TLE';
end
EEG.xmin = -(tmpevent(tles(1)).latency - 1) / EEG.srate;
end
else
for index = 1:length(boundaries)
EEG.event(index).duration = NaN;
end;
end
end
end
EEG.ref = 'common';
try
EEG = eeg_checkset(EEG);
catch
end
if nargout == 2
com = sprintf('EEG = pop_loadbv(''%s'', ''%s'', %s, %s);', path, hdrfile, mat2str(srange), mat2str(chans));
end
|
github
|
lcnbeapp/beapp-master
|
union_bc.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/union_bc.m
| 724 |
utf_8
|
958b5b56de3e20c3892b2d7809e830fd
|
% union_bc - union backward compatible with Matlab versions prior to 2013a
function [C,IA,IB] = union_bc(A,B,varargin);
errorFlag = error_bc;
v = version;
indp = find(v == '.');
v = str2num(v(1:indp(2)-1));
if v > 7.19, v = floor(v) + rem(v,1)/10; end;
if nargin > 2
ind = strmatch('legacy', varargin);
if ~isempty(ind)
varargin(ind) = [];
end;
end;
if v >= 7.14
[C,IA,IB] = union(A,B,varargin{:},'legacy');
if errorFlag
[C2,IA2,IB2] = union(A,B,varargin{:});
if (~isequal(C, C2) || ~isequal(IA, IA2) || ~isequal(IB, IB2))
warning('backward compatibility issue with call to union function');
end;
end;
else
[C,IA,IB] = union(A,B,varargin{:});
end;
|
github
|
lcnbeapp/beapp-master
|
eeg_emptyset.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/eeg_emptyset.m
| 2,505 |
utf_8
|
a93f07a3989f904c1eade15794aab1f1
|
% eeg_emptyset() - Initialize an EEG dataset structure with default values.
%
% Usage:
% >> EEG = eeg_emptyset();
%
% Outputs:
% EEG - empty dataset structure with default values.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
function EEG = eeg_emptyset();
EEG.setname = '';
EEG.filename = '';
EEG.filepath = '';
EEG.subject = '';
EEG.group = '';
EEG.condition = '';
EEG.session = [];
EEG.comments = '';
EEG.nbchan = 0;
EEG.trials = 0;
EEG.pnts = 0;
EEG.srate = 1;
EEG.xmin = 0;
EEG.xmax = 0;
EEG.times = [];
EEG.data = [];
EEG.icaact = [];
EEG.icawinv = [];
EEG.icasphere = [];
EEG.icaweights = [];
EEG.icachansind = [];
EEG.chanlocs = [];
EEG.urchanlocs = [];
EEG.chaninfo = [];
EEG.ref = [];
EEG.event = [];
EEG.urevent = [];
EEG.eventdescription = {};
EEG.epoch = [];
EEG.epochdescription = {};
EEG.reject = [];
EEG.stats = [];
EEG.specdata = [];
EEG.specicaact = [];
EEG.splinefile = '';
EEG.icasplinefile = '';
EEG.dipfit = [];
EEG.history = '';
EEG.saved = 'no';
EEG.etc = [];
%EEG.reject.threshold = [1 0.8 0.85];
%EEG.reject.icareject = [];
%EEG.reject.compreject = [];
%EEG.reject.gcompreject= [];
%EEG.reject.comptrial = [];
%EEG.reject.sigreject = [];
%EEG.reject.elecreject = [];
%EEG.stats.kurta = [];
%EEG.stats.kurtr = [];
%EEG.stats.kurtd = [];
%EEG.stats.eegentropy = [];
%EEG.stats.eegkurt = [];
%EEG.stats.eegkurtg = [];
%EEG.stats.entropy = [];
%EEG.stats.kurtc = [];
%EEG.stats.kurtt = [];
%EEG.stats.entropyc = [];
return;
|
github
|
lcnbeapp/beapp-master
|
pop_chanedit.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/pop_chanedit.m
| 51,760 |
utf_8
|
b862a91a53ab88379de4ffc7091bf575
|
% pop_chanedit() - Edit the channel locations structure of an EEGLAB dataset,
% EEG.chanlocs. For structure location and file formats,
% see >> help readlocs
%
% EEG.chanlocs. For structure location and file formats,
% see >> help readlocs
%
% Usage: >> EEG = pop_chanedit( EEG, 'key1', value1, 'key2', value2, ... );
% >> [ chanlocs options ] = pop_chanedit( chanlocs, 'key1', value1);
% >> [ chanlocs chaninfo options ] = pop_chanedit( chanlocs, chaninfo, ...
% 'key1', value1, 'key2', value2, ... );
%
% Graphic interface:
% "Channel information ('field name')" - [edit boxes] display channel field
% contents for the current channel. Command line equivalent
% to modify these fields: 'transform'
% "Opt. 3D center" - [button] optimally re-center 3-D channel coordinates. Uses
% chancenter(). Command line equivalent: 'convert', { 'chancenter'
% [xc yc zc] }, [xc yc zc] being the center of the sphere. Use []
% to find the center of the best fitting sphere.
% "Rotate axis" - [button] force one electrode to one position and rotate the other
% electrodes accordingly. Command line equivalent: 'forcelocs'.
% "Transform axis" - [button] perform any operation on channel fields. Command
% line equivalent: 'transform'.
% "Xyz->polar & sph." - [button] convert 3-D cartesian coordinates to polar and
% 3-D spherical coordinates. This is useful when you edit the
% coordinates manually. Command line equivalent: 'convert', 'cart2all'.
% "Sph.->polar & xyz" - [button] convert 3-D spherical coordinates to polar and
% 3-D cartesian coordinates. Command line equivalent: 'convert', 'sph2all'.
% "Polar->sph & xyz" - [button] convert 2-D polar coordinates to 3-D spherical and
% 3-D cartesian coordinates. Command line equivalent: 'convert', 'topo2all'.
% Note that if spherical radii are absent, they are forced to 1.
% "Set head radius" - [button] change head size radius. This is useful
% to make channels location compatible with a specified spherical model.
% Command line equivalent: 'headrad'.
% "Set channel types" - [button] set channel type names for a range of data channels.
% "Delete chan" - [button] delete channel. Command line equivalent: 'delete'.
% "Insert chan" - [button] insert channel before current channel.
% Command line equivalent: 'insert'.
% "<<" - [button] scroll channel backward by 10.
% "<" - [button] scroll channel backward by 1.
% ">" - [button] scroll channel forward by 1.
% ">>" - [button] scroll channel forward by 10.
% "Append chan" - [button] append channel after the current channel.
% Command line equivalent: 'append'.
% "Plot 2D" - [button] plot channel locations in 2-D using topoplot()
% "Plot radius [value (0.2-1.0), []=auto)" - [edit box] default plotting radius
% in 2-D polar views. This does NOT affect channel locations; it
% is only used for visualization. This parameter is attached to the
% chanlocs structure and is then used in all 2-D scalp topoplots.
% Default -> to data limits. Command line equivalent: 'plotrad'.
% "Nose along +X" - [list] Indicate the direction of the nose. This information
% is used in functions like topoplot(), headplot() and dipplot().
% Command line equivalent: 'nosedir'.
% "Plot 3D" - [button] plot channel positions in 3-D using plotchans3d()
% "Read locations" - [button] read location file using readlocs()
% Command line equivalent: 'load'.
% "Read help" - [button] display readlocs() function help.
% "Save .ced" - [button] save channel locations in native EEGLAB ".ced" format.
% Command line equivalent: 'save'.
% "Save others" - [button] save channel locations in other formats using
% pop_writelocs() (see readlocs() for available channel formats).
% "Cancel" - [button] cancel all editing.
% "Help" - [button] display this help message.
% "OK" - [button] save edits and propagate to parent.
%
% Inputs:
% EEG - EEG dataset
% chanlocs - EEG.chanlocs structure
%
% Optional inputs:
% 'convert' - {conversion_type [args]} Conversion type may be: 'cart2topo'
% 'sph2topo', 'topo2sph', 'sph2cart', 'cart2sph', or 'chancenter'.
% See help messages for these functions. Args are only relevant
% for 'chancenter'. More info is given in the graphic interface
% description above.
% 'transform' - String command for manipulating arrays. 'chan' is full channel
% info. Fields that can be manipulated are 'labels', 'theta'
% 'radius' (polar angle and radius), 'X', 'Y', 'Z' (cartesian
% 3-D) or 'sph_theta', 'sph_phi', 'sph_radius' for spherical
% horizontal angle, azimuth and radius.
% Ex: 'chans(3) = chans(14)', 'X = -X' or a multi-step transform
% with steps separated by ';': Ex. 'TMP = X; X = Y; Y = TMP'
% 'changechan' - {number value1 value2 value3 ...} Change the values of all fields
% for the given channel number, mimimally {num label theta radius}.
% Ex: 'changechan' {12 'PXz' -90 0.30}
% 'changefield' - {number field value} Change field value for channel number number.
% Ex: {34 'theta' 320.4}.
% 'insert' - {number label theta radius X Y Z sph_theta sph_phi sph_radius }
% Insert new channel and specified values before the current channel
% number. If the number of values is less than 10, remaining
% fields will be 0. (Previously, this parameter was termed 'add').
% 'append' - {num label theta radius X Y Z sph_theta sph_phi sph_radius }
% same as 'insert' (above) but insert the the new channel after
% the current channel number.
% 'delete' - [int_vector] Vector of channel numbers to delete.
% 'forcelocs' - [cell] call forcelocs() to force a particular channel to be at a
% particular location on the head sphere; rotate other channels
% accordingly.
% 'skirt' - Topographical polar skirt factor (see >> help topoplot)
% 'shrink' - Topographical polar shrink factor (see >> help topoplot)
% 'load' - [filename|{filename, 'key', 'val'}] Load channel location file
% optional arguments (such as file format) to the function
% readlocs() can be specified if the input is a cell array.
% 'save' - 'filename' Save text file with channel info.
% 'eval' - [string] evaluate string ('chantmp' is the name of the channel
% location structure).
% 'headrad' - [float] change head radius.
% 'lookup' - [string] look-up channel numbers for standard locations in the
% channel location file given as input.
%
% Outputs:
% EEG - new EEGLAB dataset with updated channel location structures
% EEG.chanlocs, EEG.urchanlocs, EEG.chaninfo
% chanlocs - updated channel location structure
% chaninfo - updated chaninfo structure
% options - structure containing plotting options (equivalent to EEG.chaninfo)
%
% Ex: EEG = pop_chanedit(EEG,'load', { 'dummy.elp' 'elp' }, 'delete', [3 4], ...
% 'convert', { 'xyz->polar' [] -1 1 }, 'save', 'mychans.loc' )
% % Load polhemus file, delete two channels, convert to polar (see
% % cart2topo() for arguments) and save into 'mychans.loc'.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 20 April 2002
%
% See also: readlocs()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 15 March 2002, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% hidden parameter
% 'gui' - [figure value], allow to process the same dialog box several times
function [chansout, chaninfo, urchans, com] = pop_chanedit(chans, orichaninfo, varargin);
urchans = [];
com ='';
if nargin < 1
help pop_chanedit;
return;
end;
chansout = chans;
chaninfo = [];
fig = [];
if nargin < 2
orichaninfo = [];
end;
if isempty(chans) || ~isnumeric(chans)
% in case an EEG structure was given as input
% -------------------------------------------
if isfield(chans, 'chanlocs')
dataset_input = 1;
EEG = chans;
chans = EEG(1).chanlocs;
nchansori = EEG.nbchan;
if isfield(EEG, 'chaninfo')
chaninfo = EEG(1).chaninfo;
else chaninfo = [];
end;
if isfield(EEG, 'urchanlocs')
urchans = EEG(1).urchanlocs;
end;
else
nchansori = 0;
dataset_input = 0;
chaninfo = orichaninfo;
end;
% dealing with additional parameters
% ----------------------------------
if nargin > 1 && ~isstr(orichaninfo), % nothing
if nargin > 2
if ~isstr(varargin{1})
urchans = varargin{1};
varargin = varargin(2:end);
end;
end;
elseif nargin > 1 && ~isempty(orichaninfo) && isstr(orichaninfo)
varargin = { orichaninfo varargin{:} };
if isequal(orichaninfo, chaninfo)
chaninfo = [];
end;
orichaninfo = [];
end;
% insert "no data channels" in channel structure
% ----------------------------------------------
nbchan = length(chans);
[tmp chaninfo chans] = eeg_checkchanlocs(chans, chaninfo);
if isfield(chaninfo, 'shrink') && ~isempty(chaninfo.shrink)
icadefs;
if SHRINKWARNING
warndlg2( [ 'You are currently shrinking channel locations for display.' 10 ...
'A new option (more anatomically correct) is to plot channels' 10 ...
'outside head limits so the shrink option has been disabled.' 10 ...
'(Edit the icadefs file to disable this message)' ], 'Shrink factor warning');
end;
end;
oldchaninfo = chaninfo;
end;
if nargin < 3
totaluserdat = {};
% lookup channel locations if necessary
% -------------------------------------
if ~all(cellfun('isempty', {chans.labels})) && all(cellfun('isempty', {chans.theta}))
[chans chaninfo urchans com] = pop_chanedit(chans, chaninfo, 'lookupgui', []);
for index = 1:length(chans)
chans(index).ref = '';
chans(index).datachan = 1;
end;
if ~isempty(com)
totaluserdat = com;
%[chans chaninfo urchans com] = pop_chanedit(chans, chaninfo, com{:});
end;
end;
commentfields = { 'Channel label ("label")', ...
'Polar angle ("theta")', 'Polar radius ("radius")', ...
'Cartesian X ("X")', ...
'Cartesian Y ("Y")', ...
'Cartesian Z ("Z")', ...
'Spherical horiz. angle ("sph_theta")', ...
'Spherical azimuth angle ("sph_phi")', ...
'Spherical radius ("sph_radius")' ...
'Channel type' 'Reference' ...
'Index in backup ''urchanlocs'' structure' ...
'Channel in data array (set=yes)' };
% add field values
% ----------------
geometry = { 1 };
tmpstr = sprintf('Channel information ("field_name"):');
uilist = { { 'Style', 'text', 'string', tmpstr, 'fontweight', 'bold' } };
uiconvert = { ...
{ 'Style', 'pushbutton', 'string', 'Opt. head center', 'callback', 'pop_chanedit(gcbf, [], ''chancenter'', []);' } ...
{ 'Style', 'pushbutton', 'string', 'Rotate axis' , 'callback', 'pop_chanedit(gcbf, [], ''forcelocs'', []);' } ...
{ 'Style', 'pushbutton', 'string', 'Transform axes' , 'callback', 'pop_chanedit(gcbf, [], ''transform'', []);' } ...
{ }, ...
{ 'Style', 'pushbutton', 'string', 'xyz -> polar & sph.', 'callback', 'pop_chanedit(gcbf, [], ''convert'', {''cart2all''});' }, ...
{ 'Style', 'pushbutton', 'string', 'sph. -> polar & xyz', 'callback', 'pop_chanedit(gcbf, [], ''convert'', {''sph2all'' });' }, ...
{ 'Style', 'pushbutton', 'string', 'polar -> sph. & xyz', 'callback', 'pop_chanedit(gcbf, [], ''convert'', {''topo2all''});' }, ...
{ }, ...
{ 'Style', 'pushbutton', 'string', 'Set head radius', 'callback', 'pop_chanedit(gcbf, [], ''headrad'', []);' } ...
{ 'Style', 'pushbutton', 'string', 'Set channel types', 'callback', 'pop_chanedit(gcbf, [], ''settype'', []);' } ...
{ 'Style', 'pushbutton', 'string', 'Set reference', 'callback', 'pop_chanedit(gcbf, [], ''setref'' , []);' } ...
{ } { } };
% create text and edit for each field
% -----------------------------------
allfields = { 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' 'sph_radius' 'type' 'ref' 'urchan' 'datachan' };
for index = 1:length(allfields)-1
cbfield = [ 'valnumtmp = str2num(get(findobj(gcbf, ''tag'', ''chaneditnumval''), ''string''));' ...
'pop_chanedit(gcbf, [], ''changefield'', { valnumtmp ''' allfields{index} ''' get(gcbo, ''string'') });' ...
'clear valnumtmp;' ];
geometry = { geometry{:} [1.5 1 0.2 1] };
uilist = { uilist{:}, ...
{ 'Style', 'text', 'string', commentfields{index} }, ...
{ 'Style', 'edit', 'tag', [ 'chanedit' allfields{index} ], 'string', ...
num2str(getfield(chans,{1}, allfields{index})), 'horizontalalignment', 'center', 'callback', cbfield } ...
{ } uiconvert{index} };
end;
% special checkbox for chandata field
% -----------------------------------
geometry = { geometry{:} [2 0.35 0.5 1] };
cbfield = [ 'valnumtmp = str2num(get(findobj(gcbf, ''tag'', ''chaneditnumval''), ''string''));' ...
'pop_chanedit(gcbf, [], ''changefield'', { valnumtmp ''' allfields{end} ''' get(gcbo, ''value'') });' ...
'clear valnumtmp;' ];
uilist = { uilist{:}, ...
{ 'Style', 'text', 'string', commentfields{end} }, ...
{ 'Style', 'checkbox', 'tag', [ 'chanedit' allfields{end}], 'string', '' 'value', 1 'callback', cbfield } { } uiconvert{end} };
% add buttons
% -----------
geometry = { geometry{:} [1] [1.15 0.5 0.6 1.9 0.4 0.4 1.15] [1.15 0.7 0.7 1 0.7 0.7 1.15] };
cb_del = [ 'valnum = str2num(char(get(findobj(gcbf,''tag'', ''chaneditnumval''), ''string'')));' ...
'pop_chanedit(gcbf, [], ''deletegui'', valnum);' ];
cb_insert = [ 'valnum = str2num(char(get(findobj(gcbf,''tag'', ''chaneditnumval''), ''string'')));' ...
'pop_chanedit(gcbf, [], ''insert'', valnum);' ];
cb_append = [ 'valnum = str2num(char(get(findobj(gcbf,''tag'', ''chaneditnumval''), ''string'')));' ...
'pop_chanedit(gcbf, [], ''append'', valnum);' ];
uilist = { uilist{:}, ...
{ }, ...
{ 'Style', 'pushbutton', 'string', 'Delete chan', 'callback', cb_del }, ...
{ },{ }, ...
{ 'Style', 'text' , 'string', ['Channel number (of ' int2str(length(chans)) ')'], ...
'fontweight', 'bold', 'tag', 'chaneditscantitle' }, { },{ },{ }, ...
{ 'Style', 'pushbutton', 'string', 'Insert chan', 'callback', cb_insert } ...
{ 'Style', 'pushbutton', 'string', '<<', 'callback', [ 'pop_chanedit(gcbf, [], ''movecursor'', -10);' ] } ...
{ 'Style', 'pushbutton', 'string', '<', 'callback', [ 'pop_chanedit(gcbf, [], ''movecursor'', -1);' ] } ...
{ 'Style', 'edit' , 'string', '1', 'tag', 'chaneditnumval', 'callback', [ 'pop_chanedit(gcbf, []);' ] } ...
{ 'Style', 'pushbutton', 'string', '>', 'callback', [ 'pop_chanedit(gcbf, [], ''movecursor'', 1);' ] } ...
{ 'Style', 'pushbutton', 'string', '>>', 'callback', [ 'pop_chanedit(gcbf, [], ''movecursor'', 10);' ] } ...
{ 'Style', 'pushbutton', 'string', 'Append chan', 'callback', cb_append }, ...
};
% add sorting options
% -------------------
noseparam = strmatch(upper(chaninfo.nosedir), { '+X' '-X' '+Y' '-Y' });
if isempty(noseparam), error('Wrong value for nose direction'); end;
geometry = { geometry{:} [1] [0.9 1.3 0.6 1.1 0.9] [1] [1 1 1 1 1]};
uilist = { uilist{:},...
{ } ...
{ 'Style', 'pushbutton', 'string', 'Plot 2-D', 'callback', 'pop_chanedit(gcbf, [], ''plot2d'', []);' },...
{ 'Style', 'text', 'string', 'Plot radius (0.2-1, []=auto)'} ...
{ 'Style', 'edit', 'string', chaninfo.plotrad, 'tag', 'plotrad' 'callback' 'pop_chanedit(gcbf, [], ''plotrad'', []);' } ...
{ 'Style', 'popupmenu', 'string', 'Nose along +X|Nose along -X|Nose along +Y|Nose along -Y', ...
'tag' 'nosedir' 'value',noseparam, 'callback' 'pop_chanedit(gcbf,[],''nosedir'',[]);' 'listboxtop' noseparam } ...
{ 'Style', 'pushbutton', 'string', 'Plot 3-D (xyz)', 'callback', 'pop_chanedit(gcbf, [], ''plot3d'', []);' } ...
{}, ...
{ 'Style', 'pushbutton', 'string', 'Read locations', 'callback', 'pop_chanedit(gcbf,[],''load'',[]);' }, ...
{ 'Style', 'pushbutton', 'string', 'Read locs help', 'callback', 'pophelp(''readlocs.m'');' }, ...
{ 'Style', 'pushbutton', 'string', 'Look up locs', 'callback', 'pop_chanedit(gcbf,[], ''lookupgui'', []);' }, ...
{ 'Style', 'pushbutton', 'string', 'Save (as .ced)', 'callback', 'pop_chanedit(gcbf,[], ''save'',[]);' } ...
{ 'Style', 'pushbutton', 'string', 'Save (other types)' 'callback', 'pop_chanedit(gcbf,[], ''saveothers'',[]);' } ...
};
% evaluation of command below is required to center text (if
% declared a text instead of edit, the uicontrol is not centered)
comeval = [ 'set(findobj( ''tag'', ''chanediturchan''), ''style'', ''text'', ''backgroundcolor'', [.66 .76 1] );' ...
'set(findobj( ''tag'', ''chaneditref''), ''style'', ''text'', ''backgroundcolor'', [.66 .76 1] );' ...
'set(findobj( ''tag'', ''ok''), ''callback'', ''pop_chanedit(gcbf, [], ''''return'''', []);'')' ];
userdata.chans = chans;
userdata.nchansori = nchansori;
userdata.chaninfo = chaninfo;
userdata.commands = totaluserdat;
[results userdata returnmode] = inputgui( 'geometry', geometry, 'uilist', uilist, 'helpcom', ...
'pophelp(''pop_chanedit'');', 'title', 'Edit channel info -- pop_chanedit()', ...
'userdata', userdata, 'eval' , comeval );
if length(results) == 0,
com = '';
if dataset_input, chansout = EEG; end;
return;
end;
% transfer events back from global workspace
chans = userdata.chans;
chaninfo = userdata.chaninfo;
if ~isempty(userdata.commands)
com = sprintf('%s=pop_chanedit(%s, %s);', inputname(1), inputname(1), vararg2str(userdata.commands));
end;
else
% call from command line or from a figure
% ---------------------------------------
currentpos = 0;
if isnumeric(chans)
fig = chans;
userdata = get(fig, 'userdata');
chans = userdata.chans;
nchansori = userdata.nchansori;
chaninfo = userdata.chaninfo;
currentpos = str2num(get(findobj(fig, 'tag', 'chaneditnumval'), 'string'));
end;
args = varargin;
% no interactive inputs
% scan all the fields of g
% ------------------------
for curfield = 1:2:length(args)
switch lower(args{curfield})
case 'return'
[tmpchans] = eeg_checkchanlocs(chans);
if nchansori ~= 0 & nchansori ~= length(tmpchans)
if ~popask(strvcat(['The number of data channels (' int2str(length(tmpchans)) ') not including fiducials does not'], ...
['correspond to the initial number of channels (' int2str(nchansori) '), so for consistency purposes'], ...
'new channel information will be ignored if this function was called from EEGLAB', ...
'If you have added a reference channel manually, check the "Data channel" checkbox is off'))
else
set(findobj(fig, 'tag', 'ok'), 'userdata', 'stop');
end;
else
set(findobj(fig, 'tag', 'ok'), 'userdata', 'stop');
end;
args = {};
case 'plot3d', % GUI only
tmpind = find(~cellfun('isempty', { chans.X }));
if ~isempty(tmpind),
plotchans3d([ [ chans(tmpind).X ]' [ chans(tmpind).Y ]' [ chans(tmpind).Z ]'], { chans(tmpind).labels });
else disp('cannot plot: no XYZ coordinates');
end;
args = {};
case 'plot2d', % GUI only
plotrad = str2num(get(findobj(fig, 'tag', 'plotrad'), 'string'));
figure; topoplot([],chans, 'style', 'blank', 'drawaxis', 'on', 'electrodes', ...
'labelpoint', 'plotrad', plotrad, 'chaninfo', chaninfo);
args = {};
case 'movecursor', % GUI only
currentpos = max(1,min(currentpos+args{curfield+1},length(chans)));
args = {};
case 'plotrad',
if isempty( args{curfield+1} )
args{curfield+1} = str2num(get(findobj(fig, 'tag', 'plotrad'), 'string'));
end;
chaninfo.plotrad = args{curfield+1};
case 'forcelocs',
if ~isempty(fig) % GUI BASED
[ comtmp tmpforce ] = forcelocs(chans);
if ~isempty(tmpforce),
args{curfield+1} = tmpforce{1};
end;
end;
if ~isempty(args{curfield+1})
chans = forcelocs(chans,args{curfield+1});
disp('Convert XYZ coordinates to spherical and polar');
end;
case 'chancenter',
if ~isempty(fig)
[chans newcenter tmpcom] = pop_chancenter(chans);
args{curfield } = 'eval';
args{curfield+1} = tmpcom;
end;
case 'convert',
if iscell(args{curfield+1})
method=args{curfield+1}{1};
extraargs = args{curfield+1}(2:end);
else
method=args{curfield+1};
extraargs = {''};
end;
if ~isempty(fig) & ~strcmp(method, 'chancenter')
tmpButtonName=questdlg2( strvcat('This will modify fields in the channel structure', ...
'Are you sure you want to apply this function ?'), 'Confirmation', 'Cancel', 'Yes','Yes');
if ~strcmpi(tmpButtonName, 'Yes'), return; end;
end;
switch method
case 'chancenter',
if isempty(extraargs)
[X Y Z]=chancenter( [chans.X ]', [ chans.Y ]', [ chans.Z ]',[]);
else
[X Y Z]=chancenter( [chans.X ]', [ chans.Y ]', [ chans.Z ]', extraargs{:});
end;
if isempty(X), return; end;
for index = 1:length(chans)
chans(index).X = X(index);
chans(index).Y = Y(index);
chans(index).Z = Z(index);
end;
disp('Note: automatically convert XYZ coordinates to spherical and polar');
chans = convertlocs(chans, 'cart2all');
otherwise
chans = convertlocs(chans, method, 'verbose', 'on');
end;
case 'settype'
if ~isempty(fig)
args{curfield+1} = inputdlg2({'Channel indices' 'Type (e.g. EEG)' }, ...
'Set channel type', 1, { '' '' }, 'pop_chanedit');
end;
try, tmpchans = args{curfield+1}{1}; tmptype = args{curfield+1}{2};catch, return; end;
if isempty(tmpchans) & isempty(tmptype), return; end;
if isstr(tmpchans)
tmpchans = eval( [ '[' tmpchans ']' ], 'settype: error in channel indices');
end;
if ~isstr(tmptype), tmptype = num2str(tmptype); end;
for index = 1:length(tmpchans)
if tmpchans(index) > 0 & tmpchans(index) <= length(chans)
chans( tmpchans(index) ).type = tmptype;
end;
end;
case 'setref'
if ~isempty(fig)
disp('Note that setting the reference only changes the reference labels');
disp('Use the re-referencing menu to change the reference');
args{curfield+1} = inputdlg2({'Channel indices' 'Reference (e.g. Cz)' }, ...
'Set channel reference', 1, { '' '' }, 'pop_chanedit');
end;
try, tmpchans = args{curfield+1}{1}; tmpref = args{curfield+1}{2};catch, return; end;
if isempty(tmpchans) & isempty(tmpref), return; end;
if isstr(tmpchans)
tmpchans = eval( [ '[' tmpchans ']' ], 'settype: error in channel indices');
end;
if ~isstr(tmpref), tmpref = num2str(tmpref); end;
for index = 1:length(tmpchans)
if tmpchans(index) > 0 & tmpchans(index) <= length(chans)
chans( tmpchans(index) ).ref = tmpref;
end;
end;
case 'transform'
if ~isempty(fig)
args{curfield+1} = inputdlg2({'Enter transform: (Ex: TMP=X; X=-Y; Y=TMP or Y(3) = X(2), etc.' }, ...
'Transform', 1, { '' }, 'pop_chanedit');
end;
try, tmpoper = args{curfield+1}; catch, return; end;
if isempty(deblank(tmpoper)), return; end;
if iscell(tmpoper), tmpoper = tmpoper{1}; end;
tmpoper = [ tmpoper ';' ];
[eloc, labels, theta, radius, indices] = readlocs(chans);
if isempty(findstr(tmpoper, 'chans'))
try,
X = [ chans(indices).X ];
Y = [ chans(indices).Y ];
Z = [ chans(indices).Z ];
sph_theta = [ chans(indices).sph_theta ];
sph_phi = [ chans(indices).sph_phi ];
sph_radius = [ chans(indices).sph_radius ];
eval(tmpoper);
for ind = 1:length(indices)
chans(indices(ind)).X = X(min(length(X),ind));
chans(indices(ind)).Y = Y(min(length(Y),ind));
chans(indices(ind)).Z = Z(min(length(Z),ind));
chans(indices(ind)).theta = theta(min(length(theta),ind));
chans(indices(ind)).radius = radius(min(length(radius),ind));
chans(indices(ind)).sph_theta = sph_theta(min(length(sph_theta),ind));
chans(indices(ind)).sph_phi = sph_phi(min(length(sph_phi),ind));
chans(indices(ind)).sph_radius = sph_radius(min(length(sph_radius),ind));
end;
if ~isempty(findstr(tmpoper, 'X')), chans = convertlocs(chans, 'cart2all'); end;
if ~isempty(findstr(tmpoper, 'Y')), chans = convertlocs(chans, 'cart2all'); end;
if ~isempty(findstr(tmpoper, 'Z')), chans = convertlocs(chans, 'cart2all'); end;
if ~isempty(findstr(tmpoper, 'sph_theta')), chans = convertlocs(chans, 'sph2all');
elseif ~isempty(findstr(tmpoper, 'theta')), chans = convertlocs(chans, 'topo2all'); end;
if ~isempty(findstr(tmpoper, 'sph_phi')), chans = convertlocs(chans, 'sph2all'); end;
if ~isempty(findstr(tmpoper, 'sph_radius')), chans = convertlocs(chans, 'sph2all');
elseif ~isempty(findstr(tmpoper, 'radius')), chans = convertlocs(chans, 'topo2all'); end;
catch, disp('Unknown error when applying transform'); end;
else
eval(tmpoper);
end;
case 'headrad'
if ~isempty(fig) % GUI
tmpres = inputdlg2({'Enter new head radius (same unit as DIPFIT head model):' }, ...
'Head radius', 1, { '' }, 'pop_chanedit');
if ~isempty(tmpres),
args{ curfield+1 } = str2num(tmpres{1});
else return;
end;
end;
if ~isempty( args{ curfield+1 } )
allrad = [ chans.sph_radius ];
if length(unique(allrad)) == 1 % already spherical
chans = pop_chanedit(chans, 'transform', [ 'sph_radius = ' num2str( args{ curfield+1 } ) ';' ]);
else % non-spherical, finding best match
factor = args{ curfield+1 } / mean(allrad);
chans = pop_chanedit(chans, 'transform', [ 'sph_radius = sph_radius*' num2str( factor ) ';' ]);
disp('Warning: electrodes do not lie on a sphere. Sphere model fitting for');
disp(' dipole localization will work but generate many warnings');
end;
chans = convertlocs(chans, 'sph2all');
end;
case 'shrink'
chans(1).shrink = args{ curfield+1 };
case 'plotrad'
chans(1).plotrad = args{ curfield+1 };
case 'deletegui'
chans(args{ curfield+1 })=[];
currentpos = min(length(chans), currentpos);
args{ curfield } = 'delete';
case 'delete'
chans(args{ curfield+1 })=[];
case 'changefield'
tmpargs = args{ curfield+1 };
if length( tmpargs ) < 3
error('pop_chanedit: not enough arguments to change field value');
end;
if ~isempty(strmatch( tmpargs{2}, { 'X' 'Y' 'Z' 'theta' 'radius' 'sph_theta' 'sph_phi' 'sph_radius'}))
if ~isnumeric(tmpargs{3}), tmpargs{3} = str2num(tmpargs{3}); end;
end;
eval([ 'chans(' int2str(tmpargs{1}) ').' tmpargs{2} '=' reformat(tmpargs{3} ) ';' ]);
case { 'insert' 'add' 'append' }
tmpargs = args{ curfield+1 };
allfields = fieldnames(chans);
if isnumeric(tmpargs)
tmpargs2 = cell(1, length(allfields)+1);
tmpargs2{1} = tmpargs;
tmpargs = tmpargs2;
if strcmpi(allfields{end}, 'datachan'), tmpargs{end} = 0; end;
end;
if length( tmpargs ) < length(allfields)+1
error('pop_chanedit: not enough arguments to change all field values');
end;
num = tmpargs{1};
if strcmpi(lower(args{curfield}), 'append'), num=num+1; currentpos = currentpos+1; end;
chans(end+1) = chans(end);
chans(num+1:end) = chans(num:end-1);
for index = 1:length( allfields )
chans = setfield(chans, {num}, allfields{index}, tmpargs{index+1});
end;
if isfield(chans, 'datachan')
if isempty(chans(num).datachan)
chans(num).datachan = 0;
end;
end;
case 'changechan'
tmpargs = args{ curfield+1 };
num = tmpargs{1};
allfields = fieldnames(chans);
if length( tmpargs ) < length(allfields)+1
error('pop_chanedit: not enough arguments to change all field values');
end;
for index = 1:length( allfields )
eval([ 'chans(' int2str(num) ').' allfields{index} '=' reformat(tmpargs{index+1}) ';' ]);
end;
case 'load'
if ~isempty(fig) % GUI
[tmpf tmpp] = uigetfile('*.*', 'Load a channel location file');
drawnow;
if ~isequal(tmpf, 0),
tmpformats = readlocs('getinfos');
tmpformattype = { 'autodetect' tmpformats(1:end-1).type };
tmpformatstr = { 'autodetect' tmpformats(1:end-1).typestring };
tmpformatdesc = { 'Autodetect file format from file extension' tmpformats(1:end-1).description };
%cb_listbox = 'tmpdesc=get(gcbf, ''userdata''); set(findobj(gcbf, ''tag'', ''strdesc''), ''string'', strmultiline([ ''File format: '' tmpdesc{get(gcbo, ''value'')} ], 30, 10)); clear tmpdesc;'' } }, ''pophelp(''''readlocs'''')'',' ...
% 'Read electrode file'', tmpformatdesc, ''normal'', 4);
%txtgui = [ strmultiline([ 'File format: Autodetect file format from file extension'], 20, 10) 10 10 ];
%tmpfmt = inputgui( 'geometry', {[1 1]}, ...
% 'uilist' , { { 'style', 'text', 'string', txtgui 'tag' 'strdesc' }, ...
% { 'style', 'listbox', 'string', strvcat(tmpformatstr) 'callback' '' } }, ...
% 'geomvert', [10], ...
% 'helpcom' , 'pophelp(''readlocs'');');
tmpfmt = inputgui( 'geometry', {[1 1 1] [1]}, ...
'uilist' , { { 'style', 'text', 'string', 'File format:' 'tag' 'strdesc' } {} {}, ...
{ 'style', 'listbox', 'string', strvcat(tmpformatstr) 'callback' '' } }, ...
'geomvert', [1 8], ...
'helpcom' , 'pophelp(''readlocs'');');
if isempty(tmpfmt),
args{ curfield+1 } = [];
else args{ curfield+1 } = { fullfile(tmpp, tmpf) 'filetype' tmpformattype{tmpfmt{1}} };
end;
else args{ curfield+1 } = [];
end;
end;
tmpargs = args{ curfield+1 };
if ~isempty(tmpargs),
if isstr(tmpargs)
[chans] = readlocs(tmpargs);
[tmp tmp2 chans] = eeg_checkchanlocs(chans);
chaninfo = [];
chaninfo.filename = tmpargs;
else
[chans] = readlocs(tmpargs{:});
[tmp tmp2 chans] = eeg_checkchanlocs(chans);
chaninfo = [];
chaninfo.filename = tmpargs{1};
end;
% backup file content etc...
% --------------------------
tmptext = loadtxt( chaninfo.filename, 'delim', [], 'verbose', 'off', 'convert', 'off');
chaninfo.filecontent = strvcat(tmptext{:});
% set urchan structure
% --------------------
urchans = chans;
for index = 1:length(chans)
chans(index).urchan = index;
end;
end;
if ~isfield(chans, 'datachan')
chans(1).datachan = [];
end;
for index = 1:length(chans)
if isempty(chans(index).datachan)
chans(index).datachan = 1;
end;
end;
case 'eval'
tmpargs = args{ curfield+1 };
eval(tmpargs);
case 'saveothers'
com = pop_writelocs(chans);
args{ curfield } = 'eval';
args{ curfield+1 } = com;
case 'save'
if ~isempty(fig)
[tmpf tmpp] = uiputfile('*.ced', 'Save channel locs in EEGLAB .ced format');
drawnow;
args{ curfield+1 } = fullfile(tmpp, tmpf);
end;
tmpargs = args{ curfield+1 };
if isempty(tmpargs), return; end;
fid = fopen(tmpargs, 'w');
if fid ==-1, error('Cannot open file'); end;
allfields = fieldnames(chans);
fields = { 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' 'sph_radius' 'type' };
tmpdiff = setdiff(fields, allfields);
if ~isempty(tmpdiff), error(sprintf('Field "%s" missing in channel location structure', tmpdiff{1})); end;
fprintf(fid, 'Number\t');
for field = 1:length(fields)
fprintf(fid, '%s\t', fields{field});
end;
fprintf(fid, '\n');
for index=1:length(chans)
fprintf(fid, '%d\t', index);
for field = 1:length(fields)
tmpval = getfield(chans, {index}, fields{field});
if isstr(tmpval)
fprintf(fid, '%s\t', tmpval);
else
fprintf(fid, '%3.3g\t', tmpval);
end;
end;
fprintf(fid, '\n');
end;
if isempty(tmpargs), chantmp = readlocs(tmpargs); end;
case 'nosedir'
nosevals = { '+X' '-X' '+Y' '-Y' };
if ~isempty(fig)
tmpval = get(findobj(gcbf, 'tag', 'nosedir'), 'value');
args{ curfield+1 } = nosevals{tmpval};
warndlg2( [ 'Changing the nose direction will force EEGLAB to physically rotate ' 10 ...
'electrodes, so next time you call this interface, nose direction will' 10 ...
'be +X. If your electrodes are currently aligned with a specific' 10 ...
'head model, you will have to rotate them in the model coregistration' 10 ...
'interface to realign them with the model.'], 'My Warn Dialog');
end;
chaninfo.nosedir = args{ curfield+1 };
if isempty(strmatch(chaninfo.nosedir, nosevals))
error('Wrong value for nose direction');
end;
case { 'lookup' 'lookupgui' }
if strcmpi(lower(args{curfield}), 'lookupgui')
standardchans = { 'Fp1' 'Fpz' 'Fp2' 'Nz' 'AF9' 'AF7' 'AF3' 'AFz' 'AF4' 'AF8' 'AF10' 'F9' 'F7' 'F5' ...
'F3' 'F1' 'Fz' 'F2' 'F4' 'F6' 'F8' 'F10' 'FT9' 'FT7' 'FC5' 'FC3' 'FC1' 'FCz' 'FC2' ...
'FC4' 'FC6' 'FT8' 'FT10' 'T9' 'T7' 'C5' 'C3' 'C1' 'Cz' 'C2' 'C4' 'C6' 'T8' 'T10' ...
'TP9' 'TP7' 'CP5' 'CP3' 'CP1' 'CPz' 'CP2' 'CP4' 'CP6' 'TP8' 'TP10' 'P9' 'P7' 'P5' ...
'P3' 'P1' 'Pz' 'P2' 'P4' 'P6' 'P8' 'P10' 'PO9' 'PO7' 'PO3' 'POz' 'PO4' 'PO8' 'PO10' ...
'O1' 'Oz' 'O2' 'O9' 'O10' 'CB1' 'CB2' 'Iz' };
for indexchan = 1:length(chans)
if isempty(chans(indexchan).labels), chans(indexchan).labels = ''; end;
end;
[tmp1 ind1 ind2] = intersect_bc( lower(standardchans), {chans.labels});
if ~isempty(tmp1) | isfield(chans, 'theta')
% finding template location files
% -------------------------------
setmodel = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'tmpval = get(gcbo, ''value'');' ...
'set(findobj(gcbf, ''tag'', ''elec''), ''string'', tmpdat{tmpval});' ...
'clear tmpval tmpdat;' ];
try
EEG = eeg_emptyset; % for dipfitdefs
dipfitdefs;
tmpp = which('eeglab.m');
tmpp = fullfile(fileparts(tmpp), 'functions', 'resources', 'Standard-10-5-Cap385_witheog.elp');
userdatatmp = { template_models(1).chanfile template_models(2).chanfile tmpp };
clear EEG;
catch, userdatatmp = { 'Standard-10-5-Cap385.sfp' 'Standard-10-5-Cap385.sfp' 'Standard-10-5-Cap385_witheog.elp' };
end;
% other commands for help/load
% ----------------------------
comhelp = [ 'warndlg2(strvcat(''The template file depends on the model'',' ...
'''you intend to use for dipole fitting. The default file is fine for'',' ...
'''spherical model.'');' ];
commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
'if filename ~=0,' ...
' set(findobj(''parent'', gcbf, ''tag'', ''elec''), ''string'', [ filepath filename ]);' ...
'end;' ...
'clear filename filepath tagtest;' ];
if ~isfield(chans, 'theta'), message =1;
elseif all(cellfun('isempty', {chans.theta })), message =1;
else message =2;
end;
if message == 1
textcomment = strvcat('Only channel labels are present currently, but some of these labels have known', ...
'positions. Do you want to look up coordinates for these channels using the electrode', ...
'file below? If you have a channel location file for this dataset, press cancel, then', ...
'use button "Read location" in the following gui. If you do not know, just press OK.');
else
textcomment = strvcat('Some channel labels may have known locations.', ...
'Do you want to look up coordinates for these channels using the electrode', ...
'file below? If you do not know, press OK.');
end;
uilist = { { 'style' 'text' 'string' textcomment } ...
{ 'style' 'popupmenu' 'string' [ 'use BESA file for 4-shell dipfit spherical model' ...
'|use MNI coordinate file for BEM dipfit model|Use spherical file with eye channels' ] ...
'callback' setmodel } ...
{ } ...
{ 'style' 'edit' 'string' userdatatmp{1} 'tag' 'elec' } ...
{ 'style' 'pushbutton' 'string' '...' 'callback' commandload } };
res = inputgui( { 1 [1 0.3] [1 0.3] }, uilist, 'pophelp(''pop_chanedit'')', 'Look up channel locations?', userdatatmp, 'normal', [4 1 1] );
if ~isempty(res)
chaninfo.filename = res{2};
args{ curfield } = 'lookup';
args{ curfield+1 } = res{2};
com = args;
else
return;
end;
end;
else
chaninfo.filename = args{ curfield+1 };
end;
if strcmpi(chaninfo.filename, 'standard-10-5-cap385.elp')
dipfitdefs;
chaninfo.filename = template_models(1).chanfile;
elseif strcmpi(chaninfo.filename, 'standard_1005.elc')
dipfitdefs;
chaninfo.filename = template_models(2).chanfile;
end;
tmplocs = readlocs( chaninfo.filename, 'defaultelp', 'BESA' );
for indexchan = 1:length(chans)
if isempty(chans(indexchan).labels), chans(indexchan).labels = ''; end;
end;
[tmp ind1 ind2] = intersect_bc(lower({ tmplocs.labels }), lower({ chans.labels }));
if ~isempty(tmp)
chans = struct('labels', { chans.labels }, 'datachan', { chans.datachan }, 'type', { chans.type });
[ind2 ind3] = sort(ind2);
ind1 = ind1(ind3);
for index = 1:length(ind2)
chans(ind2(index)).theta = tmplocs(ind1(index)).theta;
chans(ind2(index)).radius = tmplocs(ind1(index)).radius;
chans(ind2(index)).X = tmplocs(ind1(index)).X;
chans(ind2(index)).Y = tmplocs(ind1(index)).Y;
chans(ind2(index)).Z = tmplocs(ind1(index)).Z;
chans(ind2(index)).sph_theta = tmplocs(ind1(index)).sph_theta;
chans(ind2(index)).sph_phi = tmplocs(ind1(index)).sph_phi;
chans(ind2(index)).sph_radius = tmplocs(ind1(index)).sph_radius;
end;
tmpdiff = setdiff_bc([1:length(chans)], ind2);
if ~isempty(tmpdiff)
fprintf('Channel lookup: no location for ');
for index = 1:(length(tmpdiff)-1)
fprintf('%s,', chans(tmpdiff(index)).labels);
end;
fprintf('%s\nSend us standard location for your channels at [email protected]\n', ...
chans(tmpdiff(end)).labels);
end;
if ~isfield(chans, 'type'), chans(1).type = []; end;
end;
if ~isempty(findstr(args{ curfield+1 }, 'standard_10')) & ...
~isempty(findstr(args{ curfield+1 }, '.elc'))
chaninfo.nosedir = '+Y';
else
chaninfo.nosedir = '+X';
end;
urchans = chans;
for index = 1:length(chans)
chans(index).urchan = index;
chans(index).ref = '';
end;
end;
end;
end;
% call from a figure
% ------------------
if ~isempty(fig)
userdata.chans = chans;
userdata.chaninfo = chaninfo;
userdata.commands = { userdata.commands{:} args{:} };
set(fig, 'userdata', userdata);
set(findobj(fig, 'tag', 'chaneditnumval'), 'string', num2str(currentpos));
set(findobj(fig, 'tag', 'chaneditscantitle'), 'string', ['Channel number (of ' int2str(length(chans)) ')']);
% update GUI with current channel info
allfields = fieldnames(chans);
if ~isempty(chans)
for index = 1:length(allfields)
obj = findobj(fig, 'tag', [ 'chanedit' allfields{index}]);
if strcmpi(allfields{index}, 'datachan')
set(obj, 'value', getfield(chans(currentpos), allfields{index}));
else
tmpval = getfield(chans(currentpos), allfields{index});
if isstr(tmpval) && strcmpi(tmpval, '[]'), tmpval = ''; end;
set(obj, 'string', num2str(tmpval));
end;
end;
else
for index = 1:length(allfields)
obj = findobj(fig, 'tag', [ 'chanedit' allfields{index}]);
if strcmpi(allfields{index}, 'datachan')
set(obj, 'value', 0);
else
set(obj, 'string', '');
end;
end;
end;
else
[chans chaninfo] = eeg_checkchanlocs(chans, chaninfo);
if dataset_input,
if nchansori == length(chans)
for index = 1:length(EEG)
EEG(index).chanlocs = chans;
EEG(index).chaninfo = chaninfo;
end;
EEG = eeg_checkset(EEG); % for channel orientation
else
disp('Wrong channel structure size, changes ignored');
end;
chansout = EEG;
else chansout = chans;
end;
end;
return;
% format the output field
% -----------------------
function strval = reformat( val )
if isnumeric(val) & isempty(val), val = '[]'; end;
if isstr(val), strval = [ '''' val '''' ];
else strval = num2str(val);
end;
% extract text using tokens (not used)
% ------------------------------------
function txt = inserttxt( txt, tokins, tokfind);
locfind = findstr(txt, tokfind);
for index = length(locfind):-1:1
txt = [txt(1:locfind(index)-1) tokins txt(locfind(index):end)];
end;
% ask for confirmation
% --------------------
function num = popask( text )
ButtonName=questdlg2( text, ...
'Confirmation', 'Cancel', 'Yes','Yes');
switch lower(ButtonName),
case 'cancel', num = 0;
case 'yes', num = 1;
end;
|
github
|
lcnbeapp/beapp-master
|
eeg_getdatact.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/eeg_getdatact.m
| 12,037 |
utf_8
|
bc4bb0dfeb0f9183cb320544ba36fbdd
|
% eeg_getdatact() - get EEG data from a specified dataset or
% component activity
%
% Usage:
% >> signal = eeg_getdatact( EEG );
% >> signal = eeg_getdatact( EEG, 'key', 'val');
%
% Inputs:
% EEG - Input dataset
%
% Optional input:
% 'channel' - [integer array] read only specific channels.
% Default is to read all data channels.
% 'component' - [integer array] read only specific components
% 'projchan' - [integer or cell array] channel(s) onto which the component
% should be projected.
% 'rmcomps' - [integer array] remove selected components from data
% channels. This is only to be used with channel data not
% when selecting components.
% 'trialindices' - [integer array] only read specific trials. Default is
% to read all trials.
% 'samples' - [integer array] only read specific samples. Default is
% to read all samples.
% 'reshape' - ['2d'|'3d'] reshape data. Default is '3d' when possible.
% 'verbose' - ['on'|'off'] verbose mode. Default is 'on'.
%
% Outputs:
% signal - EEG data or component activity
%
% Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2008-
%
% See also: eeg_checkset()
% Copyright (C) 15 Feb 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [data boundaries] = eeg_getdatact( EEG, varargin);
data = [];
if nargin < 1
help eeg_getdatact;
return;
end;
% reading data from several datasets and concatening it
% -----------------------------------------------------
if iscell(EEG) || (~isstr(EEG) && length(EEG) > 1)
% decode some arguments
% ---------------------
trials = cell(1,length(EEG));
rmcomps = cell(1,length(EEG));
for iArg = length(varargin)-1:-2:1
if strcmpi(varargin{iArg}, 'trialindices')
trials = varargin{iArg+1};
varargin(iArg:iArg+1) = [];
elseif strcmpi(varargin{iArg}, 'rmcomps')
rmcomps = varargin{iArg+1};
varargin(iArg:iArg+1) = [];
end;
end;
if isnumeric(rmcomps), rmtmp = rmcomps; rmcomps = cell(1,length(EEG)); rmcomps(:) = { rmtmp }; end;
% concatenate datasets
% --------------------
data = [];
boundaries = [];
for dat = 1:length(EEG)
if iscell(EEG)
[tmpdata datboundaries] = eeg_getdatact(EEG{dat}, 'trialindices', trials{dat}, 'rmcomps', rmcomps{dat}, varargin{:} );
else [tmpdata datboundaries] = eeg_getdatact(EEG(dat), 'trialindices', trials{dat}, 'rmcomps', rmcomps{dat}, varargin{:} );
end;
if isempty(data),
data = tmpdata;
boundaries = datboundaries;
else
if all([ EEG.trials ] == 1) % continuous data
if size(data,1) ~= size(tmpdata,1), error('Datasets to be concatenated do not have the same number of channels'); end;
% adding boundaries
if ~isempty(datboundaries)
boundaries = [boundaries datboundaries size(data,2)];
else
boundaries = [boundaries size(data,2)];
end;
data(:,end+1:end+size(tmpdata,2)) = tmpdata; % concatenating trials
else
if size(data,1) ~= size(tmpdata,1), error('Datasets to be concatenated do not have the same number of channels'); end;
if size(data,2) ~= size(tmpdata,2), error('Datasets to be concatenated do not have the same number of time points'); end;
data(:,:,end+1:end+size(tmpdata,3)) = tmpdata; % concatenating trials
end;
end;
end;
return;
end;
% if string load dataset
% ----------------------
if isstr(EEG)
EEG = pop_loadset('filename', EEG, 'loadmode', 'info');
end;
opt = finputcheck(varargin, { ...
'channel' 'integer' {} [];
'verbose' 'string' { 'on','off' } 'on';
'reshape' 'string' { '2d','3d' } '3d';
'projchan' {'integer','cell' } { {} {} } [];
'component' 'integer' {} [];
'samples' 'integer' {} [];
'interp' 'struct' { } struct([]);
'trialindices' {'integer','cell'} { {} {} } [];
'rmcomps' {'integer','cell'} { {} {} } [] }, 'eeg_getdatact');
if isstr(opt), error(opt); end;
channelNotDefined = 0;
if isempty(opt.channel), opt.channel = [1:EEG.nbchan]; channelNotDefined = 1;
elseif isequal(opt.channel, [1:EEG.nbchan]) && ~isempty(opt.interp) channelNotDefined = 1;
end;
if isempty(opt.trialindices), opt.trialindices = [1:EEG.trials]; end;
if iscell( opt.trialindices), opt.trialindices = opt.trialindices{1}; end;
if iscell(opt.rmcomps ), opt.rmcomps = opt.rmcomps{1}; end;
if (~isempty(opt.rmcomps) | ~isempty(opt.component)) & isempty(EEG.icaweights)
error('No ICA weight in dataset');
end;
if strcmpi(EEG.data, 'in set file')
EEG = pop_loadset('filename', EEG.filename, 'filepath', EEG.filepath);
end;
% get data boundaries if continuous data
% --------------------------------------
boundaries = [];
if nargout > 1 && EEG.trials == 1 && ~isempty(EEG.event) && isfield(EEG.event, 'type') && isstr(EEG.event(1).type)
if ~isempty(opt.samples)
disp('WARNING: eeg_getdatact.m, boundaries are not accurate when selecting data samples');
end;
tmpevent = EEG.event;
tmpbound = strmatch('boundary', lower({ tmpevent.type }));
if ~isempty(tmpbound)
boundaries = [tmpevent(tmpbound).latency ]-0.5;
end;
end;
% getting channel or component activation
% ---------------------------------------
filename = fullfile(EEG.filepath, [ EEG.filename(1:end-4) '.icaact' ] );
if ~isempty(opt.component) & ~isempty(EEG.icaact)
data = EEG.icaact(opt.component,:,:);
elseif ~isempty(opt.component) & exist(filename)
% reading ICA file
% ----------------
data = repmat(single(0), [ length(opt.component) EEG.pnts EEG.trials ]);
fid = fopen( filename, 'r', 'ieee-le'); %little endian (see also pop_saveset)
if fid == -1, error( ['file ' filename ' could not be open' ]); end;
for ind = 1:length(opt.component)
fseek(fid, (opt.component(ind)-1)*EEG.pnts*EEG.trials*4, -1);
data(ind,:) = fread(fid, [EEG.trials*EEG.pnts 1], 'float32')';
end;
fclose(fid);
elseif ~isempty(opt.component)
if isempty(EEG.icaact)
data = eeg_getdatact( EEG );
data = (EEG.icaweights(opt.component,:)*EEG.icasphere)*data(EEG.icachansind,:);
else
data = EEG.icaact(opt.component,:,:);
end;
else
if isnumeric(EEG.data) % channel
data = EEG.data;
else % channel but no data loaded
filename = fullfile(EEG.filepath, EEG.data);
fid = fopen( filename, 'r', 'ieee-le'); %little endian (see also pop_saveset)
if fid == -1
error( ['file ' filename ' not found. If you have renamed/moved' 10 ...
'the .set file, you must also rename/move the associated data file.' ]);
else
if strcmpi(opt.verbose, 'on')
fprintf('Reading float file ''%s''...\n', filename);
end;
end;
% old format = .fdt; new format = .dat (transposed)
% -------------------------------------------------
datformat = 0;
if length(filename) > 3
if strcmpi(filename(end-2:end), 'dat')
datformat = 1;
end;
end;
EEG.datfile = EEG.data;
% reading data file
% -----------------
eeglab_options;
if length(opt.channel) == EEG.nbchan && option_memmapdata
fclose(fid);
data = mmo(filename, [EEG.nbchan EEG.pnts EEG.trials], false);
%data = memmapdata(filename, [EEG.nbchan EEG.pnts EEG.trials]);
else
if datformat
if length(opt.channel) == EEG.nbchan || ~isempty(opt.interp)
data = fread(fid, [EEG.trials*EEG.pnts EEG.nbchan], 'float32')';
else
data = repmat(single(0), [ length(opt.channel) EEG.pnts EEG.trials ]);
for ind = 1:length(opt.channel)
fseek(fid, (opt.channel(ind)-1)*EEG.pnts*EEG.trials*4, -1);
data(ind,:) = fread(fid, [EEG.trials*EEG.pnts 1], 'float32')';
end;
opt.channel = [1:size(data,1)];
end;
else
data = fread(fid, [EEG.nbchan Inf], 'float32');
end;
fclose(fid);
end;
end;
% subracting components from data
% -------------------------------
if ~isempty(opt.rmcomps)
if strcmpi(opt.verbose, 'on')
fprintf('Removing %d artifactual components\n', length(opt.rmcomps));
end;
rmcomps = eeg_getdatact( EEG, 'component', opt.rmcomps); % loaded from file
rmchan = [];
rmchanica = [];
for index = 1:length(opt.channel)
tmpicaind = find(opt.channel(index) == EEG.icachansind);
if ~isempty(tmpicaind)
rmchan = [ rmchan index ];
rmchanica = [ rmchanica tmpicaind ];
end;
end;
data(rmchan,:) = data(rmchan,:) - EEG.icawinv(rmchanica,opt.rmcomps)*rmcomps(:,:);
%EEG = eeg_checkset(EEG, 'loaddata');
%EEG = pop_subcomp(EEG, opt.rmcomps);
%data = EEG.data(opt.channel,:,:);
%if strcmpi(EEG.subject, 'julien') & strcmpi(EEG.condition, 'oddball') & strcmpi(EEG.group, 'after')
% jjjjf
%end;
end;
if ~isempty(opt.interp)
EEG.data = data;
EEG.event = [];
EEG.epoch = [];
EEG = eeg_interp(EEG, opt.interp, 'spherical');
data = EEG.data;
if channelNotDefined, opt.channel = [1:EEG.nbchan]; end;
end;
if ~isequal(opt.channel, [1:EEG.nbchan])
data = data(intersect(opt.channel,[1:EEG.nbchan]),:,:);
end;
end;
% projecting components on data channels
% --------------------------------------
if ~isempty(opt.projchan)
if iscell(opt.projchan)
opt.projchan = std_chaninds(EEG, opt.projchan);
end;
finalChanInds = [];
for iChan = 1:length(opt.projchan)
tmpInd = find(EEG.icachansind == opt.projchan(iChan));
if isempty(tmpInd)
error(sprintf('Warning: can not backproject component on channel %d (not used for ICA)\n', opt.projchan(iChan)));
end;
finalChanInds = [ finalChanInds tmpInd ];
end;
data = EEG.icawinv(finalChanInds, opt.component)*data(:,:);
end;
if size(data,2)*size(data,3) ~= EEG.pnts*EEG.trials
disp('WARNING: The file size on disk does not correspond to the dataset, file has been truncated');
end;
try,
if EEG.trials == 1, EEG.pnts = size(data,2); end;
if strcmpi(opt.reshape, '3d')
data = reshape(data, size(data,1), EEG.pnts, EEG.trials);
else data = reshape(data, size(data,1), EEG.pnts*EEG.trials);
end;
catch
error('The file size on disk does not correspond to the dataset information.');
end;
% select trials
% -------------
if length(opt.trialindices) ~= EEG.trials
data = data(:,:,opt.trialindices);
end;
if ~isempty(opt.samples)
data = data(:,opt.samples,:);
end;
|
github
|
lcnbeapp/beapp-master
|
questdlg2.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/questdlg2.m
| 3,133 |
utf_8
|
d94e219e87da50c5af28fe1007906abc
|
% questdlg2() - questdlg function clone with coloring and help for
% eeglab().
%
% Usage: same as questdlg()
%
% Warning:
% Case of button text and result might be changed by the function
%
% Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 11 August 2002
%
% See also: inputdlg2(), errordlg2(), supergui(), inputgui()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [result] = questdlg2(Prompt,Title,varargin);
result = '';
if nargin < 2
help questdlg2;
return;
end;
if isempty(varargin)
varargin = { 'Yes' 'No' 'Cancel' 'Yes' };
end;
result = varargin{end};
if Prompt(end) == 10, Prompt(end) = []; end;
if Prompt(end) == 10, Prompt(end) = []; end;
if Prompt(end) == 10, Prompt(end) = []; end;
if Prompt(end) == 10, Prompt(end) = []; end;
fig = figure('visible', 'off');
set(gcf, 'name', Title);
listui = {};
geometry = {};
if ~isempty(find(Prompt == 10))
indlines = find(Prompt == 10);
if indlines(1) ~= 1, indlines = [ 0 indlines ]; end;
if indlines(end) ~= length(Prompt), indlines = [ indlines length(Prompt)+1 ]; end;
for index = 1:length(indlines)-1
geometry{index} = [1];
listui{index} = { 'Style', 'text', 'string' Prompt(indlines(index)+1:indlines(index+1)-1) };
end;
else
for index = 1:size(Prompt,1)
geometry{index} = [1];
listui{index} = { 'Style', 'text', 'string' Prompt(index,:) };
end;
end;
listui{end+1} = {};
geometry = { geometry{:} 1 ones(1,length(varargin)-1) };
for index = 1:length(varargin)-1 % ignoring default val
listui = {listui{:} { 'width',80,'align','center','Style', 'pushbutton', 'string', varargin{index}, 'callback', ['set(gcbf, ''userdata'', ''' varargin{index} ''');'] } };
if strcmp(varargin{index}, varargin{end})
listui{end}{end+1} = 'fontweight';
listui{end}{end+1} = 'bold';
end;
end;
%cr = length(find(Prompt == char(10)))+1;
%if cr == 1
% cr = size(Prompt,1);
%end;
%cr = cr^(7/);
%if cr >= 8, cr = cr-1; end;
%if cr >= 4, cr = cr-1; end;
%[tmp tmp2 allobj] = supergui( 'fig', fig, 'geomhoriz', geometry, 'geomvert', [cr 1 1], 'uilist', listui, ...
[tmp tmp2 allobj] = supergui( 'fig', fig, 'geomhoriz', geometry, 'uilist', listui, ...
'borders', [0.02 0.015 0.08 0.06], 'spacing', [0 0], 'horizontalalignment', 'left', 'adjustbuttonwidth', 'on' );
waitfor( fig, 'userdata');
try,
result = get(fig, 'userdata');
close(fig);
drawnow;
end;
|
github
|
lcnbeapp/beapp-master
|
eegplot_readkey.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/eegplot_readkey.m
| 231 |
utf_8
|
a65a871257ff3e64f58f29ff2c190071
|
% eegplot helper function to read key strokes
function eegplot_readkey(src,evnt)
if strcmp(evnt.Key, 'rightarrow')==1
eegplot('drawp',4);
elseif strcmp(evnt.Key, 'leftarrow')==1
eegplot('drawp',1);
end
|
github
|
lcnbeapp/beapp-master
|
parsetxt.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/parsetxt.m
| 1,595 |
utf_8
|
daf4054768bfdb3e9112cbb24966ca21
|
% parsetxt() - parse text input into cell array
%
% Usage: >> cellarray = parsetxt( txt, delims );
%
% Inputs:
% txt - input text
% delims - optional char array of delimiters (default: [' ' ',' 9]);
%
% Note: commas, and simple quotes are ignored
%
% Author: Arnaud Delorme, CNL / Salk Institute, 18 April 2002
% Copyright (C) 18 April 2002 Arnaud Delorme, SCCN/INC/UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function cellarray = parsetxt(txt, delims);
if nargin < 1
help parsetxt;
return;
end;
if nargin < 2
delims = [' ' ',' 9 '"' '''' ];
end;
cellarray = {};
tmptxt = '';
for index =1:length(txt)
if ~isempty(findstr(txt(index), delims))
if ~isempty(tmptxt), cellarray = { cellarray{:}, tmptxt }; end;
tmptxt = '';
else
tmptxt = [ tmptxt txt(index) ];
end;
end;
if ~isempty(tmptxt)
cellarray = { cellarray{:}, tmptxt };
end;
return;
|
github
|
lcnbeapp/beapp-master
|
eeg_checkset.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/eeg_checkset.m
| 66,951 |
utf_8
|
3c84836557d3b6105331ba2977702cc0
|
% eeg_checkset() - check the consistency of the fields of an EEG dataset
% Also: See EEG dataset structure field descriptions below.
%
% Usage: >> [EEGOUT,changes] = eeg_checkset(EEG); % perform all checks
% except 'makeur'
% >> [EEGOUT,changes] = eeg_checkset(EEG, 'keyword'); % perform 'keyword' check(s)
%
% Inputs:
% EEG - EEGLAB dataset structure or (ALLEEG) array of EEG structures
%
% Optional keywords:
% 'icaconsist' - if EEG contains several datasets, check whether they have
% the same ICA decomposition
% 'epochconsist' - if EEG contains several datasets, check whether they have
% identical epoch lengths and time limits.
% 'chanconsist' - if EEG contains several datasets, check whether they have
% the same number of channela and channel labels.
% 'data' - check whether EEG contains data (EEG.data)
% 'loaddata' - load data array (if necessary)
% 'savedata' - save data array (if necessary - see EEG.saved below)
% 'contdata' - check whether EEG contains continuous data
% 'epoch' - check whether EEG contains epoched or continuous data
% 'ica' - check whether EEG contains an ICA decomposition
% 'besa' - check whether EEG contains component dipole locations
% 'event' - check whether EEG contains an event array
% 'makeur' - remake the EEG.urevent structure
% 'checkur' - check whether the EEG.urevent structure is consistent
% with the EEG.event structure
% 'chanlocsize' - check the EEG.chanlocs structure length; show warning if
% necessary.
% 'chanlocs_homogeneous' - check whether EEG contains consistent channel
% information; if not, correct it.
% 'eventconsistency' - check whether EEG.event information are consistent;
% rebuild event* subfields of the 'EEG.epoch' structure
% (can be time consuming).
% Outputs:
% EEGOUT - output EEGLAB dataset or dataset array
% changes - change code: 'no' = no changes; 'yes' = the EEG
% structure was modified
%
% ===========================================================
% The structure of an EEG dataset under EEGLAB (as of v5.03):
%
% Basic dataset information:
% EEG.setname - descriptive name|title for the dataset
% EEG.filename - filename of the dataset file on disk
% EEG.filepath - filepath (directory/folder) of the dataset file(s)
% EEG.trials - number of epochs (or trials) in the dataset.
% If data are continuous, this number is 1.
% EEG.pnts - number of time points (or data frames) per trial (epoch).
% If data are continuous (trials=1), the total number
% of time points (frames) in the dataset
% EEG.nbchan - number of channels
% EEG.srate - data sampling rate (in Hz)
% EEG.xmin - epoch start latency|time (in sec. relative to the
% time-locking event at time 0)
% EEG.xmax - epoch end latency|time (in seconds)
% EEG.times - vector of latencies|times in seconds (one per time point)
% EEG.ref - ['common'|'averef'|integer] reference channel type or number
% EEG.history - cell array of ascii pop-window commands that created
% or modified the dataset
% EEG.comments - comments about the nature of the dataset (edit this via
% menu selection Edit > About this dataset)
% EEG.etc - miscellaneous (technical or temporary) dataset information
% EEG.saved - ['yes'|'no'] 'no' flags need to save dataset changes before exit
%
% The data:
% EEG.data - two-dimensional continuous data array (chans, frames)
% ELSE, three-dim. epoched data array (chans, frames, epochs)
%
% The channel locations sub-structures:
% EEG.chanlocs - structure array containing names and locations
% of the channels on the scalp
% EEG.urchanlocs - original (ur) dataset chanlocs structure containing
% all channels originally collected with these data
% (before channel rejection)
% EEG.chaninfo - structure containing additional channel info
% EEG.ref - type of channel reference ('common'|'averef'|+/-int]
% EEG.splinefile - location of the spline file used by headplot() to plot
% data scalp maps in 3-D
%
% The event and epoch sub-structures:
% EEG.event - event structure containing times and nature of experimental
% events recorded as occurring at data time points
% EEG.urevent - original (ur) event structure containing all experimental
% events recorded as occurring at the original data time points
% (before data rejection)
% EEG.epoch - epoch event information and epoch-associated data structure array (one per epoch)
% EEG.eventdescription - cell array of strings describing event fields.
% EEG.epochdescription - cell array of strings describing epoch fields.
% --> See the http://sccn.ucsd.edu/eeglab/maintut/eeglabscript.html for details
%
% ICA (or other linear) data components:
% EEG.icasphere - sphering array returned by linear (ICA) decomposition
% EEG.icaweights - unmixing weights array returned by linear (ICA) decomposition
% EEG.icawinv - inverse (ICA) weight matrix. Columns gives the projected
% topographies of the components to the electrodes.
% EEG.icaact - ICA activations matrix (components, frames, epochs)
% Note: [] here means that 'compute_ica' option has bee set
% to 0 under 'File > Memory options' In this case,
% component activations are computed only as needed.
% EEG.icasplinefile - location of the spline file used by headplot() to plot
% component scalp maps in 3-D
% EEG.chaninfo.icachansind - indices of channels used in the ICA decomposition
% EEG.dipfit - array of structures containing component map dipole models
%
% Variables indicating membership of the dataset in a studyset:
% EEG.subject - studyset subject code
% EEG.group - studyset group code
% EEG.condition - studyset experimental condition code
% EEG.session - studyset session number
%
% Variables used for manual and semi-automatic data rejection:
% EEG.specdata - data spectrum for every single trial
% EEG.specica - data spectrum for every single trial
% EEG.stats - statistics used for data rejection
% EEG.stats.kurtc - component kurtosis values
% EEG.stats.kurtg - global kurtosis of components
% EEG.stats.kurta - kurtosis of accepted epochs
% EEG.stats.kurtr - kurtosis of rejected epochs
% EEG.stats.kurtd - kurtosis of spatial distribution
% EEG.reject - statistics used for data rejection
% EEG.reject.entropy - entropy of epochs
% EEG.reject.entropyc - entropy of components
% EEG.reject.threshold - rejection thresholds
% EEG.reject.icareject - epochs rejected by ICA criteria
% EEG.reject.gcompreject - rejected ICA components
% EEG.reject.sigreject - epochs rejected by single-channel criteria
% EEG.reject.elecreject - epochs rejected by raw data criteria
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 01-26-02 chandeg events and trial condition format -ad
% 01-27-02 debug when trial condition is empty -ad
% 02-15-02 remove icawinv recompute for pop_epoch -ad & ja
% 02-16-02 remove last modification and test icawinv separatelly -ad
% 02-16-02 empty event and epoch check -ad
% 03-07-02 add the eeglab options -ad
% 03-07-02 corrected typos and rate/point calculation -ad & ja
% 03-15-02 add channel location reading & checking -ad
% 03-15-02 add checking of ICA and epochs with pop_up windows -ad
% 03-27-02 recorrected rate/point calculation -ad & sm
function [EEG, res] = eeg_checkset( EEG, varargin );
msg = '';
res = 'no';
com = sprintf('EEG = eeg_checkset( EEG );');
if nargin < 1
help eeg_checkset;
return;
end;
if isempty(EEG), return; end;
if ~isfield(EEG, 'data'), return; end;
% checking multiple datasets
% --------------------------
if length(EEG) > 1
if nargin > 1
switch varargin{1}
case 'epochconsist', % test epoch consistency
% ----------------------
res = 'no';
datasettype = unique_bc( [ EEG.trials ] );
if datasettype(1) == 1 & length(datasettype) == 1, return; % continuous data
elseif datasettype(1) == 1, return; % continuous and epoch data
end;
allpnts = unique_bc( [ EEG.pnts ] );
allxmin = unique_bc( [ EEG.xmin ] );
if length(allpnts) == 1 & length(allxmin) == 1, res = 'yes'; end;
return;
case 'chanconsist' % test channel number and name consistency
% ----------------------------------------
res = 'yes';
chanlen = unique_bc( [ EEG.nbchan ] );
anyempty = unique_bc( cellfun( 'isempty', { EEG.chanlocs }) );
if length(chanlen) == 1 & all(anyempty == 0)
tmpchanlocs = EEG(1).chanlocs;
channame1 = { tmpchanlocs.labels };
for i = 2:length(EEG)
tmpchanlocs = EEG(i).chanlocs;
channame2 = { tmpchanlocs.labels };
if length(intersect(channame1, channame2)) ~= length(channame1), res = 'no'; end;
end;
else res = 'no';
end;
return;
case 'icaconsist' % test ICA decomposition consistency
% ----------------------------------
res = 'yes';
anyempty = unique_bc( cellfun( 'isempty', { EEG.icaweights }) );
if length(anyempty) == 1 & anyempty(1) == 0
ica1 = EEG(1).icawinv;
for i = 2:length(EEG)
if ~isequal(EEG(1).icawinv, EEG(i).icawinv)
res = 'no';
end;
end;
else res = 'no';
end;
return;
end;
end;
end;
% reading these option take time because
% of disk access
% --------------
eeglab_options;
% standard checking
% -----------------
ALLEEG = EEG;
for inddataset = 1:length(ALLEEG)
EEG = ALLEEG(inddataset);
% additional checks
% -----------------
res = -1; % error code
if ~isempty( varargin)
for index = 1:length( varargin )
switch varargin{ index }
case 'data',; % already done at the top
case 'contdata',;
if EEG.trials > 1
errordlg2(strvcat('Error: function only works on continuous data'), 'Error');
return;
end;
case 'ica',
if isempty(EEG.icaweights)
errordlg2(strvcat('Error: no ICA decomposition. use menu "Tools > Run ICA" first.'), 'Error');
return;
end;
case 'epoch',
if EEG.trials == 1
errordlg2(strvcat('Extract epochs before running that function', 'Use Tools > Extract epochs'), 'Error');
return
end;
case 'besa',
if ~isfield(EEG, 'sources')
errordlg2(strvcat('No dipole information', '1) Export component maps: Tools > Localize ... BESA > Export ...' ...
, '2) Run BESA to localize the equivalent dipoles', ...
'3) Import the BESA dipoles: Tools > Localize ... BESA > Import ...'), 'Error');
return
end;
case 'event',
if isempty(EEG.event)
errordlg2(strvcat('Requires events. You need to add events first.', ...
'Use "File > Import event info" or "File > Import epoch info"'), 'Error');
return;
end;
case 'chanloc',
tmplocs = EEG.chanlocs;
if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta }))
errordlg2( strvcat('This functionality requires channel location information.', ...
'Enter the channel file name via "Edit > Edit dataset info".', ...
'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error');
return;
end;
case 'chanlocs_homogeneous',
tmplocs = EEG.chanlocs;
if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta }))
errordlg2( strvcat('This functionality requires channel location information.', ...
'Enter the channel file name via "Edit > Edit dataset info".', ...
'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error');
return;
end;
if ~isfield(EEG.chanlocs, 'X') || isempty(EEG.chanlocs(1).X)
EEG.chanlocs = convertlocs(EEG.chanlocs, 'topo2all');
res = [ inputname(1) ' = eeg_checkset(' inputname(1) ', ''chanlocs_homogeneous'' ); ' ];
end;
case 'chanlocsize',
if ~isempty(EEG.chanlocs)
if length(EEG.chanlocs) > EEG.nbchan
questdlg2(strvcat('Warning: there is one more electrode location than', ...
'data channels. EEGLAB will consider the last electrode to be the', ...
'common reference channel. If this is not the case, remove the', ...
'extra channel'), 'Warning', 'Ok', 'Ok');
end;
end;
case 'makeur',
if ~isempty(EEG.event)
if isfield(EEG.event, 'urevent'),
EEG.event = rmfield(EEG.event, 'urevent');
disp('eeg_checkset note: re-creating the original event table (EEG.urevent)');
else
disp('eeg_checkset note: creating the original event table (EEG.urevent)');
end;
EEG.urevent = EEG.event;
for index = 1:length(EEG.event)
EEG.event(index).urevent = index;
end;
end;
case 'checkur',
if ~isempty(EEG.event)
if isfield(EEG.event, 'urevent') & ~isempty(EEG.urevent)
urlatencies = [ EEG.urevent.latency ];
[newlat tmpind] = sort(urlatencies);
if ~isequal(newlat, urlatencies)
EEG.urevent = EEG.urevent(tmpind);
[tmp tmpind2] = sort(tmpind);
for index = 1:length(EEG.event)
EEG.event(index).urevent = tmpind2(EEG.event(index).urevent);
end;
end;
end;
end;
case 'eventconsistency',
[EEG res] = eeg_checkset(EEG);
if isempty(EEG.event), return; end;
% check events (slow)
% ------------
if isfield(EEG.event, 'type')
eventInds = arrayfun(@(x)isempty(x.type), EEG.event);
if any(eventInds)
if all(arrayfun(@(x)isnumeric(x.type), EEG.event))
for ind = find(eventInds), EEG.event(ind).type = NaN; end;
else for ind = find(eventInds), EEG.event(ind).type = 'empty'; end;
end;
end;
if ~all(arrayfun(@(x)ischar(x.type), EEG.event)) && ~all(arrayfun(@(x)isnumeric(x.type), EEG.event))
disp('Warning: converting all event types to strings');
for ind = 1:length(EEG.event)
EEG.event(ind).type = num2str(EEG.event(ind).type);
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
end;
end;
% remove the events which latency are out of boundary
% ---------------------------------------------------
if isfield(EEG.event, 'latency')
if isfield(EEG.event, 'type') && ischar(EEG.event(1).type)
if strcmpi(EEG.event(1).type, 'boundary') & isfield(EEG.event, 'duration')
if EEG.event(1).duration < 1
EEG.event(1) = [];
elseif EEG.event(1).latency > 0 & EEG.event(1).latency < 1
EEG.event(1).latency = 0.5;
end;
end;
end;
try, tmpevent = EEG.event; alllatencies = [ tmpevent.latency ];
catch, error('Checkset: error empty latency entry for new events added by user');
end;
I1 = find(alllatencies < 0.5);
I2 = find(alllatencies > EEG.pnts*EEG.trials+1); % The addition of 1 was included
% because, if data epochs are extracted from -1 to
% time 0, this allow to include the last event in
% the last epoch (otherwise all epochs have an
% event except the last one
if (length(I1) + length(I2)) > 0
fprintf('eeg_checkset warning: %d/%d events had out-of-bounds latencies and were removed\n', ...
length(I1) + length(I2), length(EEG.event));
EEG.event(union(I1, I2)) = [];
end;
end;
if isempty(EEG.event), return; end;
% save information for non latency fields updates
% -----------------------------------------------
difffield = [];
if ~isempty(EEG.event) && isfield(EEG.event, 'epoch')
% remove fields with empty epochs
% -------------------------------
removeevent = [];
try, tmpevent = EEG.event; allepochs = [ tmpevent.epoch ];
removeevent = find( allepochs < 1 | allepochs > EEG.trials);
if ~isempty(removeevent)
disp([ 'eeg_checkset warning: ' int2str(length(removeevent)) ' event had invalid epoch numbers and were removed']);
end;
catch,
for indexevent = 1:length(EEG.event)
if isempty( EEG.event(indexevent).epoch ) || ~isnumeric(EEG.event(indexevent).epoch) ...
| EEG.event(indexevent).epoch < 1 || EEG.event(indexevent).epoch > EEG.trials
removeevent = [removeevent indexevent];
disp([ 'eeg_checkset warning: event ' int2str(indexevent) ' has an invalid epoch number: removed']);
end;
end;
end;
EEG.event(removeevent) = [];
tmpevent = EEG.event;
allepochs = [ tmpevent.epoch ];
% uniformize fields content for the different epochs
% --------------------------------------------------
% THIS WAS REMOVED SINCE SOME FIELDS ARE ASSOCIATED WITH THE EVENT AND NOT WITH THE EPOCH
% I PUT IT BACK, BUT IT DOES NOT ERASE NON-EMPTY VALUES
difffield = fieldnames(EEG.event);
difffield = difffield(~(strcmp(difffield,'latency')|strcmp(difffield,'epoch')|strcmp(difffield,'type')));
for index = 1:length(difffield)
tmpevent = EEG.event;
allvalues = { tmpevent.(difffield{index}) };
try
valempt = cellfun('isempty', allvalues);
catch
valempt = mycellfun('isempty', allvalues);
end;
arraytmpinfo = cell(1,EEG.trials);
% spetial case of duration
% ------------------------
if strcmp( difffield{index}, 'duration')
if any(valempt)
fprintf(['eeg_checkset: found empty values for field ''' difffield{index} ...
''' (filling with 0)\n']);
end;
for indexevent = find(valempt)
EEG.event(indexevent).duration = 0;
end;
else
% get the field content
% ---------------------
indexevent = find(~valempt);
arraytmpinfo(allepochs(indexevent)) = allvalues(indexevent);
% uniformize content for all epochs
% ---------------------------------
indexevent = find(valempt);
tmpevent = EEG.event;
[tmpevent(indexevent).(difffield{index})] = arraytmpinfo{allepochs(indexevent)};
EEG.event = tmpevent;
if any(valempt)
fprintf(['eeg_checkset: found empty values for field ''' difffield{index} '''\n']);
fprintf([' filling with values of other events in the same epochs\n']);
end;
end;
end;
end;
if isempty(EEG.event), return; end;
% uniformize fields (str or int) if necessary
% -------------------------------------------
fnames = fieldnames(EEG.event);
for fidx = 1:length(fnames)
fname = fnames{fidx};
tmpevent = EEG.event;
allvalues = { tmpevent.(fname) };
try
% find indices of numeric values among values of this event property
valreal = ~cellfun('isclass', allvalues, 'char');
catch
valreal = mycellfun('isclass', allvalues, 'double');
end;
format = 'ok';
if ~all(valreal) % all valreal ok
format = 'str';
if all(valreal == 0) % all valreal=0 ok
format = 'ok';
end;
end;
if strcmp(format, 'str')
fprintf('eeg_checkset note: value format of event field ''%s'' made uniform\n', fname);
% get the field content
% ---------------------
for indexevent = 1:length(EEG.event)
if valreal(indexevent)
EEG.event = setfield(EEG.event, { indexevent }, fname, num2str(allvalues{indexevent}) );
end;
end;
end;
end;
% check boundary events
% ---------------------
tmpevent = EEG.event;
if isfield(tmpevent, 'type') && ~isnumeric(tmpevent(1).type)
allEventTypes = { tmpevent.type };
boundsInd = strmatch('boundary', allEventTypes);
if ~isempty(boundsInd),
bounds = [ tmpevent(boundsInd).latency ];
% remove last event if necessary
if EEG.trials==1;%this if block added by James Desjardins (Jan 13th, 2014)
if round(bounds(end)-0.5+1) >= size(EEG.data,2), EEG.event(boundsInd(end)) = []; bounds(end) = []; end; % remove final boundary if any
end
% The first boundary below need to be kept for
% urevent latency calculation
% if bounds(1) < 0, EEG.event(bounds(1)) = []; end; % remove initial boundary if any
indDoublet = find(bounds(2:end)-bounds(1:end-1)==0);
if ~isempty(indDoublet)
disp('Warning: duplicate boundary event removed');
for indBound = 1:length(indDoublet)
EEG.event(boundsInd(indDoublet(indBound)+1)).duration = EEG.event(boundsInd(indDoublet(indBound)+1)).duration+EEG.event(boundsInd(indDoublet(indBound))).duration;
end;
EEG.event(boundsInd(indDoublet)) = [];
end;
end;
end;
if isempty(EEG.event), return; end;
% check that numeric format is double (Matlab 7)
% -----------------------------------
allfields = fieldnames(EEG.event);
if ~isempty(EEG.event)
for index = 1:length(allfields)
tmpval = EEG.event(1).(allfields{index});
if isnumeric(tmpval) && ~isa(tmpval, 'double')
for indexevent = 1:length(EEG.event)
tmpval = getfield(EEG.event, { indexevent }, allfields{index} );
EEG.event = setfield(EEG.event, { indexevent }, allfields{index}, double(tmpval));
end;
end;
end;
end;
% check duration field, replace empty by 0
% ----------------------------------------
if isfield(EEG.event, 'duration')
tmpevent = EEG.event;
try, valempt = cellfun('isempty' , { tmpevent.duration });
catch, valempt = mycellfun('isempty', { tmpevent.duration });
end;
if any(valempt),
for index = find(valempt)
EEG.event(index).duration = 0;
end;
end;
end;
% resort events
% -------------
if isfield(EEG.event, 'latency')
try,
if isfield(EEG.event, 'epoch')
TMPEEG = pop_editeventvals(EEG, 'sort', { 'epoch' 0 'latency' 0 });
else
TMPEEG = pop_editeventvals(EEG, 'sort', { 'latency' 0 });
end;
if ~isequal(TMPEEG.event, EEG.event)
EEG = TMPEEG;
disp('Event resorted by increasing latencies.');
end;
catch,
disp('eeg_checkset: problem when attempting to resort event latencies.');
end;
end;
% check latency of first event
% ----------------------------
if ~isempty(EEG.event)
if isfield(EEG.event, 'latency')
if EEG.event(1).latency < 0.5
EEG.event(1).latency = 0.5;
end;
end;
end;
% build epoch structure
% ---------------------
try,
if EEG.trials > 1 & ~isempty(EEG.event)
% erase existing event-related fields
% ------------------------------
if ~isfield(EEG,'epoch')
EEG.epoch = [];
end
if ~isempty(EEG.epoch)
if length(EEG.epoch) ~= EEG.trials
disp('Warning: number of epoch entries does not match number of dataset trials;');
disp(' user-defined epoch entries will be erased.');
EEG.epoch = [];
else
fn = fieldnames(EEG.epoch);
EEG.epoch = rmfield(EEG.epoch,fn(strncmp('event',fn,5)));
end
end
% set event field
% ---------------
tmpevent = EEG.event;
eventepoch = [tmpevent.epoch];
epochevent = cell(1,EEG.trials);
destdata = epochevent;
EEG.epoch(length(epochevent)).event = [];
for k=1:length(epochevent)
epochevent{k} = find(eventepoch==k);
end
tmpepoch = EEG.epoch;
[tmpepoch.event] = epochevent{:};
EEG.epoch = tmpepoch;
maxlen = max(cellfun(@length,epochevent));
% copy event information into the epoch array
% -------------------------------------------
eventfields = fieldnames(EEG.event)';
eventfields = eventfields(~strcmp(eventfields,'epoch'));
tmpevent = EEG.event;
for k = 1:length(eventfields)
fname = eventfields{k};
switch fname
case 'latency'
sourcedata = round(eeg_point2lat([tmpevent.(fname)],[tmpevent.epoch],EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3) * 10^8 )/10^8;
sourcedata = num2cell(sourcedata);
case 'duration'
sourcedata = num2cell([tmpevent.(fname)]/EEG.srate*1000);
otherwise
sourcedata = {tmpevent.(fname)};
end
if maxlen == 1
destdata = cell(1,length(epochevent));
destdata(~cellfun('isempty',epochevent)) = sourcedata([epochevent{:}]);
else
for l=1:length(epochevent)
destdata{l} = sourcedata(epochevent{l});
end
end
tmpepoch = EEG.epoch;
[tmpepoch.(['event' fname])] = destdata{:};
EEG.epoch = tmpepoch;
end
end;
catch,
errordlg2(['Warning: minor problem encountered when generating' 10 ...
'the EEG.epoch structure (used only in user scripts)']); return;
end;
case { 'loaddata' 'savedata' 'chanconsist' 'icaconsist' 'epochconsist' }, res = '';
otherwise, error('eeg_checkset: unknown option');
end;
end;
end;
res = [];
% check name consistency
% ----------------------
if ~isempty(EEG.setname)
if ~ischar(EEG.setname)
EEG.setname = '';
else
if size(EEG.setname,1) > 1
disp('eeg_checkset warning: invalid dataset name, removed');
EEG.setname = '';
end;
end;
else
EEG.setname = '';
end;
% checking history and convert if necessary
% -----------------------------------------
if isfield(EEG, 'history') & size(EEG.history,1) > 1
allcoms = cellstr(EEG.history);
EEG.history = deblank(allcoms{1});
for index = 2:length(allcoms)
EEG.history = [ EEG.history 10 deblank(allcoms{index}) ];
end;
end;
% read data if necessary
% ----------------------
if ischar(EEG.data) & nargin > 1
if strcmpi(varargin{1}, 'loaddata')
EEG.data = eeg_getdatact(EEG);
end;
end;
% save data if necessary
% ----------------------
if nargin > 1
% datfile available?
% ------------------
datfile = 0;
if isfield(EEG, 'datfile')
if ~isempty(EEG.datfile)
datfile = 1;
end;
end;
% save data
% ---------
if strcmpi(varargin{1}, 'savedata') & option_storedisk
error('eeg_checkset: cannot call savedata any more');
% the code below is deprecated
if ~ischar(EEG.data) % not already saved
disp('Writing previous dataset to disk...');
if datfile
tmpdata = reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials);
floatwrite( tmpdata', fullfile(EEG.filepath, EEG.datfile), 'ieee-le');
EEG.data = EEG.datfile;
end;
EEG.icaact = [];
% saving dataset
% --------------
filename = fullfile(EEG(1).filepath, EEG(1).filename);
if ~ischar(EEG.data) & option_single, EEG.data = single(EEG.data); end;
v = version;
if str2num(v(1)) >= 7, save( filename, '-v6', '-mat', 'EEG'); % Matlab 7
else save( filename, '-mat', 'EEG');
end;
if ~ischar(EEG.data), EEG.data = 'in set file'; end;
res = sprintf('%s = eeg_checkset( %s, ''savedata'');', inputname(1), inputname(1));
end;
end;
end;
% numerical format
% ----------------
if isnumeric(EEG.data)
v = version;
EEG.icawinv = double(EEG.icawinv); % required for dipole fitting, otherwise it crashes
EEG.icaweights = double(EEG.icaweights);
EEG.icasphere = double(EEG.icasphere);
if ~isempty(findstr(v, 'R11')) | ~isempty(findstr(v, 'R12')) | ~isempty(findstr(v, 'R13'))
EEG.data = double(EEG.data);
EEG.icaact = double(EEG.icaact);
else
try,
if isa(EEG.data, 'double') & option_single
EEG.data = single(EEG.data);
EEG.icaact = single(EEG.icaact);
end;
catch,
disp('WARNING: EEGLAB ran out of memory while converting dataset to single precision.');
disp(' Save dataset (preferably saving data to a separate file; see File > Memory options).');
disp(' Then reload it.');
end;
end;
end;
% verify the type of the variables
% --------------------------------
% data dimensions -------------------------
if isnumeric(EEG.data) && ~isempty(EEG.data)
if ~isequal(size(EEG.data,1), EEG.nbchan)
disp( [ 'eeg_checkset warning: number of columns in data (' int2str(size(EEG.data,1)) ...
') does not match the number of channels (' int2str(EEG.nbchan) '): corrected' ]);
res = com;
EEG.nbchan = size(EEG.data,1);
end;
if (ndims(EEG.data)) < 3 & (EEG.pnts > 1)
if mod(size(EEG.data,2), EEG.pnts) ~= 0
if popask( [ 'eeg_checkset error: the number of frames does not divide the number of columns in the data.' 10 ...
'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the command line)'])
error('eeg_checkset error: user abort');
%res = com;
%EEG.pnts = size(EEG.data,2);
%EEG = eeg_checkset(EEG);
%return;
else
res = com;
return;
%error( 'eeg_checkset error: number of points does not divide the number of columns in data');
end;
else
if EEG.trials > 1
disp( 'eeg_checkset note: data array made 3-D');
res = com;
end;
if size(EEG.data,2) ~= EEG.pnts
EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, size(EEG.data,2)/EEG.pnts);
end;
end;
end;
% size of data -----------
if size(EEG.data,3) ~= EEG.trials
disp( ['eeg_checkset warning: 3rd dimension size of data (' int2str(size(EEG.data,3)) ...
') does not match the number of epochs (' int2str(EEG.trials) '), corrected' ]);
res = com;
EEG.trials = size(EEG.data,3);
end;
if size(EEG.data,2) ~= EEG.pnts
disp( [ 'eeg_checkset warning: number of columns in data (' int2str(size(EEG.data,2)) ...
') does not match the number of points (' int2str(EEG.pnts) '): corrected' ]);
res = com;
EEG.pnts = size(EEG.data,2);
end;
end;
% parameters consistency
% -------------------------
if round(EEG.srate*(EEG.xmax-EEG.xmin)+1) ~= EEG.pnts
fprintf( 'eeg_checkset note: upper time limit (xmax) adjusted so (xmax-xmin)*srate+1 = number of frames\n');
if EEG.srate == 0
EEG.srate = 1;
end;
EEG.xmax = (EEG.pnts-1)/EEG.srate+EEG.xmin;
res = com;
end;
% deal with event arrays
% ----------------------
if ~isfield(EEG, 'event'), EEG.event = []; res = com; end;
if ~isempty(EEG.event)
if EEG.trials > 1 & ~isfield(EEG.event, 'epoch')
if popask( [ 'eeg_checkset error: the event info structure does not contain an ''epoch'' field.' ...
'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)'])
error('eeg_checkset error(): user abort');
%res = com;
%EEG.event = [];
%EEG = eeg_checkset(EEG);
%return;
else
res = com;
return;
%error('eeg_checkset error: no epoch field in event structure');
end;
end;
else
EEG.event = [];
end;
if isempty(EEG.event)
EEG.eventdescription = {};
end;
if ~isfield(EEG, 'eventdescription') | ~iscell(EEG.eventdescription)
EEG.eventdescription = cell(1, length(fieldnames(EEG.event)));
res = com;
else
if ~isempty(EEG.event)
if length(EEG.eventdescription) > length( fieldnames(EEG.event))
EEG.eventdescription = EEG.eventdescription(1:length( fieldnames(EEG.event)));
elseif length(EEG.eventdescription) < length( fieldnames(EEG.event))
EEG.eventdescription(end+1:length( fieldnames(EEG.event))) = {''};
end;
end;
end;
% create urevent if continuous data
% ---------------------------------
if ~isempty(EEG.event) & ~isfield(EEG, 'urevent')
EEG.urevent = EEG.event;
disp('eeg_checkset note: creating the original event table (EEG.urevent)');
for index = 1:length(EEG.event)
EEG.event(index).urevent = index;
end;
end;
if isfield(EEG, 'urevent') & isfield(EEG.urevent, 'urevent')
EEG.urevent = rmfield(EEG.urevent, 'urevent');
end;
% deal with epoch arrays
% ----------------------
if ~isfield(EEG, 'epoch'), EEG.epoch = []; res = com; end;
% check if only one epoch
% -----------------------
if EEG.trials == 1
if isfield(EEG.event, 'epoch')
EEG.event = rmfield(EEG.event, 'epoch'); res = com;
end;
if ~isempty(EEG.epoch)
EEG.epoch = []; res = com;
end;
end;
if ~isfield(EEG, 'epochdescription'), EEG.epochdescription = {}; res = com; end;
if ~isempty(EEG.epoch)
if isstruct(EEG.epoch), l = length( EEG.epoch);
else l = size( EEG.epoch, 2);
end;
if l ~= EEG.trials
if popask( [ 'eeg_checkset error: the number of epoch indices in the epoch array/struct (' ...
int2str(l) ') is different from the number of epochs in the data (' int2str(EEG.trials) ').' 10 ...
'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)'])
error('eeg_checkset error: user abort');
%res = com;
%EEG.epoch = [];
%EEG = eeg_checkset(EEG);
%return;
else
res = com;
return;
%error('eeg_checkset error: epoch structure size invalid');
end;
end;
else
EEG.epoch = [];
end;
% check ica
% ---------
if ~isfield(EEG, 'icachansind')
if isempty(EEG.icaweights)
EEG.icachansind = []; res = com;
else
EEG.icachansind = [1:EEG.nbchan]; res = com;
end;
elseif isempty(EEG.icachansind)
if isempty(EEG.icaweights)
EEG.icachansind = []; res = com;
else
EEG.icachansind = [1:EEG.nbchan]; res = com;
end;
end;
if ~isempty(EEG.icasphere)
if ~isempty(EEG.icaweights)
if size(EEG.icaweights,2) ~= size(EEG.icasphere,1)
if popask( [ 'eeg_checkset error: number of columns in weights array (' int2str(size(EEG.icaweights,2)) ')' 10 ...
'does not match the number of rows in the sphere array (' int2str(size(EEG.icasphere,1)) ')' 10 ...
'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)'])
res = com;
EEG.icasphere = [];
EEG.icaweights = [];
EEG = eeg_checkset(EEG);
return;
else
error('eeg_checkset error: user abort');
res = com;
return;
%error('eeg_checkset error: invalid weight and sphere array sizes');
end;
end;
if isnumeric(EEG.data)
if length(EEG.icachansind) ~= size(EEG.icasphere,2)
if popask( [ 'eeg_checkset error: number of elements in ''icachansind'' (' int2str(length(EEG.icachansind)) ')' 10 ...
'does not match the number of columns in the sphere array (' int2str(size(EEG.icasphere,2)) ')' 10 ...
'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)'])
res = com;
EEG.icasphere = [];
EEG.icaweights = [];
EEG = eeg_checkset(EEG);
return;
else
error('eeg_checkset error: user abort');
res = com;
return;
%error('eeg_checkset error: invalid weight and sphere array sizes');
end;
end;
if isempty(EEG.icaact) | (size(EEG.icaact,1) ~= size(EEG.icaweights,1)) | (size(EEG.icaact,2) ~= size(EEG.data,2))
EEG.icaweights = double(EEG.icaweights);
EEG.icawinv = double(EEG.icawinv);
% scale ICA components to RMS microvolt
if option_scaleicarms
if ~isempty(EEG.icawinv)
if mean(mean(abs(pinv(EEG.icaweights * EEG.icasphere)-EEG.icawinv))) < 0.0001
disp('Scaling components to RMS microvolt');
scaling = repmat(sqrt(mean(EEG(1).icawinv(:,:).^2))', [1 size(EEG.icaweights,2)]);
EEG.etc.icaweights_beforerms = EEG.icaweights;
EEG.etc.icasphere_beforerms = EEG.icasphere;
EEG.icaweights = EEG.icaweights .* scaling;
EEG.icawinv = pinv(EEG.icaweights * EEG.icasphere);
end;
end;
end;
if ~isempty(EEG.data) && option_computeica
fprintf('eeg_checkset: recomputing the ICA activation matrix ...\n');
res = com;
% Make compatible with Matlab 7
if any(isnan(EEG.data(:)))
tmpdata = EEG.data(EEG.icachansind,:);
fprintf('eeg_checkset: recomputing ICA ignoring NaN indices ...\n');
tmpindices = find(~sum(isnan(tmpdata))); % was: tmpindices = find(~isnan(EEG.data(1,:)));
EEG.icaact = zeros(size(EEG.icaweights,1), size(tmpdata,2)); EEG.icaact(:) = NaN;
EEG.icaact(:,tmpindices) = (EEG.icaweights*EEG.icasphere)*tmpdata(:,tmpindices);
else
EEG.icaact = (EEG.icaweights*EEG.icasphere)*EEG.data(EEG.icachansind,:); % automatically does single or double
end;
EEG.icaact = reshape( EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials);
end;
end;
end;
if isempty(EEG.icawinv)
EEG.icawinv = pinv(EEG.icaweights*EEG.icasphere); % a priori same result as inv
res = com;
end;
else
disp( [ 'eeg_checkset warning: weights matrix cannot be empty if sphere matrix is not, correcting ...' ]);
res = com;
EEG.icasphere = [];
end;
if option_computeica
if ~isempty(EEG.icaact) & ndims(EEG.icaact) < 3 & (EEG.trials > 1)
disp( [ 'eeg_checkset note: independent component made 3-D' ]);
res = com;
EEG.icaact = reshape(EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials);
end;
else
if ~isempty(EEG.icaact)
fprintf('eeg_checkset: removing ICA activation matrix (as per edit options) ...\n');
end;
EEG.icaact = [];
end;
else
if ~isempty( EEG.icaweights ), EEG.icaweights = []; res = com; end;
if ~isempty( EEG.icawinv ), EEG.icawinv = []; res = com; end;
if ~isempty( EEG.icaact ), EEG.icaact = []; res = com; end;
end;
if isempty(EEG.icaact)
EEG.icaact = [];
end;
% -------------
% check chanlocs
% -------------
if ~isfield(EEG, 'chaninfo')
EEG.chaninfo = [];
end;
if ~isempty( EEG.chanlocs )
% reference (use EEG structure)
% ---------
if ~isfield(EEG, 'ref'), EEG.ref = ''; end;
if strcmpi(EEG.ref, 'averef')
ref = 'average';
else ref = '';
end;
if ~isfield( EEG.chanlocs, 'ref')
EEG.chanlocs(1).ref = ref;
end;
charrefs = cellfun('isclass',{EEG.chanlocs.ref},'char');
if any(charrefs) ref = ''; end
for tmpind = find(~charrefs)
EEG.chanlocs(tmpind).ref = ref;
end
if ~isstruct( EEG.chanlocs)
if exist( EEG.chanlocs ) ~= 2
disp( [ 'eeg_checkset warning: channel file does not exist or is not in Matlab path: filename removed from EEG struct' ]);
EEG.chanlocs = [];
res = com;
else
res = com;
try, EEG.chanlocs = readlocs( EEG.chanlocs );
disp( [ 'eeg_checkset: channel file read' ]);
catch, EEG.chanlocs = []; end;
end;
else
if ~isfield(EEG.chanlocs,'labels')
disp('eeg_checkset warning: no field label in channel location structure, removing it');
EEG.chanlocs = [];
res = com;
end;
end;
if isstruct( EEG.chanlocs)
if length( EEG.chanlocs) ~= EEG.nbchan && length( EEG.chanlocs) ~= EEG.nbchan+1 && ~isempty(EEG.data)
disp( [ 'eeg_checkset warning: number of channels different in data and channel file/struct: channel file/struct removed' ]);
EEG.chanlocs = [];
res = com;
end;
end;
% force Nosedir to +X (done here because of DIPFIT)
% -------------------
if isfield(EEG.chaninfo, 'nosedir')
if strcmpi(EEG.chaninfo.nosedir, '+x')
rotate = 0;
elseif all(isfield(EEG.chanlocs,{'X','Y','theta','sph_theta'}))
disp('EEG checkset note for expert users: Noze direction now set to default +X in EEG.chanlocs and EEG.dipfit.');
if strcmpi(EEG.chaninfo.nosedir, '+y')
rotate = 270;
elseif strcmpi(EEG.chaninfo.nosedir, '-x')
rotate = 180;
else rotate = 90;
end;
for index = 1:length(EEG.chanlocs)
if ~isempty(EEG.chanlocs(index).theta)
rotategrad = rotate/180*pi;
coord = (EEG.chanlocs(index).Y + EEG.chanlocs(index).X*sqrt(-1))*exp(sqrt(-1)*-rotategrad);
EEG.chanlocs(index).Y = real(coord);
EEG.chanlocs(index).X = imag(coord);
EEG.chanlocs(index).theta = EEG.chanlocs(index).theta -rotate;
EEG.chanlocs(index).sph_theta = EEG.chanlocs(index).sph_theta+rotate;
if EEG.chanlocs(index).theta <-180, EEG.chanlocs(index).theta =EEG.chanlocs(index).theta +360; end;
if EEG.chanlocs(index).sph_theta>180 , EEG.chanlocs(index).sph_theta=EEG.chanlocs(index).sph_theta-360; end;
end;
end;
if isfield(EEG, 'dipfit')
if isfield(EEG.dipfit, 'coord_transform')
if isempty(EEG.dipfit.coord_transform)
EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
end;
EEG.dipfit.coord_transform(6) = EEG.dipfit.coord_transform(6)+rotategrad;
end;
end;
end;
EEG.chaninfo.nosedir = '+X';
end;
% general checking of channels
% ----------------------------
EEG = eeg_checkchanlocs(EEG);
if EEG.nbchan ~= length(EEG.chanlocs)
EEG.chanlocs = [];
EEG.chaninfo = [];
disp('Warning: the size of the channel location structure does not match with');
disp(' number of channels. Channel information have been removed.');
end;
end;
EEG.chaninfo.icachansind = EEG.icachansind; % just a copy for programming convinience
%if ~isfield(EEG, 'urchanlocs')
% EEG.urchanlocs = EEG.chanlocs;
% for index = 1:length(EEG.chanlocs)
% EEG.chanlocs(index).urchan = index;
% end;
% disp('eeg_checkset note: creating backup chanlocs structure (urchanlocs)');
%end;
% check reference
% ---------------
if ~isfield(EEG, 'ref')
EEG.ref = 'common';
end;
if ischar(EEG.ref) & strcmpi(EEG.ref, 'common')
if length(EEG.chanlocs) > EEG.nbchan
disp('Extra common reference electrode location detected');
EEG.ref = EEG.nbchan+1;
end;
end;
% DIPFIT structure
% ----------------
if ~isfield(EEG,'dipfit') || isempty(EEG.dipfit)
EEG.dipfit = []; res = com;
else
try
% check if dipfitdefs is present
dipfitdefs;
if isfield(EEG.dipfit, 'vol') & ~isfield(EEG.dipfit, 'hdmfile')
if exist('pop_dipfit_settings')
disp('Old DIPFIT structure detected: converting to DIPFIT 2 format');
EEG.dipfit.hdmfile = template_models(1).hdmfile;
EEG.dipfit.coordformat = template_models(1).coordformat;
EEG.dipfit.mrifile = template_models(1).mrifile;
EEG.dipfit.chanfile = template_models(1).chanfile;
EEG.dipfit.coord_transform = [];
EEG.saved = 'no';
res = com;
end;
end;
if isfield(EEG.dipfit, 'hdmfile')
if length(EEG.dipfit.hdmfile) > 8
if strcmpi(EEG.dipfit.hdmfile(end-8), template_models(1).hdmfile(end-8)), EEG.dipfit.hdmfile = template_models(1).hdmfile; end;
if strcmpi(EEG.dipfit.hdmfile(end-8), template_models(2).hdmfile(end-8)), EEG.dipfit.hdmfile = template_models(2).hdmfile; end;
end;
if length(EEG.dipfit.mrifile) > 8
if strcmpi(EEG.dipfit.mrifile(end-8), template_models(1).mrifile(end-8)), EEG.dipfit.mrifile = template_models(1).mrifile; end;
if strcmpi(EEG.dipfit.mrifile(end-8), template_models(2).mrifile(end-8)), EEG.dipfit.mrifile = template_models(2).mrifile; end;
end;
if length(EEG.dipfit.chanfile) > 8
if strcmpi(EEG.dipfit.chanfile(end-8), template_models(1).chanfile(end-8)), EEG.dipfit.chanfile = template_models(1).chanfile; end;
if strcmpi(EEG.dipfit.chanfile(end-8), template_models(2).chanfile(end-8)), EEG.dipfit.chanfile = template_models(2).chanfile; end;
end;
end;
if isfield(EEG.dipfit, 'coord_transform')
if isempty(EEG.dipfit.coord_transform)
EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
end;
elseif ~isempty(EEG.dipfit)
EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1];
end;
catch
e = lasterror;
if ~strcmp(e.identifier,'MATLAB:UndefinedFunction')
% if we got some error aside from dipfitdefs not being present, rethrow it
rethrow(e);
end
end
end;
% check events (fast)
% ------------
if isfield(EEG.event, 'type')
tmpevent = EEG.event(1:min(length(EEG.event), 100));
if ~all(cellfun(@ischar, { tmpevent.type })) && ~all(cellfun(@isnumeric, { tmpevent.type }))
disp('Warning: converting all event types to strings');
for ind = 1:length(EEG.event)
EEG.event(ind).type = num2str(EEG.event(ind).type);
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
end;
end;
% EEG.times (only for epoched datasets)
% ---------
if ~isfield(EEG, 'times') || isempty(EEG.times) || length(EEG.times) ~= EEG.pnts
EEG.times = linspace(EEG.xmin*1000, EEG.xmax*1000, EEG.pnts);
end;
if ~isfield(EEG, 'history') EEG.history = ''; res = com; end;
if ~isfield(EEG, 'splinefile') EEG.splinefile = ''; res = com; end;
if ~isfield(EEG, 'icasplinefile') EEG.icasplinefile = ''; res = com; end;
if ~isfield(EEG, 'saved') EEG.saved = 'no'; res = com; end;
if ~isfield(EEG, 'subject') EEG.subject = ''; res = com; end;
if ~isfield(EEG, 'condition') EEG.condition = ''; res = com; end;
if ~isfield(EEG, 'group') EEG.group = ''; res = com; end;
if ~isfield(EEG, 'session') EEG.session = []; res = com; end;
if ~isfield(EEG, 'urchanlocs') EEG.urchanlocs = []; res = com; end;
if ~isfield(EEG, 'specdata') EEG.specdata = []; res = com; end;
if ~isfield(EEG, 'specicaact') EEG.specicaact = []; res = com; end;
if ~isfield(EEG, 'comments') EEG.comments = ''; res = com; end;
if ~isfield(EEG, 'etc' ) EEG.etc = []; res = com; end;
if ~isfield(EEG, 'urevent' ) EEG.urevent = []; res = com; end;
if ~isfield(EEG, 'ref') | isempty(EEG.ref) EEG.ref = 'common'; res = com; end;
% create fields if absent
% -----------------------
if ~isfield(EEG, 'reject') EEG.reject.rejjp = []; res = com; end;
listf = { 'rejjp' 'rejkurt' 'rejmanual' 'rejthresh' 'rejconst', 'rejfreq' ...
'icarejjp' 'icarejkurt' 'icarejmanual' 'icarejthresh' 'icarejconst', 'icarejfreq'};
for index = 1:length(listf)
name = listf{index};
elecfield = [name 'E'];
if ~isfield(EEG.reject, elecfield), EEG.reject.(elecfield) = []; res = com; end;
if ~isfield(EEG.reject, name)
EEG.reject.(name) = [];
res = com;
elseif ~isempty(EEG.reject.(name)) && isempty(EEG.reject.(elecfield))
% check if electrode array is empty with rejection array is not
nbchan = fastif(strcmp(name, 'ica'), size(EEG.icaweights,1), EEG.nbchan);
EEG.reject = setfield(EEG.reject, elecfield, zeros(nbchan, length(getfield(EEG.reject, name)))); res = com;
end;
end;
if ~isfield(EEG.reject, 'rejglobal') EEG.reject.rejglobal = []; res = com; end;
if ~isfield(EEG.reject, 'rejglobalE') EEG.reject.rejglobalE = []; res = com; end;
% default colors for rejection
% ----------------------------
if ~isfield(EEG.reject, 'rejmanualcol') EEG.reject.rejmanualcol = [1.0000 1 0.783]; res = com; end;
if ~isfield(EEG.reject, 'rejthreshcol') EEG.reject.rejthreshcol = [0.8487 1.0000 0.5008]; res = com; end;
if ~isfield(EEG.reject, 'rejconstcol') EEG.reject.rejconstcol = [0.6940 1.0000 0.7008]; res = com; end;
if ~isfield(EEG.reject, 'rejjpcol') EEG.reject.rejjpcol = [1.0000 0.6991 0.7537]; res = com; end;
if ~isfield(EEG.reject, 'rejkurtcol') EEG.reject.rejkurtcol = [0.6880 0.7042 1.0000]; res = com; end;
if ~isfield(EEG.reject, 'rejfreqcol') EEG.reject.rejfreqcol = [0.9596 0.7193 1.0000]; res = com; end;
if ~isfield(EEG.reject, 'disprej') EEG.reject.disprej = { }; end;
if ~isfield(EEG, 'stats') EEG.stats.jp = []; res = com; end;
if ~isfield(EEG.stats, 'jp') EEG.stats.jp = []; res = com; end;
if ~isfield(EEG.stats, 'jpE') EEG.stats.jpE = []; res = com; end;
if ~isfield(EEG.stats, 'icajp') EEG.stats.icajp = []; res = com; end;
if ~isfield(EEG.stats, 'icajpE') EEG.stats.icajpE = []; res = com; end;
if ~isfield(EEG.stats, 'kurt') EEG.stats.kurt = []; res = com; end;
if ~isfield(EEG.stats, 'kurtE') EEG.stats.kurtE = []; res = com; end;
if ~isfield(EEG.stats, 'icakurt') EEG.stats.icakurt = []; res = com; end;
if ~isfield(EEG.stats, 'icakurtE') EEG.stats.icakurtE = []; res = com; end;
% component rejection
% -------------------
if ~isfield(EEG.stats, 'compenta') EEG.stats.compenta = []; res = com; end;
if ~isfield(EEG.stats, 'compentr') EEG.stats.compentr = []; res = com; end;
if ~isfield(EEG.stats, 'compkurta') EEG.stats.compkurta = []; res = com; end;
if ~isfield(EEG.stats, 'compkurtr') EEG.stats.compkurtr = []; res = com; end;
if ~isfield(EEG.stats, 'compkurtdist') EEG.stats.compkurtdist = []; res = com; end;
if ~isfield(EEG.reject, 'threshold') EEG.reject.threshold = [0.8 0.8 0.8]; res = com; end;
if ~isfield(EEG.reject, 'threshentropy') EEG.reject.threshentropy = 600; res = com; end;
if ~isfield(EEG.reject, 'threshkurtact') EEG.reject.threshkurtact = 600; res = com; end;
if ~isfield(EEG.reject, 'threshkurtdist') EEG.reject.threshkurtdist = 600; res = com; end;
if ~isfield(EEG.reject, 'gcompreject') EEG.reject.gcompreject = []; res = com; end;
if length(EEG.reject.gcompreject) ~= size(EEG.icaweights,1)
EEG.reject.gcompreject = zeros(1, size(EEG.icaweights,1));
end;
% remove old fields
% -----------------
if isfield(EEG, 'averef'), EEG = rmfield(EEG, 'averef'); end;
if isfield(EEG, 'rt' ), EEG = rmfield(EEG, 'rt'); end;
% store in new structure
% ----------------------
if isstruct(EEG)
if ~exist('ALLEEGNEW','var')
ALLEEGNEW = EEG;
else
ALLEEGNEW(inddataset) = EEG;
end;
end;
end;
% recorder fields
% ---------------
fieldorder = { 'setname' ...
'filename' ...
'filepath' ...
'subject' ...
'group' ...
'condition' ...
'session' ...
'comments' ...
'nbchan' ...
'trials' ...
'pnts' ...
'srate' ...
'xmin' ...
'xmax' ...
'times' ...
'data' ...
'icaact' ...
'icawinv' ...
'icasphere' ...
'icaweights' ...
'icachansind' ...
'chanlocs' ...
'urchanlocs' ...
'chaninfo' ...
'ref' ...
'event' ...
'urevent' ...
'eventdescription' ...
'epoch' ...
'epochdescription' ...
'reject' ...
'stats' ...
'specdata' ...
'specicaact' ...
'splinefile' ...
'icasplinefile' ...
'dipfit' ...
'history' ...
'saved' ...
'etc' };
for fcell = fieldnames(EEG)'
fname = fcell{1};
if ~any(strcmp(fieldorder,fname))
fieldorder{end+1} = fname;
end
end
try
ALLEEGNEW = orderfields(ALLEEGNEW, fieldorder);
EEG = ALLEEGNEW;
catch
disp('Couldn''t order data set fields properly.');
end;
if exist('ALLEEGNEW','var')
EEG = ALLEEGNEW;
end;
% if ~isa(EEG, 'eegobj') && option_eegobject
% EEG = eegobj(EEG);
% end;
return;
function num = popask( text )
ButtonName=questdlg2( text, ...
'Confirmation', 'Cancel', 'Yes','Yes');
switch lower(ButtonName),
case 'cancel', num = 0;
case 'yes', num = 1;
end;
function res = mycellfun(com, vals, classtype);
res = zeros(1, length(vals));
switch com
case 'isempty',
for index = 1:length(vals), res(index) = isempty(vals{index}); end;
case 'isclass'
if strcmp(classtype, 'double')
for index = 1:length(vals), res(index) = isnumeric(vals{index}); end;
else
error('unknown cellfun command');
end;
otherwise error('unknown cellfun command');
end;
|
github
|
lcnbeapp/beapp-master
|
parsebvmrk.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/parsebvmrk.m
| 1,733 |
utf_8
|
830dc68f40bea55d2ed6d85fccec8c51
|
% parsebvmrk() - convert Brain Vision Data Exchange format marker
% configuration structure to EEGLAB event structure
%
% Usage:
% >> EVENT = parsebvmrk(MRK);
%
% Inputs:
% MRK - marker configuration structure
%
% Outputs:
% EVENT - EEGLAB event structure
%
% Author: Andreas Widmann, University of Leipzig, 2007
% Copyright (C) 2007 Andreas Widmann, University of Leipzig, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% $Id: parsebvmrk.m 37 2007-06-26 12:56:17Z andreaswidmann $
function EVENT = parsebvmrk(MRK)
for idx = 1:size(MRK.markerinfos, 1)
[mrkType mrkDesc EVENT(idx).latency EVENT(idx).duration EVENT(idx).channel EVENT(idx).bvtime] = ...
strread(MRK.markerinfos{idx, 1}, '%s%s%f%d%d%d', 'delimiter', ',');
EVENT(idx).bvmknum = MRK.markerinfos{idx, 2};
if strcmpi(mrkType, 'New Segment') || strcmpi(mrkType, 'DC Correction')
EVENT(idx).type = 'boundary';
else
EVENT(idx).type = char(mrkDesc);
end
EVENT(idx).code = char(mrkType);
EVENT(idx).urevent = idx;
end
|
github
|
lcnbeapp/beapp-master
|
eeg_checkchanlocs.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/eeg_checkchanlocs.m
| 8,655 |
utf_8
|
2664c683e10493731ebda7dfec52968f
|
% eeg_checkchanlocs() - Check the consistency of the channel locations structure
% of an EEGLAB dataset.
%
% Usage:
% >> EEG = eeg_checkchanlocs( EEG, 'key1', value1, 'key2', value2, ... );
% >> [chanlocs chaninfo] = eeg_checkchanlocs( chanlocs, chaninfo, 'key1', value1, 'key2', value2, ... );
%
% Inputs:
% EEG - EEG dataset
% chanlocs - EEG.chanlocs structure
% chaninfo - EEG.chaninfo structure
%
% Outputs:
% EEG - new EEGLAB dataset with updated channel location structures
% EEG.chanlocs, EEG.urchanlocs, EEG.chaninfo
% chanlocs - updated channel location structure
% chaninfo - updated chaninfo structure
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, March 2, 2011
% Copyright (C) SCCN/INC/UCSD, March 2, 2011, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% Hey Arno -- this is a quick fix to make an analysis work for Makoto
% I think the old version had a bug...
function [chans, chaninfo, chanedit]= eeg_checkchanlocs(chans, chaninfo);
if nargin < 1
help eeg_checkchanlocs;
return;
end;
if nargin < 2
chaninfo = [];
end;
processingEEGstruct = 0;
if isfield(chans, 'data')
processingEEGstruct = 1;
tmpEEG = chans;
chans = tmpEEG.chanlocs;
chaninfo = tmpEEG.chaninfo;
end;
if ~isfield(chans, 'datachan')
[chanedit,dummy,complicated] = insertchans(chans, chaninfo);
else
chanedit = chans;
complicated = true;
end;
nosevals = { '+X' '-X' '+Y' '-Y' };
if ~isfield(chaninfo, 'plotrad'), chaninfo.plotrad = []; end;
if ~isfield(chaninfo, 'shrink'), chaninfo.shrink = []; end;
if ~isfield(chaninfo, 'nosedir'), chaninfo.nosedir = nosevals{1}; end;
% handles deprecated fields
% -------------------------
plotrad = [];
if isfield(chanedit, 'plotrad'),
plotrad = chanedit(1).plotrad;
chanedit = rmfield(chanedit, 'plotrad');
if isstr(plotrad) & ~isempty(str2num(plotrad)), plotrad = str2num(plotrad); end;
chaninfo.plotrad = plotrad;
end;
if isfield(chanedit, 'shrink') && ~isempty(chanedit(1).shrink)
shrinkorskirt = 1;
if ~isstr(chanedit(1).shrink)
plotrad = 0.5/(1-chanedit(1).shrink); % convert old values
end;
chanedit = rmfield(chanedit, 'shrink');
chaninfo.plotrad = plotrad;
end;
% set non-existent fields to []
% -----------------------------
fields = { 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' 'sph_radius' 'type' 'ref' 'urchan' };
fieldtype = { 'str' 'num' 'num' 'num' 'num' 'num' 'num' 'num' 'num' 'str' 'str' 'num' };
check_newfields = true; %length(fieldnames(chanedit)) < length(fields);
if ~isempty(chanedit)
for index = 1:length(fields)
if check_newfields && ~isfield(chanedit, fields{index})
% new field
% ---------
if strcmpi(fieldtype{index}, 'num')
chanedit = setfield(chanedit, {1}, fields{index}, []);
else
for indchan = 1:length(chanedit)
chanedit = setfield(chanedit, {indchan}, fields{index}, '');
end;
end;
else
% existing fields
% ---------------
allvals = {chanedit.(fields{index})};
if strcmpi(fieldtype{index}, 'num')
if ~all(cellfun('isclass',allvals,'double'))
numok = cellfun(@isnumeric, allvals);
if any(numok == 0)
for indConvert = find(numok == 0)
chanedit = setfield(chanedit, {indConvert}, fields{index}, []);
end;
end;
end
else
strok = cellfun('isclass', allvals,'char');
if strcmpi(fields{index}, 'labels'), prefix = 'E'; else prefix = ''; end;
if any(strok == 0)
for indConvert = find(strok == 0)
try
strval = [ prefix num2str(getfield(chanedit, {indConvert}, fields{index})) ];
chanedit = setfield(chanedit, {indConvert}, fields{index}, strval);
catch
chanedit = setfield(chanedit, {indConvert}, fields{index}, '');
end;
end;
end;
end;
end;
end;
end;
if ~isequal(fieldnames(chanedit)',fields)
try
chanedit = orderfields(chanedit, fields);
catch, end;
end
% check if duplicate channel label
% --------------------------------
if isfield(chanedit, 'labels')
tmp = sort({chanedit.labels});
if any(strcmp(tmp(1:end-1),tmp(2:end)))
disp('Warning: some channels have the same label');
end
end;
% check for empty channel label
% -----------------------------
if isfield(chanedit, 'labels')
indEmpty = find(cellfun(@isempty, {chanedit.labels}));
if ~isempty(indEmpty)
tmpWarning = warning('backtrace');
warning backtrace off;
warning('channel labels should not be empty, creating unique labels');
warning(tmpWarning);
for index = indEmpty
chanedit(index).labels = sprintf('E%d', index);
end;
end;
end;
% remove fields
% -------------
if isfield(chanedit, 'sph_phi_besa' ), chanedit = rmfield(chanedit, 'sph_phi_besa'); end;
if isfield(chanedit, 'sph_theta_besa'), chanedit = rmfield(chanedit, 'sph_theta_besa'); end;
% reconstruct the chans structure
% -------------------------------
if complicated
[chans chaninfo.nodatchans] = getnodatchan( chanedit );
if ~isfield(chaninfo, 'nodatchans'), chaninfo.nodatchans = []; end;
if isempty(chanedit)
for iField = 1:length(fields)
chanedit = setfield(chanedit, fields{iField}, []);
end;
end;
else
chans = rmfield(chanedit,'datachan');
chaninfo.nodatchans = [];
end
if processingEEGstruct
tmpEEG.chanlocs = chans;
tmpEEG.chaninfo = chaninfo;
chans = tmpEEG;
end;
% ---------------------------------------------
% separate data channels from non-data channels
% ---------------------------------------------
function [chans, fidsval] = getnodatchan(chans)
if isfield(chans,'datachan')
[chans(cellfun('isempty',{chans.datachan})).datachan] = deal(0);
fids = [chans.datachan] == 0;
fidsval = chans(fids);
chans = rmfield(chans(~fids),'datachan');
else
fids = [];
end;
% ----------------------------------------
% fuse data channels and non-data channels
% ----------------------------------------
function [chans, chaninfo,complicated] = insertchans(chans, chaninfo, nchans)
if nargin < 3, nchans = length(chans); end;
[chans.datachan] = deal(1);
complicated = false; % whether we need complicated treatment of datachans & co further down the road.....
if isfield(chans,'type')
mask = strcmpi({chans.type},'FID') | strcmpi({chans.type},'IGNORE');
if any(mask)
[chans(mask).datachan] = deal(0);
complicated = true;
end
end
if length(chans) > nchans & nchans ~= 0 % reference at the end of the structure
chans(end).datachan = 0;
complicated = true;
end;
if isfield(chaninfo, 'nodatchans')
if ~isempty(chaninfo.nodatchans) && isstruct(chaninfo.nodatchans)
chanlen = length(chans);
for index = 1:length(chaninfo.nodatchans)
fields = fieldnames( chaninfo.nodatchans );
ind = chanlen+index;
for f = 1:length( fields )
chans = setfield(chans, { ind }, fields{f}, getfield( chaninfo.nodatchans, { index }, fields{f}));
end;
chans(ind).datachan = 0;
complicated = true;
end;
chaninfo = rmfield(chaninfo, 'nodatchans');
% put these channels first
% ------------------------
% tmp = chans(chanlen+1:end);
% chans(length(tmp)+1:end) = chans(1:end-length(tmp));
% chans(1:length(tmp)) = tmp;
end;
end;
|
github
|
lcnbeapp/beapp-master
|
eeg_epochformat.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/eeg_epochformat.m
| 7,674 |
utf_8
|
b6227100d8d67253534322618e4b81fa
|
% eeg_epochformat() - Convert the epoch information of a dataset from struct
% to array or vice versa.
%
% Usage: >> [epochsout fields] = eeg_epochformat( epochs, 'format', fields, events );
%
% Input:
% epochs - epoch numerical or cell array or epoch structure
% format - ['struct'|'array'] convert epoch array to structure and epoch
% structure to array.
% fields - [optional] cell array of strings containing the names of
% the epoch struct fields. If this field is empty, it uses the
% following list for the names of the fields { 'var1' 'var2' ... }.
% For structure conversion, this field helps export a given
% event type. If this field is left empty, the time locking
% event for each epoch is exported.
% events - numerical array of event indices associated with each epoch.
% For array conversion, this field is ignored.
%
% Outputs:
% epochsout - output epoch array or structure
% fields - output cell array with the name of the fields
%
% Epoch format:
% struct - Epoch information is organised as an array of structs
% array - Epoch information is organised as an 2-d array of numbers,
% each column representing a user-defined variable (the
% order of the variable is a function of its order in the
% struct format).
%
% Note: 1) The epoch structure is defined only for epoched data.
% 2) The epoch 'struct' format is more comprehensible.
% For instance, to see all the properties of epoch i,
% type >> EEG.epoch(i)
% Unfortunately, structures are awkward for expert users to deal
% with from the command line (Ex: To get an array of 'var1' values,
% >> celltomat({EEG.epoch(:).var1})')
% In array format, asuming 'var1' is the first variable
% declared, the same information is obtained by
% >> EEG.epoch(:,1)
% 3) This function automatically updates the 'epochfields'
% cell array depending on the format.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 12 Feb 2002
%
% See also: eeglab()
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) from eeg_eventformat.m,
% Arnaud Delorme, CNL / Salk Institute, 12 Feb 2002, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% $Log: eeg_epochformat.m,v $
% Revision 1.4 2005/05/24 16:57:09 arno
% cell2mat
%
% Revision 1.3 2003/07/20 19:32:20 scott
% typos
%
% Revision 1.2 2002/04/21 01:10:35 scott
% *** empty log message ***
%
% Revision 1.1 2002/04/05 17:32:13 jorn
% Initial revision
%
% 03/13/02 added field arrays options -ad
function [ epoch, fields, epocheventout] = eeg_epochformat( epoch, format, fields, epochevent);
if nargin < 2
help eeg_epochformat;
return;
end;
if nargin < 3
fields = {};
end;
epocheventout = [];
switch format
case 'struct'
if ~isempty(epoch) & ~isstruct(epoch)
fields = getnewfields( fields, size(epoch,2) - length(fields));
% generate the structure
% ----------------------
command = 'epoch = struct(';
for index = 1:length(fields)
if iscell(epoch)
command = [ command '''' fields{index} ''', epoch(:,' num2str(index) ')'',' ];
else
command = [ command '''' fields{index} ''', mattocell( epoch(:,' num2str(index) ')'',' ...
'[1], ones(1,size(epoch,1))),' ];
end;
end;
eval( [command(1:end-1) ');' ] );
if exist('epochevent') == 1
for index = 1:size(epoch,2)
if iscell(epochevent)
epoch(index).event = epochevent{index};
else
epoch(index).event = epochevent(index);
end;
end;
end;
end
case 'array'
if isstruct(epoch)
% note that the STUDY std_maketrialinfo also gets the epoch info for the
% time locking event
selectedType = fields;
if iscell(fields) && ~isempty(fields), selectedType = fields{1}; end;
fields = fieldnames( epoch );
eval( [ 'values = { epoch.' fields{1} ' };' ]);
if any(cellfun(@length, values) > 1)
if ~isfield(epoch, 'eventlatency')
error('eventlatency field not present in data epochs');
end;
if isempty(selectedType)
% find indices of time locking events
for index = 1:length(epoch)
epochlat = [ epoch(index).eventlatency{:} ];
tmpevent = find( abs(epochlat) < 0.02 );
if isempty(tmpevent)
error('time locking event missing, cannot convert to array');
end;
epochSubIndex(index) = tmpevent;
end;
else
% find indices of specific event type (if several take the
% first one
for index = 1:length(epoch)
epochtype = epoch(index).eventtype;
tmpeventind = strmatch( selectedType, epochtype );
if length(tmpeventind) > 1
fprintf('Warning: epoch %d has several events of "type" %s, taking the fist one\n', index, selectedType);
end;
if isempty(tmpeventind)
epochSubIndex(index) = NaN;
else epochSubIndex(index) = tmpeventind(1);
end;
end;
end;
else
epochSubIndex = ones(1, length(epoch));
end;
% copy values to array
tmp = cell( length(epoch), length( fields ));
for index = 1:length( fields )
for trial = 1:length(epoch)
tmpval = getfield(epoch, {trial}, fields{index});
if isnan(epochSubIndex(trial))
tmp(trial, index) = { NaN };
elseif iscell(tmpval)
tmp(trial, index) = tmpval(epochSubIndex(trial));
elseif ~ischar(tmpval)
tmp(trial, index) = { tmpval(epochSubIndex(trial)) };
else tmp(trial, index) = { tmpval };
end;
end;
end;
epoch = tmp;
end;
otherwise, error('unrecognised format');
end;
return;
% create new field names
% ----------------------
function epochfield = getnewfields( epochfield, nbfields )
count = 1;
if nbfields > 0
while nbfields > 0
if isempty( strmatch([ 'var' int2str(count) ], epochfield ) )
epochfield = { epochfield{:} [ 'var' int2str(count) ] };
nbfields = nbfields-1;
else count = count+1;
end;
end;
else
epochfield = epochfield(1:end+nbfields);
end;
return;
|
github
|
lcnbeapp/beapp-master
|
listdlg2.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/listdlg2.m
| 3,771 |
utf_8
|
a0820fcb823bcb9968afa377c5582498
|
% listdlg2() - listdlg function clone with coloring and help for
% eeglab().
%
% Usage: same as listdlg()
%
% Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 16 August 2002
%
% See also: inputdlg2(), errordlg2(), supergui(), inputgui()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [vals, okornot, strval] = listdlg2(varargin);
if nargin < 2
help listdlg2;
return;
end;
for index = 1:length(varargin)
if iscell(varargin{index}), varargin{index} = { varargin{index} }; end;
if isstr(varargin{index}), varargin{index} = lower(varargin{index}); end;
end;
g = struct(varargin{:});
try, g.promptstring; catch, g.promptstring = ''; end;
try, g.liststring; catch, error('''liststring'' must be defined'); end;
try, g.selectionmode; catch, g.selectionmode = 'multiple'; end;
try, g.listsize; catch, g.listsize = []; end;
try, g.initialvalue; catch, g.initialvalue = []; end;
try, g.name; catch, g.name = ''; end;
fig = figure('visible', 'off');
set(gcf, 'name', g.name);
if isstr(g.liststring)
allstr = g.liststring;
else
allstr = '';
for index = 1:length(g.liststring)
allstr = [ allstr '|' g.liststring{index} ];
end;
allstr = allstr(2:end);
end;
geometry = {[1] [1 1]};
geomvert = [min(length(g.liststring), 10) 1];
if ~strcmpi(g.selectionmode, 'multiple') | ...
(iscell(g.liststring) & length(g.liststring) == 1) | ...
(isstr (g.liststring) & size (g.liststring,1) == 1 & isempty(find(g.liststring == '|')))
if isempty(g.initialvalue), g.initialvalue = 1; end;
minval = 1;
maxval = 1;
else
minval = 0;
maxval = 2;
end;
listui = {{ 'Style', 'listbox', 'tag', 'listboxvals', 'string', allstr, 'max', maxval, 'min', minval } ...
{ 'Style', 'pushbutton', 'string', 'Cancel', 'callback', ['set(gcbf, ''userdata'', ''cancel'');'] } ...
{ 'Style', 'pushbutton', 'string', 'Ok' , 'callback', ['set(gcbf, ''userdata'', ''ok'');'] } };
if ~isempty(g.promptstring)
geometry = {[1] geometry{:}};
geomvert = [1 geomvert];
listui = { { 'Style', 'text', 'string', g.promptstring } listui{:}};
end;
[tmp tmp2 allobj] = supergui( fig, geometry, geomvert, listui{:} );
% assign value to listbox
% must be done after creating it
% ------------------------------
lstbox = findobj(fig, 'tag', 'listboxvals');
set(lstbox, 'value', g.initialvalue);
if ~isempty(g.listsize)
pos = get(gcf, 'position');
set(gcf, 'position', [ pos(1:2) g.listsize]);
end;
h = findobj( 'parent', fig, 'tag', 'listboxvals');
okornot = 0;
strval = '';
vals = [];
figure(fig);
drawnow;
waitfor( fig, 'userdata');
try,
vals = get(h, 'value');
strval = '';
if iscell(g.liststring)
for index = vals
strval = [ strval ' ' g.liststring{index} ];
end;
else
for index = vals
strval = [ strval ' ' g.liststring(index,:) ];
end;
end;
strval = strval(2:end);
if strcmp(get(fig, 'userdata'), 'cancel')
okornot = 0;
else
okornot = 1;
end;
close(fig);
drawnow;
end;
|
github
|
lcnbeapp/beapp-master
|
mattocell.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/mattocell.m
| 1,311 |
utf_8
|
bb1357cab390093724fa7887f66ebef3
|
% mattocell() - convert matrix to cell array
%
% Usage: >> C = mattocell( M );
%
% Author: Arnaud Delorme, CNL / Salk Institute, Jan 25 2002
%
% Note: this function overload the nnet toolbox function mattocell,
% but does not have all its capacities. You can delete the current
% function if you have the toolbox.
% Copyright (C) Jan 25 2002 Arnaud Delorme, CNL / Salk Institute
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function C = mattocell( M, varargin );
if nargin < 1
help mattocell;
return;
end;
if isempty(M)
C = [];
return;
end;
C = cell(size(M));
for i=1:size(M,1)
for j=1:size(M,2)
C{i,j} = M(i,j);
end;
end;
|
github
|
lcnbeapp/beapp-master
|
pop_chansel.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/pop_chansel.m
| 5,372 |
utf_8
|
4773a5a96563eba18577995430d93045
|
% pop_chansel() - pop up a graphic interface to select channels
%
% Usage:
% >> [chanlist] = pop_chansel(chanstruct); % a window pops up
% >> [chanlist strchannames cellchannames] = ...
% pop_chansel(chanstruct, 'key', 'val', ...);
%
% Inputs:
% chanstruct - channel structure. See readlocs()
%
% Optional input:
% 'withindex' - ['on'|'off'] add index to each entry. May also a be
% an array of indices
% 'select' - selection of channel. Can take as input all the
% outputs of this function.
% 'selectionmode' - selection mode 'multiple' or 'single'. See listdlg2().
%
% Output:
% chanlist - indices of selected channels
% strchannames - names of selected channel names in a concatenated string
% (channel names are separated by space characters)
% cellchannames - names of selected channel names in a cell array
%
% Author: Arnaud Delorme, CNL / Salk Institute, 3 March 2003
% Copyright (C) 3 March 2003 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [chanlist,chanliststr, allchanstr] = pop_chansel(chans, varargin);
if nargin < 1
help pop_chansel;
return;
end;
if isempty(chans), disp('Empty input'); return; end;
if isnumeric(chans),
for c = 1:length(chans)
newchans{c} = num2str(chans(c));
end;
chans = newchans;
end;
chanlist = [];
chanliststr = {};
allchanstr = '';
g = finputcheck(varargin, { 'withindex' { 'integer';'string' } { [] {'on' 'off'} } 'off';
'select' { 'cell';'string';'integer' } [] [];
'selectionmode' 'string' { 'single';'multiple' } 'multiple'});
if isstr(g), error(g); end;
if ~isstr(g.withindex), chan_indices = g.withindex; g.withindex = 'on';
else chan_indices = 1:length(chans);
end;
% convert selection to integer
% ----------------------------
if isstr(g.select) & ~isempty(g.select)
g.select = parsetxt(g.select);
end;
if iscell(g.select) & ~isempty(g.select)
if isstr(g.select{1})
tmplower = lower( chans );
for index = 1:length(g.select)
matchind = strmatch(lower(g.select{index}), tmplower, 'exact');
if ~isempty(matchind), g.select{index} = matchind;
else error( [ 'Cannot find ''' g.select{index} '''' ] );
end;
end;
end;
g.select = [ g.select{:} ];
end;
if ~isnumeric( g.select ), g.select = []; end;
% add index to channel name
% -------------------------
tmpstr = {chans};
if isnumeric(chans{1})
tmpstr = [ chans{:} ];
tmpfieldnames = cell(1, length(tmpstr));
for index=1:length(tmpstr),
if strcmpi(g.withindex, 'on')
tmpfieldnames{index} = [ num2str(chan_indices(index)) ' - ' num2str(tmpstr(index)) ];
else
tmpfieldnames{index} = num2str(tmpstr(index));
end;
end;
else
tmpfieldnames = chans;
if strcmpi(g.withindex, 'on')
for index=1:length(tmpfieldnames),
tmpfieldnames{index} = [ num2str(chan_indices(index)) ' - ' tmpfieldnames{index} ];
end;
end;
end;
[chanlist,tmp,chanliststr] = listdlg2('PromptString',strvcat('(use shift|Ctrl to', 'select several)'), ...
'ListString', tmpfieldnames, 'initialvalue', g.select, 'selectionmode', g.selectionmode);
if tmp == 0
chanlist = [];
chanliststr = '';
return;
else
allchanstr = chans(chanlist);
end;
% test for spaces
% ---------------
spacepresent = 0;
if ~isnumeric(chans{1})
tmpstrs = [ allchanstr{:} ];
if ~isempty( find(tmpstrs == ' ')) | ~isempty( find(tmpstrs == 9))
spacepresent = 1;
end;
end;
% get concatenated string (if index)
% -----------------------
if strcmpi(g.withindex, 'on') | spacepresent
if isnumeric(chans{1})
chanliststr = num2str(celltomat(allchanstr));
else
chanliststr = '';
for index = 1:length(allchanstr)
if spacepresent
chanliststr = [ chanliststr '''' allchanstr{index} ''' ' ];
else
chanliststr = [ chanliststr allchanstr{index} ' ' ];
end;
end;
chanliststr = chanliststr(1:end-1);
end;
end;
return;
|
github
|
lcnbeapp/beapp-master
|
loadcnt.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/loadcnt.m
| 23,166 |
utf_8
|
3629cdf2a890ef76f423f15fff965b3a
|
% loadcnt() - Load a Neuroscan continuous signal file.
%
% Usage:
% >> cnt = loadcnt(file, varargin)
%
% Inputs:
% filename - name of the file with extension
%
% Optional inputs:
% 't1' - start at time t1, default 0. Warning, events latency
% might be innacurate (this is an open issue).
% 'sample1' - start at sample1, default 0, overrides t1. Warning,
% events latency might be innacurate.
% 'lddur' - duration of segment to load, default = whole file
% 'ldnsamples' - number of samples to load, default = whole file,
% overrides lddur
% 'scale' - ['on'|'off'] scale data to microvolt (default:'on')
% 'dataformat' - ['int16'|'int32'] default is 'int16' for 16-bit data.
% Use 'int32' for 32-bit data.
% 'blockread' - [integer] by default it is automatically determined
% from the file header, though sometimes it finds an
% incorect value, so you may want to enter a value manually
% here (1 is the most standard value).
% 'memmapfile' - ['memmapfile_name'] use this option if the .cnt file
% is too large to read in conventially. The suffix of
% the memmapfile_name must be .fdt. The memmapfile
% functions process files based on their suffix, and an
% error will occur if you use a different suffix.
%
% Outputs:
% cnt - structure with the continuous data and other informations
% cnt.header
% cnt.electloc
% cnt.data
% cnt.tag
%
% Authors: Sean Fitzgibbon, Arnaud Delorme, 2000-
%
% Note: function original name was load_scan41.m
%
% Known limitations:
% For more see http://www.cnl.salk.edu/~arno/cntload/index.html
% Copyright (C) 2000 Sean Fitzgibbon, <[email protected]>
% Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [f,lab,ev2p] = loadcnt(filename,varargin)
if ~isempty(varargin)
r=struct(varargin{:});
else r = [];
end;
try, r.t1; catch, r.t1=0; end
try, r.sample1; catch, r.sample1=[]; end
try, r.lddur; catch, r.lddur=[]; end
try, r.ldnsamples; catch, r.ldnsamples=[]; end
try, r.scale; catch, r.scale='on'; end
try, r.blockread; catch, r.blockread = []; end
try, r.dataformat; catch, r.dataformat = 'auto'; end
try, r.memmapfile; catch, r.memmapfile = ''; end
sizeEvent1 = 8 ; %%% 8 bytes for Event1
sizeEvent2 = 19 ; %%% 19 bytes for Event2
sizeEvent3 = 19 ; %%% 19 bytes for Event3
type='cnt';
if nargin ==1
scan=0;
end
fid = fopen(filename,'r', 'l');
disp(['Loading file ' filename ' ...'])
h.rev = fread(fid,12,'char');
h.nextfile = fread(fid,1,'long');
h.prevfile = fread(fid,1,'ulong');
h.type = fread(fid,1,'char');
h.id = fread(fid,20,'char');
h.oper = fread(fid,20,'char');
h.doctor = fread(fid,20,'char');
h.referral = fread(fid,20,'char');
h.hospital = fread(fid,20,'char');
h.patient = fread(fid,20,'char');
h.age = fread(fid,1,'short');
h.sex = fread(fid,1,'char');
h.hand = fread(fid,1,'char');
h.med = fread(fid,20, 'char');
h.category = fread(fid,20, 'char');
h.state = fread(fid,20, 'char');
h.label = fread(fid,20, 'char');
h.date = fread(fid,10, 'char');
h.time = fread(fid,12, 'char');
h.mean_age = fread(fid,1,'float');
h.stdev = fread(fid,1,'float');
h.n = fread(fid,1,'short');
h.compfile = fread(fid,38,'char');
h.spectwincomp = fread(fid,1,'float');
h.meanaccuracy = fread(fid,1,'float');
h.meanlatency = fread(fid,1,'float');
h.sortfile = fread(fid,46,'char');
h.numevents = fread(fid,1,'int');
h.compoper = fread(fid,1,'char');
h.avgmode = fread(fid,1,'char');
h.review = fread(fid,1,'char');
h.nsweeps = fread(fid,1,'ushort');
h.compsweeps = fread(fid,1,'ushort');
h.acceptcnt = fread(fid,1,'ushort');
h.rejectcnt = fread(fid,1,'ushort');
h.pnts = fread(fid,1,'ushort');
h.nchannels = fread(fid,1,'ushort');
h.avgupdate = fread(fid,1,'ushort');
h.domain = fread(fid,1,'char');
h.variance = fread(fid,1,'char');
h.rate = fread(fid,1,'ushort'); % A USER CLAIMS THAT SAMPLING RATE CAN BE
h.scale = fread(fid,1,'double'); % FRACTIONAL IN NEUROSCAN WHICH IS
h.veogcorrect = fread(fid,1,'char'); % OBVIOUSLY NOT POSSIBLE HERE (BUG 606)
h.heogcorrect = fread(fid,1,'char');
h.aux1correct = fread(fid,1,'char');
h.aux2correct = fread(fid,1,'char');
h.veogtrig = fread(fid,1,'float');
h.heogtrig = fread(fid,1,'float');
h.aux1trig = fread(fid,1,'float');
h.aux2trig = fread(fid,1,'float');
h.heogchnl = fread(fid,1,'short');
h.veogchnl = fread(fid,1,'short');
h.aux1chnl = fread(fid,1,'short');
h.aux2chnl = fread(fid,1,'short');
h.veogdir = fread(fid,1,'char');
h.heogdir = fread(fid,1,'char');
h.aux1dir = fread(fid,1,'char');
h.aux2dir = fread(fid,1,'char');
h.veog_n = fread(fid,1,'short');
h.heog_n = fread(fid,1,'short');
h.aux1_n = fread(fid,1,'short');
h.aux2_n = fread(fid,1,'short');
h.veogmaxcnt = fread(fid,1,'short');
h.heogmaxcnt = fread(fid,1,'short');
h.aux1maxcnt = fread(fid,1,'short');
h.aux2maxcnt = fread(fid,1,'short');
h.veogmethod = fread(fid,1,'char');
h.heogmethod = fread(fid,1,'char');
h.aux1method = fread(fid,1,'char');
h.aux2method = fread(fid,1,'char');
h.ampsensitivity = fread(fid,1,'float');
h.lowpass = fread(fid,1,'char');
h.highpass = fread(fid,1,'char');
h.notch = fread(fid,1,'char');
h.autoclipadd = fread(fid,1,'char');
h.baseline = fread(fid,1,'char');
h.offstart = fread(fid,1,'float');
h.offstop = fread(fid,1,'float');
h.reject = fread(fid,1,'char');
h.rejstart = fread(fid,1,'float');
h.rejstop = fread(fid,1,'float');
h.rejmin = fread(fid,1,'float');
h.rejmax = fread(fid,1,'float');
h.trigtype = fread(fid,1,'char');
h.trigval = fread(fid,1,'float');
h.trigchnl = fread(fid,1,'char');
h.trigmask = fread(fid,1,'short');
h.trigisi = fread(fid,1,'float');
h.trigmin = fread(fid,1,'float');
h.trigmax = fread(fid,1,'float');
h.trigdir = fread(fid,1,'char');
h.autoscale = fread(fid,1,'char');
h.n2 = fread(fid,1,'short');
h.dir = fread(fid,1,'char');
h.dispmin = fread(fid,1,'float');
h.dispmax = fread(fid,1,'float');
h.xmin = fread(fid,1,'float');
h.xmax = fread(fid,1,'float');
h.automin = fread(fid,1,'float');
h.automax = fread(fid,1,'float');
h.zmin = fread(fid,1,'float');
h.zmax = fread(fid,1,'float');
h.lowcut = fread(fid,1,'float');
h.highcut = fread(fid,1,'float');
h.common = fread(fid,1,'char');
h.savemode = fread(fid,1,'char');
h.manmode = fread(fid,1,'char');
h.ref = fread(fid,10,'char');
h.rectify = fread(fid,1,'char');
h.displayxmin = fread(fid,1,'float');
h.displayxmax = fread(fid,1,'float');
h.phase = fread(fid,1,'char');
h.screen = fread(fid,16,'char');
h.calmode = fread(fid,1,'short');
h.calmethod = fread(fid,1,'short');
h.calupdate = fread(fid,1,'short');
h.calbaseline = fread(fid,1,'short');
h.calsweeps = fread(fid,1,'short');
h.calattenuator = fread(fid,1,'float');
h.calpulsevolt = fread(fid,1,'float');
h.calpulsestart = fread(fid,1,'float');
h.calpulsestop = fread(fid,1,'float');
h.calfreq = fread(fid,1,'float');
h.taskfile = fread(fid,34,'char');
h.seqfile = fread(fid,34,'char');
h.spectmethod = fread(fid,1,'char');
h.spectscaling = fread(fid,1,'char');
h.spectwindow = fread(fid,1,'char');
h.spectwinlength = fread(fid,1,'float');
h.spectorder = fread(fid,1,'char');
h.notchfilter = fread(fid,1,'char');
h.headgain = fread(fid,1,'short');
h.additionalfiles = fread(fid,1,'int');
h.unused = fread(fid,5,'char');
h.fspstopmethod = fread(fid,1,'short');
h.fspstopmode = fread(fid,1,'short');
h.fspfvalue = fread(fid,1,'float');
h.fsppoint = fread(fid,1,'short');
h.fspblocksize = fread(fid,1,'short');
h.fspp1 = fread(fid,1,'ushort');
h.fspp2 = fread(fid,1,'ushort');
h.fspalpha = fread(fid,1,'float');
h.fspnoise = fread(fid,1,'float');
h.fspv1 = fread(fid,1,'short');
h.montage = fread(fid,40,'char');
h.eventfile = fread(fid,40,'char');
h.fratio = fread(fid,1,'float');
h.minor_rev = fread(fid,1,'char');
h.eegupdate = fread(fid,1,'short');
h.compressed = fread(fid,1,'char');
h.xscale = fread(fid,1,'float');
h.yscale = fread(fid,1,'float');
h.xsize = fread(fid,1,'float');
h.ysize = fread(fid,1,'float');
h.acmode = fread(fid,1,'char');
h.commonchnl = fread(fid,1,'uchar');
h.xtics = fread(fid,1,'char');
h.xrange = fread(fid,1,'char');
h.ytics = fread(fid,1,'char');
h.yrange = fread(fid,1,'char');
h.xscalevalue = fread(fid,1,'float');
h.xscaleinterval = fread(fid,1,'float');
h.yscalevalue = fread(fid,1,'float');
h.yscaleinterval = fread(fid,1,'float');
h.scaletoolx1 = fread(fid,1,'float');
h.scaletooly1 = fread(fid,1,'float');
h.scaletoolx2 = fread(fid,1,'float');
h.scaletooly2 = fread(fid,1,'float');
h.port = fread(fid,1,'short');
h.numsamples = fread(fid,1,'ulong');
h.filterflag = fread(fid,1,'char');
h.lowcutoff = fread(fid,1,'float');
h.lowpoles = fread(fid,1,'short');
h.highcutoff = fread(fid,1,'float');
h.highpoles = fread(fid,1,'short');
h.filtertype = fread(fid,1,'char');
h.filterdomain = fread(fid,1,'char');
h.snrflag = fread(fid,1,'char');
h.coherenceflag = fread(fid,1,'char');
h.continuoustype = fread(fid,1,'char');
h.eventtablepos = fread(fid,1,'ulong');
h.continuousseconds = fread(fid,1,'float');
h.channeloffset = fread(fid,1,'long');
h.autocorrectflag = fread(fid,1,'char');
h.dcthreshold = fread(fid,1,'uchar');
for n = 1:h.nchannels
e(n).lab = deblank(char(fread(fid,10,'char')'));
e(n).reference = fread(fid,1,'char');
e(n).skip = fread(fid,1,'char');
e(n).reject = fread(fid,1,'char');
e(n).display = fread(fid,1,'char');
e(n).bad = fread(fid,1,'char');
e(n).n = fread(fid,1,'ushort');
e(n).avg_reference = fread(fid,1,'char');
e(n).clipadd = fread(fid,1,'char');
e(n).x_coord = fread(fid,1,'float');
e(n).y_coord = fread(fid,1,'float');
e(n).veog_wt = fread(fid,1,'float');
e(n).veog_std = fread(fid,1,'float');
e(n).snr = fread(fid,1,'float');
e(n).heog_wt = fread(fid,1,'float');
e(n).heog_std = fread(fid,1,'float');
e(n).baseline = fread(fid,1,'short');
e(n).filtered = fread(fid,1,'char');
e(n).fsp = fread(fid,1,'char');
e(n).aux1_wt = fread(fid,1,'float');
e(n).aux1_std = fread(fid,1,'float');
e(n).senstivity = fread(fid,1,'float');
e(n).gain = fread(fid,1,'char');
e(n).hipass = fread(fid,1,'char');
e(n).lopass = fread(fid,1,'char');
e(n).page = fread(fid,1,'uchar');
e(n).size = fread(fid,1,'uchar');
e(n).impedance = fread(fid,1,'uchar');
e(n).physicalchnl = fread(fid,1,'uchar');
e(n).rectify = fread(fid,1,'char');
e(n).calib = fread(fid,1,'float');
end
% finding if 32-bits of 16-bits file
% ----------------------------------
begdata = ftell(fid);
if strcmpi(r.dataformat, 'auto')
r.dataformat = 'int16';
if (h.nextfile > 0)
fseek(fid,h.nextfile+52,'bof');
is32bit = fread(fid,1,'char');
if (is32bit == 1)
r.dataformat = 'int32';
end;
fseek(fid,begdata,'bof');
end;
end;
enddata = h.eventtablepos; % after data
if strcmpi(r.dataformat, 'int16')
nums = (enddata-begdata)/h.nchannels/2;
else nums = (enddata-begdata)/h.nchannels/4;
end;
% number of sample to read
% ------------------------
if ~isempty(r.sample1)
r.t1 = r.sample1/h.rate;
else
r.sample1 = r.t1*h.rate;
end;
if strcmpi(r.dataformat, 'int16')
startpos = r.t1*h.rate*2*h.nchannels;
else startpos = r.t1*h.rate*4*h.nchannels;
end;
if isempty(r.ldnsamples)
if ~isempty(r.lddur)
r.ldnsamples = round(r.lddur*h.rate);
else r.ldnsamples = nums;
end;
end;
% FIELDTRIP BUGFIX #1412
% In some cases, the orig.header.numsamples = 0, and the output number of samples is wrong.
% In the previous version of loadcnt.m the orig.header.nums field was used (instead of numsamples), which was changed in r5380 to fix bug #1348.
% This bug (1348) was due to loadcnt.m being updated to the most recent version (from neuroscan), which removed the nums field in favor of using numsamples.
% Below is a workaround for when numsamples is incorrect (bug 1412). The reason is unknown (it looks like a neuroscan data-file specific bug).
% I re-added the nums field to loadcnt.m so that it can be used in ft_read_header.m.
% -roevdmei
h.nums = nums;
% channel offset
% --------------
if ~isempty(r.blockread)
h.channeloffset = r.blockread;
end;
if h.channeloffset > 1
fprintf('WARNING: reading data in blocks of %d, if this fails, try using option "''blockread'', 1"\n', ...
h.channeloffset);
end;
disp('Reading data .....')
if type == 'cnt'
% while (ftell(fid) +1 < h.eventtablepos)
%d(:,i)=fread(fid,h.nchannels,'int16');
%end
fseek(fid, startpos, 0);
% **** This marks the beginning of the code modified for reading
% large .cnt files
% Switched to r.memmapfile for continuity. Check to see if the
% variable exists. If it does, then the user has indicated the
% file is too large to be processed in memory. If the variable
% is blank, the file is processed in memory.
if (~isempty(r.memmapfile))
% open a file for writing
foutid = fopen(r.memmapfile, 'w') ;
% This portion of the routine reads in a section of the EEG file
% and then writes it out to the harddisk.
samples_left = h.nchannels * r.ldnsamples ;
% the size of the data block to be read is limited to 4M
% samples. This equates to 16MB and 32MB of memory for
% 16 and 32 bit files, respectively.
data_block = 4000000 ;
max_rows = data_block / h.nchannels ;
%warning off ;
max_written = h.nchannels * uint32(max_rows) ;
%warning on ;
% This while look tracks the remaining samples. The
% data is processed in chunks rather than put into
% memory whole.
while (samples_left > 0)
% Check to see if the remaining data is smaller than
% the general processing block by looking at the
% remaining number of rows.
to_read = max_rows ;
if (data_block > samples_left)
to_read = samples_left / h.nchannels ;
end ;
% Read data in a relatively small chunk
temp_dat = fread(fid, [h.nchannels to_read], r.dataformat) ;
% The data is then scaled using the original routine.
% In the original routine, the entire data set was scaled
% after being read in. For this version, scaling occurs
% after every chunk is read.
if strcmpi(r.scale, 'on')
disp('Scaling data .....')
%%% scaling to microvolts
for i=1:h.nchannels
bas=e(i).baseline;sen=e(i).senstivity;cal=e(i).calib;
mf=sen*(cal/204.8);
temp_dat(i,:)=(temp_dat(i,:)-bas).*mf;
end
end
% Write out data in float32 form to the file name
% supplied by the user.
written = fwrite (foutid, temp_dat, 'float32') ;
if (written ~= max_written)
samples_left = 0 ;
else
samples_left = samples_left - written ;
end ;
end ;
fclose (foutid) ;
% Set the dat variable. This gets used later by other
% EEGLAB functions.
dat = r.memmapfile ;
% This variable tracks how the data should be read.
bReadIntoMemory = false ;
else
% The memmapfile variable is empty, read into memory.
bReadIntoMemory = true ;
end
% This ends the modifications made to read large files.
% Everything contained within the following if statement is the
% original code.
if (bReadIntoMemory == true)
if h.channeloffset <= 1
dat=fread(fid, [h.nchannels Inf], r.dataformat);
if size(dat,2) < r.ldnsamples
dat=single(dat);
r.ldnsamples = size(dat,2);
else
dat=single(dat(:,1:r.ldnsamples));
end;
else
h.channeloffset = h.channeloffset/2;
% reading data in blocks
dat = zeros( h.nchannels, r.ldnsamples, 'single');
dat(:, 1:h.channeloffset) = fread(fid, [h.channeloffset h.nchannels], r.dataformat)';
counter = 1;
while counter*h.channeloffset < r.ldnsamples
dat(:, counter*h.channeloffset+1:counter*h.channeloffset+h.channeloffset) = ...
fread(fid, [h.channeloffset h.nchannels], r.dataformat)';
counter = counter + 1;
end;
end ;
% ftell(fid)
if strcmpi(r.scale, 'on')
disp('Scaling data .....')
%%% scaling to microvolts
for i=1:h.nchannels
bas=e(i).baseline;sen=e(i).senstivity;cal=e(i).calib;
mf=sen*(cal/204.8);
dat(i,:)=(dat(i,:)-bas).*mf;
end % end for i=1:h.nchannels
end; % end if (strcmpi(r.scale, 'on')
end ;
ET_offset = (double(h.prevfile) * (2^32)) + double(h.eventtablepos); % prevfile contains high order bits of event table offset, eventtablepos contains the low order bits
fseek(fid, ET_offset, 'bof');
disp('Reading Event Table...')
eT.teeg = fread(fid,1,'uchar');
eT.size = fread(fid,1,'ulong');
eT.offset = fread(fid,1,'ulong');
if eT.teeg==2
nevents=eT.size/sizeEvent2;
if nevents > 0
ev2(nevents).stimtype = [];
for i=1:nevents
ev2(i).stimtype = fread(fid,1,'ushort');
ev2(i).keyboard = fread(fid,1,'char');
temp = fread(fid,1,'uint8');
ev2(i).keypad_accept = bitand(15,temp);
ev2(i).accept_ev1 = bitshift(temp,-4);
ev2(i).offset = fread(fid,1,'long');
ev2(i).type = fread(fid,1,'short');
ev2(i).code = fread(fid,1,'short');
ev2(i).latency = fread(fid,1,'float');
ev2(i).epochevent = fread(fid,1,'char');
ev2(i).accept = fread(fid,1,'char');
ev2(i).accuracy = fread(fid,1,'char');
end
else
ev2 = [];
end;
elseif eT.teeg==3 % type 3 is similar to type 2 except the offset field encodes the global sample frame
nevents=eT.size/sizeEvent3;
if nevents > 0
ev2(nevents).stimtype = [];
if r.dataformat == 'int32'
bytes_per_samp = 4; % I only have 32 bit data, unable to check whether this is necessary,
else % perhaps there is no type 3 file with 16 bit data
bytes_per_samp = 2;
end
for i=1:nevents
ev2(i).stimtype = fread(fid,1,'ushort');
ev2(i).keyboard = fread(fid,1,'char');
temp = fread(fid,1,'uint8');
ev2(i).keypad_accept = bitand(15,temp);
ev2(i).accept_ev1 = bitshift(temp,-4);
os = fread(fid,1,'ulong');
ev2(i).offset = os * bytes_per_samp * h.nchannels;
ev2(i).type = fread(fid,1,'short');
ev2(i).code = fread(fid,1,'short');
ev2(i).latency = fread(fid,1,'float');
ev2(i).epochevent = fread(fid,1,'char');
ev2(i).accept = fread(fid,1,'char');
ev2(i).accuracy = fread(fid,1,'char');
end
else
ev2 = [];
end;
elseif eT.teeg==1
nevents=eT.size/sizeEvent1;
if nevents > 0
ev2(nevents).stimtype = [];
for i=1:nevents
ev2(i).stimtype = fread(fid,1,'ushort');
ev2(i).keyboard = fread(fid,1,'char');
% modified by Andreas Widmann 2005/05/12 14:15:00
%ev2(i).keypad_accept = fread(fid,1,'char');
temp = fread(fid,1,'uint8');
ev2(i).keypad_accept = bitand(15,temp);
ev2(i).accept_ev1 = bitshift(temp,-4);
% end modification
ev2(i).offset = fread(fid,1,'long');
end;
else
ev2 = [];
end;
else
disp('Skipping event table (tag != 1,2,3 ; theoritically impossible)');
ev2 = [];
end
fseek(fid, -1, 'eof');
t = fread(fid,'char');
f.header = h;
f.electloc = e;
f.data = dat;
f.Teeg = eT;
f.event = ev2;
f.tag=t;
% Surgical addition of number of samples
f.ldnsamples = r.ldnsamples ;
%%%% channels labels
for i=1:h.nchannels
plab=sprintf('%c',f.electloc(i).lab);
if i>1
lab=str2mat(lab,plab);
else
lab=plab;
end
end
%%%% to change offest in bytes to points
if ~isempty(ev2)
if r.sample1 ~= 0
fprintf(2,'Warning: events imported with a time shift might be innacurate\n');
end;
ev2p=ev2;
ioff=900+(h.nchannels*75); %% initial offset : header + electordes desc
if strcmpi(r.dataformat, 'int16')
for i=1:nevents
ev2p(i).offset=(ev2p(i).offset-ioff)/(2*h.nchannels) - r.sample1; %% 2 short int end
end
else % 32 bits
for i=1:nevents
ev2p(i).offset=(ev2p(i).offset-ioff)/(4*h.nchannels) - r.sample1; %% 4 short int end
end
end;
f.event = ev2p;
end;
frewind(fid);
fclose(fid);
end
|
github
|
lcnbeapp/beapp-master
|
finputcheck.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/finputcheck.m
| 8,952 |
utf_8
|
158851ff64b79dcefc4bead7397ee6f5
|
% finputcheck() - check Matlab function {'key','value'} input argument pairs
%
% Usage: >> result = finputcheck( varargin, fieldlist );
% >> [result varargin] = finputcheck( varargin, fieldlist, ...
% callingfunc, mode, verbose );
% Input:
% varargin - Cell array 'varargin' argument from a function call using 'key',
% 'value' argument pairs. See Matlab function 'varargin'.
% May also be a structure such as struct(varargin{:})
% fieldlist - A 4-column cell array, one row per 'key'. The first
% column contains the key string, the second its type(s),
% the third the accepted value range, and the fourth the
% default value. Allowed types are 'boolean', 'integer',
% 'real', 'string', 'cell' or 'struct'. For example,
% {'key1' 'string' { 'string1' 'string2' } 'defaultval_key1'}
% {'key2' {'real' 'integer'} { minint maxint } 'defaultval_key2'}
% callingfunc - Calling function name for error messages. {default: none}.
% mode - ['ignore'|'error'] ignore keywords that are either not specified
% in the fieldlist cell array or generate an error.
% {default: 'error'}.
% verbose - ['verbose', 'quiet'] print information. Default: 'verbose'.
%
% Outputs:
% result - If no error, structure with 'key' as fields and 'value' as
% content. If error this output contain the string error.
% varargin - residual varagin containing unrecognized input arguments.
% Requires mode 'ignore' above.
%
% Note: In case of error, a string is returned containing the error message
% instead of a structure.
%
% Example (insert the following at the beginning of your function):
% result = finputcheck(varargin, ...
% { 'title' 'string' [] ''; ...
% 'percent' 'real' [0 1] 1 ; ...
% 'elecamp' 'integer' [1:10] [] });
% if isstr(result)
% error(result);
% end
%
% Note:
% The 'title' argument should be a string. {no default value}
% The 'percent' argument should be a real number between 0 and 1. {default: 1}
% The 'elecamp' argument should be an integer between 1 and 10 (inclusive).
%
% Now 'g.title' will contain the title arg (if any, else the default ''), etc.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 10 July 2002
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 10 July 2002, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [g, varargnew] = finputcheck( vararg, fieldlist, callfunc, mode, verbose )
if nargin < 2
help finputcheck;
return;
end;
if nargin < 3
callfunc = '';
else
callfunc = [callfunc ' ' ];
end;
if nargin < 4
mode = 'do not ignore';
end;
if nargin < 5
verbose = 'verbose';
end;
NAME = 1;
TYPE = 2;
VALS = 3;
DEF = 4;
SIZE = 5;
varargnew = {};
% create structure
% ----------------
if ~isempty(vararg)
if isstruct(vararg)
g = vararg;
else
for index=1:length(vararg)
if iscell(vararg{index})
vararg{index} = {vararg{index}};
end;
end;
try
g = struct(vararg{:});
catch
vararg = removedup(vararg, verbose);
try
g = struct(vararg{:});
catch
g = [ callfunc 'error: bad ''key'', ''val'' sequence' ]; return;
end;
end;
end;
else
g = [];
end;
for index = 1:size(fieldlist,NAME)
% check if present
% ----------------
if ~isfield(g, fieldlist{index, NAME})
g = setfield( g, fieldlist{index, NAME}, fieldlist{index, DEF});
end;
tmpval = getfield( g, {1}, fieldlist{index, NAME});
% check type
% ----------
if ~iscell( fieldlist{index, TYPE} )
res = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}, ...
fieldlist{index, VALS}, tmpval, callfunc );
if isstr(res), g = res; return; end;
else
testres = 0;
tmplist = fieldlist;
for it = 1:length( fieldlist{index, TYPE} )
if ~iscell(fieldlist{index, VALS})
res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ...
fieldlist{index, VALS}, tmpval, callfunc );
else res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ...
fieldlist{index, VALS}{it}, tmpval, callfunc );
end;
if ~isstr(res{it}), testres = 1; end;
end;
if testres == 0,
g = res{1};
for tmpi = 2:length(res)
g = [ g 10 'or ' res{tmpi} ];
end;
return;
end;
end;
end;
% check if fields are defined
% ---------------------------
allfields = fieldnames(g);
for index=1:length(allfields)
if isempty(strmatch(allfields{index}, fieldlist(:, 1)', 'exact'))
if ~strcmpi(mode, 'ignore')
g = [ callfunc 'error: undefined argument ''' allfields{index} '''']; return;
end;
varargnew{end+1} = allfields{index};
varargnew{end+1} = getfield(g, {1}, allfields{index});
end;
end;
function g = fieldtest( fieldname, fieldtype, fieldval, tmpval, callfunc );
NAME = 1;
TYPE = 2;
VALS = 3;
DEF = 4;
SIZE = 5;
g = [];
switch fieldtype
case { 'integer' 'real' 'boolean' 'float' },
if ~isnumeric(tmpval) && ~islogical(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be numeric' ]; return;
end;
if strcmpi(fieldtype, 'boolean')
if tmpval ~=0 && tmpval ~= 1
g = [ callfunc 'error: argument ''' fieldname ''' must be 0 or 1' ]; return;
end;
else
if strcmpi(fieldtype, 'integer')
if ~isempty(fieldval)
if (any(isnan(tmpval(:))) && ~any(isnan(fieldval))) ...
&& (~ismember(tmpval, fieldval))
g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return;
end;
end;
else % real or float
if ~isempty(fieldval) && ~isempty(tmpval)
if any(tmpval < fieldval(1)) || any(tmpval > fieldval(2))
g = [ callfunc 'error: value out of range for argument ''' fieldname '''' ]; return;
end;
end;
end;
end;
case 'string'
if ~isstr(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be a string' ]; return;
end;
if ~isempty(fieldval)
if isempty(strmatch(lower(tmpval), lower(fieldval), 'exact'))
g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return;
end;
end;
case 'cell'
if ~iscell(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be a cell array' ]; return;
end;
case 'struct'
if ~isstruct(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be a structure' ]; return;
end;
case '';
otherwise, error([ 'finputcheck error: unrecognized type ''' fieldname '''' ]);
end;
% remove duplicates in the list of parameters
% -------------------------------------------
function cella = removedup(cella, verbose)
% make sure if all the values passed to unique() are strings, if not, exist
%try
[tmp indices] = unique(cella(1:2:end));
if length(tmp) ~= length(cella)/2
myfprintf(verbose,'Note: duplicate ''key'', ''val'' parameter(s), keeping the last one(s)\n');
end;
cella = cella(sort(union(indices*2-1, indices*2)));
%catch
% some elements of cella were not string
% error('some ''key'' values are not string.');
%end;
function myfprintf(verbose, varargin)
if strcmpi(verbose, 'verbose')
fprintf(varargin{:});
end;
|
github
|
lcnbeapp/beapp-master
|
eegplot.m
|
.m
|
beapp-master/Packages/REST_MATLAB_v1.1_20170828/function/Loading/eegplot.m
| 87,220 |
utf_8
|
cff8d14db834da746efcad1710144559
|
% eegplot() - Scroll (horizontally and/or vertically) through multichannel data.
% Allows vertical scrolling through channels and manual marking
% and unmarking of data stretches or epochs for rejection.
% Usage:
% >> eegplot(data, 'key1', value1 ...); % use interface buttons, etc.
% else
% >> eegplot('noui', data, 'key1', value1 ...); % no user interface;
% % use for plotting
% Menu items:
% "Figure > print" - [menu] Print figure in portrait or landscape.
% "Figure > Edit figure" - [menu] Remove menus and buttons and call up the standard
% Matlab figure menu. Select "Tools > Edit" to format the figure
% for publication. Command line equivalent: 'noui'
% "Figure > Accept and Close" - [menu] Same as the bottom-right "Reject" button.
% "Figure > Cancel and Close" - [menu] Cancel all editing, same as the "Cancel" button.
% "Display > Marking color" > [Hide|Show] marks" - [menu] Show or hide patches of
% background color behind the data. Mark stretches of *continuous*
% data (e.g., for rejection) by dragging the mouse horizontally
% over the activity. With *epoched* data, click on the selected epochs.
% Clicked on a marked region to unmark it. Called from the
% command line, marked data stretches or epochs are returned in
% the TMPREJ variable in the global workspace *if/when* the "Reject"
% button is pressed (see Outputs); called from pop_eegplot() or
% eeglab(), the marked data portions are removed from the current
% dataset, and the dataset is automatically updated.
% "Display > Marking color > Choose color" - [menu] Change the background marking
% color. The marking color(s) of previously marked trials are preserved.
% Called from command line, subsequent functions eegplot2event() or
% eegplot2trials() allow processing trials marked with different colors
% in the TMPREJ output variable. Command line equivalent: 'wincolor'.
% "Display > Grid > ..." - [menu] Toggle (on or off) time and/or channel axis grids
% in the activity plot. Submenus allow modifications to grid aspects.
% Command line equivalents: 'xgrid' / 'ygrid'
% "Display > Show scale" - [menu] Show (or hide if shown) the scale on the bottom
% right corner of the activity window. Command line equivalent: 'scale'
% "Display > Title" - [menu] Change the title of the figure. Command line equivalent:
% 'title'
% "Settings > Time range to display" - [menu] For continuous EEG data, this item
% pops up a query window for entering the number of seconds to display
% in the activity window. For epoched data, the query window asks
% for the number of epochs to display (this can be fractional).
% Command line equivalent: 'winlength'
% "Settings > Number of channels to display" - [menu] Number of channels to display
% in the activity window. If not all channels are displayed, the
% user may scroll through channels using the slider on the left
% of the activity plot. Command line equivalent: 'dispchans'
% "Settings > Channel labels > ..." - [menu] Use numbers as channel labels or load
% a channel location file from disk. If called from the eeglab() menu or
% pop_eegplot(), the channel labels of the dataset will be used.
% Command line equivalent: 'eloc_file'
% "Settings > Zoom on/off" - [menu] Toggle Matlab figure zoom on or off for time and
% electrode axes. left-click to zoom (x2); right-click to reverse-zoom.
% Else, draw a rectange in the activity window to zoom the display into
% that region. NOTE: When zoom is on, data cannot be marked for rejection.
% "Settings > Events" - [menu] Toggle event on or off (assuming events have been
% given as input). Press "legend" to pop up a legend window for events.
%
% Display window interface:
% "Activity plot" - [main window] This axis displays the channel activities. For
% continuous data, the time axis shows time in seconds. For epoched
% data, the axis label indicate time within each epoch.
% "Cancel" - [button] Closes the window and cancels any data rejection marks.
% "Event types" - [button] pop up a legend window for events.
% "<<" - [button] Scroll backwards though time or epochs by one window length.
% "<" - [button] Scroll backwards though time or epochs by 0.2 window length.
% "Navigation edit box" - [edit box] Enter a starting time or epoch to jump to.
% ">" - [button] Scroll forward though time or epochs by 0.2 window length.
% ">>" - [button] Scroll forward though time or epochs by one window length.
% "Chan/Time/Value" - [text] If the mouse is within the activity window, indicates
% which channel, time, and activity value the cursor is closest to.
% "Scale edit box" - [edit box] Scales the displayed amplitude in activity units.
% Command line equivalent: 'spacing'
% "+ / -" - [buttons] Use these buttons to +/- the amplitude scale by 10%.
% "Reject" - [button] When pressed, save rejection marks and close the figure.
% Optional input parameter 'command' is evaluated at that time.
% NOTE: This button's label can be redefined from the command line
% (see 'butlabel' below). If no processing command is specified
% for the 'command' parameter (below), this button does not appear.
% "Stack/Spread" - [button] "Stack" collapses all channels/activations onto the
% middle axis of the plot. "Spread" undoes the operation.
% "Norm/Denorm" - [button] "Norm" normalizes each channel separately such that all
% channels have the same standard deviation without changing original
% data/activations under EEG structure. "Denorm" undoes the operation.
%
% Required command line input:
% data - Input data matrix, either continuous 2-D (channels,timepoints) or
% epoched 3-D (channels,timepoints,epochs). If the data is preceded
% by keyword 'noui', GUI control elements are omitted (useful for
% plotting data for presentation). A set of power spectra at
% each channel may also be plotted (see 'freqlimits' below).
% Optional command line keywords:
% 'srate' - Sampling rate in Hz {default|0: 256 Hz}
% 'spacing' - Display range per channel (default|0: max(whole_data)-min(whole_data))
% 'eloc_file' - Electrode filename (as in >> topoplot example) to read
% ascii channel labels. Else,
% [vector of integers] -> Show specified channel numbers. Else,
% [] -> Do not show channel labels {default|0 -> Show [1:nchans]}
% 'limits' - [start end] Time limits for data epochs in ms (for labeling
% purposes only).
% 'freqlimits' - [start end] If plotting epoch spectra instead of data, frequency
% limits of the display. (Data should contain spectral values).
% 'winlength' - [value] Seconds (or epochs) of data to display in window {default: 5}
% 'dispchans' - [integer] Number of channels to display in the activity window
% {default: from data}. If < total number of channels, a vertical
% slider on the left side of the figure allows vertical data scrolling.
% 'title' - Figure title {default: none}
% 'xgrid' - ['on'|'off'] Toggle display of the x-axis grid {default: 'off'}
% 'ygrid' - ['on'|'off'] Toggle display of the y-axis grid {default: 'off'}
% 'ploteventdur' - ['on'|'off'] Toggle display of event duration { default: 'off' }
% 'data2' - [float array] identical size to the original data and
% plotted on top of it.
%
% Additional keywords:
% 'command' - ['string'] Matlab command to evaluate when the 'REJECT' button is
% clicked. The 'REJECT' button is visible only if this parameter is
% not empty. As explained in the "Output" section below, the variable
% 'TMPREJ' contains the rejected windows (see the functions
% eegplot2event() and eegplot2trial()).
% 'butlabel' - Reject button label. {default: 'REJECT'}
% 'winrej' - [start end R G B e1 e2 e3 ...] Matrix giving data periods to mark
% for rejection, each row indicating a different period
% [start end] = period limits (in frames from beginning of data);
% [R G B] = specifies the marking color;
% [e1 e2 e3 ...] = a (1,nchans) logical [0|1] vector giving
% channels (1) to mark and (0) not mark for rejection.
% 'color' - ['on'|'off'|cell array] Plot channels with different colors.
% If an RGB cell array {'r' 'b' 'g'}, channels will be plotted
% using the cell-array color elements in cyclic order {default:'off'}.
% 'wincolor' - [color] Color to use to mark data stretches or epochs {default:
% [ 0.7 1 0.9] is the default marking color}
% 'events' - [struct] EEGLAB event structure (EEG.event) to use to show events.
% 'submean' - ['on'|'off'] Remove channel means in each window {default: 'on'}
% 'position' - [lowleft_x lowleft_y width height] Position of the figure in pixels.
% 'tag' - [string] Matlab object tag to identify this eegplot() window (allows
% keeping track of several simultaneous eegplot() windows).
% 'children' - [integer] Figure handle of a *dependent* eegplot() window. Scrolling
% horizontally in the master window will produce the same scroll in
% the dependent window. Allows comparison of two concurrent datasets,
% or of channel and component data from the same dataset.
% 'scale' - ['on'|'off'] Display the amplitude scale {default: 'on'}.
% 'mocap' - ['on'|'off'] Display motion capture data in a separate figure.
% To run, select an EEG data period in the scolling display using
% the mouse. Motion capture (mocap) data should be
% under EEG.moredata.mocap.markerPosition in xs, ys and zs fields which are
% (number of markers, number of time points) arrays.
% {default: 'off'}.
% 'selectcommand' - [cell array] list of 3 commands (strings) to run when the mouse
% button is down, when it is moving and when the mouse button is up.
% 'ctrlselectcommand' - [cell array] same as above in conjunction with pressing the
% CTRL key.
% Outputs:
% TMPREJ - Matrix (same format as 'winrej' above) placed as a variable in
% the global workspace (only) when the REJECT button is clicked.
% The command specified in the 'command' keyword argument can use
% this variable. (See eegplot2trial() and eegplot2event()).
%
% Author: Arnaud Delorme & Colin Humphries, CNL/Salk Institute, SCCN/INC/UCSD, 1998-2001
%
% See also: eeg_multieegplot(), eegplot2event(), eegplot2trial(), eeglab()
% deprecated
% 'colmodif' - nested cell array of window colors that may be marked/unmarked. Default
% is current color only.
% Copyright (C) 2001 Arnaud Delorme & Colin Humphries, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% Note for programmers - Internal variable structure:
% All in g. except for Eposition and Eg.spacingwhich are inside the boxes
% gcf
% 1 - winlength
% 2 - srate
% 3 - children
% 'backeeg' axis
% 1 - trialtag
% 2 - g.winrej
% 3 - nested call flag
% 'eegaxis'
% 1 - data
% 2 - colorlist
% 3 - submean % on or off, subtract the mean
% 4 - maxfreq % empty [] if no gfrequency content
% 'buttons hold other informations' Eposition for instance hold the current postition
function [outvar1] = eegplot(data, varargin); % p1,p2,p3,p4,p5,p6,p7,p8,p9)
% Defaults (can be re-defined):
DEFAULT_PLOT_COLOR = { [0 0 1], [0.7 0.7 0.7]}; % EEG line color
try, icadefs;
DEFAULT_FIG_COLOR = BACKCOLOR;
BUTTON_COLOR = GUIBUTTONCOLOR;
catch
DEFAULT_FIG_COLOR = [1 1 1];
BUTTON_COLOR =[0.8 0.8 0.8];
end;
DEFAULT_AXIS_COLOR = 'k'; % X-axis, Y-axis Color, text Color
DEFAULT_GRID_SPACING = 1; % Grid lines every n seconds
DEFAULT_GRID_STYLE = '-'; % Grid line style
YAXIS_NEG = 'off'; % 'off' = positive up
DEFAULT_NOUI_PLOT_COLOR = 'k'; % EEG line color for noui option
% 0 - 1st color in AxesColorOrder
SPACING_EYE = 'on'; % g.spacingI on/off
SPACING_UNITS_STRING = ''; % '\muV' for microvolt optional units for g.spacingI Ex. uV
%MAXEVENTSTRING = 10;
%DEFAULT_AXES_POSITION = [0.0964286 0.15 0.842 0.75-(MAXEVENTSTRING-5)/100];
% dimensions of main EEG axes
ORIGINAL_POSITION = [50 50 800 500];
if nargin < 1
help eegplot
return
end
% %%%%%%%%%%%%%%%%%%%%%%%%
% Setup inputs
% %%%%%%%%%%%%%%%%%%%%%%%%
if ~isstr(data) % If NOT a 'noui' call or a callback from uicontrols
try
options = varargin;
if ~isempty( varargin ),
for i = 1:2:numel(options)
g.(options{i}) = options{i+1};
end
else g= []; end;
catch
disp('eegplot() error: calling convention {''key'', value, ... } error'); return;
end;
% push button: create/remove window
% ---------------------------------
defdowncom = 'eegplot(''defdowncom'', gcbf);'; % push button: create/remove window
defmotioncom = 'eegplot(''defmotioncom'', gcbf);'; % motion button: move windows or display current position
defupcom = 'eegplot(''defupcom'', gcbf);';
defctrldowncom = 'eegplot(''topoplot'', gcbf);'; % CTRL press and motion -> do nothing by default
defctrlmotioncom = ''; % CTRL press and motion -> do nothing by default
defctrlupcom = ''; % CTRL press and up -> do nothing by default
try, g.srate; catch, g.srate = 256; end;
try, g.spacing; catch, g.spacing = 0; end;
try, g.eloc_file; catch, g.eloc_file = 0; end; % 0 mean numbered
try, g.winlength; catch, g.winlength = 5; end; % Number of seconds of EEG displayed
try, g.position; catch, g.position = ORIGINAL_POSITION; end;
try, g.title; catch, g.title = ['Scroll activity -- eegplot()']; end;
try, g.trialstag; catch, g.trialstag = -1; end;
try, g.winrej; catch, g.winrej = []; end;
try, g.command; catch, g.command = ''; end;
try, g.tag; catch, g.tag = 'EEGPLOT'; end;
try, g.xgrid; catch, g.xgrid = 'off'; end;
try, g.ygrid; catch, g.ygrid = 'off'; end;
try, g.color; catch, g.color = 'off'; end;
try, g.submean; catch, g.submean = 'off'; end;
try, g.children; catch, g.children = 0; end;
try, g.limits; catch, g.limits = [0 1000*(size(data,2)-1)/g.srate]; end;
try, g.freqlimits; catch, g.freqlimits = []; end;
try, g.dispchans; catch, g.dispchans = size(data,1); end;
try, g.wincolor; catch, g.wincolor = [ 0.7 1 0.9]; end;
try, g.butlabel; catch, g.butlabel = 'REJECT'; end;
try, g.colmodif; catch, g.colmodif = { g.wincolor }; end;
try, g.scale; catch, g.scale = 'on'; end;
try, g.events; catch, g.events = []; end;
try, g.ploteventdur; catch, g.ploteventdur = 'off'; end;
try, g.data2; catch, g.data2 = []; end;
try, g.plotdata2; catch, g.plotdata2 = 'off'; end;
try, g.mocap; catch, g.mocap = 'off'; end; % nima
try, g.selectcommand; catch, g.selectcommand = { defdowncom defmotioncom defupcom }; end;
try, g.ctrlselectcommand; catch, g.ctrlselectcommand = { defctrldowncom defctrlmotioncom defctrlupcom }; end;
try, g.datastd; catch, g.datastd = []; end; %ozgur
try, g.normed; catch, g.normed = 0; end; %ozgur
try, g.envelope; catch, g.envelope = 0; end;%ozgur
try, g.maxeventstring; catch, g.maxeventstring = 10; end; % JavierLC
if strcmpi(g.ploteventdur, 'on'), g.ploteventdur = 1; else g.ploteventdur = 0; end;
if ndims(data) > 2
g.trialstag = size( data, 2);
end;
gfields = fieldnames(g);
for index=1:length(gfields)
switch gfields{index}
case {'spacing', 'srate' 'eloc_file' 'winlength' 'position' 'title' ...
'trialstag' 'winrej' 'command' 'tag' 'xgrid' 'ygrid' 'color' 'colmodif'...
'freqlimits' 'submean' 'children' 'limits' 'dispchans' 'wincolor' ...
'maxeventstring' 'ploteventdur' 'butlabel' 'scale' 'events' 'data2' 'plotdata2' 'mocap' 'selectcommand' 'ctrlselectcommand' 'datastd' 'normed' 'envelope'},;
otherwise, error(['eegplot: unrecognized option: ''' gfields{index} '''' ]);
end;
end;
% g.data=data; % never used and slows down display dramatically - Ozgur 2010
if length(g.srate) > 1
disp('Error: srate must be a single number'); return;
end;
if length(g.spacing) > 1
disp('Error: ''spacing'' must be a single number'); return;
end;
if length(g.winlength) > 1
disp('Error: winlength must be a single number'); return;
end;
if isstr(g.title) > 1
disp('Error: title must be is a string'); return;
end;
if isstr(g.command) > 1
disp('Error: command must be is a string'); return;
end;
if isstr(g.tag) > 1
disp('Error: tag must be is a string'); return;
end;
if length(g.position) ~= 4
disp('Error: position must be is a 4 elements array'); return;
end;
switch lower(g.xgrid)
case { 'on', 'off' },;
otherwise disp('Error: xgrid must be either ''on'' or ''off'''); return;
end;
switch lower(g.ygrid)
case { 'on', 'off' },;
otherwise disp('Error: ygrid must be either ''on'' or ''off'''); return;
end;
switch lower(g.submean)
case { 'on' 'off' };
otherwise disp('Error: submean must be either ''on'' or ''off'''); return;
end;
switch lower(g.scale)
case { 'on' 'off' };
otherwise disp('Error: scale must be either ''on'' or ''off'''); return;
end;
if ~iscell(g.color)
switch lower(g.color)
case 'on', g.color = { 'k', 'm', 'c', 'b', 'g' };
case 'off', g.color = { [ 0 0 0.4] };
otherwise
disp('Error: color must be either ''on'' or ''off'' or a cell array');
return;
end;
end;
if length(g.dispchans) > size(data,1)
g.dispchans = size(data,1);
end;
if ~iscell(g.colmodif)
g.colmodif = { g.colmodif };
end;
if g.maxeventstring>20 % JavierLC
disp('Error: maxeventstring must be equal or lesser than 20'); return;
end;
% max event string; JavierLC
% ---------------------------------
MAXEVENTSTRING = g.maxeventstring;
DEFAULT_AXES_POSITION = [0.0964286 0.15 0.842 0.75-(MAXEVENTSTRING-5)/100];
% convert color to modify into array of float
% -------------------------------------------
for index = 1:length(g.colmodif)
if iscell(g.colmodif{index})
tmpcolmodif{index} = g.colmodif{index}{1} ...
+ g.colmodif{index}{2}*10 ...
+ g.colmodif{index}{3}*100;
else
tmpcolmodif{index} = g.colmodif{index}(1) ...
+ g.colmodif{index}(2)*10 ...
+ g.colmodif{index}(3)*100;
end;
end;
g.colmodif = tmpcolmodif;
[g.chans,g.frames, tmpnb] = size(data);
g.frames = g.frames*tmpnb;
if g.spacing == 0
maxindex = min(1000, g.frames);
stds = std(data(:,1:maxindex),[],2);
g.datastd = stds;
stds = sort(stds);
if length(stds) > 2
stds = mean(stds(2:end-1));
else
stds = mean(stds);
end;
g.spacing = stds*3;
if g.spacing > 10
g.spacing = round(g.spacing);
end
if g.spacing == 0 | isnan(g.spacing)
g.spacing = 1; % default
end;
end
% set defaults
% ------------
g.incallback = 0;
g.winstatus = 1;
g.setelectrode = 0;
[g.chans,g.frames,tmpnb] = size(data);
g.frames = g.frames*tmpnb;
g.nbdat = 1; % deprecated
g.time = 0;
g.elecoffset = 0;
% %%%%%%%%%%%%%%%%%%%%%%%%
% Prepare figure and axes
% %%%%%%%%%%%%%%%%%%%%%%%%
figh = figure('UserData', g,... % store the settings here
'Color',DEFAULT_FIG_COLOR, 'name', g.title,...
'MenuBar','none','tag', g.tag ,'Position',g.position, ...
'numbertitle', 'off', 'visible', 'off');
pos = get(figh,'position'); % plot relative to current axes
q = [pos(1) pos(2) 0 0];
s = [pos(3) pos(4) pos(3) pos(4)]./100;
clf;
% Background axis
% ---------------
ax0 = axes('tag','backeeg','parent',figh,...
'Position',DEFAULT_AXES_POSITION,...
'Box','off','xgrid','off', 'xaxislocation', 'top');
% Drawing axis
% ---------------
YLabels = num2str((1:g.chans)'); % Use numbers as default
YLabels = flipud(str2mat(YLabels,' '));
ax1 = axes('Position',DEFAULT_AXES_POSITION,...
'userdata', data, ...% store the data here
'tag','eegaxis','parent',figh,...%(when in g, slow down display)
'Box','on','xgrid', g.xgrid,'ygrid', g.ygrid,...
'gridlinestyle',DEFAULT_GRID_STYLE,...
'Xlim',[0 g.winlength*g.srate],...
'xtick',[0:g.srate*DEFAULT_GRID_SPACING:g.winlength*g.srate],...
'Ylim',[0 (g.chans+1)*g.spacing],...
'YTick',[0:g.spacing:g.chans*g.spacing],...
'YTickLabel', YLabels,...
'XTickLabel',num2str((0:DEFAULT_GRID_SPACING:g.winlength)'),...
'TickLength',[.005 .005],...
'Color','none',...
'XColor',DEFAULT_AXIS_COLOR,...
'YColor',DEFAULT_AXIS_COLOR);
if isstr(g.eloc_file) | isstruct(g.eloc_file) % Read in electrode names
if isstruct(g.eloc_file) & length(g.eloc_file) > size(data,1)
g.eloc_file(end) = []; % common reference channel location
end;
eegplot('setelect', g.eloc_file, ax1);
end;
% %%%%%%%%%%%%%%%%%%%%%%%%%
% Set up uicontrols
% %%%%%%%%%%%%%%%%%%%%%%%%%
% positions of buttons
posbut(1,:) = [ 0.0464 0.0254 0.0385 0.0339 ]; % <<
posbut(2,:) = [ 0.0924 0.0254 0.0288 0.0339 ]; % <
posbut(3,:) = [ 0.1924 0.0254 0.0299 0.0339 ]; % >
posbut(4,:) = [ 0.2297 0.0254 0.0385 0.0339 ]; % >>
posbut(5,:) = [ 0.1287 0.0203 0.0561 0.0390 ]; % Eposition
posbut(6,:) = [ 0.4744 0.0236 0.0582 0.0390 ]; % Espacing
posbut(7,:) = [ 0.2762 0.01 0.0582 0.0390 ]; % elec
posbut(8,:) = [ 0.3256 0.01 0.0707 0.0390 ]; % g.time
posbut(9,:) = [ 0.4006 0.01 0.0582 0.0390 ]; % value
posbut(14,:) = [ 0.2762 0.05 0.0582 0.0390 ]; % elec tag
posbut(15,:) = [ 0.3256 0.05 0.0707 0.0390 ]; % g.time tag
posbut(16,:) = [ 0.4006 0.05 0.0582 0.0390 ]; % value tag
posbut(10,:) = [ 0.5437 0.0458 0.0275 0.0270 ]; % +
posbut(11,:) = [ 0.5437 0.0134 0.0275 0.0270 ]; % -
posbut(12,:) = [ 0.6 0.02 0.14 0.05 ]; % cancel
posbut(13,:) = [-0.15 0.02 0.07 0.05 ]; % cancel
posbut(17,:) = [-0.06 0.02 0.09 0.05 ]; % events types
posbut(20,:) = [-0.17 0.15 0.015 0.8 ]; % slider
posbut(21,:) = [0.738 0.87 0.06 0.048];%normalize
posbut(22,:) = [0.738 0.93 0.06 0.048];%stack channels(same offset)
posbut(:,1) = posbut(:,1)+0.2;
% Five move buttons: << < text > >>
u(1) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'Position', posbut(1,:), ...
'Tag','Pushbutton1',...
'string','<<',...
'Callback',['global in_callback;', ...
'if isempty(in_callback);in_callback=1;', ...
' try eegplot(''drawp'',1);', ...
' clear global in_callback;', ...
' catch error_struct;', ...
' clear global in_callback;', ...
' throw(error_struct);', ...
' end;', ...
'else;return;end;']);%James Desjardins 2013/Jan/22
u(2) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'Position', posbut(2,:), ...
'Tag','Pushbutton2',...
'string','<',...
'Callback',['global in_callback;', ...
'if isempty(in_callback);in_callback=1;', ...
' try eegplot(''drawp'',2);', ...
' clear global in_callback;', ...
' catch error_struct;', ...
' clear global in_callback;', ...
' throw(error_struct);', ...
' end;', ...
'else;return;end;']);%James Desjardins 2013/Jan/22
u(5) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'BackgroundColor',[1 1 1], ...
'Position', posbut(5,:), ...
'Style','edit', ...
'Tag','EPosition',...
'string', fastif(g.trialstag(1) == -1, '0', '1'),...
'Callback', 'eegplot(''drawp'',0);' );
u(3) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'Position',posbut(3,:), ...
'Tag','Pushbutton3',...
'string','>',...
'Callback',['global in_callback;', ...
'if isempty(in_callback);in_callback=1;', ...
' try eegplot(''drawp'',3);', ...
' clear global in_callback;', ...
' catch error_struct;', ...
' clear global in_callback;', ...
' throw(error_struct);', ...
' end;', ...
'else;return;end;']);%James Desjardins 2013/Jan/22
u(4) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'Position',posbut(4,:), ...
'Tag','Pushbutton4',...
'string','>>',...
'Callback',['global in_callback;', ...
'if isempty(in_callback);in_callback=1;', ...
' try eegplot(''drawp'',4);', ...
' clear global in_callback;', ...
' catch error_struct;', ...
' clear global in_callback;', ...
' error(error_struct);', ...
' end;', ...
'else;return;end;']);%James Desjardins 2013/Jan/22
% Text edit fields: ESpacing
u(6) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'BackgroundColor',[1 1 1], ...
'Position', posbut(6,:), ...
'Style','edit', ...
'Tag','ESpacing',...
'string',num2str(g.spacing),...
'Callback', 'eegplot(''draws'',0);' );
% Slider for vertical motion
u(20) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'Position', posbut(20,:), ...
'Style','slider', ...
'visible', 'off', ...
'sliderstep', [0.9 1], ...
'Tag','eegslider', ...
'callback', [ 'tmpg = get(gcbf, ''userdata'');' ...
'tmpg.elecoffset = get(gcbo, ''value'')*(tmpg.chans-tmpg.dispchans);' ...
'set(gcbf, ''userdata'', tmpg);' ...
'eegplot(''drawp'',0);' ...
'clear tmpg;' ], ...
'value', 0);
% Channels, position, value and tag
u(9) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'BackgroundColor',DEFAULT_FIG_COLOR, ...
'Position', posbut(7,:), ...
'Style','text', ...
'Tag','Eelec',...
'string',' ');
u(10) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'BackgroundColor',DEFAULT_FIG_COLOR, ...
'Position', posbut(8,:), ...
'Style','text', ...
'Tag','Etime',...
'string','0.00');
u(11) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'BackgroundColor',DEFAULT_FIG_COLOR, ...
'Position',posbut(9,:), ...
'Style','text', ...
'Tag','Evalue',...
'string','0.00');
u(14)= uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'BackgroundColor',DEFAULT_FIG_COLOR, ...
'Position', posbut(14,:), ...
'Style','text', ...
'Tag','Eelecname',...
'string','Chan.');
u(15) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'BackgroundColor',DEFAULT_FIG_COLOR, ...
'Position', posbut(15,:), ...
'Style','text', ...
'Tag','Etimename',...
'string','Time');
u(16) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'BackgroundColor',DEFAULT_FIG_COLOR, ...
'Position',posbut(16,:), ...
'Style','text', ...
'Tag','Evaluename',...
'string','Value');
% ESpacing buttons: + -
u(7) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'Position',posbut(10,:), ...
'Tag','Pushbutton5',...
'string','+',...
'FontSize',8,...
'Callback','eegplot(''draws'',1)');
u(8) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'Position',posbut(11,:), ...
'Tag','Pushbutton6',...
'string','-',...
'FontSize',8,...
'Callback','eegplot(''draws'',2)');
cb_normalize = ['g = get(gcbf,''userdata'');if g.normed, disp(''Denormalizing...''); else, disp(''Normalizing...''); end;'...
'hmenu = findobj(gcf, ''Tag'', ''Normalize_menu'');' ...
'ax1 = findobj(''tag'',''eegaxis'',''parent'',gcbf);' ...
'data = get(ax1,''UserData'');' ...
'if isempty(g.datastd), g.datastd = std(data(:,1:min(1000,g.frames),[],2)); end;'...
'if g.normed, '...
'for i = 1:size(data,1), '...
'data(i,:,:) = data(i,:,:)*g.datastd(i);'...
'if ~isempty(g.data2), g.data2(i,:,:) = g.data2(i,:,:)*g.datastd(i);end;'...
'end;'...
'set(gcbo,''string'', ''Norm'');set(findobj(''tag'',''ESpacing'',''parent'',gcbf),''string'',num2str(g.oldspacing));' ...
'else, for i = 1:size(data,1),'...
'data(i,:,:) = data(i,:,:)/g.datastd(i);'...
'if ~isempty(g.data2), g.data2(i,:,:) = g.data2(i,:,:)/g.datastd(i);end;'...
'end;'...
'set(gcbo,''string'', ''Denorm'');g.oldspacing = g.spacing;set(findobj(''tag'',''ESpacing'',''parent'',gcbf),''string'',''5'');end;' ...
'g.normed = 1 - g.normed;' ...
'eegplot(''draws'',0);'...
'set(hmenu, ''Label'', fastif(g.normed,''Denormalize channels'',''Normalize channels''));' ...
'set(gcbf,''userdata'',g);set(ax1,''UserData'',data);clear ax1 g data;' ...
'eegplot(''drawp'',0);' ...
'disp(''Done.'')'];
% Button for Normalizing data
u(21) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'Position',posbut(21,:), ...
'Tag','Norm',...
'string','Norm', 'callback', cb_normalize);
cb_envelope = ['g = get(gcbf,''userdata'');'...
'hmenu = findobj(gcf, ''Tag'', ''Envelope_menu'');' ...
'g.envelope = ~g.envelope;' ...
'set(gcbf,''userdata'',g);'...
'set(gcbo,''string'',fastif(g.envelope,''Spread'',''Stack''));' ...
'set(hmenu, ''Label'', fastif(g.envelope,''Spread channels'',''Stack channels''));' ...
'eegplot(''drawp'',0);clear g;'];
% Button to plot envelope of data
u(22) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'Position',posbut(22,:), ...
'Tag','Envelope',...
'string','Stack', 'callback', cb_envelope);
if isempty(g.command) tmpcom = 'fprintf(''Rejections saved in variable TMPREJ\n'');';
else tmpcom = g.command;
end;
acceptcommand = [ 'g = get(gcbf, ''userdata'');' ...
'TMPREJ = g.winrej;' ...
'if g.children, delete(g.children); end;' ...
'delete(gcbf);' ...
tmpcom ...
'; clear g;']; % quitting expression
if ~isempty(g.command)
u(12) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'Position',posbut(12,:), ...
'Tag','Accept',...
'string',g.butlabel, 'callback', acceptcommand);
end;
u(13) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'Position',posbut(13,:), ...
'string',fastif(isempty(g.command),'CLOSE', 'CANCEL'), 'callback', ...
[ 'g = get(gcbf, ''userdata'');' ...
'if g.children, delete(g.children); end;' ...
'close(gcbf);'] );
if ~isempty(g.events)
u(17) = uicontrol('Parent',figh, ...
'Units', 'normalized', ...
'Position',posbut(17,:), ...
'string', 'Event types', 'callback', 'eegplot(''drawlegend'', gcbf)');
end;
set(u,'Units','Normalized')
% %%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set up uimenus
% %%%%%%%%%%%%%%%%%%%%%%%%%%%
% Figure Menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
m(7) = uimenu('Parent',figh,'Label','Figure');
m(8) = uimenu('Parent',m(7),'Label','Print');
uimenu('Parent',m(7),'Label','Edit figure', 'Callback', 'eegplot(''noui'');');
uimenu('Parent',m(7),'Label','Accept and close', 'Callback', acceptcommand );
uimenu('Parent',m(7),'Label','Cancel and close', 'Callback','delete(gcbf)')
% Portrait %%%%%%%%
timestring = ['[OBJ1,FIG1] = gcbo;',...
'PANT1 = get(OBJ1,''parent'');',...
'OBJ2 = findobj(''tag'',''orient'',''parent'',PANT1);',...
'set(OBJ2,''checked'',''off'');',...
'set(OBJ1,''checked'',''on'');',...
'set(FIG1,''PaperOrientation'',''portrait'');',...
'clear OBJ1 FIG1 OBJ2 PANT1;'];
uimenu('Parent',m(8),'Label','Portrait','checked',...
'on','tag','orient','callback',timestring)
% Landscape %%%%%%%
timestring = ['[OBJ1,FIG1] = gcbo;',...
'PANT1 = get(OBJ1,''parent'');',...
'OBJ2 = findobj(''tag'',''orient'',''parent'',PANT1);',...
'set(OBJ2,''checked'',''off'');',...
'set(OBJ1,''checked'',''on'');',...
'set(FIG1,''PaperOrientation'',''landscape'');',...
'clear OBJ1 FIG1 OBJ2 PANT1;'];
uimenu('Parent',m(8),'Label','Landscape','checked',...
'off','tag','orient','callback',timestring)
% Print command %%%%%%%
uimenu('Parent',m(8),'Label','Print','tag','printcommand','callback',...
['RESULT = inputdlg2( { ''Command:'' }, ''Print'', 1, { ''print -r72'' });' ...
'if size( RESULT,1 ) ~= 0' ...
' eval ( RESULT{1} );' ...
'end;' ...
'clear RESULT;' ]);
% Display Menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
m(1) = uimenu('Parent',figh,...
'Label','Display', 'tag', 'displaymenu');
% window grid %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% userdata = 4 cells : display yes/no, color, electrode yes/no,
% trial boundary adapt yes/no (1/0)
m(11) = uimenu('Parent',m(1),'Label','Data select/mark', 'tag', 'displaywin', ...
'userdata', { 1, [0.8 1 0.8], 0, fastif( g.trialstag(1) == -1, 0, 1)});
uimenu('Parent',m(11),'Label','Hide marks','Callback', ...
['g = get(gcbf, ''userdata'');' ...
'if ~g.winstatus' ...
' set(gcbo, ''label'', ''Hide marks'');' ...
'else' ...
' set(gcbo, ''label'', ''Show marks'');' ...
'end;' ...
'g.winstatus = ~g.winstatus;' ...
'set(gcbf, ''userdata'', g);' ...
'eegplot(''drawb''); clear g;'] )
% color %%%%%%%%%%%%%%%%%%%%%%%%%%
if isunix % for some reasons, does not work under Windows
uimenu('Parent',m(11),'Label','Choose color', 'Callback', ...
[ 'g = get(gcbf, ''userdata'');' ...
'g.wincolor = uisetcolor(g.wincolor);' ...
'set(gcbf, ''userdata'', g ); ' ...
'clear g;'] )
end;
% set channels
%uimenu('Parent',m(11),'Label','Mark channels', 'enable', 'off', ...
%'checked', 'off', 'Callback', ...
%['g = get(gcbf, ''userdata'');' ...
% 'g.setelectrode = ~g.setelectrode;' ...
% 'set(gcbf, ''userdata'', g); ' ...
% 'if ~g.setelectrode setgcbo, ''checked'', ''on''); ...
% else set(gcbo, ''checked'', ''off''); end;'...
% ' clear g;'] )
% trials boundaries
%uimenu('Parent',m(11),'Label','Trial boundaries', 'checked', fastif( g.trialstag(1) == -1, 'off', 'on'), 'Callback', ...
%['hh = findobj(''tag'',''displaywin'',''parent'', findobj(''tag'',''displaymenu'',''parent'', gcbf ));' ...
% 'hhdat = get(hh, ''userdata'');' ...
% 'set(hh, ''userdata'', { hhdat{1}, hhdat{2}, hhdat{3}, ~hhdat{4}} ); ' ...
%'if ~hhdat{4} set(gcbo, ''checked'', ''on''); else set(gcbo, ''checked'', ''off''); end;' ...
%' clear hh hhdat;'] )
% plot durations
% --------------
if g.ploteventdur & isfield(g.events, 'duration')
disp(['Use menu "Display > Hide event duration" to hide colored regions ' ...
'representing event duration']);
end;
if isfield(g.events, 'duration')
uimenu('Parent',m(1),'Label',fastif(g.ploteventdur, 'Hide event duration', 'Plot event duration'),'Callback', ...
['g = get(gcbf, ''userdata'');' ...
'if ~g.ploteventdur' ...
' set(gcbo, ''label'', ''Hide event duration'');' ...
'else' ...
' set(gcbo, ''label'', ''Show event duration'');' ...
'end;' ...
'g.ploteventdur = ~g.ploteventdur;' ...
'set(gcbf, ''userdata'', g);' ...
'eegplot(''drawb''); clear g;'] )
end;
% X grid %%%%%%%%%%%%
m(3) = uimenu('Parent',m(1),'Label','Grid');
timestring = ['FIGH = gcbf;',...
'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
'if size(get(AXESH,''xgrid''),2) == 2' ... %on
' set(AXESH,''xgrid'',''off'');',...
' set(gcbo,''label'',''X grid on'');',...
'else' ...
' set(AXESH,''xgrid'',''on'');',...
' set(gcbo,''label'',''X grid off'');',...
'end;' ...
'clear FIGH AXESH;' ];
uimenu('Parent',m(3),'Label',fastif(strcmp(g.xgrid, 'off'), ...
'X grid on','X grid off'), 'Callback',timestring)
% Y grid %%%%%%%%%%%%%
timestring = ['FIGH = gcbf;',...
'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
'if size(get(AXESH,''ygrid''),2) == 2' ... %on
' set(AXESH,''ygrid'',''off'');',...
' set(gcbo,''label'',''Y grid on'');',...
'else' ...
' set(AXESH,''ygrid'',''on'');',...
' set(gcbo,''label'',''Y grid off'');',...
'end;' ...
'clear FIGH AXESH;' ];
uimenu('Parent',m(3),'Label',fastif(strcmp(g.ygrid, 'off'), ...
'Y grid on','Y grid off'), 'Callback',timestring)
% Grid Style %%%%%%%%%
m(5) = uimenu('Parent',m(3),'Label','Grid Style');
timestring = ['FIGH = gcbf;',...
'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
'set(AXESH,''gridlinestyle'',''--'');',...
'clear FIGH AXESH;'];
uimenu('Parent',m(5),'Label','- -','Callback',timestring)
timestring = ['FIGH = gcbf;',...
'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
'set(AXESH,''gridlinestyle'',''-.'');',...
'clear FIGH AXESH;'];
uimenu('Parent',m(5),'Label','_ .','Callback',timestring)
timestring = ['FIGH = gcbf;',...
'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
'set(AXESH,''gridlinestyle'','':'');',...
'clear FIGH AXESH;'];
uimenu('Parent',m(5),'Label','. .','Callback',timestring)
timestring = ['FIGH = gcbf;',...
'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
'set(AXESH,''gridlinestyle'',''-'');',...
'clear FIGH AXESH;'];
uimenu('Parent',m(5),'Label','__','Callback',timestring)
% Submean menu %%%%%%%%%%%%%
cb = ['g = get(gcbf, ''userdata'');' ...
'if strcmpi(g.submean, ''on''),' ...
' set(gcbo, ''label'', ''Remove DC offset'');' ...
' g.submean =''off'';' ...
'else' ...
' set(gcbo, ''label'', ''Do not remove DC offset'');' ...
' g.submean =''on'';' ...
'end;' ...
'set(gcbf, ''userdata'', g);' ...
'eegplot(''drawp'', 0); clear g;'];
uimenu('Parent',m(1),'Label',fastif(strcmp(g.submean, 'on'), ...
'Do not remove DC offset','Remove DC offset'), 'Callback',cb)
% Scale Eye %%%%%%%%%
timestring = ['[OBJ1,FIG1] = gcbo;',...
'eegplot(''scaleeye'',OBJ1,FIG1);',...
'clear OBJ1 FIG1;'];
m(7) = uimenu('Parent',m(1),'Label','Show scale','Callback',timestring);
% Title %%%%%%%%%%%%
uimenu('Parent',m(1),'Label','Title','Callback','eegplot(''title'')')
% Stack/Spread %%%%%%%%%%%%%%%
cb = ['g = get(gcbf, ''userdata'');' ...
'hbutton = findobj(gcf, ''Tag'', ''Envelope'');' ... % find button
'if g.envelope == 0,' ...
' set(gcbo, ''label'', ''Spread channels'');' ...
' g.envelope = 1;' ...
' set(hbutton, ''String'', ''Spread'');' ...
'else' ...
' set(gcbo, ''label'', ''Stack channels'');' ...
' g.envelope = 0;' ...
' set(hbutton, ''String'', ''Stack'');' ...
'end;' ...
'set(gcbf, ''userdata'', g);' ...
'eegplot(''drawp'', 0); clear g;'];
uimenu('Parent',m(1),'Label',fastif(g.envelope == 0, ...
'Stack channels','Spread channels'), 'Callback',cb, 'Tag', 'Envelope_menu')
% Normalize/denormalize %%%%%%%%%%%%%%%
cb_normalize = ['g = get(gcbf,''userdata'');if g.normed, disp(''Denormalizing...''); else, disp(''Normalizing...''); end;'...
'hbutton = findobj(gcf, ''Tag'', ''Norm'');' ... % find button
'ax1 = findobj(''tag'',''eegaxis'',''parent'',gcbf);' ...
'data = get(ax1,''UserData'');' ...
'if isempty(g.datastd), g.datastd = std(data(:,1:min(1000,g.frames),[],2)); end;'...
'if g.normed, '...
' for i = 1:size(data,1), '...
' data(i,:,:) = data(i,:,:)*g.datastd(i);'...
' if ~isempty(g.data2), g.data2(i,:,:) = g.data2(i,:,:)*g.datastd(i);end;'...
' end;'...
' set(hbutton,''string'', ''Norm'');set(findobj(''tag'',''ESpacing'',''parent'',gcbf),''string'',num2str(g.oldspacing));' ...
' set(gcbo, ''label'', ''Normalize channels'');' ...
'else, for i = 1:size(data,1),'...
' data(i,:,:) = data(i,:,:)/g.datastd(i);'...
' if ~isempty(g.data2), g.data2(i,:,:) = g.data2(i,:,:)/g.datastd(i);end;'...
' end;'...
' set(hbutton,''string'', ''Denorm'');'...
' set(gcbo, ''label'', ''Denormalize channels'');' ...
' g.oldspacing = g.spacing;set(findobj(''tag'',''ESpacing'',''parent'',gcbf),''string'',''5'');end;' ...
'g.normed = 1 - g.normed;' ...
'eegplot(''draws'',0);'...
'set(gcbf,''userdata'',g);set(ax1,''UserData'',data);clear ax1 g data;' ...
'eegplot(''drawp'',0);' ...
'disp(''Done.'')'];
uimenu('Parent',m(1),'Label',fastif(g.envelope == 0, ...
'Normalize channels','Denormalize channels'), 'Callback',cb_normalize, 'Tag', 'Normalize_menu')
% Settings Menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
m(2) = uimenu('Parent',figh,...
'Label','Settings');
% Window %%%%%%%%%%%%
uimenu('Parent',m(2),'Label','Time range to display',...
'Callback','eegplot(''window'')')
% Electrode window %%%%%%%%
uimenu('Parent',m(2),'Label','Number of channels to display',...
'Callback','eegplot(''winelec'')')
% Electrodes %%%%%%%%
m(6) = uimenu('Parent',m(2),'Label','Channel labels');
timestring = ['FIGH = gcbf;',...
'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',...
'YTICK = get(AXESH,''YTick'');',...
'YTICK = length(YTICK);',...
'set(AXESH,''YTickLabel'',flipud(str2mat(num2str((1:YTICK-1)''),'' '')));',...
'clear FIGH AXESH YTICK;'];
uimenu('Parent',m(6),'Label','Show number','Callback',timestring)
uimenu('Parent',m(6),'Label','Load .loc(s) file',...
'Callback','eegplot(''loadelect'');')
% Zooms %%%%%%%%
zm = uimenu('Parent',m(2),'Label','Zoom off/on');
commandzoom = [ 'set(gcbf, ''windowbuttondownfcn'', [ ''zoom(gcbf,''''down''''); eegplot(''''zoom'''', gcbf, 1);'' ]);' ...
'tmpg = get(gcbf, ''userdata'');' ...
'set(gcbf, ''windowbuttonmotionfcn'', tmpg.commandselect{2}); clear tmpg tmpstr;'];
%uimenu('Parent',zm,'Label','Zoom time', 'callback', ...
% [ 'zoom(gcbf, ''xon'');' commandzoom ]);
%uimenu('Parent',zm,'Label','Zoom channels', 'callback', ...
% [ 'zoom(gcbf, ''yon'');' commandzoom ]);
uimenu('Parent',zm,'Label','Zoom on', 'callback', commandzoom);
uimenu('Parent',zm,'Label','Zoom off', 'separator', 'on', 'callback', ...
['zoom(gcbf, ''off''); tmpg = get(gcbf, ''userdata'');' ...
'set(gcbf, ''windowbuttondownfcn'', tmpg.commandselect{1});' ...
'set(gcbf, ''windowbuttonmotionfcn'', tmpg.commandselect{2});' ...
'set(gcbf, ''windowbuttonupfcn'', tmpg.commandselect{3});' ...
'clear tmpg;' ]);
uimenu('Parent',figh,'Label', 'Help', 'callback', 'pophelp(''eegplot'');');
% Events %%%%%%%%
zm = uimenu('Parent',m(2),'Label','Events');
complotevent = [ 'tmpg = get(gcbf, ''userdata'');' ...
'tmpg.plotevent = ''on'';' ...
'set(gcbf, ''userdata'', tmpg); clear tmpg; eegplot(''drawp'', 0);'];
comnoevent = [ 'tmpg = get(gcbf, ''userdata'');' ...
'tmpg.plotevent = ''off'';' ...
'set(gcbf, ''userdata'', tmpg); clear tmpg; eegplot(''drawp'', 0);'];
comeventmaxstring = [ 'tmpg = get(gcbf, ''userdata'');' ...
'tmpg.plotevent = ''on'';' ...
'set(gcbf, ''userdata'', tmpg); clear tmpg; eegplot(''emaxstring'');']; % JavierLC
comeventleg = [ 'eegplot(''drawlegend'', gcbf);'];
uimenu('Parent',zm,'Label','Events on' , 'callback', complotevent, 'enable', fastif(isempty(g.events), 'off', 'on'));
uimenu('Parent',zm,'Label','Events off' , 'callback', comnoevent , 'enable', fastif(isempty(g.events), 'off', 'on'));
uimenu('Parent',zm,'Label','Events'' string length' , 'callback', comeventmaxstring, 'enable', fastif(isempty(g.events), 'off', 'on')); % JavierLC
uimenu('Parent',zm,'Label','Events'' legend', 'callback', comeventleg , 'enable', fastif(isempty(g.events), 'off', 'on'));
% %%%%%%%%%%%%%%%%%
% Set up autoselect
% %%%%%%%%%%%%%%%%%
g.commandselect{1} = [ 'if strcmp(get(gcbf, ''SelectionType''),''alt''),' g.ctrlselectcommand{1} ...
'else ' g.selectcommand{1} 'end;' ];
g.commandselect{2} = [ 'if strcmp(get(gcbf, ''SelectionType''),''alt''),' g.ctrlselectcommand{2} ...
'else ' g.selectcommand{2} 'end;' ];
g.commandselect{3} = [ 'if strcmp(get(gcbf, ''SelectionType''),''alt''),' g.ctrlselectcommand{3} ...
'else ' g.selectcommand{3} 'end;' ];
set(figh, 'windowbuttondownfcn', g.commandselect{1});
set(figh, 'windowbuttonmotionfcn', g.commandselect{2});
set(figh, 'windowbuttonupfcn', g.commandselect{3});
set(figh, 'WindowKeyPressFcn', @eegplot_readkey);
set(figh, 'interruptible', 'off');
set(figh, 'busyaction', 'cancel');
% set(figh, 'windowbuttondownfcn', commandpush);
% set(figh, 'windowbuttonmotionfcn', commandmove);
% set(figh, 'windowbuttonupfcn', commandrelease);
% set(figh, 'interruptible', 'off');
% set(figh, 'busyaction', 'cancel');
% prepare event array if any
% --------------------------
if ~isempty(g.events)
if ~isfield(g.events, 'type') | ~isfield(g.events, 'latency'), g.events = []; end;
end;
if ~isempty(g.events)
if isstr(g.events(1).type)
[g.eventtypes tmpind indexcolor] = unique_bc({g.events.type}); % indexcolor countinas the event type
else [g.eventtypes tmpind indexcolor] = unique_bc([ g.events.type ]);
end;
g.eventcolors = { 'r', [0 0.8 0], 'm', 'c', 'k', 'b', [0 0.8 0] };
g.eventstyle = { '-' '-' '-' '-' '-' '-' '-' '--' '--' '--' '--' '--' '--' '--'};
g.eventwidths = [ 2.5 1 ];
g.eventtypecolors = g.eventcolors(mod([1:length(g.eventtypes)]-1 ,length(g.eventcolors))+1);
g.eventcolors = g.eventcolors(mod(indexcolor-1 ,length(g.eventcolors))+1);
g.eventtypestyle = g.eventstyle (mod([1:length(g.eventtypes)]-1 ,length(g.eventstyle))+1);
g.eventstyle = g.eventstyle (mod(indexcolor-1 ,length(g.eventstyle))+1);
% for width, only boundary events have width 2 (for the line)
% -----------------------------------------------------------
indexwidth = ones(1,length(g.eventtypes))*2;
if iscell(g.eventtypes)
for index = 1:length(g.eventtypes)
if strcmpi(g.eventtypes{index}, 'boundary'), indexwidth(index) = 1; end;
end;
end;
g.eventtypewidths = g.eventwidths (mod(indexwidth([1:length(g.eventtypes)])-1 ,length(g.eventwidths))+1);
g.eventwidths = g.eventwidths (mod(indexwidth(indexcolor)-1 ,length(g.eventwidths))+1);
% latency and duration of events
% ------------------------------
g.eventlatencies = [ g.events.latency ]+1;
if isfield(g.events, 'duration')
durations = { g.events.duration };
durations(cellfun(@isempty, durations)) = { NaN };
g.eventlatencyend = g.eventlatencies + [durations{:}]+1;
else g.eventlatencyend = [];
end;
g.plotevent = 'on';
end;
if isempty(g.events)
g.plotevent = 'off';
end;
set(figh, 'userdata', g);
% %%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot EEG Data
% %%%%%%%%%%%%%%%%%%%%%%%%%%
axes(ax1)
hold on
% %%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot Spacing I
% %%%%%%%%%%%%%%%%%%%%%%%%%%
YLim = get(ax1,'Ylim');
A = DEFAULT_AXES_POSITION;
axes('Position',[A(1)+A(3) A(2) 1-A(1)-A(3) A(4)],'Visible','off','Ylim',YLim,'tag','eyeaxes')
axis manual
if strcmp(SPACING_EYE,'on'), set(m(7),'checked','on')
else set(m(7),'checked','off');
end
eegplot('scaleeye', [], gcf);
if strcmp(lower(g.scale), 'off')
eegplot('scaleeye', 'off', gcf);
end;
eegplot('drawp', 0);
eegplot('drawp', 0);
if g.dispchans ~= g.chans
eegplot('zoom', gcf);
end;
eegplot('scaleeye', [], gcf);
h = findobj(gcf, 'style', 'pushbutton');
set(h, 'backgroundcolor', BUTTON_COLOR);
h = findobj(gcf, 'tag', 'eegslider');
set(h, 'backgroundcolor', BUTTON_COLOR);
set(figh, 'visible', 'on');
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% End Main Function
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
else
try, p1 = varargin{1}; p2 = varargin{2}; p3 = varargin{3}; catch, end;
switch data
case 'drawp' % Redraw EEG and change position
% this test help to couple eegplot windows
if exist('p3')
figh = p3;
figure(p3);
else
figh = gcf; % figure handle
end;
if strcmp(get(figh,'tag'),'dialog')
figh = get(figh,'UserData');
end
ax0 = findobj('tag','backeeg','parent',figh); % axes handle
ax1 = findobj('tag','eegaxis','parent',figh); % axes handle
g = get(figh,'UserData');
data = get(ax1,'UserData');
ESpacing = findobj('tag','ESpacing','parent',figh); % ui handle
EPosition = findobj('tag','EPosition','parent',figh); % ui handle
if ~isempty(EPosition) && ~isempty(ESpacing)
if g.trialstag(1) == -1
g.time = str2num(get(EPosition,'string'));
else
g.time = str2num(get(EPosition,'string'));
g.time = g.time - 1;
end;
g.spacing = str2num(get(ESpacing,'string'));
end;
if p1 == 1
g.time = g.time-g.winlength; % << subtract one window length
elseif p1 == 2
g.time = g.time-fastif(g.winlength>=1, 1, g.winlength/5); % < subtract one second
elseif p1 == 3
g.time = g.time+fastif(g.winlength>=1, 1, g.winlength/5); % > add one second
elseif p1 == 4
g.time = g.time+g.winlength; % >> add one window length
end
if g.trialstag ~= -1 % time in second or in trials
multiplier = g.trialstag;
else
multiplier = g.srate;
end;
% Update edit box
% ---------------
g.time = max(0,min(g.time,ceil((g.frames-1)/multiplier)-g.winlength));
if g.trialstag(1) == -1
set(EPosition,'string',num2str(g.time));
else
set(EPosition,'string',num2str(g.time+1));
end;
set(figh, 'userdata', g);
lowlim = round(g.time*multiplier+1);
highlim = round(min((g.time+g.winlength)*multiplier+2,g.frames));
% Plot data and update axes
% -------------------------
if ~isempty(g.data2)
switch lower(g.submean) % subtract the mean ?
case 'on',
meandata = mean(g.data2(:,lowlim:highlim)');
if any(isnan(meandata)) % 6/16/104 Ramon: meandata by memdata
meandata = nan_mean(g.data2(:,lowlim:highlim)');
end;
otherwise, meandata = zeros(1,g.chans);
end;
else
switch lower(g.submean) % subtract the mean ?
case 'on',
meandata = mean(data(:,lowlim:highlim)');
if any(isnan(meandata))
meandata = nan_mean(data(:,lowlim:highlim)');
end;
otherwise, meandata = zeros(1,g.chans);
end;
end;
if strcmpi(g.plotdata2, 'off')
axes(ax1)
cla
end;
oldspacing = g.spacing;
if g.envelope
g.spacing = 0;
end
% plot data
% ---------
axes(ax1)
hold on
% plot channels whose "badchan" field is set to 1.
% Bad channels are plotted first so that they appear behind the good
% channels in the eegplot figure window.
for i = 1:g.chans
if strcmpi(g.plotdata2, 'on')
tmpcolor = [ 1 0 0 ];
else tmpcolor = g.color{mod(i-1,length(g.color))+1};
end;
if isfield(g, 'eloc_file') & ...
isfield(g.eloc_file, 'badchan') & ...
g.eloc_file(g.chans-i+1).badchan;
tmpcolor = [ .85 .85 .85 ];
plot(data(g.chans-i+1,lowlim:highlim) -meandata(g.chans-i+1)+i*g.spacing + (g.dispchans+1)*(oldspacing-g.spacing)/2 +g.elecoffset*(oldspacing-g.spacing), ...
'color', tmpcolor, 'clipping','on')
plot(1,mean(data(g.chans-i+1,lowlim:highlim) -meandata(g.chans-i+1)+i*g.spacing + (g.dispchans+1)*(oldspacing-g.spacing)/2 +g.elecoffset*(oldspacing-g.spacing),2),'<r','MarkerFaceColor','r','MarkerSize',6);
end
end
% plot good channels on top of bad channels (if g.eloc_file(i).badchan = 0... or there is no bad channel information)
for i = 1:g.chans
if strcmpi(g.plotdata2, 'on')
tmpcolor = [ 1 0 0 ];
else tmpcolor = g.color{mod(g.chans-i,length(g.color))+1};
end;
% keyboard;
if (isfield(g, 'eloc_file') & ...
isfield(g.eloc_file, 'badchan') & ...
~g.eloc_file(g.chans-i+1).badchan) | ...
(~isfield(g, 'eloc_file')) | ...
(~isfield(g.eloc_file, 'badchan'));
plot(data(g.chans-i+1,lowlim:highlim) -meandata(g.chans-i+1)+i*g.spacing + (g.dispchans+1)*(oldspacing-g.spacing)/2 +g.elecoffset*(oldspacing-g.spacing), ...
'color', tmpcolor, 'clipping','on')
end
end
% draw selected channels
% ------------------------
if ~isempty(g.winrej) & size(g.winrej,2) > 2
for tpmi = 1:size(g.winrej,1) % scan rows
if (g.winrej(tpmi,1) >= lowlim & g.winrej(tpmi,1) <= highlim) | ...
(g.winrej(tpmi,2) >= lowlim & g.winrej(tpmi,2) <= highlim)
abscmin = max(1,round(g.winrej(tpmi,1)-lowlim));
abscmax = round(g.winrej(tpmi,2)-lowlim);
maxXlim = get(gca, 'xlim');
abscmax = min(abscmax, round(maxXlim(2)-1));
for i = 1:g.chans
if g.winrej(tpmi,g.chans-i+1+5)
plot(abscmin+1:abscmax+1,data(g.chans-i+1,abscmin+lowlim:abscmax+lowlim) ...
-meandata(g.chans-i+1)+i*g.spacing + (g.dispchans+1)*(oldspacing-g.spacing)/2 +g.elecoffset*(oldspacing-g.spacing), 'color','r','clipping','on')
end;
end
end;
end;
end;
g.spacing = oldspacing;
set(ax1, 'Xlim',[1 g.winlength*multiplier+1],...
'XTick',[1:multiplier*DEFAULT_GRID_SPACING:g.winlength*multiplier+1]);
set(ax1, 'XTickLabel', num2str((g.time:DEFAULT_GRID_SPACING:g.time+g.winlength)'))
% ordinates: even if all elec are plotted, some may be hidden
set(ax1, 'ylim',[g.elecoffset*g.spacing (g.elecoffset+g.dispchans+1)*g.spacing] );
if g.children ~= 0
if ~exist('p2')
p2 =[];
end;
eegplot( 'drawp', p1, p2, g.children);
figure(figh);
end;
% draw second data if necessary
if ~isempty(g.data2)
tmpdata = data;
set(ax1, 'userdata', g.data2);
g.data2 = [];
g.plotdata2 = 'on';
set(figh, 'userdata', g);
eegplot('drawp', 0);
g.plotdata2 = 'off';
g.data2 = get(ax1, 'userdata');
set(ax1, 'userdata', tmpdata);
set(figh, 'userdata', g);
else
eegplot('drawb');
end;
case 'drawb' % Draw background ******************************************************
% Redraw EEG and change position
ax0 = findobj('tag','backeeg','parent',gcf); % axes handle
ax1 = findobj('tag','eegaxis','parent',gcf); % axes handle
g = get(gcf,'UserData'); % Data (Note: this could also be global)
% Plot data and update axes
axes(ax0);
cla;
hold on;
% plot rejected windows
if g.trialstag ~= -1
multiplier = g.trialstag;
else
multiplier = g.srate;
end;
% draw rejection windows
% ----------------------
lowlim = round(g.time*multiplier+1);
highlim = round(min((g.time+g.winlength)*multiplier+1));
displaymenu = findobj('tag','displaymenu','parent',gcf);
if ~isempty(g.winrej) & g.winstatus
if g.trialstag ~= -1 % epoched data
indices = find((g.winrej(:,1)' >= lowlim & g.winrej(:,1)' <= highlim) | ...
(g.winrej(:,2)' >= lowlim & g.winrej(:,2)' <= highlim));
if ~isempty(indices)
tmpwins1 = g.winrej(indices,1)';
tmpwins2 = g.winrej(indices,2)';
if size(g.winrej,2) > 2
tmpcols = g.winrej(indices,3:5);
else tmpcols = g.wincolor;
end;
try, eval('[cumul indicescount] = histc(tmpwins1, (min(tmpwins1)-1):g.trialstag:max(tmpwins2));');
catch, [cumul indicescount] = myhistc(tmpwins1, (min(tmpwins1)-1):g.trialstag:max(tmpwins2));
end;
count = zeros(size(cumul));
%if ~isempty(find(cumul > 1)), find(cumul > 1), end;
for tmpi = 1:length(tmpwins1)
poscumul = indicescount(tmpi);
heightbeg = count(poscumul)/cumul(poscumul);
heightend = heightbeg + 1/cumul(poscumul);
count(poscumul) = count(poscumul)+1;
h = patch([tmpwins1(tmpi)-lowlim tmpwins2(tmpi)-lowlim ...
tmpwins2(tmpi)-lowlim tmpwins1(tmpi)-lowlim], ...
[heightbeg heightbeg heightend heightend], ...
tmpcols(tmpi,:)); % this argument is color
set(h, 'EdgeColor', get(h, 'facecolor'))
end;
end;
else
event2plot1 = find ( g.winrej(:,1) >= lowlim & g.winrej(:,1) <= highlim );
event2plot2 = find ( g.winrej(:,2) >= lowlim & g.winrej(:,2) <= highlim );
event2plot3 = find ( g.winrej(:,1) < lowlim & g.winrej(:,2) > highlim );
event2plot = union_bc(union(event2plot1, event2plot2), event2plot3);
for tpmi = event2plot(:)'
if size(g.winrej,2) > 2
tmpcols = g.winrej(tpmi,3:5);
else tmpcols = g.wincolor;
end;
h = patch([g.winrej(tpmi,1)-lowlim g.winrej(tpmi,2)-lowlim ...
g.winrej(tpmi,2)-lowlim g.winrej(tpmi,1)-lowlim], ...
[0 0 1 1], tmpcols);
set(h, 'EdgeColor', get(h, 'facecolor'))
end;
end;
end;
% plot tags
% ---------
%if trialtag(1) ~= -1 & displaystatus % put tags at arbitrary places
% for tmptag = trialtag
% if tmptag >= lowlim & tmptag <= highlim
% plot([tmptag-lowlim tmptag-lowlim], [0 1], 'b--');
% end;
% end;
%end;
% draw events if any
% ------------------
if strcmpi(g.plotevent, 'on')
% JavierLC ###############################
MAXEVENTSTRING = g.maxeventstring;
if MAXEVENTSTRING<0
MAXEVENTSTRING = 0;
elseif MAXEVENTSTRING>75
MAXEVENTSTRING=75;
end
AXES_POSITION = [0.0964286 0.15 0.842 0.75-(MAXEVENTSTRING-5)/100];
% JavierLC ###############################
% find event to plot
% ------------------
event2plot = find ( g.eventlatencies >=lowlim & g.eventlatencies <= highlim );
if ~isempty(g.eventlatencyend)
event2plot2 = find ( g.eventlatencyend >= lowlim & g.eventlatencyend <= highlim );
event2plot3 = find ( g.eventlatencies < lowlim & g.eventlatencyend > highlim );
event2plot = union_bc(union(event2plot, event2plot2), event2plot3);
end;
for index = 1:length(event2plot)
% draw latency line
% -----------------
tmplat = g.eventlatencies(event2plot(index))-lowlim-1;
tmph = plot([ tmplat tmplat ], ylim, 'color', g.eventcolors{ event2plot(index) }, ...
'linestyle', g.eventstyle { event2plot(index) }, ...
'linewidth', g.eventwidths( event2plot(index) ) );
% schtefan: add Event types text above event latency line
% -------------------------------------------------------
EVENTFONT = ' \fontsize{10} ';
ylims=ylim;
evntxt = strrep(num2str(g.events(event2plot(index)).type),'_','-');
if length(evntxt)>MAXEVENTSTRING, evntxt = [ evntxt(1:MAXEVENTSTRING-1) '...' ]; end; % truncate
try,
tmph2 = text([tmplat], ylims(2)-0.005, [EVENTFONT evntxt], ...
'color', g.eventcolors{ event2plot(index) }, ...
'horizontalalignment', 'left',...
'rotation',90);
catch, end;
% draw duration is not 0
% ----------------------
if g.ploteventdur & ~isempty(g.eventlatencyend) ...
& g.eventwidths( event2plot(index) ) ~= 2.5 % do not plot length of boundary events
tmplatend = g.eventlatencyend(event2plot(index))-lowlim-1;
if tmplatend ~= 0,
tmplim = ylim;
tmpcol = g.eventcolors{ event2plot(index) };
h = patch([ tmplat tmplatend tmplatend tmplat ], ...
[ tmplim(1) tmplim(1) tmplim(2) tmplim(2) ], ...
tmpcol ); % this argument is color
set(h, 'EdgeColor', 'none')
end;
end;
end;
else % JavierLC
MAXEVENTSTRING = 10; % default
AXES_POSITION = [0.0964286 0.15 0.842 0.75-(MAXEVENTSTRING-5)/100];
end;
if g.trialstag(1) ~= -1
% plot trial limits
% -----------------
tmptag = [lowlim:highlim];
tmpind = find(mod(tmptag-1, g.trialstag) == 0);
for index = tmpind
plot([tmptag(index)-lowlim-1 tmptag(index)-lowlim-1], [0 1], 'b--');
end;
alltag = tmptag(tmpind);
% compute Xticks
% --------------
tagnum = (alltag-1)/g.trialstag+1;
set(ax0,'XTickLabel', tagnum,'YTickLabel', [],...
'Xlim',[0 g.winlength*multiplier],...
'XTick',alltag-lowlim+g.trialstag/2, 'YTick',[], 'tag','backeeg');
axes(ax1);
tagpos = [];
tagtext = [];
if ~isempty(alltag)
alltag = [alltag(1)-g.trialstag alltag alltag(end)+g.trialstag]; % add border trial limits
else
alltag = [ floor(lowlim/g.trialstag)*g.trialstag ceil(highlim/g.trialstag)*g.trialstag ]+1;
end;
nbdiv = 20/g.winlength; % approximative number of divisions
divpossible = [ 100000./[1 2 4 5] 10000./[1 2 4 5] 1000./[1 2 4 5] 100./[1 2 4 5 10 20]]; % possible increments
[tmp indexdiv] = min(abs(nbdiv*divpossible-(g.limits(2)-g.limits(1)))); % closest possible increment
incrementpoint = divpossible(indexdiv)/1000*g.srate;
% tag zero below is an offset used to be sure that 0 is included
% in the absicia of the data epochs
if g.limits(2) < 0, tagzerooffset = (g.limits(2)-g.limits(1))/1000*g.srate+1;
else tagzerooffset = -g.limits(1)/1000*g.srate;
end;
if tagzerooffset < 0, tagzerooffset = 0; end;
for i=1:length(alltag)-1
if ~isempty(tagpos) & tagpos(end)-alltag(i)<2*incrementpoint/3
tagpos = tagpos(1:end-1);
end;
if ~isempty(g.freqlimits)
tagpos = [ tagpos linspace(alltag(i),alltag(i+1)-1, nbdiv) ];
else
if tagzerooffset ~= 0
tmptagpos = [alltag(i)+tagzerooffset:-incrementpoint:alltag(i)];
else
tmptagpos = [];
end;
tagpos = [ tagpos [tmptagpos(end:-1:2) alltag(i)+tagzerooffset:incrementpoint:(alltag(i+1)-1)]];
end;
end;
% find corresponding epochs
% -------------------------
tagtext = eeg_point2lat(tagpos, floor((tagpos)/g.trialstag)+1, g.srate, g.limits, 1E-3);
set(ax1,'XTickLabel', tagtext,'XTick', tagpos-lowlim);
else
set(ax0,'XTickLabel', [],'YTickLabel', [],...
'Xlim',[0 g.winlength*multiplier],...
'XTick',[], 'YTick',[], 'tag','backeeg');
axes(ax1);
set(ax1,'XTickLabel', num2str((g.time:DEFAULT_GRID_SPACING:g.time+g.winlength)'),...
'XTick',[1:multiplier*DEFAULT_GRID_SPACING:g.winlength*multiplier+1])
set(ax1, 'Position', AXES_POSITION) % JavierLC
set(ax0, 'Position', AXES_POSITION) % JavierLC
end;
% ordinates: even if all elec are plotted, some may be hidden
set(ax1, 'ylim',[g.elecoffset*g.spacing (g.elecoffset+g.dispchans+1)*g.spacing] );
axes(ax1)
case 'draws'
% Redraw EEG and change scale
ax1 = findobj('tag','eegaxis','parent',gcf); % axes handle
g = get(gcf,'UserData');
data = get(ax1, 'userdata');
ESpacing = findobj('tag','ESpacing','parent',gcf); % ui handle
EPosition = findobj('tag','EPosition','parent',gcf); % ui handle
if g.trialstag(1) == -1
g.time = str2num(get(EPosition,'string'));
else
g.time = str2num(get(EPosition,'string'))-1;
end;
g.spacing = str2num(get(ESpacing,'string'));
orgspacing= g.spacing;
if p1 == 1
g.spacing= g.spacing+ 0.1*orgspacing; % increase g.spacing(5%)
elseif p1 == 2
g.spacing= max(0,g.spacing-0.1*orgspacing); % decrease g.spacing(5%)
end
if round(g.spacing*100) == 0
maxindex = min(10000, g.frames);
g.spacing = 0.01*max(max(data(:,1:maxindex),[],2),[],1)-min(min(data(:,1:maxindex),[],2),[],1); % Set g.spacingto max/min data
end;
% update edit box
% ---------------
set(ESpacing,'string',num2str(g.spacing,4))
set(gcf, 'userdata', g);
eegplot('drawp', 0);
set(ax1,'YLim',[0 (g.chans+1)*g.spacing],'YTick',[0:g.spacing:g.chans*g.spacing])
set(ax1, 'ylim',[g.elecoffset*g.spacing (g.elecoffset+g.dispchans+1)*g.spacing] );
% update scaling eye (I) if it exists
% -----------------------------------
eyeaxes = findobj('tag','eyeaxes','parent',gcf);
if ~isempty(eyeaxes)
eyetext = findobj('type','text','parent',eyeaxes,'tag','thescalenum');
set(eyetext,'string',num2str(g.spacing,4))
end
return;
case 'window' % change window size
% get new window length with dialog box
% -------------------------------------
g = get(gcf,'UserData');
result = inputdlg2( { fastif(g.trialstag==-1,'New window length (s):', 'Number of epoch(s):') }, 'Change window length', 1, { num2str(g.winlength) });
if size(result,1) == 0 return; end;
g.winlength = eval(result{1});
set(gcf, 'UserData', g);
eegplot('drawp',0);
return;
case 'winelec' % change channel window size
% get new window length with dialog box
% -------------------------------------
fig = gcf;
g = get(gcf,'UserData');
result = inputdlg2( ...
{ 'Number of channels to display:' } , 'Change number of channels to display', 1, { num2str(g.dispchans) });
if size(result,1) == 0 return; end;
g.dispchans = eval(result{1});
if g.dispchans<0 | g.dispchans>g.chans
g.dispchans =g.chans;
end;
set(gcf, 'UserData', g);
eegplot('updateslider', fig);
eegplot('drawp',0);
eegplot('scaleeye', [], fig);
return;
case 'emaxstring' % change events' string length ; JavierLC
% get dialog box
% -------------------------------------
g = get(gcf,'UserData');
result = inputdlg2({ 'Max events'' string length:' } , 'Change events'' string length to display', 1, { num2str(g.maxeventstring) });
if size(result,1) == 0 return; end;
g.maxeventstring = eval(result{1});
set(gcf, 'UserData', g);
eegplot('drawb');
return;
case 'loadelect' % load channels
[inputname,inputpath] = uigetfile('*','Channel locations file');
if inputname == 0 return; end;
if ~exist([ inputpath inputname ])
error('no such file');
end;
AXH0 = findobj('tag','eegaxis','parent',gcf);
eegplot('setelect',[ inputpath inputname ],AXH0);
return;
case 'setelect'
% Set channels
eloc_file = p1;
axeshand = p2;
outvar1 = 1;
if isempty(eloc_file)
outvar1 = 0;
return
end
tmplocs = readlocs(eloc_file);
YLabels = { tmplocs.labels };
YLabels = strvcat(YLabels);
YLabels = flipud(str2mat(YLabels,' '));
set(axeshand,'YTickLabel',YLabels)
case 'title'
% Get new title
h = findobj('tag', 'eegplottitle');
if ~isempty(h)
result = inputdlg2( { 'New title:' }, 'Change title', 1, { get(h(1), 'string') });
if ~isempty(result), set(h, 'string', result{1}); end;
else
result = inputdlg2( { 'New title:' }, 'Change title', 1, { '' });
if ~isempty(result), h = textsc(result{1}, 'title'); set(h, 'tag', 'eegplottitle');end;
end;
return;
case 'scaleeye'
% Turn scale I on/off
obj = p1;
figh = p2;
g = get(figh,'UserData');
% figh = get(obj,'Parent');
if ~isempty(obj)
eyeaxes = findobj('tag','eyeaxes','parent',figh);
children = get(eyeaxes,'children');
if isstr(obj)
if strcmp(obj, 'off')
set(children, 'visible', 'off');
set(eyeaxes, 'visible', 'off');
return;
else
set(children, 'visible', 'on');
set(eyeaxes, 'visible', 'on');
end;
else
toggle = get(obj,'checked');
if strcmp(toggle,'on')
set(children, 'visible', 'off');
set(eyeaxes, 'visible', 'off');
set(obj,'checked','off');
return;
else
set(children, 'visible', 'on');
set(eyeaxes, 'visible', 'on');
set(obj,'checked','on');
end;
end;
end;
eyeaxes = findobj('tag','eyeaxes','parent',figh);
ax1 = findobj('tag','eegaxis','parent',gcf); % axes handle
YLim = get(ax1, 'ylim');
ESpacing = findobj('tag','ESpacing','parent',figh);
g.spacing= str2num(get(ESpacing,'string'));
axes(eyeaxes); cla; axis off;
set(eyeaxes, 'ylim', YLim);
Xl = [.35 .65; .5 .5; .35 .65];
Yl = [ g.spacing g.spacing; g.spacing 0; 0 0] + YLim(1);
plot(Xl(1,:),Yl(1,:),'color',DEFAULT_AXIS_COLOR,'clipping','off', 'tag','eyeline'); hold on;
plot(Xl(2,:),Yl(2,:),'color',DEFAULT_AXIS_COLOR,'clipping','off', 'tag','eyeline');
plot(Xl(3,:),Yl(3,:),'color',DEFAULT_AXIS_COLOR,'clipping','off', 'tag','eyeline');
text(.5,(YLim(2)-YLim(1))/23+Yl(1),num2str(g.spacing,4),...
'HorizontalAlignment','center','FontSize',10,...
'tag','thescalenum')
text(Xl(2)+.1,Yl(1),'+','HorizontalAlignment','left',...
'verticalalignment','middle', 'tag', 'thescale')
text(Xl(2)+.1,Yl(4),'-','HorizontalAlignment','left',...
'verticalalignment','middle', 'tag', 'thescale')
if ~isempty(SPACING_UNITS_STRING)
text(.5,-YLim(2)/23+Yl(4),SPACING_UNITS_STRING,...
'HorizontalAlignment','center','FontSize',10, 'tag', 'thescale')
end
text(.5,(YLim(2)-YLim(1))/10+Yl(1),'Scale',...
'HorizontalAlignment','center','FontSize',10, 'tag', 'thescale')
set(eyeaxes, 'tag', 'eyeaxes');
case 'noui'
if ~isempty(varargin)
eegplot( varargin{:} ); fig = gcf;
else
fig = findobj('tag', 'EEGPLOT');
end;
set(fig, 'menubar', 'figure');
% find button and text
obj = findobj(fig, 'style', 'pushbutton'); delete(obj);
obj = findobj(fig, 'style', 'edit'); delete(obj);
obj = findobj(fig, 'style', 'text');
%objscale = findobj(obj, 'tag', 'thescale');
%delete(setdiff(obj, objscale));
obj = findobj(fig, 'tag', 'Eelec');delete(obj);
obj = findobj(fig, 'tag', 'Etime');delete(obj);
obj = findobj(fig, 'tag', 'Evalue');delete(obj);
obj = findobj(fig, 'tag', 'Eelecname');delete(obj);
obj = findobj(fig, 'tag', 'Etimename');delete(obj);
obj = findobj(fig, 'tag', 'Evaluename');delete(obj);
obj = findobj(fig, 'type', 'uimenu');delete(obj);
case 'zoom' % if zoom
fig = varargin{1};
ax1 = findobj('tag','eegaxis','parent',fig);
ax2 = findobj('tag','backeeg','parent',fig);
tmpxlim = get(ax1, 'xlim');
tmpylim = get(ax1, 'ylim');
tmpxlim2 = get(ax2, 'xlim');
set(ax2, 'xlim', get(ax1, 'xlim'));
g = get(fig,'UserData');
% deal with abscissa
% ------------------
if g.trialstag ~= -1
Eposition = str2num(get(findobj('tag','EPosition','parent',fig), 'string'));
g.winlength = (tmpxlim(2) - tmpxlim(1))/g.trialstag;
Eposition = Eposition + (tmpxlim(1) - tmpxlim2(1)-1)/g.trialstag;
Eposition = round(Eposition*1000)/1000;
set(findobj('tag','EPosition','parent',fig), 'string', num2str(Eposition));
else
Eposition = str2num(get(findobj('tag','EPosition','parent',fig), 'string'))-1;
g.winlength = (tmpxlim(2) - tmpxlim(1))/g.srate;
Eposition = Eposition + (tmpxlim(1) - tmpxlim2(1)-1)/g.srate;
Eposition = round(Eposition*1000)/1000;
set(findobj('tag','EPosition','parent',fig), 'string', num2str(Eposition+1));
end;
% deal with ordinate
% ------------------
g.elecoffset = tmpylim(1)/g.spacing;
g.dispchans = round(1000*(tmpylim(2)-tmpylim(1))/g.spacing)/1000;
set(fig,'UserData', g);
eegplot('updateslider', fig);
eegplot('drawp', 0);
eegplot('scaleeye', [], fig);
% reactivate zoom if 3 arguments
% ------------------------------
if exist('p2') == 1
set(gcbf, 'windowbuttondownfcn', [ 'zoom(gcbf,''down''); eegplot(''zoom'', gcbf, 1);' ]);
set(gcbf, 'windowbuttonmotionfcn', g.commandselect{2});
end;
case 'updateslider' % if zoom
fig = varargin{1};
g = get(fig,'UserData');
sliider = findobj('tag','eegslider','parent',fig);
if g.elecoffset < 0
g.elecoffset = 0;
end;
if g.dispchans >= g.chans
g.dispchans = g.chans;
g.elecoffset = 0;
set(sliider, 'visible', 'off');
else
set(sliider, 'visible', 'on');
set(sliider, 'value', g.elecoffset/g.chans, ...
'sliderstep', [1/(g.chans-g.dispchans) g.dispchans/(g.chans-g.dispchans)]);
%'sliderstep', [1/(g.chans-1) g.dispchans/(g.chans-1)]);
end;
if g.elecoffset < 0
g.elecoffset = 0;
end;
if g.elecoffset > g.chans-g.dispchans
g.elecoffset = g.chans-g.dispchans;
end;
set(fig,'UserData', g);
eegplot('scaleeye', [], fig);
case 'drawlegend'
fig = varargin{1};
g = get(fig,'UserData');
if ~isempty(g.events) % draw vertical colored lines for events, add event name text above
nleg = length(g.eventtypes);
fig2 = figure('numbertitle', 'off', 'name', '', 'visible', 'off', 'menubar', 'none', 'color', DEFAULT_FIG_COLOR);
pos = get(fig2, 'position');
set(fig2, 'position', [ pos(1) pos(2) 130 14*nleg+20]);
for index = 1:nleg
plot([10 30], [(index-0.5) * 10 (index-0.5) * 10], 'color', g.eventtypecolors{index}, 'linestyle', ...
g.eventtypestyle{ index }, 'linewidth', g.eventtypewidths( index )); hold on;
if iscell(g.eventtypes)
th=text(35, (index-0.5)*10, g.eventtypes{index}, ...
'color', g.eventtypecolors{index});
else
th=text(35, (index-0.5)*10, num2str(g.eventtypes(index)), ...
'color', g.eventtypecolors{index});
end;
end;
xlim([0 130]);
ylim([0 nleg*10]);
axis off;
set(fig2, 'visible', 'on');
end;
% motion button: move windows or display current position (channel, g.time and activation)
% ----------------------------------------------------------------------------------------
case 'defmotioncom'
fig = varargin{1};
g = get(fig,'UserData');
ax1 = findobj('tag','backeeg','parent',fig);
tmppos = get(ax1, 'currentpoint');
if g.trialstag ~= -1,
lowlim = round(g.time*g.trialstag+1);
else, lowlim = round(g.time*g.srate+1);
end;
if g.incallback
g.winrej = [g.winrej(1:end-1,:)' [g.winrej(end,1) tmppos(1)+lowlim g.winrej(end,3:end)]']';
set(fig,'UserData', g);
eegplot('drawb');
else
hh = findobj('tag','Etime','parent',fig);
if g.trialstag ~= -1,
set(hh, 'string', num2str(mod(tmppos(1)+lowlim-1,g.trialstag)/g.trialstag*(g.limits(2)-g.limits(1)) + g.limits(1)));
else set(hh, 'string', num2str((tmppos(1)+lowlim-1)/g.srate)); % put g.time in the box
end;
ax1 = findobj('tag','eegaxis','parent',fig);
tmppos = get(ax1, 'currentpoint');
tmpelec = round(tmppos(1,2) / g.spacing);
tmpelec = min(max(double(tmpelec), 1),g.chans);
labls = get(ax1, 'YtickLabel');
hh = findobj('tag','Eelec','parent',fig); % put electrode in the box
if ~g.envelope
set(hh, 'string', labls(tmpelec+1,:));
else
set(hh, 'string', ' ');
end
hh = findobj('tag','Evalue','parent',fig);
if ~g.envelope
eegplotdata = get(ax1, 'userdata');
set(hh, 'string', num2str(eegplotdata(g.chans+1-tmpelec, min(g.frames,max(1,double(round(tmppos(1)+lowlim))))))); % put value in the box
else
set(hh,'string',' ');
end
end;
% add topoplot
% ------------
case 'topoplot'
fig = varargin{1};
g = get(fig,'UserData');
if ~isstruct(g.eloc_file) || ~isfield(g.eloc_file, 'theta') || isempty( [ g.eloc_file.theta ])
return;
end;
ax1 = findobj('tag','backeeg','parent',fig);
tmppos = get(ax1, 'currentpoint');
ax1 = findobj('tag','eegaxis','parent',fig); % axes handle
% plot vertical line
yl = ylim;
plot([ tmppos tmppos ], yl, 'color', [0.8 0.8 0.8]);
if g.trialstag ~= -1,
lowlim = round(g.time*g.trialstag+1);
else, lowlim = round(g.time*g.srate+1);
end;
data = get(ax1,'UserData');
datapos = max(1, round(tmppos(1)+lowlim));
datapos = min(datapos, g.frames);
figure; topoplot(data(:,datapos), g.eloc_file);
if g.trialstag == -1,
latsec = (datapos-1)/g.srate;
title(sprintf('Latency of %d seconds and %d milliseconds', floor(latsec), round(1000*(latsec-floor(latsec)))));
else
trial = ceil((datapos-1)/g.trialstag);
latintrial = eeg_point2lat(datapos, trial, g.srate, g.limits, 0.001);
title(sprintf('Latency of %d ms in trial %d', round(latintrial), trial));
end;
return;
% release button: check window consistency, add to trial boundaries
% -------------------------------------------------------------------
case 'defupcom'
fig = varargin{1};
g = get(fig,'UserData');
ax1 = findobj('tag','backeeg','parent',fig);
g.incallback = 0;
set(fig,'UserData', g); % early save in case of bug in the following
if strcmp(g.mocap,'on'), g.winrej = g.winrej(end,:);end; % nima
if ~isempty(g.winrej)', ...
if g.winrej(end,1) == g.winrej(end,2) % remove unitary windows
g.winrej = g.winrej(1:end-1,:);
else
if g.winrej(end,1) > g.winrej(end,2) % reverse values if necessary
g.winrej(end, 1:2) = [g.winrej(end,2) g.winrej(end,1)];
end;
g.winrej(end,1) = max(1, g.winrej(end,1));
g.winrej(end,2) = min(g.frames, g.winrej(end,2));
if g.trialstag == -1 % find nearest trials boundaries if necessary
I1 = find((g.winrej(end,1) >= g.winrej(1:end-1,1)) & (g.winrej(end,1) <= g.winrej(1:end-1,2)) );
if ~isempty(I1)
g.winrej(I1,2) = max(g.winrej(I1,2), g.winrej(end,2)); % extend epoch
g.winrej = g.winrej(1:end-1,:); % remove if empty match
else,
I2 = find((g.winrej(end,2) >= g.winrej(1:end-1,1)) & (g.winrej(end,2) <= g.winrej(1:end-1,2)) );
if ~isempty(I2)
g.winrej(I2,1) = min(g.winrej(I2,1), g.winrej(end,1)); % extend epoch
g.winrej = g.winrej(1:end-1,:); % remove if empty match
else,
I2 = find((g.winrej(end,1) <= g.winrej(1:end-1,1)) & (g.winrej(end,2) >= g.winrej(1:end-1,1)) );
if ~isempty(I2)
g.winrej(I2,:) = []; % remove if empty match
end;
end;
end;
end;
end;
end;
set(fig,'UserData', g);
eegplot('drawp', 0);
if strcmp(g.mocap,'on'), show_mocap_for_eegplot(g.winrej); g.winrej = g.winrej(end,:); end; % nima
% push button: create/remove window
% ---------------------------------
case 'defdowncom'
show_mocap_timer = timerfind('tag','mocapDisplayTimer'); if ~isempty(show_mocap_timer), end; % nima
fig = varargin{1};
g = get(fig,'UserData');
ax1 = findobj('tag','backeeg','parent',fig);
tmppos = get(ax1, 'currentpoint');
if strcmp(get(fig, 'SelectionType'),'normal');
g = get(fig,'UserData'); % get data of backgroung image {g.trialstag g.winrej incallback}
if g.incallback ~= 1 % interception of nestest calls
if g.trialstag ~= -1,
lowlim = round(g.time*g.trialstag+1);
highlim = round(g.winlength*g.trialstag);
else,
lowlim = round(g.time*g.srate+1);
highlim = round(g.winlength*g.srate);
end;
if (tmppos(1) >= 0) & (tmppos(1) <= highlim),
if isempty(g.winrej) Allwin=0;
else Allwin = (g.winrej(:,1) < lowlim+tmppos(1)) & (g.winrej(:,2) > lowlim+tmppos(1));
end;
if any(Allwin) % remove the mark or select electrode if necessary
lowlim = find(Allwin==1);
if g.setelectrode % select electrode
ax2 = findobj('tag','eegaxis','parent',fig);
tmppos = get(ax2, 'currentpoint');
tmpelec = g.chans + 1 - round(tmppos(1,2) / g.spacing);
tmpelec = min(max(tmpelec, 1), g.chans);
g.winrej(lowlim,tmpelec+5) = ~g.winrej(lowlim,tmpelec+5); % set the electrode
else % remove mark
g.winrej(lowlim,:) = [];
end;
else
if g.trialstag ~= -1 % find nearest trials boundaries if epoched data
alltrialtag = [0:g.trialstag:g.frames];
I1 = find(alltrialtag < (tmppos(1)+lowlim) );
if ~isempty(I1) & I1(end) ~= length(alltrialtag),
g.winrej = [g.winrej' [alltrialtag(I1(end)) alltrialtag(I1(end)+1) g.wincolor zeros(1,g.chans)]']';
end;
else,
g.incallback = 1; % set this variable for callback for continuous data
if size(g.winrej,2) < 5
g.winrej(:,3:5) = repmat(g.wincolor, [size(g.winrej,1) 1]);
end;
if size(g.winrej,2) < 5+g.chans
g.winrej(:,6:(5+g.chans)) = zeros(size(g.winrej,1),g.chans);
end;
g.winrej = [g.winrej' [tmppos(1)+lowlim tmppos(1)+lowlim g.wincolor zeros(1,g.chans)]']';
end;
end;
set(fig,'UserData', g);
eegplot('drawp', 0); % redraw background
end;
end;
end;
otherwise
error(['Error - invalid eegplot() parameter: ',data])
end
end
% function not supported under Mac
% --------------------------------
function [reshist, allbin] = myhistc(vals, intervals);
reshist = zeros(1, length(intervals));
allbin = zeros(1, length(vals));
for index=1:length(vals)
minvals = vals(index)-intervals;
bintmp = find(minvals >= 0);
[mintmp indextmp] = min(minvals(bintmp));
bintmp = bintmp(indextmp);
allbin(index) = bintmp;
reshist(bintmp) = reshist(bintmp)+1;
end;
|
github
|
lcnbeapp/beapp-master
|
eegplugin_MARA.m
|
.m
|
beapp-master/Packages/MARA-master/eegplugin_MARA.m
| 2,770 |
utf_8
|
7619f29fb825e45ca839265d7d4046e0
|
% eegplugin_MARA() - EEGLab plugin to classify artifactual ICs based on
% 6 features from the time domain, the frequency domain,
% and the pattern
%
% Inputs:
% fig - [integer] EEGLAB figure
% try_strings - [struct] "try" strings for menu callbacks.
% catch_strings - [struct] "catch" strings for menu callbacks.
%
% See also: pop_processMARA(), processMARA(), MARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function eegplugin_MARA( fig, try_strings, catch_strings)
toolsmenu = findobj(fig, 'tag', 'tools');
h = uimenu(toolsmenu, 'label', 'IC Artifact Classification (MARA)');
uimenu(h, 'label', 'MARA Classification', 'callback', ...
[try_strings.no_check ...
'[ALLEEG,EEG,CURRENTSET,LASTCOM]= pop_processMARA( ALLEEG ,EEG ,CURRENTSET );' ...
catch_strings.add_to_hist ]);
uimenu(h, 'label', 'Visualize Components', 'tag', 'MARAviz', 'Enable', ...
'off', 'callback', [try_strings.no_check ...
'EEG = pop_selectcomps_MARA(EEG); pop_visualizeMARAfeatures(EEG.reject.gcompreject, EEG.reject.MARAinfo); ' ...
catch_strings.add_to_hist ]);
uimenu(h, 'label', 'About', 'Separator', 'on', 'Callback', ...
['warndlg2(sprintf([''MARA automatizes the process of hand-labeling independent components for ', ...
'artifact rejection. It is a supervised machine learning algorithm that learns from ', ...
'expert ratings of 1290 components. Features were optimized to solve the binary classification problem ', ...
'reject vs. accept.\n \n', ...
'If you have questions or suggestions about the toolbox, please contact \n ', ...
'Irene Winkler, TU Berlin [email protected] \n \n ', ...
'Reference: \nI. Winkler, S. Haufe, and M. Tangermann, Automatic classification of artifactual', ...
'ICA-components for artifact removal in EEG signals, Behavioral and Brain Functions, 7, 2011.''])', ...
',''About MARA'');']);
|
github
|
lcnbeapp/beapp-master
|
pop_visualizeMARAfeatures.m
|
.m
|
beapp-master/Packages/MARA-master/pop_visualizeMARAfeatures.m
| 4,558 |
utf_8
|
c888a9b58c7e7893d090883d152d5e09
|
% pop_visualizeMARAfeatures() - Display features that MARA's decision
% for artifact rejection is based on
%
% Usage:
% >> pop_visualizeMARAfeatures(gcompreject, MARAinfo);
%
% Inputs:
% gcompreject - array <1 x nIC> containing 1 if component was rejected
% MARAinfo - struct containing more information about MARA classification
% (output of function <MARA>)
% .posterior_artefactprob : posterior probability for each
% IC of being an artefact according to
% .normfeats : <6 x nIC > features computed by MARA for each IC,
% normalized by the training data
% The features are: (1) Current Density Norm, (2) Range
% in Pattern, (3) Local Skewness of the Time Series,
% (4) Lambda, (5) 8-13 Hz, (6) FitError.
%
% See also: MARA(), processMARA(), pop_selectcomps_MARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function pop_visualizeMARAfeatures(gcompreject, MARAinfo)
%try
set(0,'units','pixels');
resolution = get(0, 'Screensize');
width = resolution(3);
height = resolution(4);
panelsettings.rowsize = 200;
panelsettings.columnsize = 200;
panelsettings.columns = floor(width/(2*panelsettings.columnsize));
panelsettings.rows = floor(height/panelsettings.rowsize);
panelsettings.numberPerPage = panelsettings.columns * panelsettings.rows;
panelsettings.pages = ceil(length(gcompreject)/ panelsettings.numberPerPage);
% display components on a number of different pages
for page=1:panelsettings.pages
selectcomps_1page(page, panelsettings, gcompreject, MARAinfo);
end;
%catch
% eeglab_error
%end
function EEG = selectcomps_1page(page, panelsettings, gcompreject, MARAinfo)
try, icadefs;
catch,
BACKCOLOR = [0.8 0.8 0.8];
GUIBUTTONCOLOR = [0.8 0.8 0.8];
end;
% set up the figure
% %%%%%%%%%%%%%%%%
if ~exist('fig')
mainFig = figure('name', 'Visualize MARA features', 'numbertitle', 'off');
set(mainFig, 'Color', BACKCOLOR)
set(gcf,'MenuBar', 'none');
pos = get(gcf,'Position');
set(gcf,'Position', [20 20 panelsettings.columnsize*panelsettings.columns panelsettings.rowsize*panelsettings.rows]);
end;
% compute range of components to display
if page < panelsettings.pages
range = (1 + (panelsettings.numberPerPage * (page-1))) : (panelsettings.numberPerPage + ( panelsettings.numberPerPage * (page-1)));
else
range = (1 + (panelsettings.numberPerPage * (page-1))) : length(gcompreject);
end
% draw each component
% %%%%%%%%%%%%%%%%
for i = 1:length(range)
subplot(panelsettings.rows, panelsettings.columns, i)
for j = 1:6
h = barh(j, MARAinfo.normfeats(j, range(i)));
hold on;
if j <= 4 && MARAinfo.normfeats(j, range(i)) > 0
set(h, 'FaceColor', [0.4 0 0]);
end
if j > 4 && MARAinfo.normfeats(j, range(i)) < 0
set(h, 'FaceColor', [0.4 0 0]);
end
end
axis square;
if mod(i, panelsettings.columns) == 1
set(gca,'YTick', 1:6, 'YTickLabel', {'Current Density Norm', ...
'Range in Pattern', 'Local Skewness', 'lambda', '8-13Hz', 'FitError'})
else
set(gca,'YTick', 1:6, 'YTickLabel', cell(1,6))
end
if gcompreject(range(i)) == 1
title(sprintf('IC %d, p-artifact = %1.2f', range(i),MARAinfo.posterior_artefactprob(range(i))),...
'Color', [0.4 0 0]);
set(gca, 'Color', [1 0.7 0.7])
%keyboard
else
title(sprintf('IC %d, p-artifact = %1.2f', range(i),MARAinfo.posterior_artefactprob(range(i))));
end
end
|
github
|
lcnbeapp/beapp-master
|
processMARA.m
|
.m
|
beapp-master/Packages/MARA-master/processMARA.m
| 6,510 |
utf_8
|
896a41c6475ec80bf7706cc7166ce7a8
|
% processMARA() - Processing for Automatic Artifact Classification with MARA.
% processMARA() calls MACA and saves the identified artifactual components
% in EEG.reject.gcompreject.
% The functions optionally filters the data, runs ICA, plots components or
% reject artifactual components immediately.
%
% Usage:
% >> [ALLEEG,EEG,CURRENTSET] = processMARA(ALLEEG,EEG,CURRENTSET,options)
%
% Inputs and Outputs:
% ALLEEG - array of EEG dataset structures
% EEG - current dataset structure or structure array
% (EEG.reject.gcompreject will be updated)
% CURRENTSET - index(s) of the current EEG dataset(s) in ALLEEG
%
%
% Optional Input:
% options - 1x5 array specifing optional operations, default is [0,0,0,0,0]
% - option(1) = 1 => filter the data before MARA classification
% - option(2) = 1 => run ica before MARA classification
% - option(3) = 1 => plot components to label them for rejection after MARA classification
% (for rejection)
% - option(4) = 1 => plot MARA features for each IC
% - option(4) = 1 => automatically reject MARA's artifactual
% components without inspecting them
%
% See also: pop_eegfilt(), pop_runica, MARA(), pop_selectcomps_MARA(), pop_subcomp
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ALLEEG,EEG,CURRENTSET] = processMARA(ALLEEG,EEG,CURRENTSET,varargin)
if isempty(EEG.chanlocs)
try
error('No channel locations. Aborting MARA.')
catch
eeglab_error;
return;
end
end
if not(isempty(varargin))
options = varargin{1};
else
options = [0 0 0 0 0];
end
%% filter the data
if options(1) == 1
disp('Filtering data');
[EEG, LASTCOM] = pop_eegfilt(EEG);
eegh(LASTCOM);
[ALLEEG EEG CURRENTSET, LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET);
eegh(LASTCOM);
end
%% run ica
if options(2) == 1
disp('Run ICA');
[EEG, LASTCOM] = pop_runica(EEG);
[ALLEEG EEG CURRENTSET, LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET);
eegh(LASTCOM);
end
%% check if ica components are present
[EEG LASTCOM] = eeg_checkset(EEG, 'ica');
if LASTCOM < 0
disp('There are no ICA components present. Aborting classification.');
return
else
eegh(LASTCOM);
end
%% classify artifactual components with MARA
[artcomps, MARAinfo] = MARA(EEG);
EEG.reject.MARAinfo = MARAinfo;
disp('MARA marked the following components for rejection: ')
if isempty(artcomps)
disp('None')
else
disp(artcomps)
disp(' ')
end
if isempty(EEG.reject.gcompreject)
EEG.reject.gcompreject = zeros(1,size(EEG.icawinv,2));
gcompreject_old = EEG.reject.gcompreject;
else % if gcompreject present check whether labels differ from MARA
if and(length(EEG.reject.gcompreject) == size(EEG.icawinv,2), ...
not(isempty(find(EEG.reject.gcompreject))))
tmp = zeros(1,size(EEG.icawinv,2));
tmp(artcomps) = 1;
if not(isequal(tmp, EEG.reject.gcompreject))
answer = questdlg(...
'Some components are already labeled for rejection. What do you want to do?',...
'Labels already present','Merge artifactual labels','Overwrite old labels', 'Cancel','Cancel');
switch answer,
case 'Overwrite old labels',
gcompreject_old = EEG.reject.gcompreject;
EEG.reject.gcompreject = zeros(1,size(EEG.icawinv,2));
disp('Overwrites old labels')
case 'Merge artifactual labels'
disp('Merges MARA''s and old labels')
gcompreject_old = EEG.reject.gcompreject;
case 'Cancel',
return;
end
else
gcompreject_old = EEG.reject.gcompreject;
end
else
EEG.reject.gcompreject = zeros(1,size(EEG.icawinv,2));
gcompreject_old = EEG.reject.gcompreject;
end
end
EEG.reject.gcompreject(artcomps) = 1;
try
EEGLABfig = findall(0, 'tag', 'EEGLAB');
MARAvizmenu = findobj(EEGLABfig, 'tag', 'MARAviz');
set(MARAvizmenu, 'Enable', 'on');
catch
keyboard
end
%% display components with checkbox to label them for artifact rejection
if options(3) == 1
if isempty(artcomps)
answer = questdlg2(...
'MARA identied no artifacts. Do you still want to visualize components?',...
'No artifacts identified','Yes', 'No', 'No');
if strcmp(answer,'No')
return;
end
end
[EEG, LASTCOM] = pop_selectcomps_MARA(EEG, gcompreject_old);
eegh(LASTCOM);
if options(4) == 1
pop_visualizeMARAfeatures(EEG.reject.gcompreject, EEG.reject.MARAinfo);
end
end
%% automatically remove artifacts
if and(and(options(5) == 1, not(options(3) == 1)), not(isempty(artcomps)))
try
[EEG LASTCOM] = pop_subcomp(EEG);
eegh(LASTCOM);
catch
eeglab_error
end
[ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET);
eegh(LASTCOM);
disp('Artifact rejection done.');
end
|
github
|
lcnbeapp/beapp-master
|
MARA.m
|
.m
|
beapp-master/Packages/MARA-master/MARA.m
| 12,568 |
utf_8
|
5127d8f931932b5c0760a9a61a0d0b6e
|
% MARA() - Automatic classification of multiple artifact components
% Classies artifactual ICs based on 6 features from the time domain,
% the frequency domain, and the pattern
%
% Usage:
% >> [artcomps, info] = MARA(EEG);
%
% Inputs:
% EEG - input EEG structure
%
% Outputs:
% artcomps - array containing the numbers of the artifactual
% components
% info - struct containing more information about MARA classification
% .posterior_artefactprob : posterior probability for each
% IC of being an artefact
% .normfeats : <6 x nIC > features computed by MARA for each IC,
% normalized by the training data
% The features are: (1) Current Density Norm, (2) Range
% in Pattern, (3) Local Skewness of the Time Series,
% (4) Lambda, (5) 8-13 Hz, (6) FitError.
%
% For more information see:
% I. Winkler, S. Haufe, and M. Tangermann, Automatic classification of artifactual ICA-components
% for artifact removal in EEG signals, Behavioral and Brain Functions, 7, 2011.
%
% See also: processMARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [artcomps, info] = MARA(EEG)
try
%%%%%%%%%%%%%%%%%%%%
%% Calculate features from the pattern (component map)
%%%%%%%%%%%%%%%%%%%%
% extract channel labels
clab = {};
for i=1:length(EEG.chanlocs)
clab{i} = EEG.chanlocs(i).labels;
end
% cut to channel labels common with training data
load('fv_training_MARA'); %load struct fv_tr
[clab_common i_te i_tr ] = intersect(upper(clab), upper(fv_tr.clab));
clab_common = fv_tr.clab(i_tr);
if length(clab_common) == 0
error(['There were no matching channeldescriptions found.' , ...
'MARA needs channel labels of the form Cz, Oz, F3, F4, Fz, etc. Aborting.'])
end
patterns = (EEG.icawinv(i_te,:));
[M100 idx] = get_M100_ADE(clab_common); %needed for Current Density Norm
disp('MARA is computing features. Please wait');
%standardize patterns
patterns = patterns./repmat(std(patterns,0,1),length(patterns(:,1)),1);
%compute current density norm
feats(1,:) = log(sqrt(sum((M100*patterns(idx,:)).^2)));
%compute spatial range
feats(2,:) = log(max(patterns) - min(patterns));
%%%%%%%%%%%%%%%%%%%%
%% Calculate time and frequency features
%%%%%%%%%%%%%%%%%%%%
%compute time and frequency features (Current Density Norm, Range Within Pattern,
%Average Local Skewness, Band Power 8 - 13 Hz)
feats(3:6,:) = extract_time_freq_features(EEG);
disp('Features ready');
%%%%%%%%%%%%%%%%%%%%%%
%% Adapt train features to clab
%%%%%%%%%%%%%%%%%%%%
fv_tr.pattern = fv_tr.pattern(i_tr, :);
fv_tr.pattern = fv_tr.pattern./repmat(std(fv_tr.pattern,0,1),length(fv_tr.pattern(:,1)),1);
fv_tr.x(2,:) = log(max(fv_tr.pattern) - min(fv_tr.pattern));
fv_tr.x(1,:) = log(sqrt(sum((M100 * fv_tr.pattern).^2)));
%%%%%%%%%%%%%%%%%%%%
%% Classification
%%%%%%%%%%%%%%%%%%%%
[C, foo, posterior] = classify(feats',fv_tr.x',fv_tr.labels(1,:));
artcomps = find(C == 0)';
info.posterior_artefactprob = posterior(:, 1)';
info.normfeats = (feats - repmat(mean(fv_tr.x, 2), 1, size(feats, 2)))./ ...
repmat(std(fv_tr.x,0, 2), 1, size(feats, 2));
catch
eeglab_error;
artcomps = [];
end
end
function features = extract_time_freq_features(EEG)
% - 1st row: Average Local Skewness
% - 2nd row: lambda
% - 3rd row: Band Power 8 - 13 Hz
% - 4rd row: Fit Error
%
data = EEG.data;
fs = EEG.srate; %sampling frequency
% transform epoched data into continous data
if length(size(data)) == 3
s = size(data);
data = reshape(data, [EEG.nbchan, prod(s(2:3))]);
end
%downsample (to 100-200Hz)
factor = max(floor(EEG.srate/100),1);
data = data(:, 1:factor:end);
fs = round(fs/factor);
%compute icaactivation and standardise variance to 1
icacomps = (EEG.icaweights * EEG.icasphere * data)';
icacomps = icacomps./repmat(std(icacomps,0,1),length(icacomps(:,1)),1);
icacomps = icacomps';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Calculate featues
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for ic=1:length(icacomps(:,1)) %for each component
fprintf('.');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Proc Spectrum for Channel
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[pxx, freq] = pwelch(icacomps(ic,:), ones(1, fs), [], fs, fs);
pxx = 10*log10(pxx * fs/2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The average log band power between 8 and 13 Hz
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
p = 0;
for i = 8:13
p = p + pxx(find(freq == i,1));
end
Hz8_13 = p / (13-8+1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% lambda and FitError: deviation of a component's spectrum from
% a protoptypical 1/frequency curve
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
p1.x = 2; %first point: value at 2 Hz
p1.y = pxx(find(freq == p1.x,1));
p2.x = 3; %second point: value at 3 Hz
p2.y = pxx(find(freq == p2.x,1));
%third point: local minimum in the band 5-13 Hz
p3.y = min(pxx(find(freq == 5,1):find(freq == 13,1)));
p3.x = freq(find(pxx == p3.y,1));
%fourth point: min - 1 in band 5-13 Hz
p4.x = p3.x - 1;
p4.y = pxx(find(freq == p4.x,1));
%fifth point: local minimum in the band 33-39 Hz
p5.y = min(pxx(find(freq == 33,1):find(freq == 39,1)));
p5.x = freq(find(pxx == p5.y,1));
%sixth point: min + 1 in band 33-39 Hz
p6.x = p5.x + 1;
p6.y = pxx(find(freq == p6.x,1));
pX = [p1.x; p2.x; p3.x; p4.x; p5.x; p6.x];
pY = [p1.y; p2.y; p3.y; p4.y; p5.y; p6.y];
myfun = @(x,xdata)(exp(x(1))./ xdata.^exp(x(2))) - x(3);
xstart = [4, -2, 54];
try
fittedmodel = lsqcurvefit(myfun,xstart,double(pX),double(pY), [], [], optimset('Display', 'off'));
catch
try
% If the optimization toolbox is missing we try with the CurveFit toolbox
opt = fitoptions('Method','NonlinearLeastSquares','Startpoint',xstart);
myfun = fittype('exp(x1)./x.^exp(x2) - x3;','options',opt);
fitobject = fit(double(pX),double(pY),myfun);
fittedmodel = [fitobject.x1, fitobject.x2, fitobject.x3];
catch
% If the CurveFit toolbox is also missing we try with the Statistitcs toolbox
myfun = @(p,xdata)(exp(p(1))./ xdata.^exp(p(2))) - p(3);
mdl = NonLinearModel.fit(double(pX),double(pY),myfun,xstart);
fittedmodel = mdl.Coefficients.Estimate(:)';
end
end
%FitError: mean squared error of the fit to the real spectrum in the band 2-40 Hz.
ts_8to15 = freq(find(freq == 8) : find(freq == 15));
fs_8to15 = pxx(find(freq == 8) : find(freq == 15));
fiterror = log(norm(myfun(fittedmodel, ts_8to15)-fs_8to15)^2);
%lambda: parameter of the fit
lambda = fittedmodel(2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Averaged local skewness 15s
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
interval = 15;
abs_local_scewness = [];
for i=1:interval:length(icacomps(ic,:))/fs-interval
abs_local_scewness = [abs_local_scewness, abs(skewness(icacomps(ic, i * fs:(i+interval) * fs)))];
end
if isempty(abs_local_scewness)
error('MARA needs at least 15ms long ICs to compute its features.')
else
mean_abs_local_scewness_15 = log(mean(abs_local_scewness));
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Append Features
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
features(:,ic)= [mean_abs_local_scewness_15, lambda, Hz8_13, fiterror];
end
disp('.');
end
function [M100, idx_clab_desired] = get_M100_ADE(clab_desired)
% [M100, idx_clab_desired] = get_M100_ADEC(clab_desired)
%
% IN clab_desired - channel setup for which M100 should be calculated
% OUT M100
% idx_clab_desired
% M100 is the matrix such that feature = norm(M100*ica_pattern(idx_clab_desired), 'fro')
%
% (c) Stefan Haufe
lambda = 100;
load inv_matrix_icbm152; %L (forward matrix 115 x 2124 x 3), clab (channel labels)
[cl_ ia idx_clab_desired] = intersect(clab, clab_desired);
F = L(ia, :, :); %forward matrix for desired channels labels
[n_channels m foo] = size(F); %m = 2124, number of dipole locations
F = reshape(F, n_channels, 3*m);
%H - matrix that centralizes the pattern, i.e. mean(H*pattern) = 0
H = eye(n_channels) - ones(n_channels, n_channels)./ n_channels;
%W - inverse of the depth compensation matrix Lambda
W = sloreta_invweights(L);
L = H*F*W;
%We have inv(L'L +lambda eye(size(L'*L))* L' = L'*inv(L*L' + lambda
%eye(size(L*L')), which is easier to calculate as number of dimensions is
%much smaller
%calulate the inverse of L*L' + lambda * eye(size(L*L')
[U D] = eig(L*L');
d = diag(D);
di = d+lambda;
di = 1./di;
di(d < 1e-10) = 0;
inv1 = U*diag(di)*U'; %inv1 = inv(L*L' + lambda *eye(size(L*L'))
%get M100
M100 = L'*inv1*H;
end
function W = sloreta_invweights(LL)
% inverse sLORETA-based weighting
%
% Synopsis:
% W = sloreta_invweights(LL);
%
% Arguments:
% LL: [M N 3] leadfield tensor
%
% Returns:
% W: [3*N 3*N] block-diagonal matrix of weights
%
% Stefan Haufe, 2007, 2008
%
% License
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see http://www.gnu.org/licenses/.
[M N NDUM]=size(LL);
L=reshape(permute(LL, [1 3 2]), M, N*NDUM);
L = L - repmat(mean(L, 1), M, 1);
T = L'*pinv(L*L');
W = spalloc(N*NDUM, N*NDUM, N*NDUM*NDUM);
for ivox = 1:N
W(NDUM*(ivox-1)+(1:NDUM), NDUM*(ivox-1)+(1:NDUM)) = (T(NDUM*(ivox-1)+(1:NDUM), :)*L(:, NDUM*(ivox-1)+(1:NDUM)))^-.5;
end
ind = [];
for idum = 1:NDUM
ind = [ind idum:NDUM:N*NDUM];
end
W = W(ind, ind);
end
function [i_te, i_tr] = findconvertedlabels(pos_3d, chanlocs)
% IN pos_3d - 3d-positions of training channel labels
% chanlocs - EEG.chanlocs structure of data to be classified
%compute spherical coordinates theta and phi for the training channel
%label
[theta, phi, r] = cart2sph(pos_3d(1,:),pos_3d(2,:), pos_3d(3,:));
theta = theta - pi/2;
theta(theta < -pi) = theta(theta < -pi) + 2*pi;
theta = theta*180/pi;
phi = phi * 180/pi;
theta(find(pos_3d(1,:) == 0 & pos_3d(2,:) == 0)) = 0; %exception for Cz
clab_common = {};
i_te = [];
i_tr = [];
%For each channel in EEG.chanlocs, try to find matching channel in
%training data
for chan = 1:length(chanlocs)
if not(isempty(chanlocs(chan).sph_phi))
idx = find((theta <= chanlocs(chan).sph_theta + 6) ...
& (theta >= chanlocs(chan).sph_theta - 6) ...
& (phi <= chanlocs(chan).sph_phi + 6) ...
& (phi >= chanlocs(chan).sph_phi - 6));
if not(isempty(idx))
i_tr = [i_tr, idx(1)];
i_te = [i_te, chan];
end
end
end
end
|
github
|
lcnbeapp/beapp-master
|
pop_selectcomps_MARA.m
|
.m
|
beapp-master/Packages/MARA-master/pop_selectcomps_MARA.m
| 7,617 |
utf_8
|
3df13de5291a735a3ae902eb9b7b4349
|
% pop_selectcomps_MARA() - Display components with checkbox to label
% them for artifact rejection
%
% Usage:
% >> EEG = pop_selectcomps_MARA(EEG, gcompreject_old);
%
% Inputs:
% EEG - Input dataset with rejected components (saved in
% EEG.reject.gcompreject)
%
% Optional Input:
% gcompreject_old - gcompreject to revert to in case the "Cancel"
% button is pressed
%
% Output:
% EEG - Output dataset with updated rejected components
%
% See also: processMARA(), pop_selectcomps()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, com] = pop_selectcomps_MARA(EEG, varargin)
if isempty(EEG.reject.gcompreject)
EEG.reject.gcompreject = zeros(size(EEG.icawinv,2));
end
if not(isempty(varargin))
gcompreject_old = varargin{1};
com = [ 'pop_selectcomps_MARA(' inputname(1) ',' inputname(2) ');'];
else
gcompreject_old = EEG.reject.gcompreject;
com = [ 'pop_selectcomps_MARA(' inputname(1) ');'];
end
try
set(0,'units','pixels');
resolution = get(0, 'Screensize');
width = resolution(3);
height = resolution(4);
panelsettings = {};
panelsettings.completeNumber = length(EEG.reject.gcompreject);
panelsettings.rowsize = 250;
panelsettings.columnsize = 300;
panelsettings.column = floor(width/panelsettings.columnsize);
panelsettings.rows = floor(height/panelsettings.rowsize);
panelsettings.numberPerPage = panelsettings.column * panelsettings.rows;
panelsettings.pages = ceil(length(EEG.reject.gcompreject)/ panelsettings.numberPerPage);
panelsettings.incy = 110;
panelsettings.incx = 110;
% display components on a number of different pages
for page=1:panelsettings.pages
EEG = selectcomps_1page(EEG, page, panelsettings, gcompreject_old);
end;
checks = findall(0, 'style', 'checkbox');
for i = 1: length(checks)
set(checks(i), 'Enable', 'on')
end
catch
eeglab_error
end
function EEG = selectcomps_1page(EEG, page, panelsettings, gcompreject_old)
% Display components with checkbox to label them for artifact rejection
try, icadefs;
catch,
BACKCOLOR = [0.8 0.8 0.8];
GUIBUTTONCOLOR = [0.8 0.8 0.8];
end;
% compute components (for plotting the spectrum)
if length(size(EEG.data)) == 3
s = size(EEG.data);
data = reshape(EEG.data, [EEG.nbchan, prod(s(2:3))]);
icacomps = EEG.icaweights * EEG.icasphere * data;
else
icacomps = EEG.icaweights * EEG.icasphere * EEG.data;
end
% set up the figure
% %%%%%%%%%%%%%%%%
if ~exist('fig')
mainFig = figure('name', [ 'MARA on dataset: ' EEG.setname ''], 'numbertitle', 'off', 'tag', 'ADEC - Plot');
set(mainFig, 'Color', BACKCOLOR)
set(gcf,'MenuBar', 'none');
pos = get(gcf,'Position');
set(gcf,'Position', [20 20 panelsettings.columnsize*panelsettings.column panelsettings.rowsize*panelsettings.rows]);
panelsettings.sizewx = 50/panelsettings.column;
panelsettings.sizewy = 80/panelsettings.rows;
pos = get(gca,'position'); % plot relative to current axes
hh = gca;
panelsettings.q = [pos(1) pos(2) 0 0];
panelsettings.s = [pos(3) pos(4) pos(3) pos(4)]./100;
axis off;
end;
% compute range of components to display
if page < panelsettings.pages
range = (1 + (panelsettings.numberPerPage * (page-1))) : (panelsettings.numberPerPage + ( panelsettings.numberPerPage * (page-1)));
else
range = (1 + (panelsettings.numberPerPage * (page-1))) : panelsettings.completeNumber;
end
data = struct;
data.gcompreject = EEG.reject.gcompreject;
data.gcompreject_old = gcompreject_old;
guidata(gcf, data);
% draw each component
% %%%%%%%%%%%%%%%%
count = 1;
for ri = range
% compute coordinates
X = mod(count-1, panelsettings.column)/panelsettings.column * panelsettings.incx-10;
Y = (panelsettings.rows-floor((count-1)/panelsettings.column))/panelsettings.rows * panelsettings.incy - panelsettings.sizewy*1.3;
% plot the head
if ~strcmp(get(gcf, 'tag'), 'ADEC - Plot');
disp('Aborting plot');
return;
end;
ha = axes('Units','Normalized', 'Position',[X Y panelsettings.sizewx*0.85 panelsettings.sizewy*0.85].*panelsettings.s+panelsettings.q);
topoplot( EEG.icawinv(:,ri), EEG.chanlocs, 'verbose', 'off', 'style' , 'fill');
axis square;
% plot the spectrum
ha = axes('Units','Normalized', 'Position',[X+1.05*panelsettings.sizewx Y-1 (panelsettings.sizewx*1.15)-1 panelsettings.sizewy-1].*panelsettings.s+panelsettings.q);
[pxx, freq] = pwelch(icacomps(ri,:), ones(1, EEG.srate), [], EEG.srate, EEG.srate);
pxx = 10*log10(pxx * EEG.srate/2);
plot(freq, pxx, 'LineWidth', 2)
xlim([0 50]);
grid on;
xlabel('Hz')
set(gca, 'Xtick', 0:10:50)
if isfield(EEG.reject, 'MARAinfo')
title(sprintf('Artifact Probability = %1.2f', ...
EEG.reject.MARAinfo.posterior_artefactprob(ri)));
end
uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[X+panelsettings.sizewx*0.5 Y+panelsettings.sizewy panelsettings.sizewx, ...
panelsettings.sizewy*0.2].*panelsettings.s+panelsettings.q, ...
'Enable', 'off','tag', ['check_' num2str(ri)], 'Value', EEG.reject.gcompreject(ri), ...
'String', ['IC' num2str(ri) ' - Artifact?'], ...
'Callback', {@callback_checkbox, ri});
drawnow;
count = count +1;
end;
% draw the botton buttons
% %%%%%%%%%%%%%%%%
if ~exist('fig')
% cancel button
cancelcommand = ['openplots = findall(0, ''tag'', ''ADEC - Plot'');', ...
'data = guidata(openplots(1)); close(openplots);', ...
'EEG.reject.gcompreject = data.gcompreject_old;'];
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'Cancel', ...
'Units','Normalized', 'BackgroundColor', GUIBUTTONCOLOR, ...
'Position',[-10 -11 15 panelsettings.sizewy*0.25].*panelsettings.s+panelsettings.q, ...
'callback', cancelcommand );
okcommand = ['data = guidata(gcf); EEG.reject.gcompreject = data.gcompreject; ' ...
'[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET); '...
'eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET);''); '...
'close(gcf);' ];
% ok button
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'OK', ...
'Units','Normalized', 'BackgroundColor', GUIBUTTONCOLOR, ...
'Position',[10 -11 15 panelsettings.sizewy*0.25].*panelsettings.s+panelsettings.q, ...
'callback', okcommand);
end;
function callback_checkbox(hObject,eventdata, position)
openplots = findall(0, 'tag', 'ADEC - Plot');
data = guidata(openplots(1));
data.gcompreject(position) = mod(data.gcompreject(position) + 1, 2);
%save changes in every plot
for i = 1: length(openplots)
guidata(openplots(i), data);
end
|
github
|
lcnbeapp/beapp-master
|
pop_processMARA.m
|
.m
|
beapp-master/Packages/MARA-master/pop_processMARA.m
| 5,095 |
utf_8
|
7932742793cce3ca7b8caeb78ae22d82
|
% pop_processMARA() - graphical interface to select MARA's actions
%
% Usage:
% >> [ALLEEG,EEG,CURRENTSET,com] = pop_processMARA(ALLEEG,EEG,CURRENTSET );
%
% Inputs and Outputs:
% ALLEEG - array of EEG dataset structures
% EEG - current dataset structure or structure array
% (EEG.reject.gcompreject will be updated)
% CURRENTSET - index(s) of the current EEG dataset(s) in ALLEEG
%
%
% Output:
% com - last command, call to itself
%
% See also: processMARA(), pop_selectcomps_MARA(), MARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ALLEEG,EEG,CURRENTSET,com] = pop_processMARA (ALLEEG,EEG,CURRENTSET )
com = 'pop_processMARA ( ALLEEG,EEG,CURRENTSET )';
try, icadefs;
catch,
BACKCOLOR = [0.8 0.8 0.8];
GUIBUTTONCOLOR = [0.8 0.8 0.8];
end;
% set up the figure
% %%%%%%%%%%%%%%%%%
figure('name', 'MARA', ...
'numbertitle', 'off', 'tag', 'ADEC - Init');
set(gcf,'MenuBar', 'none', 'Color', BACKCOLOR);
pos = get(gcf,'Position');
set(gcf,'Position', [pos(1) 350 350 350]);
if ~strcmp(get(gcf, 'tag'), 'ADEC - Init');
disp('Aborting plot');
return;
end;
% set standards for options and store them with guidata()
% order: filter, run_ica, plot data, remove automatically
options = [0, 0, 0, 0, 0];
guidata(gcf, options);
% text
% %%%%%%%%%%%%%%%%%
text = uicontrol(gcf, 'Style', 'text', 'Units','Normalized', 'Position',...
[0 0.85 0.75 0.06],'BackGroundColor', BACKCOLOR, 'FontWeight', 'bold', ...
'String', 'Select preprocessing operations:');
text = uicontrol(gcf, 'Style', 'text', 'Units','Normalized', 'Position',...
[0 0.55 0.75 0.06],'BackGroundColor', BACKCOLOR, 'FontWeight', 'bold', ...
'String', 'After MARA classification:');
% checkboxes
% %%%%%%%%%%%%%%%%%
filterBox = uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[0.075 0.75 0.75 0.075], 'String', 'Filter the data', 'Callback', ...
'options = guidata(gcf); options(1) = mod(options(1) + 1, 2); guidata(gcf,options);');
icaBox = uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[0.075 0.65 0.75 0.075], 'String', 'Run ICA', 'Callback', ...
'options = guidata(gcf); options(2) = mod(options(2) + 1, 2); guidata(gcf,options);');
% radio button group
% %%%%%%%%%%%%%%%%%
vizBox = uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[0.2 0.2 0.9 0.2], 'String', 'Visualize Classifcation Features', 'Enable', 'Off', ...
'tag', 'vizBox');
h = uibuttongroup('visible','off','Units','Normalized','Position',[0.075 0.15 0.9 0.35]);
% Create two radio buttons in the button group.
radNothing = uicontrol('Style','radiobutton','String','Continue using EEGLab functions',...
'Units','Normalized','Position',[0.02 0.8 0.9 0.2],'parent',h,'HandleVisibility','off','tag', 'radNothing');
radPlot = uicontrol('Style','radiobutton','String','Plot and select components for removal',...
'Units','Normalized','Position',[0.02 0.5 0.9 0.2],'parent',h,'HandleVisibility','off',...
'tag', 'radPlot');
radAuto = uicontrol('Style','radiobutton','String','Automatically remove components',...
'Units','Normalized','Position',[0.02 0.1 0.9 0.2],'parent',h,'HandleVisibility','off','tag', 'radAuto');
set(h,'SelectedObject',radNothing,'Visible','on', 'tag', 'h','BackGroundColor', BACKCOLOR);
set(h, 'SelectionChangeFcn',['s = guihandles(gcf); if get(s.h, ''SelectedObject'') == s.radPlot; ' ...
'set(s.vizBox,''Enable'', ''on''); else; set(s.vizBox,''Enable'', ''off''); end;']);
% bottom buttons
% %%%%%%%%%%%%%%%%%
cancel = uicontrol(gcf, 'Style', 'pushbutton', 'Units','Normalized', 'Position',...
[0.075 0.05 0.4 0.08],'String', 'Cancel','BackgroundColor', GUIBUTTONCOLOR,...
'Callback', 'close(gcf);');
ok = uicontrol(gcf, 'Style', 'pushbutton', 'Units','Normalized', 'Position',...
[0.5 0.05 0.4 0.08],'String', 'Ok','BackgroundColor', GUIBUTTONCOLOR, ...
'Callback', ['options = guidata(gcf);' ...
's = guihandles(gcf); if get(s.h, ''SelectedObject'') == s.radPlot; options(3) = 1; end; '...
'options(4) = get(s.vizBox, ''Value''); ' ...
'if get(s.h, ''SelectedObject'') == s.radAuto; options(5) = 1; end;' ...
'close(gcf); pause(eps); [ALLEEG, EEG, CURRENTSET] = processMARA(ALLEEG,EEG,CURRENTSET, options);']);
|
github
|
lcnbeapp/beapp-master
|
gen_HAPPE_output_table_after_crash.m
|
.m
|
beapp-master/reference_data/example_scripts/gen_HAPPE_output_table_after_crash.m
| 3,240 |
utf_8
|
2a5eb56fc5b8a26e3d27b8604f2dbe58
|
% create HAPPE report table for all files in directory if there is a crash
% during the ICA module
% function takes grp_proc_info from previous run
function gen_HAPPE_output_table_after_crash(grp_proc_info_in)
cd(grp_proc_info_in.beapp_toggle_mods{'ica','Module_Dir'}{1});
ica_report_categories = {'BEAPP_Fname','Time_Elapsed_For_File','Num_Rec_Periods', 'Number_Channels_UserSelected',...
'File_Rec_Period_Lengths_In_Secs','Number_Good_Channels_Selected_Per_Rec_Period', ...
'Interpolated_Channel_IDs_Per_Rec_Period', 'Percent_ICs_Rejected_Per_Rec_Period', ...
'Percent_Variance_Kept_of_Post_Waveleted_Data_Per_Rec_Period', ...
'Mean_Artifact_Probability_of_Kept_ICs_Per_Rec_Period','Median_Artifact_Probability_of_Kept_ICs_Per_Rec_Period'};
ICA_report_table= cell2table(cell(length(grp_proc_info_in.beapp_fname_all),length(ica_report_categories)));
ICA_report_table.Properties.VariableNames=ica_report_categories;
ICA_report_table.BEAPP_Fname = grp_proc_info_in.beapp_fname_all';
for curr_file=1:length(grp_proc_info_in.beapp_fname_all)
if exist(strcat(grp_proc_info_in.beapp_toggle_mods{'ica','Module_Dir'}{1},filesep,grp_proc_info_in.beapp_fname_all{curr_file}),'file')
load(grp_proc_info_in.beapp_fname_all{curr_file},'file_proc_info','eeg');
ICA_report_table.Num_Rec_Periods(curr_file) = num2cell(file_proc_info.beapp_num_epochs);
[~,epoch_lengths_in_samps] = cellfun(@size,eeg);
ICA_report_table.File_Rec_Period_Lengths_In_Secs(curr_file) = {epoch_lengths_in_samps/file_proc_info.beapp_srate};
chan_IDs_all = unique([grp_proc_info_in.name_10_20_elecs file_proc_info.net_happe_additional_chans_lbls]);
chan_IDs = intersect(chan_IDs_all,{file_proc_info.net_vstruct.labels});
ICA_report_table.Number_Channels_UserSelected(curr_file) = {length(chan_IDs)};
ICA_report_table.Number_Good_Channels_Selected_Per_Rec_Period(curr_file) = file_proc_info.ica_stats.Number_Good_Channels_Selected_Per_Rec_Period;
if ~all(cellfun(@isempty,file_proc_info.beapp_bad_chans))
tmp = cellfun(@mat2str,file_proc_info.beapp_bad_chans, 'UniformOutput',0);
ICA_report_table.Interpolated_Channel_IDs_Per_Rec_Period(curr_file) =tmp;
else
ICA_report_table.Interpolated_Channel_IDs_Per_Rec_Period(curr_file) ={''};
end
ICA_report_table.Percent_ICs_rejected_Per_Rec_Period(curr_file) = file_proc_info.ica_stats.Percent_ICs_Rejected_Per_Rec_Period;
ICA_report_table.Percent_Variance_Kept_of_Post_Waveleted_Data_Per_Rec_Period(curr_file) = file_proc_info.ica_stats.Percent_Variance_Kept_of_Post_Waveleted_Data_Per_Rec_Period;
ICA_report_table.Mean_Artifact_Probability_of_Kept_ICs_Per_Rec_Period(curr_file) = file_proc_info.ica_stats.Mean_Artifact_Probability_of_Kept_ICs_Per_Rec_Period;
ICA_report_table.Median_Artifact_Probability_of_Kept_ICs_Per_Rec_Period(curr_file) = file_proc_info.ica_stats.Median_Artifact_Probability_of_Kept_ICs_Per_Rec_Period;
end
clearvars -except grp_proc_info_in curr_file src_dir ICA_report_table
end
writetable(ICA_report_table, ['ICA_Report_Table ',grp_proc_info_in.beapp_curr_run_tag,'_after_crash.csv']);
|
github
|
DSAP1718/dsap1718_group2_proj-master
|
export_data.m
|
.m
|
dsap1718_group2_proj-master/VBA/export_data.m
| 3,451 |
utf_8
|
ef25565a86981986f9dddeb7f67a6a77
|
% ----------------------------------------------------------------------
% Digital Signal and Audio Processing
% Final Project: Acoustic Guitar-Pitch Detection
% using Cepstral Analysis Excel-GUI Analyzer
%
% Group No. 2
% Leader: Prince Julius T. Hari
% Members: Lester Y. Besabe
% Christian Erick L. Cimbracruz
% Vanessa E. Espino
% John Denver P. Felarca
% Hannah Lalaine Morasa1
% John Daryll M. Moya
%
% BSCS 4-4 AY 2017-18
% ----------------------------------------------------------------------
function export_data()
display(sprintf('\n\tChoose where to get the chord:\n'));
display(sprintf('\t\t[ 0 ] Actual Record'));
display(sprintf('\t\t[ 1 ] Search from files\n'));
% Prompts for user choice
prompt = sprintf('\tChoice: ');
try
choice = input(prompt);
catch
display(sprintf('\tInvalid input\n'));
end % try
if choice
get_from_files();
else
actual_record();
end % if choice
end % function export_data()
function actual_record()
SAMPLE_RATE = 44100; % Sample rate (Fs) in Hz
SAMPLE_SIZE = 16; % Sample size nBits
NUM_CHANNEL = 1; % Number of channels
RECORDING_TIME = 5;
rec_obj = audiorecorder(SAMPLE_RATE, SAMPLE_SIZE, NUM_CHANNEL);
display(sprintf('\tStart recording.'));
recordblocking(rec_obj, RECORDING_TIME);
display(sprintf('\tEnd of recording.\n'));
record_data = getaudiodata(rec_obj);
filename = 'record.wav';
audiowrite(filename, record_data, SAMPLE_RATE);
% Read and export the chord/sound
read_chord(filename);
end % actual_record()
function get_from_files()
% Look for an audio file (chord's file)
[file, path] = uigetfile('*.wav', 'Select chord (wave) file');
[~, ~, ext] = fileparts(file);
% Check if theres an audio file
if isequal(file,0)
display(sprintf('\n\tNo audio file found.'));
display(sprintf('\tProgram is terminated.\n'));
elseif isequal(ext,'.wav')
chord = strcat(path,'\',file);
% Read and export the chord/sound
read_chord(chord);
else
display(sprintf('\n\tNot an .wav file.'));
display(sprintf('\tProgram is terminated.\n'));
end
end % get_from_files()
function read_chord(chord)
XLFILE = 'guitar_pitch.xlsm'; % File where the data will be exported
SHEET = 'Sheet1'; % Sheet name of the file
RANGE1 = 'B3'; % Start cell where data will be written
RANGE2 = 'E3'; % Cell where sample rate will be written
RANGE3 = 'E4'; % Cell where no. samples will be written
no_error = 1; % Flag if theres no error
% Read audio file
[y, Fs] = audioread(chord);
display(y);
plot(y);
try
xlswrite(XLFILE, y, SHEET, RANGE1); % Write raw data
xlswrite(XLFILE, Fs, SHEET, RANGE2); % Write sampling Rate
xlswrite(XLFILE, length(y), SHEET, RANGE3); % NWrite no. of samples
catch
display(sprintf('\tA problem encountered while exporting the'));
display(sprintf('\traw data to %s\n', XLFILE));
no_error = 0;
end
if no_error
display(sprintf('\tSuccessfully exported the'));
display(sprintf('\traw data to %s\n', XLFILE));
end
end % function record_chord()
|
github
|
LIZHANGYAN/3D-Face-Recognition-using-Covariance-Based-Descriptors-master
|
read_bntfile.m
|
.m
|
3D-Face-Recognition-using-Covariance-Based-Descriptors-master/read_bntfile.m
| 1,058 |
utf_8
|
c560ad86fb267fbbd6f6e9e84880276e
|
% Author: Arman Savran ([email protected])
% Date: 2008
% Outputs:
% zmin : minimum depth value
% nrows : subsampled number of rows
% ncols : subsampled number of columns
% imfile : image file name
% data : Nx5 matrix where columns are 3D coordinates and 2D
% normalized image coordinates respectively. 2D coordinates are
% normalized to the range [0,1]. N = nrows*ncols. In this matrix, values
% that are equal to zmin denotes the background.
function [data, zmin, nrows, ncols, imfile] = read_bntfile(filepath)
%filepath = [directory '/' filename '.bnt'];
fid = fopen(filepath, 'r');
if (fid == -1)
disp(['Could not open file, ' filepath]);
return
end
nrows = fread(fid, 1, 'uint16');
ncols = fread(fid, 1, 'uint16');
zmin = fread(fid, 1, 'float64');
len = fread(fid, 1, 'uint16');
imfile = fread(fid, [1 len], 'uint8=>char');
% normally, size of data must be nrows*ncols*5
len = fread(fid, 1, 'uint32');
data = fread(fid, [len/5 5], 'float64');
fclose(fid);
|
github
|
Mr-Yuppie/SPBL-master
|
TrainBase.m
|
.m
|
SPBL-master/TrainBase.m
| 4,986 |
utf_8
|
2096e6af1d0a6a57e0afae32ff7d3392
|
function [new_Base,newH] = TrainBase(trainfea,traingnd,u,options)
% Function TrainBase accepts the samples' weights 'u' and their labels
% 'traingnd', and generates the current weak learner, with a type specified in
% 'options'.
% trainfea - the N x D input matrix, where each row data(i,:) corresponds to a data sample
tic;
checkfield(options,'options','type');
checkfield(options,'options','regu_weight',0);
if ~isempty(find(u<0,1)), error('TrainBase error: u must all >= 0.'); end
addpath L-BFGS-B-C-master/Matlab/;
[nSmp,dFea] = size(trainfea);
[label,~,ic] = unique(traingnd);
nClass = length(label);
if norm(label-(1:nClass)') > 0
labelidx = 1:nClass;
traingnd = labelidx(ic);
label = (1:nClass)';
end
augX = [trainfea,ones(nSmp,1)];
% bfgs_opts = struct('factr',1e5, 'pgtol',1e-7, 'm',10, 'printEvery',100);
bfgs_opts = struct('m',10, 'printEvery',Inf);
rw = options.regu_weight;
if nClass == 2 && size(u,2) == 1 % For the binary classification case
y = ones(nSmp,1); y(traingnd==label(2)) = -1;
lb = -Inf(dFea+1,1); ub = Inf(dFea+1,1);
switch options.type
case 'tanh'
[OptAugw,Optfval,Info] =...
lbfgsb(@(augw)tanhcost(augw,augX,u.*y,rw),lb,ub,bfgs_opts);
newH = tanh(augX*OptAugw);
case 'logistic'
[OptAugw,Optfval,Info] =...
lbfgsb(@(augw)logicost(augw,augX,u.*y,rw),lb,ub,bfgs_opts);
newH = 1./(1+exp(-augX*OptAugw));
otherwise
error('Base learner type error in TrainBase: %s.',options.type);
end
Optfval = -Optfval;
etime = toc; fprintf('%.2f s.\n',etime);
new_Base = struct('w',OptAugw(1:(end-1)),'b',OptAugw(end),...
'fval',Optfval,'regu_weight',rw,'Info',Info,'type',options.type);
else % For the multiclass case
if size(u,2) ~= nClass
error('Dimension mismatch in TrainBase: size(u,2) ~= nlabel');
end
uy = full(sparse(1:nSmp,traingnd,sum(u,2))) - u;
lb_en = -Inf((dFea+1)*nClass,1); ub_en = Inf(size(lb_en));
switch options.type
case 'tanh'
[OptAugw,OptSumScore,~] = lbfgsb(@(augw)tanhcost(augw,augX,uy,rw),...
lb_en,ub_en,bfgs_opts);
OptSumScore = -OptSumScore;
OptAugw = reshape(OptAugw,dFea+1,nClass);
AllnewH = tanh(augX*OptAugw);
OptScores = sum(AllnewH.*uy,1) - sum(OptAugw(1:end-1,:).^2,1)*rw/2;
if abs(1-sum(OptScores)/OptSumScore) > 1e-5
error('tanhcost objective error!');
end
case 'logistic'
[OptAugw,OptSumScore,~] = lbfgsb(@(augw)logicost(augw,augX,uy,rw),...
lb_en,ub_en,bfgs_opts);
OptSumScore = -OptSumScore;
OptAugw = reshape(OptAugw,dFea+1,nClass);
AllnewH = 1./(1+exp(-augX*OptAugw));
OptScores = sum(AllnewH.*uy,1) - sum(OptAugw(1:end-1,:).^2,1)*rw/2;
if abs(1-sum(OptScores)/OptSumScore) > 1e-5
error('logistic objective error!');
end
otherwise
error('Base learner type error in TrainBase: %s.',options.type);
end
etime = toc; fprintf('%.2f s.\n',etime);
if isfield(options,'EachAug') && options.EachAug > 1
[~,scoreorder] = sort(OptScores,'descend');
for i = 1:options.EachAug
idx = scoreorder(i);
new_Base(i,1) = struct('w',OptAugw(1:(end-1),idx),'b',OptAugw(end,idx),...
'maxScore',OptScores(idx),'regu_weight',rw,'maxClass',label(idx),...
'type',options.type);
end
newH = AllnewH(:,scoreorder(1:options.EachAug));
else
[maxScore,maxidx] = max(OptScores);
new_Base = struct('w',OptAugw(1:(end-1),maxidx),'b',OptAugw(end,maxidx),...
'maxScore',maxScore,'regu_weight',rw,'maxClass',label(maxidx),...
'type',options.type);
newH = AllnewH(:,maxidx);
end
end
end
function [cost,grad] = logicost(augw,augX,uy,wei_regu)
% This function returns the logistic score and its grad w.r.t. the weights uy.
% augX: N x (D+1) matrix, where each row is a sample, augmented by 1 for each sample.
% augw: each column as [w_r;b_r], (D+1)xc matrix.
% uy = delta*sum(u,2)-u
% wei_regu: weight of l2-norm regularization of augw
% if nargin < 4
% wei_regu = 1e-4;
% end
augw = reshape(augw,[],size(uy,2));
cost_each = 1./(1+exp(-augX*augw));
cost = -sum(sum(cost_each.*uy)) + sum(sum(augw(1:end-1,:).^2))*wei_regu/2;
logi_grad = cost_each.*(1-cost_each);
grad = -augX' * (logi_grad.*uy) + [wei_regu*augw(1:end-1,:);zeros(1,size(uy,2))];
grad = reshape(grad,[],1);
end
function [cost,grad] = tanhcost(augw,augX,uy,wei_regu)
augw = reshape(augw,[],size(uy,2));
cost_each = tanh(augX * augw);
cost = -sum(sum(cost_each.*uy)) + sum(sum(augw(1:end-1,:).^2))*wei_regu/2;
tanh_grad = 1-cost_each.*cost_each;
grad = -augX' * (tanh_grad.*uy) + [wei_regu*augw(1:end-1,:);zeros(1,size(uy,2))];
grad = reshape(grad,[],1);
end
|
github
|
Mr-Yuppie/SPBL-master
|
lbfgsb.m
|
.m
|
SPBL-master/L-BFGS-B-C-master/Matlab/lbfgsb.m
| 10,268 |
utf_8
|
d9ca76459532b61543d9dac41d9ba87e
|
function [x,f,info] = lbfgsb( fcn, l, u, opts )
% x = lbfgsb( fcn, l, u )
% uses the lbfgsb v.3.0 library (fortran files must be installed;
% see compile_mex.m ) which is the L-BFGS-B algorithm.
% The algorithm is similar to the L-BFGS quasi-Newton algorithm,
% but also handles bound constraints via an active-set type iteration.
% This version is based on the modified C code L-BFGS-B-C, and so has
% a slightly different calling syntax than previous versions.
%
% The minimization problem that it solves is:
% min_x f(x) subject to l <= x <= u
%
% 'fcn' is a function handle that accepts an input, 'x',
% and returns two outputs, 'f' (function value), and 'g' (function gradient).
%
% 'l' and 'u' are column-vectors of constraints. Set their values to Inf
% if you want to ignore them. (You can set some values to Inf, but keep
% others enforced).
%
% The full format of the function is:
% [x,f,info] = lbfgsb( fcn, l, u, opts )
% where the output 'f' has the value of the function f at the final iterate
% and 'info' is a structure with useful information
% (self-explanatory, except for info.err. The first column of info.err
% is the history of the function values f, and the second column
% is the history of norm( gradient, Inf ). )
%
% The 'opts' structure allows you to pass further options.
% Possible field name values:
%
% opts.x0 The starting value (default: all zeros)
% opts.m Number of limited-memory vectors to use in the algorithm
% Try 3 <= m <= 20. (default: 5 )
% opts.factr Tolerance setting (see this source code for more info)
% (default: 1e7 ). This is later multiplied by machine epsilon
% opts.pgtol Another tolerance setting, relating to norm(gradient,Inf)
% (default: 1e-5)
% opts.maxIts How many iterations to allow (default: 100)
% opts.maxTotalIts How many iterations to allow, including linesearch iterations
% (default: 5000)
% opts.printEvery How often to display information (default: 1)
% opts.errFcn A function handle (or cell array of several function handles)
% that computes whatever you want. The output will be printed
% to the screen every 'printEvery' iterations. (default: [] )
% Results saved in columns 3 and higher of info.err variable
%
% Stephen Becker, [email protected]
% Feb 14, 2012
% Updated Feb 21 2015, Stephen Becker, [email protected]
narginchk(3, 4)
if nargin < 4, opts = struct([]); end
% Matlab doesn't let you use the .name convention with structures
% if they are empty, so in that case, make the structure non-empty:
if isempty(opts), opts=struct('a',1) ; end
function out = setOpts( field, default, mn, mx )
if ~isfield( opts, field )
opts.(field) = default;
end
out = opts.(field);
if nargin >= 3 && ~isempty(mn) && any(out < mn), error('Value is too small'); end
if nargin >= 4 && ~isempty(mx) && any(out > mx), error('Value is too large'); end
opts = rmfield( opts, field ); % so we can do a check later
end
% [f,g] = callF( x );
if iscell(fcn)
% the user has given us separate functions to compute
% f (function) and g (gradient)
callF = @(x) fminunc_wrapper(x,fcn{1},fcn{2} );
else
callF = fcn;
end
n = length(l);
if length(u) ~= length(l), error('l and u must be same length'); end
x0 = setOpts( 'x0', zeros(n,1) );
x = x0 + 0; % important: we want Matlab to make a copy of this.
% just in case 'x' will be modified in-place
% (Feb 2015 version of code, it should not be modified,
% but just-in-case, may as well leave this )
if size(x0,2) ~= 1, error('x0 must be a column vector'); end
if size(l,2) ~= 1, error('l must be a column vector'); end
if size(u,2) ~= 1, error('u must be a column vector'); end
if size(x,1) ~= n, error('x0 and l have mismatchig sizes'); end
if size(u,1) ~= n, error('u and l have mismatchig sizes'); end
% Number of L-BFGS memory vectors
% From the fortran driver file:
% "Values of m < 3 are not recommended, and
% large values of m can result in excessive computing time.
% The range 3 <= m <= 20 is recommended. "
m = setOpts( 'm', 5, 0 );
% 'nbd' is 0 if no bounds, 1 if lower bound only,
% 2 if both upper and lower bounds, and 3 if upper bound only.
% This .m file assumes l=-Inf and u=+Inf imply that there are no constraints.
% So, convert this to the fortran convention:
nbd = isfinite(l) + isfinite(u) + 2*isinf(l).*isfinite(u);
if ispc
nbd = int32(nbd);
else
nbd = int64(nbd);
end
% Some scalar settings, "factr" and "pgtol"
% Their descriptions, from the fortran file:
% factr is a DOUBLE PRECISION variable that must be set by the user.
% It is a tolerance in the termination test for the algorithm.
% The iteration will stop when
%
% (f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr*epsmch
%
% where epsmch is the machine precision which is automatically
% generated by the code. Typical values for factr on a computer
% with 15 digits of accuracy in double precision are:
% factr=1.d+12 for low accuracy;
% 1.d+7 for moderate accuracy;
% 1.d+1 for extremely high accuracy.
% The user can suppress this termination test by setting factr=0.
factr = setOpts( 'factr', 1e7, 0 );
% pgtol is a double precision variable.
% On entry pgtol >= 0 is specified by the user. The iteration
% will stop when
%
% max{|proj g_i | i = 1, ..., n} <= pgtol
%
% where pg_i is the ith component of the projected gradient.
% The user can suppress this termination test by setting pgtol=0.
pgtol = setOpts( 'pgtol', 1e-5, 0 ); % may crash if < 0
% Maximum number of outer iterations
maxIts = setOpts( 'maxIts', 100, 1 );
% Maximum number of total iterations
% (this includes the line search steps )
maxTotalIts = setOpts( 'maxTotalIts', 5e3 );
% Print out information this often (and set to Inf to suppress)
printEvery = setOpts( 'printEvery', 1 );
errFcn = setOpts( 'errFcn', [] );
iprint = setOpts('verbose',-1);
% <0 for no output, 0 for some, 1 for more, 99 for more, 100 for more
% I recommend you set this -1 and use the Matlab print features
% (e.g., set printEvery )
fcn_wrapper(); % initialized persistent variables
callF_wrapped = @(x,varargin) fcn_wrapper( callF, errFcn, maxIts, ...
printEvery, x, varargin{:} );
% callF_wrapped = @(x,varargin)callF(x); % also valid, but simpler
% Call the mex file
[f,x,taskInteger,outer_count, k] = lbfgsb_wrapper( m, x, l, u, nbd, ...
callF_wrapped, factr, pgtol, ...
iprint, maxIts, maxTotalIts);
info.iterations = outer_count;
info.totalIterations = k;
info.lbfgs_message1 = findTaskString( taskInteger );
errHist = fcn_wrapper();
info.err = errHist;
end % end of main function
function [f,g] = fcn_wrapper( callF, errFcn, maxIts, printEvery, x, varargin )
persistent k history
if isempty(k), k = 1; end
if nargin==0
% reset persistent variables and return information
if ~isempty(history) && ~isempty(k)
% printFcn(k,history);
f = history(1:k,:);
end
history = [];
k = [];
return;
end
if isempty( history )
width = 0;
if iscell( errFcn ), width = length(errFcn);
elseif ~isempty(errFcn), width = 1; end
width = width + 2; % include fcn and norm(grad) as well
history = zeros( maxIts, width );
end
% Find function value and gradient:
[f,g] = callF(x);
if nargin > 5
outerIter = varargin{1}+1;
history(outerIter,1) = f;
history(outerIter,2) = norm(g,Inf); % g is not projected
if isa( errFcn, 'function_handle' )
history(outerIter,3) = errFcn(x);
elseif iscell( errFcn )
for j = 1:length(errFcn)
history(outer_count,j+2) = errFcn{j}(x);
end
end
if outerIter > k
% Display info from *previous* input
% Since this may be called several times before outerIter
% is actually updated
% fprintf('At iterate %5d, f(x)= %.2e, ||grad||_infty = %.2e [MATLAB]\n',...
% k,history(k,1),history(k,2) );
if ~isinf(printEvery) && ~mod(k,printEvery)
% printFcn(k,history);
end
k = outerIter;
end
end
end
function printFcn(k,history)
fprintf('Iter %5d, f(x) = %2e, ||grad||_infty = %.2e', ...
k, history(k,1), history(k,2) );
for col = 3:size(history,2)
fprintf(', %.2e', history(k,col) );
end
fprintf('\n');
end
function [f,g] = fminunc_wrapper(x,F,G)
% [f,g] = fminunc_wrapper( x, F, G )
% for use with Matlab's "fminunc"
f = F(x);
if nargin > 2 && nargout > 1
g = G(x);
end
end
function str = findTaskString( taskInteger )
% See the #define statements in lbfgsb.h
switch taskInteger
case 209
str = 'ERROR: N .LE. 0';
case 210
str = 'ERROR: M .LE. 0';
case 211
str = 'ERROR: FACTR .LT. 0';
case 3
str = 'ABNORMAL_TERMINATION_IN_LNSRCH.';
case 4
str = 'RESTART_FROM_LNSRCH.';
case 21
str = 'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL.';
case 22
str = 'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH.';
case 31
str = 'STOP: CPU EXCEEDING THE TIME LIMIT.';
case 32
str = 'STOP: TOTAL NO. of f AND g EVALUATIONS EXCEEDS LIM.';
case 33
str = 'STOP: THE PROJECTED GRADIENT IS SUFFICIENTLY SMALL.';
case 101
str = 'WARNING: ROUNDING ERRORS PREVENT PROGRESS';
case 102
str = 'WARNING: XTOL TEST SATISIED';
case 103
str = 'WARNING: STP = STPMAX';
case 104
str = 'WARNING: STP = STPMIN';
case 201
str = 'ERROR: STP .LT. STPMIN';
case 202
str = 'ERROR: STP .GT. STPMAX';
case 203
str = 'ERROR: INITIAL G .GE. ZERO ';
case 204
str = 'ERROR: FTOL .LT. ZERO';
case 205
str = 'ERROR: GTOL .LT. ZERO';
case 206
str = 'ERROR: XTOL .LT. ZERO';
case 207
str = 'ERROR: STPMIN .LT. ZERO';
case 208
str = 'ERROR: STPMAX .LT. STPMIN';
case 212
str = 'ERROR: INVALID NBD';
case 213
str = 'ERROR: NO FEASIBLE SOLUTION';
otherwise
str = 'UNRECOGNIZED EXIT FLAG';
end
end
|
github
|
zucar/Driver-Assistance-System-master
|
sanim_XY_vehicle_viz.m
|
.m
|
Driver-Assistance-System-master/Path Planning/Resources/Matlab_simulation/sanim_XY_vehicle_viz.m
| 16,640 |
utf_8
|
b5889ef5a1fa2d9b5713061122047130
|
function [sys,x0,str,ts] = sanim_XY_vehicle_viz(t,x,u,flag,Config)
% sanim_XY_vehicle_viz() - animate a 2D vehicle using SAE coordinates.
%
% This is a modified version of the Mathwork's sanim.m for animating 3D motion.
%
% Marc Compere, [email protected]
% created : 30 July 2011
% modified: 17 Jan 2016
%
%
% Edited from the original file:
% SANIM.m S-Function for displaying 6DoF trajectories
%
% See also: Simulink library file 'aerospace.mdl' and sanim.m
%
% Copyright 1990-2002 The MathWorks, Inc.
% J.Hodgson
% $Revision: 1.12 $ $Date: 2002/04/09 19:37:27 $
% for command line development:
%x=[0 10 0 10 0]
%u=[0 0 0]
switch flag,
%%%%%%%%%%%%%%%%%%
% Initialization %
%%%%%%%%%%%%%%%%%%
case 0,
[sys,x0,str,ts]=mdlInitializeSizes(Config);
%%%%%%%%%%%%%%%
% Derivatives %
%%%%%%%%%%%%%%%
case {1, 3, 9},
sys=[];
%%%%%%%%%%
% Update %
%%%%%%%%%%
case 2,
sys = [];
sys=mdlUpdate(t,x,u,Config);
%%%%%%%%%%%%%%%%%%%%%%%
% GetTimeOfNextVarHit %
%%%%%%%%%%%%%%%%%%%%%%%
case 4,
sys=mdlGetTimeOfNextVarHit(t,x,u,Config.Ts);
otherwise
%%%%%%%%%%%%%%%%%%%%
% Unexpected flags %
%%%%%%%%%%%%%%%%%%%%
error(['Unhandled flag = ',num2str(flag)]);
end
end % sanim_XY_pairs()
%
%=============================================================================
% mdlInitializeSizes
% Return the sizes, initial conditions, and sample times for the S-function.
%=============================================================================
%
function [sys,x0,str,ts]=mdlInitializeSizes(Config)
%
% Set Sizes Matrix
%
sizes = simsizes;
sizes.NumContStates = 0;
sizes.NumDiscStates = 6; % x(1:4) => [xmin xmax ymin ymax] when axisMode==0 (auto),
% x(5)=>initState for line trace setup is ZERO at t=0 and >0 for t>0
% x(6) counter for creating animation frame sequences
sizes.NumOutputs = 0;
sizes.NumInputs = 4; % [X_veh, Y_veh, psi_veh, delta_steer] in the global XY frame
sizes.DirFeedthrough = 0;
sizes.NumSampleTimes = 1; % at least one sample time is needed
sys = simsizes(sizes);
%
% initialise the initial conditions
%
%x0 = [];
%
% str is always an empty matrix
%
str = [];
%
% initialise the array of sample times
%
%ts = [.1 0]; % Sample period of 0.1 seconds (10Hz)
ts = [Config.Ts 0]; % inherited
%
% Initialise Figure Window
%
h_f=findobj('type','figure','Tag','XY anim');
if isempty(h_f)
h_anim=figure;
else
h_anim=h_f;
end
% Figure 'position' args -> [left, bottom, width, height]
% put the keyboard input figure right in the upper middle
screen_size=get(0,'ScreenSize'); % [left, bottom, width, height] (in pixels)
set_figure_window_size=0;
if set_figure_window_size==1,
figure_width=672; figure_height=504; % (pixels) Matlab defaults are 560x420(?) or... 672x504 on my laptop
figure_left = screen_size(3) - figure_width - 10; % (pixels) almost all the way to the left side of the screen
figure_bottom = screen_size(4) - figure_height - 100; % (pixels) almost all the way to the top of the screen
set(h_anim,'name','XY Animation Figure', ...
'renderer','OpenGL', ...
'clipping','off', ...
'position',[figure_left figure_bottom figure_width figure_height],...
'Tag','XY anim');
else
set(h_anim,'name','XY Animation Figure', ...
'renderer','OpenGL', ...
'clipping','off', ...
'Tag','XY anim');
end
%Painters
%Zbuffer
%OpenGL
if ~isempty(h_anim) % if there's a figure window..
h_del = findobj(h_anim,'type','axes'); % find the axes..
delete(h_del); % delete the axes..
figure(h_anim); % bring figure to the front
end
%
% Initialize Axes
%
handle.axes(1)=axes;
set(handle.axes(1),...
'visible','on','box','off', ...
'units','normal', ...
'position',[0.1 0.1 0.75 0.75], ...
'Color',[.8 .8 .8], ...
'clipping','off',...
'XMinorTick','on',...
'YMinorTick','on',...
'Tag','3d_axes');
% this reverses the direction of increasing Y values
% to make Matlab figure window conform to SAE coordinates where:
% +X is to the right (as usual)
% +Y is down
% +Z is into the paper
set(handle.axes(1),'YDir','reverse')
% set axes to initial [xmin xmax ymin ymax]
axis(Config.ax);
x0=axis; % assign iniital state to current axis limits
x0(5)=0; % initState==0 at t=0 and >0 for t>0
x0(6)=0; % animation frame counter (only writes .jpegs if save_anim_frames==1)
grid on
axis equal
xlabel('SAE X_{gnd} (m)')
ylabel('SAE Y_{gnd} (m)')
%
% Initialize snail trail objects (CG line trace and rearAxle trace)
%
cmap_CG = colormap(cool(1)); % run 'colormapeditor' then choose in Tools | Standard Colormaps for examples
if (Config.enable_CG_trace==1),
line_width = 2;
handle.line_CG = line(0,0); % N times with the client using each of the N lines for each server restart
set(handle.line_CG,'linestyle','-','color',cmap_CG,'userdata',0,'clipping','off','LineWidth',line_width); % create line object for trace indicating where the Nth agent has been
end
cmap_rearAxle = colormap(spring(1)); % colormaps: hsv, gray, hot, cool, copper, pink, flag, jet, autumn, spring, summer, winter
if (Config.enable_rearAxle_trace==1),
line_width = 2;
handle.line_rearAxle = line(0,0); % N times with the client using each of the N lines for each server restart
set(handle.line_rearAxle,'linestyle','-.','color',cmap_rearAxle,'userdata',0,'clipping','off','LineWidth',line_width); % create line object for trace indicating where the Nth agent has been
end
%
% Initialize vehicle object trajectories (chassis, front and rear tires)
%
% make a generic set of vertices and faces for a 2D vehicle object
veh=veh_object2(1,Config.L,Config.W); % see 'help patch' for how to make patch graphics objects
cmap_veh = colormap(summer(1)); % colormaps: hsv, gray, hot, cool, copper, pink, flag, jet, autumn, spring, summer, winter
handle.veh = patch('Vertices',veh.vertices','Faces',veh.faces,'AmbientStrength',0.46,'FaceColor',cmap_veh,'EdgeColor',[0 0 0],'FaceAlpha',0.1);
X_loc=sum(veh.vertices(1,:))/length(veh.vertices(1,:));
Y_loc=sum(veh.vertices(2,:))/length(veh.vertices(2,:));
handle.veh_text = text(X_loc,Y_loc,'veh','FontSize',10,'HorizontalAlignment','center','VerticalAlignment','middle'); % default FontSize is 10
% create tire vertices, then make 4 different graphics patch objects to move around independently
tire=veh_object2(2,Config.L/5,Config.W/5);
handle.tire_rf = patch('Vertices',tire.vertices','Faces',tire.faces,'AmbientStrength',0.46,'FaceColor',cmap_veh,'EdgeColor',[1 1 1],'FaceAlpha',0.1);
handle.tire_lf = patch('Vertices',tire.vertices','Faces',tire.faces,'AmbientStrength',0.46,'FaceColor',cmap_veh,'EdgeColor',[1 1 1],'FaceAlpha',0.1);
handle.tire_rr = patch('Vertices',tire.vertices','Faces',tire.faces,'AmbientStrength',0.46,'FaceColor',cmap_veh,'EdgeColor',[1 1 1],'FaceAlpha',0.1);
handle.tire_lr = patch('Vertices',tire.vertices','Faces',tire.faces,'AmbientStrength',0.46,'FaceColor',cmap_veh,'EdgeColor',[1 1 1],'FaceAlpha',0.1);
% we must store all unmodified vertices in their local coordinate
% frame so mdlUpdate() can orient and position in the global
% then store them in the AXES UserData (not the figure window's UsersData)
pass_these_verts{1} = get(handle.veh ,'Vertices');
pass_these_verts{2} = get(handle.tire_rf,'Vertices');
set(handle.axes(1),'userdata',pass_these_verts); % store veh object vertices for retrieval in mdlUpdate() below
%
% Set Handles of graphics in FIGURE UserData
%
set(h_anim,'UserData',handle); % store axes, line, and veh objects just created for retrieval in mdlUpdate()
end % mdlInitializeSizes
%
%=============================================================================
% mdlUpdate
% Handle discrete state updates, sample time hits, and major time step
% requirements.
%=============================================================================
%
function sys=mdlUpdate(t,x,u,Config);
sys=x; % initialize outputs
X = u(1); % (m) object positions in global XY frame
Y = u(2); % (m) object positions in global XY frame
yaw = u(3); % (rad) vehicle's yaw orientations about global Z axis
delta = u(4); % (rad) front tire's steered angle (w.r.t. vehicle yaw angle)
%
% Retrieve figure object handles
%
handle = get(findobj('type','figure','Tag','XY anim'),'userdata'); % retrieve all graphics objects handles
if isempty(findobj('type','figure','Tag','XY anim'))
%figure has been manually closed
return
end
%
% Update all object positions
%
if ~isempty(handle.axes(1))
% retrieve the object vertices from the figure window's AXES UserData
pass_these_verts=get(handle.axes(1),'UserData');
if isempty(pass_these_verts)
%axes userdata is missing for some reason - exit
return
end
else
% no axes handle for some reason - exit
return
end
% pull out the veh vertices
veh_verts = pass_these_verts{1};
tire_verts = pass_these_verts{2};
% now do all the same translation and rotation for the vehicle objects
% ----------------------------------------------------
% first: retrieve the i'th object's vertices (vehicle and rear two tires all have same)
verts_veh_xy = [veh_verts]; % pick off the i'th [X,Y] column pair
verts_tire_rf_xy = [tire_verts]; % all 4 tires use identical vertices prior to XY positioning
verts_tire_lf_xy = [tire_verts];
verts_tire_rr_xy = [tire_verts];
verts_tire_lr_xy = [tire_verts];
[a_veh,b] = size(verts_veh_xy); % a_veh is number of vertices in vehicle object (10 for vehicle_object2(1,[]) )
[a_tire,b] = size(verts_tire_rf_xy); % b_vehicle is number of vertices in tire object (12 for vehicle_object2(2,[]) )
attitude = [ cos(yaw) -sin(yaw) ; sin(yaw) cos(yaw) ]; % transformation matrix from body-fixed to global or terrain frame
attitude_steered = [ cos(delta) -sin(delta) ; sin(delta) cos(delta)]; % transformation matrix from body-fixed to global or terrain frame
% do the schmack: translate in body-fixed xy, rotate about yaw(i) with 'attitude', then translate in XY to the terrain frame's [X(i),Y(i)] position
verts_veh_XY = attitude*[verts_veh_xy' ] + [ X ; Y]*ones(1,a_veh );
verts_tire_rr_XY = attitude*[verts_tire_rr_xy' + [ -Config.L/2 ; -Config.W/2]*ones(1,a_tire)] + [ X ; Y]*ones(1,a_tire);
verts_tire_lr_XY = attitude*[verts_tire_rr_xy' + [ -Config.L/2 ; +Config.W/2]*ones(1,a_tire)] + [ X ; Y]*ones(1,a_tire);
% front tires require special consideration: rotate by steer angle first, then translate in xy, rotate by yaw, then translate in XY
verts_tire_rf_xy_steered = attitude_steered*[verts_tire_rf_xy'];
verts_tire_rf_XY = attitude*[verts_tire_rf_xy_steered + [Config.L/2;-Config.W/2]*ones(1,a_tire)] + [X;Y]*ones(1,a_tire);
verts_tire_lf_xy_steered = attitude_steered*[verts_tire_lf_xy'];
verts_tire_lf_XY = attitude*[verts_tire_lf_xy_steered + [Config.L/2;+Config.W/2]*ones(1,a_tire)] + [X;Y]*ones(1,a_tire);
% update the figure window object with the new position and orientation
set(handle.veh,'Vertices',verts_veh_XY');
set(handle.veh_text,'Position',[X;Y]);
set(handle.tire_rf,'Vertices',verts_tire_rf_XY'); % set graphics handle vertices to vertices just rotated and translated
set(handle.tire_lf,'Vertices',verts_tire_lf_XY');
set(handle.tire_rr,'Vertices',verts_tire_rr_XY');
set(handle.tire_lr,'Vertices',verts_tire_lr_XY');
%
% Update Line Objects
%
if (Config.enable_CG_trace==1),
initState = x(5); % 0 the first time through only
%str=sprintf('sanim_tracked_vehicle.m: initState=%i',initState);disp(str)
if initState>=1, % tack on the current vehicle positions to the vehicle line trace
xLine = get(handle.line_CG,'XData');
yLine = get(handle.line_CG,'YData');
% use the graphics line objects XData and YData to store and display a growing set of line points
set(handle.line_CG,'Xdata',[xLine X],'Ydata',[yLine Y]);
else % init==0 so create first line point from vehicle IC's coming in from the UDP client s-function (not the x0 initialized with zeros in this s-function)
sys(5)=1; % cause 'initState' to no longer be zero
set(handle.line_CG,'Xdata',X,'Ydata',Y);
end
end % if Config.enable_CG_trace==1
if (Config.enable_rearAxle_trace==1),
initState = x(5); % 0 the first time through only
%str=sprintf('sanim_tracked_vehicle.m: initState=%i',initState);disp(str)
if initState>=1, % tack on the current vehicle positions to the vehicle line trace
line_rearAxle_verts = attitude*[-Config.L/2 ; 0 ] + [X;Y]; % [X,Y] pair in i'th column
xLine = get(handle.line_rearAxle,'XData');
yLine = get(handle.line_rearAxle,'YData');
% use the graphics line objects XData and YData to store and display a growing set of line points
set(handle.line_rearAxle,'Xdata',[xLine line_rearAxle_verts(1)],'Ydata',[yLine line_rearAxle_verts(2)]);
else % init==0 so create first line point from vehicle IC's coming in from the UDP client s-function (not the x0 initialized with zeros in this s-function)
sys(5)=1; % cause 'initState' to no longer be zero
line_rearAxle_verts = attitude*[-Config.L/2 ; 0 ] + [X;Y]; % [X,Y] pair in i'th column
set(handle.line_rearAxle,'Xdata',line_rearAxle_verts(1),'Ydata',line_rearAxle_verts(2));
end
end % if Config.enable_rearAxle_trace==1
% -------------------------------------------
% -------- update the axis limits --------
% -------------------------------------------
sys(1:4)=x(1:4); % init the first 4 discrete state (updated immmediately below)
% this is where we grow the axis limits but never shrink - it captures
% all objects and zooms out but does not pan or shrink limits (looks better)
if (Config.axisMode==0), % -> GROW-TO-FIT from initial user-supplied axis limits
axis tight % this resets the axes to capture all objects
axisTight=axis; % capture those new minimum limits
sys(1)=min(x(1),axisTight(1)); % new xmin as smaller of auto or user-specified
sys(2)=max(x(2),axisTight(2)); % new xmax as larger of auto or user-specified
sys(3)=min(x(3),axisTight(3)); % new ymin as smaller of auto or user-specified
sys(4)=max(x(4),axisTight(4)); % new ymax as larger of auto or user-specified
% at this point the axis limits are captured but not assigned..
axis(sys(1:4)); % so make the assignment to the graphics window
else, % -> FIXED-ONLY from user supplied initial axis limits
axis(Config.ax);
end
%
% Force MATLAB to Update Drawing
%
%set(handle.axes(1),'visible','off')
%drawnow
% make a sequence of animation frames for a movie?
if Config.save_anim_frames==1,
% increment state x(6) for current frame number
sys(6) = x(6) + 1;
% create jpg filename string using datetime() function in Simulink
% dialogue box - this creates a single animation sequence using the date
% and time from when the Simulink model was started
imgFileStr=sprintf('%s_img_%0.6i.jpg',Config.anim_frame_name_str,sys(6)); % note: %0.6i pads with leading zeros just like writeVideo() demo
% prepend a folder to contain all these animation sequence images
myFile = fullfile('anim_sequences',imgFileStr);
str=sprintf('saving image sequence [%s]',myFile); disp(str)
% write this graphics frame to a file
print('-opengl','-djpeg',myFile);
end
end % mdlUpdate
%
%=============================================================================
% mdlGetTimeOfNextVarHit
% Return the time of the next hit for this block.
%=============================================================================
%
%function sys=mdlGetTimeOfNextVarHit(t,x,u,Ts)
% sys = ceil(t/Ts)*Ts+Ts;
% end mdlGetTimeOfNextVarHit
|
github
|
zucar/Driver-Assistance-System-master
|
rtwmakecfg.m
|
.m
|
Driver-Assistance-System-master/Path Planning/Resources/Matlab_simulation/rtwmakecfg.m
| 2,815 |
utf_8
|
16b58d91a07c158f3016ba8d1adbf057
|
function makeInfo=rtwmakecfg()
%RTWMAKECFG.m adds include and source directories to rtw make files.
% makeInfo=RTWMAKECFG returns a structured array containing
% following field:
% makeInfo.includePath - cell array containing additional include
% directories. Those directories will be
% expanded into include instructions of Simulink
% Coder generated make files.
%
% makeInfo.sourcePath - cell array containing additional source
% directories. Those directories will be
% expanded into rules of Simulink Coder generated
% make files.
makeInfo.includePath = {};
makeInfo.sourcePath = {};
makeInfo.linkLibsObjs = {};
%<Generated by S-Function Builder 3.0. DO NOT REMOVE>
sfBuilderBlocksByMaskType = find_system(bdroot,'FollowLinks','on','LookUnderMasks','on','MaskType','S-Function Builder');
sfBuilderBlocksByCallback = find_system(bdroot,'OpenFcn','sfunctionwizard(gcbh)');
sfBuilderBlocksDeployed = find_system(bdroot,'BlockType','S-Function','SFunctionDeploymentMode','on');
sfBuilderBlocks = {sfBuilderBlocksByMaskType{:} sfBuilderBlocksByCallback{:} sfBuilderBlocksDeployed{:}};
sfBuilderBlocks = unique(sfBuilderBlocks);
if isempty(sfBuilderBlocks)
return;
end
for idx = 1:length(sfBuilderBlocks)
sfBuilderBlockNameMATFile{idx} = get_param(sfBuilderBlocks{idx},'FunctionName');
sfBuilderBlockNameMATFile{idx} = ['.' filesep 'SFB__' char(sfBuilderBlockNameMATFile{idx}) '__SFB.mat'];
end
sfBuilderBlockNameMATFile = unique(sfBuilderBlockNameMATFile);
for idx = 1:length(sfBuilderBlockNameMATFile)
if exist(sfBuilderBlockNameMATFile{idx})
loadedData = load(sfBuilderBlockNameMATFile{idx});
if isfield(loadedData,'SFBInfoStruct')
makeInfo = UpdateMakeInfo(makeInfo,loadedData.SFBInfoStruct);
clear loadedData;
end
end
end
function updatedMakeInfo = UpdateMakeInfo(makeInfo,SFBInfoStruct)
updatedMakeInfo = {};
if isfield(makeInfo,'includePath')
if isfield(SFBInfoStruct,'includePath')
updatedMakeInfo.includePath = {makeInfo.includePath{:} SFBInfoStruct.includePath{:}};
else
updatedMakeInfo.includePath = {makeInfo.includePath{:}};
end
end
if isfield(makeInfo,'sourcePath')
if isfield(SFBInfoStruct,'sourcePath')
updatedMakeInfo.sourcePath = {makeInfo.sourcePath{:} SFBInfoStruct.sourcePath{:}};
else
updatedMakeInfo.sourcePath = {makeInfo.sourcePath{:}};
end
end
if isfield(makeInfo,'linkLibsObjs')
if isfield(SFBInfoStruct,'additionalLibraries')
updatedMakeInfo.linkLibsObjs = {makeInfo.linkLibsObjs{:} SFBInfoStruct.additionalLibraries{:}};
else
updatedMakeInfo.linkLibsObjs = {makeInfo.linkLibsObjs{:}};
end
end
|
github
|
zucar/Driver-Assistance-System-master
|
rtwmakecfg.m
|
.m
|
Driver-Assistance-System-master/Path Planning/Resources/Matlab_simulation/BaseImpl/rtwmakecfg.m
| 2,815 |
utf_8
|
16b58d91a07c158f3016ba8d1adbf057
|
function makeInfo=rtwmakecfg()
%RTWMAKECFG.m adds include and source directories to rtw make files.
% makeInfo=RTWMAKECFG returns a structured array containing
% following field:
% makeInfo.includePath - cell array containing additional include
% directories. Those directories will be
% expanded into include instructions of Simulink
% Coder generated make files.
%
% makeInfo.sourcePath - cell array containing additional source
% directories. Those directories will be
% expanded into rules of Simulink Coder generated
% make files.
makeInfo.includePath = {};
makeInfo.sourcePath = {};
makeInfo.linkLibsObjs = {};
%<Generated by S-Function Builder 3.0. DO NOT REMOVE>
sfBuilderBlocksByMaskType = find_system(bdroot,'FollowLinks','on','LookUnderMasks','on','MaskType','S-Function Builder');
sfBuilderBlocksByCallback = find_system(bdroot,'OpenFcn','sfunctionwizard(gcbh)');
sfBuilderBlocksDeployed = find_system(bdroot,'BlockType','S-Function','SFunctionDeploymentMode','on');
sfBuilderBlocks = {sfBuilderBlocksByMaskType{:} sfBuilderBlocksByCallback{:} sfBuilderBlocksDeployed{:}};
sfBuilderBlocks = unique(sfBuilderBlocks);
if isempty(sfBuilderBlocks)
return;
end
for idx = 1:length(sfBuilderBlocks)
sfBuilderBlockNameMATFile{idx} = get_param(sfBuilderBlocks{idx},'FunctionName');
sfBuilderBlockNameMATFile{idx} = ['.' filesep 'SFB__' char(sfBuilderBlockNameMATFile{idx}) '__SFB.mat'];
end
sfBuilderBlockNameMATFile = unique(sfBuilderBlockNameMATFile);
for idx = 1:length(sfBuilderBlockNameMATFile)
if exist(sfBuilderBlockNameMATFile{idx})
loadedData = load(sfBuilderBlockNameMATFile{idx});
if isfield(loadedData,'SFBInfoStruct')
makeInfo = UpdateMakeInfo(makeInfo,loadedData.SFBInfoStruct);
clear loadedData;
end
end
end
function updatedMakeInfo = UpdateMakeInfo(makeInfo,SFBInfoStruct)
updatedMakeInfo = {};
if isfield(makeInfo,'includePath')
if isfield(SFBInfoStruct,'includePath')
updatedMakeInfo.includePath = {makeInfo.includePath{:} SFBInfoStruct.includePath{:}};
else
updatedMakeInfo.includePath = {makeInfo.includePath{:}};
end
end
if isfield(makeInfo,'sourcePath')
if isfield(SFBInfoStruct,'sourcePath')
updatedMakeInfo.sourcePath = {makeInfo.sourcePath{:} SFBInfoStruct.sourcePath{:}};
else
updatedMakeInfo.sourcePath = {makeInfo.sourcePath{:}};
end
end
if isfield(makeInfo,'linkLibsObjs')
if isfield(SFBInfoStruct,'additionalLibraries')
updatedMakeInfo.linkLibsObjs = {makeInfo.linkLibsObjs{:} SFBInfoStruct.additionalLibraries{:}};
else
updatedMakeInfo.linkLibsObjs = {makeInfo.linkLibsObjs{:}};
end
end
|
github
|
zucar/Driver-Assistance-System-master
|
rtwmakecfg.m
|
.m
|
Driver-Assistance-System-master/Path Planning/Resources/Matlab_simulation/controller/rtwmakecfg.m
| 2,815 |
utf_8
|
16b58d91a07c158f3016ba8d1adbf057
|
function makeInfo=rtwmakecfg()
%RTWMAKECFG.m adds include and source directories to rtw make files.
% makeInfo=RTWMAKECFG returns a structured array containing
% following field:
% makeInfo.includePath - cell array containing additional include
% directories. Those directories will be
% expanded into include instructions of Simulink
% Coder generated make files.
%
% makeInfo.sourcePath - cell array containing additional source
% directories. Those directories will be
% expanded into rules of Simulink Coder generated
% make files.
makeInfo.includePath = {};
makeInfo.sourcePath = {};
makeInfo.linkLibsObjs = {};
%<Generated by S-Function Builder 3.0. DO NOT REMOVE>
sfBuilderBlocksByMaskType = find_system(bdroot,'FollowLinks','on','LookUnderMasks','on','MaskType','S-Function Builder');
sfBuilderBlocksByCallback = find_system(bdroot,'OpenFcn','sfunctionwizard(gcbh)');
sfBuilderBlocksDeployed = find_system(bdroot,'BlockType','S-Function','SFunctionDeploymentMode','on');
sfBuilderBlocks = {sfBuilderBlocksByMaskType{:} sfBuilderBlocksByCallback{:} sfBuilderBlocksDeployed{:}};
sfBuilderBlocks = unique(sfBuilderBlocks);
if isempty(sfBuilderBlocks)
return;
end
for idx = 1:length(sfBuilderBlocks)
sfBuilderBlockNameMATFile{idx} = get_param(sfBuilderBlocks{idx},'FunctionName');
sfBuilderBlockNameMATFile{idx} = ['.' filesep 'SFB__' char(sfBuilderBlockNameMATFile{idx}) '__SFB.mat'];
end
sfBuilderBlockNameMATFile = unique(sfBuilderBlockNameMATFile);
for idx = 1:length(sfBuilderBlockNameMATFile)
if exist(sfBuilderBlockNameMATFile{idx})
loadedData = load(sfBuilderBlockNameMATFile{idx});
if isfield(loadedData,'SFBInfoStruct')
makeInfo = UpdateMakeInfo(makeInfo,loadedData.SFBInfoStruct);
clear loadedData;
end
end
end
function updatedMakeInfo = UpdateMakeInfo(makeInfo,SFBInfoStruct)
updatedMakeInfo = {};
if isfield(makeInfo,'includePath')
if isfield(SFBInfoStruct,'includePath')
updatedMakeInfo.includePath = {makeInfo.includePath{:} SFBInfoStruct.includePath{:}};
else
updatedMakeInfo.includePath = {makeInfo.includePath{:}};
end
end
if isfield(makeInfo,'sourcePath')
if isfield(SFBInfoStruct,'sourcePath')
updatedMakeInfo.sourcePath = {makeInfo.sourcePath{:} SFBInfoStruct.sourcePath{:}};
else
updatedMakeInfo.sourcePath = {makeInfo.sourcePath{:}};
end
end
if isfield(makeInfo,'linkLibsObjs')
if isfield(SFBInfoStruct,'additionalLibraries')
updatedMakeInfo.linkLibsObjs = {makeInfo.linkLibsObjs{:} SFBInfoStruct.additionalLibraries{:}};
else
updatedMakeInfo.linkLibsObjs = {makeInfo.linkLibsObjs{:}};
end
end
|
github
|
zucar/Driver-Assistance-System-master
|
rtwmakecfg.m
|
.m
|
Driver-Assistance-System-master/CarModel/Matlab-Model/BaseImpl/rtwmakecfg.m
| 2,815 |
utf_8
|
16b58d91a07c158f3016ba8d1adbf057
|
function makeInfo=rtwmakecfg()
%RTWMAKECFG.m adds include and source directories to rtw make files.
% makeInfo=RTWMAKECFG returns a structured array containing
% following field:
% makeInfo.includePath - cell array containing additional include
% directories. Those directories will be
% expanded into include instructions of Simulink
% Coder generated make files.
%
% makeInfo.sourcePath - cell array containing additional source
% directories. Those directories will be
% expanded into rules of Simulink Coder generated
% make files.
makeInfo.includePath = {};
makeInfo.sourcePath = {};
makeInfo.linkLibsObjs = {};
%<Generated by S-Function Builder 3.0. DO NOT REMOVE>
sfBuilderBlocksByMaskType = find_system(bdroot,'FollowLinks','on','LookUnderMasks','on','MaskType','S-Function Builder');
sfBuilderBlocksByCallback = find_system(bdroot,'OpenFcn','sfunctionwizard(gcbh)');
sfBuilderBlocksDeployed = find_system(bdroot,'BlockType','S-Function','SFunctionDeploymentMode','on');
sfBuilderBlocks = {sfBuilderBlocksByMaskType{:} sfBuilderBlocksByCallback{:} sfBuilderBlocksDeployed{:}};
sfBuilderBlocks = unique(sfBuilderBlocks);
if isempty(sfBuilderBlocks)
return;
end
for idx = 1:length(sfBuilderBlocks)
sfBuilderBlockNameMATFile{idx} = get_param(sfBuilderBlocks{idx},'FunctionName');
sfBuilderBlockNameMATFile{idx} = ['.' filesep 'SFB__' char(sfBuilderBlockNameMATFile{idx}) '__SFB.mat'];
end
sfBuilderBlockNameMATFile = unique(sfBuilderBlockNameMATFile);
for idx = 1:length(sfBuilderBlockNameMATFile)
if exist(sfBuilderBlockNameMATFile{idx})
loadedData = load(sfBuilderBlockNameMATFile{idx});
if isfield(loadedData,'SFBInfoStruct')
makeInfo = UpdateMakeInfo(makeInfo,loadedData.SFBInfoStruct);
clear loadedData;
end
end
end
function updatedMakeInfo = UpdateMakeInfo(makeInfo,SFBInfoStruct)
updatedMakeInfo = {};
if isfield(makeInfo,'includePath')
if isfield(SFBInfoStruct,'includePath')
updatedMakeInfo.includePath = {makeInfo.includePath{:} SFBInfoStruct.includePath{:}};
else
updatedMakeInfo.includePath = {makeInfo.includePath{:}};
end
end
if isfield(makeInfo,'sourcePath')
if isfield(SFBInfoStruct,'sourcePath')
updatedMakeInfo.sourcePath = {makeInfo.sourcePath{:} SFBInfoStruct.sourcePath{:}};
else
updatedMakeInfo.sourcePath = {makeInfo.sourcePath{:}};
end
end
if isfield(makeInfo,'linkLibsObjs')
if isfield(SFBInfoStruct,'additionalLibraries')
updatedMakeInfo.linkLibsObjs = {makeInfo.linkLibsObjs{:} SFBInfoStruct.additionalLibraries{:}};
else
updatedMakeInfo.linkLibsObjs = {makeInfo.linkLibsObjs{:}};
end
end
|
github
|
Akshitaag/Chall-Vihaan-master
|
MeanVariance.m
|
.m
|
Chall-Vihaan-master/routes/codes/MeanVariance.m
| 1,364 |
utf_8
|
8b23466de4e94d6052135ba671cde88f
|
## Copyright (C) 2017 Shreya
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn {} {@var{retval} =} MeanVariance (@var{input1}, @var{input2})
##
## @seealso{}
## @end deftypefn
## Author: Shreya <Shreya@SARTHAK-LAPTOP>
## Created: 2017-10-28
% X is a 15x4 matrix_type
% It stores amount, location pincode, time and merchant pincode
function [mu, sigma] = MeanVariance (X)
mu = zeros(4,1);
sigma = zeros (4,1);
for i = 1:4
for j = 1:15
mu(i,1) = mu(i,1) + X(j,i);
endfor
mu(i,1)= mu(i,1)/15;
%disp("Mean");
%disp(mu(i,1));
endfor
for i = 1:4
for j = 1:15
sigma(i,1) = sigma(i,1) + (X(j,i) - mu(i,1))^2;
endfor
sigma(i,1)= sigma(i,1)/15;
%disp("i");
%disp(i);
%disp(sigma);
endfor
endfunction
|
github
|
Akshitaag/Chall-Vihaan-master
|
probability.m
|
.m
|
Chall-Vihaan-master/routes/codes/probability.m
| 1,015 |
utf_8
|
a28db31f8c29e452e555c6e50edd8c41
|
## Copyright (C) 2017 Shreya
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn {} {@var{retval} =} probability (@var{input1}, @var{input2})
##
## @seealso{}
## @end deftypefn
## Author: Shreya <Shreya@SARTHAK-LAPTOP>
## Created: 2017-10-28
function p = probability (x, mu, var)
p = (0.399/(var^(0.5)))*exponential(-(((x- mu)^2)/(2*var)));
%disp("p");
%disp(p);
endfunction
|
github
|
Akshitaag/Chall-Vihaan-master
|
main.m
|
.m
|
Chall-Vihaan-master/routes/codes/main.m
| 1,710 |
utf_8
|
1f7ebc3c7c60fd3954acb86f1669cac3
|
## Copyright (C) 2017 Shreya
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn {} {@var{retval} =} main (@var{input1}, @var{input2})
##
## @seealso{}
## @end deftypefn
## Author: Shreya <Shreya@SARTHAK-LAPTOP>
## Created: 2017-10-28
function n = main(fileName,amount, locPin, time, merchPin)
%function n = main(g)
%disp(amount)
%disp(locPin)
%disp(time)
%disp(merchPin)
amount=double(amount);
locPin=double(locPin);
time=double(time);
merchPin=double(merchPin);
X = csvread(fileName);
%X = csvread('sarthak.txt');
Y = zeros(15,4);
for i=1:15
for j =1:4
Y(i,j) = X(i,j+2);
endfor
endfor
[mu, sigma] = MeanVariance(Y);
Z = [amount, locPin, time, merchPin];
%Z=[60000,110017,12,110017];
ans = predictNature(Z, mu, sigma);
flag = 1;
for i=1:4
if (ans(i,1)==1)
flag =0;
endif
endfor
if (flag==1)
fprintf("You can Proceed with your transaction.");
else
fprintf("Based on your history,this transaction doesn't confirm to your history,Please confirm your identity.");
endif
n=1;
endfunction
|
github
|
Akshitaag/Chall-Vihaan-master
|
predictNature.m
|
.m
|
Chall-Vihaan-master/routes/codes/predictNature.m
| 1,438 |
utf_8
|
0f5d425211ad4bf375290e74adbc88bc
|
## Copyright (C) 2017 Shreya
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn {} {@var{retval} =} predictNature (@var{input1}, @var{input2})
##
## @seealso{}
## @end deftypefn
## Author: Shreya <Shreya@SARTHAK-LAPTOP>
## Created: 2017-10-28
% X is a new single data input (horizontal) from node.js that i am gng to calculate
% the probability for
function prediction = predictNature (X, mu, sigma)
prediction = ones(4,1);
for i =1:4
prediction(i,1) = prediction(i,1) * probability(X(1,i),mu(i,1), sigma(i,1));
endfor
for i = 1:4
if(i!=3)
if (prediction(i,1)<0.0000001)
prediction(i,1) =1;
else prediction(i,1) = 0;
endif
else
if (prediction(i,1)<0.02)
prediction(i,1) =1;
else prediction(i,1) = 0;
endif
endif
endfor
endfunction
|
github
|
Akshitaag/Chall-Vihaan-master
|
exponential.m
|
.m
|
Chall-Vihaan-master/routes/codes/exponential.m
| 941 |
utf_8
|
5da284170d8f5071a07b143da331d909
|
## Copyright (C) 2017 Shreya
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn {} {@var{retval} =} exponential (@var{input1}, @var{input2})
##
## @seealso{}
## @end deftypefn
## Author: Shreya <Shreya@SARTHAK-LAPTOP>
## Created: 2017-10-28
function ans = exponential (x)
ans = (2.718)^x;
endfunction
|
github
|
CSAILVision/miniplaces-master
|
VOCxml2struct.m
|
.m
|
miniplaces-master/util/VOCxml2struct.m
| 1,920 |
utf_8
|
6a873dba4b24c57e9f86a15ee12ea366
|
function res = VOCxml2struct(xml)
xml(xml==9|xml==10|xml==13)=[];
[res,xml]=parse(xml,1,[]);
function [res,ind]=parse(xml,ind,parent)
res=[];
if ~isempty(parent)&&xml(ind)~='<'
i=findchar(xml,ind,'<');
res=trim(xml(ind:i-1));
ind=i;
[tag,ind]=gettag(xml,i);
if ~strcmp(tag,['/' parent])
error('<%s> closed with <%s>',parent,tag);
end
else
while ind<=length(xml)
[tag,ind]=gettag(xml,ind);
if strcmp(tag,['/' parent])
return
else
[sub,ind]=parse(xml,ind,tag);
if isstruct(sub)
if isfield(res,tag)
n=length(res.(tag));
fn=fieldnames(sub);
for f=1:length(fn)
res.(tag)(n+1).(fn{f})=sub.(fn{f});
end
else
res.(tag)=sub;
end
else
if isfield(res,tag)
if ~iscell(res.(tag))
res.(tag)={res.(tag)};
end
res.(tag){end+1}=sub;
else
res.(tag)=sub;
end
end
end
end
end
function i = findchar(str,ind,chr)
i=[];
while ind<=length(str)
if str(ind)==chr
i=ind;
break
else
ind=ind+1;
end
end
function [tag,ind]=gettag(xml,ind)
if ind>length(xml)
tag=[];
elseif xml(ind)=='<'
i=findchar(xml,ind,'>');
if isempty(i)
error('incomplete tag');
end
tag=xml(ind+1:i-1);
ind=i+1;
else
error('expected tag');
end
function s = trim(s)
for i=1:numel(s)
if ~isspace(s(i))
s=s(i:end);
break
end
end
for i=numel(s):-1:1
if ~isspace(s(i))
s=s(1:i);
break
end
end
|
github
|
CSAILVision/miniplaces-master
|
sample_refNet_initial.m
|
.m
|
miniplaces-master/model/matconvnet/sample_refNet_initial.m
| 5,252 |
utf_8
|
68982f59559512bce9abbee46e1a0618
|
function [net] = sample_refNet_initial(varargin)
% sample code for initializing the refNet1 for mini-places challenge
% adapted from matconvnet-1.0-beta14/matconvnet-1.0-beta14/examples/cnn_imagenet_init.m
opts.scale = 1 ;
opts.initBias = 0.1 ;
opts.weightDecay = 1 ;
opts.weightInitMethod = 'gaussian' ;
opts.model = 'refNet1' ;
opts.batchNormalization = false ;
opts = vl_argparse(opts, varargin) ;
% Define layers
net.normalization.imageSize = [126, 126, 3] ;
switch opts.model
case 'refNet1'
net = refNet1(net, opts) ;
otherwise
error('Unknown model ''%s''', opts.model) ;
end
switch lower(opts.weightInitMethod)
case {'xavier', 'xavierimproved'}
net.layers{end}.weights{1} = net.layers{end}.weights{1} / 10 ;
end
net.layers{end+1} = struct('type', 'softmaxloss', 'name', 'loss') ;
net.normalization.border = 128 - net.normalization.imageSize(1:2) ;
net.normalization.interpolation = 'bicubic' ;
net.normalization.averageImage = [] ;
net.normalization.keepAspect = true ;
end
% --------------------------------------------------------------------
function net = add_block(net, opts, id, h, w, in, out, stride, pad, init_bias)
% --------------------------------------------------------------------
info = vl_simplenn_display(net) ;
fc = (h == info.dataSize(1,end) && w == info.dataSize(2,end)) ;
if fc
name = 'fc' ;
else
name = 'conv' ;
end
net.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%s', name, id), ...
'weights', {{init_weight(opts, h, w, in, out, 'single'), zeros(out, 1, 'single')}}, ...
'stride', stride, ...
'pad', pad, ...
'learningRate', [1 2], ...
'weightDecay', [opts.weightDecay 0]) ;
if opts.batchNormalization
net.layers{end+1} = struct('type', 'bnorm', 'name', sprintf('bn%d',id), ...
'weights', {{ones(out, 1, 'single'), zeros(out, 1, 'single')}}, ...
'learningRate', [2 1], ...
'weightDecay', [0 0]) ;
end
net.layers{end+1} = struct('type', 'relu', 'name', sprintf('relu%s',id)) ;
end
% -------------------------------------------------------------------------
function weights = init_weight(opts, h, w, in, out, type)
% -------------------------------------------------------------------------
% See K. He, X. Zhang, S. Ren, and J. Sun. Delving deep into
% rectifiers: Surpassing human-level performance on imagenet
% classification. CoRR, (arXiv:1502.01852v1), 2015.
switch lower(opts.weightInitMethod)
case 'gaussian'
sc = 0.01/opts.scale ;
weights = randn(h, w, in, out, type)*sc;
case 'xavier'
sc = sqrt(3/(h*w*in)) ;
weights = (rand(h, w, in, out, type)*2 - 1)*sc ;
case 'xavierimproved'
sc = sqrt(2/(h*w*out)) ;
weights = randn(h, w, in, out, type)*sc ;
otherwise
error('Unknown weight initialization method''%s''', opts.weightInitMethod) ;
end
end
% --------------------------------------------------------------------
function net = add_norm(net, opts, id)
% --------------------------------------------------------------------
if ~opts.batchNormalization
net.layers{end+1} = struct('type', 'normalize', ...
'name', sprintf('norm%s', id), ...
'param', [5 1 0.0001/5 0.75]) ;
end
end
% --------------------------------------------------------------------
function net = add_dropout(net, opts, id)
% --------------------------------------------------------------------
if ~opts.batchNormalization
net.layers{end+1} = struct('type', 'dropout', ...
'name', sprintf('dropout%s', id), ...
'rate', 0.5) ;
end
end
% --------------------------------------------------------------------
function net = refNet1(net, opts)
% 3 convnet + 1 FC + 1 softmax
% --------------------------------------------------------------------
%% add_block(net, opts, id, h, w, in, out, stride, pad, init_bias)
net.layers = {} ;
net = add_block(net, opts, '1', 8, 8, 3, 64, 2, 0) ;
net = add_norm(net, opts, '1') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '2', 5, 5, 32, 96, 1, 2) ;
net = add_norm(net, opts, '2') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '3', 3, 3, 96, 128, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '4', 6, 6, 128, 512, 1, 0) ;
net = add_dropout(net, opts, '4') ;
net = add_block(net, opts, '5', 1, 1, 512, 100, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
end
|
github
|
devaib/MXNet-SSD-master
|
eval_roc.m
|
.m
|
MXNet-SSD-master/matlab/kitti/eval_roc.m
| 16,332 |
utf_8
|
58e745530afd562972eb6733d6afb93a
|
function eval_roc
clear; close; clc;
val_file = '../../data/kitti/data_object_image_2/training/val.txt';
gts_file = '../../data/kitti/results/gts.txt';
dts_file = '../../data/kitti/results/dts.txt';
dts1_file = '../../data/kitti/results/dts_all_layer_customized.txt';
dts2_file = '../../data/kitti/results/dts_two_stream_one_shared_stages.txt';
dts3_file = '../../data/kitti/results/dts_two_stream_two_shared_stages.txt';
% List of experiment settings: { name, hr, vr, ar, overlap, filter }
% name - experiment name
% hr - height range to test
% vr - visibility range to test
% ar - aspect ratio range to test
% overlap - overlap threshold for evaluation
% filter - expanded filtering (see 3.3 in PAMI11)
exps = {
'Reasonable', [50 inf], [.65 inf], 0, .5, 1.25
'All', [20 inf], [.2 inf], 0, .5, 1.25
'Scale=large', [100 inf], [inf inf], 0, .5, 1.25
'Scale=near', [80 inf], [inf inf], 0, .5, 1.25
'Scale=medium', [30 80], [inf inf], 0, .5, 1.25
'Scale=far', [20 30], [inf inf], 0, .5, 1.25
'Occ=none', [50 inf], [inf inf], 0, .5, 1.25
'Occ=partial', [50 inf], [.65 1], 0, .5, 1.25
'Occ=heavy', [50 inf], [.2 .65], 0, .5, 1.25
'Ar=all', [50 inf], [inf inf], 0, .5, 1.25
'Ar=typical', [50 inf], [inf inf], .1, .5, 1.25
'Ar=atypical', [50 inf], [inf inf], -.1, .5, 1.25
'Overlap=25', [50 inf], [.65 inf], 0, .25, 1.25
'Overlap=50', [50 inf], [.65 inf], 0, .50, 1.25
'Overlap=75', [50 inf], [.65 inf], 0, .75, 1.25
'Expand=100', [50 inf], [.65 inf], 0, .5, 1.00
'Expand=125', [50 inf], [.65 inf], 0, .5, 1.25
'Expand=150', [50 inf], [.65 inf], 0, .5, 1.50 };
exps=cell2struct(exps',{'name','hr','vr','ar','overlap','filter'});
nn=1000; clrs=zeros(nn,3);
for ii=1:nn, clrs(ii,:)=max(.3,mod([78 121 42]*(ii+1),255)/255); end
algs = {
'SSD', 0, clrs(2,:), '-'
'SSD-customized', 0, clrs(1,:), '-'
% 'SSD-two-stream*', 0, clrs(3,:), '-'
% 'SSD-two-stream**', 0, clrs(4,:), '-'
};
algs=cell2struct(algs',{'name','resize','color','style'});
exps = exps(2);
algs = algs(:);
% remaining parameters and constants
aspectRatio = .41; % default aspect ratio for all bbs
bnds = [5 5 635 475]; % discard bbs outside this pixel range
plotRoc = 0; % if true plot ROC else PR curves
plotAlg = 0; % if true one plot per alg else one plot per exp
plotNum = 15; % only show best plotNum curves (and VJ and HOG)
samples = 10.^(-2:.25:0); % samples for computing area under the curve
%samples = 0:0.1:1;
lims = [2e-4 50 .035 1]; % axis limits for ROC plots
bbsShow = 0; % if true displays sample bbs for each alg/exp
bbsType = 'fp'; % type of bbs to display (fp/tp/fn/dt)
%algo_name = 'SSD-ResNet101';
% load val list, gts and dts files
f = fopen(val_file);
val_scan = textscan(f,'%s','delimiter','\n');
fclose(f);
f = fopen(gts_file);
gts_scan = textscan(f,'%s %d %d %d %d', 'delimiter', ',');
fclose(f);
f = fopen(dts_file);
dts_scan = textscan(f,'%s %d %d %d %d %f','delimiter',',');
fclose(f);
f = fopen(dts1_file);
dts1_scan = textscan(f,'%s %d %d %d %d %f','delimiter',',');
fclose(f);
f = fopen(dts2_file);
dts2_scan = textscan(f,'%s %d %d %d %d %f','delimiter',',');
fclose(f);
f = fopen(dts3_file);
dts3_scan = textscan(f,'%s %d %d %d %d %f','delimiter',',');
fclose(f);
% construct gts, dts
val_list = val_scan{1,1};
gts_index = gts_scan{1,1}; gts_x = gts_scan{1,2}; gts_y = gts_scan{1,3};
gts_w = gts_scan{1,4}; gts_h = gts_scan{1,5};
dts_index = dts_scan{1,1}; dts_x = dts_scan{1,2}; dts_y = dts_scan{1,3};
dts_w = dts_scan{1,4}; dts_h = dts_scan{1,5}; dts_score = dts_scan{1,6};
dts1_index = dts1_scan{1,1}; dts1_x = dts1_scan{1,2}; dts1_y = dts1_scan{1,3};
dts1_w = dts1_scan{1,4}; dts1_h = dts1_scan{1,5}; dts1_score = dts1_scan{1,6};
dts2_index = dts2_scan{1,1}; dts2_x = dts2_scan{1,2}; dts2_y = dts2_scan{1,3};
dts2_w = dts2_scan{1,4}; dts2_h = dts2_scan{1,5}; dts2_score = dts2_scan{1,6};
dts3_index = dts3_scan{1,1}; dts3_x = dts3_scan{1,2}; dts3_y = dts3_scan{1,3};
dts3_w = dts3_scan{1,4}; dts3_h = dts3_scan{1,5}; dts3_score = dts3_scan{1,6};
num_val = size(val_list, 1);
gts = cell(1,num_val);
dts = cell(1,num_val);
dts1 = cell(1,num_val);
dts2 = cell(1,num_val);
dts3 = cell(1,num_val);
for i_val = 1:num_val
index = val_list(i_val, 1);
% find index match in gts
ind_gts = find(strcmp(gts_index, index));
gts{1,i_val}(:,1) = double(gts_x(ind_gts));
gts{1,i_val}(:,2) = double(gts_y(ind_gts));
gts{1,i_val}(:,3) = double(gts_w(ind_gts));
gts{1,i_val}(:,4) = double(gts_h(ind_gts));
gts{1,i_val}(:,5) = double(zeros(size(ind_gts)));
% find index match in dts
ind_dts = find(strcmp(dts_index, index));
dts{1,i_val}(:,1) = double(dts_x(ind_dts));
dts{1,i_val}(:,2) = double(dts_y(ind_dts));
dts{1,i_val}(:,3) = double(dts_w(ind_dts));
dts{1,i_val}(:,4) = double(dts_h(ind_dts));
dts{1,i_val}(:,5) = double(dts_score(ind_dts));
ind_dts1 = find(strcmp(dts1_index, index));
dts1{1,i_val}(:,1) = double(dts1_x(ind_dts1));
dts1{1,i_val}(:,2) = double(dts1_y(ind_dts1));
dts1{1,i_val}(:,3) = double(dts1_w(ind_dts1));
dts1{1,i_val}(:,4) = double(dts1_h(ind_dts1));
dts1{1,i_val}(:,5) = double(dts1_score(ind_dts1));
ind_dts2 = find(strcmp(dts2_index, index));
dts2{1,i_val}(:,1) = double(dts2_x(ind_dts2));
dts2{1,i_val}(:,2) = double(dts2_y(ind_dts2));
dts2{1,i_val}(:,3) = double(dts2_w(ind_dts2));
dts2{1,i_val}(:,4) = double(dts2_h(ind_dts2));
dts2{1,i_val}(:,5) = double(dts2_score(ind_dts2));
ind_dts3 = find(strcmp(dts3_index, index));
dts3{1,i_val}(:,1) = double(dts3_x(ind_dts3));
dts3{1,i_val}(:,2) = double(dts3_y(ind_dts3));
dts3{1,i_val}(:,3) = double(dts3_w(ind_dts3));
dts3{1,i_val}(:,4) = double(dts3_h(ind_dts3));
dts3{1,i_val}(:,5) = double(dts3_score(ind_dts3));
end
dataName='KITTI';
plotName=[fileparts(mfilename('fullpath')) '/results/' dataName];
if(~exist(plotName,'dir')), mkdir(plotName); end
gts = {gts}; dts = {dts, dts1}; % dts = {dts, dts1, dts2, dts3};
%gName = [plotName '/gt' '.mat'];
%aName = [plotName '/dt-' algo_name '.mat'];
%save(aName,'dts','-v6');
%save(gName,'gts','-v6');
%algo = algo_name;
res = evalAlgs( plotName, algs, exps, gts, dts );
% plot curves and bbs
plotExps( res, plotRoc, plotAlg, plotNum, plotName, ...
samples, lims, reshape([algs.color]',3,[])', {algs.style} );
plotBbs( res, plotName, bbsShow, bbsType );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = evalAlgs( plotName, algs, exps, gts, dts )
% Evaluate every algorithm on each experiment
%
% OUTPUTS
% res - nGt x nDt cell of all evaluations, each with fields
% .stra - string identifying algorithm
% .stre - string identifying experiment
% .gtr - [n x 1] gt result bbs for each frame [x y w h match]
% .dtr - [n x 1] dt result bbs for each frame [x y w h score match]
fprintf('Evaluating: %s\n',plotName); nGt=length(gts); nDt=length(dts);
res=repmat(struct('stra',[],'stre',[],'gtr',[],'dtr',[]),nGt,nDt);
%nGt = 1; nDt = 1;
for g=1:nGt
for d=1:nDt
gt=gts{g}; dt=dts{d}; n=length(gt); assert(length(dt)==n);
stra=algs(d).name; stre=exps(g).name;
%stra=algo; stre='';
%fName = [plotName '/ev-' stra '.mat'];
%if(exist(fName,'file')), R=load(fName); res(g,d)=R.R; continue; end
fprintf('\tExp %i/%i, Alg %i/%i: %s\n',g,nGt,d,nDt,stra);
hr = exps(g).hr.*[1/exps(g).filter exps(g).filter];
for ff=1:n, bb=dt{ff}; dt{ff}=bb(bb(:,4)>=hr(1) & bb(:,4)<hr(2),:); end
[gtr,dtr] = bbGt('evalRes',gt,dt,exps(g).overlap);
R=struct('stra',stra,'stre',stre,'gtr',{gtr},'dtr',{dtr});
res(g,d)=R; %save(fName,'R');
end
end
end
function plotExps( res, plotRoc, plotAlg, plotNum, plotName, ...
samples, lims, colors, styles )
% Plot all ROC or PR curves.
%
% INPUTS
% res - output of evalAlgs
% plotRoc - if true plot ROC else PR curves
% plotAlg - if true one plot per alg else one plot per exp
% plotNum - only show best plotNum curves (and VJ and HOG)
% plotName - filename for saving plots
% samples - samples for computing area under the curve
% lims - axis limits for ROC plots
% colors - algorithm plot colors
% styles - algorithm plot linestyles
% Compute (xs,ys) and score (area under the curve) for every exp/alg
[nGt,nDt]=size(res); xs=cell(nGt,nDt); ys=xs; scores=zeros(nGt,nDt);
for g=1:nGt
for d=1:nDt
% score : for ROC curves is the *detection* rate at reference *FPPI*
[xs{g,d},ys{g,d},~,score] = ...
bbGt('compRoc',res(g,d).gtr,res(g,d).dtr,plotRoc,samples);
if(plotRoc), ys{g,d}=1-ys{g,d}; score=1-score; end
if(plotRoc), score=exp(mean(log(score))); else score=mean(score); end
scores(g,d)=score;
end
end
% Generate plots
if( plotRoc ), fName=[plotName 'Roc']; else fName=[plotName 'Pr']; end
stra={res(1,:).stra}; stre={res(:,1).stre}; scores1=round(scores*100);
if( plotAlg ), nPlots=nDt; else nPlots=nGt; end; plotNum=min(plotNum,nDt);
for p=1:nPlots
% prepare xs1,ys1,lgd1,colors1,styles1,fName1 according to plot type
if( plotAlg )
xs1=xs(:,p); ys1=ys(:,p); fName1=[fName stra{p}]; lgd1=stre;
for g=1:nGt, lgd1{g}=sprintf('%2i%% %s',scores1(g,p),stre{g}); end
colors1=uniqueColors(1,max(10,nGt)); styles1=repmat({'-','--'},1,nGt);
else
xs1=xs(p,:); ys1=ys(p,:); fName1=[fName stre{p}]; lgd1=stra;
for d=1:nDt, lgd1{d}=sprintf('%s',stra{d}); end
%kp=[find(strcmp(stra,'VJ')) find(strcmp(stra,'HOG')) 1 1];
kp=[find(strcmp(stra,'SSD')) 1 1];
% [~,ord]=sort(scores(p,:)); kp=ord==kp(1)|ord==kp(2);
% j=find(cumsum(~kp)>=plotNum-2); kp(1:j(1))=1; ord=fliplr(ord(kp));
ord = [1 2 ]; % ord = [1 2 3 4];
xs1=xs1(ord); ys1=ys1(ord); lgd1=lgd1(ord); colors1=colors(ord,:);
styles1=styles(ord); f=fopen([fName1 '.txt'],'w');
for d=1:nDt, fprintf(f,'%s %f\n',stra{d},scores(p,d)); end; fclose(f);
end
% plot curves and finalize display
figure(1); clf; grid on; hold on; n=length(xs1); h=zeros(1,n);
for i=1:n, h(i)=plot(xs1{i},ys1{i},'Color',colors1(i,:),...
'LineStyle',styles1{i},'LineWidth',2); end
if( plotRoc )
yt=[.05 .1:.1:.5 .64 .8]; ytStr=int2str2(yt*100,2);
for i=1:length(yt), ytStr{i}=['.' ytStr{i}]; end
set(gca,'XScale','log','YScale','log',...
'YTick',[yt 1],'YTickLabel',[ytStr '1'],...
'XMinorGrid','off','XMinorTic','off',...
'YMinorGrid','off','YMinorTic','off');
xlabel('false positives per image','FontSize',14);
ylabel('miss rate','FontSize',14); axis(lims);
else
x=1; for i=1:n, x=max(x,max(xs1{i})); end, x=min(x-mod(x,.1),1.0);
y=.8; for i=1:n, y=min(y,min(ys1{i})); end, y=max(y-mod(y,.1),.01);
xlim([0, x]); ylim([y, 1]); set(gca,'xtick',0:.1:1);
xlabel('Recall','FontSize',14); ylabel('Precision','FontSize',14);
end
if(~isempty(lgd1)), legend(h,lgd1,'Location','sw','FontSize',10); end
% save figure to disk (uncomment pdfcrop commands to automatically crop)
[o,~]=system('pdfcrop'); if(o==127), setenv('PATH',...
[getenv('PATH') ':/Library/TeX/texbin/:/usr/local/bin/']); end
% savefig(fName1,1,'pdf','-r300','-fonts'); close(1); f1=[fName1 '.pdf'];
% system(['pdfcrop -margins ''-30 -20 -50 -10 '' ' f1 ' ' f1]);
savefig(fName1,1,'jpeg','-r300','-fonts'); f1=[fName1 '.jpg'];
end
end
function plotBbs( res, plotName, pPage, type )
% This function plots sample fp/tp/fn bbs for given algs/exps
if(pPage==0), return; end; [nGt,nDt]=size(res);
% construct set/vid/frame index for each image
[~,setIds,vidIds,skip]=dbInfo;
k=length(res(1).gtr); is=zeros(k,3); k=0;
for s=1:length(setIds)
for v=1:length(vidIds{s})
A=loadVbb(s,v); s1=setIds(s); v1=vidIds{s}(v);
for ff=skip-1:skip:A.nFrame-1, k=k+1; is(k,:)=[s1 v1 ff]; end
end
end
for g=1:nGt
for d=1:nDt
% augment each bb with set/video/frame index and flatten
dtr=res(g,d).dtr; gtr=res(g,d).gtr;
for i=1:k
dtr{i}(:,7)=is(i,1); dtr{i}(:,8)=is(i,2); dtr{i}(:,9)=is(i,3);
gtr{i}(:,6)=is(i,1); gtr{i}(:,7)=is(i,2); gtr{i}(:,8)=is(i,3);
dtr{i}=dtr{i}'; gtr{i}=gtr{i}';
end
dtr=[dtr{:}]'; dtr=dtr(dtr(:,6)~=-1,:);
gtr=[gtr{:}]'; gtr=gtr(gtr(:,5)~=-1,:);
% get bb, ind, bbo, and indo according to type
if( strcmp(type,'fn') )
keep=gtr(:,5)==0; ord=randperm(sum(keep));
bbCol='r'; bboCol='y'; bbLst='-'; bboLst='--';
bb=gtr(:,1:4); ind=gtr(:,6:8); bbo=dtr(:,1:6); indo=dtr(:,7:9);
else
switch type
case 'dt', bbCol='y'; keep=dtr(:,6)>=0;
case 'fp', bbCol='r'; keep=dtr(:,6)==0;
case 'tp', bbCol='y'; keep=dtr(:,6)==1;
end
[~,ord]=sort(dtr(keep,5),'descend');
bboCol='g'; bbLst='--'; bboLst='-';
bb=dtr(:,1:6); ind=dtr(:,7:9); bbo=gtr(:,1:4); indo=gtr(:,6:8);
end
% prepare and display
n=sum(keep); bbo1=cell(1,n); O=ones(1,size(indo,1));
ind=ind(keep,:); bb=bb(keep,:); ind=ind(ord,:); bb=bb(ord,:);
for f=1:n, bbo1{f}=bbo(all(indo==ind(O*f,:),2),:); end
f=[plotName res(g,d).stre res(g,d).stra '-' type];
plotBbSheet( bb, ind, bbo1,'fName',f,'pPage',pPage,'bbCol',bbCol,...
'bbLst',bbLst,'bboCol',bboCol,'bboLst',bboLst );
end
end
end
function plotBbSheet( bb, ind, bbo, varargin )
% Draw sheet of bbs.
%
% USAGE
% plotBbSheet( R, varargin )
%
% INPUTS
% bb - [nx4] bbs to display
% ind - [nx3] the set/video/image number for each bb
% bbo - {nx1} cell of other bbs for each image (optional)
% varargin - prm struct or name/value list w following fields:
% .fName - ['REQ'] base file to save to
% .pPage - [1] num pages
% .mRows - [5] num rows / page
% .nCols - [9] num cols / page
% .scale - [2] size of image region to crop relative to bb
% .siz0 - [100 50] target size of each bb
% .pad - [4] amount of space between cells
% .bbCol - ['g'] bb color
% .bbLst - ['-'] bb LineStyle
% .bboCol - ['r'] bbo color
% .bboLst - ['--'] bbo LineStyle
dfs={'fName','REQ', 'pPage',1, 'mRows',5, 'nCols',9, 'scale',1.5, ...
'siz0',[100 50], 'pad',8, 'bbCol','g', 'bbLst','-', ...
'bboCol','r', 'bboLst','--' };
[fName,pPage,mRows,nCols,scale,siz0,pad,bbCol,bbLst, ...
bboCol,bboLst] = getPrmDflt(varargin,dfs);
n=size(ind,1); indAll=ind; bbAll=bb; bboAll=bbo;
for page=1:min(pPage,ceil(n/mRows/nCols))
Is = zeros(siz0(1)*scale,siz0(2)*scale,3,mRows*nCols,'uint8');
bbN=[]; bboN=[]; labels=repmat({''},1,mRows*nCols);
for f=1:mRows*nCols
% get fp bb (bb), double size (bb2), and other bbs (bbo)
f0=f+(page-1)*mRows*nCols; if(f0>n), break, end
[col,row]=ind2sub([nCols mRows],f);
ind=indAll(f0,:); bb=bbAll(f0,:); bbo=bboAll{f0};
hr=siz0(1)/bb(4); wr=siz0(2)/bb(3); mr=min(hr,wr);
bb2 = round(bbApply('resize',bb,scale*hr/mr,scale*wr/mr));
bbo=bbApply('intersect',bbo,bb2); bbo=bbo(bbApply('area',bbo)>0,:);
labels{f}=sprintf('%i/%i/%i',ind(1),ind(2),ind(3));
% normalize bb and bbo for siz0*scale region, then shift
bb=bbApply('shift',bb,bb2(1),bb2(2)); bb(:,1:4)=bb(:,1:4)*mr;
bbo=bbApply('shift',bbo,bb2(1),bb2(2)); bbo(:,1:4)=bbo(:,1:4)*mr;
xdel=-pad*scale-(siz0(2)+pad*2)*scale*(col-1);
ydel=-pad*scale-(siz0(1)+pad*2)*scale*(row-1);
bb=bbApply('shift',bb,xdel,ydel); bbN=[bbN; bb]; %#ok<AGROW>
bbo=bbApply('shift',bbo,xdel,ydel); bboN=[bboN; bbo]; %#ok<AGROW>
% load and crop image region
sr=seqIo(sprintf('%s/videos/set%02i/V%03i',dbInfo,ind(1),ind(2)),'r');
sr.seek(ind(3)); I=sr.getframe(); sr.close();
I=bbApply('crop',I,bb2,'replicate');
I=uint8(imResample(double(I{1}),siz0*scale));
Is(:,:,:,f)=I;
end
% now plot all and save
prm=struct('hasChn',1,'padAmt',pad*2*scale,'padEl',0,'mm',mRows,...
'showLines',0,'labels',{labels});
h=figureResized(.9,1); clf; montage2(Is,prm); hold on;
bbApply('draw',bbN,bbCol,2,bbLst); bbApply('draw',bboN,bboCol,2,bboLst);
savefig([fName int2str2(page-1,2)],h,'png','-r200','-fonts'); close(h);
if(0), save([fName int2str2(page-1,2) '.mat'],'Is'); end
end
end
end
|
github
|
devaib/MXNet-SSD-master
|
distribution_object_attr.m
|
.m
|
MXNet-SSD-master/matlab/kitti/distribution_object_attr.m
| 607 |
utf_8
|
d75ba2748e2c1b866b667e6fb0c595a9
|
% inputs
% attribute : which attribute of image to be explored, 'width', 'height' or 'ratio'
% nBin : number of bins in histogram
function distribution_object_attr(attribute, nBin)
imginfo_file = '../../data/kitti/results/imginfos_valset.txt';
% load file
f = fopen(imginfo_file);
imginfos = textscan(f,'%s %d %d %d %d %f %d','delimiter',',');
fclose(f);
if strcmp(attribute, 'width')
attr = imginfos{1,4};
elseif strcmp(attribute, 'height')
attr = imginfos{1,5};
elseif strcmp(attribute, 'ratio')
attr = imginfos{1,6};
end
histogram(attr, nBin);
[N, edges] = histcounts(attr, nBin);
end
|
github
|
devaib/MXNet-SSD-master
|
writeLabels.m
|
.m
|
MXNet-SSD-master/matlab/kitti/writeLabels.m
| 2,759 |
utf_8
|
9f25c784ee622dc760d160581deac377
|
function writeLabels(objects,label_dir,img_idx)
% parse input file
fid = fopen(sprintf('%s/%06d.txt',label_dir,img_idx),'w');
% for all objects do
for o = 1:numel(objects)
% set label, truncation, occlusion
if isfield(objects(o),'type'), fprintf(fid,'%s ',objects(o).type);
else error('ERROR: type not specified!'), end;
if isfield(objects(o),'truncation'), fprintf(fid,'%.2f ',objects(o).truncation);
else fprintf(fid,'-1 '); end; % default
if isfield(objects(o),'occlusion'), fprintf(fid,'%.d ',objects(o).occlusion);
else fprintf(fid,'-1 '); end; % default
if isfield(objects(o),'alpha'), fprintf(fid,'%.2f ',wrapToPi(objects(o).alpha));
else fprintf(fid,'-10 '); end; % default
% set 2D bounding box in 0-based C++ coordinates
if isfield(objects(o),'x1'), fprintf(fid,'%.2f ',objects(o).x1);
else error('ERROR: x1 not specified!'); end;
if isfield(objects(o),'y1'), fprintf(fid,'%.2f ',objects(o).y1);
else error('ERROR: y1 not specified!'); end;
if isfield(objects(o),'x2'), fprintf(fid,'%.2f ',objects(o).x2);
else error('ERROR: x2 not specified!'); end;
if isfield(objects(o),'y2'), fprintf(fid,'%.2f ',objects(o).y2);
else error('ERROR: y2 not specified!'); end;
% set 3D bounding box
if isfield(objects(o),'h'), fprintf(fid,'%.2f ',objects(o).h);
else fprintf(fid,'-1 '); end; % default
if isfield(objects(o),'w'), fprintf(fid,'%.2f ',objects(o).w);
else fprintf(fid,'-1 '); end; % default
if isfield(objects(o),'l'), fprintf(fid,'%.2f ',objects(o).l);
else fprintf(fid,'-1 '); end; % default
if isfield(objects(o),'t'), fprintf(fid,'%.2f %.2f %.2f ',objects(o).t);
else fprintf(fid,'-1000 -1000 -1000 '); end; % default
if isfield(objects(o),'ry'), fprintf(fid,'%.2f ',wrapToPi(objects(o).ry));
else fprintf(fid,'-10 '); end; % default
% set score
if isfield(objects(o),'score'), fprintf(fid,'%.2f ',objects(o).score);
else error('ERROR: score not specified!'); end;
% next line
fprintf(fid,'\n');
end
% close file
fclose(fid);
function alpha = wrapToPi(alpha)
% wrap to [0..2*pi]
alpha = mod(alpha,2*pi);
% wrap to [-pi..pi]
idx = alpha>pi;
alpha(idx) = alpha(idx)-2*pi;
|
github
|
devaib/MXNet-SSD-master
|
distribution_object_attr.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/distribution_object_attr.m
| 1,618 |
utf_8
|
c1bb39c275cc03eecf834929335c6f14
|
% inputs
% attribute : which attribute of image to be explored, 'width', 'height' or 'ratio'
% nBin : number of bins in histogram
function distribution_object_attr(attribute, nBin)
imginfo_file = '../../data/caltech-pedestrian-dataset-converter/results/imginfos.txt';
imginfo_train_file = '../../data/caltech-pedestrian-dataset-converter/results/imginfos_train.txt';
imginfo_val_file = '../../data/caltech-pedestrian-dataset-converter/results/imginfos_val.txt';
% load file
f = fopen(imginfo_file);
imginfos = textscan(f,'%s %s %s %f %f %f %f %f','delimiter',',');
fclose(f);
f = fopen(imginfo_train_file);
imginfos_train = textscan(f,'%s %s %s %f %f %f %f %f','delimiter',',');
fclose(f);
f = fopen(imginfo_val_file);
imginfos_val = textscan(f,'%s %s %s %f %f %f %f %f','delimiter',',');
fclose(f);
imginfo = {1,3};
imginfo{1,1} = imginfos; imginfo{1,2} = imginfos_train; imginfo{1,3} = imginfos_val;
titles = {1,3};
titles{1,1} = 'all'; titles{1,2} = 'train'; titles{1,3} = 'val';
figure(1);
for i = 1 : 3
if strcmp(attribute, 'width')
attr = imginfo{1,i}{1,6};
elseif strcmp(attribute, 'height')
attr = imginfo{1,i}{1,7};
elseif strcmp(attribute, 'ratio')
attr = imginfo{1,i}{1,8};
end
%figure
subplot(3,1,i);
%edges = [0:0.01:1];
%histogram(attr, edges);
histogram(attr, nBin)
title(titles{1,i});
[N, edges] = histcounts(attr, nBin);
average = mean(attr)
median_v = median(attr)
hold on;
line([average, average], ylim, 'LineWidth', 2, 'Color', 'r');
line([median_v, median_v], ylim, 'LineWidth', 2, 'Color', 'b');
end
end
|
github
|
devaib/MXNet-SSD-master
|
vbb.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/vbb.m
| 26,999 |
utf_8
|
49eea1941e375a3293a6f9aa9ee21726
|
function varargout = vbb( action, varargin )
% Data structure for video bounding box (vbb) annotations.
%
% A video bounding box (vbb) annotation stores bounding boxes (bbs) for
% objects of interest. The primary difference from a static annotation is
% that each object can exist for multiple frames, ie, a vbb annotation not
% only provides the locations of objects but also tracking information. A
% vbb annotation A is simply a Matlab struct. It contains data per object
% (such as a string label) and data per object per frame (such as a bb).
% Each object is identified with a unique integer id.
%
% Data per object (indexed by integer id) includes the following fields:
% init - 0/1 value indicating whether object w given id exists
% lbl - a string label describing object type (eg: 'pedestrian')
% str - the first frame in which object appears (1 indexed)
% end - the last frame in which object appears (1 indexed)
% hide - 0/1 value indicating object is 'hidden' (used during labeling)
%
% Data per object per frame (indexed by frame and id) includes:
% pos - [l t w h]: bb indicating predicted object extent
% posv - [l t w h]: bb indicating visible region (may be [0 0 0 0])
% occl - 0/1 value indicating if bb is occluded
% lock - 0/1 value indicating bb is 'locked' (used during labeling)
%
% vbb contains a number of utility functions for working with an
% annotation A, making it generally unnecessary to access the fields of A
% directly. The format for accessing the various utility functions is:
% outputs = vbb( 'action', inputs );
% Below is a list of utility functions, broken up into 3 categories.
% Occasionally more help is available via a call to help "vbb>action".
%
% %%% init and save/load annotation to/from disk
% Create new annotation for given length video
% A = vbb( 'init', nFrame, maxObj )
% Generate annotation filename (add .vbb and optionally time stamp)
% [fName,ext] = vbb( 'vbbName', fName, [timeStmp], [ext] )
% Save annotation A to fName with optional time stamp (F by default)
% vbb('vbbSave', A, fName, [timeStmp] )
% Load annotation from disk:
% A = vbb('vbbLoad', fName )
% Save annotation A to fName (in .txt format):
% vbb('vbbSaveTxt', A, fName, timeStmp )
% Load annotation from disk (in .txt format):
% A = vbb('vbbLoadTxt', fName )
% Export single frame annotations to tarDir/*.txt
% vbb( 'vbbToFiles', A, tarDir, [fs], [skip], [f0], [f1] )
% Combine single frame annotations from srcDir/*.txt
% [A,fs] = vbb( 'vbbFrFiles', srcDir, [fs] )
%
% %%% inspect / alter annotation
% Get number of unique objects in annotation
% n = vbb( 'numObj', A )
% Get an unused object id (for adding a new object)
% [A,id] = vbb( 'newId', A )
% Create a new, empty object (not added to A)
% [A,obj] = vbb( 'emptyObj', A, [frame] )
% Get struct with all data from frames s-e for given object
% obj = vbb( 'get', A, id, [s], [e] )
% Add object to annotation
% A = vbb( 'add', A, obj )
% Remove object from annotation
% A = vbb( 'del', A, id )
% Crop or extend object temporally
% A = vbb( 'setRng', A, id, s, e )
% Get object information, see above for valid properties
% v = vbb( 'getVal', A, id, name, [frmS], [frmE] )
% Set object information, see above for valid properties
% A = vbb( 'setVal', A, id, name, v, [frmS], [frmE] )
%
% %%% other functions
% Visulatization: draw annotation on top of current image
% hs = vbb( 'drawToFrame', A, frame )
% Uses seqPlayer to display seq file with overlayed annotations.
% vbb( 'vbbPlayer', A, srcName )
% Visulatization: create seq file w annotation superimposed.
% vbb( 'drawToVideo', A, srcName, tarName )
% Shift entire annotation by del frames. (useful for synchronizing w video)
% A = vbb( 'timeShift', A, del )
% Ensure posv is fully contained in pos
% A = vbb( 'swapPosv', A, validate, swap, hide )
% Stats: get stats about annotation
% [stats,stats1,logDur] = vbb( 'getStats', A );
% Returns the ground truth bbs for a single frame.
% [gt,posv,lbls] = vbb( 'frameAnn', A, frame, lbls, test )
%
% USAGE
% varargout = vbb( action, varargin );
%
% INPUTS
% action - string specifying action
% varargin - depends on action, see above
%
% OUTPUTS
% varargout - depends on action, see above
%
% EXAMPLE
%
% See also BBAPPLY
%
% Caltech Pedestrian Dataset Version 3.2.1
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%#ok<*DEFNU>
varargout = cell(1,nargout);
[varargout{:}] = eval([action '(varargin{:});']);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% init / save / load
function A = init( nFrame, maxObj )
if( nargin<2 || isempty(maxObj) ), maxObj=16; end
A.nFrame = nFrame;
A.objLists = cell(1,nFrame);
A.maxObj = maxObj;
A.objInit = zeros(1,A.maxObj);
A.objLbl = cell(1,A.maxObj);
A.objStr = -ones(1,A.maxObj);
A.objEnd = -ones(1,A.maxObj);
A.objHide = zeros(1,A.maxObj);
A.altered = false;
A.log = 0;
A.logLen = 0;
end
function [fName,ext] = vbbName( fName, timeStmp, ext )
if(nargin<2), timeStmp=false; end; if(nargin<3), ext=''; end
[d,f,ext1]=fileparts(fName); if(isempty(ext)), ext=ext1; end
if(isempty(ext)), ext='.vbb'; end
if(timeStmp), f=[f '-' regexprep(datestr(now), ':| ', '-')]; end
if(isempty(d)), d='.'; end; fName=[d '/' f ext];
end
function vbbSave( A, fName, timeStmp )
if(nargin<3), timeStmp=false; end; vers=1.4; %#ok<NASGU>
[fName,ext]=vbbName(fName,timeStmp);
if(strcmp(ext,'.txt')), vbbSaveTxt(A,fName,timeStmp); return; end
A=cleanup(A); save(fName,'A','vers','-v6'); %#ok<NASGU>
end
function A = vbbLoad( fName )
[fName,ext]=vbbName(fName); vers=1.4;
if(strcmp(ext,'.txt')), A=vbbLoadTxt(fName); return; end
L = load( '-mat', fName );
if( ~isfield(L,'A') || ~isfield(L,'vers') );
error('Not a valid video annoation file.');
end;
A = L.A;
% .06 -> 1.0 conversion (add log/logLen)
if( L.vers==.06 )
L.vers=1.0; A.log=0; A.logLen=0;
end
% 1.0 -> 1.1 conversion (add trnc field)
if( L.vers==1.0 )
L.vers=1.1;
for f=1:A.nFrame
if(isempty(A.objLists{f})); A.objLists{f}=[]; end
for j=1:length(A.objLists{f}); A.objLists{f}(j).trnc=0; end
end
end
% 1.1 -> 1.2 conversion (add hide/posv fields)
if( L.vers==1.1 )
L.vers=1.2;
for f=1:A.nFrame
if(isempty(A.objLists{f})); A.objLists{f}=[]; end
for j=1:length(A.objLists{f}); A.objLists{f}(j).posv=[0 0 0 0]; end
end
A.objHide = zeros(1,A.maxObj);
end
% 1.2 -> 1.3 conversion (remove trnc field)
if( L.vers==1.2 )
L.vers=1.3;
for f=1:A.nFrame
if(isempty(A.objLists{f})); A.objLists{f}=[]; else
A.objLists{f} = rmfield(A.objLists{f},'trnc');
end
end
end
% 1.3 -> 1.4 conversion (remove objAr field)
if( L.vers==1.3 )
L.vers=1.4; A = rmfield(A,'objAr');
end
% check version
if( L.vers~=vers )
er = [num2str(L.vers) ' (current: ' num2str(vers) ')'];
error(['Incompatible versions: ' er]);
end
% order fields
order={'nFrame','objLists','maxObj','objInit','objLbl','objStr',...
'objEnd','objHide','altered','log','logLen'};
A = orderfields(A,order);
A.altered = false;
end
function vbbSaveTxt( A, fName, timeStmp )
if(nargin<3), timeStmp=false; end; vers=1.4;
fName=vbbName(fName,timeStmp,'.txt');
A=cleanup(A,0); n=numObj(A); nFrame=A.nFrame;
fid=fopen(fName,'w'); assert(fid>0);
% write header info to text
fp=@(varargin) fprintf(fid,varargin{:});
fp('%% vbb version=%f\n',vers); fp('nFrame=%i n=%i\n',nFrame,n);
fp('log=['); fp('%f ',A.log); fp(']\n');
% write each object to text
for id=1:n, o=get(A,id);
fp('\n-----------------------------------\n');
fp('lbl=''%s'' str=%i end=%i hide=%i\n',o.lbl,o.str,o.end,o.hide);
fp('pos =['); fp('%f %f %f %f; ',o.pos'); fp(']\n');
fp('posv=['); fp('%f %f %f %f; ',o.posv'); fp(']\n');
fp('occl=['); fp('%i ',o.occl); fp(']\n');
fp('lock=['); fp('%i ',o.lock); fp(']\n');
end
fclose(fid);
end
function A = vbbLoadTxt( fName )
fName=vbbName(fName,0,'.txt'); vers=1.4;
if(~exist(fName,'file')), error([fName ' not found']); end
try
% read in header and create A
f=fopen(fName,'r'); s=fgetl(f); v=sscanf(s,'%% vbb version=%f');
if(v~=vers), error('Incompatible versions: %f (current=%f)',v,vers); end
s=fgetl(f); r=sscanf(s,'nFrame=%d n=%d'); nFrame=r(1); n=r(2);
s=fgetl(f); assert(strcmp(s(1:5),'log=[')); assert(s(end)==']');
log=sscanf(s(6:end-1),'%f ')'; A=init(nFrame,n);
% read in each object in turn
for id=1:n
s=fgetl(f); assert(isempty(s));
s=fgetl(f); assert(strcmp(s,'-----------------------------------'));
s=fgetl(f); r=textscan(s,'lbl=%s str=%d end=%d hide=%d');
[A,o]=emptyObj(A,0); o.lbl=r{1}{1}(2:end-1);
o.str=r{2}; o.end=r{3}; o.hide=r{4};
s=fgetl(f); assert(strcmp(s(1:6),'pos =[')); assert(s(end)==']');
pos=sscanf(s(7:end-1),'%f %f %f %f;'); o.pos=reshape(pos,4,[])';
s=fgetl(f); assert(strcmp(s(1:6),'posv=[')); assert(s(end)==']');
posv=sscanf(s(7:end-1),'%f %f %f %f;'); o.posv=reshape(posv,4,[])';
s=fgetl(f); assert(strcmp(s(1:6),'occl=[')); assert(s(end)==']');
o.occl=sscanf(s(7:end-1),'%d ');
s=fgetl(f); assert(strcmp(s(1:6),'lock=[')); assert(s(end)==']');
o.lock=sscanf(s(7:end-1),'%d ');
A=add(A,o);
end
if(isempty(log)), A.log=0; A.logLen=0; else
A.log=log; A.logLen=length(log); end
A.altered=false; fclose(f);
catch e, fclose(f); throw(e);
end
end
function vbbToFiles( A, tarDir, fs, skip, f0, f1 )
% export single frame annotations to tarDir/*.txt
nFrm=A.nFrame; fName=@(f) ['I' int2str2(f-1,5) '.txt'];
if(nargin<3 || isempty(fs)), for f=1:nFrm, fs{f}=fName(f); end; end
if(nargin<4 || isempty(skip)), skip=1; end
if(nargin<5 || isempty(f0)), f0=1; end
if(nargin<6 || isempty(f1)), f1=nFrm; end
if(~exist(tarDir,'dir')), mkdir(tarDir); end
for f=f0:skip:f1
nObj=length(A.objLists{f}); objs=bbGt('create',nObj);
for j=1:nObj
o=A.objLists{f}(j); objs(j).lbl=A.objLbl{o.id}; objs(j).occ=o.occl;
objs(j).bb=round(o.pos); objs(j).bbv=round(o.posv);
end
bbGt('bbSave',objs,[tarDir '/' fs{f}]);
end
end
function [A,fs] = vbbFrFiles( srcDir, fs )
% combine single frame annotations from srcDir/*.txt
if(nargin<2 || isempty(fs)), fs=dir([srcDir '/*.txt']); fs={fs.name}; end
nFrm=length(fs); A=init(nFrm);
for f=1:nFrm
objs = bbGt('bbLoad',[srcDir '/' fs{f}]);
for j=1:length(objs)
[A,obj]=emptyObj(A,f); o=objs(j); obj.lbl=o.lbl;
obj.pos=o.bb; obj.occl=o.occ; obj.posv=o.bbv; A=add(A,obj);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% inspect / alter annotation
function n = numObj( A )
n = sum( A.objInit );
end
function [A,id] = newId( A )
[val,id] = min( A.objInit );
if( isempty(val) || val~=0 );
A = doubleLen( A );
[val,id] = min( A.objInit );
end
assert(val==0);
end
function [A,obj] = emptyObj( A, frame )
[A,id] = newId( A );
obj.id = id;
obj.lbl = '';
obj.hide = 0;
if(nargin<2)
obj.str = -1;
obj.end = -1;
len = 0;
else
obj.str = frame;
obj.end = frame;
len = 1;
end
obj.pos = zeros(len,4);
obj.posv = zeros(len,4);
obj.occl = zeros(len,1);
obj.lock = ones(len,1);
end
function obj = get( A, id, s, e )
assert( 0<id && id<=A.maxObj );
assert( A.objInit(id)==1 );
if(nargin<3); s=A.objStr(id); else assert(s>=A.objStr(id)); end;
if(nargin<4); e=A.objEnd(id); else assert(e<=A.objEnd(id)); end;
% get general object info
obj.id = id;
obj.lbl = A.objLbl{id};
obj.str = s;
obj.end = e;
obj.hide = A.objHide(id);
% get per-frame object info
len = obj.end-obj.str+1;
obj.pos = zeros(len,4);
obj.posv = zeros(len,4);
obj.occl = zeros(len,1);
obj.lock = zeros(len,1);
for i=1:len
f = obj.str+i-1;
objList = A.objLists{f};
obj1 = objList([objList.id]==id);
obj.pos(i,:) = obj1.pos;
obj.posv(i,:) = obj1.posv;
obj.occl(i) = obj1.occl;
obj.lock(i) = obj1.lock;
end
end
function A = add( A, obj )
% check id or get new id
id = obj.id;
if( id==-1 )
[A,id] = newId( A );
else
assert( 0<id && id<=A.maxObj );
assert( A.objInit(id)==0 );
end
% save general object info
A.objInit(id) = 1;
A.objLbl{id} = obj.lbl;
A.objStr(id) = obj.str;
A.objEnd(id) = obj.end;
A.objHide(id) = obj.hide;
% save per-frame object info
len = obj.end - obj.str + 1;
assert( size(obj.pos,1)==len );
assert( size(obj.posv,1)==len );
assert( size(obj.occl,1)==len );
assert( size(obj.lock,1)==len );
for i = 1:len
obj1.id = id;
obj1.pos = obj.pos(i,:);
obj1.posv = obj.posv(i,:);
obj1.occl = obj.occl(i);
obj1.lock = obj.lock(i);
f = obj.str+i-1;
A.objLists{f}=[A.objLists{f} obj1];
end
A = altered( A );
end
function A = del( A, id )
assert( 0<id && id<=A.maxObj );
assert( A.objInit(id)==1 );
% delete per-frame object info
objStr = A.objStr(id);
objEnd = A.objEnd(id);
len = objEnd-objStr+1;
for i=1:len
f = objStr+i-1;
objList = A.objLists{f};
objList([objList.id]==id) = [];
A.objLists{f} = objList;
end
% delete general object info
A.objInit(id) = 0;
A.objLbl{id} = [];
A.objStr(id) = -1;
A.objEnd(id) = -1;
A.objHide(id) = 0;
A = altered( A );
end
function A = setRng( A, id, s, e )
assert( s>=1 && e<=A.nFrame && s<=e && A.objInit(id)==1 );
s0=A.objStr(id); e0=A.objEnd(id); assert( e>=s0 && e0>=s );
if(s==s0 && e==e0), return; end; A.objStr(id)=s; A.objEnd(id)=e;
if( s0>s )
objs=A.objLists{s0}; obj=objs([objs.id]==id); obj.occl=0; obj.lock=0;
for f=s:s0-1, A.objLists{f}=[A.objLists{f} obj]; end
elseif( s0<s )
for f=s0:s-1, os=A.objLists{f}; os([os.id]==id)=[]; A.objLists{f}=os; end
end
if( e>e0 )
objs=A.objLists{e0}; obj=objs([objs.id]==id); obj.occl=0; obj.lock=0;
for f=e0+1:e, A.objLists{f}=[A.objLists{f} obj]; end
elseif( e<e0 )
for f=e+1:e0, os=A.objLists{f}; os([os.id]==id)=[]; A.objLists{f}=os; end
end
A = altered( A );
end
function v = getVal( A, id, name, frmS, frmE )
if(nargin<4); frmS=[]; end;
if(nargin<5); frmE=frmS; end;
assert(strcmp(name,'init') || A.objInit(id)==1);
switch name
case 'lbl'
assert( isempty(frmS) );
v = A.objLbl{id};
case {'init','str','end','hide'}
assert( isempty(frmS) );
name = ['obj' upper(name(1)) name(2:end)];
v = A.(name)(id);
case {'pos','posv','occl','lock'}
assert( ~isempty(frmS) );
assert( A.objStr(id)<=frmS && frmE<=A.objEnd(id) );
frms = frmS:frmE; len=length(frms);
for f=1:len
objList = A.objLists{frms(f)};
v1 = objList([objList.id]==id).(name);
if( f==1 ); v=repmat(v1,[len 1]); else v(f,:) = v1; end
end
otherwise
error( ['invalid field: ' name] );
end
end
function A = setVal( A, id, name, v, frmS, frmE )
if(nargin<5); frmS=[]; end;
if(nargin<6); frmE=frmS; end;
assert( A.objInit(id)==1 );
switch name
case 'lbl'
assert( isempty(frmS) );
A.objLbl{id} = v;
case {'hide'}
assert( isempty(frmS) );
name = ['obj' upper(name(1)) name(2:end)];
A.(name)(id) = v;
case {'pos','posv','occl','lock'}
assert( ~isempty(frmS) );
assert( A.objStr(id)<=frmS && frmE<=A.objEnd(id) );
frms = frmS:frmE; len=length(frms);
for f=1:len
objList = A.objLists{frms(f)};
objList([objList.id]==id).(name) = v(f,:);
A.objLists{frms(f)} = objList;
end
otherwise
error( ['invalid/unalterable field: ' name] );
end
A = altered( A );
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% other functions
function hs = drawToFrame( A, frame )
hs=[];
for o=A.objLists{frame}
hr = bbApply('draw', o.pos, 'g', 2, '-' );
if(all(o.posv)==0), hrv=[]; else
hrv = bbApply('draw', o.posv, 'y', 2, '--' );
end
label = [A.objLbl{o.id} ' [' int2str(o.id) ']'];
ht = text( o.pos(1), o.pos(2)-10, label );
set( ht, 'color', 'w', 'FontSize', 10, 'FontWeight', 'bold' );
hs = [hs hr ht hrv]; %#ok<AGROW>
end
end
function vbbPlayer( A, srcName )
dispFunc=@(f) vbb('drawToFrame',A,f+1);
seqPlayer(srcName,dispFunc);
end
function drawToVideo( A, srcName, tarName )
% open video to read and make video to write
assert( ~strcmp(srcName,tarName) );
sr=seqIo(srcName,'r'); info=sr.getinfo();
nFrame=info.numFrames; w=info.width; h=info.height;
assert(A.nFrame==nFrame); sw=seqIo(tarName,'w',info);
% display and write each frame
ticId=ticStatus; hf=figure; hAx=axes('parent',hf);
hIm=imshow(zeros(h,w,3,'uint8'),'parent',hAx); truesize;
for i=1:nFrame
I=sr.getnext(); set(hIm,'CData',I); hs=drawToFrame(A,i);
I=getframe; I=I.cdata; I=I(1:h,1:w,:);
sw.addframe(I); delete(hs); tocStatus( ticId, i/nFrame );
end
sr.close(); sw.close(); close(hf);
end
function A = timeShift( A, del )
% shift entire annotation by del frames
nFrame=A.nFrame; locs=logical(A.objInit);
if(del>0), is=locs & A.objStr==1; A.objStr(is)=A.objStr(is)-del; end
A.objStr(locs)=min(max(A.objStr(locs)+del,1),nFrame);
A.objEnd(locs)=min(max(A.objEnd(locs)+del,1),nFrame);
if( del>0 ) % replicate annotation for first frame del times
A.objLists=[A.objLists(ones(1,del)) A.objLists(1:end-del)];
else % no annotations for last del frames
A.objLists=[A.objLists(1-del:end) cell(1,-del)];
end
end
function A = swapPosv( A, validate, swap, hide )
% Swap pos/posv and ensure pos/posv consistent.
%
% The visible region of an object (posv) should be a subset of the
% predicted region (pos). If the object is not occluded, then posv is the
% same as pos (posv=[0 0 0 0] by default and indicates posv not set).
% Swapping is used to swap pos and posv, and validating is used to ensure
% pos contains posv. In two cases no swapping/validating occurs. If occl==0
% for a given bb, posv is set to [0 0 0 0]. If occl==1 and posv=[0 0 0 0],
% posv is set to pos. In either case there is no need to swap or validate.
%
% The validate flag:
% validate==-1: posv = intersect(pos,posv)
% validate== 0: no validation
% validate==+1: pos = union(pos,posv)
% If posv is shrunk to 0, it is set to a small bb inside pos.
%
% The swap flag:
% swap==-1: pos and posv are swapped before validating
% swap== 0: no swapping
% swap==+1: pos and posv are swapped after validating
%
% The hide flag:
% hide==0: set hide attribute to 0 for all objects
% hide==1: set hide attribute to 1 iff object is at some point occluded
%
% Suppose a user has labeled pos in a given video using some annotation
% tool. At this point can swap pos and posv and use the same tool in the
% same manner to label posv (which is stored in pos). Afterwards, can swap
% pos/posv again, and ensure they are consistent, and both end up labeled.
% Additionally, in the second labeling phase, we may want to hide any
% object that is never occluded. The command to setup labeling of posv is:
% A=vbb('swapPosv',A,-1,1,1); % validate (trust pos) THEN swap
% Afterwards, to swap back, would use:
% A=vbb('swapPosv',A,1,-1,0); % swap THEN validate (trust posv)
% While labeling posv only frames where occl is already set should be
% altered (the occl flag itself shouldn't be altered).
%
% USAGE
% A = vbb( 'swapPosv', A, validate, swap, hide )
%
% INPUTS
% A - annotation structure
% validate - see above
% swap - see above
% hide - see above
%
% OUTPUTS
% A - updated annotation
%
% EXAMPLE
%
% see also vbb
for f=1:A.nFrame
for i=1:length(A.objLists{f})
o=A.objLists{f}(i); p=o.pos; v=o.posv; vt=[];
% v is trivial - either [0 0 0 0] or same as p, continue
if(o.occl==0), vt=[0 0 0 0]; elseif(all(v)==0), vt=p; end
if(~isempty(vt)), A.objLists{f}(i).posv=vt; continue; end
% optionally swap before validating
if(swap==-1), t=p; p=v; v=t; end
% validate
if( validate==-1 )
v = bbApply('intersect',v,p);
if(all(v==0)), v=[p(1:2)+p(3:4)/2 1 1]; end
elseif( validate==1 )
p = bbApply('union',v,p);
end
% optionally swap after validating
if(swap==1), t=p; p=v; v=t; end
% store results
o.pos=p; o.posv=v; A.objLists{f}(i)=o;
end
end
if(~hide), A.objHide(:)=0; else
for id=find( A.objInit )
occl=vbb('getVal',A,id,'occl',A.objStr(id),A.objEnd(id));
A.objHide(id) = all(occl==0);
end
end
end
function [stats,stats1,logDur] = getStats( A )
% get stats of many annotations simultaneously by first merging
if(length(A)>1), A=merge(A); end
% log activity (allows up to .25h of inactivity)
nObj0=numObj(A); if(nObj0==0), stats=struct(); return; end
log = A.log / 1.1574e-005 / 60 / 60;
locs = find( (log(2:end)-log(1:end-1)) > .25 );
logS=log([1 locs+1]); logE=log([locs A.logLen]);
logDur = sum(logE-logS);
% getStats1 on entire annotation
stats = getStats1( A );
% getStats1 separately for each label
lbl0=unique(A.objLbl); nLbl0=length(lbl0);
stats1=repmat(getStats1(subset(A,lbl0(1))),1,nLbl0);
for i0=2:nLbl0, stats1(i0)=getStats1(subset(A,lbl0(i0))); end
function stats = getStats1( A )
% unique labels and label counts
lbl=unique(A.objLbl); nLbl=length(lbl); lblCnts=zeros(1,nLbl);
for i=1:nLbl, lblCnts(i)=sum(strcmp(A.objLbl,lbl{i})); end
stats.labels=lbl; stats.labelCnts=lblCnts;
% get object lengths
nObj=numObj(A); stats.nObj=nObj;
len=A.objEnd-A.objStr+1; stats.len=len;
% get all per frame info in one flat array ordered by object id
nPerFrm=cellfun(@length,A.objLists); stats.nPerFrm=nPerFrm;
ols=A.objLists(nPerFrm>0); ols=[ols{:}];
ids=[ols.id]; [ids,order]=sort(ids); ols=ols(order); stats.ids=ids;
inds=[0 cumsum(len)]; stats.inds=inds;
% get all pos/posv and centers, also first/last frame for each obj
pos=reshape([ols.pos],4,[])'; posv=reshape([ols.posv],4,[])';
posS=pos(inds(1:end-1)+1,:); posE=pos(inds(2:end),:);
stats.pos=pos; stats.posv=posv; stats.posS=posS; stats.posE=posE;
% get object centers and per frame deltas
cen=bbApply('getCenter',pos); stats.cen=cen;
del=cen(2:end,:)-cen(1:end-1,:); del(inds(2:end),:)=-1; stats.del=del;
% get occlusion information
occl=(sum(posv,2)>0)'; %occl=[ols.occl]; <--slow
occFrac=1-posv(:,3).*posv(:,4)./pos(:,3)./pos(:,4); occFrac(occl==0)=0;
occTime=zeros(1,nObj); for i=1:nObj, occTime(i)=mean(occl(ids==i)); end
stats.occl=occl; stats.occFrac=occFrac'; stats.occTime=occTime;
end
function A = subset( A, lbls )
% find elements to keep
nObj=numObj(A); keep=false(1,nObj);
for i=1:length(lbls), keep=keep | strcmp(A.objLbl,lbls{i}); end
% clean up objLists by dropping elements
frms=find(cellfun('isempty',A.objLists)==0); ols=A.objLists;
for f=frms, ols{f}=ols{f}(keep([ols{f}.id])); end, A.objLists=ols;
% run cleanup to reorder/drop elements
A.objInit=keep; A=cleanup(A,0);
end
function A = merge( AS )
nFrm=0; nObj=0;
for i=1:numel(AS)
Ai=cleanup(AS(i),0);
for f=1:Ai.nFrame
for j=1:length(Ai.objLists{f}),
Ai.objLists{f}(j).id=Ai.objLists{f}(j).id+nObj;
end
end
Ai.objStr=Ai.objStr+nFrm; Ai.objEnd=Ai.objEnd+nFrm;
nFrm=Ai.nFrame+nFrm; Ai.nFrame=nFrm;
nObj=nObj+numObj(Ai); AS(i)=Ai;
end
A.nFrame = nFrm;
A.objLists = [AS.objLists];
A.maxObj = sum([AS.maxObj]);
A.objInit = [AS.objInit];
A.objLbl = [AS.objLbl];
A.objStr = [AS.objStr];
A.objEnd = [AS.objEnd];
A.objHide = [AS.objHide];
A.altered = false;
A.log = sort([AS.log]);
A.logLen = sum([AS.logLen]);
end
end
function [gt,posv,lbls1] = frameAnn( A, frame, lbls, test )
% Returns the ground truth bbs for a single frame.
%
% Returns bbs for all object with lbl in lbls. The result is an [nx5] array
% where each row is of the form [x y w h ignore]. [x y w h] is the bb and
% ignore is a 0/1 flag that indicates regions to be ignored. For each
% returned object, the ignore flag is set to 0 if test(lbl,pos,posv)=1 for
% the given object. For example, using lbls={'person','people'}, and
% test=@(lbl,bb,bbv) bb(4)>100, returns bbs for all 'person' and 'people'
% in given frame, and for any objects under 100 pixels tall ignore=1.
%
% USAGE
% [gt,posv,lbls] = vbb( 'frameAnn', A, frame, lbls, [test] )
%
% INPUTS
% A - annotation structure
% frame - the frame index
% lbls - cell array of string labels
% test - [] ignore = ~test(lbl,pos,posv)
%
% OUTPUTS
% gt - [n x 5] array containg ground truth for frame
% posv - [n x 4] bbs of visible regions
% lbls - [n x 1] list of object labels
%
% EXAMPLE
% lbls={'person','people'}; test=@(lbl,bb,bbv) bb(4)>100;
% [gt,lbls] = vbb( 'frameAnn', A, 200, lbls, test )
if( nargin<4 ), test=[]; end; assert(frame<=A.nFrame);
ng=length(A.objLists{frame}); ignore=0;
gt=zeros(ng,5); posv=zeros(ng,4); lbls1=cell(1,ng); keep=true(1,ng);
for g=1:ng
o=A.objLists{frame}(g); lbl=A.objLbl{o.id};
if(~any(strcmp(lbl,lbls))), keep(g)=0; continue; end
if(~isempty(test)), ignore=~test(lbl,o.pos,o.posv); end
gt(g,:)=[o.pos ignore]; lbls1{g}=lbl; posv(g,:)=o.posv;
end
gt=gt(keep,:); lbls1=lbls1(keep); posv=posv(keep,:);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper functions
function A = doubleLen( A )
maxObj = max(1,A.maxObj);
A.objInit = [A.objInit zeros(1,maxObj)];
A.objLbl = [A.objLbl cell(1,maxObj)];
A.objStr = [A.objStr -ones(1,maxObj)];
A.objEnd = [A.objEnd -ones(1,maxObj)];
A.objHide = [A.objHide zeros(1,maxObj)];
A.maxObj = max(1,A.maxObj * 2);
A = altered( A );
end
function A = altered( A )
A.altered = true;
if( length(A.log)==A.logLen )
A.log = [A.log zeros(1,A.logLen)];
end
T = now; sec=1.1574e-005;
if( A.logLen>0 && (T-A.log(A.logLen))/sec<1 )
A.log(A.logLen) = T;
else
A.logLen = A.logLen+1;
A.log(A.logLen) = T;
end
end
function A = cleanup( A, minn )
% cleanup() Removes placeholder entries from A
if( A.maxObj==0 ), return; end
if( nargin<2 || isempty(minn) ), minn=1; end
% reorder so all initialized objects are first
while( 1 )
% find first 0 entry in objInit
[val,id0] = min(A.objInit);
if( val==1 || id0==A.maxObj ), break; end
% find last 1 entry past 0 entry
[val,id1]=max(fliplr(A.objInit(id0+1:end))); id1=A.maxObj-id1+1;
if(val==0), break; end
% swap these two locations
A = swap( A, id0, id1 );
end
% now discard all uninitialized objects (keep at least minn though)
[val,n] = min(A.objInit); n=max(minn,n-1);
if( val==0 )
A.maxObj = n;
A.objInit = A.objInit(1:n);
A.objLbl = A.objLbl(1:n);
A.objStr = A.objStr(1:n);
A.objEnd = A.objEnd(1:n);
A.objHide = A.objHide(1:n);
end
% discard useless elements in log
A.log = A.log(1:A.logLen);
end
function A = swap( A, id1, id2 )
A0=A;
if(A0.objInit(id1)), fs=A0.objStr(id1):A0.objEnd(id1); else fs=[]; end
for f=fs, ol=A0.objLists{f}; ol([ol.id]==id1).id=id2; A.objLists{f}=ol; end
if(A0.objInit(id2)), fs=A0.objStr(id2):A0.objEnd(id2); else fs=[]; end
for f=fs, ol=A0.objLists{f}; ol([ol.id]==id2).id=id1; A.objLists{f}=ol; end
A.objInit(id1) = A0.objInit(id2); A.objInit(id2) = A0.objInit(id1);
A.objLbl(id1) = A0.objLbl(id2); A.objLbl(id2) = A0.objLbl(id1);
A.objStr(id1) = A0.objStr(id2); A.objStr(id2) = A0.objStr(id1);
A.objEnd(id1) = A0.objEnd(id2); A.objEnd(id2) = A0.objEnd(id1);
A.objHide(id1) = A0.objHide(id2); A.objHide(id2) = A0.objHide(id1);
end
|
github
|
devaib/MXNet-SSD-master
|
vbbLabeler.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/vbbLabeler.m
| 38,968 |
utf_8
|
03ea75bed8df14e50d44027476666f52
|
function vbbLabeler( objTypes, vidNm, annNm )
% Video bound box (vbb) Labeler.
%
% Used to annotated a video (seq file) with (tracked) bounding boxes. An
% online demo describing usage is available. The code below is fairly
% complex and poorly documented. Please do not email me with question about
% how it works (unless you discover a bug).
%
% USAGE
% vbbLabeler( [objTypes], [vidNm], [annNm] )
%
% INPUTS
% objTypes - [{'object'}] list of object types to annotate
% imgDir - [] initial video to load
% resDir - [] initial annotation to load
%
% OUTPUTS
%
% EXAMPLE
% vbbLabeler
%
% See also vbb, vbbPlayer
%
% Caltech Pedestrian Dataset Version 3.2.1
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% defaults
if(nargin<1 || isempty(objTypes)), objTypes={'object'}; end
if(nargin<2 || isempty(vidNm)), vidNm=''; end
if(nargin<3 || isempty(annNm)), annNm=''; end
% settable constants
maxSkip = 250; % max value for skip
nStep = 16; % number of objects to display in lower panel
repLen = 1; % number of seconds to replay on left replay
maxCache = 500; % max cache length (set as high as memory allows)
fps = 150; % initial fps for playback (if 0 uses actual fps)
skip0 = 20; % initial skip (zoom)
seqPad = 4; % amount of padding around object in seq view
siz0 = 20; % minimum rect width/height
sizLk = 0; % if true rects cannot be resized
colType=0; rectCols=uniqueColors(3,8); % color rects according to id
%colType=1; rectCols=uniqueColors(3,3); % color rects according to type
% handles to gui objects / other globals
enStr = {'off','on'};
[hFig, pLf, pRt, pMenu, pObj, pSeq ] = deal([]);
[A,skip,offset,curInd,seqH,objApi,dispApi,filesApi] = deal([]);
% initialize all
makeLayout();
filesApi = filesMakeApi();
objApi = objMakeApi();
dispApi = dispMakeApi();
filesApi.closeVid();
set(hFig,'Visible','on');
drawnow;
% optionally load default data
if(~isempty(vidNm)), filesApi.openVid(vidNm); end
if(~isempty(annNm)), filesApi.openAnn(annNm); end
function makeLayout()
% properties for gui objects
bg='BackgroundColor'; fg='ForegroundColor'; ha='HorizontalAlignment';
units={'Units','pixels'}; st='String'; ps='Position'; fs='FontSize';
axsPr=[units {'Parent'}]; o4=[1 1 1 1]; clr=[.1 .1 .1];
pnlPr=[units {bg,clr,'BorderType','none','Parent'}];
btnPr={bg,[.7 .7 .7],fs,10,ps};
chbPr={'Style','checkbox',fs,8,'Interruptible','off',bg,clr,fg,'w',ps};
txtPr={'Style','text',fs,8,bg,clr,fg,'w',ps};
edtPr={'Style','edit',fs,8,bg,clr,fg,'w',ps};
uic = @(varargin) uicontrol(varargin{:});
icn=load('vbbIcons'); icn=icn.icons;
% hFig: main figure
set(0,units{:}); ss=get(0,'ScreenSize');
if( ss(3)<800 || ss(4)<600 ), error('screen too small'); end
pos = [(ss(3)-780)/2 (ss(4)-580)/2 780 580];
hFig = figure( 'Name','VBB Labeler', 'NumberTitle','off', ...
'Toolbar','auto', 'MenuBar','none', 'ResizeFcn',@figResized, ...
'Color','k', 'Visible','off', 'DeleteFcn',@exitLb, ps,pos, ...
'keyPressFcn',@keyPress );
% pMenu: video/annotation menus
pMenu.hVid = uimenu(hFig,'Label','Video');
pMenu.hVidOpn = uimenu(pMenu.hVid,'Label','Open');
pMenu.hVidCls = uimenu(pMenu.hVid,'Label','Close');
pMenu.hAnn = uimenu(hFig,'Label','Annotation');
pMenu.hAnnNew = uimenu(pMenu.hAnn,'Label','New');
pMenu.hAnnOpn = uimenu(pMenu.hAnn,'Label','Open');
pMenu.hAnnSav = uimenu(pMenu.hAnn,'Label','Save');
pMenu.hAnnCls = uimenu(pMenu.hAnn,'Label','Close');
pMenu.hCn = [pMenu.hVid pMenu.hAnn];
% pObj: top panel containing object controls
pObj.h=uipanel(pnlPr{:},hFig);
pObj.hObjTp = uic( pObj.h,'Style','popupmenu',fs,8,units{:},...
ps,[31 2 100 25],st,objTypes,'Value',1);
pObj.hBtPrv = uic(pObj.h,btnPr{:},[5 3 25 25],'CData',icn.rNext{1});
pObj.hBtNxt = uic(pObj.h,btnPr{:},[132 3 25 25],'CData',icn.rNext{2});
pObj.hBtNew = uic(pObj.h,btnPr{:},[169 3 25 25],'CData',icn.rNew);
pObj.hBtDel = uic(pObj.h,btnPr{:},[196 3 25 25],'CData',icn.rDel);
pObj.hCbFix = uic(pObj.h,chbPr{:},[230 9 50 13],st,'Lock');
pObj.hStSiz = uic(pObj.h,txtPr{:},[280 9 80 13],ha,'Center');
pObj.hCn = [pObj.hObjTp pObj.hBtNew pObj.hBtDel ...
pObj.hBtPrv pObj.hBtNxt pObj.hCbFix];
% pSeq: bottom panel containing object sequence
pSeq.h=uipanel(pnlPr{:},hFig);
pSeq.hAx = axes(axsPr{:},pSeq.h,ps,o4);
pSeq.apiRng = selectorRange(pSeq.h,o4,nStep,[],[.1 .5 1]);
pSeq.apiOcc = selectorRange(pSeq.h,o4,nStep,[],[.9 .9 .7]);
pSeq.apiLck = selectorRange(pSeq.h,o4,nStep,[],[.5 1 .5]);
pSeq.lblRng = uic(pSeq.h,txtPr{:},o4,st,'vs',fs,7,ha,'Center');
pSeq.lblOcc = uic(pSeq.h,txtPr{:},o4,st,'oc',fs,7,ha,'Center');
pSeq.lblLck = uic(pSeq.h,txtPr{:},o4,st,'lk',fs,7,ha,'Center');
% pLf: left main panel
pLf.h=uipanel(pnlPr{:},hFig); pLf.hAx=axes(axsPr{:},hFig);
icn5={icn.pPlay{1},icn.pStep{1},icn.pPause,icn.pStep{2},icn.pPlay{2}};
for i=1:5, pLf.btn(i)=uic(pLf.h,btnPr{:},o4,'CData',icn5{i}); end
pLf.btnRep = uic(pLf.h,btnPr{:},[10 5 25 20],'CData',icn.pRepeat);
pLf.fpsLbl = uic(pLf.h,txtPr{:},o4,ha,'Left',st,'fps:');
pLf.fpsInd = uic(pLf.h,edtPr{:},o4,ha,'Center');
pLf.hFrInd = uic(pLf.h,edtPr{:},o4,ha,'Right');
pLf.hFrNum = uic(pLf.h,txtPr{:},o4,ha,'Left');
pLf.hCn = [pLf.btn pLf.btnRep];
% pRt: right main panel
pRt.h=uipanel(pnlPr{:},hFig); pRt.hAx=axes(axsPr{:},hFig);
pRt.btnRep = uic(pRt.h,btnPr{:},[10 5 25 20],'CData',icn.pRepeat);
pRt.btnGo = uic(pRt.h,btnPr{:},[350 5 25 20],'CData',icn.fJump);
pRt.hFrInd = uic(pRt.h,txtPr{:},o4,ha,'Right');
pRt.hFrNum = uic(pRt.h,txtPr{:},o4,ha,'Left');
pRt.stSkip = uic(pRt.h,txtPr{:},[55 8 45 14],ha,'Right');
pRt.edSkip = uic(pRt.h,edtPr{:},[100 7 28 16],ha,'Center');
pRt.stOffst = uic(pRt.h,txtPr{:},[140 7 30 14],ha,'Center');
pRt.slOffst = uic(pRt.h,'Style','slider',bg,clr,ps,[175 5 70 20]);
setIntSlider( pRt.slOffst, [1 nStep-1] );
pRt.hCn = [pRt.btnRep pRt.btnGo pRt.slOffst];
function figResized( h, e ) %#ok<INUSD>
% overall size of drawable area (fWxfH)
pos = get(hFig,ps); pad=8; pTopH=30;
fW=pos(3)-2*pad; fH=pos(4)-2*pad-pTopH-75;
fW0=1290; fH0=(480+fW0/nStep);
fW=max(fW,700); fH=max(fH,700*fH0/fW0);
fW=min(fW,fH*fW0/fH0); fH=min(fH,fW*fH0/fW0);
% where to draw
r = fW/fW0; fW=round(fW); fH=round(fH);
seqH=floor((fW0-pad)/nStep*r); seqW=seqH*nStep; seqH=seqH+29;
x = max(pad,(pos(3)-fW)/2);
y = max(pad,(pos(4)-fH-pTopH-70)/2);
% set panel positions (resized from canonical positions)
set( pObj.h, ps, [x y+fH+70 640*r pTopH] );
set( pLf.hAx, ps, [x y+seqH+32 640*r 480*r] );
set( pRt.hAx, ps, [x+650*r y+seqH+32 640*r 480*r] );
set( pLf.h, ps, [x y+seqH+2 640*r 30] );
set( pRt.h, ps, [x+650*r y+seqH+2 640*r 30] );
set( pSeq.h, ps, [x+(fW-seqW)/2+2 y seqW seqH] );
% postion pSeq contents
set(pSeq.hAx,ps,[0 11 seqW seqH-29]); y=1;
pSeq.apiLck.setPos([0 y seqW 10]);
set(pSeq.lblLck,ps,[-13 y 12 10]); y=seqH-18;
pSeq.apiOcc.setPos([0 y seqW 10]);
set(pSeq.lblOcc,ps,[-13 y 12 10]); y=seqH-9;
pSeq.apiRng.setPos([0 y seqW 10]);
set(pSeq.lblRng,ps,[-13 y 12 10]);
% postion pLf and pRt contents
x=640*r-90; set(pRt.btnGo,ps,[x+60 5 25 20]); x1=640/3*r-75;
set(pLf.hFrInd,ps,[x 7 40 16]); set(pLf.hFrNum,ps,[x+40 8 40 14]);
set(pRt.hFrInd,ps,[x-30 8 40 14]); set(pRt.hFrNum,ps,[x+10 8 40 14]);
for i2=1:5, set(pLf.btn(i2),ps,[640/2*r+(i2-3.5)*26+10 5 25 20]); end
set(pLf.fpsLbl,ps,[x1 8 23 14]); set(pLf.fpsInd,ps,[x1+23 7 38 16]);
% request display update
if(~isempty(dispApi)); dispApi.requestUpdate(true); end;
end
function exitLb( h, e ) %#ok<INUSD>
filesApi.closeVid();
end
function keyPress( h, evnt ) %#ok<INUSL>
char=int8(evnt.Character); if(isempty(char)), char=0; end;
if( char==28 ), dispApi.setPlay(-inf); end
if( char==29 ), dispApi.setPlay(+inf); end
if( char==31 ), dispApi.setPlay(0); end
end
function setIntSlider( hSlider, rng )
set(hSlider,'Min',rng(1),'Value',rng(1),'Max',rng(2));
minSt=1/(rng(2)-rng(1)); maxSt=ceil(.25/minSt)*minSt;
set(hSlider,'SliderStep',[minSt maxSt]);
end
end
function api = objMakeApi()
% variables
[objId,objS,objE,objInd,seqObjs,lims] = deal([]);
apiRng=pSeq.apiRng; apiOcc=pSeq.apiOcc; apiLck=pSeq.apiLck;
% callbacks
set(pObj.hBtNew, 'callback', @(h,e) objNew());
set(pObj.hBtDel, 'callback', @(h,e) objDel());
set(pObj.hBtPrv, 'callback', @(h,e) objToggle(-1));
set(pObj.hBtNxt, 'callback', @(h,e) objToggle(+1));
set(pObj.hObjTp, 'callback', @(h,e) objSetType());
set(pObj.hCbFix, 'callback', @(h,e) objSetFixed());
apiRng.setRngChnCb(@objSetRng); apiRng.setLockCen(1);
apiOcc.setRngChnCb(@objSetOcc); apiLck.setRngChnCb(@objSetLck);
% create api
api=struct( 'init',@init, 'drawRects',@drawRects, ...
'prepSeq',@prepSeq, 'prepPlay',@prepPlay, ...
'annForSave',@annForSave, 'annSaved',@annSaved );
function init()
[objId,objS,objE,objInd,seqObjs,lims] = deal([]);
objId=-1; objSelect(-1); isAnn=~isempty(A); prepPlay();
if( ~isAnn ), return; end
lims=[0 0 dispApi.width() dispApi.height()]+.5;
objTypes = unique([A.objLbl(A.objInit==1) objTypes]);
t='*new-type*'; objTypes=[setdiff(objTypes,t) t];
set( pObj.hObjTp, 'String', objTypes, 'Value',1 );
end
function prepPlay()
if(objId>0), A=vbb('setRng',A,objId,objS+1,objE+1); end
set(pObj.hStSiz,'String',''); set(pObj.hCn,'Enable','off');
apiRng.enable(0); apiOcc.enable(0); apiLck.enable(0);
end
function seqI = prepSeq()
seqI=100*ones(seqH,seqH*nStep,3,'uint8'); seqObjs=[];
if(isempty(A)), return; end; n=nStepVis();
% see if objId still visible, adjust controls accordingly
lstInd = curInd + min(dispApi.nFrameRt(),skip*n-1);
isVis = objId>0 && objS<=lstInd && objE>=curInd;
set(pObj.hStSiz,'String',''); set(pObj.hCn,'Enable','on');
apiRng.enable(isVis); apiOcc.enable(isVis); apiLck.enable(isVis);
if(~isVis), objSelect(-1); return; end
% extrapolate obj to current range for display only
objSe=min(objS,curInd); objEe=max(objE,lstInd);
A = vbb( 'setRng', A, objId, objSe+1, objEe+1 );
% bound objInd to be in a visible axes
s=max(objSe,curInd); e=min(objEe,lstInd);
objInd = min(max(objInd,s),e);
objInd = curInd + skip*floor((objInd-curInd)/skip);
% update apiRng/apiOcc/apiLck
s = max(floor((objS-curInd)/skip)+1,1);
e = min(floor((objE-curInd)/skip)+1,n);
rng=zeros(1,nStep); occ=rng; lck=rng; rng(s:e)=1;
for i=1:n
ind0=curInd+(i-1)*skip; ind1=objGrpInd(ind0,1);
occ(i) = max(vbb('getVal',A,objId,'occl',ind0+1,ind1+1));
lck(i) = max(vbb('getVal',A,objId,'lock',ind0+1,ind1+1));
end;
apiRng.setRng(rng); apiOcc.setRng(occ); apiLck.setRng(lck);
apiRng.enable([1 n]); apiOcc.enable([s e]); apiLck.enable([s e]);
if(objS<curInd), lk=0; else lk=[]; end; apiRng.setLockLf(lk);
if(objE>lstInd), lk=0; else lk=[]; end; apiRng.setLockRt(lk);
% update other gui controls
objType=vbb('getVal',A,objId,'lbl');
set(pObj.hObjTp,'Value',find(strcmp(objType,objTypes)));
p=ceil(vbb('getVal',A,objId,'pos',objInd+1));
set(pObj.hStSiz,'String',[num2str(p(3)) ' x ' num2str(p(4))]);
% create seqObjs and seqI for display
seqObjs = repmat(struct(),1,n);
for i=0:n-1, ind=curInd+i*skip;
% absolute object location
pos0 = vbb('getVal', A, objId, 'pos', ind+1 );
posv = vbb('getVal', A, objId, 'posv', ind+1 );
% crop / resize sequence image
posSq = bbApply( 'resize', pos0, seqPad, seqPad );
posSq = bbApply( 'squarify', posSq, 0 );
[Ii,posSq] = bbApply('crop',dispApi.getImg(ind),posSq); Ii=Ii{1};
rows = round(linspace(1,size(Ii,1),seqH-2));
cols = round(linspace(1,size(Ii,2),seqH-2));
seqI(2:seqH-1,(2:seqH-1)+i*seqH,:) = Ii(rows,cols,:);
% oLim~=intersect(posSq,lims); pos~=centered(pos0*res)
res = (seqH-2)/size(Ii,1);
xDel=-i*seqH-1+posSq(1)*res; yDel=-1+posSq(2)*res;
oLim = bbApply('intersect',lims-.5,posSq);
oLim = bbApply('shift',oLim*res,xDel,yDel);
pos = bbApply('shift',pos0*res,xDel,yDel);
if(any(posv)), posv=bbApply('shift',posv*res,xDel,yDel); end
% seqObjs info
lks=vbb('getVal',A,objId,'lock',ind+1,objGrpInd(ind,1)+1);
seqObjs(i+1).pos0=pos0; seqObjs(i+1).pos=pos;
seqObjs(i+1).posv=posv; seqObjs(i+1).res=res;
seqObjs(i+1).lims=oLim; seqObjs(i+1).lock=max(lks);
end
end
function hs = drawRects( flag, ind )
hs=[]; if(isempty(A)), return; end
switch flag
case {'panelLf','panelRt'}
os=A.objLists{ind+1}; n=length(os);
if(n>0), [~,ord]=sort([os.id]==objId); os=os(ord); end
lockSet = get(pObj.hCbFix,'Value');
playMode = strcmp(get(pObj.hObjTp,'enable'),'off');
for i=1:n, o=os(i); id=o.id; lbl=A.objLbl(id);
if(A.objHide(id)), continue; end
if(lockSet && id~=objId && ~playMode), continue; end
static=(lockSet && id~=objId) || playMode;
hs1=drawRect(o.pos,o.posv,lims,lbl,static,id,ind,-1);
hs=[hs hs1]; %#ok<AGROW>
end
case 'objSeq'
if(objInd==-1), return; end
n=nStepVis(); id=objId; lbl=A.objLbl(id);
for i=1:n, o=seqObjs(i); ind=curInd+skip*(i-1);
hs1=drawRect(o.pos,o.posv,o.lims,lbl,0,id,ind,i-1);
hs=[hs hs1]; %#ok<AGROW>
end
end
function hs = drawRect(pos,posv,lims,lbl,static,id,ind,sid)
if(colType), t=find(strcmp(lbl,objTypes)); else t=id; end
col=rectCols(mod(t-1,size(rectCols,1))+1,:);
if(id~=objId), ls='-'; else
if(ind==objInd), ls='--'; else ls=':'; end; end
rp = {'lw',2,'color',col,'ls',ls,'rotate',0,'ellipse',0};
[hs,api]=imRectRot('pos',pos,'lims',lims,rp{:});
api.setSizLock( sizLk );
if( static )
api.setPosLock(1);
ht=text(pos(1),pos(2)-10, lbl); hs=[hs ht];
set(ht,'color','w','FontSize',10,'FontWeight','bold');
else
api.setPosSetCb( @(pos) objSetPos(pos(1:4),id,ind,sid) );
end
if( any(posv) )
rp={'LineWidth',2,'EdgeColor','y','LineStyle',':'};
hs = [hs rectangle('Position',posv,rp{:})];
end
end
function objSetPos( pos, id, ind, sid )
if(sid>=0), o=seqObjs(sid+1); pos=o.pos0-(o.pos-pos)/o.res; end
if(sid>0), dispApi.setOffset(sid); end
pos=constrainPos(pos); A=vbb('setVal',A,id,'pos',pos,ind+1);
if(objId==id), objS=min(objS,ind); objE=max(objE,ind); end
objSelect(id,ind); ind0=curInd+floor((ind-curInd)/skip)*skip;
ind1=objGrpInd(ind0,0); lks=zeros(ind1-ind0+1,1);
A = vbb('setVal',A,id,'lock',lks,ind0+1,ind1+1);
dispApi.requestUpdate();
end
end
function objNew()
[A,o]=vbb('emptyObj',A,curInd+1); t=get(pObj.hObjTp,'Value');
o.lbl=objTypes{t}; if(colType==0), t=o.id; end
col=rectCols(mod(t-1,size(rectCols,1))+1,:);
rp={'lw',2,'color',col,'ls','--','rotate',0,'ellipse',0};
pos=dispApi.newRect(lims,rp); o.pos=constrainPos(pos);
A=vbb('add',A,o); objSelect(o.id,curInd); dispApi.requestUpdate();
end
function objDel()
if(objId<=0), return; end; A=vbb('del',A,objId);
objId=-1; objSelect(-1); dispApi.requestUpdate();
end
function objSetLck( rng0, rng1 )
assert(objId>0); [lf,rt]=apiRng.getBnds(rng0~=rng1);
% set object locks accordingly
for i=lf:rt
ind0=curInd+(i-1)*skip; ind1=objGrpInd(ind0,0);
lks = [rng1(i); zeros(ind1-ind0,1)];
A=vbb('setVal',A,objId,'lock',lks,ind0+1,ind1+1);
end
s=max(objS,curInd); e=min(objE,curInd+skip*(nStepVis()-1));
if(~rng1(lf) || s==e), dispApi.requestUpdate(); return; end
% interpolate intermediate positions
o=vbb('get',A,objId,s+1,e+1); pos=[o.pos]; [n,k]=size(pos);
lks=[o.lock]; lks([1 end])=1; lks=find(lks);
for i=1:k, pos(:,i)=interp1(lks,pos(lks,i),1:n,'cubic'); end
pos=constrainPos(pos); A=vbb('setVal',A,objId,'pos',pos,s+1,e+1);
dispApi.requestUpdate();
end
function objSetRng( rng0, rng1 )
[lf0,rt0]=apiRng.getBnds( rng0 );
[lf1,rt1]=apiRng.getBnds( rng1 );
rt1=min(rt1,nStepVis()); assert(objId>0);
if(lf1~=lf0), objS=curInd+(lf1-1)*skip; end
if(rt1~=rt0), objE=curInd+(rt1-1)*skip; end
if(lf1~=lf0 || rt1~=rt0), objSelect(objId,objInd); end
dispApi.requestUpdate();
end
function objSetOcc( rng0, rng1 )
assert(objId>0); [lf,rt]=apiRng.getBnds(rng0~=rng1); assert(lf>0);
if(lf>1 && rng0(lf-1)==1), lf=lf-1; rng1(lf)=1; end %extend lf
if(rt<nStep && rng0(rt+1)==1), rt=rt+1; rng1(rt)=1; end %extend rt
for i=lf:rt
ind0=curInd+(i-1)*skip; ind1=objGrpInd(ind0,0);
occl = ones(ind1-ind0+1,1)*rng1(i);
A=vbb('setVal',A,objId,'occl',occl,ind0+1,ind1+1);
end; dispApi.requestUpdate();
end
function objSetFixed(), dispApi.requestUpdate(); end
function objSetType()
type = get(pObj.hObjTp,'Value');
if( strcmp(objTypes{type},'*new-type*') )
typeStr = inputdlg('Define new object type:');
if(isempty(typeStr) || any(strcmp(typeStr,objTypes)))
set(pObj.hObjTp,'Value',1); return; end
objTypes = [objTypes(1:end-1) typeStr objTypes(end)];
set(pObj.hObjTp,'String',objTypes,'Value',length(objTypes)-1);
end
if( objId>0 )
A = vbb('setVal',A,objId,'lbl',objTypes{type});
dispApi.requestUpdate();
end
end
function objToggle( d )
li=curInd; ri=curInd+skip*offset;
os=A.objLists{li+1}; if(isempty(os)), L=[]; else L=[os.id]; end
os=A.objLists{ri+1}; if(isempty(os)), R=[]; else R=[os.id]; end
[ids,R,L]=union(R,L); inds=[ones(1,numel(L))*li ones(1,numel(R))*ri];
keep=A.objHide(ids)==0; ids=ids(keep); inds=inds(keep);
n=length(ids); if(n==0), return; end
if(objId==-1), if(d==1), j=1; else j=n; end; else
j=find(ids==objId)+d; end
if(j<1 || j>n), objSelect(-1); else objSelect(ids(j),inds(j)); end
dispApi.requestUpdate();
end
function objSelect( id, ind )
if(objId>0), A=vbb('setRng',A,objId,objS+1,objE+1); end
if(id==-1), [objId,objS,objE,objInd]=deal(-1); return; end
objS=vbb('getVal',A,id,'str')-1; objE=vbb('getVal',A,id,'end')-1;
objId=id; objInd=ind;
end
function ind1 = objGrpInd( ind0, useExtended )
ind1 = min(ind0+skip-1,curInd+dispApi.nFrameRt());
if(~useExtended); ind1=min(ind1,objE); end
end
function n = nStepVis()
n = min(nStep,floor(dispApi.nFrameRt()/skip+1));
end
function pos = constrainPos( pos )
p=pos; p(:,3:4)=max(1,p(:,3:4)); r=max(1,siz0./p(:,3:4));
dy=(r(:,2)-1).*p(:,4); p(:,2)=p(:,2)-dy/2; p(:,4)=p(:,4)+dy;
dx=(r(:,1)-1).*p(:,3); p(:,1)=p(:,1)-dx/2; p(:,3)=p(:,3)+dx;
s=p(:,1:2); e=s+p(:,3:4);
for j=1:2, s(:,j)=min(max(s(:,j),lims(j)),lims(j+2)-siz0); end
for j=1:2, e(:,j)=max(min(e(:,j),lims(j+2)),s(:,j)+siz0); end
pos = [s e-s];
end
function A1 = annForSave()
if(objId==-1), A1=A; else A1=vbb('setRng',A,objId,objS+1,objE+1); end
end
function annSaved(), assert(~isempty(A)); A.altered=false; end
end
function api = dispMakeApi()
% variables
[sr, info, looping, nPlay, replay, needUpdate, dispMode, ...
timeDisp, hImLf, hImRt, hImSeq, hObjCur] = deal([]);
% callbacks
set( pRt.slOffst, 'Callback', @(h,e) setOffset() );
set( pRt.edSkip, 'Callback', @(h,e) setSkip() );
set( pLf.fpsInd, 'Callback', @(h,e) setFps() );
set( pLf.btnRep, 'Callback', @(h,e) setPlay('replayLf') );
set( pRt.btnRep, 'Callback', @(h,e) setPlay('replayRt') );
set( pRt.btnGo, 'Callback', @(h,e) setFrame('go') );
set( pLf.hFrInd, 'Callback', @(h,e) setFrame() );
set( pLf.btn(1), 'Callback', @(h,e) setPlay(-inf) );
set( pLf.btn(2), 'Callback', @(h,e) setFrame('-') );
set( pLf.btn(3), 'Callback', @(h,e) setPlay(0) );
set( pLf.btn(4), 'Callback', @(h,e) setFrame('+') );
set( pLf.btn(5), 'Callback', @(h,e) setPlay(+inf) );
% create api
api = struct( 'requestUpdate',@requestUpdate, 'init',@init, ...
'newRect',@newRect, 'setOffset',@setOffset, ...
'nFrame',@nFrame, 'nFrameRt', @nFrameRt, 'getImg',@getImg, ...
'width',@width, 'height',@height, 'setPlay', @setPlay );
function init( sr1 )
if(isstruct(sr)), sr=sr.close(); end; delete(hObjCur);
[sr, info, looping, nPlay, replay, needUpdate, dispMode, ...
timeDisp, hImLf, hImRt, hImSeq, hObjCur] = deal([]);
nPlay=0; replay=0; dispMode=0; looping=1; curInd=0;
needUpdate=1; sr=sr1; skip=1;
if(isstruct(sr)), info=sr.getinfo(); else
info=struct('numFrames',0,'width',0,'height',0,'fps',25); end
if(fps), info.fps=fps; end
setOffset(nStep-1); setSkip(skip0); setFps(info.fps);
hs = [pLf.hAx pRt.hAx pSeq.hAx];
for h=hs; cla(h); set(h,'XTick',[],'YTick',[]); end
set([pLf.hCn pRt.hCn],'Enable',enStr{(nFrame>0)+1});
set([pLf.hFrInd pRt.hFrInd],'String','0');
set([pLf.hFrNum pRt.hFrNum],'String',[' / ' int2str(nFrame)]);
looping=0; requestUpdate();
end
function dispLoop()
if( looping ), return; end; looping=1; k=0;
while( 1 )
% if vid not loaded nothing to display
if( nFrame==0 ), looping=0; return; end
% increment/decrement curInd/nPlay appropriately
if( nPlay~=0 )
needUpdate=1; fps=info.fps; t=clock(); t=t(6)+60*t(5);
del=round(fps*(t-timeDisp)); timeDisp=timeDisp+del/fps;
if(nPlay>0), del=min(del,nPlay); else del=max(-del,nPlay); end
nPlay=nPlay-del; if(~replay), curInd=curInd+del; end
if(del==0), drawnow(); continue; end
end
% update display if necessary
k=k+1; if(0 && ~needUpdate), fprintf('%i draw events.\n',k); end
if( ~needUpdate ), looping=0; return; end
updateDisp(); filesApi.backupAnn(); drawnow();
end
end
function updateDisp()
% delete old objects
delete(hObjCur); hObjCur=[];
% possibly switch display modes
if( dispMode~=0 && nPlay==0 )
needUpdate=1; dispMode=0; replay=0;
elseif( abs(dispMode)==1 )
needUpdate=1; dispMode=dispMode*2;
if(dispMode<0), hImMsk=hImRt; else hImMsk=hImLf; end
I=get(hImMsk,'CData'); I(:)=100; set(hImMsk,'CData',I);
I=get(hImSeq,'CData'); I(:)=100; set(hImSeq,'CData',I);
objApi.prepPlay();
else
needUpdate=0;
end
if(dispMode==0), seqI = objApi.prepSeq(); end
% display left panel
if( dispMode<=0 )
set( hFig, 'CurrentAxes', pLf.hAx );
ind=curInd; if(replay), ind=ind-nPlay; end
hImLf = imageFast( hImLf, getImg(ind) );
set( pLf.hFrInd, 'String', int2str(ind+1) );
hObjCur=[hObjCur objApi.drawRects('panelLf',ind)];
end
% display right panel
if( dispMode>=0 )
set( hFig, 'CurrentAxes', pRt.hAx );
ind=curInd+offset*skip; if(replay), ind=ind-nPlay; end
hImRt = imageFast( hImRt, getImg(ind) );
set( pRt.hFrInd, 'String', int2str(ind+1) );
hObjCur=[hObjCur objApi.drawRects('panelRt',ind)];
end
% display seq panel
if( dispMode==0 )
set( hFig, 'CurrentAxes', pSeq.hAx );
hImSeq = imageFast( hImSeq, seqI );
hObjCur=[hObjCur objApi.drawRects('objSeq',[])];
end
% adjust play controls
set( pLf.btnRep, 'Enable', enStr{(curInd>0)+1} );
set( pLf.btn(1:2), 'Enable', enStr{(curInd>0)+1} );
set( pLf.btn(4:5), 'Enable', enStr{(offset*skip<nFrameRt())+1});
function hImg = imageFast( hImg, I )
if(isempty(hImg)), hImg=image(I); axis off; else
set(hImg,'CData',I); end
end
end
function pos = newRect( lims, rp )
% get new rectangle, extract pos (disable controls temporarily)
hs=[pObj.hCn pLf.hCn pRt.hCn pMenu.hCn];
en=get(hs,'Enable'); set(hs,'Enable','off');
[hR,api]=imRectRot('hParent',pLf.hAx,'lims',lims,rp{:});
hObjCur=[hObjCur hR]; pos=api.getPos(); pos=pos(1:4);
for i=1:length(hs); set(hs(i),'Enable',en{i}); end
requestUpdate();
end
function requestUpdate( clearHs )
if(nargin==0 || isempty(clearHs)), clearHs=0; end
if(clearHs), [hImLf, hImRt, hImSeq]=deal([]); end
needUpdate=true; dispLoop();
end
function setSkip( skip1 )
if(nargin==0), skip1=round(str2double(get(pRt.edSkip,'String'))); end
if(~isnan(skip1)), skip=max(1,min(skip1,maxSkip)); end
if(nFrame>0), skip=min(skip,floor(nFrameRt()/offset)); end
set( pRt.stSkip, 'String', 'zoom: 1 / ');
set( pRt.edSkip, 'String', int2str(skip) );
set( pRt.stOffst,'String', ['+' int2str(offset*skip)] );
setPlay(0);
end
function setOffset( offset1 )
if( nargin==1 ), offset=offset1; else
offset=round(get(pRt.slOffst,'Value')); end
if(nFrame>0), offset=min(offset,floor(nFrameRt()/skip)); end
set( pRt.slOffst, 'Value', offset );
set( pRt.stOffst, 'String', ['+' int2str(offset*skip)] );
setPlay(0);
end
function setFrame( f )
if(nargin==0), f=round(str2double(get(pLf.hFrInd,'String'))); end
if(strcmp(f,'-')), f=curInd-skip+1; end
if(strcmp(f,'+')), f=curInd+skip+1; end
if(strcmp(f,'go')), f=curInd+skip*offset+1; end
if(~isnan(f)), curInd=max(0,min(f-1,nFrame-skip*offset-1)); end
set(pLf.hFrInd,'String',int2str(curInd+1)); setPlay(0);
end
function setPlay( type )
switch type
case 'replayLf'
nPlay=min(curInd,repLen*info.fps);
dispMode=-1; replay=1;
case 'replayRt'
nPlay=min(skip*offset,nFrameRt());
dispMode=1; replay=1;
otherwise
nPlay=type; dispMode=-1; replay=0;
if(nPlay<0), nPlay=max(nPlay,-curInd); end
if(nPlay>0), nPlay=min(nPlay,nFrameRt-offset*skip); end
end
t=clock(); t=t(6)+60*t(5); timeDisp=t; requestUpdate();
end
function setFps( fps )
if(nargin==0), fps=round(str2double(get(pLf.fpsInd,'String'))); end
if(isnan(fps)), fps=info.fps; else fps=max(1,min(fps,99999)); end
set(pLf.fpsInd,'String',int2str(fps)); info.fps=fps; setPlay(0);
end
function I=getImg(f)
sr.seek(f); I=sr.getframe(); if(ismatrix(I)), I=I(:,:,[1 1 1]); end
end
function w=width(), w=info.width; end
function h=height(), h=info.height; end
function n=nFrame(), n=info.numFrames; end
function n=nFrameRt(), n=nFrame-1-curInd; end
end
function api = filesMakeApi()
% variables
[fVid, fAnn, tSave, tSave1] = deal([]);
% callbacks
set( pMenu.hVidOpn, 'Callback', @(h,e) openVid() );
set( pMenu.hVidCls, 'Callback', @(h,e) closeVid() );
set( pMenu.hAnnNew, 'Callback', @(h,e) newAnn() );
set( pMenu.hAnnOpn, 'Callback', @(h,e) openAnn() );
set( pMenu.hAnnSav, 'Callback', @(h,e) saveAnn() );
set( pMenu.hAnnCls, 'Callback', @(h,e) closeAnn() );
% create api
api = struct('closeVid',@closeVid, 'backupAnn',@backupAnn, ...
'openVid',@openVid, 'openAnn',@openAnn );
function updateMenus()
m=pMenu; en=enStr{~isempty(fVid)+1}; nm='VBB Labeler';
set([m.hVidCls m.hAnnNew m.hAnnOpn],'Enable',en);
en=enStr{~isempty(fAnn)+1}; set([m.hAnnSav m.hAnnCls],'Enable',en);
if(~isempty(fVid)), [~,nm1]=fileparts(fVid); nm=[nm ' - ' nm1]; end
set(hFig,'Name',nm); objApi.init(); dispApi.requestUpdate();
end
function closeVid()
fVid=[]; if(~isempty(fAnn)), closeAnn(); end
dispApi.init([]); updateMenus();
end
function openVid( f )
if( nargin>0 )
[d,f]=fileparts(f); if(isempty(d)), d='.'; end;
d=[d '/']; f=[f '.seq'];
else
if(isempty(fVid)), d='.'; else d=fileparts(fVid); end
[f,d]=uigetfile('*.seq','Select video',[d '/*.seq']);
end
if( f==0 ), return; end; closeVid(); fVid=[d f];
try
s=0; sr=seqIo(fVid,'r',maxCache); s=1;
dispApi.init(sr); updateMenus();
catch er
errordlg(['Failed to load: ' fVid '. ' er.message],'Error');
if(s); closeVid(); end; return;
end
end
function closeAnn()
assert(~isempty(fAnn)); A1=objApi.annForSave();
if( ~isempty(A1) && A1.altered )
qstr = 'Save Current Annotation?';
button = questdlg(qstr,'Exiting','yes','no','yes');
if(strcmp(button,'yes')); saveAnn(); end
end
A=[]; [fAnn,tSave,tSave1]=deal([]); updateMenus();
end
function openAnn( f )
assert(~isempty(fVid)); if(~isempty(fAnn)), closeAnn(); end
if( nargin>0 )
[d,f,e]=fileparts(f); if(isempty(d)), d='.'; end; d=[d '/'];
if(isempty(e) && exist([d f '.txt'],'file')), e='.txt'; end
if(isempty(e) && exist([d f '.vbb'],'file')), e='.vbb'; end
f=[f e];
else
[f,d]=uigetfile('*.vbb;*.txt','Select Annotation',fVid(1:end-4));
end
if( f==0 ), return; end; fAnn=[d f];
try
if(~exist(fAnn,'file'))
A=vbb('init',dispApi.nFrame()); vbb('vbbSave',A,fAnn);
else
A=vbb( 'vbbLoad', fAnn ); eMsg='Annotation/video mismatch.';
if(A.nFrame~=dispApi.nFrame()), error(eMsg); end
end
catch er
errordlg(['Failed to load: ' fAnn '. ' er.message],'Error');
A=[]; fAnn=[]; return;
end
tSave=clock(); tSave1=tSave; updateMenus();
end
function saveAnn()
A1=objApi.annForSave(); if(isempty(A1)), return; end
[f,d]=uiputfile('*.vbb;*.txt','Select Annotation',fAnn);
if( f==0 ), return; end; fAnn=[d f]; tSave=clock; tSave1=tSave;
if(exist(fAnn,'file')), copyfile(fAnn,vbb('vbbName',fAnn,1)); end
vbb('vbbSave',A1,fAnn); objApi.annSaved();
end
function newAnn()
if(~isempty(fAnn)), closeAnn(); end; fAnn=[fVid(1:end-3) 'vbb'];
assert(~isempty(fVid)); A=vbb('init',dispApi.nFrame());
updateMenus();
end
function backupAnn()
if(isempty(tSave) || etime(clock,tSave)<30), return; end
A1=objApi.annForSave(); if(isempty(A1)), return; end
tSave=clock(); timeStmp=etime(tSave,tSave1)>60*5;
if(timeStmp), tSave1=tSave; fAnn1=fAnn; else
fAnn1=[fAnn(1:end-4) '-autobackup' fAnn(end-3:end)]; end
vbb( 'vbbSave', A1, fAnn1, timeStmp );
end
end
end
function api = selectorRange( hParent, pos, n, col0, col1 )
% Graphical way of selecting ranges from the sequence {1,2,...,n}.
%
% The result of the selection is an n element vector rng in {0,1}^n that
% indicates whether each element is selected (or in the terminology below
% ON/OFF). Particularly efficient if the ON cells in the resulting rng can
% be grouped into a few continguous blocks.
%
% Creates n individual cells, 1 per element. Each cell is either OFF/ON,
% denoted by colors col0/col1. Each cell can be clicked in three discrete
% locations: LEFT/MID/RIGHT: (1) Clicking a cell in the MID location
% toggles it ON/OFF. (2) Clicking an ON cell i turns a number of cells OFF,
% determined in the following manner. Let [lf,rt] denote the contiguous
% block of ON cells containing i. Clicking on the LEFT of cell i shrinks
% the contiguous block of ON cells to [i,rt] (ie cells [lf,i-1] are truned
% OFF). Clicking on the RIGHT of cell i shrinks the contiguous block to
% [lf,i] (ie cells [i+1,rt] are truned OFF). (3) In a similar manner
% clicking an OFF cell i turns a number of cells ON. Clicking on the LEFT
% extends the closest contiguous block to the right of i, [lf,rt], to
% [i,rt]. Clicking on the RIGHT extends the closest contiguous block the
% the left of i, [lf,rt], to [lf,i]. To better understand the interface
% simply run the example below.
%
% Locks can be set to limit how the range can change. If setLockCen(1) is
% set, the user cannot toggle individual element by clicking the MIDDLE
% location (this prevents contiguous blocks from being split). setLockLf/Rt
% can be used to ensure the overall range [lf*,rt*], where lf*=min(rng) and
% rt*=max(rng) cannot change in certain ways (see below). Also use enable()
% to enable only portion of cells for interaction.
%
% USAGE
% api = selectorRange( hParent, pos, n, [col0], [col1] )
%
% INPUTS
% hParent - object parent, either a figure or a uipanel
% pos - guis pos vector [xMin yMin width height]
% n - sequence size
% col0 - [.7 .7 .7] 1x3 array: color for OFF cells
% col1 - [.7 .9 1] 1x3 array: color for ON cells
%
% OUTPUTS
% api - interface allowing access to created gui object
% .delete() - use to delete obj, syntax is 'api.delete()'
% .enable(en) - enable given range (or 0/1 to enable/disable all)
% .setPos(pos) - set position of range selector in the figure
% .getRng() - get range: returns n elt range vector in {0,1}^n
% .setRng(rng) - set range to specified rng (n elmt vector)
% .getBnds([rng]) - get left-most/right-most (lf,rt) bounds of range
% .setRngChnCb(f) - whenever range changes, calls f(rngOld,rngNew)
% .setLockCen(v) - 0/1 enables toggling individual elements
% .setLockLf(v) - []:none; 0:locked; -1: only shrink; +1: only ext
% .setLockRt(v) - []:none; 0:locked; -1: only shrink; +1: only ext
%
% EXAMPLE
% h=figure(1); clf; pos=[10 20 500 15]; n=10;
% api = selectorRange( h, pos, n );
% rng=zeros(1,n); rng(3:7)=1; api.setRng( rng );
% f = @(rO,rN) disp(['new range= ' int2str(rN)]);
% api.setRngChnCb( f );
%
% See also imRectRot, uicontrol
narginchk(3,5);
if(nargin<4 || isempty(col0)), col0=[.7 .7 .7]; end
if(nargin<5 || isempty(col1)), col1=[.7 .9 1]; end
% globals (n, col0, col1 are implicit globals)
lockLf=-2; lockRt=-2; lockCen=0; en=1;
[Is,hAx,hImg,rangeChnCb,rng]=deal([]);
% set initial position
rng=ones(1,n); setPos( pos );
% create api
api = struct('delete',@delete1, 'enable',@enable, 'setPos',@setPos, ...
'getRng',@getRng, 'setRng',@setRng, 'getBnds',@getBnds, ...
'setRngChnCb',@setRngChnCb, 'setLockCen',@(v) setLock(v,0), ...
'setLockLf',@(v) setLock(v,-1), 'setLockRt',@(v) setLock(v,1) );
function setPos( pos )
% create images for virtual buttons (Is = h x w x rgb x enable)
w=max(3,round(pos(3)/n)); wSid=floor(w/3); wMid=w-wSid*2;
h=max(4,round(pos(4))); cols=permute([col0; col1],[1 3 2]);
IsSid=zeros(h-2,wSid,3,2); IsMid=zeros(h-2,wMid,3,2);
for i=1:2, IsSid(:,:,:,i)=repmat(cols(i,:,:),[h-2 wSid 1]); end
for i=1:2, IsMid(:,:,:,i)=repmat(cols(i,:,:),[h-2 wMid 1]); end
IsSid(:,1,:,:)=0; Is=[IsSid IsMid IsSid(:,end:-1:1,:,:)];
Is=padarray(Is,[1 0 0 0],mean(col0)*.8,'both'); pos(3)=w*n;
% create new axes and image objects
delete1(); units=get(hParent,'units'); set(hParent,'Units','pixels');
hAx=axes('Parent',hParent,'Units','pixels','Position',pos);
hImg=image(zeros(h,w*n)); axis off; set(hParent,'Units',units);
set(hImg,'ButtonDownFcn',@(h,e) btnPressed()); draw();
end
function btnPressed()
if(length(en)==1 && en==0), return; end
x=get(hAx,'CurrentPoint'); w=size(Is,2);
x=ceil(min(1,max(eps,x(1)/w/n))*3*n);
btnId=ceil(x/3); btnPos=x-btnId*3+1;
assert( btnId>=1 && btnId<=n && btnPos>=-1 && btnPos<=1 );
if(length(en)==2 && (btnId<en(1) || btnId>en(2))), return; end
% compute what contiguous block of cells to alter
if( btnPos==0 ) % toggle center
if( lockCen ), return; end
s=btnId; e=btnId; v=~rng(btnId);
elseif( btnPos==-1 && ~rng(btnId) )
rt = find(rng(btnId+1:end)) + btnId;
if(isempty(rt)), return; else rt=rt(1); end
s=btnId; e=rt-1; v=1; %extend to left
elseif( btnPos==1 && ~rng(btnId) )
lf = btnId - find(fliplr(rng(1:btnId-1)));
if(isempty(lf)), return; else lf=lf(1); end
s=lf+1; e=btnId; v=1; %extend to right
elseif( btnPos==-1 && rng(btnId) )
if(btnId==1 || ~rng(btnId-1)), return; end
lf=btnId-find([fliplr(rng(1:btnId-1)==0) 1])+1; lf=lf(1);
s=lf; e=btnId-1; v=0; %shrink to right
elseif( btnPos==1 && rng(btnId) )
if(btnId==n || ~rng(btnId+1)), return; end
rt = find([rng(btnId+1:end)==0 1]) + btnId - 1; rt=rt(1);
s=btnId+1; e=rt; v=0; %shrink to left
end
assert( all(rng(s:e)~=v) );
% apply locks preventing extension/shrinking beyond endpoints
[lf,rt] = getBnds();
if( lf==-1 && (any(lockLf==[0 -1])||any(lockRt==[0 -1]))), return; end
if( v==1 && e<lf && any(lockLf==[0 -1]) ), return; end
if( v==1 && s>rt && any(lockRt==[0 -1]) ), return; end
if( v==0 && s==lf && any(lockLf==[0 1]) ), return; end
if( v==0 && e==rt && any(lockRt==[0 1]) ), return; end
% update rng, redraw and callback
rng0=rng; rng(s:e)=v; draw();
if(~isempty(rangeChnCb)), rangeChnCb(rng0,rng); end
end
function draw()
% construct I based on hRng and set image
h=size(Is,1); w=size(Is,2); I=zeros(h,w*n,3);
if(length(en)>1 || en==1), rng1=rng; else rng1=zeros(1,n); end
for i=1:n, I(:,(1:w)+(i-1)*w,:)=Is(:,:,:,rng1(i)+1); end
if(ishandle(hImg)), set(hImg,'CData',I); end
end
function setRng( rng1 )
assert( length(rng1)==n && all(rng1==0 | rng1==1) );
if(any(rng~=rng1)), rng=rng1; draw(); end
end
function [lf,rt] = getBnds( rng1 )
if(nargin==0 || isempty(rng1)); rng1=rng; end
[~,lf]=max(rng1); [v,rt]=max(fliplr(rng1)); rt=n-rt+1;
if(v==0); lf=-1; rt=-1; end;
end
function setLock( v, flag )
if( flag==0 ), lockCen = v; else
if(isempty(v)), v=-2; end
assert( any(v==[-2 -1 0 1]) );
if(flag==1), lockRt=v; else lockLf=v; end
end
end
function delete1()
if(ishandle(hAx)), delete(hAx); end; hAx=[];
if(ishandle(hImg)), delete(hImg); end; hImg=[];
end
function enable( en1 ), en=en1; draw(); end
function setRngChnCb( f ), rangeChnCb = f; end
end
|
github
|
devaib/MXNet-SSD-master
|
dbEval.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/dbEval.m
| 18,321 |
utf_8
|
4051885de2cf9cce93fbb6a12d8f561a
|
function dbEval
% Evaluate and plot all pedestrian detection results.
%
% Set parameters by altering this function directly.
%
% USAGE
% dbEval
%
% INPUTS
%
% OUTPUTS
%
% EXAMPLE
% dbEval
%
% See also bbGt, dbInfo
%
% Caltech Pedestrian Dataset Version 3.2.1
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% List of experiment settings: { name, hr, vr, ar, overlap, filter }
% name - experiment name
% hr - height range to test
% vr - visibility range to test
% ar - aspect ratio range to test
% overlap - overlap threshold for evaluation
% filter - expanded filtering (see 3.3 in PAMI11)
exps = {
'Reasonable', [50 inf], [.65 inf], 0, .5, 1.25
'All', [20 inf], [.2 inf], 0, .5, 1.25
'Scale=large', [100 inf], [.2 inf], 0, .5, 1.25
'Scale=near', [80 inf], [.2 inf], 0, .5, 1.25
'Scale=medium', [30 80], [.2 inf], 0, .5, 1.25
'Scale=far', [20 30], [.2 inf], 0, .5, 1.25
'Occ=none', [50 inf], [inf inf], 0, .5, 1.25
'Occ=partial', [50 inf], [.65 1], 0, .5, 1.25
'Occ=heavy', [50 inf], [.2 .65], 0, .5, 1.25
'Ar=all', [50 inf], [inf inf], 0, .5, 1.25
'Ar=typical', [50 inf], [inf inf], .1, .5, 1.25
'Ar=atypical', [50 inf], [inf inf], -.1, .5, 1.25
'Overlap=25', [50 inf], [.65 inf], 0, .25, 1.25
'Overlap=50', [50 inf], [.65 inf], 0, .50, 1.25
'Overlap=75', [50 inf], [.65 inf], 0, .75, 1.25
'Expand=100', [50 inf], [.65 inf], 0, .5, 1.00
'Expand=125', [50 inf], [.65 inf], 0, .5, 1.25
'Expand=150', [50 inf], [.65 inf], 0, .5, 1.50 };
exps=cell2struct(exps',{'name','hr','vr','ar','overlap','filter'});
exps_ahead= 2;
% List of algorithms: { name, resize, color, style }
% name - algorithm name (defines data location)
% resize - if true rescale height of each box by 100/128
% color - algorithm plot color
% style - algorithm plot linestyle
n=1000; clrs=zeros(n,3);
for i=1:n, clrs(i,:)=max(.3,mod([78 121 42]*(i+1),255)/255); end
algs = {
'ResNet50-Cal-new', 0, clrs(92, :), '-'
'ResNet50-Cal-new-customized', 0, clrs(91, :), '-'
'ResNet50-Cal-new-two-stream', 0, clrs(90, :), '-'
'resnet50', 0, clrs(93, :), '-'
% 'ResNet50-Two-Stream-New', 0, clrs(81, :), '-'
% 'ResNet50-Two-Stream-720', 0, clrs(80, :), '-'
% 'ResNet50-Two-Stream-600', 0, clrs(77, :), '-'
% 'ResNet50-two-stream', 0, clrs(74,:), '-'
% 'ResNet50-Customized-600', 0, clrs(70,:), '-'
% 'ResNet50-600', 0, clrs(69,:), '-'
% 'ACF++', 0, clrs(68,:), '--'
% 'HOG', 1, clrs(2,:), '--'
% 'SpatialPooling', 0, clrs(40,:), '-'
% 'TA-CNN', 0, clrs(48,:), '--'
% 'DeepParts', 0, clrs(50,:), '--'
% 'Checkerboards', 0, clrs(53,:), '--'
% 'CCF', 0, clrs(54,:), '--'
% 'CCF+CF', 0, clrs(54,:), '-'
% 'CompACT-Deep', 0, clrs(55,:), '--'
% 'RPN+BF', 0, clrs(58,:), '-'
};
algs=cell2struct(algs',{'name','resize','color','style'});
% List of database names
dataNames = {'UsaTest','UsaTrain','InriaTest',...
'TudBrussels','ETH','Daimler','Japan'};
% select databases, experiments and algorithms for evaluation
dataNames = dataNames(1); % select one or more databases for evaluation
exps = exps(exps_ahead); % select one or more experiment for evaluation
algs = algs(:); % select one or more algorithms for evaluation
% remaining parameters and constants
aspectRatio = .41; % default aspect ratio for all bbs
bnds = [5 5 635 475]; % discard bbs outside this pixel range
plotRoc = 1; % if true plot ROC else PR curves
plotAlg = 0; % if true one plot per alg else one plot per exp
plotNum = 20; % only show best plotNum curves (and VJ and HOG)
samples = 10.^(-2:.25:0); % samples for computing area under the curve
lims = [2e-4 50 .035 1]; % axis limits for ROC plots
bbsShow = 0; % if true displays sample bbs for each alg/exp
bbsType = 'fp'; % type of bbs to display (fp/tp/fn/dt)
algs0=algs; bnds0=bnds;
for d=1:length(dataNames), dataName=dataNames{d};
% select algorithms with results for current dataset
[~,set]=dbInfo(dataName); set=['/set' int2str2(set(1),2)];
names={algs0.name}; n=length(names); keep=false(1,n);
for i=1:n, keep(i)=exist([dbInfo '/res/' names{i} set],'dir'); end
algs=algs0(keep);
% handle special database specific cases
if(any(strcmp(dataName,{'InriaTest','TudBrussels','ETH'})))
bnds=[-inf -inf inf inf]; else bnds=bnds0; end
if(strcmp(dataName,'InriaTest'))
i=find(strcmp({algs.name},'FeatSynth'));
if(~isempty(i)), algs(i).resize=1; end;
end
% name for all plots (and also temp directory for results)
plotName=[fileparts(mfilename('fullpath')) '/results/' dataName];
if(~exist(plotName,'dir')), mkdir(plotName); end
% load detections and ground truth and evaluate
dts = loadDt( algs, plotName, aspectRatio );
gts = loadGt( exps, plotName, aspectRatio, bnds );
res = evalAlgs( plotName, algs, exps, gts, dts );
% plot curves and bbs
plotExps( res, plotRoc, plotAlg, plotNum, plotName, ...
samples, lims, reshape([algs.color]',3,[])', {algs.style} );
plotBbs( res, plotName, bbsShow, bbsType );
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = evalAlgs( plotName, algs, exps, gts, dts )
% Evaluate every algorithm on each experiment
%
% OUTPUTS
% res - nGt x nDt cell of all evaluations, each with fields
% .stra - string identifying algorithm
% .stre - string identifying experiment
% .gtr - [n x 1] gt result bbs for each frame [x y w h match]
% .dtr - [n x 1] dt result bbs for each frame [x y w h score match]
fprintf('Evaluating: %s\n',plotName); nGt=length(gts); nDt=length(dts);
res=repmat(struct('stra',[],'stre',[],'gtr',[],'dtr',[]),nGt,nDt);
for g=1:nGt
for d=1:nDt
gt=gts{g}; dt=dts{d}; n=length(gt); assert(length(dt)==n);
stra=algs(d).name; stre=exps(g).name;
fName = [plotName '/ev-' [stre '-' stra] '.mat'];
if(exist(fName,'file')), R=load(fName); res(g,d)=R.R; continue; end
fprintf('\tExp %i/%i, Alg %i/%i: %s/%s\n',g,nGt,d,nDt,stre,stra);
hr = exps(g).hr.*[1/exps(g).filter exps(g).filter];
for f=1:n, bb=dt{f}; dt{f}=bb(bb(:,4)>=hr(1) & bb(:,4)<hr(2),:); end
[gtr,dtr] = bbGt('evalRes',gt,dt,exps(g).overlap);
R=struct('stra',stra,'stre',stre,'gtr',{gtr},'dtr',{dtr});
res(g,d)=R; %save(fName,'R');
end
end
end
function plotExps( res, plotRoc, plotAlg, plotNum, plotName, ...
samples, lims, colors, styles )
% Plot all ROC or PR curves.
%
% INPUTS
% res - output of evalAlgs
% plotRoc - if true plot ROC else PR curves
% plotAlg - if true one plot per alg else one plot per exp
% plotNum - only show best plotNum curves (and VJ and HOG)
% plotName - filename for saving plots
% samples - samples for computing area under the curve
% lims - axis limits for ROC plots
% colors - algorithm plot colors
% styles - algorithm plot linestyles
% Compute (xs,ys) and score (area under the curve) for every exp/alg
[nGt,nDt]=size(res); xs=cell(nGt,nDt); ys=xs; scores=zeros(nGt,nDt);
for g=1:nGt
for d=1:nDt
[xs{g,d},ys{g,d},~,score] = ...
bbGt('compRoc',res(g,d).gtr,res(g,d).dtr,plotRoc,samples);
if(plotRoc), ys{g,d}=1-ys{g,d}; score=1-score; end
if(plotRoc), score=exp(mean(log(score))); else score=mean(score); end
scores(g,d)=score;
end
end
% Generate plots
if( plotRoc ), fName=[plotName 'Roc']; else fName=[plotName 'Pr']; end
stra={res(1,:).stra}; stre={res(:,1).stre}; scores1=round(scores*100);
if( plotAlg ), nPlots=nDt; else nPlots=nGt; end; plotNum=min(plotNum,nDt);
for p=1:nPlots
% prepare xs1,ys1,lgd1,colors1,styles1,fName1 according to plot type
if( plotAlg )
xs1=xs(:,p); ys1=ys(:,p); fName1=[fName stra{p}]; lgd1=stre;
for g=1:nGt, lgd1{g}=sprintf('%2i%% %s',scores1(g,p),stre{g}); end
colors1=uniqueColors(1,max(10,nGt)); styles1=repmat({'-','--'},1,nGt);
else
xs1=xs(p,:); ys1=ys(p,:); fName1=[fName stre{p}]; lgd1=stra;
for d=1:nDt, lgd1{d}=sprintf('%2i%% %s',scores1(p,d),stra{d}); end
kp=[find(strcmp(stra,'VJ')) find(strcmp(stra,'HOG')) 1 1];
[~,ord]=sort(scores(p,:)); kp=ord==kp(1)|ord==kp(2);
j=find(cumsum(~kp)>=plotNum-2); kp(1:j(1))=1; ord=fliplr(ord(kp));
xs1=xs1(ord); ys1=ys1(ord); lgd1=lgd1(ord); colors1=colors(ord,:);
styles1=styles(ord); f=fopen([fName1 '.txt'],'w');
for d=1:nDt, fprintf(f,'%s %f\n',stra{d},scores(p,d)); end; fclose(f);
end
% plot curves and finalize display
figure(1); clf; grid on; hold on; n=length(xs1); h=zeros(1,n);
for i=1:n, h(i)=plot(xs1{i},ys1{i},'Color',colors1(i,:),...
'LineStyle',styles1{i},'LineWidth',2);
end
if( plotRoc )
yt=[.05 .1:.1:.5 .64 .8]; ytStr=int2str2(yt*100,2);
for i=1:length(yt), ytStr{i}=['.' ytStr{i}]; end
set(gca,'XScale','log','YScale','log',...
'YTick',[yt 1],'YTickLabel',[ytStr '1'],...
'XMinorGrid','off','XMinorTic','off',...
'YMinorGrid','off','YMinorTic','off');
xlabel('false positives per image','FontSize',14);
ylabel('miss rate','FontSize',14); axis(lims);
else
x=1; for i=1:n, x=max(x,max(xs1{i})); end, x=min(x-mod(x,.1),1.0);
y=.8; for i=1:n, y=min(y,min(ys1{i})); end, y=max(y-mod(y,.1),.01);
xlim([0, x]); ylim([y, 1]); set(gca,'xtick',0:.1:1);
xlabel('Recall','FontSize',14); ylabel('Precision','FontSize',14);
end
if(~isempty(lgd1)), legend(h,lgd1,'Location','sw','FontSize',10); end
% save figure to disk (uncomment pdfcrop commands to automatically crop)
[o,~]=system('pdfcrop'); if(o==127), setenv('PATH',...
[getenv('PATH') ':/Library/TeX/texbin/:/usr/local/bin/']); end
% savefig(fName1,1,'pdf','-r300','-fonts'); close(1); f1=[fName1 '.pdf'];
% system(['pdfcrop -margins ''-30 -20 -50 -10 '' ' f1 ' ' f1]);
savefig(fName1,1,'jpeg','-r300','-fonts'); f1=[fName1 '.jpg'];
end
end
function plotBbs( res, plotName, pPage, type )
% This function plots sample fp/tp/fn bbs for given algs/exps
if(pPage==0), return; end; [nGt,nDt]=size(res);
% construct set/vid/frame index for each image
[~,setIds,vidIds,skip]=dbInfo;
k=length(res(1).gtr); is=zeros(k,3); k=0;
for s=1:length(setIds)
for v=1:length(vidIds{s})
A=loadVbb(s,v); s1=setIds(s); v1=vidIds{s}(v);
for f=skip-1:skip:A.nFrame-1, k=k+1; is(k,:)=[s1 v1 f]; end
end
end
for g=1:nGt
for d=1:nDt
% augment each bb with set/video/frame index and flatten
dtr=res(g,d).dtr; gtr=res(g,d).gtr;
for i=1:k
dtr{i}(:,7)=is(i,1); dtr{i}(:,8)=is(i,2); dtr{i}(:,9)=is(i,3);
gtr{i}(:,6)=is(i,1); gtr{i}(:,7)=is(i,2); gtr{i}(:,8)=is(i,3);
dtr{i}=dtr{i}'; gtr{i}=gtr{i}';
end
dtr=[dtr{:}]'; dtr=dtr(dtr(:,6)~=-1,:);
gtr=[gtr{:}]'; gtr=gtr(gtr(:,5)~=-1,:);
% get bb, ind, bbo, and indo according to type
if( strcmp(type,'fn') )
keep=gtr(:,5)==0; ord=randperm(sum(keep));
bbCol='r'; bboCol='y'; bbLst='-'; bboLst='--';
bb=gtr(:,1:4); ind=gtr(:,6:8); bbo=dtr(:,1:6); indo=dtr(:,7:9);
else
switch type
case 'dt', bbCol='y'; keep=dtr(:,6)>=0;
case 'fp', bbCol='r'; keep=dtr(:,6)==0;
case 'tp', bbCol='y'; keep=dtr(:,6)==1;
end
[~,ord]=sort(dtr(keep,5),'descend');
bboCol='g'; bbLst='--'; bboLst='-';
bb=dtr(:,1:6); ind=dtr(:,7:9); bbo=gtr(:,1:4); indo=gtr(:,6:8);
end
% prepare and display
n=sum(keep); bbo1=cell(1,n); O=ones(1,size(indo,1));
ind=ind(keep,:); bb=bb(keep,:); ind=ind(ord,:); bb=bb(ord,:);
for f=1:n, bbo1{f}=bbo(all(indo==ind(O*f,:),2),:); end
f=[plotName res(g,d).stre res(g,d).stra '-' type];
plotBbSheet( bb, ind, bbo1,'fName',f,'pPage',pPage,'bbCol',bbCol,...
'bbLst',bbLst,'bboCol',bboCol,'bboLst',bboLst );
end
end
end
function plotBbSheet( bb, ind, bbo, varargin )
% Draw sheet of bbs.
%
% USAGE
% plotBbSheet( R, varargin )
%
% INPUTS
% bb - [nx4] bbs to display
% ind - [nx3] the set/video/image number for each bb
% bbo - {nx1} cell of other bbs for each image (optional)
% varargin - prm struct or name/value list w following fields:
% .fName - ['REQ'] base file to save to
% .pPage - [1] num pages
% .mRows - [5] num rows / page
% .nCols - [9] num cols / page
% .scale - [2] size of image region to crop relative to bb
% .siz0 - [100 50] target size of each bb
% .pad - [4] amount of space between cells
% .bbCol - ['g'] bb color
% .bbLst - ['-'] bb LineStyle
% .bboCol - ['r'] bbo color
% .bboLst - ['--'] bbo LineStyle
dfs={'fName','REQ', 'pPage',1, 'mRows',5, 'nCols',9, 'scale',1.5, ...
'siz0',[100 50], 'pad',8, 'bbCol','g', 'bbLst','-', ...
'bboCol','r', 'bboLst','--' };
[fName,pPage,mRows,nCols,scale,siz0,pad,bbCol,bbLst, ...
bboCol,bboLst] = getPrmDflt(varargin,dfs);
n=size(ind,1); indAll=ind; bbAll=bb; bboAll=bbo;
for page=1:min(pPage,ceil(n/mRows/nCols))
Is = zeros(siz0(1)*scale,siz0(2)*scale,3,mRows*nCols,'uint8');
bbN=[]; bboN=[]; labels=repmat({''},1,mRows*nCols);
for f=1:mRows*nCols
% get fp bb (bb), double size (bb2), and other bbs (bbo)
f0=f+(page-1)*mRows*nCols; if(f0>n), break, end
[col,row]=ind2sub([nCols mRows],f);
ind=indAll(f0,:); bb=bbAll(f0,:); bbo=bboAll{f0};
hr=siz0(1)/bb(4); wr=siz0(2)/bb(3); mr=min(hr,wr);
bb2 = round(bbApply('resize',bb,scale*hr/mr,scale*wr/mr));
bbo=bbApply('intersect',bbo,bb2); bbo=bbo(bbApply('area',bbo)>0,:);
labels{f}=sprintf('%i/%i/%i',ind(1),ind(2),ind(3));
% normalize bb and bbo for siz0*scale region, then shift
bb=bbApply('shift',bb,bb2(1),bb2(2)); bb(:,1:4)=bb(:,1:4)*mr;
bbo=bbApply('shift',bbo,bb2(1),bb2(2)); bbo(:,1:4)=bbo(:,1:4)*mr;
xdel=-pad*scale-(siz0(2)+pad*2)*scale*(col-1);
ydel=-pad*scale-(siz0(1)+pad*2)*scale*(row-1);
bb=bbApply('shift',bb,xdel,ydel); bbN=[bbN; bb]; %#ok<AGROW>
bbo=bbApply('shift',bbo,xdel,ydel); bboN=[bboN; bbo]; %#ok<AGROW>
% load and crop image region
sr=seqIo(sprintf('%s/videos/set%02i/V%03i',dbInfo,ind(1),ind(2)),'r');
sr.seek(ind(3)); I=sr.getframe(); sr.close();
I=bbApply('crop',I,bb2,'replicate');
I=uint8(imResample(double(I{1}),siz0*scale));
Is(:,:,:,f)=I;
end
% now plot all and save
prm=struct('hasChn',1,'padAmt',pad*2*scale,'padEl',0,'mm',mRows,...
'showLines',0,'labels',{labels});
h=figureResized(.9,1); clf; montage2(Is,prm); hold on;
bbApply('draw',bbN,bbCol,2,bbLst); bbApply('draw',bboN,bboCol,2,bboLst);
savefig([fName int2str2(page-1,2)],h,'png','-r200','-fonts'); close(h);
%if(0), save([fName int2str2(page-1,2) '.mat'],'Is'); end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function A = loadVbb( s, v )
% Load given annotation (caches AS for speed).
persistent AS pth sIds vIds; [pth1,sIds1,vIds1]=dbInfo;
if(~strcmp(pth,pth1) || ~isequal(sIds,sIds1) || ~isequal(vIds,vIds1))
[pth,sIds,vIds]=dbInfo; AS=cell(length(sIds),1e3); end
A=AS{s,v}; if(~isempty(A)), return; end
fName=@(s,v) sprintf('%s/annotations/set%02i/V%03i',pth,s,v);
A=vbb('vbbLoad',fName(sIds(s),vIds{s}(v))); AS{s,v}=A;
end
function gts = loadGt( exps, plotName, aspectRatio, bnds )
% Load ground truth of all experiments for all frames.
fprintf('Loading ground truth: %s\n',plotName);
nExp=length(exps); gts=cell(1,nExp);
[~,setIds,vidIds,skip] = dbInfo;
for i=1:nExp
gName = [plotName '/gt-' exps(i).name '.mat'];
if(exist(gName,'file')), gt=load(gName); gts{i}=gt.gt; continue; end
fprintf('\tExperiment #%d: %s\n', i, exps(i).name);
gt=cell(1,100000); k=0; lbls={'person','person?','people','ignore'};
filterGt = @(lbl,bb,bbv) filterGtFun(lbl,bb,bbv,...
exps(i).hr,exps(i).vr,exps(i).ar,bnds,aspectRatio);
for s=1:length(setIds)
for v=1:length(vidIds{s})
A = loadVbb(s,v);
for f=skip-1:skip:A.nFrame-1
bb = vbb('frameAnn',A,f+1,lbls,filterGt); ids=bb(:,5)~=1;
bb(ids,:)=bbApply('resize',bb(ids,:),1,0,aspectRatio);
k=k+1; gt{k}=bb;
end
end
end
gt=gt(1:k); gts{i}=gt; save(gName,'gt','-v6');
end
function p = filterGtFun( lbl, bb, bbv, hr, vr, ar, bnds, aspectRatio )
p=strcmp(lbl,'person'); h=bb(4); p=p & (h>=hr(1) & h<hr(2));
if(all(bbv==0)), vf=inf; else vf=bbv(3).*bbv(4)./(bb(3)*bb(4)); end
p=p & vf>=vr(1) & vf<=vr(2);
if(ar~=0), p=p & sign(ar)*abs(bb(3)./bb(4)-aspectRatio)<ar; end
p = p & bb(1)>=bnds(1) & (bb(1)+bb(3)<=bnds(3));
p = p & bb(2)>=bnds(2) & (bb(2)+bb(4)<=bnds(4));
end
end
function dts = loadDt( algs, plotName, aspectRatio )
% Load detections of all algorithm for all frames.
fprintf('Loading detections: %s\n',plotName);
nAlg=length(algs); dts=cell(1,nAlg);
[~,setIds,vidIds,skip] = dbInfo;
for i=1:nAlg
aName = [plotName '/dt-' algs(i).name '.mat'];
if(exist(aName,'file')), dt=load(aName); dts{i}=dt.dt; continue; end
fprintf('\tAlgorithm #%d: %s\n', i, algs(i).name);
dt=cell(1,100000); k=0; aDir=[dbInfo '/res/' algs(i).name];
if(algs(i).resize), resize=100/128; else resize=1; end
for s=1:length(setIds), s1=setIds(s);
for v=1:length(vidIds{s}), v1=vidIds{s}(v);
A=loadVbb(s,v); frames=skip-1:skip:A.nFrame-1;
vName=sprintf('%s/set%02d/V%03d',aDir,s1,v1);
if(~exist([vName '.txt'],'file'))
% consolidate bbs for video into single text file
bbs=cell(length(frames),1);
for f=1:length(frames)
fName = sprintf('%s/I%05d.txt',vName,frames(f));
if(~exist(fName,'file')), error(['file not found:' fName]); end
bb=load(fName,'-ascii'); if(isempty(bb)), bb=zeros(0,5); end
if(size(bb,2)~=5), error('incorrect dimensions'); end
bbs{f}=[ones(size(bb,1),1)*(frames(f)+1) bb];
end
for f=frames, delete(sprintf('%s/I%05d.txt',vName,f)); end
bbs=cell2mat(bbs); dlmwrite([vName '.txt'],bbs); rmdir(vName,'s');
end
bbs=load([vName '.txt'],'-ascii');
for f=frames, bb=bbs(bbs(:,1)==f+1,2:6);
bb=bbApply('resize',bb,resize,0,aspectRatio); k=k+1; dt{k}=bb;
end
end
end
dt=dt(1:k); dts{i}=dt; %save(aName,'dt','-v6');
end
end
|
github
|
devaib/MXNet-SSD-master
|
visualize_annotations.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/GT-visualization/visualize_annotations.m
| 5,112 |
utf_8
|
f6bec1dd622dcdfd3bd1e86b31b464ba
|
function visualize_annotations(path_to_seq_files, set_n, video_n)
% Shows standard caltech annotations and new annotations of ICCV 2015
% submission #1624.
%
% Arguments:
% path_to_seq_files path to the directory containing the set
% directories with the video frames in seq format
% set_n specify a specific set number to watch videos in
% that set
% video_n specify a specific video number to watch it
%
% check if arguments are correct
if nargin < 1 || ...
(nargin < 2 && ~exist(fullfile(path_to_seq_files, 'set00', 'V000.seq'), 'file'))
fprintf('\n\nERROR: You need to supply the path to the videos directory of the caltech data,\nwhich contains the caltech video frames.\n\n');
fprintf('You can download it at\n http:9\//www.vision.caltech.edu/Image_Datasets/CaltechPedestrians/datasets/USA/\n\n');
return;
end
load('caltech_layout.mat', 'caltech_layout');
if nargin >= 2 && ~any(caltech_layout(:,1) == set_n)
fprintf('\n\nERROR: set %d does not exist, caltech has only set %d - %d (including)\n\n', ...
set_n, min(caltech_layout(:,1)), max(caltech_layout(:,1)));
end
if nargin >= 3
set_videos = caltech_layout(caltech_layout(:,1) == set_n,2);
if ~any(set_videos == video_n)
fprintf('\n\nERROR: set %d does not have video %d, set %d has only video %d - %d (including)\n\n', ...
set_n, video_n, set_n, min(set_videos), max(set_videos));
end
end
% add Piotrs toolbox
addpath(genpath('toolbox'));
if nargin < 2
% if no sets and videos are provided, let's show all of them
fprintf('showing caltech videos, starting with training set\n');
fprintf('If you want to have a look at specific sets or videos, you can\nspecify set ids and video ids as arguments to the function\n');
fprintf('example: visualize_annotations(''path_to_seqs'', 6);\n');
fprintf('Training sets: 0 - 5, test sets: 6 - 10\n');
videos_to_watch = caltech_layout;
elseif nargin < 3
% set specified but no video, let's show the whole set
fprintf('showing set %d, all videos\n', set_n);
videos_to_watch = caltech_layout(caltech_layout(:,1) == set_n,:);
else
videos_to_watch = [set_n, video_n];
end
standard = load('gt-standard.mat', 'gt');
new = load('gt-new.mat', 'gt');
fprintf('\n\nStarting to show annotations frame by frame. Please press a button\nto go to the next frame. Press Ctrl-C in the matlab window to stop.\n\n');
fh = figure;
% finishup = onCleanup(@() close(fh));
for i = 1:size(videos_to_watch,1)
set_id = videos_to_watch(i,1);
video_id = videos_to_watch(i,2);
seq_file = fullfile(path_to_seq_files, sprintf('set%02d', set_id), ...
sprintf('V%03d.seq', video_id));
fprintf('set %02d, video %03d: %s\n', set_id, video_id, seq_file);
if ~exist(fullfile(path_to_seq_files, 'set00', 'V000.seq'), 'file')
fprintf('\n\nERROR: Could not find seq file. Either the path_to_seq_files is wrong or you''re missing the video files.\n\n');
fprintf('You can download them at\n http://www.vision.caltech.edu/Image_Datasets/CaltechPedestrians/datasets/USA/\n\n');
return;
end
std_video_gt = get_video_gt(standard.gt, set_id, video_id, caltech_layout);
new_video_gt = get_video_gt(new.gt, set_id, video_id, caltech_layout);
show_video(fh, seq_file, std_video_gt, new_video_gt);
end
fprintf('\ndone, all is well\n');
end
function video_gt = get_video_gt(gt, set_id, video_id, caltech_layout)
idx = find((caltech_layout(:,1) == set_id) & (caltech_layout(:,2) == video_id));
assert(numel(idx) == 1);
first = sum(caltech_layout(1:(idx-1),3)) + 1;
num = caltech_layout(idx,3);
video_gt = gt(first:(first+num-1));
end
function show_video(fh, seq_file, std_gt, new_gt)
colors = [228,26,28
55,126,184
77,175,74
152,78,163
255,127,0
166,86,40]/255;
sr = seqIo(seq_file, 'reader');
finishup = onCleanup(@() sr.close());
i = 0;
delta = 30;
while 1
i = i + 1;
frame = delta * i - 1;
success = sr.seek(frame);
if success == 0
break;
end
[im, ~] = sr.getframe();
if isempty(im)
break;
end
figure(fh);
subplot(1,2,1);
imshow(im);
title('standard ground truth');
fa = std_gt{i};
anno = fa(fa(:,5)==0,:);
ignore = fa(fa(:,5)==1,:);
draw_boxes(anno, colors(2,:), '-');
draw_boxes(ignore, colors(2,:), '--');
subplot(1,2,2);
imshow(im);
title('new ground truth');
fa = new_gt{i};
anno = fa(fa(:,5)==0,:);
ignore = fa(fa(:,5)==1,:);
draw_boxes(anno, colors(3,:), '-');
draw_boxes(ignore, colors(3,:), '--');
pause;
end
end
function draw_boxes(boxes, color, style)
if nargin < 3
style = '-';
end
boxes(:,1:2) = boxes(:,1:2)+1; % matlab is 1-based
for i = 1:size(boxes, 1)
rectangle('Position', boxes(i,1:4), 'EdgeColor', color, ...
'LineWidth', 2, ...
'LineStyle', style);
end
end
|
github
|
devaib/MXNet-SSD-master
|
imagesAlign.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/GT-visualization/toolbox/videos/imagesAlign.m
| 8,167 |
utf_8
|
d125eb5beb502d940be5bd145521f34b
|
function [H,Ip] = imagesAlign( I, Iref, varargin )
% Fast and robust estimation of homography relating two images.
%
% The algorithm for image alignment is a simple but effective variant of
% the inverse compositional algorithm. For a thorough overview, see:
% "Lucas-kanade 20 years on A unifying framework,"
% S. Baker and I. Matthews. IJCV 2004.
% The implementation is optimized and can easily run at 20-30 fps.
%
% type may take on the following values:
% 'translation' - translation only
% 'rigid' - translation and rotation
% 'similarity' - translation, rotation and scale
% 'affine' - 6 parameter affine transform
% 'rotation' - pure rotation (about x, y and z)
% 'projective' - full 8 parameter homography
% Alternatively, type may be a vector of ids between 1 and 8, specifying
% exactly the types of transforms allowed. The ids correspond, to: 1:
% translate-x, 2: translate-y, 3: uniform scale, 4: shear, 5: non-uniform
% scale, 6: rotate-z, 7: rotate-x, 8: rotate-y. For example, to specify
% translation use type=[1,2]. If the transforms don't form a group, the
% returned homography may have more degrees of freedom than expected.
%
% Parameters (in rough order of importance): [resample] controls image
% downsampling prior to computing H. Runtime is proportional to area, so
% using resample<1 can dramatically speed up alignment, and in general not
% degrade performance much. [sig] controls image smoothing, sig=2 gives
% good performance, setting sig too low causes loss of information and too
% high will violate the linearity assumption. [epsilon] defines the
% stopping criteria, use to adjust performance versus speed tradeoff.
% [lambda] is a regularization term that causes small transforms to be
% favored, in general any small non-zero setting of lambda works well.
% [outThr] is a threshold beyond which pixels are considered outliers, be
% careful not to set too low. [minArea] determines coarsest scale beyond
% which the image is not downsampled (should not be set too low). [H0] can
% be used to specify an initial alignment. Use [show] to display results.
%
% USAGE
% [H,Ip] = imagesAlign( I, Iref, varargin )
%
% INPUTS
% I - transformed version of I
% Iref - reference grayscale double image
% varargin - additional params (struct or name/value pairs)
% .type - ['projective'] see above for options
% .resample - [1] image resampling prior to homography estimation
% .sig - [2] amount of Gaussian spatial smoothing to apply
% .epsilon - [1e-3] stopping criteria (min change in error)
% .lambda - [1e-6] regularization term favoring small transforms
% .outThr - [inf] outlier threshold
% .minArea - [4096] minimum image area in coarse to fine search
% .H0 - [eye(3)] optional initial homography estimate
% .show - [0] optionally display results in figure show
%
% OUTPUTS
% H - estimated homography to transform I into Iref
% Ip - tranformed version of I (slow to compute)
%
% EXAMPLE
% Iref = double(imread('cameraman.tif'))/255;
% H0 = [eye(2)+randn(2)*.1 randn(2,1)*10; randn(1,2)*1e-3 1];
% I = imtransform2(Iref,H0^-1,'pad','replicate');
% o=50; P=ones(o)*1; I(150:149+o,150:149+o)=P;
% prmAlign={'outThr',.1,'resample',.5,'type',1:8,'show'};
% [H,Ip]=imagesAlign(I,Iref,prmAlign{:},1);
% tic, for i=1:30, H=imagesAlign(I,Iref,prmAlign{:},0); end;
% t=toc; fprintf('average fps: %f\n',30/t)
%
% See also imTransform2
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get parameters
dfs={'type','projective','resample',1,'sig',2,'epsilon',1e-3,...
'lambda',1e-6,'outThr',inf,'minArea',4096,'H0',eye(3),'show',0};
[type,resample,sig,epsilon,lambda,outThr,minArea,H0,show] = ...
getPrmDflt(varargin,dfs,1);
filt = filterGauss(2*ceil(sig*2.5)+1,[],sig^2);
% determine type of transformation to recover
if(isnumeric(type)), assert(length(type)<=8); else
id=find(strcmpi(type,{'translation','rigid','similarity','affine',...
'rotation','projective'})); msgId='piotr:imagesAlign';
if(isempty(id)), error(msgId,'unknown type: %s',type); end
type={1:2,[1:2 6],[1:3 6],1:6,6:8,1:8}; type=type{id};
end; keep=zeros(1,8); keep(type)=1; keep=keep>0;
% compute image alignment (optionally resample first)
prm={keep,filt,epsilon,H0,minArea,outThr,lambda};
if( resample==1 ), H=imagesAlign1(I,Iref,prm); else
S=eye(3); S([1 5])=resample; H0=S*H0*S^-1; prm{4}=H0;
I1=imResample(I,resample); Iref1=imResample(Iref,resample);
H=imagesAlign1(I1,Iref1,prm); H=S^-1*H*S;
end
% optionally rectify I and display results (can be expensive)
if(nargout==1 && show==0), return; end
Ip = imtransform2(I,H,'pad','replicate');
if(show), figure(show); clf; s=@(i) subplot(2,3,i);
Is=[I Iref Ip]; ri=[min(Is(:)) max(Is(:))];
D0=abs(I-Iref); D1=abs(Ip-Iref); Ds=[D0 D1]; di=[min(Ds(:)) max(Ds(:))];
s(1); im(I,ri,0); s(2); im(Iref,ri,0); s(3); im(D0,di,0);
s(4); im(Ip,ri,0); s(5); im(Iref,ri,0); s(6); im(D1,di,0);
s(3); title('|I-Iref|'); s(6); title('|Ip-Iref|');
end
end
function H = imagesAlign1( I, Iref, prm )
% apply recursively if image large
[keep,filt,epsilon,H0,minArea,outThr,lambda]=deal(prm{:});
[h,w]=size(I); hc=mod(h,2); wc=mod(w,2);
if( w*h<minArea ), H=H0; else
I1=imResample(I(1:(h-hc),1:(w-wc)),.5);
Iref1=imResample(Iref(1:(h-hc),1:(w-wc)),.5);
S=eye(3); S([1 5])=2; H0=S^-1*H0*S; prm{4}=H0;
H=imagesAlign1(I1,Iref1,prm); H=S*H*S^-1;
end
% smooth images (pad first so dimensions unchanged)
O=ones(1,(length(filt)-1)/2); hs=[O 1:h h*O]; ws=[O 1:w w*O];
Iref=conv2(conv2(Iref(hs,ws),filt','valid'),filt,'valid');
I=conv2(conv2(I(hs,ws),filt','valid'),filt,'valid');
% pad images with nan so later can determine valid regions
hs=[1 1 1:h h h]; ws=[1 1 1:w w w]; I=I(hs,ws); Iref=Iref(hs,ws);
hs=[1:2 h+3:h+4]; I(hs,:)=nan; Iref(hs,:)=nan;
ws=[1:2 w+3:w+4]; I(:,ws)=nan; Iref(:,ws)=nan;
% convert weights hardcoded for 128x128 image to given image dims
wts=[1 1 1.0204 .03125 1.0313 0.0204 .00055516 .00055516];
s=sqrt(numel(Iref))/128;
wts=[wts(1:2) wts(3)^(1/s) wts(4)/s wts(5)^(1/s) wts(6)/s wts(7:8)/(s*s)];
% prepare subspace around Iref
[~,Hs]=ds2H(-ones(1,8),wts); Hs=Hs(:,:,keep); K=size(Hs,3);
[h,w]=size(Iref); Ts=zeros(h,w,K); k=0;
if(keep(1)), k=k+1; Ts(:,1:end-1,k)=Iref(:,2:end); end
if(keep(2)), k=k+1; Ts(1:end-1,:,k)=Iref(2:end,:); end
pTransf={'method','bilinear','pad','none','useCache'};
for i=k+1:K, Ts(:,:,i)=imtransform2(Iref,Hs(:,:,i),pTransf{:},1); end
Ds=Ts-Iref(:,:,ones(1,K)); Mref = ~any(isnan(Ds),3);
if(0), figure(10); montage2(Ds); end
Ds = reshape(Ds,[],size(Ds,3));
% iteratively project Ip onto subspace, storing transformation
lambda=lambda*w*h*eye(K); ds=zeros(1,8); err=inf;
for i=1:100
s=svd(H); if(s(3)<=1e-4*s(1)), H=eye(3); return; end
Ip=imtransform2(I,H,pTransf{:},0); dI=Ip-Iref; dI0=abs(dI);
M=Mref & ~isnan(Ip); M0=M; if(outThr<inf), M=M & dI0<outThr; end
M1=find(M); D=Ds(M1,:); ds1=(D'*D + lambda)^(-1)*(D'*dI(M1));
if(any(isnan(ds1))), ds1=zeros(K,1); end
ds(keep)=ds1; H1=ds2H(ds,wts); H=H*H1; H=H/H(9);
err0=err; err=dI0; err(~M0)=0; err=mean2(err); del=err0-err;
if(0), fprintf('i=%03i err=%e del=%e\n',i,err,del); end
if( del<epsilon ), break; end
end
end
function [H,Hs] = ds2H( ds, wts )
% compute homography from offsets ds
Hs=eye(3); Hs=Hs(:,:,ones(1,8));
Hs(2,3,1)=wts(1)*ds(1); % 1 x translation
Hs(1,3,2)=wts(2)*ds(2); % 2 y translation
Hs(1:2,1:2,3)=eye(2)*wts(3)^ds(3); % 3 scale
Hs(2,1,4)=wts(4)*ds(4); % 4 shear
Hs(1,1,5)=wts(5)^ds(5); % 5 scale non-uniform
ct=cos(wts(6)*ds(6)); st=sin(wts(6)*ds(6));
Hs(1:2,1:2,6)=[ct -st; st ct]; % 6 rotation about z
ct=cos(wts(7)*ds(7)); st=sin(wts(7)*ds(7));
Hs([1 3],[1 3],7)=[ct -st; st ct]; % 7 rotation about x
ct=cos(wts(8)*ds(8)); st=sin(wts(8)*ds(8));
Hs(2:3,2:3,8)=[ct -st; st ct]; % 8 rotation about y
H=eye(3); for i=1:8, H=Hs(:,:,i)*H; end
end
|
github
|
devaib/MXNet-SSD-master
|
opticalFlow.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/GT-visualization/toolbox/videos/opticalFlow.m
| 7,385 |
utf_8
|
0fdca13d3caa4421fc488d0031e7838c
|
function [Vx,Vy,reliab] = opticalFlow( I1, I2, varargin )
% Coarse-to-fine optical flow using Lucas&Kanade or Horn&Schunck.
%
% Implemented 'type' of optical flow estimation:
% LK: http://en.wikipedia.org/wiki/Lucas-Kanade_method
% HS: http://en.wikipedia.org/wiki/Horn-Schunck_method
% SD: Simple block-based sum of absolute differences flow
% LK is a local, fast method (the implementation is fully vectorized).
% HS is a global, slower method (an SSE implementation is provided).
% SD is a simple but potentially expensive approach.
%
% Common parameters: 'smooth' determines smoothing prior to computing flow
% and can make flow estimation more robust. 'filt' determines amount of
% median filtering of the computed flow field which improves results but is
% costly. 'minScale' and 'maxScale' control image scales in the pyramid.
% Setting 'maxScale'<1 results in faster but lower quality results, e.g.
% maxScale=.5 makes flow computation about 4x faster. Method specific
% parameters: 'radius' controls window size (and smoothness of flow) for LK
% and SD. 'nBlock' determines number of blocks tested in each direction for
% SD, computation time is O(nBlock^2). For HS, 'alpha' controls tradeoff
% between data and smoothness term (and smoothness of flow) and 'nIter'
% determines number of gradient decent steps.
%
% USAGE
% [Vx,Vy,reliab] = opticalFlow( I1, I2, pFlow )
%
% INPUTS
% I1, I2 - input images to calculate flow between
% pFlow - parameters (struct or name/value pairs)
% .type - ['LK'] may be 'LK', 'HS' or 'SD'
% .smooth - [1] smoothing radius for triangle filter (may be 0)
% .filt - [0] median filtering radius for smoothing flow field
% .minScale - [1/64] minimum pyramid scale (must be a power of 2)
% .maxScale - [1] maximum pyramid scale (must be a power of 2)
% .radius - [10] integration radius for weighted window [LK/SD only]
% .nBlock - [5] number of tested blocks [SD only]
% .alpha - [1] smoothness constraint [HS only]
% .nIter - [250] number of iterations [HS only]
%
% OUTPUTS
% Vx, Vy - x,y components of flow [Vx>0->right, Vy>0->down]
% reliab - reliability of flow in given window
%
% EXAMPLE - compute LK flow on test images
% load opticalFlowTest;
% [Vx,Vy]=opticalFlow(I1,I2,'smooth',1,'radius',10,'type','LK');
% figure(1); im(I1); figure(2); im(I2);
% figure(3); im([Vx Vy]); colormap jet;
%
% EXAMPLE - rectify I1 to I2 using computed flow
% load opticalFlowTest;
% [Vx,Vy]=opticalFlow(I1,I2,'smooth',1,'radius',10,'type','LK');
% I1=imtransform2(I1,[],'vs',-Vx,'us',-Vy,'pad','replicate');
% figure(1); im(I1); figure(2); im(I2);
%
% EXAMPLE - compare LK/HS/SD flows
% load opticalFlowTest;
% prm={'smooth',1,'radius',10,'alpha',20,'nIter',250,'type'};
% tic, [Vx1,Vy1]=opticalFlow(I1,I2,prm{:},'LK'); toc
% tic, [Vx2,Vy2]=opticalFlow(I1,I2,prm{:},'HS'); toc
% tic, [Vx3,Vy3]=opticalFlow(I1,I2,prm{:},'SD','minScale',1); toc
% figure(1); im([Vx1 Vy1; Vx2 Vy2; Vx3 Vy3]); colormap jet;
%
% See also convTri, imtransform2, medfilt2
%
% Piotr's Computer Vision Matlab Toolbox Version NEW
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get default parameters and do error checking
dfs={ 'type','LK', 'smooth',1, 'filt',0, 'minScale',1/64, ...
'maxScale',1, 'radius',10, 'nBlock',5, 'alpha',1, 'nIter',250 };
[type,smooth,filt,minScale,maxScale,radius,nBlock,alpha,nIter] = ...
getPrmDflt(varargin,dfs,1);
assert(any(strcmp(type,{'LK','HS','SD'})));
if( ~ismatrix(I1) || ~ismatrix(I2) || any(size(I1)~=size(I2)) )
error('Input images must be 2D and have same dimensions.'); end
% run optical flow in coarse to fine fashion
if(~isa(I1,'single')), I1=single(I1); I2=single(I2); end
[h,w]=size(I1); nScales=max(1,floor(log2(min([h w 1/minScale])))+1);
for s=1:max(1,nScales + round(log2(maxScale)))
% get current scale and I1s and I2s at given scale
scale=2^(nScales-s); h1=round(h/scale); w1=round(w/scale);
if( scale==1 ), I1s=I1; I2s=I2; else
I1s=imResample(I1,[h1 w1]); I2s=imResample(I2,[h1 w1]); end
% initialize Vx,Vy or upsample from previous scale
if(s==1), Vx=zeros(h1,w1,'single'); Vy=Vx; else r=sqrt(h1*w1/numel(Vx));
Vx=imResample(Vx,[h1 w1])*r; Vy=imResample(Vy,[h1 w1])*r; end
% transform I2s according to current estimate of Vx and Vy
if(s>1), I2s=imtransform2(I2s,[],'pad','replciate','vs',Vx,'us',Vy); end
% smooth images
I1s=convTri(I1s,smooth); I2s=convTri(I2s,smooth);
% run optical flow on current scale
switch type
case 'LK', [Vx1,Vy1,reliab]=opticalFlowLk(I1s,I2s,radius);
case 'HS', [Vx1,Vy1,reliab]=opticalFlowHs(I1s,I2s,alpha,nIter);
case 'SD', [Vx1,Vy1,reliab]=opticalFlowSd(I1s,I2s,radius,nBlock,1);
end
Vx=Vx+Vx1; Vy=Vy+Vy1;
% finally median filter the resulting flow field
if(filt), Vx=medfilt2(Vx,[filt filt],'symmetric'); end
if(filt), Vy=medfilt2(Vy,[filt filt],'symmetric'); end
end
r=sqrt(h*w/numel(Vx));
if(r~=1), Vx=imResample(Vx,[h w])*r; Vy=imResample(Vy,[h w])*r; end
if(r~=1 && nargout==3), reliab=imResample(reliab,[h w]); end
end
function [Vx,Vy,reliab] = opticalFlowLk( I1, I2, radius )
% Compute elements of A'A and also of A'b
radius=min(radius,floor(min(size(I1,1),size(I1,2))/2)-1);
[Ix,Iy]=gradient2(I1); It=I2-I1; AAxy=convTri(Ix.*Iy,radius);
AAxx=convTri(Ix.^2,radius)+1e-5; ABxt=convTri(-Ix.*It,radius);
AAyy=convTri(Iy.^2,radius)+1e-5; AByt=convTri(-Iy.*It,radius);
% Find determinant and trace of A'A
AAdet=AAxx.*AAyy-AAxy.^2; AAdeti=1./AAdet;
AAdeti(isinf(AAdeti))=0; AAtr=AAxx+AAyy;
% Compute components of velocity vectors (A'A)^-1 * A'b
Vx = AAdeti .* ( AAyy.*ABxt - AAxy.*AByt);
Vy = AAdeti .* (-AAxy.*ABxt + AAxx.*AByt);
% Check for ill conditioned second moment matrices
reliab = 0.5*AAtr - 0.5*sqrt(AAtr.^2-4*AAdet);
end
function [Vx,Vy,reliab] = opticalFlowHs( I1, I2, alpha, nIter )
% compute derivatives (averaging over 2x2 neighborhoods)
pad = @(I,p) imPad(I,p,'replicate');
crop = @(I,c) I(1+c:end-c,1+c:end-c);
Ex = I1(:,2:end)-I1(:,1:end-1) + I2(:,2:end)-I2(:,1:end-1);
Ey = I1(2:end,:)-I1(1:end-1,:) + I2(2:end,:)-I2(1:end-1,:);
Ex = Ex/4; Ey = Ey/4; Et = (I2-I1)/4;
Ex = pad(Ex,[1 1 1 2]) + pad(Ex,[0 2 1 2]);
Ey = pad(Ey,[1 2 1 1]) + pad(Ey,[1 2 0 2]);
Et=pad(Et,[0 2 1 1])+pad(Et,[1 1 1 1])+pad(Et,[1 1 0 2])+pad(Et,[0 2 0 2]);
Z=1./(alpha*alpha + Ex.*Ex + Ey.*Ey); reliab=crop(Z,1);
% iterate updating Ux and Vx in each iter
if( 1 )
[Vx,Vy]=opticalFlowHsMex(Ex,Ey,Et,Z,nIter);
Vx=crop(Vx,1); Vy=crop(Vy,1);
else
Ex=crop(Ex,1); Ey=crop(Ey,1); Et=crop(Et,1); Z=crop(Z,1);
Vx=zeros(size(I1),'single'); Vy=Vx;
f=single([0 1 0; 1 0 1; 0 1 0])/4;
for i = 1:nIter
Mx=conv2(Vx,f,'same'); My=conv2(Vy,f,'same');
m=(Ex.*Mx+Ey.*My+Et).*Z; Vx=Mx-Ex.*m; Vy=My-Ey.*m;
end
end
end
function [Vx,Vy,reliab] = opticalFlowSd( I1, I2, radius, nBlock, step )
% simple block-based sum of absolute differences flow
[h,w]=size(I1); k=2*nBlock+1; k=k*k; D=zeros(h,w,k,'single'); k=1;
rng = @(x,w) max(1+x*step,1):min(w+x*step,w);
for x=-nBlock:nBlock, xs0=rng(x,w); xs1=rng(-x,w);
for y=-nBlock:nBlock, ys0=rng(y,h); ys1=rng(-y,h);
D(ys0,xs0,k)=abs(I1(ys0,xs0)-I2(ys1,xs1)); k=k+1;
end
end
D=convTri(D,radius); [reliab,D]=min(D,[],3);
k=2*nBlock+1; Vy=mod(D-1,k)+1; Vx=(D-Vy)/k+1;
Vy=(nBlock+1-Vy)*step; Vx=(nBlock+1-Vx)*step;
end
|
github
|
devaib/MXNet-SSD-master
|
seqWriterPlugin.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/GT-visualization/toolbox/videos/seqWriterPlugin.m
| 8,280 |
utf_8
|
597792f79fff08b8bb709313267c3860
|
function varargout = seqWriterPlugin( cmd, h, varargin )
% Plugin for seqIo and videoIO to allow writing of seq files.
%
% Do not call directly, use as plugin for seqIo or videoIO instead.
% The following is a list of commands available (swp=seqWriterPlugin):
% h=swp('open',h,fName,info) % Open a seq file for writing (h ignored).
% h=swp('close',h) % Close seq file (output h is -1).
% swp('addframe',h,I,[ts]) % Writes video frame (and timestamp).
% swp('addframeb',h,I,[ts]) % Writes video frame with no encoding.
% info = swp('getinfo',h) % Return struct with info about video.
%
% The following params must be specified in struct 'info' upon opening:
% width - frame width
% height - frame height
% fps - frames per second
% quality - [80] compression quality (0 to 100)
% codec - string representing codec, options include:
% 'monoraw'/'imageFormat100' - black/white uncompressed
% 'raw'/'imageFormat200' - color (BGR) uncompressed
% 'monojpg'/'imageFormat102' - black/white jpg compressed
% 'jpg'/'imageFormat201' - color jpg compressed
% 'monopng'/'imageFormat001' - black/white png compressed
% 'png'/'imageFormat002' - color png compressed
%
% USAGE
% varargout = seqWriterPlugin( cmd, h, varargin )
%
% INPUTS
% cmd - string indicating operation to perform
% h - unique identifier for open seq file
% varargin - additional options (vary according to cmd)
%
% OUTPUTS
% varargout - output (varies according to cmd)
%
% EXAMPLE
%
% See also SEQIO, SEQREADERPLUGIN
%
% Piotr's Computer Vision Matlab Toolbox Version 2.66
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% persistent variables to keep track of all loaded .seq files
persistent h1 hs fids infos tNms;
if(isempty(h1)), h1=int32(now); hs=int32([]); infos={}; tNms={}; end
nIn=nargin-2; in=varargin; o1=[]; cmd=lower(cmd);
% open seq file
if(strcmp(cmd,'open'))
chk(nIn,2); h=length(hs)+1; hs(h)=h1; varargout={h1}; h1=h1+1;
[pth,name]=fileparts(in{1}); if(isempty(pth)), pth='.'; end
fName=[pth filesep name];
[infos{h},fids(h),tNms{h}]=open(fName,in{2}); return;
end
% Get the handle for this instance
[v,h]=ismember(h,hs); if(~v), error('Invalid load plugin handle'); end
fid=fids(h); info=infos{h}; tNm=tNms{h};
% close seq file
if(strcmp(cmd,'close'))
writeHeader(fid,info);
chk(nIn,0); varargout={-1}; fclose(fid); kp=[1:h-1 h+1:length(hs)];
hs=hs(kp); fids=fids(kp); infos=infos(kp);
tNms=tNms(kp); if(exist(tNm,'file')), delete(tNm); end; return;
end
% perform appropriate operation
switch( cmd )
case 'addframe', chk(nIn,1,2); info=addFrame(fid,info,tNm,1,in{:});
case 'addframeb', chk(nIn,1,2); info=addFrame(fid,info,tNm,0,in{:});
case 'getinfo', chk(nIn,0); o1=info;
otherwise, error(['Unrecognized command: "' cmd '"']);
end
infos{h}=info; varargout={o1};
end
function chk(nIn,nMin,nMax)
if(nargin<3), nMax=nMin; end
if(nIn>0 && nMin==0 && nMax==0), error(['"' cmd '" takes no args.']); end
if(nIn<nMin||nIn>nMax), error(['Incorrect num args for "' cmd '".']); end
end
function success = getImgFile( fName )
% create local copy of fName which is in a imagesci/private
fName = [fName '.' mexext]; s = filesep; success = 1;
sName = [fileparts(which('imread.m')) s 'private' s fName];
tName = [fileparts(mfilename('fullpath')) s 'private' s fName];
if(~exist(tName,'file')), success=copyfile(sName,tName); end
end
function [info, fid, tNm] = open( fName, info )
% open video for writing, create space for header
t=[fName '.seq']; if(exist(t,'file')), delete(t); end
t=[fName '-seek.mat']; if(exist(t,'file')), delete(t); end
fid=fopen([fName '.seq'],'w','l'); assert(fid~=-1);
fwrite(fid,zeros(1,1024),'uint8');
% initialize info struct (w all fields necessary for writeHeader)
assert(isfield2(info,{'width','height','fps','codec'},1));
switch(info.codec)
case {'monoraw', 'imageFormat100'}, frmt=100; nCh=1; ext='raw';
case {'raw', 'imageFormat200'}, frmt=200; nCh=3; ext='raw';
case {'monojpg', 'imageFormat102'}, frmt=102; nCh=1; ext='jpg';
case {'jpg', 'imageFormat201'}, frmt=201; nCh=3; ext='jpg';
case {'monopng', 'imageFormat001'}, frmt=001; nCh=1; ext='png';
case {'png', 'imageFormat002'}, frmt=002; nCh=3; ext='png';
otherwise, error('unknown format');
end; s=1;
if(strcmp(ext,'jpg')), s=getImgFile('wjpg8c'); end
if(strcmp(ext,'png')), s=getImgFile('png');
if(s), info.writeImg=@(p) png('write',p{:}); end; end
if(strcmp(ext,'png') && ~s), s=getImgFile('pngwritec');
if(s), info.writeImg=@(p) pngwritec(p{:}); end; end
if(~s), error('Cannot find Matlab''s source image writer'); end
info.imageFormat=frmt; info.ext=ext;
if(any(strcmp(ext,{'jpg','png'}))), info.seek=1024; info.seekNm=t; end
if(~isfield2(info,'quality')), info.quality=80; end
info.imageBitDepth=8*nCh; info.imageBitDepthReal=8;
nByte=info.width*info.height*nCh; info.imageSizeBytes=nByte;
info.numFrames=0; info.trueImageSize=nByte+6+512-mod(nByte+6,512);
% generate unique temporary name
[~,tNm]=fileparts(fName); t=clock; t=mod(t(end),1);
tNm=sprintf('tmp_%s_%15i.%s',tNm,round((t+rand)/2*1e15),ext);
end
function info = addFrame( fid, info, tNm, encode, I, ts )
% write frame
nCh=info.imageBitDepth/8; ext=info.ext; c=info.numFrames+1;
if( encode )
siz = [info.height info.width nCh];
assert(size(I,1)==siz(1) && size(I,2)==siz(2) && size(I,3)==siz(3));
end
switch ext
case 'raw'
% write an uncompressed image (assume imageBitDepthReal==8)
if( ~encode ), assert(numel(I)==info.imageSizeBytes); else
if(nCh==3), t=I(:,:,3); I(:,:,3)=I(:,:,1); I(:,:,1)=t; end
if(nCh==1), I=I'; else I=permute(I,[3,2,1]); end
end
fwrite(fid,I(:),'uint8'); pad=info.trueImageSize-info.imageSizeBytes-6;
case 'jpg'
if( encode )
% write/read to/from temporary .jpg (not that much overhead)
p=struct('quality',info.quality,'comment',{{}},'mode','lossy');
for t=0:99, try wjpg8c(I,tNm,p); fr=fopen(tNm,'r'); assert(fr>0);
break; catch, pause(.01); fr=-1; end; end %#ok<CTCH>
if(fr<0), error(['write fail: ' tNm]); end; I=fread(fr); fclose(fr);
end
assert(I(1)==255 && I(2)==216 && I(end-1)==255 && I(end)==217); % JPG
fwrite(fid,numel(I)+4,'uint32'); fwrite(fid,I); pad=10;
case 'png'
if( encode )
% write/read to/from temporary .png (not that much overhead)
p=cell(1,17); if(nCh==1), p{4}=0; else p{4}=2; end
p{1}=I; p{3}=tNm; p{5}=8; p{8}='none'; p{16}=cell(0,2);
for t=0:99, try info.writeImg(p); fr=fopen(tNm,'r'); assert(fr>0);
break; catch, pause(.01); fr=-1; end; end %#ok<CTCH>
if(fr<0), error(['write fail: ' tNm]); end; I=fread(fr); fclose(fr);
end
fwrite(fid,numel(I)+4,'uint32'); fwrite(fid,I); pad=10;
otherwise, assert(false);
end
% store seek info
if(any(strcmp(ext,{'jpg','png'})))
if(length(info.seek)<c+1), info.seek=[info.seek; zeros(c,1)]; end
info.seek(c+1)=info.seek(c)+numel(I)+10+pad;
end
% write timestamp
if(nargin<6),ts=(c-1)/info.fps; end; s=floor(ts); ms=round(mod(ts,1)*1000);
fwrite(fid,s,'int32'); fwrite(fid,ms,'uint16'); info.numFrames=c;
% pad with zeros
if(pad>0), fwrite(fid,zeros(1,pad),'uint8'); end
end
function writeHeader( fid, info )
fseek(fid,0,'bof');
% first 4 bytes store OxFEED, next 24 store 'Norpix seq '
fwrite(fid,hex2dec('FEED'),'uint32');
fwrite(fid,['Norpix seq' 0 0],'uint16');
% next 8 bytes for version (3) and header size (1024), then 512 for descr
fwrite(fid,[3 1024],'int32');
if(isfield(info,'descr')), d=info.descr(:); else d=('No Description')'; end
d=[d(1:min(256,end)); zeros(256-length(d),1)]; fwrite(fid,d,'uint16');
% write remaining info
vals=[info.width info.height info.imageBitDepth info.imageBitDepthReal ...
info.imageSizeBytes info.imageFormat info.numFrames 0 ...
info.trueImageSize];
fwrite(fid,vals,'uint32');
% store frame rate and pad with 0's
fwrite(fid,info.fps,'float64'); fwrite(fid,zeros(1,432),'uint8');
% write seek info for compressed images to disk
if(any(strcmp(info.ext,{'jpg','png'})))
seek=info.seek(1:info.numFrames); %#ok<NASGU>
try save(info.seekNm,'seek'); catch; end %#ok<CTCH>
end
end
|
github
|
devaib/MXNet-SSD-master
|
kernelTracker.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/GT-visualization/toolbox/videos/kernelTracker.m
| 9,315 |
utf_8
|
4a7d0235f1e518ab5f1c9f1b5450b3f0
|
function [allRct, allSim, allIc] = kernelTracker( I, prm )
% Kernel Tracker from Comaniciu, Ramesh and Meer PAMI 2003.
%
% Implements the algorithm described in "Kernel-Based Object Tracking" by
% Dorin Comaniciu, Visvanathan Ramesh and Peter Meer, PAMI 25, 564-577,
% 2003. This is a fast tracking algorithm that utilizes a histogram
% representation of an object (in this implementation we use color
% histograms, as in the original work). The idea is given a histogram q in
% frame t, find histogram p in frame t+1 that is most similar to q. It
% turns out that this can be formulated as a mean shift problem. Here, the
% kernel is fixed to the Epanechnikov kernel.
%
% This implementation uses mex files to optimize speed, it is significantly
% faster than real time for a single object on a 2GHz standard laptop (as
% of 2007).
%
% If I==[], toy data is created. If rctS==0, the user is queried to
% specify the first rectangle. rctE, denoting the object location in the
% last frame, can optionally be specified. If rctE is given, the model
% histogram at fraction r of the video is (1-r)*histS+r*histE where histS
% and histE are the model histograms from the first and last frame. If
% rctE==0 rectangle in final frame is queried, if rectE==-1 it is not used.
%
% Let T denote the length of the video. Returned values are of length t,
% where t==T if the object was tracked through the whole sequence (ie sim
% does not fall below simThr), otherwise t<=T is equal to the last frame in
% which obj was found. You can test if the object was tracked using:
% success = (size(allRct,1)==size(I,4));
%
% USAGE
% [allRct, allIc, allSim] = kernelTracker( [I], [prm] )
%
% INPUTS
% I - MxNx3xT input video
% [prm]
% .rctS - [0] rectangle denoting initial object location
% .rctE - [-1] rectangle denoting final object location
% .dispFlag - [1] show interactive display
% .scaleSrch - [1] if true search over scale
% .nBit - [4] n=2^nBit, color histograms are [n x n x n]
% .simThr - [.7] sim thr for when obj is considered lost
% .scaleDel - [.9] multiplicative diff between consecutive scales
%
% OUTPUTS
% allRct - [t x 4] array of t locations [x,y,wd,ht]
% allSim - [1 x t] array of similarity measures during tracking
% allIc - [1 x t] cell array of cropped windows containing obj
%
% EXAMPLE
% disp('Select a rectangular region for tracking');
% [allRct,allSim,allIc] = kernelTracker();
% figure(2); clf; plot(allRct);
% figure(3); clf; montage2(allIc,struct('hasChn',true));
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.22
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%%% get parameters (set defaults)
if( nargin<1 ); I=[]; end;
if( nargin<2 ); prm=struct(); end;
dfs = {'scaleSrch',1, 'nBit',4, 'simThr',.7, ...
'dispFlag',1, 'scaleDel',.9, 'rctS',0, 'rctE',-1 };
prm = getPrmDflt( prm, dfs );
scaleSrch=prm.scaleSrch; nBit=prm.nBit; simThr=prm.simThr;
dispFlag=prm.dispFlag; scaleDel=prm.scaleDel;
rctS=prm.rctS; rctE=prm.rctE;
if(isempty(I)); I=toyData(100,1); end;
%%% get rctS and rectE if necessary
rctProp = {'EdgeColor','g','Curvature',[1 1],'LineWidth',2};
if(rctS==0); figure(1); clf; imshow(I(:,:,:,1)); rctS=getrect; end
if(rctE==0); figure(1); clf; imshow(I(:,:,:,end)); rctE=getrect; end
%%% precompute kernels for all relevant scales
rctS=round(rctS); rctS(3:4)=rctS(3:4)-mod(rctS(3:4),2);
pos1 = rctS(1:2)+rctS(3:4)/2; wd=rctS(3); ht=rctS(4);
[mRows,nCols,~,nFrame] = size(I);
nScaleSm = max(1,floor(log(max(10/wd,10/ht))/log(scaleDel)));
nScaleLr = max(1,floor(-log(min(nCols/wd,mRows/ht)/2)/log(scaleDel)));
nScale = nScaleSm+nScaleLr+1; scale = nScaleSm+1;
kernel = repmat( buildKernel(wd,ht), [1 nScale] );
for s=1:nScale
r = power(scaleDel,s-1-nScaleSm);
kernel(s) = buildKernel( wd/r, ht/r );
end
%%% build model histogram for rctS
[Ic,Qc] = cropWindow( I(:,:,:,1), nBit, pos1, wd, ht );
qS = buildHist( Qc, kernel(scale), nBit );
%%% optionally build model histogram for rctE
if(length(rctE)==4);
rctE=round(rctE); rctE(3:4)=rctE(3:4)-mod(rctE(3:4),2);
posE = rctE(1:2)+rctE(3:4)/2; wdE=rctE(3); htE=rctE(4);
kernelE = buildKernel(wdE,htE);
[Ic,Qc] = cropWindow( I(:,:,:,end), nBit, posE, wdE, htE ); %end
qE = buildHist( Qc, kernelE, nBit );
else
qE = qS;
end
%%% setup display
if( dispFlag )
figure(1); clf; hImg=imshow(I(:,:,:,1));
hR = rectangle('Position', rctS, rctProp{:} );
pause(.1);
end
%%% main loop
pos = pos1;
allRct = zeros(nFrame,4); allRct(1,:)=rctS;
allIc = cell(1,nFrame); allIc{1}=Ic;
allSim = zeros(1,nFrame);
for frm = 1:nFrame
Icur = I(:,:,:,frm);
% current model (linearly interpolate)
r=(frm-1)/nFrame; q = qS*(1-r) + qE*r;
if( scaleSrch )
% search over scale
best={}; bestSim=-1; pos1=pos;
for s=max(1,scale-1):min(nScale,scale+1)
[p,pos,Ic,sim]=kernelTracker1(Icur,q,pos1,kernel(s),nBit);
if( sim>bestSim ); best={p,pos,Ic,s}; bestSim=sim; end;
end
[~,pos,Ic,scale]=deal(best{:});
wd=kernel(scale).wd; ht=kernel(scale).ht;
else
% otherwise just do meanshift once
[~,pos,Ic,bestSim]=kernelTracker1(Icur,q,pos,kernel(scale),nBit);
end
% record results
if( bestSim<simThr ); break; end;
rctC=[pos(1)-wd/2 pos(2)-ht/2 wd, ht ];
allIc{frm}=Ic; allRct(frm,:)=rctC;
allSim(frm)=bestSim;
% display
if( dispFlag )
set(hImg,'CData',Icur); title(['bestSim=' num2str(bestSim)]);
delete(hR); hR=rectangle('Position', rctC, rctProp{:} );
if(0); waitforbuttonpress; else drawnow; end
end
end
%%% finalize & display
if( bestSim<simThr ); frm=frm-1; end;
allIc=allIc(1:frm); allRct=allRct(1:frm,:); allSim=allSim(1:frm);
if( dispFlag )
if( bestSim<simThr ); disp('lost target'); end
disp( ['final sim = ' num2str(bestSim) ] );
end
end
function [p,pos,Ic,sim] = kernelTracker1( I, q, pos, kernel, nBit )
mRows=size(I,1); nCols=size(I,2);
wd=kernel.wd; wd2=wd/2;
ht=kernel.ht; ht2=ht/2;
xs=kernel.xs; ys=kernel.ys;
for iter=1:1000
posPrev = pos;
% check if pos in bounds
rct = [pos(1)-wd/2 pos(2)-ht/2 wd, ht ];
if( rct(1)<1 || rct(2)<1 || (rct(1)+wd)>nCols || (rct(2)+ht)>mRows )
pos=posPrev; p=[]; Ic=[]; sim=eps; return;
end
% crop window / compute histogram
[Ic,Qc] = cropWindow( I, nBit, pos, wd, ht );
p = buildHist( Qc, kernel, nBit );
if( iter==20 ); break; end;
% compute meanshift step
w = ktComputeW_c( Qc, q, p, nBit );
posDel = [sum(xs.*w)*wd2, sum(ys.*w)*ht2] / (sum(w)+eps);
posDel = round(posDel+.1);
if(all(posDel==0)); break; end;
pos = pos + posDel;
end
locs=p>0; sim=sum( sqrt(q(locs).*p(locs)) );
end
function kernel = buildKernel( wd, ht )
wd = round(wd/2)*2; xs = linspace(-1,1,wd);
ht = round(ht/2)*2; ys = linspace(-1,1,ht);
[ys,xs] = ndgrid(ys,xs); xs=xs(:); ys=ys(:);
xMag = ys.*ys + xs.*xs; xMag(xMag>1) = 1;
K = 2/pi * (1-xMag); sumK=sum(K);
kernel = struct( 'K',K, 'sumK',sumK, 'xs',xs, 'ys',ys, 'wd',wd, 'ht',ht );
end
function p = buildHist( Qc, kernel, nBit )
p = ktHistcRgb_c( Qc, kernel.K, nBit ) / kernel.sumK;
if(0); p=gaussSmooth(p,.5,'same',2); p=p*(1/sum(p(:))); end;
end
function [Ic,Qc] = cropWindow( I, nBit, pos, wd, ht )
row = pos(2)-ht/2; col = pos(1)-wd/2;
Ic = I(row:row+ht-1,col:col+wd-1,:);
if(nargout==2); Qc=bitshift(reshape(Ic,[],3),nBit-8); end;
end
function I = toyData( n, sigma )
I1 = imresize(imread('peppers.png'),[256 256],'bilinear');
I=ones(512,512,3,n,'uint8')*100;
pos = round(gaussSmooth(randn(2,n)*80,[0 4]))+128;
for i=1:n
I((1:256)+pos(1,i),(1:256)+pos(2,i),:,i)=I1;
I1 = uint8(double(I1) + randn(size(I1))*sigma);
end;
I=I((1:256)+128,(1:256)+128,:,:);
end
% % debugging code
% if( debug )
% figure(1);
% subplot(2,3,2); image( Ic ); subplot(2,3,1); image(Icur);
% rectangle('Position', posToRct(pos0,wd,ht), rctProp{:} );
% subplot(2,3,3); imagesc( reshape(w,wd,ht), [0 5] ); colormap gray;
% subplot(2,3,4); montage2( q ); subplot(2,3,5); montage2( p1 );
% waitforbuttonpress;
% end
% % search over 9 locations (with fixed scale)
% if( locSrch )
% best={}; bestSim=0.0; pos1=pos;
% for lr=-1:1
% for ud=-1:1
% posSt = pos1 + [wd*lr ht*ud];
% [p,pos,Ic,sim] = kernelTracker1(Icur,q,posSt,kernel(scale),nBit);
% if( sim>bestSim ); best={p,pos,Ic}; bestSim=sim; end;
% end
% end
% [p,pos,Ic]=deal(best{:});
% end
%%% background histogram -- seems kind of useless, removed
% if( 0 )
% bgSiz = 3; bgImp = 2;
% rctBgStr = max([1 1],rctS(1:2)-rctS(3:4)*(bgSiz/2-.5));
% rctBgEnd = min([nCols mRows],rctS(1:2)+rctS(3:4)*(bgSiz/2+.5));
% rctBg = [rctBgStr rctBgEnd-rctBgStr+1];
% posBg = rctBg(1:2)+rctBg(3:4)/2; wdBg=rctBg(3); htBg=rctBg(4);
% [IcBg,QcBg] = cropWindow( I(:,:,:,1), nBit, posBg, wdBg, htBg );
% wtBg = double( reshape(kernel.K,ht,wd)==0 );
% pre=rctS(1:2)-rctBg(1:2); pst=rctBg(3:4)-rctS(3:4)-pre;
% wtBg = padarray( wtBg, fliplr(pre), 1, 'pre' );
% wtBg = padarray( wtBg, fliplr(pst), 1, 'post' );
% pBg = buildHist( QcBg, wtBg, [], nBit );
% pWts = min( 1, max(pBg(:))/bgImp./pBg );
% if(0); montage2(pWts); impixelinfo; return; end
% else
% pWts=[];
% end;
% if(~isempty(pWts)); p = p .* pWts; end; % in buildHistogram
|
github
|
devaib/MXNet-SSD-master
|
seqIo.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/GT-visualization/toolbox/videos/seqIo.m
| 17,019 |
utf_8
|
9c631b324bb527372ec3eed3416c5dcc
|
function out = seqIo( fName, action, varargin )
% Utilities for reading and writing seq files.
%
% A seq file is a series of concatentated image frames with a fixed size
% header. It is essentially the same as merging a directory of images into
% a single file. seq files are convenient for storing videos because: (1)
% no video codec is required, (2) seek is instant and exact, (3) seq files
% can be read on any operating system. The main drawback is that each frame
% is encoded independently, resulting in increased file size. The advantage
% over storing as a directory of images is that a single large file is
% created. Currently, either uncompressed, jpg or png compressed frames
% are supported. The seq file format is modeled after the Norpix seq format
% (in fact this reader can be used to read some Norpix seq files). The
% actual work of reading/writing seq files is done by seqReaderPlugin and
% seqWriterPlugin (there is no need to call those functions directly).
%
% seqIo contains a number of utility functions for working with seq files.
% The format for accessing the various utility functions is:
% out = seqIo( fName, 'action', inputs );
% The list of functions and help for each is given below. Also, help on
% individual subfunctions can be accessed by: "help seqIo>action".
%
% Create interface sr for reading seq files.
% sr = seqIo( fName, 'reader', [cache] )
% Create interface sw for writing seq files.
% sw = seqIo( fName, 'writer', info )
% Get info about seq file.
% info = seqIo( fName, 'getInfo' )
% Crop sub-sequence from seq file.
% seqIo( fName, 'crop', tName, frames )
% Extract images from seq file to target directory or array.
% Is = seqIo( fName, 'toImgs', [tDir], [skip], [f0], [f1], [ext] )
% Create seq file from an array or directory of images or from an AVI file.
% seqIo( fName, 'frImgs', info, varargin )
% Convert seq file by applying imgFun(I) to each frame I.
% seqIo( fName, 'convert', tName, imgFun, varargin )
% Replace header of seq file with provided info.
% seqIo( fName, 'newHeader', info )
% Create interface sr for reading dual seq files.
% sr = seqIo( fNames, 'readerDual', [cache] )
%
% USAGE
% out = seqIo( fName, action, varargin )
%
% INPUTS
% fName - seq file to open
% action - controls action (see above)
% varargin - additional inputs (see above)
%
% OUTPUTS
% out - depends on action (see above)
%
% EXAMPLE
%
% See also seqIo>reader, seqIo>writer, seqIo>getInfo, seqIo>crop,
% seqIo>toImgs, seqIo>frImgs, seqIo>convert, seqIo>newHeader,
% seqIo>readerDual, seqPlayer, seqReaderPlugin, seqWriterPlugin
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
switch lower(action)
case {'reader','r'}, out = reader( fName, varargin{:} );
case {'writer','w'}, out = writer( fName, varargin{:} );
case 'getinfo', out = getInfo( fName );
case 'crop', crop( fName, varargin{:} ); out=1;
case 'toimgs', out = toImgs( fName, varargin{:} );
case 'frimgs', frImgs( fName, varargin{:} ); out=1;
case 'convert', convert( fName, varargin{:} ); out=1;
case 'newheader', newHeader( fName, varargin{:} ); out=1;
case {'readerdual','rdual'}, out=readerDual(fName,varargin{:});
otherwise, error('seqIo unknown action: ''%s''',action);
end
end
function sr = reader( fName, cache )
% Create interface sr for reading seq files.
%
% Create interface sr to seq file with the following commands:
% sr.close(); % Close seq file (sr is useless after).
% [I,ts]=sr.getframe(); % Get current frame (returns [] if invalid).
% [I,ts]=sr.getframeb(); % Get current frame with no decoding.
% ts = sr.getts(); % Return timestamps for all frames.
% info = sr.getinfo(); % Return struct with info about video.
% [I,ts]=sr.getnext(); % Shortcut for next() followed by getframe().
% out = sr.next(); % Go to next frame (out=0 on fail).
% out = sr.seek(frame); % Go to specified frame (out=0 on fail).
% out = sr.step(delta); % Go to current frame+delta (out=0 on fail).
%
% If cache>0, reader() will cache frames in memory, so that calls to
% getframe() can avoid disk IO for cached frames (note that only frames
% returned by getframe() are cached). This is useful if the same frames are
% accessed repeatedly. When the cache is full, the frame in the cache
% accessed least recently is discarded. Memory requirements are
% proportional to cache size.
%
% USAGE
% sr = seqIo( fName, 'reader', [cache] )
%
% INPUTS
% fName - seq file name
% cache - [0] size of cache
%
% OUTPUTS
% sr - interface for reading seq file
%
% EXAMPLE
%
% See also seqIo, seqReaderPlugin
if(nargin<2 || isempty(cache)), cache=0; end
if( cache>0 ), [as, fs, Is, ts, inds]=deal([]); end
r=@seqReaderPlugin; s=r('open',int32(-1),fName);
sr = struct( 'close',@() r('close',s), 'getframe',@getframe, ...
'getframeb',@() r('getframeb',s), 'getts',@() r('getts',s), ...
'getinfo',@() r('getinfo',s), 'getnext',@() r('getnext',s), ...
'next',@() r('next',s), 'seek',@(f) r('seek',s,f), ...
'step',@(d) r('step',s,d));
function [I,t] = getframe()
% if not using cache simply call 'getframe' and done
if(cache<=0), [I,t]=r('getframe',s); return; end
% if cache initialized and frame in cache perform lookup
f=r('getinfo',s); f=f.curFrame; i=find(f==fs,1);
if(i), as=as+1; as(i)=0; t=ts(i); I=Is(inds{:},i); return; end
% if image not in cache add (and possibly initialize)
[I,t]=r('getframe',s); if(0), fprintf('reading frame %i\n',f); end
if(isempty(Is)), Is=zeros([size(I) cache],class(I));
as=ones(1,cache); fs=-as; ts=as; inds=repmat({':'},1,ndims(I)); end
[~,i]=max(as); as(i)=0; fs(i)=f; ts(i)=t; Is(inds{:},i)=I;
end
end
function sw = writer( fName, info )
% Create interface sw for writing seq files.
%
% Create interface sw to seq file with the following commands:
% sw.close(); % Close seq file (sw is useless after).
% sw.addframe(I,[ts]); % Writes video frame (and timestamp)
% sw.addframeb(bytes); % Writes video frame with no encoding.
% info = sw.getinfo(); % Return struct with info about video.
%
% The following params must be specified in struct 'info' upon opening:
% width - frame width
% height - frame height
% fps - frames per second
% quality - [80] compression quality (0 to 100)
% codec - string representing codec, options include:
% 'monoraw'/'imageFormat100' - black/white uncompressed
% 'raw'/'imageFormat200' - color (BGR) uncompressed
% 'monojpg'/'imageFormat102' - black/white jpg compressed
% 'jpg'/'imageFormat201' - color jpg compressed
% 'monopng'/'imageFormat001' - black/white png compressed
% 'png'/'imageFormat002' - color png compressed
%
% USAGE
% sw = seqIo( fName, 'writer', info )
%
% INPUTS
% fName - seq file name
% info - see above
%
% OUTPUTS
% sw - interface for writing seq file
%
% EXAMPLE
%
% See also seqIo, seqWriterPlugin
w=@seqWriterPlugin; s=w('open',int32(-1),fName,info);
sw = struct( 'close',@() w('close',s), 'getinfo',@() w('getinfo',s), ...
'addframe',@(varargin) w('addframe',s,varargin{:}), ...
'addframeb',@(varargin) w('addframeb',s,varargin{:}) );
end
function info = getInfo( fName )
% Get info about seq file.
%
% USAGE
% info = seqIo( fName, 'getInfo' )
%
% INPUTS
% fName - seq file name
%
% OUTPUTS
% info - information struct
%
% EXAMPLE
%
% See also seqIo
sr=reader(fName); info=sr.getinfo(); sr.close();
end
function crop( fName, tName, frames )
% Crop sub-sequence from seq file.
%
% Frame indices are 0 indexed. frames need not be consecutive and can
% contain duplicates. An index of -1 indicates a blank (all 0) frame. If
% contiguous subset of frames is cropped timestamps are preserved.
%
% USAGE
% seqIo( fName, 'crop', tName, frames )
%
% INPUTS
% fName - seq file name
% tName - cropped seq file name
% frames - frame indices (0 indexed)
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo
sr=reader(fName); info=sr.getinfo(); sw=writer(tName,info);
frames=frames(:)'; pad=sr.getnext(); pad(:)=0;
kp=frames>=0 & frames<info.numFrames; if(~all(kp)), frames=frames(kp);
warning('piotr:seqIo:crop','%i out of bounds frames',sum(~kp)); end
ordered=all(frames(2:end)==frames(1:end-1)+1);
n=length(frames); k=0; tid=ticStatus;
for f=frames
if(f<0), sw.addframe(pad); continue; end
sr.seek(f); [I,ts]=sr.getframeb(); k=k+1; tocStatus(tid,k/n);
if(ordered), sw.addframeb(I,ts); else sw.addframeb(I); end
end; sw.close(); sr.close();
end
function Is = toImgs( fName, tDir, skip, f0, f1, ext )
% Extract images from seq file to target directory or array.
%
% USAGE
% Is = seqIo( fName, 'toImgs', [tDir], [skip], [f0], [f1], [ext] )
%
% INPUTS
% fName - seq file name
% tDir - [] target directory (if empty extract images to array)
% skip - [1] skip between written frames
% f0 - [0] first frame to write
% f1 - [numFrames-1] last frame to write
% ext - [] optionally save as given type (slow, reconverts)
%
% OUTPUTS
% Is - if isempty(tDir) outputs image array (else Is=[])
%
% EXAMPLE
%
% See also seqIo
if(nargin<2 || isempty(tDir)), tDir=[]; end
if(nargin<3 || isempty(skip)), skip=1; end
if(nargin<4 || isempty(f0)), f0=0; end
if(nargin<5 || isempty(f1)), f1=inf; end
if(nargin<6 || isempty(ext)), ext=''; end
sr=reader(fName); info=sr.getinfo(); f1=min(f1,info.numFrames-1);
frames=f0:skip:f1; n=length(frames); tid=ticStatus; k=0;
% output images to array
if(isempty(tDir))
I=sr.getnext(); d=ndims(I); assert(d==2 || d==3);
try Is=zeros([size(I) n],class(I)); catch e; sr.close(); throw(e); end
for k=1:n, sr.seek(frames(k)); I=sr.getframe(); tocStatus(tid,k/n);
if(d==2), Is(:,:,k)=I; else Is(:,:,:,k)=I; end; end
sr.close(); return;
end
% output images to directory
if(~exist(tDir,'dir')), mkdir(tDir); end; Is=[];
for frame=frames
f=[tDir '/I' int2str2(frame,5) '.']; sr.seek(frame);
if(~isempty(ext)), I=sr.getframe(); imwrite(I,[f ext]); else
I=sr.getframeb(); f=fopen([f info.ext],'w');
if(f<=0), sr.close(); assert(false); end
fwrite(f,I); fclose(f);
end; k=k+1; tocStatus(tid,k/n);
end; sr.close();
end
function frImgs( fName, info, varargin )
% Create seq file from an array or directory of images or from an AVI file.
%
% For info, if converting from array, only codec (e.g., 'jpg') and fps must
% be specified while width and height and determined automatically. If
% converting from AVI, fps is also determined automatically.
%
% USAGE
% seqIo( fName, 'frImgs', info, varargin )
%
% INPUTS
% fName - seq file name
% info - defines codec, etc, see seqIo>writer
% varargin - additional params (struct or name/value pairs)
% .aviName - [] if specified create seq from avi file
% .Is - [] if specified create seq from image array
% .sDir - [] source directory
% .skip - [1] skip between frames
% .name - ['I'] base name of images
% .nDigits - [5] number of digits for filename index
% .f0 - [0] first frame to read
% .f1 - [10^6] last frame to read
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo, seqIo>writer
dfs={'aviName','','Is',[],'sDir',[],'skip',1,'name','I',...
'nDigits',5,'f0',0,'f1',10^6};
[aviName,Is,sDir,skip,name,nDigits,f0,f1] ...
= getPrmDflt(varargin,dfs,1);
if(~isempty(aviName))
if(exist('mmread.m','file')==2) % use external mmread function
% mmread requires full pathname, which is obtained via 'which'. But,
% 'which' can fail (maltab bug), so best to just pass in full pathname
t=which(aviName); if(~isempty(t)), aviName=t; end
V=mmread(aviName); n=V.nrFramesTotal;
info.height=V.height; info.width=V.width; info.fps=V.rate;
sw=writer(fName,info); tid=ticStatus('creating seq from avi');
for f=1:n, sw.addframe(V.frames(f).cdata); tocStatus(tid,f/n); end
sw.close();
else % use matlab mmreader function
emsg=['mmreader.m failed to load video. In general mmreader.m is ' ...
'known to have many issues, especially on Linux. I suggest ' ...
'installing the similarly named mmread toolbox from Micah ' ...
'Richert, available at Matlab Central. If mmread is installed, ' ...
'seqIo will automatically use mmread instead of mmreader.'];
try V=mmreader(aviName); catch %#ok<DMMR,CTCH>
error('piotr:seqIo:frImgs',emsg); end; n=V.NumberOfFrames;
info.height=V.Height; info.width=V.Width; info.fps=V.FrameRate;
sw=writer(fName,info); tid=ticStatus('creating seq from avi');
for f=1:n, sw.addframe(read(V,f)); tocStatus(tid,f/n); end
sw.close();
end
elseif( isempty(Is) )
assert(exist(sDir,'dir')==7); sw=writer(fName,info); info=sw.getinfo();
frmStr=sprintf('%s/%s%%0%ii.%s',sDir,name,nDigits,info.ext);
for frame = f0:skip:f1
f=sprintf(frmStr,frame); if(~exist(f,'file')), break; end
f=fopen(f,'r'); if(f<=0), sw.close(); assert(false); end
I=fread(f); fclose(f); sw.addframeb(I);
end; sw.close();
if(frame==f0), warning('No images found.'); end %#ok<WNTAG>
else
nd=ndims(Is); if(nd==2), nd=3; end; assert(nd<=4); nFrm=size(Is,nd);
info.height=size(Is,1); info.width=size(Is,2); sw=writer(fName,info);
if(nd==3), for f=1:nFrm, sw.addframe(Is(:,:,f)); end; end
if(nd==4), for f=1:nFrm, sw.addframe(Is(:,:,:,f)); end; end
sw.close();
end
end
function convert( fName, tName, imgFun, varargin )
% Convert seq file by applying imgFun(I) to each frame I.
%
% USAGE
% seqIo( fName, 'convert', tName, imgFun, varargin )
%
% INPUTS
% fName - seq file name
% tName - converted seq file name
% imgFun - function to apply to each image
% varargin - additional params (struct or name/value pairs)
% .info - [] info for target seq file
% .skip - [1] skip between frames
% .f0 - [0] first frame to read
% .f1 - [inf] last frame to read
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo
dfs={'info',[],'skip',1,'f0',0,'f1',inf};
[info,skip,f0,f1]=getPrmDflt(varargin,dfs,1);
assert(~strcmp(tName,fName)); sr=reader(fName); infor=sr.getinfo();
if(isempty(info)), info=infor; end; n=infor.numFrames; f1=min(f1,n-1);
I=sr.getnext(); I=imgFun(I); info.width=size(I,2); info.height=size(I,1);
sw=writer(tName,info); tid=ticStatus('converting seq');
frames=f0:skip:f1; n=length(frames); k=0;
for f=frames, sr.seek(f); [I,ts]=sr.getframe(); I=imgFun(I);
if(skip==1), sw.addframe(I,ts); else sw.addframe(I); end
k=k+1; tocStatus(tid,k/n);
end; sw.close(); sr.close();
end
function newHeader( fName, info )
% Replace header of seq file with provided info.
%
% Can be used if the file fName has a corrupt header. Automatically tries
% to compute number of frames in fName. No guarantees that it will work.
%
% USAGE
% seqIo( fName, 'newHeader', info )
%
% INPUTS
% fName - seq file name
% info - info for target seq file
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo
[d,n]=fileparts(fName); if(isempty(d)), d='.'; end
fName=[d '/' n]; tName=[fName '-new' datestr(now,30)];
if(exist([fName '-seek.mat'],'file')); delete([fName '-seek.mat']); end
srp=@seqReaderPlugin; hr=srp('open',int32(-1),fName,info); tid=ticStatus;
info=srp('getinfo',hr); sw=writer(tName,info); n=info.numFrames;
for f=1:n, srp('next',hr); [I,ts]=srp('getframeb',hr);
sw.addframeb(I,ts); tocStatus(tid,f/n); end
srp('close',hr); sw.close();
end
function sr = readerDual( fNames, cache )
% Create interface sr for reading dual seq files.
%
% Wrapper for two seq files of the same image dims and roughly the same
% frame counts that are treated as a single reader object. getframe()
% returns the concatentation of the two frames. For videos of different
% frame counts, the first video serves as the "dominant" video and the
% frame count of the second video is adjusted accordingly. Same general
% usage as in reader, but the only supported operations are: close(),
% getframe(), getinfo(), and seek().
%
% USAGE
% sr = seqIo( fNames, 'readerDual', [cache] )
%
% INPUTS
% fNames - two seq file names
% cache - [0] size of cache (see seqIo>reader)
%
% OUTPUTS
% sr - interface for reading seq file
%
% EXAMPLE
%
% See also seqIo, seqIo>reader
if(nargin<2 || isempty(cache)), cache=0; end
s1=reader(fNames{1}, cache); i1=s1.getinfo();
s2=reader(fNames{2}, cache); i2=s2.getinfo();
info=i1; info.width=i1.width+i2.width;
if( i1.width~=i2.width || i1.height~=i2.height )
s1.close(); s2.close(); error('Mismatched videos'); end
if( i1.numFrames~=i2.numFrames )
warning('seq files of different lengths'); end %#ok<WNTAG>
frame2=@(f) round(f/(i1.numFrames-1)*(i2.numFrames-1));
sr=struct('close',@() min(s1.close(),s2.close()), ...
'getframe',@getframe, 'getinfo',@() info, ...
'seek',@(f) s1.seek(f) & s2.seek(frame2(f)) );
function [I,t] = getframe()
[I1,t]=s1.getframe(); I2=s2.getframe(); I=[I1 I2]; end
end
|
github
|
devaib/MXNet-SSD-master
|
seqReaderPlugin.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/GT-visualization/toolbox/videos/seqReaderPlugin.m
| 9,617 |
utf_8
|
ad8f912634cafe13df6fc7d67aeff05a
|
function varargout = seqReaderPlugin( cmd, h, varargin )
% Plugin for seqIo and videoIO to allow reading of seq files.
%
% Do not call directly, use as plugin for seqIo or videoIO instead.
% The following is a list of commands available (srp=seqReaderPlugin):
% h = srp('open',h,fName) % Open a seq file for reading (h ignored).
% h = srp('close',h); % Close seq file (output h is -1).
% [I,ts] =srp('getframe',h) % Get current frame (returns [] if invalid).
% [I,ts] =srp('getframeb',h) % Get current frame with no decoding.
% ts = srp('getts',h) % Return timestamps for all frames.
% info = srp('getinfo',h) % Return struct with info about video.
% [I,ts] =srp('getnext',h) % Shortcut for 'next' followed by 'getframe'.
% out = srp('next',h) % Go to next frame (out=0 on fail).
% out = srp('seek',h,frame) % Go to specified frame (out=0 on fail).
% out = srp('step',h,delta) % Go to current frame+delta (out=0 on fail).
%
% USAGE
% varargout = seqReaderPlugin( cmd, h, varargin )
%
% INPUTS
% cmd - string indicating operation to perform
% h - unique identifier for open seq file
% varargin - additional options (vary according to cmd)
%
% OUTPUTS
% varargout - output (varies according to cmd)
%
% EXAMPLE
%
% See also SEQIO, SEQWRITERPLUGIN
%
% Piotr's Computer Vision Matlab Toolbox Version 3.10
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% persistent variables to keep track of all loaded .seq files
persistent h1 hs cs fids infos tNms;
if(isempty(h1)), h1=int32(now); hs=int32([]); infos={}; tNms={}; end
nIn=nargin-2; in=varargin; o2=[]; cmd=lower(cmd);
% open seq file
if(strcmp(cmd,'open'))
chk(nIn,1,2); h=length(hs)+1; hs(h)=h1; varargout={h1}; h1=h1+1;
[pth,name]=fileparts(in{1}); if(isempty(pth)), pth='.'; end
if(nIn==1), info=[]; else info=in{2}; end
fName=[pth filesep name]; cs(h)=-1;
[infos{h},fids(h),tNms{h}]=open(fName,info); return;
end
% Get the handle for this instance
[v,h]=ismember(h,hs); if(~v), error('Invalid load plugin handle'); end
c=cs(h); fid=fids(h); info=infos{h}; tNm=tNms{h};
% close seq file
if(strcmp(cmd,'close'))
chk(nIn,0); varargout={-1}; fclose(fid); kp=[1:h-1 h+1:length(hs)];
hs=hs(kp); cs=cs(kp); fids=fids(kp); infos=infos(kp);
tNms=tNms(kp); if(exist(tNm,'file')), delete(tNm); end; return;
end
% perform appropriate operation
switch( cmd )
case 'getframe', chk(nIn,0); [o1,o2]=getFrame(c,fid,info,tNm,1);
case 'getframeb', chk(nIn,0); [o1,o2]=getFrame(c,fid,info,tNm,0);
case 'getts', chk(nIn,0); o1=getTs(0:info.numFrames-1,fid,info);
case 'getinfo', chk(nIn,0); o1=info; o1.curFrame=c;
case 'getnext', chk(nIn,0); c=c+1; [o1,o2]=getFrame(c,fid,info,tNm,1);
case 'next', chk(nIn,0); [c,o1]=valid(c+1,info);
case 'seek', chk(nIn,1); [c,o1]=valid(in{1},info);
case 'step', chk(nIn,1); [c,o1]=valid(c+in{1},info);
otherwise, error(['Unrecognized command: "' cmd '"']);
end
cs(h)=c; varargout={o1,o2};
end
function chk(nIn,nMin,nMax)
if(nargin<3), nMax=nMin; end
if(nIn>0 && nMin==0 && nMax==0), error(['"' cmd '" takes no args.']); end
if(nIn<nMin||nIn>nMax), error(['Incorrect num args for "' cmd '".']); end
end
function success = getImgFile( fName )
% create local copy of fName which is in a imagesci/private
fName = [fName '.' mexext]; s = filesep; success = 1;
sName = [fileparts(which('imread.m')) s 'private' s fName];
tName = [fileparts(mfilename('fullpath')) s 'private' s fName];
if(~exist(tName,'file')), success=copyfile(sName,tName); end
end
function [info, fid, tNm] = open( fName, info )
% open video for reading, get header
if(exist([fName '.seq'],'file')==0)
error('seq file not found: %s.seq',fName); end
fid=fopen([fName '.seq'],'r','l');
if(isempty(info)), info=readHeader(fid); else
info.numFrames=0; fseek(fid,1024,'bof'); end
switch(info.imageFormat)
case {100,200}, ext='raw';
case {101 }, ext='brgb8';
case {102,201}, ext='jpg';
case {103 }, ext ='jbrgb';
case {001,002}, ext='png';
otherwise, error('unknown format');
end; info.ext=ext; s=1;
if(any(strcmp(ext,{'jpg','jbrgb'}))), s=getImgFile('rjpg8c'); end
if(strcmp(ext,'png')), s=getImgFile('png');
if(s), info.readImg=@(nm) png('read',nm,[]); end; end
if(strcmp(ext,'png') && ~s), s=getImgFile('pngreadc');
if(s), info.readImg=@(nm) pngreadc(nm,[],false); end; end
if(~s), error('Cannot find Matlab''s source image reader'); end
% generate unique temporary name
[~,tNm]=fileparts(fName); t=clock; t=mod(t(end),1);
tNm=sprintf('tmp_%s_%15i.%s',tNm,round((t+rand)/2*1e15),ext);
% compute seek info for compressed images
if(any(strcmp(ext,{'raw','brgb8'}))), assert(info.numFrames>0); else
oName=[fName '-seek.mat']; n=info.numFrames; if(n==0), n=10^7; end
if(exist(oName,'file')==2), load(oName); info.seek=seek; else %#ok<NODEF>
tid=ticStatus('loading seek info',.1,5); seek=zeros(n,1); seek(1)=1024;
extra=8; % extra bytes after image data (8 for ts, then 0 or 8 empty)
for i=2:n
s=seek(i-1)+fread(fid,1,'uint32')+extra; valid=fseek(fid,s,'bof')==0;
if(i==2 && valid), if(fread(fid,1,'uint32')~=0), fseek(fid,-4,'cof');
else extra=extra+8; s=s+8; valid=fseek(fid,s,'bof')==0; end; end
if(valid), seek(i)=s; tocStatus(tid,i/n);
else n=i-1; seek=seek(1:n); tocStatus(tid,1); break; end
end; if(info.numFrames==0), info.numFrames=n; end
try save(oName,'seek'); catch; end; info.seek=seek; %#ok<CTCH>
end
end
% compute frame rate from timestamps as stored fps may be incorrect
n=min(100,info.numFrames); if(n==1), return; end
ts = getTs( 0:(n-1), fid, info );
ds=ts(2:end)-ts(1:end-1); ds=ds(abs(ds-median(ds))<.005);
if(~isempty(ds)), info.fps=1/mean(ds); end
end
function [frame,v] = valid( frame, info )
v=(frame>=0 && frame<info.numFrames);
end
function [I,ts] = getFrame( frame, fid, info, tNm, decode )
% get frame image (I) and timestamp (ts) at which frame was recorded
nCh=info.imageBitDepth/8; ext=info.ext;
if(frame<0 || frame>=info.numFrames), I=[]; ts=[]; return; end
switch ext
case {'raw','brgb8'}
% read in an uncompressed image (assume imageBitDepthReal==8)
fseek(fid,1024+frame*info.trueImageSize,'bof');
I = fread(fid,info.imageSizeBytes,'*uint8');
if( decode )
% reshape appropriately for mxn or mxnx3 RGB image
siz = [info.height info.width nCh];
if(nCh==1), I=reshape(I,siz(2),siz(1))'; else
I = permute(reshape(I,siz(3),siz(2),siz(1)),[3,2,1]);
end
if(nCh==3), t=I(:,:,3); I(:,:,3)=I(:,:,1); I(:,:,1)=t; end
if(strcmp(ext,'brgb8')), I=demosaic(I,'bggr'); end
end
case {'jpg','jbrgb'}
fseek(fid,info.seek(frame+1),'bof'); nBytes=fread(fid,1,'uint32');
I = fread(fid,nBytes-4,'*uint8');
if( decode )
% write/read to/from temporary .jpg (not that much overhead)
assert(I(1)==255 && I(2)==216 && I(end-1)==255 && I(end)==217); % JPG
for t=0:99, fw=fopen(tNm,'w'); if(fw>=0), break; end; pause(.01); end
if(fw==-1), error(['unable to write: ' tNm]); end
fwrite(fw,I); fclose(fw); I=rjpg8c(tNm);
if(strcmp(ext,'jbrgb')), I=demosaic(I,'bggr'); end
end
case 'png'
fseek(fid,info.seek(frame+1),'bof'); nBytes=fread(fid,1,'uint32');
I = fread(fid,nBytes-4,'*uint8');
if( decode )
% write/read to/from temporary .png (not that much overhead)
for t=0:99, fw=fopen(tNm,'w'); if(fw>=0), break; end; pause(.01); end
if(fw==-1), error(['unable to write: ' tNm]); end
fwrite(fw,I); fclose(fw); I=info.readImg(tNm);
I=permute(I,ndims(I):-1:1);
end
otherwise, assert(false);
end
if(nargout==2), ts=fread(fid,1,'uint32')+fread(fid,1,'uint16')/1000; end
end
function ts = getTs( frames, fid, info )
% get timestamps (ts) at which frames were recorded
n=length(frames); ts=nan(1,n);
for i=1:n, frame=frames(i);
if(frame<0 || frame>=info.numFrames), continue; end
switch info.ext
case {'raw','brgb8'} % uncompressed
fseek(fid,1024+frame*info.trueImageSize+info.imageSizeBytes,'bof');
case {'jpg','png','jbrgb'} % compressed
fseek(fid,info.seek(frame+1),'bof');
fseek(fid,fread(fid,1,'uint32')-4,'cof');
otherwise, assert(false);
end
ts(i)=fread(fid,1,'uint32')+fread(fid,1,'uint16')/1000;
end
end
function info = readHeader( fid )
% see streampix manual for info on header
fseek(fid,0,'bof');
% check that header is not all 0's (a common error)
[tmp,n]=fread(fid,1024); if(n<1024), error('no header'); end
if(all(tmp==0)), error('fully empty header'); end; fseek(fid,0,'bof');
% first 4 bytes store OxFEED, next 24 store 'Norpix seq '
if( ~strcmp(sprintf('%X',fread(fid,1,'uint32')),'FEED') || ...
~strcmp(char(fread(fid,10,'uint16'))','Norpix seq') ) %#ok<FREAD>
error('invalid header');
end; fseek(fid,4,'cof');
% next 8 bytes for version and header size (1024), then 512 for descr
version=fread(fid,1,'int32'); assert(fread(fid,1,'uint32')==1024);
descr=char(fread(fid,256,'uint16'))'; %#ok<FREAD>
% read in more info
tmp=fread(fid,9,'uint32'); assert(tmp(8)==0);
fps = fread(fid,1,'float64'); codec=['imageFormat' int2str2(tmp(6),3)];
% store information in info struct
info=struct( 'width',tmp(1), 'height',tmp(2), 'imageBitDepth',tmp(3), ...
'imageBitDepthReal',tmp(4), 'imageSizeBytes',tmp(5), ...
'imageFormat',tmp(6), 'numFrames',tmp(7), 'trueImageSize', tmp(9),...
'fps',fps, 'seqVersion',version, 'codec',codec, 'descr',descr, ...
'nHiddenFinalFrames',0 );
assert(info.imageBitDepthReal==8);
% seek to end of header
fseek(fid,432,'cof');
end
|
github
|
devaib/MXNet-SSD-master
|
dirSynch.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/GT-visualization/toolbox/matlab/dirSynch.m
| 4,570 |
utf_8
|
d288299d31d15f1804183206d0aa0227
|
function dirSynch( root1, root2, showOnly, flag, ignDate )
% Synchronize two directory trees (or show differences between them).
%
% If a file or directory 'name' is found in both tree1 and tree2:
% 1) if 'name' is a file in both the pair is considered the same if they
% have identical size and identical datestamp (or if ignDate=1).
% 2) if 'name' is a directory in both the dirs are searched recursively.
% 3) if 'name' is a dir in root1 and a file in root2 (or vice-versa)
% synchronization cannot proceed (an error is thrown).
% If 'name' is found only in root1 or root2 it's a difference between them.
%
% The parameter flag controls how synchronization occurs:
% flag==0: neither tree1 nor tree2 has preference (newer file is kept)
% flag==1: tree2 is altered to reflect tree1 (tree1 is unchanged)
% flag==2: tree1 is altered to reflect tree2 (tree2 is unchanged)
% Run with showOnly=1 and different values of flag to see its effect.
%
% By default showOnly==1. If showOnly, displays a list of actions that need
% to be performed in order to synchronize the two directory trees, but does
% not actually perform the actions. It is highly recommended to run
% dirSynch first with showOnly=1 before running it with showOnly=0.
%
% USAGE
% dirSynch( root1, root2, [showOnly], [flag], [ignDate] )
%
% INPUTS
% root1 - root directory of tree1
% root2 - root directory of tree2
% showOnly - [1] show but do NOT perform actions
% flag - [0] 0: synchronize; 1: set root2=root1; 2: set root1==root2
% ignDate - [0] if true considers two files same even if have diff dates
%
% OUTPUTS
% dirSynch( 'c:\toolbox', 'c:\toolbox-old', 1 )
%
% EXAMPLE
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 2.10
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if(nargin<3 || isempty(showOnly)), showOnly=1; end;
if(nargin<4 || isempty(flag)), flag=0; end;
if(nargin<5 || isempty(ignDate)), ignDate=0; end;
% get differences between root1/root2 and loop over them
D = dirDiff( root1, root2, ignDate );
roots={root1,root2}; ticId = ticStatus;
for i=1:length(D)
% get action
if( flag==1 )
if( D(i).in1 ), act=1; src1=1; else act=0; src1=2; end
elseif( flag==2 )
if( D(i).in2 ), act=1; src1=2; else act=0; src1=1; end
else
act=1;
if(D(i).in1 && D(i).in2)
if( D(i).new1 ), src1=1; else src1=2; end
else
if( D(i).in1 ), src1=1; else src1=2; end
end
end
src2=mod(src1,2)+1;
% perform action
if( act==1 )
if( showOnly )
disp(['COPY ' int2str(src1) '->' int2str(src2) ': ' D(i).name]);
else
copyfile( [roots{src1} D(i).name], [roots{src2} D(i).name], 'f' );
end;
else
if( showOnly )
disp(['DEL in ' int2str(src1) ': ' D(i).name]);
else
fName = [roots{src1} D(i).name];
if(D(i).isdir), rmdir(fName,'s'); else delete(fName); end
end
end
if(~showOnly), tocStatus( ticId, i/length(D) ); end;
end
end
function D = dirDiff( root1, root2, ignDate )
% get differences from root1 to root2
D1 = dirDiff1( root1, root2, ignDate, '/' );
% get differences from root2 to root1
D2 = dirDiff1( root2, root1, ignDate, '/' );
% remove duplicates (arbitrarily from D2)
D2=D2(~([D2.in1] & [D2.in2]));
% swap 1 and 2 in D2
for i=1:length(D2),
D2(i).in1=0; D2(i).in2=1; D2(i).new1=~D2(i).new1;
end
% merge
D = [D1 D2];
end
function D = dirDiff1( root1, root2, ignDate, subdir )
if(root1(end)~='/'), root1(end+1)='/'; end
if(root2(end)~='/'), root2(end+1)='/'; end
if(subdir(end)~='/'), subdir(end+1)='/'; end
fs1=dir([root1 subdir]); fs2=dir([root2 subdir]);
D=struct('name',0,'isdir',0,'in1',0,'in2',0,'new1',0);
D=repmat(D,[1 length(fs1)]); n=0; names2={fs2.name}; Dsub=[];
for i1=1:length( fs1 )
name=fs1(i1).name; isdir=fs1(i1).isdir;
if( any(strcmp(name,{'.','..'})) ), continue; end;
i2 = find(strcmp(name,names2));
if(~isempty(i2) && isdir)
% cannot handle this condition
if(~fs2(i2).isdir), disp([root1 subdir name]); assert(false); end;
% recurse and record possible differences
Dsub=[Dsub dirDiff1(root1,root2,ignDate,[subdir name])]; %#ok<AGROW>
elseif( ~isempty(i2) && fs1(i1).bytes==fs2(i2).bytes && ...
(ignDate || fs1(i1).datenum==fs2(i2).datenum))
% nothing to do - files are same
continue;
else
% record differences
n=n+1;
D(n).name=[subdir name]; D(n).isdir=isdir;
D(n).in1=1; D(n).in2=~isempty(i2);
D(n).new1 = ~D(n).in2 || (fs1(i1).datenum>fs2(i2).datenum);
end
end
D = [D(1:n) Dsub];
end
|
github
|
devaib/MXNet-SSD-master
|
plotRoc.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/GT-visualization/toolbox/matlab/plotRoc.m
| 5,212 |
utf_8
|
008f9c63073c6400c4960e9e213c47e5
|
function [h,miss,stds] = plotRoc( D, varargin )
% Function for display of rocs (receiver operator characteristic curves).
%
% Display roc curves. Consistent usage ensures uniform look for rocs. The
% input D should have n rows, each of which is of the form:
% D = [falsePosRate truePosRate]
% D is generated, for example, by scanning a detection threshold over n
% values from 0 (so first entry is [1 1]) to 1 (so last entry is [0 0]).
% Alternatively D can be a cell vector of rocs, in which case an average
% ROC will be shown with error bars. Plots missRate (which is just 1 minus
% the truePosRate) on the y-axis versus the falsePosRate on the x-axis.
%
% USAGE
% [h,miss,stds] = plotRoc( D, prm )
%
% INPUTS
% D - [nx2] n data points along roc [falsePosRate truePosRate]
% typically ranges from [1 1] to [0 0] (or may be reversed)
% prm - [] param struct
% .color - ['g'] color for curve
% .lineSt - ['-'] linestyle (see LineSpec)
% .lineWd - [4] curve width
% .logx - [0] use logarithmic scale for x-axis
% .logy - [0] use logarithmic scale for y-axis
% .marker - [''] marker type (see LineSpec)
% .mrkrSiz - [12] marker size
% .nMarker - [5] number of markers (regularly spaced) to display
% .lims - [0 1 0 1] axes limits
% .smooth - [0] if T compute lower envelop of roc to smooth staircase
% .fpTarget - [] return miss rates at given fp values (and draw lines)
% .xLbl - ['false positive rate'] label for x-axis
% .yLbl - ['miss rate'] label for y-axis
%
% OUTPUTS
% h - plot handle for use in legend only
% miss - average miss rates at fpTarget reference values
% stds - standard deviation of miss rates at fpTarget reference values
%
% EXAMPLE
% k=2; x=0:.0001:1; data1 = [1-x; (1-x.^k).^(1/k)]';
% k=3; x=0:.0001:1; data2 = [1-x; (1-x.^k).^(1/k)]';
% hs(1)=plotRoc(data1,struct('color','g','marker','s'));
% hs(2)=plotRoc(data2,struct('color','b','lineSt','--'));
% legend( hs, {'roc1','roc2'} ); xlabel('fp'); ylabel('fn');
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.02
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get params
[color,lineSt,lineWd,logx,logy,marker,mrkrSiz,nMarker,lims,smooth, ...
fpTarget,xLbl,yLbl] = getPrmDflt( varargin, {'color' 'g' 'lineSt' '-' ...
'lineWd' 4 'logx' 0 'logy' 0 'marker' '' 'mrkrSiz' 12 'nMarker' 5 ...
'lims' [] 'smooth' 0 'fpTarget' [] 'xLbl' 'false positive rate' ...
'yLbl' 'miss rate' } );
if( isempty(lims) ); lims=[logx*1e-5 1 logy*1e-5 1]; end
% ensure descending fp rate, change to miss rate, optionally 'nicefy' roc
if(~iscell(D)), D={D}; end; nD=length(D);
for j=1:nD, assert(size(D{j},2)==2); end
for j=1:nD, if(D{j}(1,2)<D{j}(end,2)), D{j}=flipud(D{j}); end; end
for j=1:nD, D{j}(:,2)=1-D{j}(:,2); assert(all(D{j}(:,2)>=0)); end
if(smooth), for j=1:nD, D{j}=smoothRoc(D{j}); end; end
% plot: (1) h for legend only, (2) markers, (3) error bars, (4) roc curves
hold on; axis(lims); xlabel(xLbl); ylabel(yLbl);
prmMrkr = {'MarkerSize',mrkrSiz,'MarkerFaceColor',color};
prmClr={'Color',color}; prmPlot = [prmClr,{'LineWidth',lineWd}];
h = plot( 2, 0, [lineSt marker], prmMrkr{:}, prmPlot{:} ); %(1)
DQ = quantizeRocs( D, nMarker, logx, lims ); DQm=mean(DQ,3);
if(~isempty(marker))
plot(DQm(:,1),DQm(:,2),marker,prmClr{:},prmMrkr{:} ); end %(2)
if(nD>1), DQs=std(DQ,0,3);
errorbar(DQm(:,1),DQm(:,2),DQs(:,2),'.',prmClr{:}); end %(3)
if(nD==1), DQ=D{1}; else DQ=quantizeRocs(D,100,logx,lims); end
DQm = mean(DQ,3); plot( DQm(:,1), DQm(:,2), lineSt, prmPlot{:} ); %(4)
% plot line at given fp rate
m=length(fpTarget); miss=zeros(1,m); stds=miss;
if( m>0 )
assert( min(DQm(:,1))<=min(fpTarget) ); DQs=std(DQ,0,3);
for i=1:m, j=find(DQm(:,1)<=fpTarget(i)); j=j(1);
miss(i)=DQm(j,2); stds(i)=DQs(j,2); end
fp=min(fpTarget); plot([fp fp],lims(3:4),'Color',.7*[1 1 1]);
fp=max(fpTarget); plot([fp fp],lims(3:4),'Color',.7*[1 1 1]);
end
% set log axes
if( logx==1 )
ticks=10.^(-8:8);
set(gca,'XScale','log','XTick',ticks);
end
if( logy==1 )
ticks=[.001 .002 .005 .01 .02 .05 .1 .2 .5 1];
set(gca,'YScale','log','YTick',ticks);
end
if( logx==1 || logy==1 ), grid on;
set(gca,'XMinorGrid','off','XMinorTic','off');
set(gca,'YMinorGrid','off','YMinorTic','off');
end
end
function DQ = quantizeRocs( Ds, nPnts, logx, lims )
% estimate miss rate at each target fp rate
nD=length(Ds); DQ=zeros(nPnts,2,nD);
if(logx==1), fps=logspace(log10(lims(1)),log10(lims(2)),nPnts);
else fps=linspace(lims(1),lims(2),nPnts); end; fps=flipud(fps');
for j=1:nD, D=[Ds{j}; 0 1]; k=1; fp=D(k,1);
for i=1:nPnts
while( k<size(D,1) && fp>=fps(i) ), k=k+1; fp=D(k,1); end
k0=max(k-1,1); fp0=D(k0,1); assert(fp0>=fp);
if(fp0==fp), r=.5; else r=(fps(i)-fp)/(fp0-fp); end
DQ(i,1,j)=fps(i); DQ(i,2,j)=r*D(k0,2)+(1-r)*D(k,2);
end
end
end
function D1 = smoothRoc( D )
D1 = zeros(size(D));
n = size(D,1); cnt=0;
for i=1:n
isAnkle = (i==1) || (i==n);
if( ~isAnkle )
dP=D1(cnt,:); dC=D(i,:); dN=D(i+1,:);
isAnkle = (dC(1)~=dP(1)) && (dC(2)~=dN(2));
end
if(isAnkle); cnt=cnt+1; D1(cnt,:)=D(i,:); end
end
D1=D1(1:cnt,:);
end
|
github
|
devaib/MXNet-SSD-master
|
simpleCache.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/GT-visualization/toolbox/matlab/simpleCache.m
| 4,098 |
utf_8
|
92df86b0b7e919c9a26388e598e4d370
|
function varargout = simpleCache( op, cache, varargin )
% A simple cache that can be used to store results of computations.
%
% Can save and retrieve arbitrary values using a vector (includnig char
% vectors) as a key. Especially useful if a function must perform heavy
% computation but is often called with the same inputs (for which it will
% give the same outputs). Note that the current implementation does a
% linear search for the key (a more refined implementation would use a hash
% table), so it is not meant for large scale usage.
%
% To use inside a function, make the cache persistent:
% persistent cache; if( isempty(cache) ) cache=simpleCache('init'); end;
% The following line, when placed inside a function, means the cache will
% stay in memory until the matlab environment changes. For an example
% usage see maskGaussians.
%
% USAGE - 'init': initialize a cache object
% cache = simpleCache('init');
%
% USAGE - 'put': put something in cache. key must be a numeric vector
% cache = simpleCache( 'put', cache, key, val );
%
% USAGE - 'get': retrieve from cache. found==1 if obj was found
% [found,val] = simpleCache( 'get', cache, key );
%
% USAGE - 'remove': free key
% [cache,found] = simpleCache( 'remove', cache, key );
%
% INPUTS
% op - 'init', 'put', 'get', 'remove'
% cache - the cache object being operated on
% varargin - see USAGE above
%
% OUTPUTS
% varargout - see USAGE above
%
% EXAMPLE
% cache = simpleCache('init');
% hellokey=rand(1,3); worldkey=rand(1,11);
% cache = simpleCache( 'put', cache, hellokey, 'hello' );
% cache = simpleCache( 'put', cache, worldkey, 'world' );
% [f,v]=simpleCache( 'get', cache, hellokey ); disp(v);
% [f,v]=simpleCache( 'get', cache, worldkey ); disp(v);
%
% See also PERSISTENT, MASKGAUSSIANS
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
switch op
case 'init' % init a cache
cacheSiz = 8;
cache.freeinds = 1:cacheSiz;
cache.keyns = -ones(1,cacheSiz);
cache.keys = cell(1,cacheSiz);
cache.vals = cell(1,cacheSiz);
varargout = {cache};
case 'put' % a put operation
key=varargin{1}; val=varargin{2};
cache = cacheput( cache, key, val );
varargout = {cache};
case 'get' % a get operation
key=varargin{1};
[ind,val] = cacheget( cache, key );
found = ind>0;
varargout = {found,val};
case 'remove' % a remove operation
key=varargin{1};
[cache,found] = cacheremove( cache, key );
varargout = {cache,found};
otherwise
error('Unknown cache operation: %s',op);
end
end
function cache = cachegrow( cache )
% double cache size
cacheSiz = length( cache.keyns );
if( cacheSiz>64 ) % warn if getting big
warning(['doubling cache size to: ' int2str2(cacheSiz*2)]);%#ok<WNTAG>
end
cache.freeinds = [cache.freeinds (cacheSiz+1):(2*cacheSiz)];
cache.keyns = [cache.keyns -ones(1,cacheSiz)];
cache.keys = [cache.keys cell(1,cacheSiz)];
cache.vals = [cache.vals cell(1,cacheSiz)];
end
function cache = cacheput( cache, key, val )
% put something into the cache
% get location to place
ind = cacheget( cache, key ); % see if already in cache
if( ind==-1 )
if( isempty( cache.freeinds ) )
cache = cachegrow( cache ); %grow cache
end
ind = cache.freeinds(1); % get new cache loc
cache.freeinds = cache.freeinds(2:end);
end
% now simply place in ind
cache.keyns(ind) = length(key);
cache.keys{ind} = key;
cache.vals{ind} = val;
end
function [ind,val] = cacheget( cache, key )
% get cache element, or fail
cacheSiz = length( cache.keyns );
keyn = length( key );
for i=1:cacheSiz
if(keyn==cache.keyns(i) && all(key==cache.keys{i}))
val = cache.vals{i}; ind = i; return; end
end
ind=-1; val=-1;
end
function [cache,found] = cacheremove( cache, key )
% get cache element, or fail
ind = cacheget( cache, key );
found = ind>0;
if( found )
cache.freeinds = [ind cache.freeinds];
cache.keyns(ind) = -1;
cache.keys{ind} = [];
cache.vals{ind} = [];
end
end
|
github
|
devaib/MXNet-SSD-master
|
tpsInterpolate.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/GT-visualization/toolbox/matlab/tpsInterpolate.m
| 1,646 |
utf_8
|
d3bd3a26d048f32cfdc17884ccae6d8c
|
function [xsR,ysR] = tpsInterpolate( warp, xs, ys, show )
% Apply warp (obtained by tpsGetWarp) to a set of new points.
%
% USAGE
% [xsR,ysR] = tpsInterpolate( warp, xs, ys, [show] )
%
% INPUTS
% warp - [see tpsGetWarp] bookstein warping parameters
% xs, ys - points to apply warp to
% show - [1] will display results in figure(show)
%
% OUTPUTS
% xsR, ysR - result of warp applied to xs, ys
%
% EXAMPLE
%
% See also TPSGETWARP
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<4 || isempty(show)); show = 1; end
wx = warp.wx; affinex = warp.affinex;
wy = warp.wy; affiney = warp.affiney;
xsS = warp.xsS; ysS = warp.ysS;
xsD = warp.xsD; ysD = warp.ysD;
% interpolate points (xs,ys)
xsR = f( wx, affinex, xsS, ysS, xs(:)', ys(:)' );
ysR = f( wy, affiney, xsS, ysS, xs(:)', ys(:)' );
% optionally show points (xsR, ysR)
if( show )
figure(show);
subplot(2,1,1); plot( xs, ys, '.', 'color', [0 0 1] );
hold('on'); plot( xsS, ysS, '+' ); hold('off');
subplot(2,1,2); plot( xsR, ysR, '.' );
hold('on'); plot( xsD, ysD, '+' ); hold('off');
end
function zs = f( w, aff, xsS, ysS, xs, ys )
% find f(x,y) for xs and ys given W and original points
n = size(w,1); ns = size(xs,2);
delXs = xs'*ones(1,n) - ones(ns,1)*xsS;
delYs = ys'*ones(1,n) - ones(ns,1)*ysS;
distSq = (delXs .* delXs + delYs .* delYs);
distSq = distSq + eye(size(distSq)) + eps;
U = distSq .* log( distSq ); U( isnan(U) )=0;
zs = aff(1)*ones(ns,1)+aff(2)*xs'+aff(3)*ys';
zs = zs + sum((U.*(ones(ns,1)*w')),2);
|
github
|
devaib/MXNet-SSD-master
|
checkNumArgs.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/GT-visualization/toolbox/matlab/checkNumArgs.m
| 3,796 |
utf_8
|
726c125c7dc994c4989c0e53ad4be747
|
function [ x, er ] = checkNumArgs( x, siz, intFlag, signFlag )
% Helper utility for checking numeric vector arguments.
%
% Runs a number of tests on the numeric array x. Tests to see if x has all
% integer values, all positive values, and so on, depending on the values
% for intFlag and signFlag. Also tests to see if the size of x matches siz
% (unless siz==[]). If x is a scalar, x is converted to a array simply by
% creating a matrix of size siz with x in each entry. This is why the
% function returns x. siz=M is equivalent to siz=[M M]. If x does not
% satisfy some criteria, an error message is returned in er. If x satisfied
% all the criteria er=''. Note that error('') has no effect, so can use:
% [ x, er ] = checkNumArgs( x, ... ); error(er);
% which will throw an error only if something was wrong with x.
%
% USAGE
% [ x, er ] = checkNumArgs( x, siz, intFlag, signFlag )
%
% INPUTS
% x - numeric array
% siz - []: does not test size of x
% - [if not []]: intended size for x
% intFlag - -1: no need for integer x
% 0: error if non integer x
% 1: error if non odd integers
% 2: error if non even integers
% signFlag - -2: entires of x must be strictly negative
% -1: entires of x must be negative
% 0: no contstraints on sign of entries in x
% 1: entires of x must be positive
% 2: entires of x must be strictly positive
%
% OUTPUTS
% x - if x was a scalar it may have been replicated into a matrix
% er - contains error msg if anything was wrong with x
%
% EXAMPLE
% a=1; [a, er]=checkNumArgs( a, [1 3], 2, 0 ); a, error(er)
%
% See also NARGCHK
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
xname = inputname(1); er='';
if( isempty(siz) ); siz = size(x); end;
if( length(siz)==1 ); siz=[siz siz]; end;
% first check that x is numeric
if( ~isnumeric(x) ); er = [xname ' not numeric']; return; end;
% if x is a scalar, simply replicate it.
xorig = x; if( length(x)==1); x = x(ones(siz)); end;
% regardless, must have same number of x as n
if( length(siz)~=ndims(x) || ~all(size(x)==siz) )
er = ['has size = [' num2str(size(x)) '], '];
er = [er 'which is not the required size of [' num2str(siz) ']'];
er = createErrMsg( xname, xorig, er ); return;
end
% check that x are the right type of integers (unless intFlag==-1)
switch intFlag
case 0
if( ~all(mod(x,1)==0))
er = 'must have integer entries';
er = createErrMsg( xname, xorig, er); return;
end;
case 1
if( ~all(mod(x,2)==1))
er = 'must have odd integer entries';
er = createErrMsg( xname, xorig, er); return;
end;
case 2
if( ~all(mod(x,2)==0))
er = 'must have even integer entries';
er = createErrMsg( xname, xorig, er ); return;
end;
end;
% check sign of entries in x (unless signFlag==0)
switch signFlag
case -2
if( ~all(x<0))
er = 'must have strictly negative entries';
er = createErrMsg( xname, xorig, er ); return;
end;
case -1
if( ~all(x<=0))
er = 'must have negative entries';
er = createErrMsg( xname, xorig, er ); return;
end;
case 1
if( ~all(x>=0))
er = 'must have positive entries';
er = createErrMsg( xname, xorig, er ); return;
end;
case 2
if( ~all(x>0))
er = 'must have strictly positive entries';
er = createErrMsg( xname, xorig, er ); return;
end
end
function er = createErrMsg( xname, x, er )
if(numel(x)<10)
er = ['Numeric input argument ' xname '=[' num2str(x) '] ' er '.'];
else
er = ['Numeric input argument ' xname ' ' er '.'];
end
|
github
|
devaib/MXNet-SSD-master
|
fevalDistr.m
|
.m
|
MXNet-SSD-master/matlab/caltechUSA/GT-visualization/toolbox/matlab/fevalDistr.m
| 11,227 |
utf_8
|
7e4d5077ef3d7a891b2847cb858a2c6c
|
function [out,res] = fevalDistr( funNm, jobs, varargin )
% Wrapper for embarrassingly parallel function evaluation.
%
% Runs "r=feval(funNm,jobs{i}{:})" for each job in a parallel manner. jobs
% should be a cell array of length nJob and each job should be a cell array
% of parameters to pass to funNm. funNm must be a function in the path and
% must return a single value (which may be a dummy value if funNm writes
% results to disk). Different forms of parallelization are supported
% depending on the hardware and Matlab toolboxes available. The type of
% parallelization is determined by the parameter 'type' described below.
%
% type='LOCAL': jobs are executed using a simple "for" loop. This implies
% no parallelization and is the default fallback option.
%
% type='PARFOR': jobs are executed using a "parfor" loop. This option is
% only available if the Matlab *Parallel Computing Toolbox* is installed.
% Make sure to setup Matlab workers first using "matlabpool open".
%
% type='DISTR': jobs are executed on the Caltech cluster. Distributed
% queuing system must be installed separately. Currently this option is
% only supported on the Caltech cluster but could easily be installed on
% any Linux cluster as it requires only SSH and a shared filesystem.
% Parameter pLaunch is used for controller('launchQueue',pLaunch{:}) and
% determines cluster machines used (e.g. pLaunch={48,401:408}).
%
% type='COMPILED': jobs are executed locally in parallel by first compiling
% an executable and then running it in background. This option requires the
% *Matlab Compiler* to be installed (but does NOT require the Parallel
% Computing Toolbox). Compiling can take 1-10 minutes, so use this option
% only for large jobs. (On Linux alter startup.m by calling addpath() only
% if ~isdeployed, otherwise will get error about "CTF" after compiling).
% Note that relative paths will not work after compiling so all paths used
% by funNm must be absolute paths.
%
% type='WINHPC': jobs are executed on a Windows HPC Server 2008 cluster.
% Similar to type='COMPILED', except after compiling, the executable is
% queued to the HPC cluster where all computation occurs. This option
% likewise requires the *Matlab Compiler*. Paths to data, etc., must be
% absolute paths and available from HPC cluster. Parameter pLaunch must
% have two fields 'scheduler' and 'shareDir' that define the HPC Server.
% Extra parameters in pLaunch add finer control, see fedWinhpc for details.
% For example, at MSR one possible cluster is defined by scheduler =
% 'MSR-L25-DEV21' and shareDir = '\\msr-arrays\scratch\msr-pool\L25-dev21'.
% Note call to 'job submit' from Matlab will hang unless pwd is saved
% (simply call 'job submit' from cmd prompt and enter pwd).
%
% USAGE
% [out,res] = fevalDistr( funNm, jobs, [varargin] )
%
% INPUTS
% funNm - name of function that will process jobs
% jobs - [1xnJob] cell array of parameters for each job
% varargin - additional params (struct or name/value pairs)
% .type - ['local'], 'parfor', 'distr', 'compiled', 'winhpc'
% .pLaunch - [] extra params for type='distr' or type='winhpc'
% .group - [1] send jobs in batches (only relevant if type='distr')
%
% OUTPUTS
% out - 1 if jobs completed successfully
% res - [1xnJob] cell array containing results of each job
%
% EXAMPLE
% % Note: in this case parallel versions are slower since conv2 is so fast
% n=16; jobs=cell(1,n); for i=1:n, jobs{i}={rand(500),ones(25)}; end
% tic, [out,J1] = fevalDistr('conv2',jobs,'type','local'); toc,
% tic, [out,J2] = fevalDistr('conv2',jobs,'type','parfor'); toc,
% tic, [out,J3] = fevalDistr('conv2',jobs,'type','compiled'); toc
% [isequal(J1,J2), isequal(J1,J3)], figure(1); montage2(cell2array(J1))
%
% See also matlabpool mcc
%
% Piotr's Computer Vision Matlab Toolbox Version 3.26
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
dfs={'type','local','pLaunch',[],'group',1};
[type,pLaunch,group]=getPrmDflt(varargin,dfs,1); store=(nargout==2);
if(isempty(jobs)), res=cell(1,0); out=1; return; end
switch lower(type)
case 'local', [out,res]=fedLocal(funNm,jobs,store);
case 'parfor', [out,res]=fedParfor(funNm,jobs,store);
case 'distr', [out,res]=fedDistr(funNm,jobs,pLaunch,group,store);
case 'compiled', [out,res]=fedCompiled(funNm,jobs,store);
case 'winhpc', [out,res]=fedWinhpc(funNm,jobs,pLaunch,store);
otherwise, error('unkown type: ''%s''',type);
end
end
function [out,res] = fedLocal( funNm, jobs, store )
% Run jobs locally using for loop.
nJob=length(jobs); res=cell(1,nJob); out=1;
tid=ticStatus('collecting jobs');
for i=1:nJob, r=feval(funNm,jobs{i}{:});
if(store), res{i}=r; end; tocStatus(tid,i/nJob); end
end
function [out,res] = fedParfor( funNm, jobs, store )
% Run jobs locally using parfor loop.
nJob=length(jobs); res=cell(1,nJob); out=1;
parfor i=1:nJob, r=feval(funNm,jobs{i}{:});
if(store), res{i}=r; end; end
end
function [out,res] = fedDistr( funNm, jobs, pLaunch, group, store )
% Run jobs using Linux queuing system.
if(~exist('controller.m','file'))
msg='distributed queuing not installed, switching to type=''local''.';
warning(msg); [out,res]=fedLocal(funNm,jobs,store); return; %#ok<WNTAG>
end
nJob=length(jobs); res=cell(1,nJob); controller('launchQueue',pLaunch{:});
if( group>1 )
nJobGrp=ceil(nJob/group); jobsGrp=cell(1,nJobGrp); k=0;
for i=1:nJobGrp, k1=min(nJob,k+group);
jobsGrp{i}={funNm,jobs(k+1:k1),'type','local'}; k=k1; end
nJob=nJobGrp; jobs=jobsGrp; funNm='fevalDistr';
end
jids=controller('jobsAdd',nJob,funNm,jobs); k=0;
fprintf('Sent %i jobs...\n',nJob); tid=ticStatus('collecting jobs');
while( 1 )
jids1=controller('jobProbe',jids);
if(isempty(jids1)), pause(.1); continue; end
jid=jids1(1); [r,err]=controller('jobRecv',jid);
if(~isempty(err)), disp('ABORTING'); out=0; break; end
k=k+1; if(store), res{jid==jids}=r; end
tocStatus(tid,k/nJob); if(k==nJob), out=1; break; end
end; controller('closeQueue');
end
function [out,res] = fedCompiled( funNm, jobs, store )
% Run jobs locally in background in parallel using compiled code.
nJob=length(jobs); res=cell(1,nJob); tDir=jobSetup('.',funNm,'',{});
cmd=[tDir 'fevalDistrDisk ' funNm ' ' tDir ' ']; i=0; k=0;
Q=feature('numCores'); q=0; tid=ticStatus('collecting jobs');
while( 1 )
% launch jobs until queue is full (q==Q) or all jobs launched (i==nJob)
while(q<Q && i<nJob), q=q+1; i=i+1; jobSave(tDir,jobs{i},i);
if(ispc), system2(['start /B /min ' cmd int2str2(i,10)],0);
else system2([cmd int2str2(i,10) ' &'],0); end
end
% collect completed jobs (k1 of them), release queue slots
done=jobFileIds(tDir,'done'); k1=length(done); k=k+k1; q=q-k1;
for i1=done, res{i1}=jobLoad(tDir,i1,store); end
pause(1); tocStatus(tid,k/nJob); if(k==nJob), out=1; break; end
end
for i=1:10, try rmdir(tDir,'s'); break; catch,pause(1),end; end %#ok<CTCH>
end
function [out,res] = fedWinhpc( funNm, jobs, pLaunch, store )
% Run jobs using Windows HPC Server.
nJob=length(jobs); res=cell(1,nJob);
dfs={'shareDir','REQ','scheduler','REQ','executable','fevalDistrDisk',...
'mccOptions',{},'coresPerTask',1,'minCores',1024,'priority',2000};
p = getPrmDflt(pLaunch,dfs,1);
tDir = jobSetup(p.shareDir,funNm,p.executable,p.mccOptions);
for i=1:nJob, jobSave(tDir,jobs{i},i); end
hpcSubmit(funNm,1:nJob,tDir,p); k=0;
ticId=ticStatus('collecting jobs');
while( 1 )
done=jobFileIds(tDir,'done'); k=k+length(done);
for i1=done, res{i1}=jobLoad(tDir,i1,store); end
pause(5); tocStatus(ticId,k/nJob); if(k==nJob), out=1; break; end
end
for i=1:10, try rmdir(tDir,'s'); break; catch,pause(5),end; end %#ok<CTCH>
end
function tids = hpcSubmit( funNm, ids, tDir, pLaunch )
% Helper: send jobs w given ids to HPC cluster.
n=length(ids); tids=cell(1,n); if(n==0), return; end;
scheduler=[' /scheduler:' pLaunch.scheduler ' '];
m=system2(['cluscfg view' scheduler],0);
minCores=(hpcParse(m,'total number of nodes',1) - ...
hpcParse(m,'Unreachable nodes',1) - 1)*8;
minCores=min([minCores pLaunch.minCores n*pLaunch.coresPerTask]);
m=system2(['job new /numcores:' int2str(minCores) '-*' scheduler ...
'/priority:' int2str(pLaunch.priority)],1);
jid=hpcParse(m,'created job, id',0);
s=min(ids); e=max(ids); p=n>1 && isequal(ids,s:e);
if(p), jid1=[jid '.1']; else jid1=jid; end
for i=1:n, tids{i}=[jid1 '.' int2str(i)]; end
cmd0=''; if(p), cmd0=['/parametric:' int2str(s) '-' int2str(e)]; end
cmd=@(id) ['job add ' jid scheduler '/workdir:' tDir ' /numcores:' ...
int2str(pLaunch.coresPerTask) ' ' cmd0 ' /stdout:stdout' id ...
'.txt ' pLaunch.executable ' ' funNm ' ' tDir ' ' id];
if(p), ids1='*'; n=1; else ids1=int2str2(ids); end
if(n==1), ids1={ids1}; end; for i=1:n, system2(cmd(ids1{i}),1); end
system2(['job submit /id:' jid scheduler],1); disp(repmat(' ',1,80));
end
function v = hpcParse( msg, key, tonum )
% Helper: extract val corresponding to key in hpc msg.
t=regexp(msg,': |\n','split'); t=strtrim(t(1:floor(length(t)/2)*2));
keys=t(1:2:end); vals=t(2:2:end); j=find(strcmpi(key,keys));
if(isempty(j)), error('key ''%s'' not found in:\n %s',key,msg); end
v=vals{j}; if(tonum==0), return; elseif(isempty(v)), v=0; return; end
if(tonum==1), v=str2double(v); return; end
v=regexp(v,' ','split'); v=str2double(regexp(v{1},':','split'));
if(numel(v)==4), v(5)=0; end; v=((v(1)*24+v(2))*60+v(3))*60+v(4)+v(5)/1000;
end
function tDir = jobSetup( rtDir, funNm, executable, mccOptions )
% Helper: prepare by setting up temporary dir and compiling funNm
t=clock; t=mod(t(end),1); t=round((t+rand)/2*1e15);
tDir=[rtDir filesep sprintf('fevalDistr-%015i',t) filesep]; mkdir(tDir);
if(~isempty(executable) && exist(executable,'file'))
fprintf('Reusing compiled executable...\n'); copyfile(executable,tDir);
else
t=clock; fprintf('Compiling (this may take a while)...\n');
[~,f,e]=fileparts(executable); if(isempty(f)), f='fevalDistrDisk'; end
mcc('-m','fevalDistrDisk','-d',tDir,'-o',f,'-a',funNm,mccOptions{:});
t=etime(clock,t); fprintf('Compile complete (%.1f seconds).\n',t);
if(~isempty(executable)), copyfile([tDir filesep f e],executable); end
end
end
function ids = jobFileIds( tDir, type )
% Helper: get list of job files ids on disk of given type
fs=dir([tDir '*-' type '*']); fs={fs.name}; n=length(fs);
ids=zeros(1,n); for i=1:n, ids(i)=str2double(fs{i}(1:10)); end
end
function jobSave( tDir, job, ind ) %#ok<INUSL>
% Helper: save job to temporary file for use with fevalDistrDisk()
save([tDir int2str2(ind,10) '-in'],'job');
end
function r = jobLoad( tDir, ind, store )
% Helper: load job and delete temporary files from fevalDistrDisk()
f=[tDir int2str2(ind,10)];
if(store), r=load([f '-out']); r=r.r; else r=[]; end
fs={[f '-done'],[f '-in.mat'],[f '-out.mat']};
delete(fs{:}); pause(.1);
for i=1:3, k=0; while(exist(fs{i},'file')==2) %#ok<ALIGN>
warning('Waiting to delete %s.',fs{i}); %#ok<WNTAG>
delete(fs{i}); pause(5); k=k+1; if(k>12), break; end;
end; end
end
function msg = system2( cmd, show )
% Helper: wraps system() call
if(show), disp(cmd); end
[status,msg]=system(cmd); msg=msg(1:end-1);
if(status), error(msg); end
if(show), disp(msg); end
end
|
github
|
haoranleo/Super-Resolution-Image-Reconstruction-master
|
generation.m
|
.m
|
Super-Resolution-Image-Reconstruction-master/generation.m
| 19,112 |
utf_8
|
9384a8218695302ca4b4883159523357
|
function varargout = generation(varargin)
% GENERATION - GUI for creating low resolution images from an input image
% varargout = generation(varargin)
% graphical user interface used to create a number of shifted and
% rotated low resolution images from a single high resolution input
% image
%% -----------------------------------------------------------------------
% SUPERRESOLUTION - Graphical User Interface for Super-Resolution Imaging
% Copyright (C) 2005-2007 Laboratory of Audiovisual Communications (LCAV),
% Ecole Polytechnique Federale de Lausanne (EPFL),
% CH-1015 Lausanne, Switzerland
%
% This program is free software; you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by the
% Free Software Foundation; either version 2 of the License, or (at your
% option) any later version. This software is distributed in the hope that
% it will be useful, but without any warranty; without even the implied
% warranty of merchantability or fitness for a particular purpose.
% See the GNU General Public License for more details
% (enclosed in the file GPL).
%
% Latest modifications: August, 2005, by Patrick Zbinden
% January 12, 2006, by Patrick Vandewalle
% November 6, 2006 by Karim Krichane
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @generation_OpeningFcn, ...
'gui_OutputFcn', @generation_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 generation is made visible.
function generation_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 generation (see VARARGIN)
global PARAMSGIVEN;
global PARAMSGIVENBYUSER;
global DESTGIVEN;
global NAME;
NAME = [];
DESTGIVEN = false;
PARAMSGIVEN = false;
PARAMSGIVENBYUSER = {};
% Choose default command line output for generation
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes generation wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = generation_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;
%%%%%%%%%%%%%%%%%%%%%%%%%
% Generate input images %
%%%%%%%%%%%%%%%%%%%%%%%%%
function generateInputImages(handles)
global INPUTIMAGE;
global PARAMSGIVEN;
global PARAMSGIVENBYUSER;
global DESTGIVEN;
global NAME;
im = INPUTIMAGE;
% multiply the image with a Tukey window to make it circularly symmetric
% and add zeros at the borders
autoSave = get(handles.autoSaveCheckbox,'Value');
tempPath = get(handles.text9,'String');
if (get(handles.checkbox1, 'Value') == 1)
s_im=size(im);
w1=window(@tukeywin,s_im(1),0.25);
w2=window(@tukeywin,s_im(2),0.25)';
w=w1*w2;
if(size(im,3) == 3)
% color image
for i=1:3
im2(:,:,i) = [zeros(32,s_im(2)+64); zeros(s_im(1),32) im(:,:,i).*w zeros(s_im(1),32); zeros(32,s_im(2)+64)];
end
im = im2;
else
% black image
im = [zeros(32,s_im(2)+64); zeros(s_im(1),32) im.*w zeros(s_im(1),32); zeros(32,s_im(2)+64)];
end
clear w w1 w2;
end
% set shift and rotation parameters to fixed numbers
strings = get(handles.popupmenu1,'String');
selected = str2double(strings{get(handles.popupmenu1,'Value')});
if (PARAMSGIVEN == true)
delta = [PARAMSGIVENBYUSER{2} PARAMSGIVENBYUSER{3}];
phi = PARAMSGIVENBYUSER{1};
else
delta = rand(selected,2); %[0 0; 3.125 -1.875; 0.875 2.25; -1.5 0.5];
phi = rand(1,selected); %[0 5 -3 2];
end
% construct the low resolution shifted and rotated images from the original
% image
IMAGESCREATED = false;
if(size(im,3) == 3)
% color image
for i=1:3
[s{i}, im_target] = create_images(im(:,:,i),delta,phi,4,selected);
end
close;
for i=1:selected
for j=1:3
titi(:,:,j) = s{j}{i};
end
% Save images in files if corresponding option is checked
if (autoSave)
imageName = [NAME '_LR_' num2str(i) '.tif'];
if(DESTGIVEN)
imwrite(titi, [tempPath '/' imageName]);
CIPATH = tempPath;
CINAMES{i} = imageName;
IMAGESCREATED = true;
else
imwrite(titi, imageName);
CIPATH = pwd;
CINAMES{i} = imageName;
IMAGESCREATED = true;
end
else
figure;
imshow(titi);
end
end
else
% black image
[s, im_target] = create_images(im,delta,phi,4,selected);
close;
for i=1:selected
if (autoSave)
imageName = [NAME '_LR_' num2str(i) '.tif'];
if(DESTGIVEN)
imwrite(s{i}, [tempPath '/' imageName]);
CIPATH = tempPath;
CINAMES{i} = imageName;
IMAGESCREATED = true;
else
imwrite(s{i}, imageName);
CIPATH = pwd;
CINAMES{i} = imageName;
IMAGESCREATED = true;
end
else
figure;
imshow(s{i});
end
end
end
if IMAGESCREATED
save CIPATH;
save CINAMES;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Enter the motion parameters %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function parametersGivenByUser = enterParameters(handles, imagesNumber)
global PARAMSGIVEN;
parametersGivenByUser = {};
tempTest = true;
tempRotations = {};
tempTranslationx = {};
tempTranslationy = {};
canceled = false;
% getting the rotation parameters
for i=1:imagesNumber
prompt(i) = {strcat('Rotation image', int2str(i))};
end
title = 'Please, enter the rotation parameters';
lines = 1;
tempRotations = inputdlg(prompt,title,lines);
% test rotation parameters
if size(tempRotations,1) > 0
for i=1:size(tempRotations,1)
if(size(tempRotations{i},1) == 0 | str2num(tempRotations{i}) > 10 | str2num(tempRotations{i}) < -10)
tempTest = false;
end
end
if(tempTest)
parametersGivenByUser{1} = tempRotations;
end
else
tempTest = false;
canceled = true;
end
% getting the x translation parameters
if(tempTest)
for i=1:imagesNumber
prompt(i) = {strcat('Translation x of image', int2str(i))};
end
title = 'Please, enter the translation x parameters';
lines = 1;
tempTranslationx = inputdlg(prompt,title,lines);
% test rotation parameters
if size(tempTranslationx,1) > 0
for i=1:size(tempTranslationx,1)
if(size(tempTranslationx{i},1) == 0 | str2num(tempTranslationx{i}) > 10 | str2num(tempTranslationx{i}) < -10)
tempTest = false;
end
end
if(tempTest)
parametersGivenByUser{2} = tempTranslationx;
end
else
tempTest = false;
canceled = true;
end
end
% getting the y translation parameters
if(tempTest)
for i=1:imagesNumber
prompt(i) = {strcat('Translation y of image', int2str(i))};
end
title = 'Please, enter the translation y parameters';
lines = 1;
tempTranslationy = inputdlg(prompt,title,lines);
% test translation y parameters
if size(tempTranslationy,1) > 0
for i=1:size(tempTranslationy,1)
if(size(tempTranslationy{i},1) == 0 | str2num(tempTranslationy{i}) > 10 | str2num(tempTranslationy{i}) < -10)
tempTest = false;
end
end
if(tempTest)
parametersGivenByUser{3} = tempTranslationy;
end
else
tempTest = false;
canceled = true;
end
end
if(tempTest)
set(handles.listbox3, 'String', parametersGivenByUser{1});
set(handles.listbox1, 'String', parametersGivenByUser{2});
set(handles.listbox2, 'String', parametersGivenByUser{3});
for i=1:imagesNumber
phi(i) = str2num(parametersGivenByUser{1}{i});
deltax(i,1) = str2num(parametersGivenByUser{2}{i});
deltay(i,1) = str2num(parametersGivenByUser{3}{i});
end
parametersGivenByUser{1} = phi;
parametersGivenByUser{2} = deltax;
parametersGivenByUser{3} = deltay;
parametersGivenByUser;
PARAMSGIVEN = true;
else
if (size(tempRotations,1) > 0 & (canceled == false))
errordlg('One parameter in not correct');
parametersGivenByUser = {};
end
end
% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns popupmenu1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu1
% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on button press in checkbox1.
function checkbox1_Callback(hObject, eventdata, handles)
% hObject handle to checkbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox1
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
generateInputImages(handles);
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
uiresume();
close;
% --- Executes on selection change in listbox3.
function listbox3_Callback(hObject, eventdata, handles)
% hObject handle to listbox3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns listbox3 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox3
% --- Executes during object creation, after setting all properties.
function listbox3_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns listbox1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox1
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in listbox2.
function listbox2_Callback(hObject, eventdata, handles)
% hObject handle to listbox2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns listbox2 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox2
% --- Executes during object creation, after setting all properties.
function listbox2_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global PARAMSGIVENBYUSER;
strings = get(handles.popupmenu1,'String');
selected = str2double(strings{get(handles.popupmenu1,'Value')});
PARAMSGIVENBYUSER = enterParameters(handles, selected);
% Random radio
% --- Executes on button press in radiobutton2.
function radiobutton2_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton2
set(handles.text6, 'Enable', 'on');
set(handles.text3, 'Enable', 'off');
set(handles.text5, 'Enable', 'off');
set(handles.text4, 'Enable', 'off');
set(handles.listbox3, 'Enable', 'off');
set(handles.listbox2, 'Enable', 'off');
set(handles.listbox1, 'Enable', 'off');
set(handles.pushbutton3, 'Enable', 'off');
% Perdonal radio
% --- Executes on button press in radiobutton1.
function radiobutton1_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton1
set(handles.text6, 'Enable', 'off');
set(handles.text3, 'Enable', 'on');
set(handles.text5, 'Enable', 'on');
set(handles.text4, 'Enable', 'on');
set(handles.listbox3, 'Enable', 'on');
set(handles.listbox2, 'Enable', 'on');
set(handles.listbox1, 'Enable', 'on');
set(handles.pushbutton3, 'Enable', 'on');
% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% read image from file
global INPUTIMAGE;
global NAME;
[fileName,pathName] = uigetfile({'*.tif'; '*.jpg'; '*.bmp'}, 'Choose the source image');
NAME = fileName(1:end-4);
if(size(fileName,2)>3)
im = double(imread(strcat(pathName, fileName)));
info = imfinfo([pathName fileName]);
im = double(im)/(2^(info.BitDepth/size(im, 3)));
INPUTIMAGE = im;
set(handles.text8, 'String', [pathName fileName]);
set(handles.radiobutton2, 'Enable', 'on');
set(handles.radiobutton1, 'Enable', 'on');
set(handles.text6, 'Enable', 'on');
set(handles.pushbutton1, 'Enable', 'on');
else
set(handles.text8, 'String', 'No image');
set(handles.radiobutton2, 'Enable', 'off');
set(handles.radiobutton1, 'Enable', 'off');
set(handles.text6, 'Enable', 'off');
set(handles.pushbutton1, 'Enable', 'off');
end
% --- Executes on button press in autoSaveCheckbox.
function autoSaveCheckbox_Callback(hObject, eventdata, handles)
% hObject handle to autoSaveCheckbox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of autoSaveCheckbox
% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global DESTGIVEN;
dest_temp = uigetdir('Choose the destination directory');
if length(dest_temp)>2
set(handles.text9, 'String', dest_temp);
DESTGIVEN = true;
end
% --- Executes during object creation, after setting all properties.
function back_CreateFcn(hObject, eventdata, handles)
% hObject handle to back (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: place code in OpeningFcn to populate back
ha=axes('units','normalized','position',[0 0 1 1]);
uistack(ha,'down')
II=imread('background.jpg');
image(II)
colormap gray
set(ha,'handlevisibility','off','visible','off');
|
github
|
xuewenfei/EducationAlgorithms-master
|
ex02_java.m
|
.m
|
EducationAlgorithms-master/THEALGORITHMS/IRT_Resources/oscats-0.6 2/examples/ex02_java.m
| 6,274 |
utf_8
|
87438e3f75b8e3c0a32b96e231be8b6f
|
% OSCATS: Open-Source Computerized Adaptive Testing System
% Copyright 2011 Michael Culbertson <[email protected]>
%
% Example 2
%
% Example 2
%
% 500 Items: 2D 2PL with covariate
% a1 ~ U(0, 1), a2 ~ U(0, 2), b ~ N(0,3), covariate coef ~ U(0.5, 1.5)
% 500 Examinees on each point of the grid {-1, 0, 1} x {-1, 0, 1}
% Examinee covariate ~ N(0, 1)
% Item selection:
% - A-optimality
% - D-optimality
% - KL
% Test length: 20
% Report:
% - Mean Euclidian distance between estimated and simulated theta,
% calculated for each grid point
function ex02_java()
%% Add glib.jar and oscats.jar to class path
%javaaddpath('../bindings/java/glib.jar');
%javaaddpath('../bindings/java/oscats.jar');
%% Note that the path to libglibjni and liboscatsjni
%% must be in Matlab's toolbox/local/librarypath.txt
import oscats.Space;
import oscats.Point;
import oscats.Examinee;
import oscats.Test;
N_EXAMINEES = 500;
N_ITEMS = 500;
LEN = 20;
COVARIATE_NAME = 'MyCovariate';
%/ Helper function to calculate the Euclidian distance between two points
function ret = distance(a, b)
d1 = a.getCont(dims(1)) - b.getCont(dims(1));
d2 = a.getCont(dims(2)) - b.getCont(dims(2));
ret = sqrt(d1*d1 + d2*d2);
end
% We will have to tell the models which covariate to use. This is done by
% supplying an OscatsCovariates object that includes only that covariate to
% be included in the model. In this case, all of our items will use the
% same covariate. We'll create the OscatsCovariates object below when we
% create the latent space, and pass both to the gen_items() function.
function ret = gen_items(space, covariate, dims)
import oscats.ItemBank
import oscats.ModelL2p
import oscats.Item
% Create an item bank to store the items.
% Setting the property "sizeHint" increases allocation efficiency.
bank = ItemBank(N_ITEMS);
% Create the items
for k = 1:N_ITEMS
% First we create an IRT model container for our item
% We have to specify which dimensions to be used with the "dims" array
% (in this case, we use both of the dimensions of the space)
model = ModelL2p(space, dims, covariate);
% Then, set the parameters. Here there are 4:
% Discrimination on two dimensions, difficulty, and covariate coef.
model.setParamByName('Diff', oscats.Random.normal(sqrt(3)));
model.setParamByName('Discr.Cont.1', oscats.Random.uniformRange(0, 1));
model.setParamByName('Discr.Cont.2', oscats.Random.uniformRange(0, 2));
model.setParamByName(COVARIATE_NAME, oscats.Random.uniformRange(0.5, 1.5));
% Create an item based on this model (as default model)
item = Item(model);
% Add the item to the item bank
bank.addItem(item);
% Since Java and Matlab are garbage collected, we don't have to worry
% about reference counting.
end
ret = bank;
end
%% main
num_tests = 3; num_grid = 3;
test_names = { 'A-opt', 'D-opt', 'KL' };
grid = [ -1 0 1 ];
test = javaArray('oscats.Test', num_tests);
% Create the latent space for the test: 2 continuous dimensions
space = oscats.Space(2, 0);
% Fetch the first and second continuous dimensions via the default names
dims = [ space.getDim('Cont.1') space.getDim('Cont.2') ];
% reate the covariate
covariate = oscats.Covariates();
covariate.set(COVARIATE_NAME, 0);
% "covariate" variable now includes one covariate called "MyCovariate"
% It's current value is 0.
% Set up space for error calculation
err_sums = zeros(num_tests, num_grid*num_grid);
disp('Creating items.');
bank = gen_items(space, covariate, dims);
disp('Creating tests.');
for j = 1:num_tests
% Create a new test with the given properties
% In this case, we know what the length of the test will be (30),
% so, we set length_hint for allocation efficiency.
% Any good/reasonable guess will do---the size will be adjusted
% automatically as necessary.
test(j) = Test(test_names(j), bank, LEN);
% Register the CAT algorithms for this test.
% A test must have at minimum a selection algorithm, and administration
% algorithm, and a stoping critierion.
oscats.AlgSimulate().register(test(j));
oscats.AlgEstimate(5).register(test(j));
alg = oscats.AlgFixedLength.createAlgFixedLength(LEN);
alg.register(test(j));
end
% Here we register the item selection criteria for the different tests
alg = oscats.AlgMaxFisher.createAlgMaxFisher(true, 5);
alg.register(test(1));
alg = oscats.AlgMaxFisher.createAlgMaxFisher(5);
alg.register(test(2));
alg = oscats.AlgMaxKl.createAlgMaxKl(5);
alg.register(test(3));
% In Example 1, we created OscatsExaminee objects for each examinee.
% Here, we'll just use one object over again for each administration.
e = Examinee(covariate);
sim_theta = Point(space);
est_theta = Point(space);
e.setSimTheta(sim_theta);
e.setEstTheta(est_theta);
disp('Administering.');
for I = 1:num_grid
sim_theta.setCont(dims(1), grid(I));
for J = 1:num_grid
fprintf('At grid point (%g, %g) ...\n', grid(I), grid(J));
sim_theta.setCont(dims(2), grid(J));
for i = 1:N_EXAMINEES
% "covariate" is the same OscatsCovariates object used by "e"
covariate.set(COVARIATE_NAME, oscats.Random.normal(1));
fprintf('%d\r', i); % System.out.flush();
for j = 1:num_tests
% Reset initial theta: Random start ~ N_2(0, I_2)
est_theta.setCont(dims(1), oscats.Random.normal(1));
est_theta.setCont(dims(2), oscats.Random.normal(1));
% Administer the test
test(j).administer(e);
% Calculate error (Euclidean distance between sim/est theta)
err_sums(j, (I-1)*num_grid+J) = err_sums(j, (I-1)*num_grid+J) + distance(sim_theta, est_theta);
end
end
end
end
% Report results
f = fopen('ex02-results.txt', 'w');
fprintf(f, 'D1\tD2');
for i = 1:num_tests
fprintf(f, '\t%s', test_names{i});
end
fprintf(f, '\n');
for I = 1:num_grid
for J = 1:num_grid
fprintf(f, '%g\t%g', grid(I), grid(J));
for i = 1:num_tests
fprintf(f, '\t%g', err_sums(i, (I-1)*num_grid+J)/N_EXAMINEES);
end
fprintf(f, '\n');
end
end
fclose(f);
% No clean up necessary, since Java and Matlab are garbage collected.
disp('Done.');
end
|
github
|
xuewenfei/EducationAlgorithms-master
|
ex01_java.m
|
.m
|
EducationAlgorithms-master/THEALGORITHMS/IRT_Resources/oscats-0.6 2/examples/ex01_java.m
| 5,859 |
utf_8
|
0f8a8a8738518e1dde827c23b300aae4
|
% OSCATS: Open-Source Computerized Adaptive Testing System
% Copyright 2010, 2011 Michael Culbertson <[email protected]>
%
% Example 1
%
% 400 Items: 1PL, b ~ N(0,1)
% 1000 Examinees: theta ~ N(0,1)
% Item selection:
% - pick randomly
% - match theta with b, exactly
% - match theta with b, randomize 5, 10 items
% Test length: 30
% Report:
% - theta.hat, Item exposure
function ex01_java()
%% Add glib.jar and oscats.jar to class path
%javaaddpath('../bindings/java/glib.jar');
%javaaddpath('../bindings/java/oscats.jar');
%% Note that the path to libglibjni and liboscatsjni
%% must be in Matlab's toolbox/local/librarypath.txt
import oscats.Space;
import oscats.Point;
import oscats.Examinee;
import oscats.Test;
import oscats.AlgExposureCounter;
N_EXAMINEES = 1000;
N_ITEMS = 400;
LEN = 30;
function ret = gen_items(space)
import oscats.ItemBank
import oscats.ModelL1p
import oscats.Item
% Create an item bank to store the items.
% Setting the property "sizeHint" increases allocation efficiency.
bank = ItemBank(N_ITEMS);
for k = 1:N_ITEMS
% First we create an IRT model container for our item
% Defaults to unidimensional, using the first dimension of space
model = ModelL1p(space);
% Then, set the parameters. Here there is only one, the difficulty (b).
model.setParamByIndex(0, oscats.Random.normal(1));
% Create an item based on this model (as default model)
item = Item(model);
% Add the item to the item bank
bank.addItem(item);
% Since Java and Matlab are garbage collected, we don't have to worry
% about reference counting.
end
ret = bank;
end
% Returns an array of new OscatsExaminee pointers
function examinees = gen_examinees(space)
import oscats.Examinee
import oscats.Point
dim = char(oscats.Space.OSCATS_DIM_CONT + 0); % First continuous dimension
ret = javaArray('oscats.Examinee', N_EXAMINEES);
for k = 1:N_EXAMINEES
% Latent IRT ability parameter. This is a one-dimensional test.
theta = oscats.Point(space);
% Sample the ability from N(0,1) distribution
theta.setCont(dim, oscats.Random.normal(1));
% Create a new examinee
ret(k) = Examinee();
% Set the examinee's true (simulated) ability
ret(k).setSimTheta(theta);
end
examinees = ret;
end
%% main
num_tests = 4;
test_names = { 'random', 'matched', 'match.5', 'match.10' };
test = javaArray('oscats.Test', num_tests);
exposure = javaArray('oscats.AlgExposureCounter', num_tests);
% Create the latent space for the test: continuous unidimensional
space = oscats.Space(1, 0);
dim = oscats.Space.OSCATS_DIM_CONT + 0; % First continuous dimension
disp('Creating examinees.');
examinees = gen_examinees(space);
disp('Creating items.');
bank = gen_items(space);
disp('Creating tests.');
for j = 1:num_tests
% Create a new test with the given properties
% In this case, we know what the length of the test will be (30),
% so, we set length_hint for allocation efficiency.
% Any good/reasonable guess will do---the size will be adjusted
% automatically as necessary.
test(j) = Test(test_names(j), bank, LEN);
% Register the CAT algorithms for this test.
% A test must have at minimum a selection algorithm, and administration
% algorithm, and a stoping critierion.
oscats.AlgSimulate().register(test(j));
oscats.AlgEstimate().register(test(j));
% All calls to oscats.Algorithm.register() return an algorithm
% data object. In many cases, we don't care about this object, since
% it doesn't contain any interesting information. But, for the
% item exposure counter, we want to have access to the item exposure
% rates when the test is over, so we keep the object.
exposure(j) = oscats.AlgExposureCounter();
exposure(j).register(test(j));
alg = oscats.AlgFixedLength.createAlgFixedLength(LEN);
alg.register(test(j));
end
% Here we register the item selection criteria for the different tests
oscats.AlgPickRand().register(test(1));
% The default for OscatsAlgClosestDiff is to pick the exact closest item
oscats.AlgClosestDiff().register(test(2));
% But, we can have the algorithm choose randomly from among the num closest
alg = oscats.AlgClosestDiff.createAlgClosestDiff(5);
alg.register(test(3));
alg = oscats.AlgClosestDiff.createAlgClosestDiff(10);
alg.register(test(4));
disp('Administering.');
f = fopen('ex01-examinees.dat', 'w');
fprintf(f, 'ID\ttrue');
for j = 1:num_tests
fprintf(f, '\t%s', char(test_names(j)) );
end
fprintf(f, '\n');
for i = 1:N_EXAMINEES
% An initial estimate for latent IRT ability must be provided.
examinees(i).setEstTheta(oscats.Point(space));
fprintf(f, '%d\t%g', i, examinees(i).getSimTheta().getCont(dim));
for j = 1:num_tests
% Reset initial latent ability for this test
examinees(i).getEstTheta().setCont(dim, 0);
% Do the administration!
test(j).administer(examinees(i));
% Output the resulting theta.hat
fprintf(f, '\t%g', examinees(i).getEstTheta().getCont(dim) );
end
fprintf(f, '\n');
end
fclose(f);
f = fopen('ex01-items.dat', 'w');
fprintf(f, 'ID\tb');
for j = 1:num_tests
fprintf(f, '\t%s', char(test_names(j)));
end
fprintf(f, '\n');
for i = 1:N_ITEMS
% Get the item's difficulty parameter
fprintf(f, '%d\t%g', i, bank.getItem(i-1).getModel().getParamByIndex(0));
% Get the exposure rate for this item in each test
for j = 1:num_tests
fprintf(f, '\t%g', exposure(j).getRate(bank.getItem(i-1)) );
end
fprintf(f, '\n');
end
fclose(f);
% No clean up necessary, since Java and Matlab are garbage collected.
disp('Done.');
end
|
github
|
safecrypto/libsafecrypto-master
|
huffman.m
|
.m
|
libsafecrypto-master/huffman.m
| 1,976 |
utf_8
|
45149521f88dd8ef4d638b578731fa60
|
function [huffman, tree] = huffman(bits, sig)
depth = 2^bits;
d = 1 / (sqrt(2 * pi) * sig);
e = -0.5 / (sig * sig);
p(1:depth) = d * exp(e * [0:depth-1].^2);
nodes = num2cell(1:depth);
probs = p;
while length(nodes) > 1
[mn, idx] = min(probs);
probs(idx) = Inf;
[mn2, idx2] = min(probs);
probs(idx) = mn + mn2;
probs(idx2) = [];
nodes{idx} = {nodes{idx}, nodes{idx2}};
nodes(idx2) = [];
end
codes = cell(size(p));
codes = huffman_codes('', nodes{1}, codes);
tree = [];
tree = huffman_tree(nodes{1}, tree);
lengths = cellfun(@length, codes);
huffman = cell(length(lengths),2);
for i=1:length(lengths)
huffman{i,1} = codes{i};
huffman{i,2} = lengths(i);
end
fprintf('// Generated from Matlab/Octave using %d bits and sigma=%f\n', bits, sig);
fprintf('static const huffman_code_t huff_code_gaussian_%d[] = {\n', bits);
for i=1:length(lengths)
fprintf(' { 0x%08X, %4d },\n', bin2dec(huffman{i,1}), huffman{i,2});
end
fprintf('};\n');
fprintf('static const huffman_node_t huff_node_gaussian_%d[] = {\n', bits);
for i=1:size(tree,1)
fprintf(' {%4d, %4d, %4d },\n', tree(i,1), tree(i,2), tree(i,3));
end
fprintf('};\n');
fprintf('static const huffman_table_t huff_table_gaussian_%d[] = {\n', bits);
fprintf(' huff_code_gaussian_%d, huff_node_gaussian_%d, %d\n', bits, bits, depth);
fprintf('};\n\n');
function tree = huffman_tree(nodes, tree)
if length(nodes) == 1
tuple = [-1,-1,nodes-1];
tree = [tree; tuple];
return;
else
tuple = [-1,-1,-1];
tree = [tree; tuple];
idx = size(tree,1);
tree(idx,1) = size(tree,1);
tree = huffman_tree(nodes{1}, tree);
tree(idx,2) = size(tree,1);
tree = huffman_tree(nodes{2}, tree);
end
function codes = huffman_codes(cur_code, nodes, codes)
if length(nodes) == 1
symbol = nodes;
codes{symbol} = cur_code;
return;
else
codes = huffman_codes([cur_code, '0'], nodes{1}, codes);
codes = huffman_codes([cur_code, '1'], nodes{2}, codes);
end
|
github
|
BestSonny/SSTD-master
|
classification_demo.m
|
.m
|
SSTD-master/matlab/demo/classification_demo.m
| 5,412 |
utf_8
|
8f46deabe6cde287c4759f3bc8b7f819
|
function [scores, maxlabel] = classification_demo(im, use_gpu)
% [scores, maxlabel] = classification_demo(im, use_gpu)
%
% Image classification demo using BVLC CaffeNet.
%
% IMPORTANT: before you run this demo, you should download BVLC CaffeNet
% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)
%
% ****************************************************************************
% For detailed documentation and usage on Caffe's Matlab interface, please
% refer to Caffe Interface Tutorial at
% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab
% ****************************************************************************
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
% maxlabel the label of the highest score
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = classification_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab for putting image data into the correct
% format in W x H x C with BGR channels:
% % permute channels from RGB to BGR
% im_data = im(:, :, [3, 2, 1]);
% % flip width and height to make width the fastest dimension
% im_data = permute(im_data, [2, 1, 3]);
% % convert from uint8 to single
% im_data = single(im_data);
% % reshape to a fixed size (e.g., 227x227).
% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % subtract mean_data (already in W x H x C with BGR channels)
% im_data = im_data - mean_data;
% If you have multiple images, cat them with cat(4, ...)
% Add caffe/matlab to you Matlab search PATH to use matcaffe
if exist('../+caffe', 'dir')
addpath('..');
else
error('Please run this demo from caffe/matlab/demo');
end
% Set caffe mode
if exist('use_gpu', 'var') && use_gpu
caffe.set_mode_gpu();
gpu_id = 0; % we will use the first gpu in this demo
caffe.set_device(gpu_id);
else
caffe.set_mode_cpu();
end
% Initialize the network using BVLC CaffeNet for image classification
% Weights (parameter) file needs to be downloaded from Model Zoo.
model_dir = '../../models/bvlc_reference_caffenet/';
net_model = [model_dir 'deploy.prototxt'];
net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];
phase = 'test'; % run with phase test (so that dropout isn't applied)
if ~exist(net_weights, 'file')
error('Please download CaffeNet from Model Zoo before you run this demo');
end
% Initialize a network
net = caffe.Net(net_model, net_weights, phase);
if nargin < 1
% For demo purposes we will use the cat image
fprintf('using caffe/examples/images/cat.jpg as input image\n');
im = imread('../../examples/images/cat.jpg');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Channels x Num, where Channels == 1000
tic;
% The net forward function. It takes in a cell array of N-D arrays
% (where N == 4 here) containing data of input blob(s) and outputs a cell
% array containing data from output blob(s)
scores = net.forward(input_data);
toc;
scores = scores{1};
scores = mean(scores, 2); % take average scores over 10 crops
[~, maxlabel] = max(scores);
% call caffe.reset_all() to reset caffe
caffe.reset_all();
% ------------------------------------------------------------------------
function crops_data = prepare_image(im)
% ------------------------------------------------------------------------
% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that
% is already in W x H x C with BGR channels
d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');
mean_data = d.mean_data;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]); % flip width and height
im_data = single(im_data); % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data
im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)
% oversample (4 corners, center, and their x-axis flips)
crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
n = 1;
for i = indices
for j = indices
crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);
crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);
n = n + 1;
end
end
center = floor(indices(2) / 2) + 1;
crops_data(:,:,:,5) = ...
im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);
crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
|
github
|
ATajadod94/Functional-Connectivity-Analysis-master
|
myCheckRegistraAndNormalization.m
|
.m
|
Functional-Connectivity-Analysis-master/Code/myCheckRegistraAndNormalization.m
| 1,601 |
utf_8
|
2835a47014775ebc26bb74e1c8b6024b
|
function myCheckRegistraAndNormalization(isubj,checkFlag)
%i subject id
%checkFlag ===1: check coregistration ==2 check nomormalization
spm('defaults', 'FMRI');
spm_jobman('initcfg');
facefMRIDCMDirectories = importDicomDirectoryExcel;
dataDir = 'C:\Users\zliu\Documents\myStudies\fixMTL\Faces_Repetiion_fMRI\';
[a ia ib]=unique(facefMRIDCMDirectories.subjID);
disp(isubj)
dirData = facefMRIDCMDirectories(facefMRIDCMDirectories.subjID==a(isubj),:);
nrun = size(dirData)-1;
subAnatDir = [dataDir,'subj', sprintf('%02d',a(isubj)),'\anat'];
anatImg = GetImageList3D(subAnatDir, WildcardFilename('ws*.img'));
if checkFlag==1
for jblc = 1:nrun
subFuncDir =[dataDir,'subj', sprintf('%02d',a(isubj)),'\run',num2str(jblc)];
imgFile=GetImageList4D(subFuncDir, WildcardFilename('w*.img'));
imids = randsample(195,2)
imgToCheck{jblc}=imgFile(imids);
end
else
imgToCheck{1} = 'C:\Users\zliu\Documents\myStudies\fixMTL\Faces_Repetiion_fMRI\myMatlabCode\ch2.img';
end
imgToCheck= cat(1,anatImg,imgToCheck{:})
mychecking(imgToCheck);
clearvars imgFile imids imgToCheck;
function mychecking(imgToCheck)
images = spm_vol(imgToCheck);
spm_figure('GetWin','Graphics');
spm_figure('Clear','Graphics');
spm_orthviews('Reset');
mn = length(images);
n = round(mn^0.4);
m = ceil(mn/n);
w = 1/n;
h = 1/m;
ds = (w+h)*0.02;
for ij=1:mn
i = 1-h*(floor((ij-1)/n)+1);
j = w*rem(ij-1,n);
handle = spm_orthviews('Image', images{ij},...
[j+ds/2 i+ds/2 w-ds h-ds]);
if ij==1, spm_orthviews('Space'); end
spm_orthviews('AddContext',handle);
end
|
github
|
ATajadod94/Functional-Connectivity-Analysis-master
|
Getting_labels.m
|
.m
|
Functional-Connectivity-Analysis-master/Code/4. Label_Code/4.3 Mapping/Getting_labels.m
| 8,315 |
utf_8
|
f9cb09ad034981690b8c486134e142ff
|
function files = Getting_labels(type,subject,label)
switch type
case 'label'
files = get_labels(subject,label);
case 'structure'
files = get_structure(subject,label);
case 'function'
files = get_functional(subject,label);
case 'motion'
files = get_motion(subject,label);
end
end
function labels = get_labels(subject , label)
%data_dir = 'H:\myStudies\phdThesisData\Data'; %% windows
data_dir = '/Volumes/Ryan3T1/myStudies/phdThesisData/Data';
switch label
case 'glasser'
labels = fullfile(data_dir,'glasser_label', sprintf('%02d',subject),'HCPMMP1.nii.gz');
case 'kastner'
folder = fullfile(data_dir,'PreProcess',strcat('Subject_', ...
sprintf('%02d',subject)),'Kastner_Label');
myfiles = dir(folder);
label_names = {};
labels = {};
for i=3:length(myfiles)
if (((myfiles(i).name(1) == 'l') || (myfiles(i).name(1) == 'r')) && myfiles(i).name(end) == 'i')
label_names(length(label_names)+1) = cellstr(myfiles(i).name);
end
end
label_names(length(label_names)+1) = cellstr('Kastner_maxprob_vol_rh.nii');
label_names(length(label_names)+1) = cellstr('Kastner_maxprob_vol_lh.nii');
for i=1:length(label_names)
labels(length(labels)+1) = cellstr(fullfile(folder,label_names{i}));
end
case 'griffis'
folder = fullfile(data_dir,'griffisV1_zx',sprintf('%02d',subject));
label_names = dir(folder);
label_names = label_names(3:end);
labels = {};
for i=1:length(label_names)
labels(length(labels)+1) = cellstr(fullfile(folder,label_names(i).name));
end
case 'MTL'
folder = fullfile(data_dir,'FreeSurfer_ROIs',sprintf('%02d',subject),'Ali_ROIs');
label_names = dir(folder);
label_names = label_names(3:end-2);
labels = {};
for i=1:length(label_names)
labels(length(labels)+1) = cellstr(fullfile(folder,label_names(i).name));
end
end
end
function files = get_structure(subject,label)
%data_dir = 'H:\myStudies\phdThesisData\Data'; %% windows
data_dir = '/Volumes/Ryan3T1/myStudies/phdThesisData/Data/PreProcess';
switch label
case 'Structural'
f_name = dir(fullfile(data_dir, strcat('Subject_',sprintf('%02d',subject)), 'Anatomy','s*.img'));
files = fullfile(data_dir, strcat('Subject_',sprintf('%02d',subject)), 'Anatomy', f_name.name);
case 'Grey'
f_name = dir(fullfile(data_dir, strcat('Subject_',sprintf('%02d',subject)), 'Anatomy','c1*.img'));
files = fullfile(data_dir, strcat('Subject_',sprintf('%02d',subject)), 'Anatomy', f_name.name);
case 'White'
f_name = dir(fullfile(data_dir, strcat('Subject_',sprintf('%02d',subject)), 'Anatomy','c2*.img'));
files = fullfile(data_dir, strcat('Subject_',sprintf('%02d',subject)), 'Anatomy', f_name.name);
case 'CSF'
f_name = dir(fullfile(data_dir, strcat('Subject_',sprintf('%02d',subject)), 'Anatomy','c3*.img'));
files = fullfile(data_dir, strcat('Subject_',sprintf('%02d',subject)), 'Anatomy', f_name.name);
end
end
function files = get_functional(subject,label)
subject_file = strcat('/Volumes/Ryan3T1/myStudies/phdThesisData/Data/PreProcess','/Subject_', sprintf('%02d',subject));
%subject_file = strcat('H:\myStudies\phdThesisData\Data\PreProcess','\Subject_', sprintf('%02d',subject));
switch label
case 'runs'
fundir = strcat(subject_file,'/preencoding_rest/');
funfiles = dir([fundir,'ra*.img']);
files{1} = [repmat(fundir,[181,1]),strvcat(funfiles(1:181).name)];
fundir = strcat(subject_file,'/post_encoding_rest_fam/');
funfiles = dir([fundir,'ra*.img']);
files{2} = [repmat(fundir,[181,1]),strvcat(funfiles(1:181).name)];
fundir = strcat(subject_file,'/post_encoding_rest_nonfam/');
funfiles = dir([fundir,'ra*.img']);
files{3} = [repmat(fundir,[181,1]),strvcat(funfiles(1:181).name)];
fundir = strcat(subject_file,'/thinkback/');
funfiles = dir([fundir,'ra*.img']);
files{4} = [repmat(fundir,[181,1]),strvcat(funfiles(1:181).name)];
fundir = strcat(subject_file,'/thinkahead/');
funfiles = dir([fundir,'ra*.img']);
files{5} = [repmat(fundir,[181,1]),strvcat(funfiles(1:181).name)];
case 'tasks'
% fundir = strcat(subject_file,'/encoding_fam1/');
% funfiles = dir([fundir,'ra*.img']);
% files{1} = [repmat(fundir,[287,1]),strvcat(funfiles(1:287).name)];
fundir = strcat(subject_file,'/encoding_fam2/');
funfiles = dir([fundir,'ra*.img']);
files{1} = [repmat(fundir,[287,1]),strvcat(funfiles(1:287).name)];
% fundir = strcat(subject_file,'/encoding_nonfam1/');
% funfiles = dir([fundir,'ra*.img']);
% files{3} = [repmat(fundir,[287,1]),strvcat(funfiles(1:287).name)];
% fundir = strcat(subject_file,'/encoding_nonfam2/');
% funfiles = dir([fundir,'ra*.img']);
% files{4} = [repmat(fundir,[287,1]),strvcat(funfiles(1:287).name)];
case 'res'
fundir = strcat(subject_file,'/firstlevelAnalysis_Native/');
funfiles = dir([fundir,'Res*.img']);
files{1} = [repmat(fundir,[287,1]),strvcat(funfiles(1:287).name)];
fundir = strcat(subject_file,'/firstlevelAnalysis_Native/');
funfiles = dir([fundir,'ResI_*.img']);
files{2} = [repmat(fundir,[287,1]),strvcat(funfiles(288:574).name)];
fundir = strcat(subject_file,'/firstlevelAnalysis_Native/');
funfiles = dir([fundir,'ResI_*.img']);
files{3} = [repmat(fundir,[287,1]),strvcat(funfiles(576:862).name)];
fundir = strcat(subject_file,'/firstlevelAnalysis_Native/');
funfiles = dir([fundir,'ResI_*.img']);
files{4} = [repmat(fundir,[287,1]),strvcat(funfiles(862:1148).name)];
end
end
function files = get_motion(subject,label)
%subject_file = strcat('H:\myStudies\phdThesisData\Data\PreProcess','\Subject_', sprintf('%02d',subject));
subject_file = strcat('/Volumes/Ryan3T1/myStudies/phdThesisData/Data/PreProcess','/Subject_', sprintf('%02d',subject));
switch label
case 'runs'
fundir = strcat(subject_file,'/preencoding_rest/');
funfiles = dir([fundir,'*txt']);
files{1} = [repmat(fundir,[1,1]),strvcat(funfiles(1:1).name)];
fundir = strcat(subject_file,'/post_encoding_rest_fam/');
funfiles = dir([fundir,'*txt']);
files{2} = [repmat(fundir,[1,1]),strvcat(funfiles(1:1).name)];
fundir = strcat(subject_file,'/post_encoding_rest_nonfam/');
funfiles = dir([fundir,'*txt']);
files{3} = [repmat(fundir,[1,1]),strvcat(funfiles(1:1).name)];
fundir = strcat(subject_file,'/thinkback/');
funfiles = dir([fundir,'*txt']);
files{4} = [repmat(fundir,[1,1]),strvcat(funfiles(1:1).name)];
fundir = strcat(subject_file,'/thinkahead/');
funfiles = dir([fundir,'*txt']);
files{5} = [repmat(fundir,[1,1]),strvcat(funfiles(1:1).name)];
files = files';
case 'tasks'
% fundir = strcat(subject_file,'/encoding_fam1/');
% funfiles = dir([fundir,'*txt']);
% files{1} = [repmat(fundir,[1,1]),strvcat(funfiles(1:1).name)];
fundir = strcat(subject_file,'/encoding_fam2/');
funfiles = dir([fundir,'*txt']);
files{1} = [repmat(fundir,[1,1]),strvcat(funfiles(1:1).name)];
%
% fundir = strcat(subject_file,'/encoding_nonfam1/');
% funfiles = dir([fundir,'*txt']);
% files{3} = [repmat(fundir,[1,1]),strvcat(funfiles(1:1).name)];
%
% fundir = strcat(subject_file,'/encoding_nonfam2/');
% funfiles = dir([fundir,'*txt']);
% files{4} = [repmat(fundir,[1,1]),strvcat(funfiles(1:1).name)];
%
end
end
|
github
|
ATajadod94/Functional-Connectivity-Analysis-master
|
resize_img.m
|
.m
|
Functional-Connectivity-Analysis-master/Code/4. Label_Code/4.2 Segmenting/resize_img.m
| 4,516 |
utf_8
|
b1e768cfb8086d7aa410954b6b0bf07f
|
function resize_img(imnames, Voxdim, BB, ismask)
% resize_img -- resample images to have specified voxel dims and BBox
% resize_img(imnames, voxdim, bb, ismask)
%
% Output images will be prefixed with 'r', and will have voxel dimensions
% equal to voxdim. Use NaNs to determine voxdims from transformation matrix
% of input image(s).
% If bb == nan(2,3), bounding box will include entire original image
% Origin will move appropriately. Use world_bb to compute bounding box from
% a different image.
%
% Pass ismask=true to re-round binary mask values (avoid
% growing/shrinking masks due to linear interp)
%
% See also voxdim, world_bb
% Based on John Ashburner's reorient.m
% http://www.sph.umich.edu/~nichols/JohnsGems.html#Gem7
% http://www.sph.umich.edu/~nichols/JohnsGems5.html#Gem2
% Adapted by Ged Ridgway -- email bugs to [email protected]
% This version doesn't check spm_flip_analyze_images -- the handedness of
% the output image and matrix should match those of the input.
% Check spm version:
if exist('spm_select','file') % should be true for spm5
spm5 = 1;
elseif exist('spm_get','file') % should be true for spm2
spm5 = 0;
else
error('Can''t find spm_get or spm_select; please add SPM to path')
end
spm_defaults;
% prompt for missing arguments
if ( ~exist('imnames','var') || isempty(char(imnames)) )
if spm5
imnames = spm_select(inf, 'image', 'Choose images to resize');
else
imnames = spm_get(inf, 'img', 'Choose images to resize');
end
end
% check if inter fig already open, don't close later if so...
Fint = spm_figure('FindWin', 'Interactive'); Fnew = [];
if ( ~exist('Voxdim', 'var') || isempty(Voxdim) )
Fnew = spm_figure('GetWin', 'Interactive');
Voxdim = spm_input('Vox Dims (NaN for "as input")? ',...
'+1', 'e', '[nan nan nan]', 3);
end
if ( ~exist('BB', 'var') || isempty(BB) )
Fnew = spm_figure('GetWin', 'Interactive');
BB = spm_input('Bound Box (NaN => original)? ',...
'+1', 'e', '[nan nan nan; nan nan nan]', [2 3]);
end
if ~exist('ismask', 'var')
ismask = false;
end
if isempty(ismask)
ismask = false;
end
% reslice images one-by-one
vols = spm_vol(imnames);
for V=vols'
% (copy to allow defaulting of NaNs differently for each volume)
voxdim = Voxdim;
bb = BB;
% default voxdim to current volume's voxdim, (from mat parameters)
if any(isnan(voxdim))
vprm = spm_imatrix(V.mat);
vvoxdim = vprm(7:9);
voxdim(isnan(voxdim)) = vvoxdim(isnan(voxdim));
end
voxdim = voxdim(:)';
mn = bb(1,:);
mx = bb(2,:);
% default BB to current volume's
if any(isnan(bb(:)))
vbb = world_bb(V);
vmn = vbb(1,:);
vmx = vbb(2,:);
mn(isnan(mn)) = vmn(isnan(mn));
mx(isnan(mx)) = vmx(isnan(mx));
end
% voxel [1 1 1] of output should map to BB mn
% (the combination of matrices below first maps [1 1 1] to [0 0 0])
mat = spm_matrix([mn 0 0 0 voxdim])*spm_matrix([-1 -1 -1]);
% voxel-coords of BB mx gives number of voxels required
% (round up if more than a tenth of a voxel over)
imgdim = ceil(mat \ [mx 1]' - 0.1)';
% output image
VO = V;
[pth,nam,ext] = fileparts(V.fname);
VO.fname = fullfile(pth,['r' nam ext]);% add r to not rewrite JG
VO.dim(1:3) = imgdim(1:3);
VO.mat = mat;
VO = spm_create_vol(VO);
spm_progress_bar('Init',imgdim(3),'reslicing...','planes completed');
for i = 1:imgdim(3)
M = inv(spm_matrix([0 0 -i])*inv(VO.mat)*V.mat);
img = spm_slice_vol(V, M, imgdim(1:2), 1); % (linear interp)
if ismask
img = round(img);
end
spm_write_plane(VO, img, i);
spm_progress_bar('Set', i)
end
spm_progress_bar('Clear');
end
% call spm_close_vol if spm2
if ~spm5
spm_close_vol(VO);
end
if (isempty(Fint) && ~isempty(Fnew))
% interactive figure was opened by this script, so close it again.
close(Fnew);
end
disp('Done.')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function bb = world_bb(V)
% world-bb -- get bounding box in world (mm) coordinates
d = V.dim(1:3);
% corners in voxel-space
c = [ 1 1 1 1
1 1 d(3) 1
1 d(2) 1 1
1 d(2) d(3) 1
d(1) 1 1 1
d(1) 1 d(3) 1
d(1) d(2) 1 1
d(1) d(2) d(3) 1 ]';
% corners in world-space
tc = V.mat(1:3,1:4)*c;
% bounding box (world) min and max
mn = min(tc,[],2)';
mx = max(tc,[],2)';
bb = [mn; mx];
|
github
|
hihixuyang/formation_control-master
|
graph_create.m
|
.m
|
formation_control-master/graph_create.m
| 3,946 |
utf_8
|
8624b473d2653e9c9ff836062facdc37
|
function [A_c, A_c_2, A, A_2] = graph_create(connections, connections2, N)
%creates two random graphs using Erdos-Renyi-Algorithm of n-vehicles and
%finds minimum directed spanning tree of these two graphs
%
% Inputs:
% N - number of vehicles
% connections - to leader connected vehicles in graph 1
% connections2 - to leader connected vehicles in graph 2
% Outputs:
% A_c - Consensus adjacency matrix graph 1 with virtual leader connections
% A_c_2 - same as above for graph 2
% A - Adjacency matrix graph 1 without virtual leader
% A_2 - same as above for graph 2
graphs = figure;
scrsz = get(groot,'ScreenSize');
set(graphs, 'Name', 'Communication Topologies', 'NumberTitle', 'off','OuterPosition',[0 0 scrsz(3)/2 scrsz(4)/2]);
% first graph
connect = zeros(1,N);
for i=1:1:length(connections)
connect(connections(i)) = 1;
end
rnd_g = erdosRenyi(N,0.6,4);
G = graph(rnd_g.Adj,'upper','OmitSelfLoops');
subplot(2,2,1);
p = plot(G);
% find minimum spanning tree
[T,pred] = minspantree(G,'Type','forest','Root',connections(1));
highlight(p,T)
rootedTree = digraph(pred(pred~=0),find(pred~=0),[]);
subplot(2,2,2);
plot(rootedTree);
A = full(rootedTree.adjacency)'
A_c = [A connect'; zeros(1,N+1)]
% second graph
connect2 = zeros(1,N);
for i=1:1:length(connections2)
connect2(connections2(i)) = 1;
end
rnd_g = erdosRenyi(N,0.6,4);
G = graph(rnd_g.Adj,'upper','OmitSelfLoops');
subplot(2,2,3);
p = plot(G);
[T,pred] = minspantree(G,'Type','forest','Root',connections2(1));
highlight(p,T)
rootedTree = digraph(pred(pred~=0),find(pred~=0),[]);
subplot(2,2,4);
plot(rootedTree);
A_2 = full(rootedTree.adjacency)'
A_c_2 = [A_2 connect2'; zeros(1,N+1)]
end
function [G]=erdosRenyi(nv,p,Kreg)
%Generates a random graph based on the Erdos and Renyi algoritm where all possible pairs of 'nv' nodes are
%connected with probability 'p'.
%
% Inputs:
% nv - number of nodes
% p - rewiring probability
% Kreg - initial node degree of for regular graph (use 1 or even numbers)
%
% Output:
% G is a structure inplemented as data structure in this as well as other
% graph theory algorithms.
% G.Adj - is the adjacency matrix (1 for connected nodes, 0 otherwise).
% G.x and G.y - are row vectors of size nv wiht the (x,y) coordinates of
% each node of G.
% G.nv - number of vertices in G
% G.ne - number of edges in G
%
%Created by Pablo Blinder. [email protected]
%
%Last update 25/01/2005
%build regular lattice
A=sparse(nv,nv);
Kreg=fix(abs(Kreg)/2);Kreg=(Kreg<1)+Kreg;
for k=1:Kreg
A=sparse(A+diag(ones(1,length(diag(A,k))),k)+diag(ones(1,length(diag(A,nv-k))),nv-k));
end
ne0=nnz(A);
%find connected pairs
[v1,v2]=find(A);
% P=permPairs(nv);%my version is faster
Dis=(rand(length(v1),1)<=p);%pairs to disconnect
A(v1(Dis),v2(Dis))=0;
vDis=unique([v1(Dis),v2(Dis)]);%disconnected vertices
nDis=ne0-nnz(A);sum(Dis);
%cycle trough disconnected pairs
disconPairs=[v1(Dis),v2(Dis)];
for n=1:nDis
%choose one of the vertices from the disconnected pair
i=ceil(rand*size(disconPairs,1));
j=logical(1+rand>0.5);
vDisToRec=disconPairs(i,j);
%find non adjacent vertices and reconnect
adj=[find(A(:,vDisToRec)) ; find(A(vDisToRec,:))'];
nonAdj=setdiff(1:nv,adj);
vToRec=nonAdj(ceil(rand*length(nonAdj)));
S=sort([vDisToRec vToRec]);
A(S(1),S(2))=1;
end
[x,y]=getNodeCoordinates(nv);
%make adjacency matrix symetric
A=A+fliplr((flipud(triu(A))));
G=struct('Adj',A,'x',x','y',y','nv',nv,'ne',nnz(A));
end
function [x,y]=getNodeCoordinates(nv)
%Adapted from circle.m by Zhenhai Wang <[email protected]>. For more details
%see under MATLAB Central > File Exchange > Graphics > Specialized
%Plot and Graph Types > Draw a circle.
center=[0,0];
theta=linspace(0,2*pi,nv+1);
rho=ones(1,nv+1);%fit radius and nv
[X,Y] = pol2cart(theta',rho');
X=X+center(1);
Y=Y+center(2);
x=X(1:end-1)*10;
y=Y(1:end-1)*10;
end
|
github
|
MINED-MATKIT/SpatStat-Tools-master
|
LightningCLD2.m
|
.m
|
SpatStat-Tools-master/Functions/LightningCLD2.m
| 1,625 |
utf_8
|
f502c2a2b73ba2933d89590845b3c90a
|
function [chords, ids] = LightningCLD2(A,direction,varargin)
% Calculates the chord length frequency or distribution from 2D or 3D
% binary image.
if direction == 'x'
elseif direction == 'y'
A = permute(A,[2 1 3]);
elseif direction == 'z'
A = permute(A,[1 3 2]);
else
error('Direction must either be ''x'', ''y'' or ''z''.')
end
% Detect Edges
B = imfilter(A,[0 -1 1],'circular');
% Identify Left and Right Chord Ends
[XL, YL, ZL] = ind2sub(size(permute(A,[2 1 3])),find(permute(B,[2 1 3])~=0));
XR = XL;
% X contains the needed information, Y and Z only contain grid information.
% Use Y and Z as a grid/group index for computation on X.
[~, ~, J] = unique(YL+(ZL-1)*size(A,2));
% Get chords at each grid. Get distribution by histogram.
ll = splitapply(@(xr,xl) {getchords(xr,xl,size(A,1))},XR,XL,J);
labelxind = mod(XL+1,size(A,1)); labelxind(labelxind==0)=size(A,1);
labels = A(sub2ind(size(A),YL,labelxind,ZL));
[ids, ~, J] = unique(labels);
chords = splitapply(@(chordlist) histcounts(chordlist,0.5:(size(A,1)+0.5)),cell2mat(ll),J);
% Normalize if requested.
if nargin == 3
if varargin{1} == 'chordf'
% By chord frequency.
chords = chords./sum(chords,2);
elseif varargin{1} == 'pixelf'
% By pixel/voxel frequency.
chords = (1:size(A,1)).*chords./sum(sum((1:size(A,1)).*chords));
else
error('Normalization must either be ''pixelf'' or ''chordf''')
end
end
function s = getchords(xr,xl,dimlength)
if xr(1)<=xl(1)
s = circshift(xr,-1,1)-xl;
s(end) = s(end) + dimlength;
else
s = xr-xl;
end
end
end
|
github
|
jpeyre/unrel-master
|
extract_spatialconfig.m
|
.m
|
unrel-master/preprocessing/extract_spatialconfig.m
| 1,366 |
utf_8
|
4b1d3a6dfcd5fb871bc0d2a4eb80da8b
|
function [features] = extract_spatialconfig(pairs)
[x1,y1,w1,h1,x2,y2,w2,h2] = get_boxes_xywh(pairs);
% Scale
scale1 = w1.*h1;
scale2 = w2.*h2;
% Offset
x1_c = x1+w1/2;
y1_c = y1+h1/2;
x2_c = x2+w2/2;
y2_c = y2+h2/2;
offsetx = x2_c-x1_c;
offsety = -(y2_c-y1_c);
% Aspect ratio
aspectx = w1./h1;
aspecty = w2./h2;
% Overlap
boxI.xmin = max(x1,x2);
boxI.ymin = max(y1,y2);
boxI.xmax = min(x1+w1-1, x2+w2-1);
boxI.ymax = min(y1+h1-1, y2+h2-1);
wI = max((boxI.xmax - boxI.xmin + 1), 0);
yI = max((boxI.ymax - boxI.ymin + 1), 0);
areaI = wI.*yI;
areaU = scale1 + scale2 - areaI;
% Fill spatial features
N = length(x1);
features = zeros(N,6);
features(:,1) = offsetx./sqrt(scale1);
features(:,2) = offsety./sqrt(scale1);
features(:,3) = sqrt(scale2./scale1);
features(:,4) = aspectx;
features(:,5) = aspecty;
features(:,6) = sqrt(areaI./areaU);
end
function [x1,y1,w1,h1,x2,y2,w2,h2] = get_boxes_xywh(pairs)
x1 = pairs.subject_box(:,1);
y1 = pairs.subject_box(:,2);
w1 = pairs.subject_box(:,3) - pairs.subject_box(:,1) + 1;
h1 = pairs.subject_box(:,4) - pairs.subject_box(:,2) + 1;
x2 = pairs.object_box(:,1);
y2 = pairs.object_box(:,2);
w2 = pairs.object_box(:,3) - pairs.object_box(:,1) + 1;
h2 = pairs.object_box(:,4) - pairs.object_box(:,2) + 1;
end
|
github
|
jpeyre/unrel-master
|
VOCap.m
|
.m
|
unrel-master/eval/Lu-eval/VOCap.m
| 313 |
utf_8
|
3f7eece0efb56f494c27047656d2c31d
|
% This code was originally written and distributed as part of the
% PASCAL VOC challenge
function ap = VOCap(rec,prec)
mrec=[0 ; rec ; 1];
mpre=[0 ; prec ; 0];
for i=numel(mpre)-1:-1:1
mpre(i)=max(mpre(i),mpre(i+1));
end
i=find(mrec(2:end)~=mrec(1:end-1))+1;
ap=sum((mrec(i)-mrec(i-1)).*mpre(i));
|
github
|
jpeyre/unrel-master
|
vis_retrieval.m
|
.m
|
unrel-master/vis/vis_retrieval.m
| 4,037 |
utf_8
|
96b9fb6d0303de57dd6d173bc7eec458
|
function vis_retrieval()
% Visualize the top retrieved candidate pairs given a triplet query
% For this, put the images of each dataset in subfloder : ./data/datasetname/images
opts = config();
opts.split = 'test';
opts.use_languagescores = 0;
opts.use_objectscores = 0;
opts.IoUmode = 'subject-object'; % choose 'union', 'subject, 'subject-object'
opts.candidatespairs = 'candidates'; opts.overlap = 0.3;
opts.supervision = 'weak';
% Load a pre-trained model, e.g :
load(fullfile(opts.dataroot, 'classifiers', [opts.supervision, '_', strjoin(opts.featurestype, '-'), '_bg', num2str(opts.num_negatives)]));
datasets = {'unrel-dataset','vrd-dataset'};
image_filenames = [];
for k=1:length(datasets)
path = load(fullfile(opts.dataroot, datasets{k},['image_filenames_', opts.split, '.mat']));
image_filenames{k} = path.image_filenames;
end
load(fullfile(opts.dataroot, opts.vocab_objects));
load(fullfile(opts.dataroot, opts.vocab_predicates));
load(fullfile(opts.dataroot, opts.unusual_triplets));
%% Compute scores
opts.dataset = datasets{1};
[unrel.pairs, unrel.scores, unrel.annotations] = predict(W, opts);
opts.dataset = datasets{2};
[vrd.pairs, vrd.scores, vrd.annotations] = predict(W, opts);
% Merge dataset
[pairs, scores, annotations] = merge_datasets_for_retrieval(unrel, vrd);
%% Get positives for triplet
% Choose triplet to visualize 'subject-predicate-object'
tripletname = 'cat-wear-tie';
%tripletname = triplets{1};
% Get positives
triplet = Dataset.get_triplet_index(tripletname, vocab_objects, vocab_predicates);
positives_triplet = Dataset.get_annotations_for_triplet(annotations, triplet);
[candidates_triplet, idx] = Dataset.get_candidates_for_triplet(pairs, triplet);
scores_triplet = scores(idx, triplet.rel);
[~, indsort] = sort(scores_triplet, 'descend');
candidates_triplet = Dataset.select(candidates_triplet, indsort);
[positives, labels] = get_truepositives(candidates_triplet, positives_triplet, opts.overlap, opts.IoUmode);
%% Top results
idx = find(labels==1); % top retrieved positives
%idx = find(labels==-1); % top retrieved negatives
figure(1)
for j=1:min(length(idx),5)
clf
k = idx(j);
im_id = candidates_triplet.im_id(k);
data_id = candidates_triplet.data_id(k);
subject_box = candidates_triplet.subject_box(k,:);
object_box = candidates_triplet.object_box(k,:);
filename = image_filenames{data_id+1}{im_id};
img = imread(fullfile(opts.dataroot, datasets{data_id+1}, 'images', filename));
% Resize the image
scale = 500/size(img,1);
img = imresize(img, scale);
imshow(img);hold on,
Boxes = [subject_box; object_box];
Boxes = Boxes*scale;
draw_boxes(Boxes);
pause
end
%% Missed detections
idx = find(positives==0); % missed detections
figure(1)
for j=1:min(length(idx),5)
clf
k = idx(j);
im_id = positives_triplet.im_id(k);
data_id = positives_triplet.data_id(k);
subject_box = positives_triplet.subject_box(k,:);
object_box = positives_triplet.object_box(k,:);
filename = image_filenames{data_id+1}{im_id};
img = imread(fullfile(opts.dataroot, datasets{data_id+1}, 'images', filename));
% Resize the image
scale = 500/size(img,1);
img = imresize(img, scale);
imshow(img);hold on,
Boxes = [subject_box; object_box];
Boxes = Boxes*scale;
draw_boxes(Boxes);
pause
end
end
function draw_boxes( Boxes, linewidth)
% Display boxes on current figure
% Boxes is a matrix : B * 4 where B is the number of boxes to draw
% The coordinates have to been given in the format : [xmin, ymin, xmax, ymax]
if nargin<2
linewidth=8;
end
B = size(Boxes,1);
if B==2
colormap = [[0,0,1];[1,0,0]];
elseif B==1
colormap = [[1,0,0]];
else
colormap = jet(B);
end
% Convert coordinates [x,y,w,h]
Boxes(:,3) = Boxes(:,3) - Boxes(:,1) + 1;
Boxes(:,4) = Boxes(:,4) - Boxes(:,2) + 1;
for b=1:B
box = Boxes(b,:);
rectangle('Position',box, 'EdgeColor',colormap(b,:),'LineWidth',linewidth); hold on,
end
hold off
end
|
github
|
jpeyre/unrel-master
|
test_retrieval_Densecap_baseline.m
|
.m
|
unrel-master/experiments/test_retrieval_Densecap_baseline.m
| 4,043 |
utf_8
|
6a9dcceacab24afba4f580f688380bab
|
function [ap] = test_retrieval_Densecap_baseline()
% DenseCap [1] provides only a region proposal (contrary to our method which provide a pair of boxes).
% Once can interpret this region proposal either as a subject box or union box.
% We obtained these candidate regions and scores by forwarding VRD and
% UnRel dataset in the pre-trained DenseCap network released by the
% authors. See : https://github.com/jcjohnson/densecap
% [1] DenseCap: Fully Convolutional Localization Networks for Dense Captioning, Justin Johnson*, Andrej Karpathy*, Li Fei-Fei,
%% DenseCap baseline for evaluation with recall
opts = config();
opts.split = 'test';
IoUmode = opts.IoUmode;
opts.overlap = 0.3; opts.IoUmode = 'subject';
%opts.overlap = 1'; opts.IoUmode = 'subject-object';
assert((strcmp(IoUmode, 'union') || strcmp(IoUmode, 'subject')), 'IoUmode for DenseCap baseline should be either union or subject');
% Path to pre-computed Lu16 scores
path_scores = sprintf('%s/%s/%s/%s', opts.dataroot, '%s', 'test', 'densecap-candidates');
% UNREL
opts.dataset = 'unrel-dataset';
dataset = Dataset(opts);
% Load candidates/annotations
unrel.annotations = dataset.get_full_annotations();
% Load pre-computed scores
[unrel.pairs, unrel.scores] = load_densecap_outputs(sprintf(path_scores, opts.dataset));
% VRD
opts.dataset = 'vrd-dataset';
dataset = Dataset(opts);
% Load candidates/annotations
vrd.annotations = dataset.get_full_annotations();
% Load pre-computed scores
[vrd.pairs, vrd.scores] = load_densecap_outputs(sprintf(path_scores, opts.dataset));
% Merge dataset
[candidates, scores, annotations] = merge_datasets_for_retrieval(unrel, vrd);
% Compute AP
[ap, ub] = evaluate_retrieval_DenseCap(candidates, scores, annotations, opts);
fprintf('mAP=%.1f\n', 100*mean(ap));
end
function [ap, ub] = evaluate_retrieval_DenseCap(candidates, scores, annotations, opts)
overlap_thresh = opts.overlap;
IoUmode = opts.IoUmode;
load(fullfile(opts.dataroot, opts.vocab_objects));
load(fullfile(opts.dataroot, opts.vocab_predicates));
load(fullfile(opts.dataroot, opts.unusual_triplets));
ap = zeros(length(triplets),1);
ub = zeros(length(triplets),1); % provide upperbound detection. Number of hits.
for t=1:length(triplets)
% Extract the groundtruth positives, the candidates and scores for the triplet query
triplet = Dataset.get_triplet_index(triplets{t}, vocab_objects, vocab_predicates);
positives_triplet = Dataset.get_annotations_for_triplet(annotations, triplet);
scores_triplet = scores(:, t); % the score of the triplet is the score of the predicate
[ap(t), ub(t)] = compute_ap(candidates, scores_triplet, positives_triplet, overlap_thresh, IoUmode);
end
end
function [regions, triplet_scores] = load_densecap_outputs(path)
regions = struct('im_id',[],'reg_id',[],'subject_box',[], 'object_box',[]);
triplet_scores = [];
files = dir(fullfile(path, 'candidates', '*.mat'));
num_images = length(files);
reg_id = 1;
for i=1:num_images
boxes = load(fullfile(path, 'candidates', files(i).name));
region_box = boxes.x';
num_candidates = size(region_box,1);
im_id = strsplit(files(i).name, '.');
im_id = str2num(im_id{1});
regions.im_id = [regions.im_id ; im_id*ones(num_candidates,1)];
regions.reg_id = [regions.reg_id ; reg_id*ones(num_candidates,1)];
regions.subject_box = [regions.subject_box ; region_box];
% Load triplet scores
scores = load(fullfile(path, 'scores', files(i).name));
scores = scores.x';
triplet_scores = [triplet_scores ; scores];
reg_id = reg_id + 1;
end
regions.object_box = regions.subject_box;
% Minus score as DenseCap returns distance
triplet_scores = -triplet_scores;
end
|
github
|
auroua/tf_rfcn-master
|
voc_eval.m
|
.m
|
tf_rfcn-master/lib/datasets/VOCdevkit-matlab-wrapper/voc_eval.m
| 1,332 |
utf_8
|
3ee1d5373b091ae4ab79d26ab657c962
|
function res = voc_eval(path, comp_id, test_set, output_dir)
VOCopts = get_voc_opts(path);
VOCopts.testset = test_set;
for i = 1:length(VOCopts.classes)
cls = VOCopts.classes{i};
res(i) = voc_eval_cls(cls, VOCopts, comp_id, output_dir);
end
fprintf('\n~~~~~~~~~~~~~~~~~~~~\n');
fprintf('Results:\n');
aps = [res(:).ap]';
fprintf('%.1f\n', aps * 100);
fprintf('%.1f\n', mean(aps) * 100);
fprintf('~~~~~~~~~~~~~~~~~~~~\n');
function res = voc_eval_cls(cls, VOCopts, comp_id, output_dir)
test_set = VOCopts.testset;
year = VOCopts.dataset(4:end);
addpath(fullfile(VOCopts.datadir, 'VOCcode'));
res_fn = sprintf(VOCopts.detrespath, comp_id, cls);
recall = [];
prec = [];
ap = 0;
ap_auc = 0;
do_eval = (str2num(year) <= 2007) | ~strcmp(test_set, 'test');
if do_eval
% Bug in VOCevaldet requires that tic has been called first
tic;
[recall, prec, ap] = VOCevaldet(VOCopts, comp_id, cls, true);
ap_auc = xVOCap(recall, prec);
% force plot limits
ylim([0 1]);
xlim([0 1]);
print(gcf, '-djpeg', '-r0', ...
[output_dir '/' cls '_pr.jpg']);
end
fprintf('!!! %s : %.4f %.4f\n', cls, ap, ap_auc);
res.recall = recall;
res.prec = prec;
res.ap = ap;
res.ap_auc = ap_auc;
save([output_dir '/' cls '_pr.mat'], ...
'res', 'recall', 'prec', 'ap', 'ap_auc');
rmpath(fullfile(VOCopts.datadir, 'VOCcode'));
|
github
|
jbhuang0604/LapSRN-master
|
vllab_cnn_train_dag.m
|
.m
|
LapSRN-master/vllab_cnn_train_dag.m
| 16,946 |
utf_8
|
31a94eb8574989c25368eff1ca37acbd
|
function [net,stats] = vllab_cnn_train_dag(net, imdb, getBatch, varargin)
%CNN_TRAIN_DAG Demonstrates training a CNN using the DagNN wrapper
% CNN_TRAIN_DAG() is similar to CNN_TRAIN(), but works with
% the DagNN wrapper instead of the SimpleNN wrapper.
% Copyright (C) 2014-16 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
addpath(fullfile(vl_rootnn, 'examples'));
opts.expDir = fullfile('data','exp') ;
opts.continue = true ;
opts.batchSize = 256 ;
opts.numSubBatches = 1 ;
opts.train = [] ;
opts.val = [] ;
opts.gpus = [] ;
opts.prefetch = false ;
opts.epochSize = inf;
opts.numEpochs = 300 ;
opts.learningRate = 0.001 ;
opts.weightDecay = 0.0005 ;
opts.solver = [] ; % Empty array means use the default SGD solver
[opts, varargin] = vl_argparse(opts, varargin) ;
if ~isempty(opts.solver)
assert(isa(opts.solver, 'function_handle') && nargout(opts.solver) == 2,...
'Invalid solver; expected a function handle with two outputs.') ;
% Call without input arguments, to get default options
opts.solverOpts = opts.solver() ;
end
opts.momentum = 0.9 ;
opts.saveSolverState = true ;
opts.nesterovUpdate = false ;
opts.randomSeed = 0 ;
opts.profile = false ;
opts.parameterServer.method = 'mmap' ;
opts.parameterServer.prefix = 'mcn' ;
opts.derOutputs = {'objective', 1} ;
opts.extractStatsFn = @extractStats ;
opts.plotStatistics = true;
opts.postEpochFn = [] ; % postEpochFn(net,params,state) called after each epoch; can return a new learning rate, 0 to stop, [] for no change
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% additional opts
opts.model_name = '';
opts.num_train_batch = 1000;
opts.num_valid_batch = 100;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
opts = vl_argparse(opts, varargin) ;
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end
if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end
if isscalar(opts.train) && isnumeric(opts.train) && isnan(opts.train)
opts.train = [] ;
end
if isscalar(opts.val) && isnumeric(opts.val) && isnan(opts.val)
opts.val = [] ;
end
% -------------------------------------------------------------------------
% Initialization
% -------------------------------------------------------------------------
evaluateMode = isempty(opts.train) ;
if ~evaluateMode
if isempty(opts.derOutputs)
error('DEROUTPUTS must be specified when training.\n') ;
end
end
% -------------------------------------------------------------------------
% Train and validate
% -------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));
modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;
start = opts.continue * findLastCheckpoint(opts.expDir) ;
if start >= 1
fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ;
[net, state, stats] = loadState(modelPath(start)) ;
else
state = [] ;
end
for epoch=start+1:opts.numEpochs
% Set the random seed based on the epoch and opts.randomSeed.
% This is important for reproducibility, including when training
% is restarted from a checkpoint.
rng(epoch + opts.randomSeed) ;
prepareGPUs(opts, epoch == start+1) ;
% Train for one epoch.
params = opts ;
params.epoch = epoch ;
params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
params.train = opts.train(randperm(numel(opts.train))) ; % shuffle
params.train = params.train(1:min(opts.epochSize, numel(opts.train)));
params.val = opts.val(randperm(numel(opts.val))) ;
params.imdb = imdb ;
params.getBatch = getBatch ;
if numel(opts.gpus) <= 1
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
else
spmd
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if labindex == 1 && ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
end
lastStats = accumulateStats(lastStats) ;
end
stats.train(epoch) = lastStats.train ;
stats.val(epoch) = lastStats.val ;
clear lastStats ;
saveStats(modelPath(epoch), stats) ;
if opts.plotStatistics
switchFigure(1) ; clf ;
plots = setdiff(...
cat(2,...
fieldnames(stats.train)', ...
fieldnames(stats.val)'), {'num', 'time'}) ;
for p = plots
p = char(p) ;
values = zeros(0, epoch) ;
leg = {} ;
for f = {'train', 'val'}
f = char(f) ;
if isfield(stats.(f), p)
tmp = [stats.(f).(p)] ;
values(end+1,:) = tmp(1,:)' ;
leg{end+1} = f ;
end
end
subplot(1,numel(plots),find(strcmp(p,plots))) ;
plot(1:epoch, values','o-') ;
xlabel('epoch') ;
% title(p) ;
title(strrep(p, '_', '-')) ;
legend(leg{:}) ;
grid on ;
end
drawnow ;
print(1, modelFigPath, '-dpdf') ;
end
if ~isempty(opts.postEpochFn)
if nargout(opts.postEpochFn) == 0
opts.postEpochFn(net, params, state) ;
else
lr = opts.postEpochFn(net, params, state) ;
if ~isempty(lr), opts.learningRate = lr; end
if opts.learningRate == 0, break; end
end
end
end
% With multiple GPUs, return one copy
if isa(net, 'Composite'), net = net{1} ; end
% -------------------------------------------------------------------------
function [net, state] = processEpoch(net, state, params, mode)
% -------------------------------------------------------------------------
% Note that net is not strictly needed as an output argument as net
% is a handle class. However, this fixes some aliasing issue in the
% spmd caller.
% initialize with momentum 0
if isempty(state) || isempty(state.solverState)
state.solverState = cell(1, numel(net.params)) ;
state.solverState(:) = {0} ;
end
% move CNN to GPU as needed
numGpus = numel(params.gpus) ;
if numGpus >= 1
net.move('gpu') ;
for i = 1:numel(state.solverState)
s = state.solverState{i} ;
if isnumeric(s)
state.solverState{i} = gpuArray(s) ;
elseif isstruct(s)
state.solverState{i} = structfun(@gpuArray, s, 'UniformOutput', false) ;
end
end
end
if numGpus > 1
parserv = ParameterServer(params.parameterServer) ;
net.setParameterServer(parserv) ;
else
parserv = [] ;
end
% profile
if params.profile
if numGpus <= 1
profile clear ;
profile on ;
else
mpiprofile reset ;
mpiprofile on ;
end
end
num = 0 ;
epoch = params.epoch ;
% subset = params.(mode) ;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
image_set = params.(mode) ;
if( strcmp(mode,'train') )
num_samples = params.num_train_batch * params.batchSize;
elseif( strcmp(mode,'val') )
num_samples = params.num_valid_batch * params.batchSize;
end
subset = [];
while( length(subset) < num_samples )
subset = cat(1, subset, image_set(:));
end
subset = subset(1:num_samples);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
adjustTime = 0 ;
stats.num = 0 ; % return something even if subset = []
stats.time = 0 ;
start = tic ;
for t=1:params.batchSize:numel(subset)
% fprintf('%s: epoch %02d: %3d/%3d:', mode, epoch, ...
% fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;
batchSize = min(params.batchSize, numel(subset) - t + 1) ;
for s=1:params.numSubBatches
% get this image batch and prefetch the next
batchStart = t + (labindex-1) + (s-1) * numlabs ;
batchEnd = min(t+params.batchSize-1, numel(subset)) ;
batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
num = num + numel(batch) ;
if numel(batch) == 0, continue ; end
inputs = params.getBatch(params.imdb, batch, mode) ;
if params.prefetch
if s == params.numSubBatches
batchStart = t + (labindex-1) + params.batchSize ;
batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;
else
batchStart = batchStart + numlabs ;
end
nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
params.getBatch(params.imdb, nextBatch) ;
end
if strcmp(mode, 'train')
net.mode = 'normal' ;
net.accumulateParamDers = (s ~= 1) ;
net.eval(inputs, params.derOutputs, 'holdOn', s < params.numSubBatches) ;
else
net.mode = 'test' ;
net.eval(inputs) ;
end
end
% Accumulate gradient.
if strcmp(mode, 'train')
if ~isempty(parserv), parserv.sync() ; end
state = accumulateGradients(net, state, params, batchSize, parserv) ;
end
% Get statistics.
time = toc(start) + adjustTime ;
batchTime = time - stats.time ;
stats.num = num ;
stats.time = time ;
stats = params.extractStatsFn(stats,net) ;
currentSpeed = batchSize / batchTime ;
averageSpeed = (t + batchSize - 1) / time ;
if t == 3*params.batchSize + 1
% compensate for the first three iterations, which are outliers
adjustTime = 4*batchTime - time ;
stats.time = time + adjustTime ;
end
% fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if( numel(params.gpus) > 0 )
fprintf('%s [gpu %d]: ', mode, params.gpus(1)) ;
else
fprintf('%s [cpu]: ', mode) ;
end
fprintf('epoch %02d: %3d/%3d: %.1f (%.1f) Hz, lr = %s\n', ...
epoch, ...
fix((t-1)/params.batchSize)+1, ...
ceil(numel(subset)/params.batchSize),...
averageSpeed, currentSpeed, ...
num2str(params.learningRate));
fprintf('\tModel = %s\n', params.model_name);
for f = setdiff(fieldnames(stats)', {'num', 'time'})
fc = char(f) ;
fprintf('\t%s: %.4f\n', fc, stats.(fc)) ;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
% Save back to state.
state.stats.(mode) = stats ;
if params.profile
if numGpus <= 1
state.prof.(mode) = profile('info') ;
profile off ;
else
state.prof.(mode) = mpiprofile('info');
mpiprofile off ;
end
end
if ~params.saveSolverState
state.solverState = [] ;
else
for i = 1:numel(state.solverState)
s = state.solverState{i} ;
if isnumeric(s)
state.solverState{i} = gather(s) ;
elseif isstruct(s)
state.solverState{i} = structfun(@gather, s, 'UniformOutput', false) ;
end
end
end
net.reset() ;
net.move('cpu') ;
% -------------------------------------------------------------------------
function state = accumulateGradients(net, state, params, batchSize, parserv)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
otherGpus = setdiff(1:numGpus, labindex) ;
for p=1:numel(net.params)
if ~isempty(parserv)
parDer = parserv.pullWithIndex(p) ;
else
parDer = net.params(p).der ;
end
switch net.params(p).trainMethod
case 'average' % mainly for batch normalization
thisLR = net.params(p).learningRate ;
net.params(p).value = vl_taccum(...
1 - thisLR, net.params(p).value, ...
(thisLR/batchSize/net.params(p).fanout), parDer) ;
case 'gradient'
thisDecay = params.weightDecay * net.params(p).weightDecay ;
thisLR = params.learningRate * net.params(p).learningRate ;
if thisLR>0 || thisDecay>0
% Normalize gradient and incorporate weight decay.
parDer = vl_taccum(1/batchSize, parDer, ...
thisDecay, net.params(p).value) ;
if isempty(params.solver)
% Default solver is the optimised SGD.
% Update momentum.
state.solverState{p} = vl_taccum(...
params.momentum, state.solverState{p}, ...
-1, parDer) ;
% Nesterov update (aka one step ahead).
if params.nesterovUpdate
delta = params.momentum * state.solverState{p} - parDer ;
else
delta = state.solverState{p} ;
end
% Update parameters.
net.params(p).value = vl_taccum(...
1, net.params(p).value, thisLR, delta) ;
else
% call solver function to update weights
[net.params(p).value, state.solverState{p}] = ...
params.solver(net.params(p).value, state.solverState{p}, ...
parDer, params.solverOpts, thisLR) ;
end
end
otherwise
error('Unknown training method ''%s'' for parameter ''%s''.', ...
net.params(p).trainMethod, ...
net.params(p).name) ;
end
end
% -------------------------------------------------------------------------
function stats = accumulateStats(stats_)
% -------------------------------------------------------------------------
for s = {'train', 'val'}
s = char(s) ;
total = 0 ;
% initialize stats stucture with same fields and same order as
% stats_{1}
stats__ = stats_{1} ;
names = fieldnames(stats__.(s))' ;
values = zeros(1, numel(names)) ;
fields = cat(1, names, num2cell(values)) ;
stats.(s) = struct(fields{:}) ;
for g = 1:numel(stats_)
stats__ = stats_{g} ;
num__ = stats__.(s).num ;
total = total + num__ ;
for f = setdiff(fieldnames(stats__.(s))', 'num')
f = char(f) ;
stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;
if g == numel(stats_)
stats.(s).(f) = stats.(s).(f) / total ;
end
end
end
stats.(s).num = total ;
end
% -------------------------------------------------------------------------
function stats = extractStats(stats, net)
% -------------------------------------------------------------------------
sel = find(cellfun(@(x) isa(x,'dagnn.Loss'), {net.layers.block})) ;
for i = 1:numel(sel)
if net.layers(sel(i)).block.ignoreAverage, continue; end;
stats.(net.layers(sel(i)).outputs{1}) = net.layers(sel(i)).block.average ;
end
% -------------------------------------------------------------------------
function saveState(fileName, net_, state)
% -------------------------------------------------------------------------
net = net_.saveobj() ;
fprintf('Save %s\n', fileName);
save(fileName, 'net', 'state') ;
% -------------------------------------------------------------------------
function saveStats(fileName, stats)
% -------------------------------------------------------------------------
fprintf('Save %s\n', fileName);
if exist(fileName)
save(fileName, 'stats', '-append') ;
else
save(fileName, 'stats') ;
end
% -------------------------------------------------------------------------
function [net, state, stats] = loadState(fileName)
% -------------------------------------------------------------------------
load(fileName, 'net', 'state', 'stats') ;
net = dagnn.DagNN.loadobj(net) ;
if isempty(whos('stats'))
error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...
fileName) ;
end
% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir)
% -------------------------------------------------------------------------
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
% -------------------------------------------------------------------------
function switchFigure(n)
% -------------------------------------------------------------------------
if get(0,'CurrentFigure') ~= n
try
set(0,'CurrentFigure',n) ;
catch
figure(n) ;
end
end
% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
clear vl_tmove vl_imreadjpeg ;
% -------------------------------------------------------------------------
function prepareGPUs(opts, cold)
% -------------------------------------------------------------------------
numGpus = numel(opts.gpus) ;
if numGpus > 1
% check parallel pool integrity as it could have timed out
pool = gcp('nocreate') ;
if ~isempty(pool) && pool.NumWorkers ~= numGpus
delete(pool) ;
end
pool = gcp('nocreate') ;
if isempty(pool)
parpool('local', numGpus) ;
cold = true ;
end
end
if numGpus >= 1 && cold
fprintf('%s: resetting GPU\n', mfilename)
clearMex() ;
if numGpus == 1
gpuDevice(opts.gpus)
else
spmd
clearMex() ;
gpuDevice(opts.gpus(labindex))
end
end
end
|
github
|
jbhuang0604/LapSRN-master
|
sp3Filters.m
|
.m
|
LapSRN-master/utils/matlabPyrTools/sp3Filters.m
| 17,188 |
utf_8
|
a3514d77e5a92b96d96197ebad343395
|
% Steerable pyramid filters. Transform described in:
%
% @INPROCEEDINGS{Simoncelli95b,
% TITLE = "The Steerable Pyramid: A Flexible Architecture for
% Multi-Scale Derivative Computation",
% AUTHOR = "E P Simoncelli and W T Freeman",
% BOOKTITLE = "Second Int'l Conf on Image Processing",
% ADDRESS = "Washington, DC", MONTH = "October", YEAR = 1995 }
%
% Filter kernel design described in:
%
%@INPROCEEDINGS{Karasaridis96,
% TITLE = "A Filter Design Technique for
% Steerable Pyramid Image Transforms",
% AUTHOR = "A Karasaridis and E P Simoncelli",
% BOOKTITLE = "ICASSP", ADDRESS = "Atlanta, GA",
% MONTH = "May", YEAR = 1996 }
% Eero Simoncelli, 6/96.
function [lo0filt,hi0filt,lofilt,bfilts,mtx,harmonics] = sp3Filters();
harmonics = [1 3];
mtx = [ ...
0.5000 0.3536 0 -0.3536
-0.0000 0.3536 0.5000 0.3536
0.5000 -0.3536 0 0.3536
-0.0000 0.3536 -0.5000 0.3536];
hi0filt = [
-4.0483998600E-4 -6.2596000498E-4 -3.7829999201E-5 8.8387000142E-4 1.5450799838E-3 1.9235999789E-3 2.0687500946E-3 2.0898699295E-3 2.0687500946E-3 1.9235999789E-3 1.5450799838E-3 8.8387000142E-4 -3.7829999201E-5 -6.2596000498E-4 -4.0483998600E-4
-6.2596000498E-4 -3.2734998967E-4 7.7435001731E-4 1.5874400269E-3 2.1750701126E-3 2.5626500137E-3 2.2892199922E-3 1.9755100366E-3 2.2892199922E-3 2.5626500137E-3 2.1750701126E-3 1.5874400269E-3 7.7435001731E-4 -3.2734998967E-4 -6.2596000498E-4
-3.7829999201E-5 7.7435001731E-4 1.1793200392E-3 1.4050999889E-3 2.2253401112E-3 2.1145299543E-3 3.3578000148E-4 -8.3368999185E-4 3.3578000148E-4 2.1145299543E-3 2.2253401112E-3 1.4050999889E-3 1.1793200392E-3 7.7435001731E-4 -3.7829999201E-5
8.8387000142E-4 1.5874400269E-3 1.4050999889E-3 1.2960999738E-3 -4.9274001503E-4 -3.1295299996E-3 -4.5751798898E-3 -5.1014497876E-3 -4.5751798898E-3 -3.1295299996E-3 -4.9274001503E-4 1.2960999738E-3 1.4050999889E-3 1.5874400269E-3 8.8387000142E-4
1.5450799838E-3 2.1750701126E-3 2.2253401112E-3 -4.9274001503E-4 -6.3222697936E-3 -2.7556000277E-3 5.3632198833E-3 7.3032598011E-3 5.3632198833E-3 -2.7556000277E-3 -6.3222697936E-3 -4.9274001503E-4 2.2253401112E-3 2.1750701126E-3 1.5450799838E-3
1.9235999789E-3 2.5626500137E-3 2.1145299543E-3 -3.1295299996E-3 -2.7556000277E-3 1.3962360099E-2 7.8046298586E-3 -9.3812197447E-3 7.8046298586E-3 1.3962360099E-2 -2.7556000277E-3 -3.1295299996E-3 2.1145299543E-3 2.5626500137E-3 1.9235999789E-3
2.0687500946E-3 2.2892199922E-3 3.3578000148E-4 -4.5751798898E-3 5.3632198833E-3 7.8046298586E-3 -7.9501636326E-2 -0.1554141641 -7.9501636326E-2 7.8046298586E-3 5.3632198833E-3 -4.5751798898E-3 3.3578000148E-4 2.2892199922E-3 2.0687500946E-3
2.0898699295E-3 1.9755100366E-3 -8.3368999185E-4 -5.1014497876E-3 7.3032598011E-3 -9.3812197447E-3 -0.1554141641 0.7303866148 -0.1554141641 -9.3812197447E-3 7.3032598011E-3 -5.1014497876E-3 -8.3368999185E-4 1.9755100366E-3 2.0898699295E-3
2.0687500946E-3 2.2892199922E-3 3.3578000148E-4 -4.5751798898E-3 5.3632198833E-3 7.8046298586E-3 -7.9501636326E-2 -0.1554141641 -7.9501636326E-2 7.8046298586E-3 5.3632198833E-3 -4.5751798898E-3 3.3578000148E-4 2.2892199922E-3 2.0687500946E-3
1.9235999789E-3 2.5626500137E-3 2.1145299543E-3 -3.1295299996E-3 -2.7556000277E-3 1.3962360099E-2 7.8046298586E-3 -9.3812197447E-3 7.8046298586E-3 1.3962360099E-2 -2.7556000277E-3 -3.1295299996E-3 2.1145299543E-3 2.5626500137E-3 1.9235999789E-3
1.5450799838E-3 2.1750701126E-3 2.2253401112E-3 -4.9274001503E-4 -6.3222697936E-3 -2.7556000277E-3 5.3632198833E-3 7.3032598011E-3 5.3632198833E-3 -2.7556000277E-3 -6.3222697936E-3 -4.9274001503E-4 2.2253401112E-3 2.1750701126E-3 1.5450799838E-3
8.8387000142E-4 1.5874400269E-3 1.4050999889E-3 1.2960999738E-3 -4.9274001503E-4 -3.1295299996E-3 -4.5751798898E-3 -5.1014497876E-3 -4.5751798898E-3 -3.1295299996E-3 -4.9274001503E-4 1.2960999738E-3 1.4050999889E-3 1.5874400269E-3 8.8387000142E-4
-3.7829999201E-5 7.7435001731E-4 1.1793200392E-3 1.4050999889E-3 2.2253401112E-3 2.1145299543E-3 3.3578000148E-4 -8.3368999185E-4 3.3578000148E-4 2.1145299543E-3 2.2253401112E-3 1.4050999889E-3 1.1793200392E-3 7.7435001731E-4 -3.7829999201E-5
-6.2596000498E-4 -3.2734998967E-4 7.7435001731E-4 1.5874400269E-3 2.1750701126E-3 2.5626500137E-3 2.2892199922E-3 1.9755100366E-3 2.2892199922E-3 2.5626500137E-3 2.1750701126E-3 1.5874400269E-3 7.7435001731E-4 -3.2734998967E-4 -6.2596000498E-4
-4.0483998600E-4 -6.2596000498E-4 -3.7829999201E-5 8.8387000142E-4 1.5450799838E-3 1.9235999789E-3 2.0687500946E-3 2.0898699295E-3 2.0687500946E-3 1.9235999789E-3 1.5450799838E-3 8.8387000142E-4 -3.7829999201E-5 -6.2596000498E-4 -4.0483998600E-4
];
lo0filt = [
-8.7009997515E-5 -1.3542800443E-3 -1.6012600390E-3 -5.0337001448E-4 2.5240099058E-3 -5.0337001448E-4 -1.6012600390E-3 -1.3542800443E-3 -8.7009997515E-5
-1.3542800443E-3 2.9215801042E-3 7.5227199122E-3 8.2244202495E-3 1.1076199589E-3 8.2244202495E-3 7.5227199122E-3 2.9215801042E-3 -1.3542800443E-3
-1.6012600390E-3 7.5227199122E-3 -7.0612900890E-3 -3.7694871426E-2 -3.2971370965E-2 -3.7694871426E-2 -7.0612900890E-3 7.5227199122E-3 -1.6012600390E-3
-5.0337001448E-4 8.2244202495E-3 -3.7694871426E-2 4.3813198805E-2 0.1811603010 4.3813198805E-2 -3.7694871426E-2 8.2244202495E-3 -5.0337001448E-4
2.5240099058E-3 1.1076199589E-3 -3.2971370965E-2 0.1811603010 0.4376249909 0.1811603010 -3.2971370965E-2 1.1076199589E-3 2.5240099058E-3
-5.0337001448E-4 8.2244202495E-3 -3.7694871426E-2 4.3813198805E-2 0.1811603010 4.3813198805E-2 -3.7694871426E-2 8.2244202495E-3 -5.0337001448E-4
-1.6012600390E-3 7.5227199122E-3 -7.0612900890E-3 -3.7694871426E-2 -3.2971370965E-2 -3.7694871426E-2 -7.0612900890E-3 7.5227199122E-3 -1.6012600390E-3
-1.3542800443E-3 2.9215801042E-3 7.5227199122E-3 8.2244202495E-3 1.1076199589E-3 8.2244202495E-3 7.5227199122E-3 2.9215801042E-3 -1.3542800443E-3
-8.7009997515E-5 -1.3542800443E-3 -1.6012600390E-3 -5.0337001448E-4 2.5240099058E-3 -5.0337001448E-4 -1.6012600390E-3 -1.3542800443E-3 -8.7009997515E-5
];
lofilt = [
-4.3500000174E-5 1.2078000145E-4 -6.7714002216E-4 -1.2434000382E-4 -8.0063997302E-4 -1.5970399836E-3 -2.5168000138E-4 -4.2019999819E-4 1.2619999470E-3 -4.2019999819E-4 -2.5168000138E-4 -1.5970399836E-3 -8.0063997302E-4 -1.2434000382E-4 -6.7714002216E-4 1.2078000145E-4 -4.3500000174E-5
1.2078000145E-4 4.4606000301E-4 -5.8146001538E-4 5.6215998484E-4 -1.3688000035E-4 2.3255399428E-3 2.8898599558E-3 4.2872801423E-3 5.5893999524E-3 4.2872801423E-3 2.8898599558E-3 2.3255399428E-3 -1.3688000035E-4 5.6215998484E-4 -5.8146001538E-4 4.4606000301E-4 1.2078000145E-4
-6.7714002216E-4 -5.8146001538E-4 1.4607800404E-3 2.1605400834E-3 3.7613599561E-3 3.0809799209E-3 4.1121998802E-3 2.2212199401E-3 5.5381999118E-4 2.2212199401E-3 4.1121998802E-3 3.0809799209E-3 3.7613599561E-3 2.1605400834E-3 1.4607800404E-3 -5.8146001538E-4 -6.7714002216E-4
-1.2434000382E-4 5.6215998484E-4 2.1605400834E-3 3.1757799443E-3 3.1846798956E-3 -1.7774800071E-3 -7.4316998944E-3 -9.0569201857E-3 -9.6372198313E-3 -9.0569201857E-3 -7.4316998944E-3 -1.7774800071E-3 3.1846798956E-3 3.1757799443E-3 2.1605400834E-3 5.6215998484E-4 -1.2434000382E-4
-8.0063997302E-4 -1.3688000035E-4 3.7613599561E-3 3.1846798956E-3 -3.5306399222E-3 -1.2604200281E-2 -1.8847439438E-2 -1.7508180812E-2 -1.6485679895E-2 -1.7508180812E-2 -1.8847439438E-2 -1.2604200281E-2 -3.5306399222E-3 3.1846798956E-3 3.7613599561E-3 -1.3688000035E-4 -8.0063997302E-4
-1.5970399836E-3 2.3255399428E-3 3.0809799209E-3 -1.7774800071E-3 -1.2604200281E-2 -2.0229380578E-2 -1.1091699824E-2 3.9556599222E-3 1.4385120012E-2 3.9556599222E-3 -1.1091699824E-2 -2.0229380578E-2 -1.2604200281E-2 -1.7774800071E-3 3.0809799209E-3 2.3255399428E-3 -1.5970399836E-3
-2.5168000138E-4 2.8898599558E-3 4.1121998802E-3 -7.4316998944E-3 -1.8847439438E-2 -1.1091699824E-2 2.1906599402E-2 6.8065837026E-2 9.0580143034E-2 6.8065837026E-2 2.1906599402E-2 -1.1091699824E-2 -1.8847439438E-2 -7.4316998944E-3 4.1121998802E-3 2.8898599558E-3 -2.5168000138E-4
-4.2019999819E-4 4.2872801423E-3 2.2212199401E-3 -9.0569201857E-3 -1.7508180812E-2 3.9556599222E-3 6.8065837026E-2 0.1445499808 0.1773651242 0.1445499808 6.8065837026E-2 3.9556599222E-3 -1.7508180812E-2 -9.0569201857E-3 2.2212199401E-3 4.2872801423E-3 -4.2019999819E-4
1.2619999470E-3 5.5893999524E-3 5.5381999118E-4 -9.6372198313E-3 -1.6485679895E-2 1.4385120012E-2 9.0580143034E-2 0.1773651242 0.2120374441 0.1773651242 9.0580143034E-2 1.4385120012E-2 -1.6485679895E-2 -9.6372198313E-3 5.5381999118E-4 5.5893999524E-3 1.2619999470E-3
-4.2019999819E-4 4.2872801423E-3 2.2212199401E-3 -9.0569201857E-3 -1.7508180812E-2 3.9556599222E-3 6.8065837026E-2 0.1445499808 0.1773651242 0.1445499808 6.8065837026E-2 3.9556599222E-3 -1.7508180812E-2 -9.0569201857E-3 2.2212199401E-3 4.2872801423E-3 -4.2019999819E-4
-2.5168000138E-4 2.8898599558E-3 4.1121998802E-3 -7.4316998944E-3 -1.8847439438E-2 -1.1091699824E-2 2.1906599402E-2 6.8065837026E-2 9.0580143034E-2 6.8065837026E-2 2.1906599402E-2 -1.1091699824E-2 -1.8847439438E-2 -7.4316998944E-3 4.1121998802E-3 2.8898599558E-3 -2.5168000138E-4
-1.5970399836E-3 2.3255399428E-3 3.0809799209E-3 -1.7774800071E-3 -1.2604200281E-2 -2.0229380578E-2 -1.1091699824E-2 3.9556599222E-3 1.4385120012E-2 3.9556599222E-3 -1.1091699824E-2 -2.0229380578E-2 -1.2604200281E-2 -1.7774800071E-3 3.0809799209E-3 2.3255399428E-3 -1.5970399836E-3
-8.0063997302E-4 -1.3688000035E-4 3.7613599561E-3 3.1846798956E-3 -3.5306399222E-3 -1.2604200281E-2 -1.8847439438E-2 -1.7508180812E-2 -1.6485679895E-2 -1.7508180812E-2 -1.8847439438E-2 -1.2604200281E-2 -3.5306399222E-3 3.1846798956E-3 3.7613599561E-3 -1.3688000035E-4 -8.0063997302E-4
-1.2434000382E-4 5.6215998484E-4 2.1605400834E-3 3.1757799443E-3 3.1846798956E-3 -1.7774800071E-3 -7.4316998944E-3 -9.0569201857E-3 -9.6372198313E-3 -9.0569201857E-3 -7.4316998944E-3 -1.7774800071E-3 3.1846798956E-3 3.1757799443E-3 2.1605400834E-3 5.6215998484E-4 -1.2434000382E-4
-6.7714002216E-4 -5.8146001538E-4 1.4607800404E-3 2.1605400834E-3 3.7613599561E-3 3.0809799209E-3 4.1121998802E-3 2.2212199401E-3 5.5381999118E-4 2.2212199401E-3 4.1121998802E-3 3.0809799209E-3 3.7613599561E-3 2.1605400834E-3 1.4607800404E-3 -5.8146001538E-4 -6.7714002216E-4
1.2078000145E-4 4.4606000301E-4 -5.8146001538E-4 5.6215998484E-4 -1.3688000035E-4 2.3255399428E-3 2.8898599558E-3 4.2872801423E-3 5.5893999524E-3 4.2872801423E-3 2.8898599558E-3 2.3255399428E-3 -1.3688000035E-4 5.6215998484E-4 -5.8146001538E-4 4.4606000301E-4 1.2078000145E-4
-4.3500000174E-5 1.2078000145E-4 -6.7714002216E-4 -1.2434000382E-4 -8.0063997302E-4 -1.5970399836E-3 -2.5168000138E-4 -4.2019999819E-4 1.2619999470E-3 -4.2019999819E-4 -2.5168000138E-4 -1.5970399836E-3 -8.0063997302E-4 -1.2434000382E-4 -6.7714002216E-4 1.2078000145E-4 -4.3500000174E-5
];
bfilts = [...
-8.1125000725E-4 4.4451598078E-3 1.2316980399E-2 1.3955879956E-2 1.4179450460E-2 1.3955879956E-2 1.2316980399E-2 4.4451598078E-3 -8.1125000725E-4 ...
3.9103501476E-3 4.4565401040E-3 -5.8724298142E-3 -2.8760801069E-3 8.5267601535E-3 -2.8760801069E-3 -5.8724298142E-3 4.4565401040E-3 3.9103501476E-3 ...
1.3462699717E-3 -3.7740699481E-3 8.2581602037E-3 3.9442278445E-2 5.3605638444E-2 3.9442278445E-2 8.2581602037E-3 -3.7740699481E-3 1.3462699717E-3 ...
7.4700999539E-4 -3.6522001028E-4 -2.2522680461E-2 -0.1105690673 -0.1768419296 -0.1105690673 -2.2522680461E-2 -3.6522001028E-4 7.4700999539E-4 ...
0.0000000000 0.0000000000 0.0000000000 0.0000000000 0.0000000000 0.0000000000 0.0000000000 0.0000000000 0.0000000000 ...
-7.4700999539E-4 3.6522001028E-4 2.2522680461E-2 0.1105690673 0.1768419296 0.1105690673 2.2522680461E-2 3.6522001028E-4 -7.4700999539E-4 ...
-1.3462699717E-3 3.7740699481E-3 -8.2581602037E-3 -3.9442278445E-2 -5.3605638444E-2 -3.9442278445E-2 -8.2581602037E-3 3.7740699481E-3 -1.3462699717E-3 ...
-3.9103501476E-3 -4.4565401040E-3 5.8724298142E-3 2.8760801069E-3 -8.5267601535E-3 2.8760801069E-3 5.8724298142E-3 -4.4565401040E-3 -3.9103501476E-3 ...
8.1125000725E-4 -4.4451598078E-3 -1.2316980399E-2 -1.3955879956E-2 -1.4179450460E-2 -1.3955879956E-2 -1.2316980399E-2 -4.4451598078E-3 8.1125000725E-4; ...
...
0.0000000000 -8.2846998703E-4 -5.7109999034E-5 4.0110000555E-5 4.6670897864E-3 8.0871898681E-3 1.4807609841E-2 8.6204400286E-3 -3.1221499667E-3 ...
8.2846998703E-4 0.0000000000 -9.7479997203E-4 -6.9718998857E-3 -2.0865600090E-3 2.3298799060E-3 -4.4814897701E-3 1.4917500317E-2 8.6204400286E-3 ...
5.7109999034E-5 9.7479997203E-4 0.0000000000 -1.2145539746E-2 -2.4427289143E-2 5.0797060132E-2 3.2785870135E-2 -4.4814897701E-3 1.4807609841E-2 ...
-4.0110000555E-5 6.9718998857E-3 1.2145539746E-2 0.0000000000 -0.1510555595 -8.2495503128E-2 5.0797060132E-2 2.3298799060E-3 8.0871898681E-3 ...
-4.6670897864E-3 2.0865600090E-3 2.4427289143E-2 0.1510555595 0.0000000000 -0.1510555595 -2.4427289143E-2 -2.0865600090E-3 4.6670897864E-3 ...
-8.0871898681E-3 -2.3298799060E-3 -5.0797060132E-2 8.2495503128E-2 0.1510555595 0.0000000000 -1.2145539746E-2 -6.9718998857E-3 4.0110000555E-5 ...
-1.4807609841E-2 4.4814897701E-3 -3.2785870135E-2 -5.0797060132E-2 2.4427289143E-2 1.2145539746E-2 0.0000000000 -9.7479997203E-4 -5.7109999034E-5 ...
-8.6204400286E-3 -1.4917500317E-2 4.4814897701E-3 -2.3298799060E-3 2.0865600090E-3 6.9718998857E-3 9.7479997203E-4 0.0000000000 -8.2846998703E-4 ...
3.1221499667E-3 -8.6204400286E-3 -1.4807609841E-2 -8.0871898681E-3 -4.6670897864E-3 -4.0110000555E-5 5.7109999034E-5 8.2846998703E-4 0.0000000000; ...
...
8.1125000725E-4 -3.9103501476E-3 -1.3462699717E-3 -7.4700999539E-4 0.0000000000 7.4700999539E-4 1.3462699717E-3 3.9103501476E-3 -8.1125000725E-4 ...
-4.4451598078E-3 -4.4565401040E-3 3.7740699481E-3 3.6522001028E-4 0.0000000000 -3.6522001028E-4 -3.7740699481E-3 4.4565401040E-3 4.4451598078E-3 ...
-1.2316980399E-2 5.8724298142E-3 -8.2581602037E-3 2.2522680461E-2 0.0000000000 -2.2522680461E-2 8.2581602037E-3 -5.8724298142E-3 1.2316980399E-2 ...
-1.3955879956E-2 2.8760801069E-3 -3.9442278445E-2 0.1105690673 0.0000000000 -0.1105690673 3.9442278445E-2 -2.8760801069E-3 1.3955879956E-2 ...
-1.4179450460E-2 -8.5267601535E-3 -5.3605638444E-2 0.1768419296 0.0000000000 -0.1768419296 5.3605638444E-2 8.5267601535E-3 1.4179450460E-2 ...
-1.3955879956E-2 2.8760801069E-3 -3.9442278445E-2 0.1105690673 0.0000000000 -0.1105690673 3.9442278445E-2 -2.8760801069E-3 1.3955879956E-2 ...
-1.2316980399E-2 5.8724298142E-3 -8.2581602037E-3 2.2522680461E-2 0.0000000000 -2.2522680461E-2 8.2581602037E-3 -5.8724298142E-3 1.2316980399E-2 ...
-4.4451598078E-3 -4.4565401040E-3 3.7740699481E-3 3.6522001028E-4 0.0000000000 -3.6522001028E-4 -3.7740699481E-3 4.4565401040E-3 4.4451598078E-3 ...
8.1125000725E-4 -3.9103501476E-3 -1.3462699717E-3 -7.4700999539E-4 0.0000000000 7.4700999539E-4 1.3462699717E-3 3.9103501476E-3 -8.1125000725E-4; ...
...
3.1221499667E-3 -8.6204400286E-3 -1.4807609841E-2 -8.0871898681E-3 -4.6670897864E-3 -4.0110000555E-5 5.7109999034E-5 8.2846998703E-4 0.0000000000 ...
-8.6204400286E-3 -1.4917500317E-2 4.4814897701E-3 -2.3298799060E-3 2.0865600090E-3 6.9718998857E-3 9.7479997203E-4 -0.0000000000 -8.2846998703E-4 ...
-1.4807609841E-2 4.4814897701E-3 -3.2785870135E-2 -5.0797060132E-2 2.4427289143E-2 1.2145539746E-2 0.0000000000 -9.7479997203E-4 -5.7109999034E-5 ...
-8.0871898681E-3 -2.3298799060E-3 -5.0797060132E-2 8.2495503128E-2 0.1510555595 -0.0000000000 -1.2145539746E-2 -6.9718998857E-3 4.0110000555E-5 ...
-4.6670897864E-3 2.0865600090E-3 2.4427289143E-2 0.1510555595 0.0000000000 -0.1510555595 -2.4427289143E-2 -2.0865600090E-3 4.6670897864E-3 ...
-4.0110000555E-5 6.9718998857E-3 1.2145539746E-2 0.0000000000 -0.1510555595 -8.2495503128E-2 5.0797060132E-2 2.3298799060E-3 8.0871898681E-3 ...
5.7109999034E-5 9.7479997203E-4 -0.0000000000 -1.2145539746E-2 -2.4427289143E-2 5.0797060132E-2 3.2785870135E-2 -4.4814897701E-3 1.4807609841E-2 ...
8.2846998703E-4 -0.0000000000 -9.7479997203E-4 -6.9718998857E-3 -2.0865600090E-3 2.3298799060E-3 -4.4814897701E-3 1.4917500317E-2 8.6204400286E-3 ...
0.0000000000 -8.2846998703E-4 -5.7109999034E-5 4.0110000555E-5 4.6670897864E-3 8.0871898681E-3 1.4807609841E-2 8.6204400286E-3 -3.1221499667E-3 ...
]';
|
github
|
jbhuang0604/LapSRN-master
|
buildWpyr.m
|
.m
|
LapSRN-master/utils/matlabPyrTools/buildWpyr.m
| 2,644 |
utf_8
|
e741b2037d9a1358d4de94580ebcc4bf
|
% [PYR, INDICES] = buildWpyr(IM, HEIGHT, FILT, EDGES)
%
% Construct a separable orthonormal QMF/wavelet pyramid on matrix (or vector) IM.
%
% HEIGHT (optional) specifies the number of pyramid levels to build. Default
% is maxPyrHt(IM,FILT). You can also specify 'auto' to use this value.
%
% FILT (optional) can be a string naming a standard filter (see
% namedFilter), or a vector which will be used for (separable)
% convolution. Filter can be of even or odd length, but should be symmetric.
% Default = 'qmf9'. EDGES specifies edge-handling, and
% defaults to 'reflect1' (see corrDn).
%
% PYR is a vector containing the N pyramid subbands, ordered from fine
% to coarse. INDICES is an Nx2 matrix containing the sizes of
% each subband. This is compatible with the MatLab Wavelet toolbox.
% Eero Simoncelli, 6/96, based on original lisp code from 1987.
function [pyr,pind] = buildWpyr(im, ht, filt, edges)
if (nargin < 1)
error('First argument (IM) is required');
end
%------------------------------------------------------------
%% OPTIONAL ARGS:
if (exist('filt') ~= 1)
filt = 'qmf9';
end
if (exist('edges') ~= 1)
edges= 'reflect1';
end
if isstr(filt)
filt = namedFilter(filt);
end
if ( (size(filt,1) > 1) & (size(filt,2) > 1) )
error('FILT should be a 1D filter (i.e., a vector)');
else
filt = filt(:);
end
hfilt = modulateFlip(filt);
% Stagger sampling if filter is odd-length:
if (mod(size(filt,1),2) == 0)
stag = 2;
else
stag = 1;
end
im_sz = size(im);
max_ht = maxPyrHt(im_sz, size(filt,1));
if ( (exist('ht') ~= 1) | (ht == 'auto') )
ht = max_ht;
else
if (ht > max_ht)
error(sprintf('Cannot build pyramid higher than %d levels.',max_ht));
end
end
if (ht <= 0)
pyr = im(:);
pind = im_sz;
else
if (im_sz(2) == 1)
lolo = corrDn(im, filt, edges, [2 1], [stag 1]);
hihi = corrDn(im, hfilt, edges, [2 1], [2 1]);
elseif (im_sz(1) == 1)
lolo = corrDn(im, filt', edges, [1 2], [1 stag]);
hihi = corrDn(im, hfilt', edges, [1 2], [1 2]);
else
lo = corrDn(im, filt, edges, [2 1], [stag 1]);
hi = corrDn(im, hfilt, edges, [2 1], [2 1]);
lolo = corrDn(lo, filt', edges, [1 2], [1 stag]);
lohi = corrDn(hi, filt', edges, [1 2], [1 stag]); % horizontal
hilo = corrDn(lo, hfilt', edges, [1 2], [1 2]); % vertical
hihi = corrDn(hi, hfilt', edges, [1 2], [1 2]); % diagonal
end
[npyr,nind] = buildWpyr(lolo, ht-1, filt, edges);
if ((im_sz(1) == 1) | (im_sz(2) == 1))
pyr = [hihi(:); npyr];
pind = [size(hihi); nind];
else
pyr = [lohi(:); hilo(:); hihi(:); npyr];
pind = [size(lohi); size(hilo); size(hihi); nind];
end
end
|
github
|
jbhuang0604/LapSRN-master
|
reconLpyr.m
|
.m
|
LapSRN-master/utils/matlabPyrTools/reconLpyr.m
| 2,049 |
utf_8
|
657b8012a1ed06b6573496855309b2ae
|
% RES = reconLpyr(PYR, INDICES, LEVS, FILT2, EDGES)
%
% Reconstruct image from Laplacian pyramid, as created by buildLpyr.
%
% PYR is a vector containing the N pyramid subbands, ordered from fine
% to coarse. INDICES is an Nx2 matrix containing the sizes of
% each subband. This is compatible with the MatLab Wavelet toolbox.
%
% LEVS (optional) should be a list of levels to include, or the string
% 'all' (default). The finest scale is number 1. The lowpass band
% corresponds to lpyrHt(INDICES)+1.
%
% FILT2 (optional) can be a string naming a standard filter (see
% namedFilter), or a vector which will be used for (separable)
% convolution. Default = 'binom5'. EDGES specifies edge-handling,
% and defaults to 'reflect1' (see corrDn).
% Eero Simoncelli, 6/96
function res = reconLpyr(pyr, ind, levs, filt2, edges)
if (nargin < 2)
error('First two arguments (PYR, INDICES) are required');
end
%%------------------------------------------------------------
%% DEFAULTS:
if (exist('levs') ~= 1)
levs = 'all';
end
if (exist('filt2') ~= 1)
filt2 = 'binom5';
end
if (exist('edges') ~= 1)
edges= 'reflect1';
end
%%------------------------------------------------------------
maxLev = 1+lpyrHt(ind);
if strcmp(levs,'all')
levs = [1:maxLev]';
else
if (any(levs > maxLev))
error(sprintf('Level numbers must be in the range [1, %d].', maxLev));
end
levs = levs(:);
end
if isstr(filt2)
filt2 = namedFilter(filt2);
end
filt2 = filt2(:);
res_sz = ind(1,:);
if any(levs > 1)
int_sz = [ind(1,1), ind(2,2)];
nres = reconLpyr( pyr(prod(res_sz)+1:size(pyr,1)), ...
ind(2:size(ind,1),:), levs-1, filt2, edges);
if (res_sz(1) == 1)
res = upConv(nres, filt2', edges, [1 2], [1 1], res_sz);
elseif (res_sz(2) == 1)
res = upConv(nres, filt2, edges, [2 1], [1 1], res_sz);
else
hi = upConv(nres, filt2, edges, [2 1], [1 1], int_sz);
res = upConv(hi, filt2', edges, [1 2], [1 1], res_sz);
end
else
res = zeros(res_sz);
end
if any(levs == 1)
res = res + pyrBand(pyr,ind,1);
end
|
github
|
jbhuang0604/LapSRN-master
|
mkDisc.m
|
.m
|
LapSRN-master/utils/matlabPyrTools/mkDisc.m
| 1,428 |
utf_8
|
c6acae0ac1aa738b7ef094eb2ac60f52
|
% IM = mkDisc(SIZE, RADIUS, ORIGIN, TWIDTH, VALS)
%
% Make a "disk" image. SIZE specifies the matrix size, as for
% zeros(). RADIUS (default = min(size)/4) specifies the radius of
% the disk. ORIGIN (default = (size+1)/2) specifies the
% location of the disk center. TWIDTH (in pixels, default = 2)
% specifies the width over which a soft threshold transition is made.
% VALS (default = [0,1]) should be a 2-vector containing the
% intensity value inside and outside the disk.
% Eero Simoncelli, 6/96.
function [res] = mkDisc(sz, rad, origin, twidth, vals)
if (nargin < 1)
error('Must pass at least a size argument');
end
sz = sz(:);
if (size(sz,1) == 1)
sz = [sz sz];
end
%------------------------------------------------------------
% OPTIONAL ARGS:
if (exist('rad') ~= 1)
rad = min(sz(1),sz(2))/4;
end
if (exist('origin') ~= 1)
origin = (sz+1)./2;
end
if (exist('twidth') ~= 1)
twidth = 2;
end
if (exist('vals') ~= 1)
vals = [1,0];
end
%------------------------------------------------------------
res = mkR(sz,1,origin);
if (abs(twidth) < realmin)
res = vals(2) + (vals(1) - vals(2)) * (res <= rad);
else
[Xtbl,Ytbl] = rcosFn(twidth, rad, [vals(1), vals(2)]);
res = pointOp(res, Ytbl, Xtbl(1), Xtbl(2)-Xtbl(1), 0);
%
% OLD interp1 VERSION:
% res = res(:);
% Xtbl(1) = min(res);
% Xtbl(size(Xtbl,2)) = max(res);
% res = reshape(interp1(Xtbl,Ytbl,res), sz(1), sz(2));
%
end
|
github
|
jbhuang0604/LapSRN-master
|
spyrHigh.m
|
.m
|
LapSRN-master/utils/matlabPyrTools/spyrHigh.m
| 189 |
utf_8
|
3132a747e0c7bf1879bb32e4d5fda257
|
% RES = spyrHigh(PYR, INDICES)
%
% Access the highpass residual band from a steerable pyramid.
% Eero Simoncelli, 6/96.
function res = spyrHigh(pyr,pind)
res = pyrBand(pyr, pind, 1);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.