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
Shenc0411/CS445-master
vl_test_phow.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_phow.m
549
utf_8
f761a3bb218af855986263c67b2da411
function results = vl_test_phow(varargin) % VL_TEST_PHOPW vl_test_init ; function s = setup() s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ; s.I = single(s.I) ; function test_gray(s) [f,d] = vl_phow(s.I, 'color', 'gray') ; assert(size(d,1) == 128) ; function test_rgb(s) [f,d] = vl_phow(s.I, 'color', 'rgb') ; assert(size(d,1) == 128*3) ; function test_hsv(s) [f,d] = vl_phow(s.I, 'color', 'hsv') ; assert(size(d,1) == 128*3) ; function test_opponent(s) [f,d] = vl_phow(s.I, 'color', 'opponent') ; assert(size(d,1) == 128*3) ;
github
Shenc0411/CS445-master
vl_test_kmeans.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_kmeans.m
3,632
utf_8
0e1d6f4f8101c8982a0e743e0980c65a
function results = vl_test_kmeans(varargin) % VL_TEST_KMEANS % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % 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). vl_test_init ; function s = setup() randn('state',0) ; s.X = randn(128, 100) ; function test_basic(s) [centers, assignments, en] = vl_kmeans(s.X, 10, 'NumRepetitions', 10) ; [centers_, assignments_, en_] = simpleKMeans(s.X, 10) ; assert(en_ <= 1.1 * en, 'vl_kmeans did not optimize enough') ; function test_algorithms(s) distances = {'l1', 'l2'} ; dataTypes = {'single','double'} ; for dataType = dataTypes for distance = distances distance = char(distance) ; conversion = str2func(char(dataType)) ; X = conversion(s.X) ; vl_twister('state',0) ; [centers, assignments, en] = vl_kmeans(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Algorithm', 'Lloyd', ... 'Distance', distance) ; vl_twister('state',0) ; [centers_, assignments_, en_] = vl_kmeans(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Algorithm', 'Elkan', ... 'Distance', distance) ; vl_twister('state',0) ; [centers__, assignments__, en__] = vl_kmeans(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Algorithm', 'ANN', ... 'Distance', distance, ... 'NumTrees', 3, ... 'MaxNumComparisons',0) ; vl_assert_almost_equal(centers, centers_, 1e-5) ; vl_assert_almost_equal(assignments, assignments_, 1e-5) ; vl_assert_almost_equal(en, en_, 1e-4) ; vl_assert_almost_equal(centers, centers__, 1e-5) ; vl_assert_almost_equal(assignments, assignments__, 1e-5) ; vl_assert_almost_equal(en, en__, 1e-4) ; vl_assert_almost_equal(centers_, centers__, 1e-5) ; vl_assert_almost_equal(assignments_, assignments__, 1e-5) ; vl_assert_almost_equal(en_, en__, 1e-4) ; end end function test_patterns(s) distances = {'l1', 'l2'} ; dataTypes = {'single','double'} ; for dataType = dataTypes for distance = distances distance = char(distance) ; conversion = str2func(char(dataType)) ; data = [1 1 0 0 ; 1 0 1 0] ; data = conversion(data) ; [centers, assignments, en] = vl_kmeans(data, 4, ... 'NumRepetitions', 100, ... 'Distance', distance) ; assert(isempty(setdiff(data', centers', 'rows'))) ; end end function [centers, assignments, en] = simpleKMeans(X, numCenters) [dimension, numData] = size(X) ; centers = randn(dimension, numCenters) ; for iter = 1:10 [dists, assignments] = min(vl_alldist(centers, X)) ; en = sum(dists) ; centers = [zeros(dimension, numCenters) ; ones(1, numCenters)] ; centers = vl_binsum(centers, ... [X ; ones(1,numData)], ... repmat(assignments, dimension+1, 1), 2) ; centers = centers(1:end-1, :) ./ repmat(centers(end,:), dimension, 1) ; end
github
Shenc0411/CS445-master
vl_test_hikmeans.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_hikmeans.m
463
utf_8
dc3b493646e66316184e86ff4e6138ab
function results = vl_test_hikmeans(varargin) % VL_TEST_IKMEANS vl_test_init ; function s = setup() rand('state',0) ; s.data = uint8(rand(2,1000) * 255) ; function test_basic(s) [tree, assign] = vl_hikmeans(s.data,3,100) ; assign_ = vl_hikmeanspush(tree, s.data) ; vl_assert_equal(assign,assign_) ; function test_elkan(s) [tree, assign] = vl_hikmeans(s.data,3,100,'method','elkan') ; assign_ = vl_hikmeanspush(tree, s.data) ; vl_assert_equal(assign,assign_) ;
github
Shenc0411/CS445-master
vl_test_aib.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_aib.m
1,277
utf_8
78978ae54e7ebe991d136336ba4bf9c6
function results = vl_test_aib(varargin) % VL_TEST_AIB vl_test_init ; function s = setup() s = [] ; function test_basic(s) Pcx = [.3 .3 0 0 0 0 .2 .2] ; % This results in the AIB tree % % 1 - \ % 5 - \ % 2 - / \ % - 7 % 3 - \ / % 6 - / % 4 - / % % coded by the map [5 5 6 6 7 1] (1 denotes the root). [parents,cost] = vl_aib(Pcx) ; vl_assert_equal(parents, [5 5 6 6 7 7 1]) ; vl_assert_almost_equal(mi(Pcx)*[1 1 1], cost(1:3), 1e-3) ; [cut,map,short] = vl_aibcut(parents,2) ; vl_assert_equal(cut, [5 6]) ; vl_assert_equal(map, [1 1 2 2 1 2 0]) ; vl_assert_equal(short, [5 5 6 6 5 6 7]) ; function test_cluster_null(s) Pcx = [.5 .5 0 0 0 0 0 0] ; % This results in the AIB tree % % 1 - \ % 5 % 2 - / % % 3 x % % 4 x % % If ClusterNull is specified, the values 3 and 4 % which have zero probability are merged first % % 1 ----------\ % 7 % 2 ----- \ / % 6-/ % 3 -\ / % 5 -/ % 4 -/ parents1 = vl_aib(Pcx) ; parents2 = vl_aib(Pcx,'ClusterNull') ; vl_assert_equal(parents1, [5 5 0 0 1 0 0]) ; vl_assert_equal(parents2(3), parents2(4)) ; function x = mi(P) % mutual information P1 = sum(P,1) ; P2 = sum(P,2) ; x = sum(sum(P .* log(max(P,1e-10) ./ (P2*P1)))) ;
github
Shenc0411/CS445-master
vl_test_plotbox.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_plotbox.m
414
utf_8
aa06ce4932a213fb933bbede6072b029
function results = vl_test_plotbox(varargin) % VL_TEST_PLOTBOX vl_test_init ; function test_basic(s) figure(1) ; clf ; vl_plotbox([-1 -1 1 1]') ; xlim([-2 2]) ; ylim([-2 2]) ; close(1) ; function test_multiple(s) figure(1) ; clf ; randn('state', 0) ; vl_plotbox(randn(4,10)) ; close(1) ; function test_style(s) figure(1) ; clf ; randn('state', 0) ; vl_plotbox(randn(4,10), 'r-.', 'LineWidth', 3) ; close(1) ;
github
Shenc0411/CS445-master
vl_test_imarray.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_imarray.m
795
utf_8
c5e6a5aa8c2e63e248814f5bd89832a8
function results = vl_test_imarray(varargin) % VL_TEST_IMARRAY vl_test_init ; function test_movie_rgb(s) A = rand(23,15,3,4) ; B = vl_imarray(A,'movie',true) ; function test_movie_indexed(s) cmap = get(0,'DefaultFigureColormap') ; A = uint8(size(cmap,1)*rand(23,15,4)) ; A = min(A,size(cmap,1)-1) ; B = vl_imarray(A,'movie',true) ; function test_movie_gray_indexed(s) A = uint8(255*rand(23,15,4)) ; B = vl_imarray(A,'movie',true,'cmap',gray(256)) ; for k=1:size(A,3) vl_assert_equal(squeeze(A(:,:,k)), ... frame2im(B(k))) ; end function test_basic(s) M = 3 ; N = 4 ; width = 32 ; height = 15 ; for i=1:M for j=1:N A{i,j} = rand(width,height) ; end end A1 = A'; A1 = cat(3,A1{:}) ; A2 = cell2mat(A) ; B = vl_imarray(A1, 'layout', [M N]) ; vl_assert_equal(A2,B) ;
github
Shenc0411/CS445-master
vl_test_homkermap.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_homkermap.m
1,903
utf_8
c157052bf4213793a961bde1f73fb307
function results = vl_test_homkermap(varargin) % VL_TEST_HOMKERMAP vl_test_init ; function check_ker(ker, n, window, period) args = {n, ker, 'window', window} ; if nargin > 3 args = {args{:}, 'period', period} ; end x = [-1 -.5 0 .5 1] ; y = linspace(0,2,100) ; for conv = {@single, @double} x = feval(conv{1}, x) ; y = feval(conv{1}, y) ; sx = sign(x) ; sy = sign(y) ; psix = vl_homkermap(x, args{:}) ; psiy = vl_homkermap(y, args{:}) ; k = vl_alldist(psix,psiy,'kl2') ; k_ = (sx'*sy) .* vl_alldist(sx.*x,sy.*y,ker) ; vl_assert_almost_equal(k, k_, 2e-2) ; end function test_uniform_kchi2(), check_ker('kchi2', 3, 'uniform', 15) ; function test_uniform_kjs(), check_ker('kjs', 3, 'uniform', 15) ; function test_uniform_kl1(), check_ker('kl1', 29, 'uniform', 15) ; function test_rect_kchi2(), check_ker('kchi2', 3, 'rectangular', 15) ; function test_rect_kjs(), check_ker('kjs', 3, 'rectangular', 15) ; function test_rect_kl1(), check_ker('kl1', 29, 'rectangular', 10) ; function test_auto_uniform_kchi2(),check_ker('kchi2', 3, 'uniform') ; function test_auto_uniform_kjs(), check_ker('kjs', 3, 'uniform') ; function test_auto_uniform_kl1(), check_ker('kl1', 25, 'uniform') ; function test_auto_rect_kchi2(), check_ker('kchi2', 3, 'rectangular') ; function test_auto_rect_kjs(), check_ker('kjs', 3, 'rectangular') ; function test_auto_rect_kl1(), check_ker('kl1', 25, 'rectangular') ; function test_gamma() x = linspace(0,1,20) ; for gamma = linspace(.2,2,10) k = vl_alldist(x, 'kchi2') .* (x'*x + 1e-12).^((gamma-1)/2) ; psix = vl_homkermap(x, 3, 'kchi2', 'gamma', gamma) ; assert(norm(k - psix'*psix) < 1e-2) ; end function test_negative() x = linspace(-1,1,20) ; k = vl_alldist(abs(x), 'kchi2') .* (sign(x)'*sign(x)) ; psix = vl_homkermap(x, 3, 'kchi2') ; assert(norm(k - psix'*psix) < 1e-2) ;
github
Shenc0411/CS445-master
vl_test_slic.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_slic.m
200
utf_8
12a6465e3ef5b4bcfd7303cd8a9229d4
function results = vl_test_slic(varargin) % VL_TEST_SLIC vl_test_init ; function s = setup() s.im = im2single(vl_impattern('roofs1')) ; function test_slic(s) segmentation = vl_slic(s.im, 10, 0.1) ;
github
Shenc0411/CS445-master
vl_test_ikmeans.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_ikmeans.m
466
utf_8
1ee2f647ac0035ed0d704a0cd615b040
function results = vl_test_ikmeans(varargin) % VL_TEST_IKMEANS vl_test_init ; function s = setup() rand('state',0) ; s.data = uint8(rand(2,1000) * 255) ; function test_basic(s) [centers, assign] = vl_ikmeans(s.data,100) ; assign_ = vl_ikmeanspush(s.data, centers) ; vl_assert_equal(assign,assign_) ; function test_elkan(s) [centers, assign] = vl_ikmeans(s.data,100,'method','elkan') ; assign_ = vl_ikmeanspush(s.data, centers) ; vl_assert_equal(assign,assign_) ;
github
Shenc0411/CS445-master
vl_test_mser.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_mser.m
242
utf_8
1ad33563b0c86542a2978ee94e0f4a39
function results = vl_test_mser(varargin) % VL_TEST_MSER vl_test_init ; function s = setup() s.im = im2uint8(rgb2gray(vl_impattern('roofs1'))) ; function test_mser(s) [regions,frames] = vl_mser(s.im) ; mask = vl_erfill(s.im, regions(1)) ;
github
Shenc0411/CS445-master
vl_test_inthist.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_inthist.m
811
utf_8
459027d0c54d8f197563a02ab66ef45d
function results = vl_test_inthist(varargin) % VL_TEST_INTHIST vl_test_init ; function s = setup() rand('state',0) ; s.labels = uint32(8*rand(123, 76, 3)) ; function test_basic(s) l = 10 ; hist = vl_inthist(s.labels, 'numlabels', l) ; hist_ = inthist_slow(s.labels, l) ; vl_assert_equal(double(hist),hist_) ; function test_sample(s) rand('state',0) ; boxes = 10 * rand(4,20) + .5 ; boxes(3:4,:) = boxes(3:4,:) + boxes(1:2,:) ; boxes = min(boxes, 10) ; boxes = uint32(boxes) ; inthist = vl_inthist(s.labels) ; hist = vl_sampleinthist(inthist, boxes) ; function hist = inthist_slow(labels, numLabels) m = size(labels,1) ; n = size(labels,2) ; l = numLabels ; b = zeros(m*n,l) ; b = vl_binsum(b, 1, reshape(labels,m*n,[]), 2) ; b = reshape(b,m,n,l) ; for k=1:l hist(:,:,k) = cumsum(cumsum(b(:,:,k)')') ; end
github
Shenc0411/CS445-master
vl_test_imdisttf.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_imdisttf.m
1,885
utf_8
ae921197988abeb984cbcdf9eaf80e77
function results = vl_test_imdisttf(varargin) % VL_TEST_DISTTF vl_test_init ; function test_basic() for conv = {@single, @double} conv = conv{1} ; I = conv([0 0 0 ; 0 -2 0 ; 0 0 0]) ; D = vl_imdisttf(I); assert(isequal(D, conv(- [0 1 0 ; 1 2 1 ; 0 1 0]))) ; I(2,2) = -3 ; [D,map] = vl_imdisttf(I) ; assert(isequal(D, conv(-1 - [0 1 0 ; 1 2 1 ; 0 1 0]))) ; assert(isequal(map, 5 * ones(3))) ; end function test_1x1() assert(isequal(1, vl_imdisttf(1))) ; function test_rand() I = rand(13,31) ; for t=1:4 param = [rand randn rand randn] ; [D0,map0] = imdisttf_equiv(I,param) ; [D,map] = vl_imdisttf(I,param) ; vl_assert_almost_equal(D,D0,1e-10) assert(isequal(map,map0)) ; end function test_param() I = zeros(3,4) ; I(1,1) = -1 ; [D,map] = vl_imdisttf(I,[1 0 1 0]); assert(isequal(-[1 0 0 0 ; 0 0 0 0 ; 0 0 0 0 ;], D)) ; D0 = -[1 .9 .6 .1 ; 0 0 0 0 ; 0 0 0 0 ;] ; [D,map] = vl_imdisttf(I,[.1 0 1 0]); vl_assert_almost_equal(D,D0,1e-10); D0 = -[1 .9 .6 .1 ; .9 .8 .5 0 ; .6 .5 .2 0 ;] ; [D,map] = vl_imdisttf(I,[.1 0 .1 0]); vl_assert_almost_equal(D,D0,1e-10); D0 = -[.9 1 .9 .6 ; .8 .9 .8 .5 ; .5 .6 .5 .2 ; ] ; [D,map] = vl_imdisttf(I,[.1 1 .1 0]); vl_assert_almost_equal(D,D0,1e-10); function test_special() I = rand(13,31) -.5 ; D = vl_imdisttf(I, [0 0 1e5 0]) ; vl_assert_almost_equal(D(:,1),min(I,[],2),1e-10); D = vl_imdisttf(I, [1e5 0 0 0]) ; vl_assert_almost_equal(D(1,:),min(I,[],1),1e-10); function [D,map]=imdisttf_equiv(I,param) D = inf + zeros(size(I)) ; map = zeros(size(I)) ; ur = 1:size(D,2) ; vr = 1:size(D,1) ; [u,v] = meshgrid(ur,vr) ; for v_=vr for u_=ur E = I(v_,u_) + ... param(1) * (u - u_ - param(2)).^2 + ... param(3) * (v - v_ - param(4)).^2 ; map(E < D) = sub2ind(size(I),v_,u_) ; D = min(D,E) ; end end
github
Shenc0411/CS445-master
vl_test_vlad.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_vlad.m
1,977
utf_8
d3797288d6edb1d445b890db3780c8ce
function results = vl_test_vlad(varargin) % VL_TEST_VLAD vl_test_init ; function s = setup() randn('state',0) ; s.x = randn(128,256) ; s.mu = randn(128,16) ; assignments = rand(16, 256) ; s.assignments = bsxfun(@times, assignments, 1 ./ sum(assignments,1)) ; function test_basic (s) x = [1, 2, 3] ; mu = [0, 0, 0] ; assignments = eye(3) ; phi = vl_vlad(x, mu, assignments, 'unnormalized') ; vl_assert_equal(phi, [1 2 3]') ; mu = [0, 1, 2] ; phi = vl_vlad(x, mu, assignments, 'unnormalized') ; vl_assert_equal(phi, [1 1 1]') ; phi = vl_vlad([x x], mu, [assignments assignments], 'unnormalized') ; vl_assert_equal(phi, [2 2 2]') ; function test_rand (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized') ; vl_assert_equal(phi, phi_) ; function test_norm (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = phi_ / norm(phi_) ; phi = vl_vlad(s.x, s.mu, s.assignments) ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function test_sqrt (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = sign(phi_) .* sqrt(abs(phi_)) ; phi_ = phi_ / norm(phi_) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'squareroot') ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function test_individual (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = reshape(phi_, size(s.x,1), []) ; phi_ = bsxfun(@times, phi_, 1 ./ sqrt(sum(phi_.^2))) ; phi_ = phi_(:) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizecomponents') ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function test_mass (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = reshape(phi_, size(s.x,1), []) ; phi_ = bsxfun(@times, phi_, 1 ./ sum(s.assignments,2)') ; phi_ = phi_(:) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizemass') ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function enc = simple_vlad(x, mu, assign) for i = 1:size(assign,1) enc{i} = x * assign(i,:)' - sum(assign(i,:)) * mu(:,i) ; end enc = cat(1, enc{:}) ;
github
Shenc0411/CS445-master
vl_test_pr.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_pr.m
3,763
utf_8
4d1da5ccda1a7df2bec35b8f12fdd620
function results = vl_test_pr(varargin) % VL_TEST_PR vl_test_init ; function s = setup() s.scores0 = [5 4 3 2 1] ; s.scores1 = [5 3 4 2 1] ; s.labels = [1 1 -1 -1 -1] ; function test_perfect_tptn(s) [rc,pr] = vl_pr(s.labels,s.scores0) ; vl_assert_almost_equal(pr, [1 1/1 2/2 2/3 2/4 2/5]) ; vl_assert_almost_equal(rc, [0 1 2 2 2 2] / 2) ; function test_perfect_metrics(s) [rc,pr,info] = vl_pr(s.labels,s.scores0) ; vl_assert_almost_equal(info.auc, 1) ; vl_assert_almost_equal(info.ap, 1) ; vl_assert_almost_equal(info.ap_interp_11, 1) ; function test_swap1_tptn(s) [rc,pr] = vl_pr(s.labels,s.scores1) ; vl_assert_almost_equal(pr, [1 1/1 1/2 2/3 2/4 2/5]) ; vl_assert_almost_equal(rc, [0 1 1 2 2 2] / 2) ; function test_swap1_tptn_stable(s) [rc,pr] = vl_pr(s.labels,s.scores1,'stable',true) ; vl_assert_almost_equal(pr, [1/1 2/3 1/2 2/4 2/5]) ; vl_assert_almost_equal(rc, [1 2 1 2 2] / 2) ; function test_swap1_metrics(s) [rc,pr,info] = vl_pr(s.labels,s.scores1) ; clf; vl_pr(s.labels,s.scores1) ; vl_assert_almost_equal(info.auc, [.5 + .5 * (.5 + 2/3)/2]) ; vl_assert_almost_equal(info.ap, [1/1 + 2/3]/2) ; vl_assert_almost_equal(info.ap_interp_11, mean([1 1 1 1 1 1 2/3 2/3 2/3 2/3 2/3])) ; function test_inf(s) scores = [1 -inf -1 -1 -1 -1] ; labels = [1 1 -1 -1 -1 -1] ; [rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true) ; [rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false) ; vl_assert_equal(numel(rc1), numel(rc2) + 1) ; vl_assert_almost_equal(info1.auc, [1 * .5 + (1/5 + 2/6)/2 * .5]) ; vl_assert_almost_equal(info1.ap, [1 * .5 + 2/6 * .5]) ; vl_assert_almost_equal(info1.ap_interp_11, [1 * 6/11 + 2/6 * 5/11]) ; vl_assert_almost_equal(info2.auc, 0.5) ; vl_assert_almost_equal(info2.ap, 0.5) ; vl_assert_almost_equal(info2.ap_interp_11, 1 * 6 / 11) ; function test_inf_stable(s) scores = [-1 -1 -1 -1 -inf +1] ; labels = [-1 -1 -1 -1 +1 +1] ; [rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true, 'stable', true) ; [rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false, 'stable', true) ; [rc1_,pr1_,info1_] = vl_pr(labels, scores, 'includeInf', true, 'stable', false) ; [rc2_,pr2_,info2_] = vl_pr(labels, scores, 'includeInf', false, 'stable', false) ; % stability does not change scores vl_assert_almost_equal(info1,info1_) ; vl_assert_almost_equal(info2,info2_) ; % unstable with inf (first point (0,1) is conventional) vl_assert_almost_equal(rc1_, [0 .5 .5 .5 .5 .5 1]) vl_assert_almost_equal(pr1_, [1 1 1/2 1/3 1/4 1/5 2/6]) % unstable without inf vl_assert_almost_equal(rc2_, [0 .5 .5 .5 .5 .5]) vl_assert_almost_equal(pr2_, [1 1 1/2 1/3 1/4 1/5]) % stable with inf (no conventional point here) vl_assert_almost_equal(rc1, [.5 .5 .5 .5 1 .5]) ; vl_assert_almost_equal(pr1, [1/2 1/3 1/4 1/5 2/6 1]) ; % stable without inf (no conventional point and -inf are NaN) vl_assert_almost_equal(rc2, [.5 .5 .5 .5 NaN .5]) ; vl_assert_almost_equal(pr2, [1/2 1/3 1/4 1/5 NaN 1]) ; function test_normalised_pr(s) scores = [+1 +2] ; labels = [+1 -1] ; [rc1,pr1,info1] = vl_pr(labels,scores) ; [rc2,pr2,info2] = vl_pr(labels,scores,'normalizePrior',.5) ; vl_assert_almost_equal(pr1, pr2) ; vl_assert_almost_equal(rc1, rc2) ; scores_ = [+1 +2 +2 +2] ; labels_ = [+1 -1 -1 -1] ; [rc3,pr3,info3] = vl_pr(labels_,scores_) ; [rc4,pr4,info4] = vl_pr(labels,scores,'normalizePrior',1/4) ; vl_assert_almost_equal(info3, info4) ; function test_normalised_pr_corner_cases(s) scores = 1:10 ; labels = ones(1,10) ; [rc1,pr1,info1] = vl_pr(labels,scores) ; vl_assert_almost_equal(rc1, (0:10)/10) ; vl_assert_almost_equal(pr1, ones(1,11)) ; scores = 1:10 ; labels = zeros(1,10) ; [rc2,pr2,info2] = vl_pr(labels,scores) ; vl_assert_almost_equal(rc2, zeros(1,11)) ; vl_assert_almost_equal(pr2, ones(1,11)) ;
github
Shenc0411/CS445-master
vl_test_hog.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_hog.m
1,555
utf_8
eed7b2a116d142040587dc9c4eb7cd2e
function results = vl_test_hog(varargin) % VL_TEST_HOG vl_test_init ; function s = setup() s.im = im2single(vl_impattern('roofs1')) ; [x,y]= meshgrid(linspace(-1,1,128)) ; s.round = single(x.^2+y.^2); s.imSmall = s.im(1:128,1:128,:) ; s.imSmall = s.im ; s.imSmallFlipped = s.imSmall(:,end:-1:1,:) ; function test_basic_call(s) cellSize = 8 ; hog = vl_hog(s.im, cellSize) ; function test_bilinear_orientations(s) cellSize = 8 ; vl_hog(s.im, cellSize, 'bilinearOrientations') ; function test_variants_and_flipping(s) variants = {'uoctti', 'dalaltriggs'} ; numOrientationsRange = 3:9 ; cellSize = 8 ; for cellSize = [4 8 16] for i=1:numel(variants) for j=1:numel(numOrientationsRange) args = {'bilinearOrientations', ... 'variant', variants{i}, ... 'numOrientations', numOrientationsRange(j)} ; hog = vl_hog(s.imSmall, cellSize, args{:}) ; perm = vl_hog('permutation', args{:}) ; hog1 = vl_hog(s.imSmallFlipped, cellSize, args{:}) ; hog2 = hog(:,end:-1:1,perm) ; %norm(hog1(:)-hog2(:)) vl_assert_almost_equal(hog1,hog2,1e-3) ; end end end function test_polar(s) cellSize = 8 ; im = s.round ; for b = [0 1] if b args = {'bilinearOrientations'} ; else args = {} ; end hog1 = vl_hog(im, cellSize, args{:}) ; [ix,iy] = vl_grad(im) ; m = sqrt(ix.^2 + iy.^2) ; a = atan2(iy,ix) ; m(:,[1 end]) = 0 ; m([1 end],:) = 0 ; hog2 = vl_hog(cat(3,m,a), cellSize, 'DirectedPolarField', args{:}) ; vl_assert_almost_equal(hog1,hog2,norm(hog1(:))/1000) ; end
github
Shenc0411/CS445-master
vl_test_argparse.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_argparse.m
795
utf_8
e72185b27206d0ee1dfdc19fe77a5be6
function results = vl_test_argparse(varargin) % VL_TEST_ARGPARSE vl_test_init ; function test_basic() opts.field1 = 1 ; opts.field2 = 2 ; opts.field3 = 3 ; opts_ = opts ; opts_.field1 = 3 ; opts_.field2 = 10 ; opts = vl_argparse(opts, {'field2', 10, 'field1', 3}) ; assert(isequal(opts, opts_)) ; opts_.field1 = 9 ; opts = vl_argparse(opts, {'field1', 4, 'field1', 9}) ; assert(isequal(opts, opts_)) ; function test_error() opts.field1 = 1 ; try opts = vl_argparse(opts, {'field2', 5}) ; catch e return ; end assert(false) ; function test_leftovers() opts1.field1 = 1 ; opts2.field2 = 1 ; opts1_.field1 = 2 ; opts2_.field2 = 2 ; [opts1,args] = vl_argparse(opts1, {'field1', 2, 'field2', 2}) ; opts2 = vl_argparse(opts2, args) ; assert(isequal(opts1,opts1_), isequal(opts2,opts2_)) ;
github
Shenc0411/CS445-master
vl_test_liop.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_liop.m
1,023
utf_8
a162be369073bed18e61210f44088cf3
function results = vl_test_liop(varargin) % VL_TEST_SIFT vl_test_init ; function s = setup() randn('state',0) ; s.patch = randn(65,'single') ; xr = -32:32 ; [x,y] = meshgrid(xr) ; s.blob = - single(x.^2+y.^2) ; function test_basic(s) d = vl_liop(s.patch) ; function test_blob(s) % with a blob, all local intensity order pattern are equal. In % particular, if the blob intensity decreases away from the center, % then all local intensities sampled in a neighbourhood of 2 elements % are already sorted (see LIOP details). d = vl_liop(s.blob, ... 'IntensityThreshold', 0, ... 'NumNeighbours', 2, ... 'NumSpatialBins', 1) ; assert(isequal(d, single([1;0]))) ; function test_neighbours(s) for n=2:5 for p=1:3 d = vl_liop(s.patch, 'NumNeighbours', n, 'NumSpatialBins', p) ; assert(numel(d) == p * factorial(n)) ; end end function test_multiple(s) x = randn(31,31,3, 'single') ; d = vl_liop(x) ; for i=1:3 d_(:,i) = vl_liop(squeeze(x(:,:,i))) ; end assert(isequal(d,d_)) ;
github
Shenc0411/CS445-master
vl_test_binsearch.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/xtest/vl_test_binsearch.m
1,339
utf_8
85dc020adce3f228fe7dfb24cf3acc63
function results = vl_test_binsearch(varargin) % VL_TEST_BINSEARCH vl_test_init ; function test_inf_bins() x = [-inf -1 0 1 +inf] ; vl_assert_equal(vl_binsearch([], x), [0 0 0 0 0]) ; vl_assert_equal(vl_binsearch([-inf 0], x), [1 1 2 2 2]) ; vl_assert_equal(vl_binsearch([-inf], x), [1 1 1 1 1]) ; vl_assert_equal(vl_binsearch([-inf +inf], x), [1 1 1 1 2]) ; function test_empty() vl_assert_equal(vl_binsearch([], []), []) ; function test_bnd() vl_assert_equal(vl_binsearch([], [1]), [0]) ; vl_assert_equal(vl_binsearch([], [-inf]), [0]) ; vl_assert_equal(vl_binsearch([], [+inf]), [0]) ; vl_assert_equal(vl_binsearch([1], [.9]), [0]) ; vl_assert_equal(vl_binsearch([1], [1]), [1]) ; vl_assert_equal(vl_binsearch([1], [-inf]), [0]) ; vl_assert_equal(vl_binsearch([1], [+inf]), [1]) ; function test_basic() vl_assert_equal(vl_binsearch(-10:10, -10:10), 1:21) ; vl_assert_equal(vl_binsearch(-10:10, -11:10), 0:21) ; vl_assert_equal(vl_binsearch(-10:10, [-inf, -11:10, +inf]), [0 0:21 21]) ; function test_frac() vl_assert_equal(vl_binsearch(1:10, 1:.5:10), floor(1:.5:10)) vl_assert_equal(vl_binsearch(1:10, fliplr(1:.5:10)), ... fliplr(floor(1:.5:10))) ; function test_array() a = reshape(1:100,10,10) ; b = reshape(1:.5:100.5, 2, []) ; c = floor(b) ; vl_assert_equal(vl_binsearch(a,b), c) ;
github
Shenc0411/CS445-master
vl_roc.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/plotop/vl_roc.m
9,777
utf_8
8d45b3dad4c701e12284b8c5a7f91efc
function [tpr,tnr,info] = vl_roc(labels, scores, varargin) %VL_ROC ROC curve. % [TPR,TNR] = VL_ROC(LABELS, SCORES) computes the Receiver Operating % Characteristic (ROC) curve [1]. LABELS is a row vector of ground % truth labels, greater than zero for a positive sample and smaller % than zero for a negative one. SCORES is a row vector of % corresponding sample scores, usually obtained from a % classifier. The scores induce a ranking of the samples where % larger scores should correspond to positive labels. % % Without output arguments, the function plots the ROC graph of the % specified data in the current graphical axis. % % Otherwise, the function returns the true positive and true % negative rates TPR and TNR. These are vectors of the same size of % LABELS and SCORES and are computed as follows. Samples are ranked % by decreasing scores, starting from rank 1. TPR(K) and TNR(K) are % the true positive and true negative rates when samples of rank % smaller or equal to K-1 are predicted to be positive. So for % example TPR(3) is the true positive rate when the two samples with % largest score are predicted to be positive. Similarly, TPR(1) is % the true positive rate when no samples are predicted to be % positive, i.e. the constant 0. % % Setting a label to zero ignores the corresponding sample in the % calculations, as if the sample was removed from the data. Setting % the score of a sample to -INF causes the function to assume that % that sample was never retrieved. If there are samples with -INF % score, the ROC curve is incomplete as the maximum recall is less % than 1. % % [TPR,TNR,INFO] = VL_ROC(...) returns an additional structure INFO % with the following fields: % % info.auc:: Area under the ROC curve (AUC). % This is the area under the ROC plot, the parametric curve % (FPR(S), TPR(S)). The PLOT option can be used to plot variants % of this curve, which affects the calculation of a corresponding % AUC. % % info.eer:: Equal error rate (EER). % The equal error rate is the value of FPR (or FNR) when the ROC % curves intersects the line connecting (0,0) to (1,1). % % VL_ROC() accepts the following options: % % Plot:: [] % Setting this option turns on plotting unconditionally. The % following plot variants are supported: % % tntp:: Plot TPR against TNR (standard ROC plot). % tptn:: Plot TNR against TPR (recall on the horizontal axis). % fptp:: Plot TPR against FPR. % fpfn:: Plot FNR against FPR (similar to a DET curve). % % Note that this option will affect the INFO.AUC value computation % too. % % NumPositives:: [] % NumNegatives:: [] % If either of these parameters is set to a number, the function % pretends that LABELS contains the specified number of % positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be % smaller than the actual number of positive/negative entries in % LABELS. The additional positive/negative labels are appended to % the end of the sequence as if they had -INF scores (as explained % above, the function interprets such samples as `not % retrieved'). This feature can be used to evaluate the % performance of a large-scale retrieval experiment in which only % a subset of highly-scoring results are recorded for efficiency % reason. % % About the ROC curve:: % Consider a classifier that predicts as positive all samples whose % score is not smaller than a threshold S. The ROC curve represents % the performance of such classifier as the threshold S is % changed. Formally, define % % P = overall num. of positive samples, % N = overall num. of negative samples, % % and for each threshold S % % TP(S) = num. of samples that are correctly classified as positive, % TN(S) = num. of samples that are correctly classified as negative, % FP(S) = num. of samples that are incorrectly classified as positive, % FN(S) = num. of samples that are incorrectly classified as negative. % % Consider also the rates: % % TPR = TP(S) / P, FNR = FN(S) / P, % TNR = TN(S) / N, FPR = FP(S) / N, % % and notice that, by definition, % % P = TP(S) + FN(S) , N = TN(S) + FP(S), % 1 = TPR(S) + FNR(S), 1 = TNR(S) + FPR(S). % % The ROC curve is the parametric curve (FPR(S), TPR(S)) obtained % as the classifier threshold S is varied in the reals. The TPR is % the same as `recall' in a PR curve (see VL_PR()). % % The ROC curve is contained in the square with vertices (0,0) The % (average) ROC curve of a random classifier is a line which % connects (1,0) and (0,1). % % The ROC curve is independent of the prior probability of the % labels (i.e. of P/(P+N) and N/(P+N)). % % REFERENCES: % [1] http://en.wikipedia.org/wiki/Receiver_operating_characteristic % % See also: VL_PR(), VL_DET(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % 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). [tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ; opts.plot = [] ; opts.stable = false ; opts = vl_argparse(opts,varargin) ; % compute the rates small = 1e-10 ; tpr = tp / max(p, small) ; fpr = fp / max(n, small) ; fnr = 1 - tpr ; tnr = 1 - fpr ; do_plots = ~isempty(opts.plot) || nargout == 0 ; if isempty(opts.plot), opts.plot = 'fptp' ; end % -------------------------------------------------------------------- % Additional info % -------------------------------------------------------------------- if nargout > 2 || do_plots % Area under the curve. Since the curve is a staircase (in the % sense that for each sample either tn is decremented by one % or tp is incremented by one but the other remains fixed), % the integral is particularly simple and exact. switch opts.plot case 'tntp', info.auc = -sum(tpr .* diff([0 tnr])) ; case 'fptp', info.auc = +sum(tpr .* diff([0 fpr])) ; case 'tptn', info.auc = +sum(tnr .* diff([0 tpr])) ; case 'fpfn', info.auc = +sum(fnr .* diff([0 fpr])) ; otherwise error('''%s'' is not a valid PLOT type.', opts.plot); end % Equal error rate. One must find the index S in correspondence of % which TNR(S) and TPR(s) cross. Note that TPR(S) is non-decreasing, % TNR(S) is non-increasing, and from rank S to rank S+1 only one of % the two quantities can change. Hence there are exactly two types % of crossing points: % % 1) TNR(S) = TNR(S+1) = EER and TPR(S) <= EER, TPR(S+1) > EER, % 2) TPR(S) = TPR(S+1) = EER and TNR(S) > EER, TNR(S+1) <= EER. % % Moreover, if the maximum TPR is smaller than 1, then it is % possible that neither of the two cases realizes. In the latter % case, we return EER=NaN. s = max(find(tnr > tpr)) ; if s == length(tpr) info.eer = NaN ; else if tpr(s) == tpr(s+1) info.eer = 1 - tpr(s) ; else info.eer = 1 - tnr(s) ; end end end % -------------------------------------------------------------------- % Plot % -------------------------------------------------------------------- if do_plots cla ; hold on ; switch lower(opts.plot) case 'tntp' hroc = plot(tnr, tpr, 'b', 'linewidth', 2) ; hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ; spline([0 1], [0 1], 'k--', 'linewidth', 1) ; plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ; xlabel('true negative rate') ; ylabel('true positive rate (recall)') ; loc = 'sw' ; case 'fptp' hroc = plot(fpr, tpr, 'b', 'linewidth', 2) ; hrand = spline([0 1], [0 1], 'r--', 'linewidth', 2) ; spline([1 0], [0 1], 'k--', 'linewidth', 1) ; plot(info.eer, 1-info.eer, 'k*', 'linewidth', 1) ; xlabel('false positive rate') ; ylabel('true positive rate (recall)') ; loc = 'se' ; case 'tptn' hroc = plot(tpr, tnr, 'b', 'linewidth', 2) ; hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ; spline([0 1], [0 1], 'k--', 'linewidth', 1) ; plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ; xlabel('true positive rate (recall)') ; ylabel('false positive rate') ; loc = 'sw' ; case 'fpfn' hroc = plot(fpr, fnr, 'b', 'linewidth', 2) ; hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ; spline([0 1], [0 1], 'k--', 'linewidth', 1) ; plot(info.eer, info.eer, 'k*', 'linewidth', 1) ; xlabel('false positive (false alarm) rate') ; ylabel('false negative (miss) rate') ; loc = 'ne' ; otherwise error('''%s'' is not a valid PLOT type.', opts.plot); end grid on ; xlim([0 1]) ; ylim([0 1]) ; axis square ; title(sprintf('ROC (AUC: %.2f%%, EER: %.2f%%)', info.auc * 100, info.eer * 100), ... 'interpreter', 'none') ; legend([hroc hrand], 'ROC', 'ROC rand.', 'location', loc) ; end % -------------------------------------------------------------------- % Stable output % -------------------------------------------------------------------- if opts.stable tpr(1) = [] ; tnr(1) = [] ; tpr_ = tpr ; tnr_ = tnr ; tpr = NaN(size(tpr)) ; tnr = NaN(size(tnr)) ; tpr(perm) = tpr_ ; tnr(perm) = tnr_ ; end % -------------------------------------------------------------------- function h = spline(x,y,spec,varargin) % -------------------------------------------------------------------- prop = vl_linespec2prop(spec) ; h = line(x,y,prop{:},varargin{:}) ;
github
Shenc0411/CS445-master
vl_click.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/plotop/vl_click.m
2,661
utf_8
6982e869cf80da57fdf68f5ebcd05a86
function P = vl_click(N,varargin) ; % VL_CLICK Click a point % P=VL_CLICK() let the user click a point in the current figure and % returns its coordinates in P. P is a two dimensiona vectors where % P(1) is the point X-coordinate and P(2) the point Y-coordinate. The % user can abort the operation by pressing any key, in which case the % empty matrix is returned. % % P=VL_CLICK(N) lets the user select N points in a row. The user can % stop inserting points by pressing any key, in which case the % partial list is returned. % % VL_CLICK() accepts the following options: % % PlotMarker:: [0] % Plot a marker as points are selected. The markers are deleted on % exiting the function. % % See also: VL_CLICKPOINT(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % 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). plot_marker = 0 ; for k=1:2:length(varargin) switch lower(varargin{k}) case 'plotmarker' plot_marker = varargin{k+1} ; otherwise error(['Uknown option ''', varargin{k}, '''.']) ; end end if nargin < 1 N=1; end % -------------------------------------------------------------------- % Do job % -------------------------------------------------------------------- fig = gcf ; is_hold = ishold ; hold on ; bhandler = get(fig,'WindowButtonDownFcn') ; khandler = get(fig,'KeyPressFcn') ; pointer = get(fig,'Pointer') ; set(fig,'WindowButtonDownFcn',@click_handler) ; set(fig,'KeyPressFcn',@key_handler) ; set(fig,'Pointer','crosshair') ; P=[] ; h=[] ; data.exit=0; guidata(fig,data) ; while size(P,2) < N uiwait(fig) ; data = guidata(fig) ; if(data.exit) break ; end P = [P data.P] ; if( plot_marker ) h=[h plot(data.P(1),data.P(2),'rx')] ; end end if ~is_hold hold off ; end if( plot_marker ) pause(.1); delete(h) ; end set(fig,'WindowButtonDownFcn',bhandler) ; set(fig,'KeyPressFcn',khandler) ; set(fig,'Pointer',pointer) ; % ==================================================================== function click_handler(obj,event) % -------------------------------------------------------------------- data = guidata(gcbo) ; P = get(gca, 'CurrentPoint') ; P = [P(1,1); P(1,2)] ; data.P = P ; guidata(obj,data) ; uiresume(gcbo) ; % ==================================================================== function key_handler(obj,event) % -------------------------------------------------------------------- data = guidata(gcbo) ; data.exit = 1 ; guidata(obj,data) ; uiresume(gcbo) ;
github
Shenc0411/CS445-master
vl_pr.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/plotop/vl_pr.m
9,135
utf_8
c5d1b9d67f843d10c0b2c6b48fab3c53
function [recall, precision, info] = vl_pr(labels, scores, varargin) %VL_PR Precision-recall curve. % [RECALL, PRECISION] = VL_PR(LABELS, SCORES) computes the % precision-recall (PR) curve. LABELS are the ground truth labels, % greather than zero for a positive sample and smaller than zero for % a negative one. SCORES are the scores of the samples obtained from % a classifier, where lager scores should correspond to positive % samples. % % Samples are ranked by decreasing scores, starting from rank 1. % PRECISION(K) and RECALL(K) are the precison and recall when % samples of rank smaller or equal to K-1 are predicted to be % positive and the remaining to be negative. So for example % PRECISION(3) is the percentage of positive samples among the two % samples with largest score. PRECISION(1) is the precision when no % samples are predicted to be positive and is conventionally set to % the value 1. % % Set to zero the lables of samples that should be ignored in the % evaluation. Set to -INF the scores of samples which are not % retrieved. If there are samples with -INF score, then the PR curve % may have maximum recall smaller than 1, unless the INCLUDEINF % option is used (see below). The options NUMNEGATIVES and % NUMPOSITIVES can be used to add additional surrogate samples with % -INF score (see below). % % [RECALL, PRECISION, INFO] = VL_PR(...) returns an additional % structure INFO with the following fields: % % info.auc:: % The area under the precision-recall curve. If the INTERPOLATE % option is set to FALSE, then trapezoidal interpolation is used % to integrate the PR curve. If the INTERPOLATE option is set to % TRUE, then the curve is piecewise constant and no other % approximation is introduced in the calculation of the area. In % the latter case, INFO.AUC is the same as INFO.AP. % % info.ap:: % Average precision as defined by TREC. This is the average of the % precision observed each time a new positive sample is % recalled. In this calculation, any sample with -INF score % (unless INCLUDEINF is used) and any additional positive induced % by NUMPOSITIVES has precision equal to zero. If the INTERPOLATE % option is set to true, the AP is computed from the interpolated % precision and the result is the same as INFO.AUC. Note that AP % as defined by TREC normally does not use interpolation [1]. % % info.ap_interp_11:: % 11-points interpolated average precision as defined by TREC. % This is the average of the maximum precision for recall levels % greather than 0.0, 0.1, 0.2, ..., 1.0. This measure was used in % the PASCAL VOC challenge up to the 2008 edition. % % info.auc_pa08:: % Deprecated. It is the same of INFO.AP_INTERP_11. % % VL_PR(...) with no output arguments plots the PR curve in the % current axis. % % VL_PR() accepts the following options: % % Interpolate:: false % If set to true, use interpolated precision. The interpolated % precision is defined as the maximum precision for a given recall % level and onwards. Here it is implemented as the culumative % maximum from low to high scores of the precision. % % NumPositives:: [] % NumNegatives:: [] % If set to a number, pretend that LABELS contains this may % positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be % smaller than the actual number of positive/negative entrires in % LABELS. The additional positive/negative labels are appended to % the end of the sequence, as if they had -INF scores (not % retrieved). This is useful to evaluate large retrieval systems % for which one stores ony a handful of top results for efficiency % reasons. % % IncludeInf:: false % If set to true, data with -INF score SCORES is included in the % evaluation and the maximum recall is 1 even if -INF scores are % present. This option does not include any additional positive or % negative data introduced by specifying NUMPOSITIVES and % NUMNEGATIVES. % % Stable:: false % If set to true, RECALL and PRECISION are returned the same order % of LABELS and SCORES rather than being sorted by decreasing % score (increasing recall). Samples with -INF scores are assigned % RECALL and PRECISION equal to NaN. % % NormalizePrior:: [] % If set to a scalar, reweights positive and negative labels so % that the fraction of positive ones is equal to the specified % value. This computes the normalised PR curves of [2] % % About the PR curve:: % This section uses the same symbols used in the documentation of % the VL_ROC() function. In addition to those quantities, define: % % PRECISION(S) = TP(S) / (TP(S) + FP(S)) % RECALL(S) = TPR(S) = TP(S) / P % % The precision is the fraction of positivie predictions which are % correct, and the recall is the fraction of positive labels that % have been correctly classified (recalled). Notice that the recall % is also equal to the true positive rate for the ROC curve (see % VL_ROC()). % % REFERENCES: % [1] C. D. Manning, P. Raghavan, and H. Schutze. An Introduction to % Information Retrieval. Cambridge University Press, 2008. % [2] D. Hoiem, Y. Chodpathumwan, and Q. Dai. Diagnosing error in % object detectors. In Proc. ECCV, 2012. % % See also VL_ROC(), VL_HELP(). % Author: Andrea Vedaldi % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % 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). % TP and FP are the vectors of true positie and false positve label % counts for decreasing scores, P and N are the total number of % positive and negative labels. Note that if certain options are used % some labels may actually not be stored explicitly by LABELS, so P+N % can be larger than the number of element of LABELS. [tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ; opts.stable = false ; opts.interpolate = false ; opts.normalizePrior = [] ; opts = vl_argparse(opts,varargin) ; % compute precision and recall small = 1e-10 ; recall = tp / max(p, small) ; if isempty(opts.normalizePrior) precision = max(tp, small) ./ max(tp + fp, small) ; else a = opts.normalizePrior ; precision = max(tp * a/max(p,small), small) ./ ... max(tp * a/max(p,small) + fp * (1-a)/max(n,small), small) ; end % interpolate precision if needed if opts.interpolate precision = fliplr(vl_cummax(fliplr(precision))) ; end % -------------------------------------------------------------------- % Additional info % -------------------------------------------------------------------- if nargout > 2 || nargout == 0 % area under the curve using trapezoid interpolation if ~opts.interpolate info.auc = 0.5 * sum((precision(1:end-1) + precision(2:end)) .* diff(recall)) ; end % average precision (for each recalled positive sample) sel = find(diff(recall)) + 1 ; info.ap = sum(precision(sel)) / p ; if opts.interpolate info.auc = info.ap ; end % TREC 11 points average interpolated precision info.ap_interp_11 = 0.0 ; for rc = linspace(0,1,11) pr = max([0, precision(recall >= rc)]) ; info.ap_interp_11 = info.ap_interp_11 + pr / 11 ; end % legacy definition info.auc_pa08 = info.ap_interp_11 ; end % -------------------------------------------------------------------- % Plot % -------------------------------------------------------------------- if nargout == 0 cla ; hold on ; plot(recall,precision,'linewidth',2) ; if isempty(opts.normalizePrior) randomPrecision = p / (p + n) ; else randomPrecision = opts.normalizePrior ; end spline([0 1], [1 1] * randomPrecision, 'r--', 'linewidth', 2) ; axis square ; grid on ; xlim([0 1]) ; xlabel('recall') ; ylim([0 1]) ; ylabel('precision') ; title(sprintf('PR (AUC: %.2f%%, AP: %.2f%%, AP11: %.2f%%)', ... info.auc * 100, ... info.ap * 100, ... info.ap_interp_11 * 100)) ; if opts.interpolate legend('PR interp.', 'PR rand.', 'Location', 'SouthEast') ; else legend('PR', 'PR rand.', 'Location', 'SouthEast') ; end clear recall precision info ; end % -------------------------------------------------------------------- % Stable output % -------------------------------------------------------------------- if opts.stable precision(1) = [] ; recall(1) = [] ; precision_ = precision ; recall_ = recall ; precision = NaN(size(precision)) ; recall = NaN(size(recall)) ; precision(perm) = precision_ ; recall(perm) = recall_ ; end % -------------------------------------------------------------------- function h = spline(x,y,spec,varargin) % -------------------------------------------------------------------- prop = vl_linespec2prop(spec) ; h = line(x,y,prop{:},varargin{:}) ;
github
Shenc0411/CS445-master
vl_ubcread.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/sift/vl_ubcread.m
3,015
utf_8
e8ddd3ecd87e76b6c738ba153fef050f
function [f,d] = vl_ubcread(file, varargin) % SIFTREAD Read Lowe's SIFT implementation data files % [F,D] = VL_UBCREAD(FILE) reads the frames F and the descriptors D % from FILE in UBC (Lowe's original implementation of SIFT) format % and returns F and D as defined by VL_SIFT(). % % VL_UBCREAD(FILE, 'FORMAT', 'OXFORD') assumes the format used by % Oxford VGG implementations . % % See also: VL_SIFT(), VL_HELP(). % Authors: Andrea Vedaldi % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % 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). opts.verbosity = 0 ; opts.format = 'ubc' ; opts = vl_argparse(opts, varargin) ; g = fopen(file, 'r'); if g == -1 error(['Could not open file ''', file, '''.']) ; end [header, count] = fscanf(g, '%d', [1 2]) ; if count ~= 2 error('Invalid keypoint file header.'); end switch opts.format case 'ubc' numKeypoints = header(1) ; descrLen = header(2) ; case 'oxford' numKeypoints = header(2) ; descrLen = header(1) ; otherwise error('Unknown format ''%s''.', opts.format) ; end if(opts.verbosity > 0) fprintf('%d keypoints, %d descriptor length.\n', numKeypoints, descrLen) ; end %creates two output matrices switch opts.format case 'ubc' P = zeros(4,numKeypoints) ; case 'oxford' P = zeros(5,numKeypoints) ; end L = zeros(descrLen, numKeypoints) ; %parse tmp.key for k = 1:numKeypoints switch opts.format case 'ubc' % Record format: i,j,s,th [record, count] = fscanf(g, '%f', [1 4]) ; if count ~= 4 error(... sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) ); end P(:,k) = record(:) ; case 'oxford' % Record format: x, y, a, b, c such that x' [a b ; b c] x = 1 [record, count] = fscanf(g, '%f', [1 5]) ; if count ~= 5 error(... sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) ); end P(:,k) = record(:) ; end % Record format: descriptor [record, count] = fscanf(g, '%d', [1 descrLen]) ; if count ~= descrLen error(... sprintf('Invalid keypoint file (parsing keypoint %d, descriptor part)',k) ); end L(:,k) = record(:) ; end fclose(g) ; switch opts.format case 'ubc' P(1:2,:) = flipud(P(1:2,:)) + 1 ; % i,j -> x,y f=[ P(1:2,:) ; P(3,:) ; -P(4,:) ] ; d=uint8(L) ; p=[1 2 3 4 5 6 7 8] ; q=[1 8 7 6 5 4 3 2] ; for j=0:3 for i=0:3 d(8*(i+4*j)+p,:) = d(8*(i+4*j)+q,:) ; end end case 'oxford' P(1:2,:) = P(1:2,:) + 1 ; % matlab origin f = P ; f(3:5,:) = inv2x2(f(3:5,:)) ; d = uint8(L) ; end % -------------------------------------------------------------------- function S = inv2x2(C) % -------------------------------------------------------------------- den = C(1,:) .* C(3,:) - C(2,:) .* C(2,:) ; S = [C(3,:) ; -C(2,:) ; C(1,:)] ./ den([1 1 1], :) ;
github
Shenc0411/CS445-master
vl_frame2oell.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/sift/vl_frame2oell.m
2,806
utf_8
c93792632f630743485fa4c2cf12d647
function eframes = vl_frame2oell(frames) % VL_FRAMES2OELL Convert a geometric frame to an oriented ellipse % EFRAME = VL_FRAME2OELL(FRAME) converts the generic FRAME to an % oriented ellipses EFRAME. FRAME and EFRAME can be matrices, with % one frame per column. % % A frame is either a point, a disc, an oriented disc, an ellipse, % or an oriented ellipse. These are represented respectively by 2, % 3, 4, 5 and 6 parameters each, as described in VL_PLOTFRAME(). An % oriented ellipse is the most general geometric frame; hence, there % is no loss of information in this conversion. % % If FRAME is an oriented disc or ellipse, then the conversion is % immediate. If, however, FRAME is not oriented (it is either a % point or an unoriented disc or ellipse), then an orientation must % be assigned. The orientation is chosen in such a way that the % affine transformation that maps the standard oriented frame into % the output EFRAME does not rotate the Y axis. If frames represent % detected visual features, this convention corresponds to assume % that features are upright. % % If FRAME is a point, then the output is an ellipse with null area. % % See: <a href="matlab:vl_help('tut.frame')">feature frames</a>, % VL_PLOTFRAME(), VL_HELP(). % Author: Andrea Vedaldi % Copyright (C) 2013 Andrea Vedaldi and Brian Fulkerson. % 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). [D,K] = size(frames) ; eframes = zeros(6,K) ; switch D case 2 eframes(1:2,:) = frames(1:2,:) ; case 3 eframes(1:2,:) = frames(1:2,:) ; eframes(3,:) = frames(3,:) ; eframes(6,:) = frames(3,:) ; case 4 r = frames(3,:) ; c = r.*cos(frames(4,:)) ; s = r.*sin(frames(4,:)) ; eframes(1:2,:) = frames(1:2,:) ; eframes(3:6,:) = [c ; s ; -s ; c] ; case 5 eframes(1:2,:) = frames(1:2,:) ; eframes(3:6,:) = mapFromS(frames(3:5,:)) ; case 6 eframes = frames ; otherwise error('FRAMES format is unknown.') ; end % -------------------------------------------------------------------- function A = mapFromS(S) % -------------------------------------------------------------------- % Returns the (stacking of the) 2x2 matrix A that maps the unit circle % into the ellipses satisfying the equation x' inv(S) x = 1. Here S % is a stacked covariance matrix, with elements S11, S12 and S22. % % The goal is to find A such that AA' = S. In order to let the Y % direction unaffected (upright feature), the assumption is taht % A = [a b ; 0 c]. Hence % % AA' = [a^2, ab ; ab, b^2+c^2] = S. A = zeros(4,size(S,2)) ; a = sqrt(S(1,:)); b = S(2,:) ./ max(a, 1e-18) ; A(1,:) = a ; A(2,:) = b ; A(4,:) = sqrt(max(S(3,:) - b.*b, 0)) ;
github
Shenc0411/CS445-master
vl_plotsiftdescriptor.m
.m
CS445-master/mp5/vlfeat-0.9.19/toolbox/sift/vl_plotsiftdescriptor.m
5,114
utf_8
a4e125a8916653f00143b61cceda2f23
function h=vl_plotsiftdescriptor(d,f,varargin) % VL_PLOTSIFTDESCRIPTOR Plot SIFT descriptor % VL_PLOTSIFTDESCRIPTOR(D) plots the SIFT descriptor D. If D is a % matrix, it plots one descriptor per column. D has the same format % used by VL_SIFT(). % % VL_PLOTSIFTDESCRIPTOR(D,F) plots the SIFT descriptors warped to % the SIFT frames F, specified as columns of the matrix F. F has the % same format used by VL_SIFT(). % % H=VL_PLOTSIFTDESCRIPTOR(...) returns the handle H to the line % drawing representing the descriptors. % % The function assumes that the SIFT descriptors use the standard % configuration of 4x4 spatial bins and 8 orientations bins. The % following parameters can be used to change this: % % NumSpatialBins:: 4 % Number of spatial bins in both spatial directions X and Y. % % NumOrientationBins:: 8 % Number of orientation bis. % % MagnificationFactor:: 3 % Magnification factor. The width of one bin is equal to the scale % of the keypoint F multiplied by this factor. % % See also: VL_SIFT(), VL_PLOTFRAME(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % 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). opts.magnificationFactor = 3.0 ; opts.numSpatialBins = 4 ; opts.numOrientationBins = 8 ; opts.maxValue = 0 ; if nargin > 1 if ~ isnumeric(f) error('F must be a numeric type (use [] to leave it unspecified)') ; end end opts = vl_argparse(opts, varargin) ; % -------------------------------------------------------------------- % Check the arguments % -------------------------------------------------------------------- if(size(d,1) ~= opts.numSpatialBins^2 * opts.numOrientationBins) error('The number of rows of D does not match the geometry of the descriptor') ; end if nargin > 1 if (~isempty(f) & (size(f,1) < 2 | size(f,1) > 6)) error('F must be either empty of have from 2 to six rows.'); end if size(f,1) == 2 % translation only f(3:6,:) = deal([10 0 0 10]') ; %f = [f; 10 * ones(1, size(f,2)) ; 0 * zeros(1, size(f,2))] ; end if size(f,1) == 3 % translation and scale f(3:6,:) = [1 0 0 1]' * f(3,:) ; %f = [f; 0 * zeros(1, size(f,2))] ; end if size(f,1) == 4 c = cos(f(4,:)) ; s = sin(f(4,:)) ; f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ; end if size(f,1) == 5 assert(false) ; c = cos(f(4,:)) ; s = sin(f(4,:)) ; f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ; end if(~isempty(f) & size(f,2) ~= size(d,2)) error('D and F have incompatible dimension') ; end end % Descriptors are often non-double numeric arrays d = double(d) ; K = size(d,2) ; if nargin < 2 | isempty(f) f = repmat([0;0;1;0;0;1],1,K) ; end % -------------------------------------------------------------------- % Do the job % -------------------------------------------------------------------- xall=[] ; yall=[] ; for k=1:K [x,y] = render_descr(d(:,k), opts.numSpatialBins, opts.numOrientationBins, opts.maxValue) ; xall = [xall opts.magnificationFactor*f(3,k)*x + opts.magnificationFactor*f(5,k)*y + f(1,k)] ; yall = [yall opts.magnificationFactor*f(4,k)*x + opts.magnificationFactor*f(6,k)*y + f(2,k)] ; end h=line(xall,yall) ; % -------------------------------------------------------------------- function [x,y] = render_descr(d, numSpatialBins, numOrientationBins, maxValue) % -------------------------------------------------------------------- % Get the coordinates of the lines of the SIFT grid; each bin has side 1 [x,y] = meshgrid(-numSpatialBins/2:numSpatialBins/2,-numSpatialBins/2:numSpatialBins/2) ; % Get the corresponding bin centers xc = x(1:end-1,1:end-1) + 0.5 ; yc = y(1:end-1,1:end-1) + 0.5 ; % Rescale the descriptor range so that the biggest peak fits inside the bin diagram if maxValue d = 0.4 * d / maxValue ; else d = 0.4 * d / max(d(:)+eps) ; end % We scramble the the centers to have them in row major order % (descriptor convention). xc = xc' ; yc = yc' ; % Each spatial bin contains a star with numOrientationBins tips xc = repmat(xc(:)',numOrientationBins,1) ; yc = repmat(yc(:)',numOrientationBins,1) ; % Do the stars th=linspace(0,2*pi,numOrientationBins+1) ; th=th(1:end-1) ; xd = repmat(cos(th), 1, numSpatialBins*numSpatialBins) ; yd = repmat(sin(th), 1, numSpatialBins*numSpatialBins) ; xd = xd .* d(:)' ; yd = yd .* d(:)' ; % Re-arrange in sequential order the lines to draw nans = NaN * ones(1,numSpatialBins^2*numOrientationBins) ; x1 = xc(:)' ; y1 = yc(:)' ; x2 = x1 + xd ; y2 = y1 + yd ; xstars = [x1;x2;nans] ; ystars = [y1;y2;nans] ; % Horizontal lines of the grid nans = NaN * ones(1,numSpatialBins+1); xh = [x(:,1)' ; x(:,end)' ; nans] ; yh = [y(:,1)' ; y(:,end)' ; nans] ; % Verical lines of the grid xv = [x(1,:) ; x(end,:) ; nans] ; yv = [y(1,:) ; y(end,:) ; nans] ; x=[xstars(:)' xh(:)' xv(:)'] ; y=[ystars(:)' yh(:)' yv(:)'] ;
github
Shenc0411/CS445-master
phow_caltech101.m
.m
CS445-master/mp5/vlfeat-0.9.19/apps/phow_caltech101.m
11,594
utf_8
7f4890a2e6844ca56debbfe23cca64f3
function phow_caltech101() % PHOW_CALTECH101 Image classification in the Caltech-101 dataset % This program demonstrates how to use VLFeat to construct an image % classifier on the Caltech-101 data. The classifier uses PHOW % features (dense SIFT), spatial histograms of visual words, and a % Chi2 SVM. To speedup computation it uses VLFeat fast dense SIFT, % kd-trees, and homogeneous kernel map. The program also % demonstrates VLFeat PEGASOS SVM solver, although for this small % dataset other solvers such as LIBLINEAR can be more efficient. % % By default 15 training images are used, which should result in % about 64% performance (a good performance considering that only a % single feature type is being used). % % Call PHOW_CALTECH101 to train and test a classifier on a small % subset of the Caltech-101 data. Note that the program % automatically downloads a copy of the Caltech-101 data from the % Internet if it cannot find a local copy. % % Edit the PHOW_CALTECH101 file to change the program configuration. % % To run on the entire dataset change CONF.TINYPROBLEM to FALSE. % % The Caltech-101 data is saved into CONF.CALDIR, which defaults to % 'data/caltech-101'. Change this path to the desired location, for % instance to point to an existing copy of the Caltech-101 data. % % The program can also be used to train a model on custom data by % pointing CONF.CALDIR to it. Just create a subdirectory for each % class and put the training images there. Make sure to adjust % CONF.NUMTRAIN accordingly. % % Intermediate files are stored in the directory CONF.DATADIR. All % such files begin with the prefix CONF.PREFIX, which can be changed % to test different parameter settings without overriding previous % results. % % The program saves the trained model in % <CONF.DATADIR>/<CONF.PREFIX>-model.mat. This model can be used to % test novel images independently of the Caltech data. % % load('data/baseline-model.mat') ; # change to the model path % label = model.classify(model, im) ; % % Author: Andrea Vedaldi % Copyright (C) 2011-2013 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). conf.calDir = 'data/caltech-101' ; conf.dataDir = 'data/' ; conf.autoDownloadData = true ; conf.numTrain = 15 ; conf.numTest = 15 ; conf.numClasses = 102 ; conf.numWords = 600 ; conf.numSpatialX = [2 4] ; conf.numSpatialY = [2 4] ; conf.quantizer = 'kdtree' ; conf.svm.C = 10 ; conf.svm.solver = 'sdca' ; %conf.svm.solver = 'sgd' ; %conf.svm.solver = 'liblinear' ; conf.svm.biasMultiplier = 1 ; conf.phowOpts = {'Step', 3} ; conf.clobber = false ; conf.tinyProblem = true ; conf.prefix = 'baseline' ; conf.randSeed = 1 ; if conf.tinyProblem conf.prefix = 'tiny' ; conf.numClasses = 5 ; conf.numSpatialX = 2 ; conf.numSpatialY = 2 ; conf.numWords = 300 ; conf.phowOpts = {'Verbose', 2, 'Sizes', 7, 'Step', 5} ; end conf.vocabPath = fullfile(conf.dataDir, [conf.prefix '-vocab.mat']) ; conf.histPath = fullfile(conf.dataDir, [conf.prefix '-hists.mat']) ; conf.modelPath = fullfile(conf.dataDir, [conf.prefix '-model.mat']) ; conf.resultPath = fullfile(conf.dataDir, [conf.prefix '-result']) ; randn('state',conf.randSeed) ; rand('state',conf.randSeed) ; vl_twister('state',conf.randSeed) ; % -------------------------------------------------------------------- % Download Caltech-101 data % -------------------------------------------------------------------- if ~exist(conf.calDir, 'dir') || ... (~exist(fullfile(conf.calDir, 'airplanes'),'dir') && ... ~exist(fullfile(conf.calDir, '101_ObjectCategories', 'airplanes'))) if ~conf.autoDownloadData error(... ['Caltech-101 data not found. ' ... 'Set conf.autoDownloadData=true to download the required data.']) ; end vl_xmkdir(conf.calDir) ; calUrl = ['http://www.vision.caltech.edu/Image_Datasets/' ... 'Caltech101/101_ObjectCategories.tar.gz'] ; fprintf('Downloading Caltech-101 data to ''%s''. This will take a while.', conf.calDir) ; untar(calUrl, conf.calDir) ; end if ~exist(fullfile(conf.calDir, 'airplanes'),'dir') conf.calDir = fullfile(conf.calDir, '101_ObjectCategories') ; end % -------------------------------------------------------------------- % Setup data % -------------------------------------------------------------------- classes = dir(conf.calDir) ; classes = classes([classes.isdir]) ; classes = {classes(3:conf.numClasses+2).name} ; images = {} ; imageClass = {} ; for ci = 1:length(classes) ims = dir(fullfile(conf.calDir, classes{ci}, '*.jpg'))' ; ims = vl_colsubset(ims, conf.numTrain + conf.numTest) ; ims = cellfun(@(x)fullfile(classes{ci},x),{ims.name},'UniformOutput',false) ; images = {images{:}, ims{:}} ; imageClass{end+1} = ci * ones(1,length(ims)) ; end selTrain = find(mod(0:length(images)-1, conf.numTrain+conf.numTest) < conf.numTrain) ; selTest = setdiff(1:length(images), selTrain) ; imageClass = cat(2, imageClass{:}) ; model.classes = classes ; model.phowOpts = conf.phowOpts ; model.numSpatialX = conf.numSpatialX ; model.numSpatialY = conf.numSpatialY ; model.quantizer = conf.quantizer ; model.vocab = [] ; model.w = [] ; model.b = [] ; model.classify = @classify ; % -------------------------------------------------------------------- % Train vocabulary % -------------------------------------------------------------------- if ~exist(conf.vocabPath) || conf.clobber % Get some PHOW descriptors to train the dictionary selTrainFeats = vl_colsubset(selTrain, 30) ; descrs = {} ; %for ii = 1:length(selTrainFeats) parfor ii = 1:length(selTrainFeats) im = imread(fullfile(conf.calDir, images{selTrainFeats(ii)})) ; im = standarizeImage(im) ; [drop, descrs{ii}] = vl_phow(im, model.phowOpts{:}) ; end descrs = vl_colsubset(cat(2, descrs{:}), 10e4) ; descrs = single(descrs) ; % Quantize the descriptors to get the visual words vocab = vl_kmeans(descrs, conf.numWords, 'verbose', 'algorithm', 'elkan', 'MaxNumIterations', 50) ; save(conf.vocabPath, 'vocab') ; else load(conf.vocabPath) ; end model.vocab = vocab ; if strcmp(model.quantizer, 'kdtree') model.kdtree = vl_kdtreebuild(vocab) ; end % -------------------------------------------------------------------- % Compute spatial histograms % -------------------------------------------------------------------- if ~exist(conf.histPath) || conf.clobber hists = {} ; parfor ii = 1:length(images) % for ii = 1:length(images) fprintf('Processing %s (%.2f %%)\n', images{ii}, 100 * ii / length(images)) ; im = imread(fullfile(conf.calDir, images{ii})) ; hists{ii} = getImageDescriptor(model, im); end hists = cat(2, hists{:}) ; save(conf.histPath, 'hists') ; else load(conf.histPath) ; end % -------------------------------------------------------------------- % Compute feature map % -------------------------------------------------------------------- psix = vl_homkermap(hists, 1, 'kchi2', 'gamma', .5) ; % -------------------------------------------------------------------- % Train SVM % -------------------------------------------------------------------- if ~exist(conf.modelPath) || conf.clobber switch conf.svm.solver case {'sgd', 'sdca'} lambda = 1 / (conf.svm.C * length(selTrain)) ; w = [] ; parfor ci = 1:length(classes) perm = randperm(length(selTrain)) ; fprintf('Training model for class %s\n', classes{ci}) ; y = 2 * (imageClass(selTrain) == ci) - 1 ; [w(:,ci) b(ci) info] = vl_svmtrain(psix(:, selTrain(perm)), y(perm), lambda, ... 'Solver', conf.svm.solver, ... 'MaxNumIterations', 50/lambda, ... 'BiasMultiplier', conf.svm.biasMultiplier, ... 'Epsilon', 1e-3); end case 'liblinear' svm = train(imageClass(selTrain)', ... sparse(double(psix(:,selTrain))), ... sprintf(' -s 3 -B %f -c %f', ... conf.svm.biasMultiplier, conf.svm.C), ... 'col') ; w = svm.w(:,1:end-1)' ; b = svm.w(:,end)' ; end model.b = conf.svm.biasMultiplier * b ; model.w = w ; save(conf.modelPath, 'model') ; else load(conf.modelPath) ; end % -------------------------------------------------------------------- % Test SVM and evaluate % -------------------------------------------------------------------- % Estimate the class of the test images scores = model.w' * psix + model.b' * ones(1,size(psix,2)) ; [drop, imageEstClass] = max(scores, [], 1) ; % Compute the confusion matrix idx = sub2ind([length(classes), length(classes)], ... imageClass(selTest), imageEstClass(selTest)) ; confus = zeros(length(classes)) ; confus = vl_binsum(confus, ones(size(idx)), idx) ; % Plots figure(1) ; clf; subplot(1,2,1) ; imagesc(scores(:,[selTrain selTest])) ; title('Scores') ; set(gca, 'ytick', 1:length(classes), 'yticklabel', classes) ; subplot(1,2,2) ; imagesc(confus) ; title(sprintf('Confusion matrix (%.2f %% accuracy)', ... 100 * mean(diag(confus)/conf.numTest) )) ; print('-depsc2', [conf.resultPath '.ps']) ; save([conf.resultPath '.mat'], 'confus', 'conf') ; % ------------------------------------------------------------------------- function im = standarizeImage(im) % ------------------------------------------------------------------------- im = im2single(im) ; if size(im,1) > 480, im = imresize(im, [480 NaN]) ; end % ------------------------------------------------------------------------- function hist = getImageDescriptor(model, im) % ------------------------------------------------------------------------- im = standarizeImage(im) ; width = size(im,2) ; height = size(im,1) ; numWords = size(model.vocab, 2) ; % get PHOW features [frames, descrs] = vl_phow(im, model.phowOpts{:}) ; % quantize local descriptors into visual words switch model.quantizer case 'vq' [drop, binsa] = min(vl_alldist(model.vocab, single(descrs)), [], 1) ; case 'kdtree' binsa = double(vl_kdtreequery(model.kdtree, model.vocab, ... single(descrs), ... 'MaxComparisons', 50)) ; end for i = 1:length(model.numSpatialX) binsx = vl_binsearch(linspace(1,width,model.numSpatialX(i)+1), frames(1,:)) ; binsy = vl_binsearch(linspace(1,height,model.numSpatialY(i)+1), frames(2,:)) ; % combined quantization bins = sub2ind([model.numSpatialY(i), model.numSpatialX(i), numWords], ... binsy,binsx,binsa) ; hist = zeros(model.numSpatialY(i) * model.numSpatialX(i) * numWords, 1) ; hist = vl_binsum(hist, ones(size(bins)), bins) ; hists{i} = single(hist / sum(hist)) ; end hist = cat(1,hists{:}) ; hist = hist / sum(hist) ; % ------------------------------------------------------------------------- function [className, score] = classify(model, im) % ------------------------------------------------------------------------- hist = getImageDescriptor(model, im) ; psix = vl_homkermap(hist, 1, 'kchi2', 'gamma', .5) ; scores = model.w' * psix + model.b' ; [score, best] = max(scores) ; className = model.classes{best} ;
github
Shenc0411/CS445-master
sift_mosaic.m
.m
CS445-master/mp5/vlfeat-0.9.19/apps/sift_mosaic.m
4,621
utf_8
8fa3ad91b401b8f2400fb65944c79712
function mosaic = sift_mosaic(im1, im2) % SIFT_MOSAIC Demonstrates matching two images using SIFT and RANSAC % % SIFT_MOSAIC demonstrates matching two images based on SIFT % features and RANSAC and computing their mosaic. % % SIFT_MOSAIC by itself runs the algorithm on two standard test % images. Use SIFT_MOSAIC(IM1,IM2) to compute the mosaic of two % custom images IM1 and IM2. % AUTORIGHTS if nargin == 0 im1 = imread(fullfile(vl_root, 'data', 'river1.jpg')) ; im2 = imread(fullfile(vl_root, 'data', 'river2.jpg')) ; end % make single im1 = im2single(im1) ; im2 = im2single(im2) ; % make grayscale if size(im1,3) > 1, im1g = rgb2gray(im1) ; else im1g = im1 ; end if size(im2,3) > 1, im2g = rgb2gray(im2) ; else im2g = im2 ; end % -------------------------------------------------------------------- % SIFT matches % -------------------------------------------------------------------- [f1,d1] = vl_sift(im1g) ; [f2,d2] = vl_sift(im2g) ; [matches, scores] = vl_ubcmatch(d1,d2) ; numMatches = size(matches,2) ; X1 = f1(1:2,matches(1,:)) ; X1(3,:) = 1 ; X2 = f2(1:2,matches(2,:)) ; X2(3,:) = 1 ; % -------------------------------------------------------------------- % RANSAC with homography model % -------------------------------------------------------------------- clear H score ok ; for t = 1:100 % estimate homograpyh subset = vl_colsubset(1:numMatches, 4) ; A = [] ; for i = subset A = cat(1, A, kron(X1(:,i)', vl_hat(X2(:,i)))) ; end [U,S,V] = svd(A) ; H{t} = reshape(V(:,9),3,3) ; % score homography X2_ = H{t} * X1 ; du = X2_(1,:)./X2_(3,:) - X2(1,:)./X2(3,:) ; dv = X2_(2,:)./X2_(3,:) - X2(2,:)./X2(3,:) ; ok{t} = (du.*du + dv.*dv) < 6*6 ; score(t) = sum(ok{t}) ; end [score, best] = max(score) ; H = H{best} ; ok = ok{best} ; % -------------------------------------------------------------------- % Optional refinement % -------------------------------------------------------------------- function err = residual(H) u = H(1) * X1(1,ok) + H(4) * X1(2,ok) + H(7) ; v = H(2) * X1(1,ok) + H(5) * X1(2,ok) + H(8) ; d = H(3) * X1(1,ok) + H(6) * X1(2,ok) + 1 ; du = X2(1,ok) - u ./ d ; dv = X2(2,ok) - v ./ d ; err = sum(du.*du + dv.*dv) ; end if exist('fminsearch') == 2 H = H / H(3,3) ; opts = optimset('Display', 'none', 'TolFun', 1e-8, 'TolX', 1e-8) ; H(1:8) = fminsearch(@residual, H(1:8)', opts) ; else warning('Refinement disabled as fminsearch was not found.') ; end % -------------------------------------------------------------------- % Show matches % -------------------------------------------------------------------- dh1 = max(size(im2,1)-size(im1,1),0) ; dh2 = max(size(im1,1)-size(im2,1),0) ; figure(1) ; clf ; subplot(2,1,1) ; imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ; o = size(im1,2) ; line([f1(1,matches(1,:));f2(1,matches(2,:))+o], ... [f1(2,matches(1,:));f2(2,matches(2,:))]) ; title(sprintf('%d tentative matches', numMatches)) ; axis image off ; subplot(2,1,2) ; imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ; o = size(im1,2) ; line([f1(1,matches(1,ok));f2(1,matches(2,ok))+o], ... [f1(2,matches(1,ok));f2(2,matches(2,ok))]) ; title(sprintf('%d (%.2f%%) inliner matches out of %d', ... sum(ok), ... 100*sum(ok)/numMatches, ... numMatches)) ; axis image off ; drawnow ; % -------------------------------------------------------------------- % Mosaic % -------------------------------------------------------------------- box2 = [1 size(im2,2) size(im2,2) 1 ; 1 1 size(im2,1) size(im2,1) ; 1 1 1 1 ] ; box2_ = inv(H) * box2 ; box2_(1,:) = box2_(1,:) ./ box2_(3,:) ; box2_(2,:) = box2_(2,:) ./ box2_(3,:) ; ur = min([1 box2_(1,:)]):max([size(im1,2) box2_(1,:)]) ; vr = min([1 box2_(2,:)]):max([size(im1,1) box2_(2,:)]) ; [u,v] = meshgrid(ur,vr) ; im1_ = vl_imwbackward(im2double(im1),u,v) ; z_ = H(3,1) * u + H(3,2) * v + H(3,3) ; u_ = (H(1,1) * u + H(1,2) * v + H(1,3)) ./ z_ ; v_ = (H(2,1) * u + H(2,2) * v + H(2,3)) ./ z_ ; im2_ = vl_imwbackward(im2double(im2),u_,v_) ; mass = ~isnan(im1_) + ~isnan(im2_) ; im1_(isnan(im1_)) = 0 ; im2_(isnan(im2_)) = 0 ; mosaic = (im1_ + im2_) ./ mass ; figure(2) ; clf ; imagesc(mosaic) ; axis image off ; title('Mosaic') ; if nargout == 0, clear mosaic ; end end
github
Shenc0411/CS445-master
encodeImage.m
.m
CS445-master/mp5/vlfeat-0.9.19/apps/recognition/encodeImage.m
5,278
utf_8
5d9dc6161995b8e10366b5649bf4fda4
function descrs = encodeImage(encoder, im, varargin) % ENCODEIMAGE Apply an encoder to an image % DESCRS = ENCODEIMAGE(ENCODER, IM) applies the ENCODER % to image IM, returning a corresponding code vector PSI. % % IM can be an image, the path to an image, or a cell array of % the same, to operate on multiple images. % % ENCODEIMAGE(ENCODER, IM, CACHE) utilizes the specified CACHE % directory to store encodings for the given images. The cache % is used only if the images are specified as file names. % % See also: TRAINENCODER(). % Author: Andrea Vedaldi % Copyright (C) 2013 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). opts.cacheDir = [] ; opts.cacheChunkSize = 512 ; opts = vl_argparse(opts,varargin) ; if ~iscell(im), im = {im} ; end % break the computation into cached chunks startTime = tic ; descrs = cell(1, numel(im)) ; numChunks = ceil(numel(im) / opts.cacheChunkSize) ; for c = 1:numChunks n = min(opts.cacheChunkSize, numel(im) - (c-1)*opts.cacheChunkSize) ; chunkPath = fullfile(opts.cacheDir, sprintf('chunk-%03d.mat',c)) ; if ~isempty(opts.cacheDir) && exist(chunkPath) fprintf('%s: loading descriptors from %s\n', mfilename, chunkPath) ; load(chunkPath, 'data') ; else range = (c-1)*opts.cacheChunkSize + (1:n) ; fprintf('%s: processing a chunk of %d images (%3d of %3d, %5.1fs to go)\n', ... mfilename, numel(range), ... c, numChunks, toc(startTime) / (c - 1) * (numChunks - c + 1)) ; data = processChunk(encoder, im(range)) ; if ~isempty(opts.cacheDir) save(chunkPath, 'data') ; end end descrs{c} = data ; clear data ; end descrs = cat(2,descrs{:}) ; % -------------------------------------------------------------------- function psi = processChunk(encoder, im) % -------------------------------------------------------------------- psi = cell(1,numel(im)) ; if numel(im) > 1 & matlabpool('size') > 1 parfor i = 1:numel(im) psi{i} = encodeOne(encoder, im{i}) ; end else % avoiding parfor makes debugging easier for i = 1:numel(im) psi{i} = encodeOne(encoder, im{i}) ; end end psi = cat(2, psi{:}) ; % -------------------------------------------------------------------- function psi = encodeOne(encoder, im) % -------------------------------------------------------------------- im = encoder.readImageFn(im) ; features = encoder.extractorFn(im) ; imageSize = size(im) ; psi = {} ; for i = 1:size(encoder.subdivisions,2) minx = encoder.subdivisions(1,i) * imageSize(2) ; miny = encoder.subdivisions(2,i) * imageSize(1) ; maxx = encoder.subdivisions(3,i) * imageSize(2) ; maxy = encoder.subdivisions(4,i) * imageSize(1) ; ok = ... minx <= features.frame(1,:) & features.frame(1,:) < maxx & ... miny <= features.frame(2,:) & features.frame(2,:) < maxy ; descrs = encoder.projection * bsxfun(@minus, ... features.descr(:,ok), ... encoder.projectionCenter) ; if encoder.renormalize descrs = bsxfun(@times, descrs, 1./max(1e-12, sqrt(sum(descrs.^2)))) ; end w = size(im,2) ; h = size(im,1) ; frames = features.frame(1:2,:) ; frames = bsxfun(@times, bsxfun(@minus, frames, [w;h]/2), 1./[w;h]) ; descrs = extendDescriptorsWithGeometry(encoder.geometricExtension, frames, descrs) ; switch encoder.type case 'bovw' [words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ... descrs, ... 'MaxComparisons', 100) ; z = vl_binsum(zeros(encoder.numWords,1), 1, double(words)) ; z = sqrt(z) ; case 'fv' z = vl_fisher(descrs, ... encoder.means, ... encoder.covariances, ... encoder.priors, ... 'Improved') ; case 'vlad' [words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ... descrs, ... 'MaxComparisons', 15) ; assign = zeros(encoder.numWords, numel(words), 'single') ; assign(sub2ind(size(assign), double(words), 1:numel(words))) = 1 ; z = vl_vlad(descrs, ... encoder.words, ... assign, ... 'SquareRoot', ... 'NormalizeComponents') ; end z = z / max(sqrt(sum(z.^2)), 1e-12) ; psi{i} = z(:) ; end psi = cat(1, psi{:}) ; % -------------------------------------------------------------------- function psi = getFromCache(name, cache) % -------------------------------------------------------------------- [drop, name] = fileparts(name) ; cachePath = fullfile(cache, [name '.mat']) ; if exist(cachePath, 'file') data = load(cachePath) ; psi = data.psi ; else psi = [] ; end % -------------------------------------------------------------------- function storeToCache(name, cache, psi) % -------------------------------------------------------------------- [drop, name] = fileparts(name) ; cachePath = fullfile(cache, [name '.mat']) ; vl_xmkdir(cache) ; data.psi = psi ; save(cachePath, '-STRUCT', 'data') ;
github
Shenc0411/CS445-master
experiments.m
.m
CS445-master/mp5/vlfeat-0.9.19/apps/recognition/experiments.m
6,905
utf_8
1e4a4911eed4a451b9488b9e6cc9b39c
function experiments() % EXPERIMENTS Run image classification experiments % The experimens download a number of benchmark datasets in the % 'data/' subfolder. Make sure that there are several GBs of % space available. % % By default, experiments run with a lite option turned on. This % quickly runs all of them on tiny subsets of the actual data. % This is used only for testing; to run the actual experiments, % set the lite variable to false. % % Running all the experiments is a slow process. Using parallel % MATLAB and several cores/machiens is suggested. % Author: Andrea Vedaldi % Copyright (C) 2013 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). lite = true ; clear ex ; ex(1).prefix = 'fv-aug' ; ex(1).trainOpts = {'C', 10} ; ex(1).datasets = {'fmd', 'scene67'} ; ex(1).seed = 1 ; ex(1).opts = {... 'type', 'fv', ... 'numWords', 256, ... 'layouts', {'1x1'}, ... 'geometricExtension', 'xy', ... 'numPcaDimensions', 80, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(2) = ex(1) ; ex(2).datasets = {'caltech101'} ; ex(2).opts{end} = @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(0:-.5:-3)) ; ex(3) = ex(1) ; ex(3).datasets = {'voc07'} ; ex(3).C = 1 ; ex(4) = ex(1) ; ex(4).prefix = 'vlad-aug' ; ex(4).opts = {... 'type', 'vlad', ... 'numWords', 256, ... 'layouts', {'1x1'}, ... 'geometricExtension', 'xy', ... 'numPcaDimensions', 100, ... 'whitening', true, ... 'whiteningRegul', 0.01, ... 'renormalize', true, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(5) = ex(4) ; ex(5).datasets = {'caltech101'} ; ex(5).opts{end} = ex(2).opts{end} ; ex(6) = ex(4) ; ex(6).datasets = {'voc07'} ; ex(6).C = 1 ; ex(7) = ex(1) ; ex(7).prefix = 'bovw-aug' ; ex(7).opts = {... 'type', 'bovw', ... 'numWords', 4096, ... 'layouts', {'1x1'}, ... 'geometricExtension', 'xy', ... 'numPcaDimensions', 100, ... 'whitening', true, ... 'whiteningRegul', 0.01, ... 'renormalize', true, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(8) = ex(7) ; ex(8).datasets = {'caltech101'} ; ex(8).opts{end} = ex(2).opts{end} ; ex(9) = ex(7) ; ex(9).datasets = {'voc07'} ; ex(9).C = 1 ; ex(10).prefix = 'fv' ; ex(10).trainOpts = {'C', 10} ; ex(10).datasets = {'fmd', 'scene67'} ; ex(10).seed = 1 ; ex(10).opts = {... 'type', 'fv', ... 'numWords', 256, ... 'layouts', {'1x1'}, ... 'geometricExtension', 'none', ... 'numPcaDimensions', 80, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(11) = ex(10) ; ex(11).datasets = {'caltech101'} ; ex(11).opts{end} = @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(0:-.5:-3)) ; ex(12) = ex(10) ; ex(12).datasets = {'voc07'} ; ex(12).C = 1 ; ex(13).prefix = 'fv-sp' ; ex(13).trainOpts = {'C', 10} ; ex(13).datasets = {'fmd', 'scene67'} ; ex(13).seed = 1 ; ex(13).opts = {... 'type', 'fv', ... 'numWords', 256, ... 'layouts', {'1x1', '3x1'}, ... 'geometricExtension', 'none', ... 'numPcaDimensions', 80, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(14) = ex(13) ; ex(14).datasets = {'caltech101'} ; ex(14).opts{6} = {'1x1', '2x2'} ; ex(14).opts{end} = @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(0:-.5:-3)) ; ex(15) = ex(13) ; ex(15).datasets = {'voc07'} ; ex(15).C = 1 ; if lite, tag = 'lite' ; else, tag = 'ex' ; end for i=1:numel(ex) for j=1:numel(ex(i).datasets) dataset = ex(i).datasets{j} ; if ~isfield(ex(i), 'trainOpts') || ~iscell(ex(i).trainOpts) ex(i).trainOpts = {} ; end traintest(... 'prefix', [tag '-' dataset '-' ex(i).prefix], ... 'seed', ex(i).seed, ... 'dataset', char(dataset), ... 'datasetDir', fullfile('data', dataset), ... 'lite', lite, ... ex(i).trainOpts{:}, ... 'encoderParams', ex(i).opts) ; end end % print HTML table pf('<table>\n') ; ph('method', 'VOC07', 'Caltech 101', 'Scene 67', 'FMD') ; pr('FV', ... ge([tag '-voc07-fv'],'ap11'), ... ge([tag '-caltech101-fv']), ... ge([tag '-scene67-fv']), ... ge([tag '-fmd-fv'])) ; pr('FV + aug.', ... ge([tag '-voc07-fv-aug'],'ap11'), ... ge([tag '-caltech101-fv-aug']), ... ge([tag '-scene67-fv-aug']), ... ge([tag '-fmd-fv-aug'])) ; pr('FV + s.p.', ... ge([tag '-voc07-fv-sp'],'ap11'), ... ge([tag '-caltech101-fv-sp']), ... ge([tag '-scene67-fv-sp']), ... ge([tag '-fmd-fv-sp'])) ; %pr('VLAD', ... % ge([tag '-voc07-vlad'],'ap11'), ... % ge([tag '-caltech101-vlad']), ... % ge([tag '-scene67-vlad']), ... % ge([tag '-fmd-vlad'])) ; pr('VLAD + aug.', ... ge([tag '-voc07-vlad-aug'],'ap11'), ... ge([tag '-caltech101-vlad-aug']), ... ge([tag '-scene67-vlad-aug']), ... ge([tag '-fmd-vlad-aug'])) ; %pr('VLAD+sp', ... % ge([tag '-voc07-vlad-sp'],'ap11'), ... % ge([tag '-caltech101-vlad-sp']), ... % ge([tag '-scene67-vlad-sp']), ... % ge([tag '-fmd-vlad-sp'])) ; %pr('BOVW', ... % ge([tag '-voc07-bovw'],'ap11'), ... % ge([tag '-caltech101-bovw']), ... % ge([tag '-scene67-bovw']), ... % ge([tag '-fmd-bovw'])) ; pr('BOVW + aug.', ... ge([tag '-voc07-bovw-aug'],'ap11'), ... ge([tag '-caltech101-bovw-aug']), ... ge([tag '-scene67-bovw-aug']), ... ge([tag '-fmd-bovw-aug'])) ; %pr('BOVW+sp', ... % ge([tag '-voc07-bovw-sp'],'ap11'), ... % ge([tag '-caltech101-bovw-sp']), ... % ge([tag '-scene67-bovw-sp']), ... % ge([tag '-fmd-bovw-sp'])) ; pf('</table>\n'); function pf(str) fprintf(str) ; function str = ge(name, format) if nargin == 1, format = 'acc'; end data = load(fullfile('data', name, 'result.mat')) ; switch format case 'acc' str = sprintf('%.2f%% <span style="font-size:8px;">Acc</span>', mean(diag(data.confusion)) * 100) ; case 'ap11' str = sprintf('%.2f%% <span style="font-size:8px;">mAP</span>', mean(data.ap11) * 100) ; end function pr(varargin) fprintf('<tr>') ; for i=1:numel(varargin), fprintf('<td>%s</td>',varargin{i}) ; end fprintf('</tr>\n') ; function ph(varargin) fprintf('<tr>') ; for i=1:numel(varargin), fprintf('<th>%s</th>',varargin{i}) ; end fprintf('</tr>\n') ;
github
Shenc0411/CS445-master
getDenseSIFT.m
.m
CS445-master/mp5/vlfeat-0.9.19/apps/recognition/getDenseSIFT.m
1,679
utf_8
2059c0a2a4e762226d89121408c6e51c
function features = getDenseSIFT(im, varargin) % GETDENSESIFT Extract dense SIFT features % FEATURES = GETDENSESIFT(IM) extract dense SIFT features from % image IM. % Author: Andrea Vedaldi % Copyright (C) 2013 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). opts.scales = logspace(log10(1), log10(.25), 5) ; opts.contrastthreshold = 0 ; opts.step = 3 ; opts.rootSift = false ; opts.normalizeSift = true ; opts.binSize = 8 ; opts.geometry = [4 4 8] ; opts.sigma = 0 ; opts = vl_argparse(opts, varargin) ; dsiftOpts = {'norm', 'fast', 'floatdescriptors', ... 'step', opts.step, ... 'size', opts.binSize, ... 'geometry', opts.geometry} ; if size(im,3)>1, im = rgb2gray(im) ; end im = im2single(im) ; im = vl_imsmooth(im, opts.sigma) ; for si = 1:numel(opts.scales) im_ = imresize(im, opts.scales(si)) ; [frames{si}, descrs{si}] = vl_dsift(im_, dsiftOpts{:}) ; % root SIFT if opts.rootSift descrs{si} = sqrt(descrs{si}) ; end if opts.normalizeSift descrs{si} = snorm(descrs{si}) ; end % zero low contrast descriptors info.contrast{si} = frames{si}(3,:) ; kill = info.contrast{si} < opts.contrastthreshold ; descrs{si}(:,kill) = 0 ; % store frames frames{si}(1:2,:) = (frames{si}(1:2,:)-1) / opts.scales(si) + 1 ; frames{si}(3,:) = opts.binSize / opts.scales(si) / 3 ; end features.frame = cat(2, frames{:}) ; features.descr = cat(2, descrs{:}) ; features.contrast = cat(2, info.contrast{:}) ; function x = snorm(x) x = bsxfun(@times, x, 1./max(1e-5,sqrt(sum(x.^2,1)))) ;
github
evanypeng/ICCV2017_RevisitCCIT_code-master
build_mmx.m
.m
ICCV2017_RevisitCCIT_code-master/util/mmx/mmx_package/build_mmx.m
8,089
utf_8
fe6dfb85a5c474af0fc5dbcbfc231f68
function build_mmx(verbose) % BUILD_MMX - compiles mmx() for different platforms and provides help % regarding compilation. % % BUILD_MMX will try to compile, in this order, 3 different builds of mmx: % mmx_mkl_single - linked to Intel's single-threaded MKL library (usually fastest) % mmx_mkl_multi - linked to the multithreaded BLAS/LAPACK libraries that come % with Matlab. % mmx_naive - does not link to anything, uses simple C-loops. % % The first time BUILD_MMX succeeds, it will compile again to 'mmx', so % that the mex-file mmx should be the fastest possible build on your % system. % % BUILD_MMX has been tested on Win32, Win64, OSX, Linux 64 % % %% FOR LINUX OR MAC SYSTEMS: % % To properly link to Intel's MKL, user needs to repackage their libraries % into one single statically linked library. The instructions are as % follows: % % % Download Intel MKL for Linux here: % http://software.intel.com/en-us/articles/non-commercial-software-download/ % % Donwload Intel MKL for Mac here: % https://registrationcenter.intel.com/RegCenter/AutoGen.aspx?ProductID=1518&AccountID=&EmailID=&ProgramID=&RequestDt=&rm=EVAL&lang= % % The Default installation directory for both Linux and Mac will be % /opt/intel/ % with the MKL libraries in /opt/intel/mkl % % %% To build needed static Library % assuming default installation directory % % Run the following commands in Linux/Mac terminal: % % sudo -s % cd /opt/intel/mkl/tools/builder % cat blas_example_list > blas_lapack_list % cat lapack_example_list >> blas_lapack_list % % For Linux 64 bit: % make libintel64 interface=ilp64 export=blas_lapack_list name=libsingle_mkl_ilp64 threading=sequential % For Linux 32 bit: % make libia32 interface=lp64 export=blas_lapack_list name=libsingle_mkl_32 threading=sequential % % For Mac: % make libuni interface=ilp64 export=blas_lapack_list name=libsingle_mkl_ilp64 threading=sequential % % A new libsingle_mkl_ilp64.so, libsingle_mkl_32.so, or % libsingle_mkl_ilp64.dylib will appear. % This needs to be copied to Matlab's external libraries directory. % % For Mac: % cp libsingle_mkl_ilp64* MATLAB_ROOT/extern/lib/maci64 % % For Linux 64 bit: % cp libsingle_mkl_ilp64* MATLAB_ROOT/extern/lib/glnxa64 % For Linux 32 bit: % cp libsingle_mkl_32* MATLAB_ROOT/extern/lib/glnx86 % % Where MATLAB_ROOT is the installation directory of your Matlab. if nargin == 0 verbose = false; end clc build_names = {'mmx_mkl_single', 'mmx_mkl_multi','mmx_naive'}; built_mmx = false; arch = computer('arch'); for b = 2:3 %1:3 % note that for the first case of using mmx_naive, MKL is needed which may sometimes become % a critical constraint, thus we would suggest to use 2/3 cases, which yield competitive results name = build_names{b}; [link, define] = deal({}); [inc_dir, link_dir, Cflags, Lflags] = deal(''); switch arch case {'win64','win32'} switch name case 'mmx_naive' define = {'WIN_SYSTEM'}; case 'mmx_mkl_multi' root = matlabroot; if strcmp(arch,'win32') inc_dir = [root '\extern\lib\win32\microsoft']; else inc_dir = [root '\extern\lib\win64\microsoft']; end link = {'libmwblas','libmwlapack'}; link_dir = [matlabroot '\extern\lib\win64\microsoft']; define = {'WIN_SYSTEM','USE_BLAS'}; case 'mmx_mkl_single' root = 'C:\Program Files (x86)\Intel\Composer XE 2011 SP1\mkl'; inc_dir = [root '\include']; if strcmp(arch,'win32') link_dir = [root '\lib\ia32']; link = {'mkl_intel_c','mkl_sequential','mkl_core'}; define = {'WIN_SYSTEM','USE_BLAS','MKL_32'}; else link_dir = [root '\lib\intel64']; link = {'mkl_intel_ilp64','mkl_sequential','mkl_core'}; define = {'WIN_SYSTEM','USE_BLAS','MKL_ILP64'}; end end case {'glnxa64','glnx86'} switch name case 'mmx_naive' link = {'pthread'}; define = {'UNIX_SYSTEM'}; case 'mmx_mkl_multi' if strcmp(arch,'glnx86') inc_dir = [matlabroot '/extern/lib/glnx86']; else inc_dir = [matlabroot '/extern/lib/glnxa64']; end link = {'mwblas','mwlapack','pthread'}; define = {'UNIX_SYSTEM','USE_BLAS'}; case 'mmx_mkl_single' root = '/opt/intel/mkl'; inc_dir = [ root '/include']; if strcmp(arch,'glnx86') link_dir = [matlabroot '/extern/lib/glnx86']; link = {'single_mkl_32','pthread'}; define = {'UNIX_SYSTEM', 'USE_BLAS', 'MKL_32'}; else link_dir = [matlabroot '/extern/lib/glnxa64']; link = {'small_mkl_ilp64','pthread'}; define = {'UNIX_SYSTEM', 'USE_BLAS', 'MKL_ILP64'}; end end case {'maci64'} switch name case 'mmx_naive' link = {'pthread'}; define = {'UNIX_SYSTEM'}; case 'mmx_mkl_multi' root = matlabroot; inc_dir = [root '/extern/lib/maci64']; link = {'mwblas','mwlapack','pthread'}; define = {'UNIX_SYSTEM','USE_BLAS'}; case 'mmx_mkl_single' root = '/opt/intel/mkl'; inc_dir = [ root '/include']; link_dir = [matlabroot '/extern/lib/maci64']; link = {'single_mkl_ilp64','pthread'}; %link = {'small_mkl_ilp64','pthread'}; define = {'UNIX_SYSTEM', 'USE_BLAS', 'MKL_ILP64'}; end otherwise error unsupported_architecture end if ~isempty(link_dir) if strcmp(arch,'glnxa64') || strcmp(arch,'maci64') L_dir = {['LDFLAGS="\$LDFLAGS -L' link_dir ' ' Lflags '"']}; else L_dir = {['-L' link_dir]}; end else L_dir = {}; end if ~isempty(inc_dir) if strcmp(arch,'glnxa64') || strcmp(arch,'maci64') I_dir = {['CXXFLAGS="\$CXXFLAGS -I' inc_dir ' ' Cflags '"']}; else I_dir = {['-I' inc_dir]}; end else I_dir = {}; end prefix = @(pref,str_array) cellfun(@(x)[pref x],str_array,'UniformOutput',0); l_link = prefix('-l',link); D_define = prefix('-D',define); if verbose verb = {'-v'}; else verb = {}; end try check_dir(link_dir, link) check_dir(inc_dir) clear(name) command = {verb{:}, I_dir{:}, L_dir{:}, l_link{:}, D_define{:}}; %#ok<*CCAT> fprintf('==========\nTrying to compile ''%s'', using \n',name); fprintf('%s, ',command{:}) fprintf('\n') mex(command{:}, '-output', name, 'mmx.cpp'); fprintf('Compilation of ''%s'' succeeded.\n',name); if ~built_mmx fprintf('Compiling again to ''mmx'' target using ''%s'' build.\n',name); mex(command{:}, '-output','mmx','mmx.cpp'); built_mmx = true; end catch err fprintf('Compilation of ''%s'' failed with error:\n%s\n',name,err.message); end end function check_dir(dir,files) if ~isempty(dir) here = cd(dir); if nargin == 2 for i = 1:size(files) if isempty(ls(['*' files{i} '.*'])) cd(here); error('could not find file %s', files{i}); end end end cd(here); end
github
duqbo/varpro2-master
varpro_opts.m
.m
varpro2-master/src/varpro_opts.m
4,713
utf_8
2c493bac13f3036c9820d527950e4f5c
function opts = varpro_opts(varargin) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Create options structure for varpro routines % % INPUT: % % The input should be pairs of strings and % values for setting fields of the structure % % OUTPUT: % % The output will be a structure with the % given values for the specified fields and % the default values for the rest % % OPTIONS STRUCTURE FORMAT % % The options structure has several fields, % denoted as strings below, with default values % in parentheses, that determine the behavior % of varpro2. See the descriptions below % % 'lambda0' (1.0) --- lambda0 is the initial % value used for the regularization parameter % lambda in the Levenberg method (a larger % lambda makes it more like gradient descent) % % 'maxlam' (52) --- maxlam is the maximum number % of steps used in the inner Levenberg loop, % i.e. the number of times you increase lambda % before quitting % % 'lamup' (2.0) --- lamup is the factor by which % you increase lambda when searching for an % appropriate step % % 'lamdown' (2.0) --- lamdown is the factor by which % you decrease lambda when checking if that % results in an error decrease % % 'ifmarq' (1) --- ifmarq is a flag which determines % whether you use the Levenberg algorithm or the % Levenberg-Marquardt algorithm. ifmarq == 1 % results in the Levenberg-Marquardt algorithm. % Anything else gives the standard Levenberg % algorithm % % 'maxiter' (30) --- the maximum number of outer % loop iterations to use before quitting % % 'tol' (1.0e-6) --- the tolerance for the relative % error in the residual, i.e. the program will % terminate if % norm(y-Phi(alpha)*b,'fro')/norm(y,'fro') < tol % is achieved. % % 'eps_stall' (1.0e-12) --- the tolerance for detecting % a stall. If err(iter-1)-err(iter) < eps_stall*err(iter-1) % then a stall is detected and the program halts. % % 'iffulljac' (1) --- flag determines whether or not to use % the full expression for the Jacobian or Kaufman's % approximation. % % 'ifprint' (1) --- flag determines whether or not to % print info on progress of optimization % % 'ptf' (1) --- prints every ptf steps % % Author: Travis Askham % % Copyright 2017 Travis Askham % % License: MIT License % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% errstr1 = 'nargin = %d. input should be pairs of values'; errstr2 = 'input %d is not a valid field name'; errstr3 = 'input %d is non-numeric'; % default values opts.lambda0 = 1.0; opts.maxlam = 52; opts.lamup = 2.0; opts.lamdown = 2.0; opts.ifmarq = 1; opts.maxiter = 30; opts.tol = 1.0e-6; opts.eps_stall = 1.0e-12; opts.iffulljac = 1; opts.ifprint = 1; opts.ptf = 1; % minimum values (in some reasonable sense) optsmin.lambda0 = 0.0; optsmin.maxlam = 0; optsmin.lamup = 1.0; optsmin.lamdown = 1.0; optsmin.ifmarq = -Inf; optsmin.maxiter = 0; optsmin.tol = 0.0; optsmin.eps_stall = -Inf; optsmin.iffulljac = -Inf; optsmin.ifprint = -Inf; optsmin.ptf = 0; % maximum values (in some reasonable sense) optsmax.lambda0 = 1.0e16; optsmax.maxlam = 200; optsmax.lamup = 1.0e16; optsmax.lamdown = 1.0e16; optsmax.ifmarq = Inf; optsmax.maxiter = 1.0e12; optsmax.tol = 1.0e16; optsmax.eps_stall = 1.0; optsmax.iffulljac = Inf; optsmax.ifprint = Inf; optsmax.ptf = Inf; % check if input comes in pairs if(mod(nargin,2) ~= 0) error(errstr1,nargin); end % for each pair of inputs, check if the first % input is a valid structure field name and if % the second input is numeric. If so, set value of % that field to the second input. Otherwise, bomb % with error message. for i = 1:nargin/2 if (isfield(opts,varargin{2*(i-1)+1})) if (isnumeric(varargin{2*i})) opts.(varargin{2*(i-1)+1}) = varargin{2*i}; else error(errstr3,2*i) end else error(errstr2,2*(i-1)+1); end end varpro_opts_warn(opts,optsmin,optsmax); end function varpro_opts_warn(opts,optsmin,optsmax) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % For each value of the opts structure, this % routine prints a warning if it is not within % the bounds determined by optsmin and optsmax % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% warnstrmin = ['option %s with value %e is less than %e, which' ... ' is not recommended']; warnstrmax = ['option %s with value %e is greater than %e, which' ... ' is not recommended']; names = fieldnames(opts); for i = 1:length(names) s = names{i}; optv = opts.(s); optminv = optsmin.(s); optmaxv = optsmax.(s); if (optv < optminv) warning(warnstrmin,s,optv,optminv); end if (optv > optmaxv) warning(warnstrmax,s,optv,optmaxv); end end end
github
duqbo/varpro2-master
match_vectors.m
.m
varpro2-master/src/match_vectors.m
481
utf_8
572dfefc3527774f1c52834bf15354b0
function indices = match_vectors(v1,v2) %MATCH_VECTORS Wrapper for MUNKRES % % Sets up a cost function so that the indices % returned by munkres correspond to the permutation % which minimizes the 1-norm of the difference % between v1(indices) and v2( (indices ~= 0) ) % % Example: % % >> indices = match_vectors(v1,v2) % % See also MUNKRES v1 = v1(:); v2 = v2(:); costmat = abs(kron(v1.',ones(length(v2),1)) - kron(v2,ones(1,length(v1)))); [indices,cost] = munkres(costmat);
github
duqbo/varpro2-master
varpro2expfun.m
.m
varpro2-master/src/varpro2expfun.m
337
utf_8
4a95a7400aab8cdadcdbb96aaf6748a7
function A = varpro2expfun(alpha,t) % % matrix of exponentials % % Input % % alpha - vector of exponent values % t - vector of times % % Output % % A(i,j) = exp(alpha_j t_i) % m = length(t); n = length(alpha); A = zeros(m,n); ttemp = reshape(t,m,1); atemp = reshape(alpha,n,1); temp = ttemp*transpose(atemp); A = exp(temp); end
github
duqbo/varpro2-master
varpro2dexpfun.m
.m
varpro2-master/src/varpro2dexpfun.m
487
utf_8
3224b37a08883b9cc3d7ab6801aa106e
function A = varpro2dexpfun(alpha,t,i) % % Derivatives of the matrix of exponentials % % Input % % alpha - vector of exponent values % t - vector of times % i - the desired derivative % % Output % % If Phi_i,j = exp(alpha_j t_i) % then A = d/d(alpha_i) Phi in sparse % format % m = length(t); n = length(alpha); if (i < 1 || i > n) error('varpro2dexpfun: invalid index') end %A = zeros(m,n); A = sparse(m,n); ttemp = reshape(t,m,1); A(:,i) = ttemp.*exp(alpha(i)*ttemp); end
github
duqbo/varpro2-master
munkres.m
.m
varpro2-master/src/munkres.m
7,171
utf_8
b44ad4f1a20fc5d03db019c44a65bac3
function [assignment,cost] = munkres(costMat) % MUNKRES Munkres (Hungarian) Algorithm for Linear Assignment Problem. % % [ASSIGN,COST] = munkres(COSTMAT) returns the optimal column indices, % ASSIGN assigned to each row and the minimum COST based on the assignment % problem represented by the COSTMAT, where the (i,j)th element represents the cost to assign the jth % job to the ith worker. % % Partial assignment: This code can identify a partial assignment is a full % assignment is not feasible. For a partial assignment, there are some % zero elements in the returning assignment vector, which indicate % un-assigned tasks. The cost returned only contains the cost of partially % assigned tasks. % This is vectorized implementation of the algorithm. It is the fastest % among all Matlab implementations of the algorithm. % Examples % Example 1: a 5 x 5 example %{ [assignment,cost] = munkres(magic(5)); disp(assignment); % 3 2 1 5 4 disp(cost); %15 %} % Example 2: 400 x 400 random data %{ n=400; A=rand(n); tic [a,b]=munkres(A); toc % about 2 seconds %} % Example 3: rectangular assignment with inf costs %{ A=rand(10,7); A(A>0.7)=Inf; [a,b]=munkres(A); %} % Example 4: an example of partial assignment %{ A = [1 3 Inf; Inf Inf 5; Inf Inf 0.5]; [a,b]=munkres(A) %} % a = [1 0 3] % b = 1.5 % Reference: % "Munkres' Assignment Algorithm, Modified for Rectangular Matrices", % http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html % version 2.3 by Yi Cao at Cranfield University on 11th September 2011 assignment = zeros(1,size(costMat,1)); cost = 0; validMat = costMat == costMat & costMat < Inf; bigM = 10^(ceil(log10(sum(costMat(validMat))))+1); costMat(~validMat) = bigM; % costMat(costMat~=costMat)=Inf; % validMat = costMat<Inf; validCol = any(validMat,1); validRow = any(validMat,2); nRows = sum(validRow); nCols = sum(validCol); n = max(nRows,nCols); if ~n return end maxv=10*max(costMat(validMat)); dMat = zeros(n) + maxv; dMat(1:nRows,1:nCols) = costMat(validRow,validCol); %************************************************* % Munkres' Assignment Algorithm starts here %************************************************* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % STEP 1: Subtract the row minimum from each row. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% minR = min(dMat,[],2); minC = min(bsxfun(@minus, dMat, minR)); %************************************************************************** % STEP 2: Find a zero of dMat. If there are no starred zeros in its % column or row start the zero. Repeat for each zero %************************************************************************** zP = dMat == bsxfun(@plus, minC, minR); starZ = zeros(n,1); while any(zP(:)) [r,c]=find(zP,1); starZ(r)=c; zP(r,:)=false; zP(:,c)=false; end while 1 %************************************************************************** % STEP 3: Cover each column with a starred zero. If all the columns are % covered then the matching is maximum %************************************************************************** if all(starZ>0) break end coverColumn = false(1,n); coverColumn(starZ(starZ>0))=true; coverRow = false(n,1); primeZ = zeros(n,1); [rIdx, cIdx] = find(dMat(~coverRow,~coverColumn)==bsxfun(@plus,minR(~coverRow),minC(~coverColumn))); while 1 %************************************************************************** % STEP 4: Find a noncovered zero and prime it. If there is no starred % zero in the row containing this primed zero, Go to Step 5. % Otherwise, cover this row and uncover the column containing % the starred zero. Continue in this manner until there are no % uncovered zeros left. Save the smallest uncovered value and % Go to Step 6. %************************************************************************** cR = find(~coverRow); cC = find(~coverColumn); rIdx = cR(rIdx); cIdx = cC(cIdx); Step = 6; while ~isempty(cIdx) uZr = rIdx(1); uZc = cIdx(1); primeZ(uZr) = uZc; stz = starZ(uZr); if ~stz Step = 5; break; end coverRow(uZr) = true; coverColumn(stz) = false; z = rIdx==uZr; rIdx(z) = []; cIdx(z) = []; cR = find(~coverRow); z = dMat(~coverRow,stz) == minR(~coverRow) + minC(stz); rIdx = [rIdx(:);cR(z)]; cIdx = [cIdx(:);stz(ones(sum(z),1))]; end if Step == 6 % ************************************************************************* % STEP 6: Add the minimum uncovered value to every element of each covered % row, and subtract it from every element of each uncovered column. % Return to Step 4 without altering any stars, primes, or covered lines. %************************************************************************** [minval,rIdx,cIdx]=outerplus(dMat(~coverRow,~coverColumn),minR(~coverRow),minC(~coverColumn)); minC(~coverColumn) = minC(~coverColumn) + minval; minR(coverRow) = minR(coverRow) - minval; else break end end %************************************************************************** % STEP 5: % Construct a series of alternating primed and starred zeros as % follows: % Let Z0 represent the uncovered primed zero found in Step 4. % Let Z1 denote the starred zero in the column of Z0 (if any). % Let Z2 denote the primed zero in the row of Z1 (there will always % be one). Continue until the series terminates at a primed zero % that has no starred zero in its column. Unstar each starred % zero of the series, star each primed zero of the series, erase % all primes and uncover every line in the matrix. Return to Step 3. %************************************************************************** rowZ1 = find(starZ==uZc); starZ(uZr)=uZc; while rowZ1>0 starZ(rowZ1)=0; uZc = primeZ(rowZ1); uZr = rowZ1; rowZ1 = find(starZ==uZc); starZ(uZr)=uZc; end end % Cost of assignment rowIdx = find(validRow); colIdx = find(validCol); starZ = starZ(1:nRows); vIdx = starZ <= nCols; assignment(rowIdx(vIdx)) = colIdx(starZ(vIdx)); pass = assignment(assignment>0); pass(~diag(validMat(assignment>0,pass))) = 0; assignment(assignment>0) = pass; cost = trace(costMat(assignment>0,assignment(assignment>0))); function [minval,rIdx,cIdx]=outerplus(M,x,y) ny=size(M,2); minval=inf; for c=1:ny M(:,c)=M(:,c)-(x+y(c)); minval = min(minval,min(M(:,c))); end [rIdx,cIdx]=find(M==minval);
github
gallunf/SR2-master
SR2.m
.m
SR2-master/Experiment/SR2.m
41,020
utf_8
489758e109280113949978673f45e0bb
function varargout = SR2(varargin) % SR2 M-file for SR2.fig % SR2, by itself, creates a new SR2 or raises the existing % singleton*. % % H = SR2 returns the handle to a new SR2 or the handle to % the existing singleton*. % % SR2('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in SR2.M with the given input arguments. % % SR2('Property','Value',...) creates a new SR2 or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before SR2_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to SR2_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help SR2 % Last Modified by GUIDE v2.5 24-Apr-2012 14:47:21 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @SR2_OpeningFcn, ... 'gui_OutputFcn', @SR2_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 SR2 is made visible. function SR2_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 SR2 (see VARARGIN) % Choose default command line output for SR2 handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes SR2 wait for user response (see UIRESUME) % uiwait(handles.figure1); caldir=pwd; try load([caldir '\calfiles\SR_calvals.mat']) set(handles.ed_cal_date,'String',calvals.date) catch set(handles.ed_cal_date,'String','UNCALIBRATED') end prompt = {'Enter subject number:','Enter Right Ear SRT:','Enter Left Ear SRT:'}; dlg_title = 'Initialize Spatial Release Testing'; num_lines = 3; def = {'555','0','0'}; subjdata = inputdlg(prompt,dlg_title,num_lines,def); set(handles.ed_subjnum,'String',subjdata{1}) set(handles.ed_RE_SRT,'String',subjdata{2}) set(handles.ed_LE_SRT,'String',subjdata{3}) handles.SR2vals.SRT.RE=str2double(subjdata{2}); handles.SR2vals.SRT.LE=str2double(subjdata{3}); SLval=30; HL2SPL=22; SRT_dB_SPL.RE=str2num(subjdata{2})+HL2SPL; SRT_dB_SPL.LE=str2num(subjdata{3})+HL2SPL; handles.SR2vals.presentation_level.LE=SRT_dB_SPL.LE+SLval; handles.SR2vals.presentation_level.RE=SRT_dB_SPL.RE+SLval; if handles.SR2vals.presentation_level.LE > 80 handles.SR2vals.presentation_level.LE = 80; end if handles.SR2vals.presentation_level.RE > 80 handles.SR2vals.presentation_level.RE = 80; end maxlev=max([handles.SR2vals.presentation_level.RE handles.SR2vals.presentation_level.RE]); handles.target_level=maxlev; set(handles.ed_tlev,'String',num2str(maxlev)) subject=subjdata{1}; homedir=pwd; if ~exist([homedir '\data'],'dir') eval(['mkdir ' homedir '\data']) end if ~exist([homedir '\data\' subject],'dir') eval(['mkdir ' homedir '\data\' subject]) end fdir = dir([homedir '\data\' subject '\' subject '_SR2.*']); runs=length(fdir); if runs for n=1:runs try load([homedir '\data\' subject '\' subject '_SR2.' num2str(n)],'-mat') switch SR2vals.condition case 0 set(handles.ed_colocated,'String',num2str(SR2vals.total_correct)) case 15 set(handles.ed_15degrees,'String',num2str(SR2vals.total_correct)) case 30 set(handles.ed_30degrees,'String',num2str(SR2vals.total_correct)) case 45 set(handles.ed_45degrees,'String',num2str(SR2vals.total_correct)) end handles.summary{n}=SR2vals; end end end guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = SR2_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in pb_go. function pb_go_Callback(hObject, eventdata, handles) % hObject handle to pb_go (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.pb_go,'String','Running') set(handles.pb_go,'BackgroundColor',[1 0 0]) set(handles.pb_go,'Enable','off') set(handles.pb_stop,'Enable','on') set(handles.pb_go,'UserData',1) subject=get(handles.ed_subjnum,'String'); handles.SR2vals.subject=subject; homedir=pwd; if ~exist([homedir '\data'],'dir') eval(['mkdir ' homedir '\data']) end if ~exist([homedir '\data\' subject],'dir') eval(['mkdir ' homedir '\data\' subject]) end fdir = dir([homedir '\data\' subject '\' subject '_SR2.*']); runs=length(fdir); run=length(fdir)+1; handles.SR2vals.run=run; handles.SR2vals.total_correct=NaN; handles.SR2vals.file = [pwd '\data\' subject '\' subject '_SR2.' num2str(run)]; handles.SR2vals.condition=handles.condition; handles.SR2vals.SRT.LE=str2double(get(handles.ed_LE_SRT,'String')); handles.SR2vals.SRT.RE=str2double(get(handles.ed_RE_SRT,'String')); handles.SR2vals.RMS=.123; handles.SR2vals.target_level=str2double(get(handles.ed_tlev,'String')); caldir=pwd; try load([caldir '\calfiles\SR_calvals.mat']) catch calvals.system=2; calvals.cal_level_left=99; calvals.cal_level_right=99; calvals.cal_atten=-20; calvals.system_name='Default'; calvals.date=NaN; end handles.SR2vals.calvals=calvals; handles.SR2vals.caltone_RMS=10^(calvals.cal_atten/20); CRMdir='D:\Experiments\SR2\Experiment\CRM_original\Talker'; load Kemar_CIPIC handles.SR2vals.samplerate=44100; % Set the random number generator to a unique state rand('state',sum(100*clock)) randn('state',sum(100*clock)) f=CRM_resp_gui; set(f,'Position',[501 26 130 33]) set(f,'Name','Response') buttonhandles=guidata(f); set(f,'UserData',[]); set(buttonhandles.pb_start,'String','Start'); set(buttonhandles.pb_start,'Enable','on'); start=get(f,'UserData'); set(buttonhandles.tx_instructions,'String','Press Start to begin.') while isempty(start) pause(.1) start=get(f,'UserData'); end set(buttonhandles.pb_start,'String',''); target_level=handles.SR2vals.target_level*ones(1,20); SNR=[10 10 8 8 6 6 4 4 2 2 0 0 -2 -2 -4 -4 -6 -6 -8 -8]; masker_level=target_level-SNR; handles.SR2vals.masker_level=masker_level; handles.SR2vals.SNR=SNR; separation=handles.SR2vals.condition; guidata(handles.figure1, handles); running=get(handles.pb_go,'UserData'); trial=1; set(handles.axes1,'NextPlot','replace') while running set(handles.ed_mlev,'String',num2str(masker_level(trial))); twavs=[];m1wavs=[];m2wavs=[]; target=[];masker1=[]; masker2=[]; ta=[];m1=[];m2=[]; num=randperm(8)-1; col=randperm(4)-1;callsign=randperm(6); ttalker=randperm(3); target=[num2str(ttalker(1)) '\000' num2str(col(1)) '0' num2str(num(1)) '.wav']; masker1=[num2str(ttalker(2)) '\0' num2str(callsign(1)) '0' num2str(col(2)) '0' num2str(num(2)) '.wav']; masker2=[num2str(ttalker(3)) '\0' num2str(callsign(2)) '0' num2str(col(3)) '0' num2str(num(3)) '.wav']; ta=audioread([CRMdir target]); ta=ta.*(handles.SR2vals.RMS/std(ta)); m1=audioread([CRMdir masker1]); m1=m1.*(handles.SR2vals.RMS/std(m1)); m2=audioread([CRMdir masker2]); m2=m2.*(handles.SR2vals.RMS/std(m2)); % create a modulation / windowing function (an envelope) rampdur = 0.02; % 20 millisecond ramps rampsamps = ceil(rampdur.*handles.SR2vals.samplerate); ta_envelope = [cos(linspace(-pi/2,0,rampsamps)) ones(1,length(ta)-2*rampsamps) cos(linspace(0,pi/2,rampsamps))].^2; m1_envelope = [cos(linspace(-pi/2,0,rampsamps)) ones(1,length(m1)-2*rampsamps) cos(linspace(0,pi/2,rampsamps))].^2; m2_envelope = [cos(linspace(-pi/2,0,rampsamps)) ones(1,length(m2)-2*rampsamps) cos(linspace(0,pi/2,rampsamps))].^2; % Modulate each signal ta=ta.*ta_envelope'; m1=m1.*m1_envelope'; m2=m2.*m2_envelope'; handles.SR2vals.target_atten_LE=target_level(trial)-calvals.cal_level_left; handles.SR2vals.target_atten_RE=target_level(trial)-calvals.cal_level_right; handles.SR2vals.target_RMS.LE=handles.SR2vals.caltone_RMS*10^(handles.SR2vals.target_atten_LE/20); handles.SR2vals.target_RMS.RE=handles.SR2vals.caltone_RMS*10^(handles.SR2vals.target_atten_RE/20); handles.SR2vals.ampfactor.target.LE=handles.SR2vals.target_RMS.LE/handles.SR2vals.RMS; handles.SR2vals.ampfactor.target.RE=handles.SR2vals.target_RMS.RE/handles.SR2vals.RMS; handles.SR2vals.masker_atten_LE=masker_level(trial)-calvals.cal_level_left; handles.SR2vals.masker_atten_RE=masker_level(trial)-calvals.cal_level_right; handles.SR2vals.masker_RMS.LE=handles.SR2vals.caltone_RMS*10^(handles.SR2vals.masker_atten_LE/20); handles.SR2vals.masker_RMS.RE=handles.SR2vals.caltone_RMS*10^(handles.SR2vals.masker_atten_RE/20); handles.SR2vals.ampfactor.masker.LE=handles.SR2vals.masker_RMS.LE/handles.SR2vals.RMS; handles.SR2vals.ampfactor.masker.RE=handles.SR2vals.masker_RMS.RE/handles.SR2vals.RMS; tlen=length(ta); m1len=length(m1); m2len=length(m2); maxlen=max([tlen,m1len,m2len]); tbuff=maxlen-tlen; m1buff=maxlen-m1len; m2buff=maxlen-m2len; tzeros=zeros(tbuff,1); m1zeros=zeros(m1buff,1); m2zeros=zeros(m2buff,1); targ.LE=[ta; tzeros]*handles.SR2vals.ampfactor.target.LE; targ.RE=[ta; tzeros]*handles.SR2vals.ampfactor.target.LE; mask1.LE=[m1; m1zeros]*handles.SR2vals.ampfactor.masker.LE; mask1.RE=[m1; m1zeros]*handles.SR2vals.ampfactor.masker.RE; mask2.LE=[m2; m2zeros]*handles.SR2vals.ampfactor.masker.LE; mask2.RE=[m2; m2zeros]*handles.SR2vals.ampfactor.masker.RE; set(buttonhandles.tx_instructions,'String',['Trial ' num2str(trial)]) set(handles.ed_trial,'String',num2str(trial)) pause(.5) set(buttonhandles.tx_instructions,'String','') pause(.5) switch handles.SR2vals.condition case 0 tIR=IR_0; m1IR=IR_0; m2IR=IR_0; case 15 tIR=IR_0; m1IR=IR_n15; m2IR=IR_p15; case 30 tIR=IR_0; m1IR=IR_n30; m2IR=IR_p30; case 45 tIR=IR_0; m1IR=IR_n45; m2IR=IR_p45; end twavs(:,1) = conv(tIR(:,1),targ.LE); twavs(:,2) = conv(tIR(:,2),targ.RE); m1wavs(:,1) = conv(m1IR(:,1),mask1.LE); m1wavs(:,2) = conv(m1IR(:,2),mask1.RE); m2wavs(:,1) = conv(m2IR(:,1),mask2.LE); m2wavs(:,2) = conv(m2IR(:,2),mask2.RE); sig.left=twavs(:,1)+m1wavs(:,1)+m2wavs(:,1); sig.right=twavs(:,2)+m1wavs(:,2)+m2wavs(:,2); if calvals.system==1 pa_wavplay([sig.left sig.right],handles.SR2vals.samplerate); else sound([sig.left sig.right],handles.SR2vals.samplerate,16); pause(length(sig.left)/handles.SR2vals.samplerate); end for n=1:32 commandtext=['set(buttonhandles.pushbutton' num2str(n) ',''Enable'',''on'')']; eval(commandtext) end set(buttonhandles.tx_instructions,'String','What Color and Number?') set(f,'UserData',[]); mydata=get(f,'UserData'); while isempty(mydata) pause(.1) mydata=get(f,'UserData'); running=get(handles.pb_go,'UserData'); if ~running set(buttonhandles.tx_instructions,'String','Thank you. Please wait.') set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 0.5]) set(handles.pb_go,'Enable','on') set(handles.pb_stop,'Enable','off') guidata(handles.figure1, handles); return end end mydata.tlevel=target_level(trial); mydata.mlevel=masker_level(trial); mydata.SNR=SNR(trial); mydata.tcol=col(1); mydata.tnum=num(1); mydata.m1col=col(2); mydata.m1num=num(2); mydata.m2col=col(3); mydata.m2num=num(3); if mydata.color==col(1) mydata.colcorr=1; else mydata.colcorr=0; end if mydata.number==num(1) mydata.numcorr=1; else mydata.numcorr=0; end if mydata.numcorr+mydata.colcorr == 2 mydata.correct=1; set(buttonhandles.tx_instructions,'String','Correct') else mydata.correct=0; set(buttonhandles.tx_instructions,'String','Incorrect.') end data{trial}=mydata; summary(trial)=data{trial}.correct; set(handles.ed_total,'String',num2str(sum(summary))) plot(handles.axes1,handles.SR2vals.SNR(1:2:trial)+.15,summary(1:2:trial),'ko') set(handles.axes1,'NextPlot','add') plot(handles.axes1,handles.SR2vals.SNR(2:2:trial)-.15,summary(2:2:trial),'k^') xlabel(handles.axes1,'SNR (dB)') %ylabel(handles.axes1,'Correct = 1; Incorrect = 0') set(handles.axes1,'YTick',[0 1]) set(handles.axes1,'XTick',-10:2:12) set(handles.axes1,'YTickLabel',{'Incorrect','Correct'}) axis(handles.axes1,[-9 11 -.1 1.1]) pause(.5) trial=trial+1; if trial>20 set(handles.pb_go,'UserData',0) handles.SR2vals.total_correct=sum(summary); handles.SR2vals.data=data; handles.SR2vals.summary=summary; SR2vals=handles.SR2vals; save(handles.SR2vals.file,'SR2vals') switch SR2vals.condition case 0 set(handles.ed_colocated,'String',num2str(SR2vals.total_correct)) case 15 set(handles.ed_15degrees,'String',num2str(SR2vals.total_correct)) case 30 set(handles.ed_30degrees,'String',num2str(SR2vals.total_correct)) case 45 set(handles.ed_45degrees,'String',num2str(SR2vals.total_correct)) end if ~exist('SR2summary.csv','file') fid=fopen('SR2summary.csv','w'); fprintf(fid,'%s','Subject'); fprintf(fid,', %s','Date'); fprintf(fid,', %s','Spatial'); fprintf(fid,', %s','Total Correct'); fprintf(fid,', %s',num2str(SR2vals.SNR)); fclose(fid); end fid=fopen('SR2summary.csv','a'); fprintf(fid,'\n'); fprintf(fid,'%s',SR2vals.subject); fprintf(fid,', %s',date); fprintf(fid,', %s',num2str(SR2vals.condition)); fprintf(fid,', %s',num2str(SR2vals.total_correct)); fprintf(fid,', %s',num2str(SR2vals.summary)); fclose(fid); end running=get(handles.pb_go,'UserData'); end set(buttonhandles.tx_instructions,'String','Thank you. Please wait.') set(handles.pb_go,'String','Saving') set(handles.pb_go,'Enable','off') fid=fopen([pwd '\data\' subject '\' subject '_SR2_summary.csv'],'w'); fdir = dir([homedir '\data\' subject '\' subject '_SR2.*']); fprintf(fid,'%s','Subject'); fprintf(fid,', %s','Condition'); fprintf(fid,', %s','Total Correct'); fprintf(fid,', %s',num2str(SR2vals.SNR)); runs=length(fdir); if runs for n=1:runs try load([homedir '\data\' subject '\' subject '_SR2.' num2str(n)],'-mat') fprintf(fid,'\n'); fprintf(fid,'%s',SR2vals.subject); fprintf(fid,', %s',num2str(SR2vals.condition)); fprintf(fid,', %s',num2str(SR2vals.total_correct)); fprintf(fid,', %s',num2str(SR2vals.summary)); end end end fclose(fid); set(handles.pb_go,'String','Export Data') set(handles.pb_go,'Enable','on') set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 0.5]) set(handles.pb_go,'Enable','on') set(handles.pb_stop,'Enable','off') set(handles.pb_go,'UserData',0) guidata(handles.figure1, handles); function ed_subjnum_Callback(hObject, eventdata, handles) % hObject handle to ed_subjnum (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_subjnum as text % str2double(get(hObject,'String')) returns contents of ed_subjnum as a double % --- Executes during object creation, after setting all properties. function ed_subjnum_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_subjnum (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pb_stop. function pb_stop_Callback(hObject, eventdata, handles) % hObject handle to pb_stop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 0.5]) set(handles.pb_go,'Enable','on') set(handles.pb_stop,'Enable','off') set(handles.pb_go,'UserData',0) % --- Executes on button press in pb_done. function pb_done_Callback(hObject, eventdata, handles) % hObject handle to pb_done (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) f=CRM_resp_gui; close(f); close(handles.figure1); % --- Executes on button press in rb_0. function rb_0_Callback(hObject, eventdata, handles) % hObject handle to rb_0 (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 rb_0 set(handles.rb_15,'Value',0) set(handles.rb_30,'Value',0) set(handles.rb_45,'Value',0) handles.condition=0; guidata(hObject, handles); set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 .5]) set(handles.pb_go,'Enable','on') % --- Executes on button press in rb_15. function rb_15_Callback(hObject, eventdata, handles) % hObject handle to rb_15 (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 rb_15 set(handles.rb_0,'Value',0) set(handles.rb_30,'Value',0) set(handles.rb_45,'Value',0) handles.condition=15; guidata(hObject, handles); set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 .5]) set(handles.pb_go,'Enable','on') % --- Executes on button press in rb_30. function rb_30_Callback(hObject, eventdata, handles) % hObject handle to rb_30 (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 rb_30 set(handles.rb_0,'Value',0) set(handles.rb_15,'Value',0) set(handles.rb_45,'Value',0) handles.condition=30; guidata(hObject, handles); set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 .5]) set(handles.pb_go,'Enable','on') % --- Executes on button press in rb_45. function rb_45_Callback(hObject, eventdata, handles) % hObject handle to rb_45 (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 rb_45 set(handles.rb_0,'Value',0) set(handles.rb_15,'Value',0) set(handles.rb_30,'Value',0) handles.condition=45; guidata(hObject, handles); set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 .5]) set(handles.pb_go,'Enable','on') function ed_mlev_Callback(hObject, eventdata, handles) % hObject handle to ed_mlev (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_mlev as text % str2double(get(hObject,'String')) returns contents of ed_mlev as a double % --- Executes during object creation, after setting all properties. function ed_mlev_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_mlev (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_tlev_Callback(hObject, eventdata, handles) % hObject handle to ed_tlev (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_tlev as text % str2double(get(hObject,'String')) returns contents of ed_tlev as a double % --- Executes during object creation, after setting all properties. function ed_tlev_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_tlev (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_trial_Callback(hObject, eventdata, handles) % hObject handle to ed_trial (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_trial as text % str2double(get(hObject,'String')) returns contents of ed_trial as a double % --- Executes during object creation, after setting all properties. function ed_trial_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_trial (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_correct_Callback(hObject, eventdata, handles) % hObject handle to ed_correct (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_correct as text % str2double(get(hObject,'String')) returns contents of ed_correct as a double % --- Executes during object creation, after setting all properties. function ed_correct_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_correct (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_total_Callback(hObject, eventdata, handles) % hObject handle to ed_total (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_total as text % str2double(get(hObject,'String')) returns contents of ed_total as a double % --- Executes during object creation, after setting all properties. function ed_total_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_total (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_RE_SRT_Callback(hObject, eventdata, handles) % hObject handle to ed_RE_SRT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_RE_SRT as text % str2double(get(hObject,'String')) returns contents of ed_RE_SRT as a double % --- Executes during object creation, after setting all properties. function ed_RE_SRT_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_RE_SRT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_LE_SRT_Callback(hObject, eventdata, handles) % hObject handle to ed_LE_SRT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_LE_SRT as text % str2double(get(hObject,'String')) returns contents of ed_LE_SRT as a double % --- Executes during object creation, after setting all properties. function ed_LE_SRT_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_LE_SRT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit10_Callback(hObject, eventdata, handles) % hObject handle to edit10 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit10 as text % str2double(get(hObject,'String')) returns contents of edit10 as a double % --- Executes during object creation, after setting all properties. function edit10_CreateFcn(hObject, eventdata, handles) % hObject handle to edit10 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit11_Callback(hObject, eventdata, handles) % hObject handle to edit11 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit11 as text % str2double(get(hObject,'String')) returns contents of edit11 as a double % --- Executes during object creation, after setting all properties. function edit11_CreateFcn(hObject, eventdata, handles) % hObject handle to edit11 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_cal_date_Callback(hObject, eventdata, handles) % hObject handle to ed_cal_date (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_cal_date as text % str2double(get(hObject,'String')) returns contents of ed_cal_date as a double % --- Executes during object creation, after setting all properties. function ed_cal_date_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_cal_date (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pb_cal. function pb_cal_Callback(hObject, eventdata, handles) % hObject handle to pb_cal (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(hObject,'Enable','off') calvals = go_calibrate(handles); set(handles.ed_cal_date,'String',calvals.date) set(hObject,'Enable','on') function calvals = go_calibrate(handles) % play three-second long tone and save the RMS values caldir=pwd; calfile=[caldir '\calfiles\SR_calvals.mat']; if ~exist([caldir '\calfiles'],'dir') eval(['mkdir ' caldir '\calfiles']) end if exist(calfile,'file') load([caldir '\calfiles\SR_calvals.mat']) calvals.previous_cal_level_left=calvals.cal_level_left; calvals.previous_cal_level_right=calvals.cal_level_right; % Construct a questdlg with three options ovrwrt = questdlg('Calibration file exists. Overwrite?','Calibration File Exists','Yes','No','No'); if strcmp(ovrwrt,'No') load([caldir '\calfiles\SR_calvals.mat']) return end D=dir([caldir '\calfiles\SR_calvals_old*']); numfiles=size(D,1); fname2 = [caldir '\calfiles\SR_calvals_old_' num2str(numfiles+1) '.mat']; copyfile(calfile,fname2); else calvals.previous_cal_level_left=0; calvals.previous_cal_level_right=0; end calvals.date=date; calvals.directory=pwd; calvals.cal_freq=1000; calvals.cal_level_left=-99; calvals.cal_level_right=-99; calvals.cal_atten=-20; tone=makeCalTone(calvals.cal_freq, 44100, 3, calvals.cal_atten, 0,.005); silence=zeros(size(tone.wave)); isasio=questdlg('Does sound generation system use ASIO Drivers?','Sound System','Yes','No','Unsure','Yes'); if strcmp(isasio,'Yes') sname=inputdlg('Enter System name:','Name System',1,{'ASIO Soundcard'}); calvals.system_name=sname{1}; calvals.system=1; calvals.driver='asio'; elseif strcmp(isasio,'No') sname=inputdlg('Enter System name:','Name System',1,{'Windows Soundcard'}); calvals.system=2; calvals.system_name=sname{1}; calvals.driver='win'; elseif strcmp(isasio,'Unsure') checkasio=questdlg('Check to see if sound generation system supports greater ASIO Drivers?','Sound System','Yes','No','Yes'); if strcmp(checkasio,'Yes') h=warndlg('Click Ok and then listen for a 1000 Hz tone.','Tone Will Play'); uiwait(h) pause(.1) pa_wavplay([tone.wave' tone.wave'],tone.sampling_rate,'asio'); useasio=questdlg('Was a sound presented?','Sound System','Yes','No','Yes'); if strcmp(useasio,'Yes') sname=inputdlg('Enter System name:','Name System',1,{'ASIO Soundcard'}); calvals.system_name=sname{1}; calvals.system=1; calvals.driver='asio'; elseif strcmp(useasio,'No') sname=inputdlg('Enter System name:','Name System',1,{'Windows Soundcard'}); calvals.system=2; calvals.system_name=sname{1}; calvals.driver='win'; end else warndlg('System will use Windows drivers. Redo calibration to reset.') sname=inputdlg('Enter System name:','Name System',1,{'Windows Soundcard'}); calvals.system=2; calvals.system_name=sname{1}; calvals.driver='win'; end end for side=1:2 if side==1 while calvals.cal_level_left==-99 % set(handles.tx_comment,'String',['Now playing ' num2str(calvals.cal_freq) ' Hz tone on left channel at 44100 Hz.']) pause(.5) tone=makeCalTone(calvals.cal_freq, 44100, 3, calvals.cal_atten, 0,.005); silence=zeros(size(tone.wave)); if calvals.system==1 pa_wavplay([tone.wave' silence'],tone.sampling_rate); else sound([tone.wave' silence'],tone.sampling_rate,16); end % set(handles.tx_comment,'String','') level=[]; qstring=['Enter dB SPL reading for LEFT CHANNEL (enter -99 to play again) Previous level was ' num2str(calvals.previous_cal_level_left) ': ']; level = inputdlg(qstring,'Calibration Level (dB)',1,{'-99'}); try calvals.cal_level_left =str2num(level{1}); catch calvals.cal_level_left = -99; end end else while calvals.cal_level_right==-99 % set(handles.tx_comment,'String',['Now playing ' num2str(calvals.cal_freq) ' Hz tone on right channel at 44100 Hz.']) pause(.5) tone=makeCalTone(calvals.cal_freq, 44100, 3, calvals.cal_atten, 0,.005); silence=zeros(size(tone.wave)); if calvals.system==1 pa_wavplay([silence' tone.wave'],tone.sampling_rate); else sound([silence' tone.wave'],tone.sampling_rate,16); end % set(handles.tx_comment,'String','') level=[]; qstring=['Enter dB SPL reading for RIGHT CHANNEL (enter -99 to play again) Previous level was ' num2str(calvals.previous_cal_level_right) ': ']; level = inputdlg(qstring,'Calibration Level (dB)',1,{'-99'}); try calvals.cal_level_right =str2num(level{1}); catch calvals.cal_level_right =-99; end end end end save([caldir '\calfiles\SR_calvals.mat'],'calvals') function s=makeCalTone(frequency, sampling_rate, duration, amplitude, phase, onoff_ramp) % s=makeCalTone(frequency, sampling_rate, duration, amplitude, phase) % frequency: in Hz (e.g., 1000); a vector creates a tone complex % sampling_rate: in Hz (e.g., 48000) % duration: in seconds (e.g., 1) % amplitude: in decibels re: maximum (e.g., -30) % phase: in radians, between 0 and 2*pi (e.g., pi) % onofframp: in seconds (e.g., .01) s.frequency=frequency; s.sampling_rate=sampling_rate; s.duration=duration; s.amplitude=amplitude; s.phase=phase; %determine the signal length in samples and create a vector (x) of the right length to hold it x=1:ceil(duration.*sampling_rate); final_tone=zeros(1,length(x)); for n=1:length(frequency) %generate a sine wave tone=sin((2*pi*(frequency(n)/sampling_rate).*x)+phase); % create a windowing function (an envelope) rampdur = onoff_ramp; rampsamps = ceil(rampdur.*sampling_rate); envelope = [cos(linspace(-pi/2,0,rampsamps)) ones(1,ceil(duration.*sampling_rate)-2*rampsamps) cos(linspace(0,pi/2,rampsamps))].^2; tone=tone.*envelope; final_tone=final_tone+tone; end %set the RMS level of the signal to the specified amplitude in dB toneRMS=sqrt(mean(final_tone.^2)); amp=10^(amplitude/20); ampdiff=amp/toneRMS; s.wave=final_tone.*ampdiff; function ed_15degrees_Callback(hObject, eventdata, handles) % hObject handle to ed_15degrees (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_15degrees as text % str2double(get(hObject,'String')) returns contents of ed_15degrees as a double % --- Executes during object creation, after setting all properties. function ed_15degrees_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_15degrees (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_30degrees_Callback(hObject, eventdata, handles) % hObject handle to ed_30degrees (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_30degrees as text % str2double(get(hObject,'String')) returns contents of ed_30degrees as a double % --- Executes during object creation, after setting all properties. function ed_30degrees_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_30degrees (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_45degrees_Callback(hObject, eventdata, handles) % hObject handle to ed_45degrees (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_45degrees as text % str2double(get(hObject,'String')) returns contents of ed_45degrees as a double % --- Executes during object creation, after setting all properties. function ed_45degrees_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_45degrees (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_colocated_Callback(hObject, eventdata, handles) % hObject handle to ed_colocated (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_colocated as text % str2double(get(hObject,'String')) returns contents of ed_colocated as a double % --- Executes during object creation, after setting all properties. function ed_colocated_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_colocated (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end
github
gallunf/SR2-master
CRM_resp_gui.m
.m
SR2-master/Experiment/CRM_resp_gui.m
15,017
utf_8
0416c995ef68731f227f9a03d1c7e6aa
function varargout = CRM_resp_gui(varargin) % CRM_RESP_GUI M-file for CRM_resp_gui.fig % CRM_RESP_GUI, by itself, creates a new CRM_RESP_GUI or raises the existing % singleton*. % % H = CRM_RESP_GUI returns the handle to a new CRM_RESP_GUI or the handle to % the existing singleton*. % % CRM_RESP_GUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in CRM_RESP_GUI.M with the given input arguments. % % CRM_RESP_GUI('Property','Value',...) creates a new CRM_RESP_GUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before CRM_resp_gui_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to CRM_resp_gui_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help CRM_resp_gui % Last Modified by GUIDE v2.5 22-Mar-2010 09:45:10 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @CRM_resp_gui_OpeningFcn, ... 'gui_OutputFcn', @CRM_resp_gui_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before CRM_resp_gui is made visible. function CRM_resp_gui_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to CRM_resp_gui (see VARARGIN) % Choose default command line output for CRM_resp_gui handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes CRM_resp_gui wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = CRM_resp_gui_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- 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) mydata.color=00; mydata.number=00; set(get(gcbo,'Parent'),'UserData',mydata); % --- 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) mydata.color=00; mydata.number=01; set(get(gcbo,'Parent'),'UserData',mydata); % --- 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) mydata.color=00; mydata.number=02; set(get(gcbo,'Parent'),'UserData',mydata); % --- 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) mydata.color=00; mydata.number=03; set(get(gcbo,'Parent'),'UserData',mydata); % --- 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) mydata.color=00; mydata.number=04; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton6. function pushbutton6_Callback(hObject, eventdata, handles) % hObject handle to pushbutton6 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=00; mydata.number=05; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton7. function pushbutton7_Callback(hObject, eventdata, handles) % hObject handle to pushbutton7 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=00; mydata.number=06; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton8. function pushbutton8_Callback(hObject, eventdata, handles) % hObject handle to pushbutton8 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=00; mydata.number=07; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton9. function pushbutton9_Callback(hObject, eventdata, handles) % hObject handle to pushbutton9 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=01; mydata.number=00; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton10. function pushbutton10_Callback(hObject, eventdata, handles) % hObject handle to pushbutton10 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=01; mydata.number=01; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton11. function pushbutton11_Callback(hObject, eventdata, handles) % hObject handle to pushbutton11 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=01; mydata.number=02; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton12. function pushbutton12_Callback(hObject, eventdata, handles) % hObject handle to pushbutton12 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=01; mydata.number=03; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton13. function pushbutton13_Callback(hObject, eventdata, handles) % hObject handle to pushbutton13 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=01; mydata.number=04; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton14. function pushbutton14_Callback(hObject, eventdata, handles) % hObject handle to pushbutton14 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=01; mydata.number=05; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton15. function pushbutton15_Callback(hObject, eventdata, handles) % hObject handle to pushbutton15 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=01; mydata.number=06; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton16. function pushbutton16_Callback(hObject, eventdata, handles) % hObject handle to pushbutton16 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=01; mydata.number=07; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton17. function pushbutton17_Callback(hObject, eventdata, handles) % hObject handle to pushbutton17 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=02; mydata.number=00; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton18. function pushbutton18_Callback(hObject, eventdata, handles) % hObject handle to pushbutton18 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=02; mydata.number=01; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton19. function pushbutton19_Callback(hObject, eventdata, handles) % hObject handle to pushbutton19 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=02; mydata.number=02; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton20. function pushbutton20_Callback(hObject, eventdata, handles) % hObject handle to pushbutton20 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=02; mydata.number=03; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton21. function pushbutton21_Callback(hObject, eventdata, handles) % hObject handle to pushbutton21 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=02; mydata.number=04; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton22. function pushbutton22_Callback(hObject, eventdata, handles) % hObject handle to pushbutton22 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=02; mydata.number=05; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton23. function pushbutton23_Callback(hObject, eventdata, handles) % hObject handle to pushbutton23 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=02; mydata.number=06; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton24. function pushbutton24_Callback(hObject, eventdata, handles) % hObject handle to pushbutton24 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=02; mydata.number=07; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton25. function pushbutton25_Callback(hObject, eventdata, handles) % hObject handle to pushbutton25 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=03; mydata.number=00; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton26. function pushbutton26_Callback(hObject, eventdata, handles) % hObject handle to pushbutton26 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=03; mydata.number=01; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton27. function pushbutton27_Callback(hObject, eventdata, handles) % hObject handle to pushbutton27 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=03; mydata.number=02; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton28. function pushbutton28_Callback(hObject, eventdata, handles) % hObject handle to pushbutton28 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=03; mydata.number=03; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton29. function pushbutton29_Callback(hObject, eventdata, handles) % hObject handle to pushbutton29 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=03; mydata.number=04; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton30. function pushbutton30_Callback(hObject, eventdata, handles) % hObject handle to pushbutton30 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=03; mydata.number=05; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton31. function pushbutton31_Callback(hObject, eventdata, handles) % hObject handle to pushbutton31 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=03; mydata.number=06; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pushbutton32. function pushbutton32_Callback(hObject, eventdata, handles) % hObject handle to pushbutton32 (see gcbo) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=03; mydata.number=07; set(get(gcbo,'Parent'),'UserData',mydata); % --- Executes on button press in pb_start. function pb_start_Callback(hObject, eventdata, handles) % hObject handle to pb_start (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) mydata.color=99; mydata.number=99; set(get(gcbo,'Parent'),'UserData',mydata);
github
gallunf/SR2-master
run_SR2.m
.m
SR2-master/Experiment/run_SR2.m
41,079
utf_8
c978b5428101845656e0b9cc059670c8
function varargout = run_SR2(varargin) % run_SR2 M-file for run_SR2.fig % run_SR2, by itself, creates a new run_SR2 or raises the existing % singleton*. % % H = run_SR2 returns the handle to a new run_SR2 or the handle to % the existing singleton*. % % run_SR2('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in run_SR2.M with the given input arguments. % % run_SR2('Property','Value',...) creates a new run_SR2 or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before run_SR2_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to run_SR2_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help run_SR2 % Last Modified by GUIDE v2.5 24-Apr-2012 14:47:21 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @run_SR2_OpeningFcn, ... 'gui_OutputFcn', @run_SR2_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 run_SR2 is made visible. function run_SR2_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 run_SR2 (see VARARGIN) % Choose default command line output for run_SR2 handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes run_SR2 wait for user response (see UIRESUME) % uiwait(handles.figure1); caldir=pwd; try load([caldir '\calfiles\SR_calvals.mat']) set(handles.ed_cal_date,'String',calvals.date) catch set(handles.ed_cal_date,'String','UNCALIBRATED') end prompt = {'Enter subject number:','Enter Right Ear SRT:','Enter Left Ear SRT:'}; dlg_title = 'Initialize Spatial Release Testing'; num_lines = 3; def = {'555','0','0'}; subjdata = inputdlg(prompt,dlg_title,num_lines,def); set(handles.ed_subjnum,'String',subjdata{1}) set(handles.ed_RE_SRT,'String',subjdata{2}) set(handles.ed_LE_SRT,'String',subjdata{3}) handles.SR2vals.SRT.RE=str2double(subjdata{2}); handles.SR2vals.SRT.LE=str2double(subjdata{3}); SLval=30; HL2SPL=22; SRT_dB_SPL.RE=str2num(subjdata{2})+HL2SPL; SRT_dB_SPL.LE=str2num(subjdata{3})+HL2SPL; handles.SR2vals.presentation_level.LE=SRT_dB_SPL.LE+SLval; handles.SR2vals.presentation_level.RE=SRT_dB_SPL.RE+SLval; if handles.SR2vals.presentation_level.LE > 80 handles.SR2vals.presentation_level.LE = 80; end if handles.SR2vals.presentation_level.RE > 80 handles.SR2vals.presentation_level.RE = 80; end maxlev=max([handles.SR2vals.presentation_level.RE handles.SR2vals.presentation_level.RE]); handles.target_level=maxlev; set(handles.ed_tlev,'String',num2str(maxlev)) subject=subjdata{1}; homedir=pwd; if ~exist([homedir '\data'],'dir') eval(['mkdir ' homedir '\data']) end if ~exist([homedir '\data\' subject],'dir') eval(['mkdir ' homedir '\data\' subject]) end fdir = dir([homedir '\data\' subject '\' subject '_SR2.*']); runs=length(fdir); if runs for n=1:runs try load([homedir '\data\' subject '\' subject '_SR2.' num2str(n)],'-mat') switch SR2vals.condition case 0 set(handles.ed_colocated,'String',num2str(SR2vals.total_correct)) case 15 set(handles.ed_15degrees,'String',num2str(SR2vals.total_correct)) case 30 set(handles.ed_30degrees,'String',num2str(SR2vals.total_correct)) case 45 set(handles.ed_45degrees,'String',num2str(SR2vals.total_correct)) end handles.summary{n}=SR2vals; end end end guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = run_SR2_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in pb_go. function pb_go_Callback(hObject, eventdata, handles) % hObject handle to pb_go (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.pb_go,'String','Running') set(handles.pb_go,'BackgroundColor',[1 0 0]) set(handles.pb_go,'Enable','off') set(handles.pb_stop,'Enable','on') set(handles.pb_go,'UserData',1) subject=get(handles.ed_subjnum,'String'); handles.SR2vals.subject=subject; homedir=pwd; if ~exist([homedir '\data'],'dir') eval(['mkdir ' homedir '\data']) end if ~exist([homedir '\data\' subject],'dir') eval(['mkdir ' homedir '\data\' subject]) end fdir = dir([homedir '\data\' subject '\' subject '_SR2.*']); runs=length(fdir); run=length(fdir)+1; handles.SR2vals.run=run; handles.SR2vals.total_correct=NaN; handles.SR2vals.file = [pwd '\data\' subject '\' subject '_SR2.' num2str(run)]; handles.SR2vals.condition=handles.condition; handles.SR2vals.SRT.LE=str2double(get(handles.ed_LE_SRT,'String')); handles.SR2vals.SRT.RE=str2double(get(handles.ed_RE_SRT,'String')); handles.SR2vals.RMS=.123; handles.SR2vals.target_level=str2double(get(handles.ed_tlev,'String')); caldir=pwd; try load([caldir '\calfiles\SR_calvals.mat']) catch calvals.system=2; calvals.cal_level_left=99; calvals.cal_level_right=99; calvals.cal_atten=-20; calvals.system_name='Default'; calvals.date=NaN; end handles.SR2vals.calvals=calvals; handles.SR2vals.caltone_RMS=10^(calvals.cal_atten/20); CRMdir='C:\wavFiles\CRMwaves\Talker'; load Kemar_CIPIC handles.SR2vals.samplerate=44100; % Set the random number generator to a unique state rand('state',sum(100*clock)) randn('state',sum(100*clock)) f=CRM_resp_gui; set(f,'Position',[270 40 130 33]) set(f,'Name','Response') buttonhandles=guidata(f); set(f,'UserData',[]); set(buttonhandles.pb_start,'String','Start'); set(buttonhandles.pb_start,'Enable','on'); start=get(f,'UserData'); set(buttonhandles.tx_instructions,'String','Press Start to begin.') while isempty(start) pause(.1) start=get(f,'UserData'); end set(buttonhandles.pb_start,'String',''); target_level=handles.SR2vals.target_level*ones(1,20); SNR=[10 10 8 8 6 6 4 4 2 2 0 0 -2 -2 -4 -4 -6 -6 -8 -8]; masker_level=target_level-SNR; handles.SR2vals.masker_level=masker_level; handles.SR2vals.SNR=SNR; separation=handles.SR2vals.condition; guidata(handles.figure1, handles); running=get(handles.pb_go,'UserData'); trial=1; set(handles.axes1,'NextPlot','replace') while running set(handles.ed_mlev,'String',num2str(masker_level(trial))); twavs=[];m1wavs=[];m2wavs=[]; target=[];masker1=[]; masker2=[]; ta=[];m1=[];m2=[]; num=randperm(8)-1; col=randperm(4)-1;callsign=randperm(6); ttalker=randperm(3); target=[num2str(ttalker(1)) '\000' num2str(col(1)) '0' num2str(num(1)) '.wav']; masker1=[num2str(ttalker(2)) '\0' num2str(callsign(1)) '0' num2str(col(2)) '0' num2str(num(2)) '.wav']; masker2=[num2str(ttalker(3)) '\0' num2str(callsign(2)) '0' num2str(col(3)) '0' num2str(num(3)) '.wav']; ta=wavread([CRMdir target]); ta=ta.*(handles.SR2vals.RMS/std(ta)); m1=wavread([CRMdir masker1]); m1=m1.*(handles.SR2vals.RMS/std(m1)); m2=wavread([CRMdir masker2]); m2=m2.*(handles.SR2vals.RMS/std(m2)); % create a modulation / windowing function (an envelope) rampdur = 0.02; % 20 millisecond ramps rampsamps = ceil(rampdur.*handles.SR2vals.samplerate); ta_envelope = [cos(linspace(-pi/2,0,rampsamps)) ones(1,length(ta)-2*rampsamps) cos(linspace(0,pi/2,rampsamps))].^2; m1_envelope = [cos(linspace(-pi/2,0,rampsamps)) ones(1,length(m1)-2*rampsamps) cos(linspace(0,pi/2,rampsamps))].^2; m2_envelope = [cos(linspace(-pi/2,0,rampsamps)) ones(1,length(m2)-2*rampsamps) cos(linspace(0,pi/2,rampsamps))].^2; % Modulate each signal ta=ta.*ta_envelope'; m1=m1.*m1_envelope'; m2=m2.*m2_envelope'; handles.SR2vals.target_atten_LE=target_level(trial)-calvals.cal_level_left; handles.SR2vals.target_atten_RE=target_level(trial)-calvals.cal_level_right; handles.SR2vals.target_RMS.LE=handles.SR2vals.caltone_RMS*10^(handles.SR2vals.target_atten_LE/20); handles.SR2vals.target_RMS.RE=handles.SR2vals.caltone_RMS*10^(handles.SR2vals.target_atten_RE/20); handles.SR2vals.ampfactor.target.LE=handles.SR2vals.target_RMS.LE/handles.SR2vals.RMS; handles.SR2vals.ampfactor.target.RE=handles.SR2vals.target_RMS.RE/handles.SR2vals.RMS; handles.SR2vals.masker_atten_LE=masker_level(trial)-calvals.cal_level_left; handles.SR2vals.masker_atten_RE=masker_level(trial)-calvals.cal_level_right; handles.SR2vals.masker_RMS.LE=handles.SR2vals.caltone_RMS*10^(handles.SR2vals.masker_atten_LE/20); handles.SR2vals.masker_RMS.RE=handles.SR2vals.caltone_RMS*10^(handles.SR2vals.masker_atten_RE/20); handles.SR2vals.ampfactor.masker.LE=handles.SR2vals.masker_RMS.LE/handles.SR2vals.RMS; handles.SR2vals.ampfactor.masker.RE=handles.SR2vals.masker_RMS.RE/handles.SR2vals.RMS; tlen=length(ta); m1len=length(m1); m2len=length(m2); maxlen=max([tlen,m1len,m2len]); tbuff=maxlen-tlen; m1buff=maxlen-m1len; m2buff=maxlen-m2len; tzeros=zeros(tbuff,1); m1zeros=zeros(m1buff,1); m2zeros=zeros(m2buff,1); targ.LE=[ta; tzeros]*handles.SR2vals.ampfactor.target.LE; targ.RE=[ta; tzeros]*handles.SR2vals.ampfactor.target.LE; mask1.LE=[m1; m1zeros]*handles.SR2vals.ampfactor.masker.LE; mask1.RE=[m1; m1zeros]*handles.SR2vals.ampfactor.masker.RE; mask2.LE=[m2; m2zeros]*handles.SR2vals.ampfactor.masker.LE; mask2.RE=[m2; m2zeros]*handles.SR2vals.ampfactor.masker.RE; set(buttonhandles.tx_instructions,'String',['Trial ' num2str(trial)]) set(handles.ed_trial,'String',num2str(trial)) pause(.5) set(buttonhandles.tx_instructions,'String','') pause(.5) switch handles.SR2vals.condition case 0 tIR=IR_0; m1IR=IR_0; m2IR=IR_0; case 15 tIR=IR_0; m1IR=IR_n15; m2IR=IR_p15; case 30 tIR=IR_0; m1IR=IR_n30; m2IR=IR_p30; case 45 tIR=IR_0; m1IR=IR_n45; m2IR=IR_p45; end twavs(:,1) = conv(tIR(:,1),targ.LE); twavs(:,2) = conv(tIR(:,2),targ.RE); m1wavs(:,1) = conv(m1IR(:,1),mask1.LE); m1wavs(:,2) = conv(m1IR(:,2),mask1.RE); m2wavs(:,1) = conv(m2IR(:,1),mask2.LE); m2wavs(:,2) = conv(m2IR(:,2),mask2.RE); sig.left=twavs(:,1)+m1wavs(:,1)+m2wavs(:,1); sig.right=twavs(:,2)+m1wavs(:,2)+m2wavs(:,2); if calvals.system==1 pa_wavplay([sig.left sig.right],handles.SR2vals.samplerate); else sound([sig.left sig.right],handles.SR2vals.samplerate,16); pause(length(sig.left)/handles.SR2vals.samplerate); end for n=1:32 commandtext=['set(buttonhandles.pushbutton' num2str(n) ',''Enable'',''on'')']; eval(commandtext) end set(buttonhandles.tx_instructions,'String','What Color and Number?') set(f,'UserData',[]); mydata=get(f,'UserData'); while isempty(mydata) pause(.1) mydata=get(f,'UserData'); running=get(handles.pb_go,'UserData'); if ~running set(buttonhandles.tx_instructions,'String','Thank you. Please wait.') set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 0.5]) set(handles.pb_go,'Enable','on') set(handles.pb_stop,'Enable','off') guidata(handles.figure1, handles); return end end mydata.tlevel=target_level(trial); mydata.mlevel=masker_level(trial); mydata.SNR=SNR(trial); mydata.tcol=col(1); mydata.tnum=num(1); mydata.m1col=col(2); mydata.m1num=num(2); mydata.m2col=col(3); mydata.m2num=num(3); if mydata.color==col(1) mydata.colcorr=1; else mydata.colcorr=0; end if mydata.number==num(1) mydata.numcorr=1; else mydata.numcorr=0; end if mydata.numcorr+mydata.colcorr == 2 mydata.correct=1; set(buttonhandles.tx_instructions,'String','Correct') else mydata.correct=0; set(buttonhandles.tx_instructions,'String','Incorrect.') end data{trial}=mydata; summary(trial)=data{trial}.correct; set(handles.ed_total,'String',num2str(sum(summary))) plot(handles.axes1,handles.SR2vals.SNR(1:2:trial)+.15,summary(1:2:trial),'ko') set(handles.axes1,'NextPlot','add') plot(handles.axes1,handles.SR2vals.SNR(2:2:trial)-.15,summary(2:2:trial),'k^') xlabel(handles.axes1,'SNR (dB)') %ylabel(handles.axes1,'Correct = 1; Incorrect = 0') set(handles.axes1,'YTick',[0 1]) set(handles.axes1,'XTick',-10:2:12) set(handles.axes1,'YTickLabel',{'Incorrect','Correct'}) axis(handles.axes1,[-9 11 -.1 1.1]) pause(.5) trial=trial+1; if trial>20 set(handles.pb_go,'UserData',0) handles.SR2vals.total_correct=sum(summary); handles.SR2vals.data=data; handles.SR2vals.summary=summary; SR2vals=handles.SR2vals; save(handles.SR2vals.file,'SR2vals') switch SR2vals.condition case 0 set(handles.ed_colocated,'String',num2str(SR2vals.total_correct)) case 15 set(handles.ed_15degrees,'String',num2str(SR2vals.total_correct)) case 30 set(handles.ed_30degrees,'String',num2str(SR2vals.total_correct)) case 45 set(handles.ed_45degrees,'String',num2str(SR2vals.total_correct)) end if ~exist('SR2summary.csv','file') fid=fopen('SR2summary.csv','w'); fprintf(fid,'%s','Subject'); fprintf(fid,', %s','Date'); fprintf(fid,', %s','Spatial'); fprintf(fid,', %s','Total Correct'); fprintf(fid,', %s',num2str(SR2vals.SNR)); fclose(fid); end fid=fopen('SR2summary.csv','a'); fprintf(fid,'\n'); fprintf(fid,'%s',SR2vals.subject); fprintf(fid,', %s',date); fprintf(fid,', %s',num2str(SR2vals.condition)); fprintf(fid,', %s',num2str(SR2vals.total_correct)); fprintf(fid,', %s',num2str(SR2vals.summary)); fclose(fid); end running=get(handles.pb_go,'UserData'); end set(buttonhandles.tx_instructions,'String','Thank you. Please wait.') set(handles.pb_go,'String','Saving') set(handles.pb_go,'Enable','off') fid=fopen([pwd '\data\' subject '\' subject '_SR2_summary.csv'],'w'); fdir = dir([homedir '\data\' subject '\' subject '_SR2.*']); fprintf(fid,'%s','Subject'); fprintf(fid,', %s','Condition'); fprintf(fid,', %s','Total Correct'); fprintf(fid,', %s',num2str(SR2vals.SNR)); runs=length(fdir); if runs for n=1:runs try load([homedir '\data\' subject '\' subject '_SR2.' num2str(n)],'-mat') fprintf(fid,'\n'); fprintf(fid,'%s',SR2vals.subject); fprintf(fid,', %s',num2str(SR2vals.condition)); fprintf(fid,', %s',num2str(SR2vals.total_correct)); fprintf(fid,', %s',num2str(SR2vals.summary)); end end end fclose(fid); set(handles.pb_go,'String','Export Data') set(handles.pb_go,'Enable','on') set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 0.5]) set(handles.pb_go,'Enable','on') set(handles.pb_stop,'Enable','off') set(handles.pb_go,'UserData',0) guidata(handles.figure1, handles); function ed_subjnum_Callback(hObject, eventdata, handles) % hObject handle to ed_subjnum (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_subjnum as text % str2double(get(hObject,'String')) returns contents of ed_subjnum as a double % --- Executes during object creation, after setting all properties. function ed_subjnum_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_subjnum (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pb_stop. function pb_stop_Callback(hObject, eventdata, handles) % hObject handle to pb_stop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 0.5]) set(handles.pb_go,'Enable','on') set(handles.pb_stop,'Enable','off') set(handles.pb_go,'UserData',0) % --- Executes on button press in pb_done. function pb_done_Callback(hObject, eventdata, handles) % hObject handle to pb_done (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) f=CRM_resp_gui; close(f); close(handles.figure1); % --- Executes on button press in rb_0. function rb_0_Callback(hObject, eventdata, handles) % hObject handle to rb_0 (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 rb_0 set(handles.rb_15,'Value',0) set(handles.rb_30,'Value',0) set(handles.rb_45,'Value',0) handles.condition=0; guidata(hObject, handles); set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 .5]) set(handles.pb_go,'Enable','on') % --- Executes on button press in rb_15. function rb_15_Callback(hObject, eventdata, handles) % hObject handle to rb_15 (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 rb_15 set(handles.rb_0,'Value',0) set(handles.rb_30,'Value',0) set(handles.rb_45,'Value',0) handles.condition=15; guidata(hObject, handles); set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 .5]) set(handles.pb_go,'Enable','on') % --- Executes on button press in rb_30. function rb_30_Callback(hObject, eventdata, handles) % hObject handle to rb_30 (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 rb_30 set(handles.rb_0,'Value',0) set(handles.rb_15,'Value',0) set(handles.rb_45,'Value',0) handles.condition=30; guidata(hObject, handles); set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 .5]) set(handles.pb_go,'Enable','on') % --- Executes on button press in rb_45. function rb_45_Callback(hObject, eventdata, handles) % hObject handle to rb_45 (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 rb_45 set(handles.rb_0,'Value',0) set(handles.rb_15,'Value',0) set(handles.rb_30,'Value',0) handles.condition=45; guidata(hObject, handles); set(handles.pb_go,'String','Go') set(handles.pb_go,'BackgroundColor',[0 1 .5]) set(handles.pb_go,'Enable','on') function ed_mlev_Callback(hObject, eventdata, handles) % hObject handle to ed_mlev (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_mlev as text % str2double(get(hObject,'String')) returns contents of ed_mlev as a double % --- Executes during object creation, after setting all properties. function ed_mlev_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_mlev (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_tlev_Callback(hObject, eventdata, handles) % hObject handle to ed_tlev (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_tlev as text % str2double(get(hObject,'String')) returns contents of ed_tlev as a double % --- Executes during object creation, after setting all properties. function ed_tlev_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_tlev (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_trial_Callback(hObject, eventdata, handles) % hObject handle to ed_trial (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_trial as text % str2double(get(hObject,'String')) returns contents of ed_trial as a double % --- Executes during object creation, after setting all properties. function ed_trial_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_trial (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_correct_Callback(hObject, eventdata, handles) % hObject handle to ed_correct (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_correct as text % str2double(get(hObject,'String')) returns contents of ed_correct as a double % --- Executes during object creation, after setting all properties. function ed_correct_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_correct (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_total_Callback(hObject, eventdata, handles) % hObject handle to ed_total (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_total as text % str2double(get(hObject,'String')) returns contents of ed_total as a double % --- Executes during object creation, after setting all properties. function ed_total_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_total (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_RE_SRT_Callback(hObject, eventdata, handles) % hObject handle to ed_RE_SRT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_RE_SRT as text % str2double(get(hObject,'String')) returns contents of ed_RE_SRT as a double % --- Executes during object creation, after setting all properties. function ed_RE_SRT_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_RE_SRT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_LE_SRT_Callback(hObject, eventdata, handles) % hObject handle to ed_LE_SRT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_LE_SRT as text % str2double(get(hObject,'String')) returns contents of ed_LE_SRT as a double % --- Executes during object creation, after setting all properties. function ed_LE_SRT_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_LE_SRT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit10_Callback(hObject, eventdata, handles) % hObject handle to edit10 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit10 as text % str2double(get(hObject,'String')) returns contents of edit10 as a double % --- Executes during object creation, after setting all properties. function edit10_CreateFcn(hObject, eventdata, handles) % hObject handle to edit10 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit11_Callback(hObject, eventdata, handles) % hObject handle to edit11 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit11 as text % str2double(get(hObject,'String')) returns contents of edit11 as a double % --- Executes during object creation, after setting all properties. function edit11_CreateFcn(hObject, eventdata, handles) % hObject handle to edit11 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_cal_date_Callback(hObject, eventdata, handles) % hObject handle to ed_cal_date (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_cal_date as text % str2double(get(hObject,'String')) returns contents of ed_cal_date as a double % --- Executes during object creation, after setting all properties. function ed_cal_date_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_cal_date (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pb_cal. function pb_cal_Callback(hObject, eventdata, handles) % hObject handle to pb_cal (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(hObject,'Enable','off') calvals = go_calibrate(handles); set(handles.ed_cal_date,'String',calvals.date) set(hObject,'Enable','on') function calvals = go_calibrate(handles) % play three-second long tone and save the RMS values caldir=pwd; calfile=[caldir '\calfiles\SR_calvals.mat']; if ~exist([caldir '\calfiles'],'dir') eval(['mkdir ' caldir '\calfiles']) end if exist(calfile,'file') load([caldir '\calfiles\SR_calvals.mat']) calvals.previous_cal_level_left=calvals.cal_level_left; calvals.previous_cal_level_right=calvals.cal_level_left; % Construct a questdlg with three options ovrwrt = questdlg('Calibration file exists. Overwrite?','Calibration File Exists','Yes','No','No'); if strcmp(ovrwrt,'No') load([caldir '\calfiles\SR_calvals.mat']) return end D=dir([caldir '\calfiles\SR_calvals_old*']); numfiles=size(D,1); fname2 = [caldir '\calfiles\SR_calvals_old_' num2str(numfiles+1) '.mat']; copyfile(calfile,fname2); else calvals.previous_cal_level_left=0; calvals.previous_cal_level_right=0; end calvals.date=date; calvals.directory=pwd; calvals.cal_freq=1000; calvals.cal_level_left=-99; calvals.cal_level_right=-99; calvals.cal_atten=-20; tone=makeCalTone(calvals.cal_freq, 44100, 3, calvals.cal_atten, 0,.005); silence=zeros(size(tone.wave)); isasio=questdlg('Does sound generation system use ASIO Drivers?','Sound System','Yes','No','Unsure','Yes'); if strcmp(isasio,'Yes') sname=inputdlg('Enter System name:','Name System',1,{'ASIO Soundcard'}); calvals.system_name=sname{1}; calvals.system=1; calvals.driver='asio'; elseif strcmp(isasio,'No') sname=inputdlg('Enter System name:','Name System',1,{'Windows Soundcard'}); calvals.system=2; calvals.system_name=sname{1}; calvals.driver='win'; elseif strcmp(isasio,'Unsure') checkasio=questdlg('Check to see if sound generation system supports greater ASIO Drivers?','Sound System','Yes','No','Yes'); if strcmp(checkasio,'Yes') h=warndlg('Click Ok and then listen for a 1000 Hz tone.','Tone Will Play'); uiwait(h) pause(.1) pa_wavplay([tone.wave' tone.wave'],tone.sampling_rate,'asio'); useasio=questdlg('Was a sound presented?','Sound System','Yes','No','Yes'); if strcmp(useasio,'Yes') sname=inputdlg('Enter System name:','Name System',1,{'ASIO Soundcard'}); calvals.system_name=sname{1}; calvals.system=1; calvals.driver='asio'; elseif strcmp(useasio,'No') sname=inputdlg('Enter System name:','Name System',1,{'Windows Soundcard'}); calvals.system=2; calvals.system_name=sname{1}; calvals.driver='win'; end else warndlg('System will use Windows drivers. Redo calibration to reset.') sname=inputdlg('Enter System name:','Name System',1,{'Windows Soundcard'}); calvals.system=2; calvals.system_name=sname{1}; calvals.driver='win'; end end for side=1:2 if side==1 while calvals.cal_level_left==-99 % set(handles.tx_comment,'String',['Now playing ' num2str(calvals.cal_freq) ' Hz tone on left channel at 44100 Hz.']) pause(.5) tone=makeCalTone(calvals.cal_freq, 44100, 3, calvals.cal_atten, 0,.005); silence=zeros(size(tone.wave)); if calvals.system==1 pa_wavplay([tone.wave' silence'],tone.sampling_rate); else sound([tone.wave' silence'],tone.sampling_rate,16); end % set(handles.tx_comment,'String','') level=[]; qstring=['Enter dB SPL reading for LEFT CHANNEL (enter -99 to play again) Previous level was ' num2str(calvals.previous_cal_level_left) ': ']; level = inputdlg(qstring,'Calibration Level (dB)',1,{'-99'}); try calvals.cal_level_left =str2num(level{1}); catch calvals.cal_level_left = -99; end end else while calvals.cal_level_right==-99 % set(handles.tx_comment,'String',['Now playing ' num2str(calvals.cal_freq) ' Hz tone on right channel at 44100 Hz.']) pause(.5) tone=makeCalTone(calvals.cal_freq, 44100, 3, calvals.cal_atten, 0,.005); silence=zeros(size(tone.wave)); if calvals.system==1 pa_wavplay([silence' tone.wave'],tone.sampling_rate); else sound([silence' tone.wave'],tone.sampling_rate,16); end % set(handles.tx_comment,'String','') level=[]; qstring=['Enter dB SPL reading for RIGHT CHANNEL (enter -99 to play again) Previous level was ' num2str(calvals.previous_cal_level_right) ': ']; level = inputdlg(qstring,'Calibration Level (dB)',1,{'-99'}); try calvals.cal_level_right =str2num(level{1}); catch calvals.cal_level_right =-99; end end end end save([caldir '\calfiles\SR_calvals.mat'],'calvals') function s=makeCalTone(frequency, sampling_rate, duration, amplitude, phase, onoff_ramp) % s=makeCalTone(frequency, sampling_rate, duration, amplitude, phase) % frequency: in Hz (e.g., 1000); a vector creates a tone complex % sampling_rate: in Hz (e.g., 48000) % duration: in seconds (e.g., 1) % amplitude: in decibels re: maximum (e.g., -30) % phase: in radians, between 0 and 2*pi (e.g., pi) % onofframp: in seconds (e.g., .01) s.frequency=frequency; s.sampling_rate=sampling_rate; s.duration=duration; s.amplitude=amplitude; s.phase=phase; %determine the signal length in samples and create a vector (x) of the right length to hold it x=1:ceil(duration.*sampling_rate); final_tone=zeros(1,length(x)); for n=1:length(frequency) %generate a sine wave tone=sin((2*pi*(frequency(n)/sampling_rate).*x)+phase); % create a windowing function (an envelope) rampdur = onoff_ramp; rampsamps = ceil(rampdur.*sampling_rate); envelope = [cos(linspace(-pi/2,0,rampsamps)) ones(1,ceil(duration.*sampling_rate)-2*rampsamps) cos(linspace(0,pi/2,rampsamps))].^2; tone=tone.*envelope; final_tone=final_tone+tone; end %set the RMS level of the signal to the specified amplitude in dB toneRMS=sqrt(mean(final_tone.^2)); amp=10^(amplitude/20); ampdiff=amp/toneRMS; s.wave=final_tone.*ampdiff; function ed_15degrees_Callback(hObject, eventdata, handles) % hObject handle to ed_15degrees (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_15degrees as text % str2double(get(hObject,'String')) returns contents of ed_15degrees as a double % --- Executes during object creation, after setting all properties. function ed_15degrees_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_15degrees (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_30degrees_Callback(hObject, eventdata, handles) % hObject handle to ed_30degrees (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_30degrees as text % str2double(get(hObject,'String')) returns contents of ed_30degrees as a double % --- Executes during object creation, after setting all properties. function ed_30degrees_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_30degrees (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_45degrees_Callback(hObject, eventdata, handles) % hObject handle to ed_45degrees (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_45degrees as text % str2double(get(hObject,'String')) returns contents of ed_45degrees as a double % --- Executes during object creation, after setting all properties. function ed_45degrees_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_45degrees (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ed_colocated_Callback(hObject, eventdata, handles) % hObject handle to ed_colocated (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ed_colocated as text % str2double(get(hObject,'String')) returns contents of ed_colocated as a double % --- Executes during object creation, after setting all properties. function ed_colocated_CreateFcn(hObject, eventdata, handles) % hObject handle to ed_colocated (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end
github
rfsantacruz/deep-perm-net-master
voc_eval.m
.m
deep-perm-net-master/lib/datasets/VOCdevkit-matlab-wrapper/voc_eval.m
1,467
utf_8
a251b8cc6ec333e2df948dfdd2f90a17
function res = voc_eval(path, comp_id, test_set, output_dir, rm_res) VOCopts = get_voc_opts(path); VOCopts.testset = test_set; VOCopts.detrespath=[VOCopts.resdir 'Main/%s_det_' VOCopts.testset '_%s.txt']; for i = 1:length(VOCopts.classes) cls = VOCopts.classes{i}; res(i) = voc_eval_cls(cls, VOCopts, comp_id, output_dir, rm_res); 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, rm_res) 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'); if rm_res delete(res_fn); end rmpath(fullfile(VOCopts.datadir, 'VOCcode'));
github
rfsantacruz/deep-perm-net-master
classification_demo.m
.m
deep-perm-net-master/caffe-perm/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
Liel-Research-Group/Internal_Codes-master
BSSA_14.m
.m
Internal_Codes-master/ZR19 GMPE/BSSA_14.m
4,633
utf_8
c248b3af769f194dc5fdb150bf45392a
%Eric Johnson %Liel Research Group %NGA-West2 Equations for Predicting PGA, PGV, and 5% Damped PSA for Shallow Crustal Earthquakes %David M. Boore, Jonathan P. Stewart, Emel Seyhan, and Gail M. Atkinson % %This GMPE is dependent on the following files: % BSSA_14.mat % %Inputs required are: % siteprop.Rjb, siteprop.VS30, siteprop.T, faultprop.M, and faultprop.d function [Sa,SD] = BSSA_14(siteprop,faultprop) T = siteprop.T; coeff = load('BSSA_14.mat'); T_vec = coeff.T_vec; if isempty(find(abs(T_vec-T)<0.0001)) == 0 [Sa,SD] = BSSA_14_sub1(T,siteprop,faultprop); else T_low = T_vec(max(find(T_vec<T))); T_high = T_vec(min(find(T_vec>T))); [Sa_low, SD_low] = BSSA_14_sub1( T_low,siteprop,faultprop ); [Sa_high, SD_high] = BSSA_14_sub1( T_high,siteprop,faultprop ); totalSD_low = SD_low(1); totalSD_high = SD_high(1); interSD_low = SD_low(2); interSD_high = SD_high(2); intraSD_low = SD_low(3); intraSD_high = SD_high(3); T_bounds = [log(T_low) log(T_high)]; Sa_bounds = [log(Sa_low) log(Sa_high)]; intraSD_bounds = [intraSD_low intraSD_high]; interSD_bounds = [interSD_low interSD_high]; totalSD_bounds = [totalSD_low totalSD_high]; Sa = exp(interp1(T_bounds,Sa_bounds,log(T))); intraSD = interp1(T_bounds,intraSD_bounds,log(T)); interSD = interp1(T_bounds,interSD_bounds,log(T)); totalSD = interp1(T_bounds,totalSD_bounds,log(T)); SD = [totalSD;interSD;intraSD]; end end function [Sa,SD] = BSSA_14_sub1(T,siteprop,faultprop) Rjb = siteprop.Rjb; VS30 = siteprop.VS30; M = faultprop.M; d = faultprop.d; coeff = load('BSSA_14.mat'); T_vec_sub = coeff.T_vec; c = interp1(T_vec_sub,coeff.c_vec,T); c1 = interp1(T_vec_sub,coeff.c1_vec,T); c2 = interp1(T_vec_sub,coeff.c2_vec,T); c3 = interp1(T_vec_sub,coeff.c3_vec,T); Dc3 = interp1(T_vec_sub,coeff.Dc3_vec,T); DfR = interp1(T_vec_sub,coeff.DfR_vec,T); DfV = interp1(T_vec_sub,coeff.DfV_vec,T); e0 = interp1(T_vec_sub,coeff.e0_vec,T); e1 = interp1(T_vec_sub,coeff.e1_vec,T); e2 = interp1(T_vec_sub,coeff.e2_vec,T); e3 = interp1(T_vec_sub,coeff.e3_vec,T); e4 = interp1(T_vec_sub,coeff.e4_vec,T); e5 = interp1(T_vec_sub,coeff.e5_vec,T); e6 = interp1(T_vec_sub,coeff.e6_vec,T); f1 = interp1(T_vec_sub,coeff.f1_vec,T); f3 = interp1(T_vec_sub,coeff.f3_vec,T); f4 = interp1(T_vec_sub,coeff.f4_vec,T); f5 = interp1(T_vec_sub,coeff.f5_vec,T); f6 = interp1(T_vec_sub,coeff.f6_vec,T); f7 = interp1(T_vec_sub,coeff.f7_vec,T); h = interp1(T_vec_sub,coeff.h_vec,T); Mh = interp1(T_vec_sub,coeff.Mh_vec,T); Mref = interp1(T_vec_sub,coeff.Mref_vec,T); phi1 = interp1(T_vec_sub,coeff.phi1_vec,T); phi2 = interp1(T_vec_sub,coeff.phi2_vec,T); R1 = interp1(T_vec_sub,coeff.R1_vec,T); R2 = interp1(T_vec_sub,coeff.R2_vec,T); Rref = interp1(T_vec_sub,coeff.Rref_vec,T); tau1 = interp1(T_vec_sub,coeff.tau1_vec,T); tau2 = interp1(T_vec_sub,coeff.tau2_vec,T); V1 = interp1(T_vec_sub,coeff.V1_vec,T); V2 = interp1(T_vec_sub,coeff.V2_vec,T); Vc = interp1(T_vec_sub,coeff.Vc_vec,T); Vref = interp1(T_vec_sub,coeff.Vref_vec,T); %Source Function if M <= Mh FE = e0 + e4*(M - Mh) + e5*(M - Mh)^2; else FE = e0 + e6*(M - Mh); end %Path Function R = sqrt(Rjb^2 + h^2); FP = (c1 + c2*(M - Mref)) * log(R/Rref) + (c3 + Dc3)*(R - Rref); %Site Function if VS30 <= Vc F_lin = c*log(VS30/Vref); else F_lin = c*log(Vc/Vref); end siteprop_r = siteprop; faultprop_r = faultprop; if T ~= 0 || VS30 ~= 760 siteprop_r.T = 0; siteprop_r.VS30 = 760; [PGAr,~] = BSSA_14_sub1(0,siteprop_r,faultprop_r); f2 = f4*(exp(f5*(min(VS30,760)-360)-360)-exp(f5*(760-360))); F_nl = f1 + f2*log((PGAr + f3)/f3); else F_nl = 0; end FS = F_lin + F_nl; %Aleatory Uncertainty if M <= 4.5 PhiM = phi1; elseif M > 4.5 && M < 5.5 PhiM = phi1 + (phi2 - phi1)*(M - 4.5); elseif M >= 5.5 PhiM = phi2; end if Rjb <= R1 Phi_MRjb = PhiM; elseif Rjb > R1 && Rjb <= R2 Phi_MRjb = PhiM + DfR*(log(Rjb/R1)/log(R2/R1)); elseif Rjb > R2 Phi_MRjb = PhiM + DfR; end if VS30 >= V2 phi = Phi_MRjb; elseif VS30 >= V1 && VS30 <=V2 phi = Phi_MRjb + DfV*(log(V2/VS30)/log(V2/V1)); elseif VS30 <= V1 phi = Phi_MRjb + DfV; end if M <= 4.5 tau = tau1; elseif M > 4.5 && M < 5.5 tau = tau1 + (tau2 - tau1)*(M - 4.5); elseif M >= 5.5 tau = tau2; end sigma = sqrt(phi^2 + tau^2); lnSa = FE + FP + FS; Sa = exp(lnSa); SD = [sigma;phi;tau]; end
github
Liel-Research-Group/Internal_Codes-master
HA_15.m
.m
Internal_Codes-master/ZR19 GMPE/HA_15.m
2,131
utf_8
44df058a83125eb61b8b4e1b7b01427b
%Eric Johnson %Liel Research Group %Referenced Empirical Ground-Motion Model for Eastern North America %Behzad Hassani and Gail M. Atkinson % %This GMPE is dependent on the following files: % HA_15.mat, BSSA_14.m, and BSSA_14.mat % %Inputs required are: % siteprop.Rjb, siteprop.VS30, siteprop.T, faultprop.M, and faultprop.d function [Sa,SD] = HA_15(siteprop,faultprop) T = siteprop.T; coeff = load('HA_15.mat'); T_vec = coeff.T_vec; if isempty(find(abs(T_vec-T)<0.0001)) == 0 [Sa,SD] = HA_15_sub1(T,siteprop,faultprop); else T_low = T_vec(max(find(T_vec<T))); T_high = T_vec(min(find(T_vec>T))); [Sa_low, SD_low] = HA_15_sub1( T_low,siteprop,faultprop ); [Sa_high, SD_high] = HA_15_sub1( T_high,siteprop,faultprop ); totalSD_low = SD_low(1); totalSD_high = SD_high(1); interSD_low = SD_low(2); interSD_high = SD_high(2); intraSD_low = SD_low(3); intraSD_high = SD_high(3); T_bounds = [log(T_low) log(T_high)]; Sa_bounds = [log(Sa_low) log(Sa_high)]; intraSD_bounds = [intraSD_low intraSD_high]; interSD_bounds = [interSD_low interSD_high]; totalSD_bounds = [totalSD_low totalSD_high]; Sa = exp(interp1(T_bounds,Sa_bounds,log(T))); intraSD = interp1(T_bounds,intraSD_bounds,log(T)); interSD = interp1(T_bounds,interSD_bounds,log(T)); totalSD = interp1(T_bounds,totalSD_bounds,log(T)); SD = [totalSD;interSD;intraSD]; end end function [Sa,SD] = HA_15_sub1(T,siteprop,faultprop) Rjb = siteprop.Rjb; VS30 = siteprop.VS30; coeff = load('HA_15.mat'); T_vec_sub = coeff.T_vec; Sa_bssa = BSSA_14(siteprop,faultprop); C1 = interp1(T_vec_sub,coeff.C1_vec,T); C2 = interp1(T_vec_sub,coeff.C2_vec,T); C3 = interp1(T_vec_sub,coeff.C3_vec,T); phi = interp1(T_vec_sub,coeff.phi_vec,T); sigma = interp1(T_vec_sub,coeff.sigma_vec,T); tau = interp1(T_vec_sub,coeff.tau_vec,T); logFENA = C1 + C2*Rjb + C3*max(0,log10(min(Rjb,150)/50)); FENA = 10^(logFENA); Sa = Sa_bssa*FENA; SD = [sigma;phi;tau]; end
github
Liel-Research-Group/Internal_Codes-master
ZR_19.m
.m
Internal_Codes-master/ZR19 GMPE/ZR_19.m
2,771
utf_8
932f24b35c9eec6d63dce3332eae0ae1
%Eric Johnson %Liel Research Group %Ground Motion Model for Small-to-Moderate Earthquakes in Texas, Oklahoma, and Kansas %Georgios Zalachoris and Ellen M. Rathje % %This GMPE is dependent on the following files: % ZR_19.mat, HA_15.m, HA_15.mat, BSSA_14.m, and BSSA_14.mat % %Inputs required are: % siteprop.Rjb, siteprop.VS30, siteprop.T, faultprop.M, and faultprop.d function [Sa,SD] = ZR_19(siteprop,faultprop) T = siteprop.T; coeff = load('ZR_19.mat'); T_vec = coeff.T_vec; if isempty(find(abs(T_vec-T)<=0.000001)) == 0 [Sa,SD] = ZR_19_sub1(T,siteprop,faultprop); else T_low = T_vec(max(find(T_vec<T))); T_high = T_vec(min(find(T_vec>T))); [Sa_low, SD_low] = ZR_19_sub1( T_low,siteprop,faultprop ); [Sa_high, SD_high] = ZR_19_sub1( T_high,siteprop,faultprop ); totalSD_low = SD_low(1); totalSD_high = SD_high(1); interSD_low = SD_low(2); interSD_high = SD_high(2); intraSD_low = SD_low(3); intraSD_high = SD_high(3); T_bounds = [log(T_low) log(T_high)]; Sa_bounds = [log(Sa_low) log(Sa_high)]; intraSD_bounds = [intraSD_low intraSD_high]; interSD_bounds = [interSD_low interSD_high]; totalSD_bounds = [totalSD_low totalSD_high]; Sa = exp(interp1(T_bounds,Sa_bounds,log(T))); intraSD = interp1(T_bounds,intraSD_bounds,log(T)); interSD = interp1(T_bounds,interSD_bounds,log(T)); totalSD = interp1(T_bounds,totalSD_bounds,log(T)); SD = [intraSD;interSD;totalSD]; end end function [Sa,SD] = ZR_19_sub1(T,siteprop,faultprop) M = faultprop.M; d = faultprop.d; Rjb = siteprop.Rjb; Rhyp = sqrt(Rjb^2 + d^2); VS30 = siteprop.VS30; coeff = load('ZR_19.mat'); T_vec_sub = coeff.T_vec; Sa_ha15 = HA_15(siteprop,faultprop); Alpha = interp1(T_vec_sub,coeff.Alpha_vec,T); Rb = interp1(T_vec_sub,coeff.Rb_vec,T); Mb = interp1(T_vec_sub,coeff.Mb_vec,T); b0 = interp1(T_vec_sub,coeff.b0_vec,T); b1 = interp1(T_vec_sub,coeff.b1_vec,T); c = interp1(T_vec_sub,coeff.c_vec,T); Vc = interp1(T_vec_sub,coeff.Vc_vec,T); Cadj = interp1(T_vec_sub,coeff.Cadj_vec,T); Tau = interp1(T_vec_sub,coeff.Tau_vec,T); Phi = interp1(T_vec_sub,coeff.Phi_vec,T); Sigma = interp1(T_vec_sub,coeff.Sigma_vec,T); %Magnitude Adjustment Factor if M >= 3.0 && M < Mb F_M = b0; elseif M >= Mb && M < 5.8 F_M = b0 + b1 * (M - Mb); else fprintf('This GMPE is only valid for 3.0 <= Mw <= 5.8') end %Near Source Attenuation Correction if Rhyp < 4 %km F_R = Alpha * log(4 / Rb); elseif Rhyp >= 4 && Rhyp < Rb F_R = Alpha * log(Rhyp / Rb); else F_R = 0; end %Site Amplification Correction if VS30 < Vc F_S = c * log(VS30 / Vc); else F_S = 0; end %Overall Adjustment Cadj = Cadj; lnF = Cadj + F_M + F_R + F_S; F = exp(lnF); Sa = Sa_ha15*F; SD = [Phi;Tau;Sigma]; end
github
halfways/caffe-master
classification_demo.m
.m
caffe-master/matlab/demo/classification_demo.m
5,466
utf_8
45745fb7cfe37ef723c307dfa06f1b97
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 the 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 % and what versions are installed. % % 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 code 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 your Matlab search PATH in order 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
lcnhappe/happe-master
wICA.m
.m
happe-master/scripts/wICA.m
4,565
utf_8
b83858321e2ca4c7c711b6e02dcd3af7
%function [wIC,A,W,IC] = wICA(data, type= 'fastica', plotting= 1, Fs= 250, L=5) function [wIC,A,W,IC] = wICA(EEG,varargin) %--------------- function [wIC,A,W] = wICA(data,varargin) ----------------- % % Performs ICA on data matrix (row vector) and subsequent wavelet % thresholding to remove low-amplitude activity from the computed ICs. % This is useful for extracting artifact-only ICs in EEG (for example), and % then subtracting the artifact-reconstruction from the original data. % % >>> INPUTS >>> % Required: % data = data matrix in row format % Optional: % type = "fastica" or "radical"...two different ICA algorithms based on % entropy. "fastica" (default) is parametric, "radical" is nonparametric. % mult = threshold multiplier...multiplies the computed threshold from % "ddencmp" by this number. Higher thresh multipliers = less % "background" (or low amp. signal) is kept in the wICs. % plotting = 1 or 0. If 1, plots wIC vs. non-wavelet thresholded ICs % Fs = sampling rate, (for plotting...default = 1); % L = level set for stationary wavelet transform. Higher levels give % better frequency resolution, but less temporal resolution. % Default = 5 % wavename = wavelet family to use. type "wavenames" to see a list of % possible wavelets. (default = "coif5"); % % <<< OUTPUTS <<< % wIC = wavelet-thresholded ICs % A = mixing matrix (inv(W)) (optional) % W = demixing matrix (inv(A)) (optional) % IC = non-wavelet ICs (optional) % % * you can reconstruct the artifact-only signals as: % artifacts = A*wIC; % - upon reconstruction, you can then subtract the artifacts from your % original data set to remove artifacts, for instance. % % Example: % n = rand(10,1000); % a = [zeros(1,400),[.5,.8,1,2,2.4,2.5,3.5,5,6.3,6,4,3.2,3,1.7,1,-.6,-2.2,-4,-3.6,-3,-1,0],zeros(1,578)]; % data = n + linspace(0,2,10)'*a; % [wIC,A] = wICA(data,[],5,1); % ahat = A*wIC; % nhat = data-ahat; % err = sum(sqrt((nhat-n).^2)); % By JMS, 11/10/2015 %--------------------------------------------------------------------------------------- % check inputs if nargin>1 && ~isempty(varargin{1}) type=varargin{1}; else type='runica';end if nargin>2 && ~isempty(varargin{2}) mult=varargin{2};else mult=1;end if nargin>3 && ~isempty(varargin{3}) plotting=varargin{3}; else plotting=0;end if nargin>4 && ~isempty(varargin{4}) Fs=varargin{4};else Fs=1;end if nargin>5 && ~isempty(varargin{5}) L=varargin{5}; else L=5;end if nargin>6 && ~isempty(varargin{6}) wavename=varargin{6}; else wavename='coif5';end % run ICA using "runica" or "radical" if strcmp(type,'runica') [OUTEEG, com] = pop_runica(EEG, 'extended',1,'interupt','on'); %runica for parametric, default extended for finding subgaussian distributions W = OUTEEG.icaweights*OUTEEG.icasphere; A = inv(W); IC=reshape(OUTEEG.icaact, size(OUTEEG.icaact,1), []); %com = pop_export(OUTEEG,'ICactivationmatrix','ica','on','elec','off','time','off','precision',4); %IC = ICactivationmatrix; elseif strcmp(type,'radical') [IC,W] = radical(data); % radical ICA for non-parametric A = inv(W); end % padding data for proper wavelet transform...data must be divisible by % 2^L, where L = level set for the stationary wavelet transform modulus = mod(size(IC,2),2^L); %2^level (level for wavelet) if modulus ~=0 extra = zeros(1,(2^L)-modulus); else extra = []; end % loop through ICs and perform wavelet thresholding disp('Performing wavelet thresholding'); for s = 1:size(IC,1) if ~isempty(extra) sig = [IC(s,:),extra]; % pad with zeros else sig = IC(s,:); end [thresh,sorh,~] = ddencmp('den','wv',sig); % get automatic threshold value thresh = thresh*mult; % multiply threshold by scalar swc = swt(sig,L,wavename); % use stationary wavelet transform (SWT) to wavelet transform the ICs Y = wthresh(swc,sorh,thresh); % threshold the wavelet to remove small values wIC(s,:) = iswt(Y,wavename); % perform inverse wavelet transform to reconstruct a wavelet IC (wIC) clear y sig thresh sorh swc end % remove extra padding if ~isempty(extra) wIC = wIC(:,1:end-numel(extra)); end % plot the ICs vs. wICs if plotting>0 disp('Plotting'); subplot(3,1,1); multisignalplot(IC,Fs,'r'); title('ICs'); subplot(3,1,2); multisignalplot(wIC,Fs,'r'); title('wICs') subplot(3,1,3); multisignalplot(IC-wIC,Fs,'r'); title('Difference (IC - wIC)'); end end
github
lcnhappe/happe-master
h_epoch_interp_spl.m
.m
happe-master/scripts/h_epoch_interp_spl.m
5,579
utf_8
b3f72af0ca562a5a7d2b9cd9eca573ff
% Edit to the EEGLAB interpolation function to interpolate different % channels within each epoch % Cleaned up and removed irrelevant sections. % % Additions Copyright (C) 2010 Hugh Nolan, Robert Whelan and Richard Reilly, Trinity College Dublin, % Ireland % % Based on: % % eeg_interp() - interpolate data channels % % Usage: EEGOUT = eeg_interp(EEG, badchans, method); % % Inputs: % EEG - EEGLAB dataset % badchans - [integer array] indices of channels to interpolate. % For instance, these channels might be bad. % [chanlocs structure] channel location structure containing % either locations of channels to interpolate or a full % channel structure (missing channels in the current % dataset are interpolated). % method - [string] method used for interpolation (default is 'spherical'). % 'invdist' uses inverse distance on the scalp % 'spherical' uses superfast spherical interpolation. % 'spacetime' uses griddata3 to interpolate both in space % and time (very slow and cannot be interupted). % Output: % EEGOUT - data set with bad electrode data replaced by % interpolated data % % Author: Arnaud Delorme, CERCO, CNRS, Mai 2006- % Copyright (C) Arnaud Delorme, CERCO, 2006, [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_interp.m,v $ % Revision 1.7 2009/08/05 03:20:42 arno % new interpolation function % % Revision 1.6 2009/07/30 03:32:47 arno % fixed interpolating bad channels % % Revision 1.5 2009/07/02 19:30:33 arno % fix problem with empty channel % % Revision 1.4 2009/07/02 18:23:33 arno % fixing interpolation % % Revision 1.3 2009/04/21 21:48:53 arno % make default spherical in eeg_interp % % Revision 1.2 2008/04/16 17:34:45 arno % added spherical and 3-D interpolation % % Revision 1.1 2006/09/12 18:46:30 arno % Initial revision % function EEG = h_epoch_interp_spl(EEG, bad_elec_epochs, ignore_chans) warning off; if nargin < 2 help eeg_interp; return; end; if isempty(bad_elec_epochs) || ~iscell(bad_elec_epochs) fprintf('Incorrect input format.\n'); return; end if ~exist('ignore_chans','var') ignore_chans=[]; end for v=1:length(bad_elec_epochs) if ~isempty(bad_elec_epochs{v}) badchans = bad_elec_epochs{v}; goodchans = setdiff(1:size(EEG.data,1), badchans); goodchans = setdiff(goodchans, ignore_chans); % find non-empty good channels % ---------------------------- nonemptychans = find(~cellfun('isempty', { EEG.chanlocs.theta })); goodchans = intersect(goodchans,nonemptychans); badchans = intersect(badchans, nonemptychans); % scan data points % ---------------- % get theta, rad of electrodes % ---------------------------- xelec = [ EEG.chanlocs(goodchans).X ]; yelec = [ EEG.chanlocs(goodchans).Y ]; zelec = [ EEG.chanlocs(goodchans).Z ]; rad = sqrt(xelec.^2+yelec.^2+zelec.^2); xelec = xelec./rad; yelec = yelec./rad; zelec = zelec./rad; xbad = [ EEG.chanlocs(badchans).X ]; ybad = [ EEG.chanlocs(badchans).Y ]; zbad = [ EEG.chanlocs(badchans).Z ]; rad = sqrt(xbad.^2+ybad.^2+zbad.^2); xbad = xbad./rad; ybad = ybad./rad; zbad = zbad./rad; EEG.data(badchans,:,v) = spheric_spline( xelec, yelec, zelec, xbad, ybad, zbad, EEG.data(goodchans,:,v)); end end EEG = eeg_checkset(EEG); warning on; function allres = spheric_spline( xelec, yelec, zelec, xbad, ybad, zbad, values) newchans = length(xbad); numpoints = size(values,2); Gelec = computeg(xelec,yelec,zelec,xelec,yelec,zelec); Gsph = computeg(xbad,ybad,zbad,xelec,yelec,zelec); % compute solution for parameters C % --------------------------------- meanvalues = mean(values); values = values - repmat(meanvalues, [size(values,1) 1]); % make mean zero values = [values;zeros(1,numpoints)]; C = pinv([Gelec;ones(1,length(Gelec))]) * values; clear values; allres = zeros(newchans, numpoints); % apply results % ------------- for j = 1:size(Gsph,1) allres(j,:) = sum(C .* repmat(Gsph(j,:)', [1 size(C,2)])); end allres = allres + repmat(meanvalues, [size(allres,1) 1]); % compute G function % ------------------ function g = computeg(x,y,z,xelec,yelec,zelec) unitmat = ones(length(x(:)),length(xelec)); EI = unitmat - sqrt((repmat(x(:),1,length(xelec)) - repmat(xelec,length(x(:)),1)).^2 +... (repmat(y(:),1,length(xelec)) - repmat(yelec,length(x(:)),1)).^2 +... (repmat(z(:),1,length(xelec)) - repmat(zelec,length(x(:)),1)).^2); g = zeros(length(x(:)),length(xelec)); %dsafds m = 4; % 3 is linear, 4 is best according to Perrin's curve for n = 1:7 L = legendre(n,EI); g = g + ((2*n+1)/(n^m*(n+1)^m))*squeeze(L(1,:,:)); end g = g/(4*pi);
github
lcnhappe/happe-master
eeglab.m
.m
happe-master/Packages/eeglab14_0_0b/eeglab.m
112,891
utf_8
fffefc22649f15632d7eca04b8c03088
% eeglab() - Matlab graphic user interface environment for % electrophysiological data analysis incorporating the ICA/EEG toolbox % (Makeig et al.) developed at CNL / The Salk Institute, 1997-2001. % Released 11/2002- as EEGLAB (Delorme, Makeig, et al.) at the Swartz Center % for Computational Neuroscience, Institute for Neural Computation, % University of California San Diego (http://sccn.ucsd.edu/). % User feedback welcome: email [email protected] % % Authors: Arnaud Delorme and Scott Makeig, with substantial contributions % from Colin Humphries, Sigurd Enghoff, Tzyy-Ping Jung, plus % contributions % from Tony Bell, Te-Won Lee, Luca Finelli and many other contributors. % % Description: % EEGLAB is Matlab-based software for processing continuous or event-related % EEG or other physiological data. It is designed for use by both novice and % expert Matlab users. In normal use, the EEGLAB graphic interface calls % graphic functions via pop-up function windows. The EEGLAB history mechanism % can save the resulting Matlab calls to disk for later incorporation into % Matlab scripts. A single data structure ('EEG') containing all dataset % parameters may be accessed and modified directly from the Matlab commandline. % EEGLAB now recognizes "plugins," sets of EEGLAB functions linked to the EEGLAB % main menu through an "eegplugin_[name].m" function (Ex. >> help eeplugin_besa.m). % % Usage: 1) To (re)start EEGLAB, type % >> eeglab % Ignores any loaded datasets % 2) To redaw and update the EEGLAB interface, type % >> eeglab redraw % Scans for non-empty datasets % >> eeglab rebuild % Closes and rebuilds the EEGLAB window % >> eeglab versions % State EEGLAB version number % % >> type "license.txt" % the GNU public license % >> web http://sccn.ucsd.edu/eeglab/tutorial/ % the EEGLAB tutorial % >> help eeg_checkset % the EEG dataset structure % % GUI Functions calling eponymous processing and plotting functions: % ------------------------------------------------------------------ % <a href="matlab:helpwin pop_eegfilt">pop_eegfilt</a> - bandpass filter data (eegfilt()) % <a href="matlab:helpwin pop_eegplot">pop_eegplot</a> - scrolling multichannel data viewer (eegplot()) % <a href="matlab:helpwin pop_eegthresh">pop_eegthresh</a> - simple thresholding method (eegthresh()) % <a href="matlab:helpwin pop_envtopo">pop_envtopo</a> - plot ERP data and component contributions (envtopo()) % <a href="matlab:helpwin pop_epoch">pop_epoch</a> - extract epochs from a continuous dataset (epoch()) % <a href="matlab:helpwin pop_erpimage">pop_erpimage</a> - plot single epochs as an image (erpimage()) % <a href="matlab:helpwin pop_jointprob">pop_jointprob</a> - reject epochs using joint probability (jointprob()) % <a href="matlab:helpwin pop_loaddat">pop_loaddat</a> - load Neuroscan .DAT info file (loaddat()) % <a href="matlab:helpwin pop_loadcnt">pop_loadcnt</a> - load Neuroscan .CNT data (lndcnt()) % <a href="matlab:helpwin pop_loadeeg">pop_loadeeg</a> - load Neuroscan .EEG data (loadeeg()) % <a href="matlab:helpwin pop_loadbva">pop_loadbva</a> - load Brain Vision Analyser matlab files % <a href="matlab:helpwin pop_plotdata">pop_plotdata</a> - plot data epochs in rectangular array (plotdata()) % <a href="matlab:helpwin pop_readegi">pop_readegi</a> - load binary EGI data file (readegi()) % <a href="matlab:helpwin pop_rejkurt">pop_rejkurt</a> - compute data kurtosis (rejkurt()) % <a href="matlab:helpwin pop_rejtrend">pop_rejtrend</a> - reject EEG epochs showing linear trends (rejtrend()) % <a href="matlab:helpwin pop_resample">pop_resample</a> - change data sampling rate (resample()) % <a href="matlab:helpwin pop_rmbase">pop_rmbase</a> - remove epoch baseline (rmbase()) % <a href="matlab:helpwin pop_runica">pop_runica</a> - run infomax ICA decomposition (runica()) % <a href="matlab:helpwin pop_newtimef">pop_newtimef</a> - event-related time-frequency (newtimef()) % <a href="matlab:helpwin pop_timtopo">pop_timtopo</a> - plot ERP and scalp maps (timtopo()) % <a href="matlab:helpwin pop_topoplot">pop_topoplot</a> - plot scalp maps (topoplot()) % <a href="matlab:helpwin pop_snapread">pop_snapread</a> - read Snapmaster .SMA files (snapread()) % <a href="matlab:helpwin pop_newcrossf">pop_newcrossf</a> - event-related cross-coherence (newcrossf()) % <a href="matlab:helpwin pop_spectopo">pop_spectopo</a> - plot all channel spectra and scalp maps (spectopo()) % <a href="matlab:helpwin pop_plottopo">pop_plottopo</a> - plot a data epoch in a topographic array (plottopo()) % <a href="matlab:helpwin pop_readedf">pop_readedf</a> - read .EDF EEG data format (readedf()) % <a href="matlab:helpwin pop_headplot">pop_headplot</a> - plot a 3-D data scalp map (headplot()) % <a href="matlab:helpwin pop_reref">pop_reref</a> - re-reference data (reref()) % <a href="matlab:helpwin pop_signalstat">pop_signalstat</a> - plot signal or component statistic (signalstat()) % % Other GUI functions: % ------------------- % <a href="matlab:helpwin pop_chanevent">pop_chanevent</a> - import events stored in data channel(s) % <a href="matlab:helpwin pop_comments">pop_comments</a> - edit dataset comment ('about') text % <a href="matlab:helpwin pop_compareerps">pop_compareerps</a> - compare two dataset ERPs using plottopo() % <a href="matlab:helpwin pop_prop">pop_prop</a> - plot channel or component properties (erpimage, spectra, map) % <a href="matlab:helpwin pop_copyset">pop_copyset</a> - copy dataset % <a href="matlab:helpwin pop_dispcomp">pop_dispcomp</a> - display component scalp maps with reject buttons % <a href="matlab:helpwin pop_editeventfield">pop_editeventfield</a> - edit event fields % <a href="matlab:helpwin pop_editeventvals">pop_editeventvals</a> - edit event values % <a href="matlab:helpwin pop_editset">pop_editset</a> - edit dataset information % <a href="matlab:helpwin pop_export">pop_export</a> - export data or ica activity to ASCII file % <a href="matlab:helpwin pop_expica">pop_expica</a> - export ica weights or inverse matrix to ASCII file % <a href="matlab:helpwin pop_icathresh">pop_icathresh</a> - choose rejection thresholds (in development) % <a href="matlab:helpwin pop_importepoch">pop_importepoch</a> - import epoch info ASCII file % <a href="matlab:helpwin pop_importevent">pop_importevent</a> - import event info ASCII file % <a href="matlab:helpwin pop_importpres">pop_importpres</a> - import Presentation info file % <a href="matlab:helpwin pop_importev2">pop_importev2</a> - import Neuroscan ev2 file % <a href="matlab:helpwin pop_loadset">pop_loadset</a> - load dataset % <a href="matlab:helpwin pop_mergeset">pop_mergeset</a> - merge two datasets % <a href="matlab:helpwin pop_rejepoch">pop_rejepoch</a> - reject pre-identified epochs in a EEG dataset % <a href="matlab:helpwin pop_rejspec">pop_rejspec</a> - reject based on spectrum (computes spectrum -% eegthresh) % <a href="matlab:helpwin pop_saveh">pop_saveh</a> - save EEGLAB command history % <a href="matlab:helpwin pop_saveset">pop_saveset</a> - save dataset % <a href="matlab:helpwin pop_select">pop_select</a> - select data (epochs, time points, channels ...) % <a href="matlab:helpwin pop_selectevent">pop_selectevent</a> - select events % <a href="matlab:helpwin pop_subcomp">pop_subcomp</a> - subtract components from data % % Non-GUI functions use for handling the EEG structure: % ---------------------------------------------------- % <a href="matlab:helpwin eeg_checkset">eeg_checkset</a> - check dataset parameter consistency % <a href="matlab:helpwin eeg_context">eeg_context</a> - return info about events surrounding given events % <a href="matlab:helpwin pop_delset">pop_delset</a> - delete dataset % <a href="matlab:helpwin pop_editoptions">pop_editoptions</a> - edit the option file % <a href="matlab:helpwin eeg_emptyset">eeg_emptyset</a> - empty dataset % <a href="matlab:helpwin eeg_epochformat">eeg_epochformat</a> - convert epoch array to structure % <a href="matlab:helpwin eeg_eventformat">eeg_eventformat</a> - convert event array to structure % <a href="matlab:helpwin eeg_getepochevent">eeg_getepochevent</a> - return event values for a subset of event types % <a href="matlab:helpwin eeg_global">eeg_global</a> - global variables % <a href="matlab:helpwin eeg_multieegplot">eeg_multieegplot</a> - plot several rejections (using different colors) % <a href="matlab:helpwin eeg_options">eeg_options</a> - option file % <a href="matlab:helpwin eeg_rejsuperpose">eeg_rejsuperpose</a> - use by rejmenu to superpose all rejections % <a href="matlab:helpwin eeg_rejmacro">eeg_rejmacro</a> - used by all rejection functions % <a href="matlab:helpwin pop_rejmenu">pop_rejmenu</a> - rejection menu (with all rejection methods visible) % <a href="matlab:helpwin eeg_retrieve">eeg_retrieve</a> - retrieve dataset from ALLEEG % <a href="matlab:helpwin eeg_store">eeg_store</a> - store dataset into ALLEEG % % Help functions: % -------------- % <a href="matlab:helpwin eeg_helpadmin">eeg_helpadmin</a> - help on admin function % <a href="matlab:helpwin eeg_helphelp">eeg_helphelp</a> - help on help % <a href="matlab:helpwin eeg_helpmenu">eeg_helpmenu</a> - EEG help menus % <a href="matlab:helpwin eeg_helppop">eeg_helppop</a> - help on pop_ and eeg_ functions % <a href="matlab:helpwin eeg_helpsigproc">eeg_helpsigproc</a> - help on % Copyright (C) 2001 Arnaud Delorme and Scott Makeig, Salk Institute, % [email protected], [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 varargout = eeglab( onearg ) if nargout > 0 varargout = { [] [] 0 {} [] }; %[ALLEEG, EEG, CURRENTSET, ALLCOM] end; % check Matlab version % -------------------- vers = version; tmpv = which('version'); if ~isempty(findstr(lower(tmpv), 'biosig')) [tmpp tmp] = fileparts(tmpv); rmpath(tmpp); end; % remove freemat folder if it exist tmpPath = fileparts(fileparts(which('sread'))); newPath = fullfile(tmpPath, 'maybe-missing', 'freemat3.5'); if exist(newPath) == 7 warning('off', 'MATLAB:rmpath:DirNotFound'); rmpath(newPath) warning('on', 'MATLAB:rmpath:DirNotFound'); end; if str2num(vers(1)) < 7 && str2num(vers(1)) >= 5 tmpWarning = warning('backtrace'); warning backtrace off; warning('You are using a Matlab version older than 7.0'); warning('This Matlab version is too old to run the current EEGLAB'); warning('Download EEGLAB 4.3b at http://sccn.ucsd.edu/eeglab/eeglab4.5b.teaching.zip'); warning('This version of EEGLAB is compatible with all Matlab version down to Matlab 5.3'); warning(tmpWarning); return; end; % check Matlab version % -------------------- vers = version; indp = find(vers == '.'); if str2num(vers(indp(1)+1)) > 1, vers = [ vers(1:indp(1)) '0' vers(indp(1)+1:end) ]; end; indp = find(vers == '.'); vers = str2num(vers(1:indp(2)-1)); if vers < 7.06 tmpWarning = warning('backtrace'); warning backtrace off; warning('You are using a Matlab version older than 7.6 (2008a)'); warning('Some of the EEGLAB functions might not be functional'); warning('Download EEGLAB 4.3b at http://sccn.ucsd.edu/eeglab/eeglab4.5b.teaching.zip'); warning('This version of EEGLAB is compatible with all Matlab version down to Matlab 5.3'); warning(tmpWarning); end; % check for duplicate versions of EEGLAB % -------------------------------------- eeglabpath = mywhich('eeglab.m'); eeglabpath = eeglabpath(1:end-length('eeglab.m')); if nargin < 1 eeglabpath2 = ''; if strcmpi(eeglabpath, pwd) || strcmpi(eeglabpath(1:end-1), pwd) cd('functions'); warning('off', 'MATLAB:rmpath:DirNotFound'); rmpath(eeglabpath); warning('on', 'MATLAB:rmpath:DirNotFound'); eeglabpath2 = mywhich('eeglab.m'); cd('..'); else try, rmpath(eeglabpath); catch, end; eeglabpath2 = mywhich('eeglab.m'); end; if ~isempty(eeglabpath2) %evalin('base', 'clear classes updater;'); % this clears all the variables eeglabpath2 = eeglabpath2(1:end-length('eeglab.m')); tmpWarning = warning('backtrace'); warning backtrace off; disp('******************************************************'); warning('There are at least two versions of EEGLAB in your path'); warning(sprintf('One is at %s', eeglabpath)); warning(sprintf('The other one is at %s', eeglabpath2)); warning(tmpWarning); end; addpath(eeglabpath); end; % add the paths % ------------- if strcmpi(eeglabpath, './') || strcmpi(eeglabpath, '.\'), eeglabpath = [ pwd filesep ]; end; % solve BIOSIG problem % -------------------- pathtmp = mywhich('wilcoxon_test'); if ~isempty(pathtmp) try, rmpath(pathtmp(1:end-15)); catch, end; end; % test for local SCCN copy % ------------------------ if ~iseeglabdeployed2 addpathifnotinlist(eeglabpath); if exist( fullfile( eeglabpath, 'functions', 'adminfunc') ) ~= 7 warning('EEGLAB subfolders not found'); end; end; % determine file format % --------------------- fileformat = 'maclinux'; comp = computer; try if strcmpi(comp(1:3), 'GLN') | strcmpi(comp(1:3), 'MAC') | strcmpi(comp(1:3), 'SOL') fileformat = 'maclinux'; elseif strcmpi(comp(1:5), 'pcwin') fileformat = 'pcwin'; end; end; % add paths % --------- if ~iseeglabdeployed2 tmp = which('eeglab_data.set'); if ~isempty(which('eeglab_data.set')) && ~isempty(which('GSN-HydroCel-32.sfp')) warning backtrace off; warning(sprintf([ '\n\nPath Warning: It appears that you have added the path to all of the\n' ... 'subfolders to EEGLAB. This may create issues with some EEGLAB extensions\n' ... 'If EEGLAB cannot start or your experience a large number of warning\n' ... 'messages, remove all the EEGLAB paths then go to the EEGLAB folder\n' ... 'and start EEGLAB which will add all the necessary paths.\n\n' ])); warning backtrace on; foldertorm = fileparts(which('fgetl.m')); if ~isempty(strfind(foldertorm, 'eeglab')) rmpath(foldertorm); end; foldertorm = fileparts(which('strjoin.m')); if ~isempty(strfind(foldertorm, 'eeglab')) rmpath(foldertorm); end; end; myaddpath( eeglabpath, 'eeg_checkset.m', [ 'functions' filesep 'adminfunc' ]); myaddpath( eeglabpath, 'eeg_checkset.m', [ 'functions' filesep 'adminfunc' ]); myaddpath( eeglabpath, ['@mmo' filesep 'mmo.m'], 'functions'); myaddpath( eeglabpath, 'readeetraklocs.m', [ 'functions' filesep 'sigprocfunc' ]); myaddpath( eeglabpath, 'supergui.m', [ 'functions' filesep 'guifunc' ]); myaddpath( eeglabpath, 'pop_study.m', [ 'functions' filesep 'studyfunc' ]); myaddpath( eeglabpath, 'pop_loadbci.m', [ 'functions' filesep 'popfunc' ]); myaddpath( eeglabpath, 'statcond.m', [ 'functions' filesep 'statistics' ]); myaddpath( eeglabpath, 'timefreq.m', [ 'functions' filesep 'timefreqfunc' ]); myaddpath( eeglabpath, 'icademo.m', [ 'functions' filesep 'miscfunc' ]); myaddpath( eeglabpath, 'eeglab1020.ced', [ 'functions' filesep 'resources' ]); myaddpath( eeglabpath, 'startpane.m', [ 'functions' filesep 'javachatfunc' ]); addpathifnotinlist(fullfile(eeglabpath, 'plugins')); eeglab_options; % remove path to to fmrlab if neceecessary path_runica = fileparts(mywhich('runica')); if length(path_runica) > 6 && strcmpi(path_runica(end-5:end), 'fmrlab') rmpath(path_runica); end; % add path if toolboxes are missing % --------------------------------- signalpath = fullfile(eeglabpath, 'functions', 'octavefunc', 'signal'); optimpath = fullfile(eeglabpath, 'functions', 'octavefunc', 'optim'); if option_donotusetoolboxes p1 = fileparts(mywhich('ttest')); p2 = fileparts(mywhich('filtfilt')); p3 = fileparts(mywhich('optimtool')); p4 = fileparts(mywhich('gray2ind')); if ~isempty(p1), rmpath(p1); end; if ~isempty(p2), rmpath(p2); end; if ~isempty(p3), rmpath(p3); end; if ~isempty(p4), rmpath(p4); end; end; if ~license('test','signal_toolbox') || exist('pwelch') ~= 2 warning('off', 'MATLAB:dispatcher:nameConflict'); addpath( signalpath ); else warning('off', 'MATLAB:rmpath:DirNotFound'); rmpathifpresent( signalpath ); rmpathifpresent(optimpath); warning('on', 'MATLAB:rmpath:DirNotFound'); end; if ~license('test','optim_toolbox') && ~ismatlab addpath( optimpath ); else warning('off', 'MATLAB:rmpath:DirNotFound'); rmpathifpresent( optimpath ); warning('on', 'MATLAB:rmpath:DirNotFound'); end; % remove BIOSIG path which are not needed and might cause conflicts biosigp{1} = fileparts(which('sopen.m')); biosigp{2} = fileparts(which('regress_eog.m')); biosigp{3} = fileparts(which('DecimalFactors.txt')); removepath(fileparts(fileparts(biosigp{1})), biosigp{:}) else eeglab_options; end; if nargin == 1 && strcmp(onearg, 'redraw') if evalin('base', 'exist(''EEG'')', '0') == 1 evalin('base', 'eeg_global;'); end; end; eeg_global; % remove empty datasets in ALLEEG while ~isempty(ALLEEG) && isempty(ALLEEG(end).data) ALLEEG(end) = []; end; if ~isempty(ALLEEG) && max(CURRENTSET) > length(ALLEEG) CURRENTSET = 1; EEG = eeg_retrieve(ALLEEG, CURRENTSET); end; % for the history function % ------------------------ comtmp = 'warning off MATLAB:mir_warning_variable_used_as_function'; evalin('base' , comtmp, ''); evalin('caller', comtmp, ''); evalin('base', 'eeg_global;'); if nargin < 1 | exist('EEG') ~= 1 clear global EEG ALLEEG CURRENTSET ALLCOM LASTCOM STUDY; CURRENTSTUDY = 0; eeg_global; EEG = eeg_emptyset; eegh('[ALLEEG EEG CURRENTSET ALLCOM] = eeglab;'); if ismatlab && get(0, 'screendepth') <= 8 disp('Warning: screen color depth too low, some colors will be inaccurate in time-frequency plots'); end; end; if nargin == 1 if strcmp(onearg, 'versions') disp( [ 'EEGLAB v' eeg_getversion ] ); elseif strcmp(onearg, 'nogui') if nargout < 1, clear ALLEEG; end; % do not return output var return; elseif strcmp(onearg, 'redraw') if ~ismatlab,return; end; W_MAIN = findobj('tag', 'EEGLAB'); if ~isempty(W_MAIN) updatemenu; if nargout < 1, clear ALLEEG; end; % do not return output var return; else eegh('eeglab(''redraw'');'); end; elseif strcmp(onearg, 'rebuild') if ~ismatlab,return; end; W_MAIN = findobj('tag', 'EEGLAB'); close(W_MAIN); eeglab; return; else fprintf(2,['EEGLAB Warning: Invalid argument ''' onearg '''. Restarting EEGLAB interface instead.\n']); eegh('[ALLEEG EEG CURRENTSET ALLCOM] = eeglab(''rebuild'');'); end; else onearg = 'rebuild'; end; ALLCOM = ALLCOM; try, eval('colordef white;'); catch end; % default option folder % --------------------- if ~iseeglabdeployed2 eeglab_options; fprintf('eeglab: options file is %s%seeg_options.m\n', homefolder, filesep); end; % checking strings % ---------------- e_try = 'try,'; e_catch = 'catch, eeglab_error; LASTCOM= ''''; clear EEGTMP ALLEEGTMP STUDYTMP; end;'; nocheck = e_try; ret = 'if ~isempty(LASTCOM), if LASTCOM(1) == -1, LASTCOM = ''''; return; end; end;'; check = ['[EEG LASTCOM] = eeg_checkset(EEG, ''data'');' ret ' eegh(LASTCOM);' e_try]; checkcont = ['[EEG LASTCOM] = eeg_checkset(EEG, ''contdata'');' ret ' eegh(LASTCOM);' e_try]; checkica = ['[EEG LASTCOM] = eeg_checkset(EEG, ''ica'');' ret ' eegh(LASTCOM);' e_try]; checkepoch = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'');' ret ' eegh(LASTCOM);' e_try]; checkevent = ['[EEG LASTCOM] = eeg_checkset(EEG, ''event'');' ret ' eegh(LASTCOM);' e_try]; checkbesa = ['[EEG LASTCOM] = eeg_checkset(EEG, ''besa'');' ret ' eegh(''% no history yet for BESA dipole localization'');' e_try]; checkepochica = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'', ''ica'');' ret ' eegh(LASTCOM);' e_try]; checkplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''chanloc'');' ret ' eegh(LASTCOM);' e_try]; checkicaplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''ica'', ''chanloc'');' ret ' eegh(LASTCOM);' e_try]; checkepochplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'', ''chanloc'');' ret ' eegh(LASTCOM);' e_try]; checkepochicaplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'', ''ica'', ''chanloc'');' ret ' eegh(LASTCOM);' e_try]; % check string and backup old dataset % ----------------------------------- backup = [ 'if CURRENTSET ~= 0,' ... ' [ ALLEEG EEG ] = eeg_store(ALLEEG, EEG, CURRENTSET, ''savegui'');' ... ' eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET, ''''savedata'''');'');' ... 'end;' ]; storecall = '[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET); eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET);'');'; storenewcall = '[ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''study'', ~isempty(STUDY)+0); eegh(LASTCOM);'; storeallcall = [ 'if ~isempty(ALLEEG) & ~isempty(ALLEEG(1).data), ALLEEG = eeg_checkset(ALLEEG);' ... 'EEG = eeg_retrieve(ALLEEG, CURRENTSET); eegh(''ALLEEG = eeg_checkset(ALLEEG); EEG = eeg_retrieve(ALLEEG, CURRENTSET);''); end;' ]; testeegtmp = 'if exist(''EEGTMP'') == 1, EEG = EEGTMP; clear EEGTMP; end;'; % for backward compatibility ifeeg = 'if ~isempty(LASTCOM) & ~isempty(EEG),'; ifeegnh = 'if ~isempty(LASTCOM) & ~isempty(EEG) & ~isempty(findstr(''='',LASTCOM)),'; % nh = no dataset history % ----------------------- e_storeall_nh = [e_catch 'eegh(LASTCOM);' ifeeg storeallcall 'disp(''Done.''); end; eeglab(''redraw'');']; e_hist_nh = [e_catch 'eegh(LASTCOM);']; % same as above but also save history in dataset % ---------------------------------------------- e_newset = [e_catch 'EEG = eegh(LASTCOM, EEG);' testeegtmp ifeeg storenewcall 'disp(''Done.''); end; eeglab(''redraw'');']; e_store = [e_catch 'EEG = eegh(LASTCOM, EEG);' ifeegnh storecall 'disp(''Done.''); end; eeglab(''redraw'');']; e_hist = [e_catch 'EEG = eegh(LASTCOM, EEG);']; e_histdone = [e_catch 'EEG = eegh(LASTCOM, EEG); if ~isempty(LASTCOM), disp(''Done.''); end;' ]; % study checking % -------------- e_load_study = [e_catch 'if ~isempty(LASTCOM), STUDY = STUDYTMP; STUDY = eegh(LASTCOM, STUDY); ALLEEG = ALLEEGTMP; EEG = ALLEEG; CURRENTSET = [1:length(EEG)]; eegh(''CURRENTSTUDY = 1; EEG = ALLEEG; CURRENTSET = [1:length(EEG)];''); CURRENTSTUDY = 1; disp(''Done.''); end; clear ALLEEGTMP STUDYTMP; eeglab(''redraw'');']; e_plot_study = [e_catch 'if ~isempty(LASTCOM), STUDY = STUDYTMP; STUDY = eegh(LASTCOM, STUDY); disp(''Done.''); end; clear ALLEEGTMP STUDYTMP; eeglab(''redraw'');']; % ALLEEG not modified % build structures for plugins % ---------------------------- trystrs.no_check = e_try; trystrs.check_data = check; trystrs.check_ica = checkica; trystrs.check_cont = checkcont; trystrs.check_epoch = checkepoch; trystrs.check_event = checkevent; trystrs.check_epoch_ica = checkepochica; trystrs.check_chanlocs = checkplot; trystrs.check_epoch_chanlocs = checkepochplot; trystrs.check_epoch_ica_chanlocs = checkepochicaplot; catchstrs.add_to_hist = e_hist; catchstrs.store_and_hist = e_store; catchstrs.new_and_hist = e_newset; catchstrs.new_non_empty = e_newset; catchstrs.update_study = e_plot_study; % create eeglab figure % -------------------- javaobj = eeg_mainfig(onearg); % detecting icalab % ---------------- if exist('icalab') disp('ICALAB toolbox detected (algo. added to "run ICA" interface)'); end; if ~iseeglabdeployed2 % check for older version of Fieldtrip and presence of topoplot % ------------------------------------------------------------- if ismatlab ptopoplot = fileparts(mywhich('cbar')); ptopoplot2 = fileparts(mywhich('topoplot')); if ~strcmpi(ptopoplot, ptopoplot2), %disp(' Warning: duplicate function topoplot.m in Fieldtrip and EEGLAB'); %disp(' EEGLAB function will prevail and call the Fieldtrip one when appropriate'); addpath(ptopoplot); end; end; end; cb_importdata = [ nocheck '[EEG LASTCOM] = pop_importdata;' e_newset ]; cb_readegi = [ nocheck '[EEG LASTCOM] = pop_readegi;' e_newset ]; cb_readsegegi = [ nocheck '[EEG LASTCOM] = pop_readsegegi;' e_newset ]; cb_readegiepo = [ nocheck '[EEG LASTCOM] = pop_importegimat;' e_newset ]; cb_loadbci = [ nocheck '[EEG LASTCOM] = pop_loadbci;' e_newset ]; cb_snapread = [ nocheck '[EEG LASTCOM] = pop_snapread;' e_newset ]; cb_loadcnt = [ nocheck '[EEG LASTCOM] = pop_loadcnt;' e_newset ]; cb_loadeeg = [ nocheck '[EEG LASTCOM] = pop_loadeeg;' e_newset ]; cb_biosig = [ nocheck '[EEG LASTCOM] = pop_biosig; ' e_newset ]; cb_fileio = [ nocheck '[EEG LASTCOM] = pop_fileio; ' e_newset ]; cb_fileio2 = [ nocheck '[EEG LASTCOM] = pop_fileiodir;' e_newset ]; cb_importepoch = [ checkepoch '[EEG LASTCOM] = pop_importepoch(EEG);' e_store ]; cb_loaddat = [ checkepoch '[EEG LASTCOM]= pop_loaddat(EEG);' e_store ]; cb_importevent = [ check '[EEG LASTCOM] = pop_importevent(EEG);' e_store ]; cb_chanevent = [ check '[EEG LASTCOM]= pop_chanevent(EEG);' e_store ]; cb_importpres = [ check '[EEG LASTCOM]= pop_importpres(EEG);' e_store ]; cb_importev2 = [ check '[EEG LASTCOM]= pop_importev2(EEG);' e_store ]; cb_importerplab= [ check '[EEG LASTCOM]= pop_importerplab(EEG);' e_store ]; cb_export = [ check 'LASTCOM = pop_export(EEG);' e_histdone ]; cb_expica1 = [ check 'LASTCOM = pop_expica(EEG, ''weights'');' e_histdone ]; cb_expica2 = [ check 'LASTCOM = pop_expica(EEG, ''inv'');' e_histdone ]; cb_expevents = [ check 'LASTCOM = pop_expevents(EEG);' e_histdone ]; cb_expdata = [ check 'LASTCOM = pop_writeeeg(EEG);' e_histdone ]; cb_loadset = [ nocheck '[EEG LASTCOM] = pop_loadset;' e_newset]; cb_saveset = [ check '[EEG LASTCOM] = pop_saveset(EEG, ''savemode'', ''resave'');' e_store ]; cb_savesetas = [ check '[EEG LASTCOM] = pop_saveset(EEG);' e_store ]; cb_delset = [ nocheck '[ALLEEG LASTCOM] = pop_delset(ALLEEG, -CURRENTSET);' e_hist_nh 'eeglab redraw;' ]; cb_study1 = [ nocheck 'pop_stdwarn; [STUDYTMP ALLEEGTMP LASTCOM] = pop_study([], ALLEEG , ''gui'', ''on'');' e_load_study]; cb_study2 = [ nocheck 'pop_stdwarn; [STUDYTMP ALLEEGTMP LASTCOM] = pop_study([], isempty(ALLEEG), ''gui'', ''on'');' e_load_study]; cb_studyerp = [ nocheck 'pop_stdwarn; [STUDYTMP ALLEEGTMP LASTCOM] = pop_studyerp;' e_load_study]; cb_loadstudy = [ nocheck 'pop_stdwarn; [STUDYTMP ALLEEGTMP LASTCOM] = pop_loadstudy; if ~isempty(LASTCOM), STUDYTMP = std_renamestudyfiles(STUDYTMP, ALLEEGTMP); end;' e_load_study]; cb_savestudy1 = [ check '[STUDYTMP ALLEEGTMP LASTCOM] = pop_savestudy(STUDY, EEG, ''savemode'', ''resave'');' e_load_study]; cb_savestudy2 = [ check '[STUDYTMP ALLEEGTMP LASTCOM] = pop_savestudy(STUDY, EEG);' e_load_study]; cb_clearstudy = 'LASTCOM = ''STUDY = []; CURRENTSTUDY = 0; ALLEEG = []; EEG=[]; CURRENTSET=[];''; eval(LASTCOM); eegh( LASTCOM ); eeglab redraw;'; cb_editoptions = [ nocheck 'if isfield(ALLEEG, ''nbchan''), LASTCOM = pop_editoptions(length([ ALLEEG.nbchan ]) >1);' ... 'else LASTCOM = pop_editoptions(0); end;' e_storeall_nh]; cb_plugin1 = [ nocheck 'if plugin_extract(''import'', PLUGINLIST) , close(findobj(''tag'', ''EEGLAB'')); eeglab redraw; end;' e_hist_nh ]; cb_plugin2 = [ nocheck 'if plugin_extract(''process'', PLUGINLIST), close(findobj(''tag'', ''EEGLAB'')); eeglab redraw; end;' e_hist_nh ]; cb_saveh1 = [ nocheck 'LASTCOM = pop_saveh(EEG.history);' e_hist_nh]; cb_saveh2 = [ nocheck 'LASTCOM = pop_saveh(ALLCOM);' e_hist_nh]; cb_runsc = [ nocheck 'LASTCOM = pop_runscript;' e_hist ]; cb_quit = [ 'close(gcf); disp(''To save the EEGLAB command history >> pop_saveh(ALLCOM);'');' ... 'clear global EEG ALLEEG LASTCOM CURRENTSET;']; cb_editset = [ check '[EEG LASTCOM] = pop_editset(EEG);' e_store]; cb_editeventf = [ checkevent '[EEG LASTCOM] = pop_editeventfield(EEG);' e_store]; cb_editeventv = [ checkevent '[EEG LASTCOM] = pop_editeventvals(EEG);' e_store]; cb_comments = [ check '[EEG.comments LASTCOM] =pop_comments(EEG.comments, ''About this dataset'');' e_store]; cb_chanedit = [ 'disp(''IMPORTANT: After importing/modifying data channels, you must close'');' ... 'disp(''the channel editing window for the changes to take effect in EEGLAB.'');' ... 'disp(''TIP: Call this function directy from the prompt, ">> pop_chanedit([]);"'');' ... 'disp('' to convert between channel location file formats'');' ... '[EEG TMPINFO TMP LASTCOM] = pop_chanedit(EEG); if ~isempty(LASTCOM), EEG = eeg_checkset(EEG, ''chanlocsize'');' ... 'clear TMPINFO TMP; EEG = eegh(LASTCOM, EEG);' storecall 'end; eeglab(''redraw'');']; cb_select = [ check '[EEG LASTCOM] = pop_select(EEG);' e_newset]; cb_rmdat = [ checkevent '[EEG LASTCOM] = pop_rmdat(EEG);' e_newset]; cb_selectevent = [ checkevent '[EEG TMP LASTCOM] = pop_selectevent(EEG); clear TMP;' e_newset ]; cb_copyset = [ check '[ALLEEG EEG CURRENTSET LASTCOM] = pop_copyset(ALLEEG, CURRENTSET); eeglab(''redraw'');' e_hist_nh]; cb_mergeset = [ check '[EEG LASTCOM] = pop_mergeset(ALLEEG);' e_newset]; cb_resample = [ check '[EEG LASTCOM] = pop_resample(EEG);' e_newset]; cb_eegfilt = [ check '[EEG LASTCOM] = pop_eegfilt(EEG);' e_newset]; cb_interp = [ check '[EEG LASTCOM] = pop_interp(EEG); ' e_newset]; cb_reref = [ check '[EEG LASTCOM] = pop_reref(EEG);' e_newset]; cb_eegplot = [ checkcont '[LASTCOM] = pop_eegplot(EEG, 1);' e_hist]; cb_epoch = [ check '[EEG tmp LASTCOM] = pop_epoch(EEG); clear tmp;' e_newset check '[EEG LASTCOM] = pop_rmbase(EEG);' e_newset]; cb_rmbase = [ check '[EEG LASTCOM] = pop_rmbase(EEG);' e_store]; cb_runica = [ check '[EEG LASTCOM] = pop_runica(EEG);' e_store]; cb_subcomp = [ checkica '[EEG LASTCOM] = pop_subcomp(EEG);' e_newset]; %cb_chanrej = [ check 'pop_rejchan(EEG); LASTCOM = '''';' e_hist]; cb_chanrej = [ check '[EEG tmp1 tmp2 LASTCOM] = pop_rejchan(EEG); clear tmp1 tmp2;' e_hist]; cb_autorej = [ checkepoch '[EEG tmpp LASTCOM] = pop_autorej(EEG); clear tmpp;' e_hist]; cb_rejcont = [ check '[EEG tmp1 tmp2 LASTCOM] = pop_rejcont(EEG); clear tmp1 tmp2;' e_hist]; cb_rejmenu1 = [ check 'pop_rejmenu(EEG, 1); LASTCOM = '''';' e_hist]; cb_eegplotrej1 = [ check '[LASTCOM] = pop_eegplot(EEG, 1);' e_hist]; cb_eegthresh1 = [ checkepoch '[TMP LASTCOM] = pop_eegthresh(EEG, 1); clear TMP;' e_hist]; cb_rejtrend1 = [ checkepoch '[EEG LASTCOM] = pop_rejtrend(EEG, 1);' e_store]; cb_jointprob1 = [ checkepoch '[EEG LASTCOM] = pop_jointprob(EEG, 1);' e_store]; cb_rejkurt1 = [ checkepoch '[EEG LASTCOM] = pop_rejkurt(EEG, 1);' e_store]; cb_rejspec1 = [ checkepoch '[EEG Itmp LASTCOM] = pop_rejspec(EEG, 1); clear Itmp;' e_store]; cb_rejsup1 = [ checkepochica '[EEG LASTCOM] = eeg_rejsuperpose(EEG, 1,1,1,1,1,1,1,1); eegh(LASTCOM);' ... 'LASTCOM = ''EEG.reject.icarejmanual = EEG.reject.rejglobal;''; eval(LASTCOM);' e_store ]; cb_rejsup2 = [ checkepoch '[EEG LASTCOM] = eeg_rejsuperpose(EEG, 1,1,1,1,1,1,1,1); EEG = eegh(LASTCOM, EEG);' ... '[EEG LASTCOM] = pop_rejepoch(EEG);' e_newset]; cb_selectcomps = [ checkicaplot '[EEG LASTCOM] = pop_selectcomps(EEG);' e_store]; cb_rejmenu2 = [ checkepochica 'pop_rejmenu(EEG, 0); LASTCOM ='''';' e_hist]; cb_eegplotrej2 = [ checkica '[LASTCOM] = pop_eegplot(EEG, 0);' e_hist]; cb_eegthresh2 = [ checkepochica '[TMP LASTCOM] = pop_eegthresh(EEG, 0); clear TMP;' e_hist]; cb_rejtrend2 = [ checkepochica '[EEG LASTCOM] = pop_rejtrend(EEG, 0);' e_store]; cb_jointprob2 = [ checkepochica '[EEG LASTCOM] = pop_jointprob(EEG, 0);' e_store]; cb_rejkurt2 = [ checkepochica '[EEG LASTCOM] = pop_rejkurt(EEG, 0);' e_store]; cb_rejspec2 = [ checkepochica '[EEG Itmp LASTCOM] = pop_rejspec(EEG, 1); clear Itmp;' e_store]; cb_rejsup3 = [ checkepochica '[EEG LASTCOM] = eeg_rejsuperpose(EEG, 0,1,1,1,1,1,1,1); eegh(LASTCOM);' ... 'LASTCOM = ''EEG.reject.rejmanual = EEG.reject.rejglobal;''; eval(LASTCOM);' e_store ]; cb_rejsup4 = [ checkepochica '[EEG LASTCOM] = eeg_rejsuperpose(EEG, 0,1,1,1,1,1,1,1); EEG = eegh(LASTCOM, EEG);' ... '[EEG LASTCOM] = pop_rejepoch(EEG);' e_newset ]; cb_topoblank1 = [ checkplot 'LASTCOM = [''figure; topoplot([],EEG.chanlocs, ''''style'''', ''''blank'''', ' ... '''''electrodes'''', ''''labelpoint'''', ''''chaninfo'''', EEG.chaninfo);'']; eval(LASTCOM);' e_hist]; cb_topoblank2 = [ checkplot 'LASTCOM = [''figure; topoplot([],EEG.chanlocs, ''''style'''', ''''blank'''', ' ... '''''electrodes'''', ''''numpoint'''', ''''chaninfo'''', EEG.chaninfo);'']; eval(LASTCOM);' e_hist]; cb_eegplot1 = [ check 'LASTCOM = pop_eegplot(EEG, 1, 1, 1);' e_hist]; cb_spectopo1 = [ check 'LASTCOM = pop_spectopo(EEG, 1);' e_hist]; cb_prop1 = [ checkplot 'LASTCOM = pop_prop(EEG,1);' e_hist]; cb_erpimage1 = [ checkepoch 'LASTCOM = pop_erpimage(EEG, 1, eegh(''find'',''pop_erpimage(EEG,1''));' e_hist]; cb_timtopo = [ checkplot 'LASTCOM = pop_timtopo(EEG);' e_hist]; cb_plottopo = [ check 'LASTCOM = pop_plottopo(EEG);' e_hist]; cb_topoplot1 = [ checkplot 'LASTCOM = pop_topoplot(EEG, 1);' e_hist]; cb_headplot1 = [ checkplot '[EEG LASTCOM] = pop_headplot(EEG, 1);' e_store]; cb_comperp1 = [ checkepoch 'LASTCOM = pop_comperp(ALLEEG);' e_hist]; cb_eegplot2 = [ checkica '[LASTCOM] = pop_eegplot(EEG, 0, 1, 1);' e_hist]; cb_spectopo2 = [ checkicaplot 'LASTCOM = pop_spectopo(EEG, 0);' e_hist]; cb_topoplot2 = [ checkicaplot 'LASTCOM = pop_topoplot(EEG, 0);' e_hist]; cb_headplot2 = [ checkicaplot '[EEG LASTCOM] = pop_headplot(EEG, 0);' e_store]; cb_prop2 = [ checkicaplot 'LASTCOM = pop_prop(EEG,0);' e_hist]; cb_erpimage2 = [ checkepochica 'LASTCOM = pop_erpimage(EEG, 0, eegh(''find'',''pop_erpimage(EEG,0''));' e_hist]; cb_envtopo1 = [ checkica 'LASTCOM = pop_envtopo(EEG);' e_hist]; cb_envtopo2 = [ checkica 'if length(ALLEEG) == 1, error(''Need at least 2 datasets''); end; LASTCOM = pop_envtopo(ALLEEG);' e_hist]; cb_plotdata2 = [ checkepochica '[tmpeeg LASTCOM] = pop_plotdata(EEG, 0); clear tmpeeg;' e_hist]; cb_comperp2 = [ checkepochica 'LASTCOM = pop_comperp(ALLEEG, 0);' e_hist]; cb_signalstat1 = [ check 'LASTCOM = pop_signalstat(EEG, 1);' e_hist]; cb_signalstat2 = [ checkica 'LASTCOM = pop_signalstat(EEG, 0);' e_hist]; cb_eventstat = [ checkevent 'LASTCOM = pop_eventstat(EEG);' e_hist]; cb_timef1 = [ check 'LASTCOM = pop_newtimef(EEG, 1, eegh(''find'',''pop_newtimef(EEG,1''));' e_hist]; cb_crossf1 = [ check 'LASTCOM = pop_newcrossf(EEG, 1,eegh(''find'',''pop_newcrossf(EEG,1''));' e_hist]; cb_timef2 = [ checkica 'LASTCOM = pop_newtimef(EEG, 0, eegh(''find'',''pop_newtimef(EEG,0''));' e_hist]; cb_crossf2 = [ checkica 'LASTCOM = pop_newcrossf(EEG, 0,eegh(''find'',''pop_newcrossf(EEG,0''));' e_hist]; cb_study3 = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_study(STUDY, ALLEEG, ''gui'', ''on'');' e_load_study]; cb_studydesign = [ nocheck '[STUDYTMP LASTCOM] = pop_studydesign(STUDY, ALLEEG); ALLEEGTMP = ALLEEG;' e_plot_study]; cb_precomp = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_precomp(STUDY, ALLEEG);' e_plot_study]; cb_chanplot = [ nocheck '[STUDYTMP LASTCOM] = pop_chanplot(STUDY, ALLEEG); ALLEEGTMP=ALLEEG;' e_plot_study]; cb_precomp2 = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_precomp(STUDY, ALLEEG, ''components'');' e_plot_study]; cb_preclust = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_preclust(STUDY, ALLEEG);' e_plot_study]; cb_clust = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_clust(STUDY, ALLEEG);' e_plot_study]; cb_clustedit = [ nocheck 'ALLEEGTMP = ALLEEG; [STUDYTMP LASTCOM] = pop_clustedit(STUDY, ALLEEG);' e_plot_study]; % % % add STUDY plugin menus % if exist('eegplugin_stderpimage') % structure.uilist = { { } ... % {'style' 'pushbutton' 'string' 'Plot ERPimage' 'Callback' 'stderpimageplugin_plot(''onecomp'', gcf);' } { } ... % {'style' 'pushbutton' 'string' 'Plot ERPimage(s)' 'Callback' 'stderpimageplugin_plot(''oneclust'', gcf);' } }; % structure.geometry = { [1] [1 0.3 1] }; % arg = vararg2str( { structure } ); % cb_clustedit = [ nocheck 'ALLEEGTMP = ALLEEG; [STUDYTMP LASTCOM] = pop_clustedit(STUDY, ALLEEG, [], ' arg ');' e_load_study]; % end; % menu definition % --------------- if ismatlab % defaults % -------- % startup:on % study:off % chanloc:off % epoch:on % continuous:on on = 'study:on'; onnostudy = ''; ondata = 'startup:off'; onepoch = 'startup:off;continuous:off'; ondatastudy = 'startup:off;study:on'; onchannel = 'startup:off;chanloc:on'; onepochchan = 'startup:off;continuous:off;chanloc:on'; onstudy = 'startup:off;epoch:off;continuous:off;study:on'; W_MAIN = findobj('tag', 'EEGLAB'); EEGUSERDAT = get(W_MAIN, 'userdata'); set(W_MAIN, 'MenuBar', 'none'); file_m = uimenu( W_MAIN, 'Label', 'File' , 'userdata', on); import_m = uimenu( file_m, 'Label', 'Import data' , 'userdata', onnostudy); neuro_m = uimenu( import_m, 'Label', 'Using EEGLAB functions and plugins' , 'tag', 'import data' , 'userdata', onnostudy); epoch_m = uimenu( file_m, 'Label', 'Import epoch info', 'tag', 'import epoch', 'userdata', onepoch); event_m = uimenu( file_m, 'Label', 'Import event info', 'tag', 'import event', 'userdata', ondata); exportm = uimenu( file_m, 'Label', 'Export' , 'tag', 'export' , 'userdata', ondata); edit_m = uimenu( W_MAIN, 'Label', 'Edit' , 'userdata', ondata); tools_m = uimenu( W_MAIN, 'Label', 'Tools', 'tag', 'tools' , 'userdata', ondatastudy); plot_m = uimenu( W_MAIN, 'Label', 'Plot', 'tag', 'plot' , 'userdata', ondata); loc_m = uimenu( plot_m, 'Label', 'Channel locations' , 'userdata', onchannel); std_m = uimenu( W_MAIN, 'Label', 'Study', 'tag', 'study' , 'userdata', onstudy); set_m = uimenu( W_MAIN, 'Label', 'Datasets' , 'userdata', ondatastudy); help_m = uimenu( W_MAIN, 'Label', 'Help' , 'userdata', on); uimenu( neuro_m, 'Label', 'From ASCII/float file or Matlab array' , 'CallBack', cb_importdata); %uimenu( neuro_m, 'Label', 'From Netstation .mff (FILE-IO toolbox)', 'CallBack', cb_fileio2, 'Separator', 'on'); uimenu( neuro_m, 'Label', 'From Netstation binary simple file' , 'CallBack', cb_readegi, 'Separator', 'on'); uimenu( neuro_m, 'Label', 'From Multiple seg. Netstation files' , 'CallBack', cb_readsegegi); uimenu( neuro_m, 'Label', 'From Netstation Matlab files' , 'CallBack', cb_readegiepo); uimenu( neuro_m, 'Label', 'From BCI2000 ASCII file' , 'CallBack', cb_loadbci, 'Separator', 'on'); uimenu( neuro_m, 'Label', 'From Snapmaster .SMA file' , 'CallBack', cb_snapread, 'Separator', 'on'); uimenu( neuro_m, 'Label', 'From Neuroscan .CNT file' , 'CallBack', cb_loadcnt, 'Separator', 'on'); uimenu( neuro_m, 'Label', 'From Neuroscan .EEG file' , 'CallBack', cb_loadeeg); % BIOSIG MENUS % ------------ uimenu( neuro_m, 'Label', 'From Biosemi BDF file (BIOSIG toolbox)', 'CallBack' , cb_biosig, 'Separator', 'on'); uimenu( neuro_m, 'Label', 'From EDF/EDF+/GDF files (BIOSIG toolbox)', 'CallBack', cb_biosig); uimenu( epoch_m, 'Label', 'From Matlab array or ASCII file' , 'CallBack', cb_importepoch); uimenu( epoch_m, 'Label', 'From Neuroscan .DAT file' , 'CallBack', cb_loaddat); uimenu( event_m, 'Label', 'From Matlab array or ASCII file' , 'CallBack', cb_importevent); uimenu( event_m, 'Label', 'From data channel' , 'CallBack', cb_chanevent); uimenu( event_m, 'Label', 'From Presentation .LOG file' , 'CallBack', cb_importpres); uimenu( event_m, 'Label', 'From E-Prime ASCII (text) file' , 'CallBack', cb_importevent); uimenu( event_m, 'Label', 'From Neuroscan .ev2 file' , 'CallBack', cb_importev2); ; uimenu( event_m, 'Label', 'From ERPLAB text files' , 'CallBack', cb_importerplab); uimenu( exportm, 'Label', 'Data and ICA activity to text file' , 'CallBack', cb_export); uimenu( exportm, 'Label', 'Weight matrix to text file' , 'CallBack', cb_expica1); uimenu( exportm, 'Label', 'Inverse weight matrix to text file' , 'CallBack', cb_expica2); uimenu( exportm, 'Label', 'Events to text file' , 'CallBack', cb_expevents); uimenu( exportm, 'Label', 'Data to EDF/BDF/GDF file' , 'CallBack', cb_expdata, 'separator', 'on'); uimenu( file_m, 'Label', 'Load existing dataset' , 'userdata', onnostudy, 'CallBack', cb_loadset, 'Separator', 'on'); uimenu( file_m, 'Label', 'Save current dataset(s)' , 'userdata', ondatastudy, 'CallBack', cb_saveset); uimenu( file_m, 'Label', 'Save current dataset as' , 'userdata', ondata, 'CallBack', cb_savesetas); uimenu( file_m, 'Label', 'Clear dataset(s)' , 'userdata', ondata, 'CallBack', cb_delset); std2_m = uimenu( file_m, 'Label', 'Create study' , 'userdata', on , 'Separator', 'on'); uimenu( std2_m, 'Label', 'Using all loaded datasets' , 'userdata', ondata , 'Callback', cb_study1); uimenu( std2_m, 'Label', 'Browse for datasets' , 'userdata', on , 'Callback', cb_study2); uimenu( std2_m, 'Label', 'Simple ERP STUDY' , 'userdata', on , 'Callback', cb_studyerp); uimenu( file_m, 'Label', 'Load existing study' , 'userdata', on , 'CallBack', cb_loadstudy,'Separator', 'on' ); uimenu( file_m, 'Label', 'Save current study' , 'userdata', onstudy, 'CallBack', cb_savestudy1); uimenu( file_m, 'Label', 'Save current study as' , 'userdata', onstudy, 'CallBack', cb_savestudy2); uimenu( file_m, 'Label', 'Clear study / Clear all' , 'userdata', ondatastudy, 'CallBack', cb_clearstudy); uimenu( file_m, 'Label', 'Memory and other options' , 'userdata', on , 'CallBack', cb_editoptions, 'Separator', 'on'); hist_m = uimenu( file_m, 'Label', 'History scripts' , 'userdata', on , 'Separator', 'on'); uimenu( hist_m, 'Label', 'Save dataset history script' , 'userdata', ondata , 'CallBack', cb_saveh1); uimenu( hist_m, 'Label', 'Save session history script' , 'userdata', ondatastudy, 'CallBack', cb_saveh2); uimenu( hist_m, 'Label', 'Run script' , 'userdata', on , 'CallBack', cb_runsc); plugin_m = uimenu( file_m, 'Label', 'Manage EEGLAB extensions' , 'userdata', on); uimenu( plugin_m, 'Label', 'Data import extensions' , 'userdata', on , 'CallBack', cb_plugin1); uimenu( plugin_m, 'Label', 'Data processing extensions' , 'userdata', on , 'CallBack', cb_plugin2); uimenu( file_m, 'Label', 'Quit' , 'userdata', on , 'CallBack', cb_quit, 'Separator', 'on'); uimenu( edit_m, 'Label', 'Dataset info' , 'userdata', ondata, 'CallBack', cb_editset); uimenu( edit_m, 'Label', 'Event fields' , 'userdata', ondata, 'CallBack', cb_editeventf); uimenu( edit_m, 'Label', 'Event values' , 'userdata', ondata, 'CallBack', cb_editeventv); uimenu( edit_m, 'Label', 'About this dataset' , 'userdata', ondata, 'CallBack', cb_comments); uimenu( edit_m, 'Label', 'Channel locations' , 'userdata', ondata, 'CallBack', cb_chanedit); uimenu( edit_m, 'Label', 'Select data' , 'userdata', ondata, 'CallBack', cb_select, 'Separator', 'on'); uimenu( edit_m, 'Label', 'Select data using events' , 'userdata', ondata, 'CallBack', cb_rmdat); uimenu( edit_m, 'Label', 'Select epochs or events' , 'userdata', ondata, 'CallBack', cb_selectevent); uimenu( edit_m, 'Label', 'Copy current dataset' , 'userdata', ondata, 'CallBack', cb_copyset, 'Separator', 'on'); uimenu( edit_m, 'Label', 'Append datasets' , 'userdata', ondata, 'CallBack', cb_mergeset); uimenu( edit_m, 'Label', 'Delete dataset(s) from memory' , 'userdata', ondata, 'CallBack', cb_delset); uimenu( tools_m, 'Label', 'Change sampling rate' , 'userdata', ondatastudy, 'CallBack', cb_resample); filter_m = uimenu( tools_m, 'Label', 'Filter the data' , 'userdata', ondatastudy, 'tag', 'filter'); uimenu( filter_m, 'Label', 'Basic FIR filter (legacy)' , 'userdata', ondatastudy, 'CallBack', cb_eegfilt); uimenu( tools_m, 'Label', 'Re-reference' , 'userdata', ondata, 'CallBack', cb_reref); uimenu( tools_m, 'Label', 'Interpolate electrodes' , 'userdata', ondata, 'CallBack', cb_interp); uimenu( tools_m, 'Label', 'Reject continuous data by eye' , 'userdata', ondata, 'CallBack', cb_eegplot); uimenu( tools_m, 'Label', 'Extract epochs' , 'userdata', ondata, 'CallBack', cb_epoch, 'Separator', 'on'); uimenu( tools_m, 'Label', 'Remove baseline' , 'userdata', ondatastudy, 'CallBack', cb_rmbase); uimenu( tools_m, 'Label', 'Run ICA' , 'userdata', ondatastudy, 'CallBack', cb_runica, 'foregroundcolor', 'b', 'Separator', 'on'); uimenu( tools_m, 'Label', 'Remove components' , 'userdata', ondata, 'CallBack', cb_subcomp); uimenu( tools_m, 'Label', 'Automatic channel rejection' , 'userdata', ondata, 'CallBack', cb_chanrej, 'Separator', 'on'); uimenu( tools_m, 'Label', 'Automatic continuous rejection' , 'userdata', ondata, 'CallBack', cb_rejcont); uimenu( tools_m, 'Label', 'Automatic epoch rejection' , 'userdata', onepoch, 'CallBack', cb_autorej); rej_m1 = uimenu( tools_m, 'Label', 'Reject data epochs' , 'userdata', onepoch); rej_m2 = uimenu( tools_m, 'Label', 'Reject data using ICA' , 'userdata', ondata ); uimenu( rej_m1, 'Label', 'Reject data (all methods)' , 'userdata', onepoch, 'CallBack', cb_rejmenu1); uimenu( rej_m1, 'Label', 'Reject by inspection' , 'userdata', onepoch, 'CallBack', cb_eegplotrej1); uimenu( rej_m1, 'Label', 'Reject extreme values' , 'userdata', onepoch, 'CallBack', cb_eegthresh1); uimenu( rej_m1, 'Label', 'Reject by linear trend/variance' , 'userdata', onepoch, 'CallBack', cb_rejtrend1); uimenu( rej_m1, 'Label', 'Reject by probability' , 'userdata', onepoch, 'CallBack', cb_jointprob1); uimenu( rej_m1, 'Label', 'Reject by kurtosis' , 'userdata', onepoch, 'CallBack', cb_rejkurt1); uimenu( rej_m1, 'Label', 'Reject by spectra' , 'userdata', onepoch, 'CallBack', cb_rejspec1); uimenu( rej_m1, 'Label', 'Export marks to ICA reject' , 'userdata', onepoch, 'CallBack', cb_rejsup1, 'separator', 'on'); uimenu( rej_m1, 'Label', 'Reject marked epochs' , 'userdata', onepoch, 'CallBack', cb_rejsup2, 'separator', 'on', 'foregroundcolor', 'b'); uimenu( rej_m2, 'Label', 'Reject components by map' , 'userdata', ondata , 'CallBack', cb_selectcomps); uimenu( rej_m2, 'Label', 'Reject data (all methods)' , 'userdata', onepoch, 'CallBack', cb_rejmenu2, 'Separator', 'on'); uimenu( rej_m2, 'Label', 'Reject by inspection' , 'userdata', onepoch, 'CallBack', cb_eegplotrej2); uimenu( rej_m2, 'Label', 'Reject extreme values' , 'userdata', onepoch, 'CallBack', cb_eegthresh2); uimenu( rej_m2, 'Label', 'Reject by linear trend/variance' , 'userdata', onepoch, 'CallBack', cb_rejtrend2); uimenu( rej_m2, 'Label', 'Reject by probability' , 'userdata', onepoch, 'CallBack', cb_jointprob2); uimenu( rej_m2, 'Label', 'Reject by kurtosis' , 'userdata', onepoch, 'CallBack', cb_rejkurt2); uimenu( rej_m2, 'Label', 'Reject by spectra' , 'userdata', onepoch, 'CallBack', cb_rejspec2); uimenu( rej_m2, 'Label', 'Export marks to data reject' , 'userdata', onepoch, 'CallBack', cb_rejsup3, 'separator', 'on'); uimenu( rej_m2, 'Label', 'Reject marked epochs' , 'userdata', onepoch, 'CallBack', cb_rejsup4, 'separator', 'on', 'foregroundcolor', 'b'); uimenu( loc_m, 'Label', 'By name' , 'userdata', onchannel, 'CallBack', cb_topoblank1); uimenu( loc_m, 'Label', 'By number' , 'userdata', onchannel, 'CallBack', cb_topoblank2); uimenu( plot_m, 'Label', 'Channel data (scroll)' , 'userdata', ondata , 'CallBack', cb_eegplot1, 'Separator', 'on'); uimenu( plot_m, 'Label', 'Channel spectra and maps' , 'userdata', ondata , 'CallBack', cb_spectopo1); uimenu( plot_m, 'Label', 'Channel properties' , 'userdata', ondata , 'CallBack', cb_prop1); uimenu( plot_m, 'Label', 'Channel ERP image' , 'userdata', onepoch, 'CallBack', cb_erpimage1); ERP_m = uimenu( plot_m, 'Label', 'Channel ERPs' , 'userdata', onepoch); uimenu( ERP_m, 'Label', 'With scalp maps' , 'CallBack', cb_timtopo); uimenu( ERP_m, 'Label', 'In scalp/rect. array' , 'CallBack', cb_plottopo); topo_m = uimenu( plot_m, 'Label', 'ERP map series' , 'userdata', onepochchan); uimenu( topo_m, 'Label', 'In 2-D' , 'CallBack', cb_topoplot1); uimenu( topo_m, 'Label', 'In 3-D' , 'CallBack', cb_headplot1); uimenu( plot_m, 'Label', 'Sum/Compare ERPs' , 'userdata', onepoch, 'CallBack', cb_comperp1); uimenu( plot_m, 'Label', 'Component activations (scroll)' , 'userdata', ondata , 'CallBack', cb_eegplot2,'Separator', 'on'); uimenu( plot_m, 'Label', 'Component spectra and maps' , 'userdata', ondata , 'CallBack', cb_spectopo2); tica_m = uimenu( plot_m, 'Label', 'Component maps' , 'userdata', onchannel); uimenu( tica_m, 'Label', 'In 2-D' , 'CallBack', cb_topoplot2); uimenu( tica_m, 'Label', 'In 3-D' , 'CallBack', cb_headplot2); uimenu( plot_m, 'Label', 'Component properties' , 'userdata', ondata , 'CallBack', cb_prop2); uimenu( plot_m, 'Label', 'Component ERP image' , 'userdata', onepoch, 'CallBack', cb_erpimage2); ERPC_m = uimenu( plot_m, 'Label', 'Component ERPs' , 'userdata', onepoch); uimenu( ERPC_m, 'Label', 'With component maps' , 'CallBack', cb_envtopo1); uimenu( ERPC_m, 'Label', 'With comp. maps (compare)' , 'CallBack', cb_envtopo2); uimenu( ERPC_m, 'Label', 'In rectangular array' , 'CallBack', cb_plotdata2); uimenu( plot_m, 'Label', 'Sum/Compare comp. ERPs' , 'userdata', onepoch, 'CallBack', cb_comperp2); stat_m = uimenu( plot_m, 'Label', 'Data statistics', 'Separator', 'on', 'userdata', ondata ); uimenu( stat_m, 'Label', 'Channel statistics' , 'CallBack', cb_signalstat1); uimenu( stat_m, 'Label', 'Component statistics' , 'CallBack', cb_signalstat2); uimenu( stat_m, 'Label', 'Event statistics' , 'CallBack', cb_eventstat); spec_m = uimenu( plot_m, 'Label', 'Time-frequency transforms', 'Separator', 'on', 'userdata', ondata); uimenu( spec_m, 'Label', 'Channel time-frequency' , 'CallBack', cb_timef1); uimenu( spec_m, 'Label', 'Channel cross-coherence' , 'CallBack', cb_crossf1); uimenu( spec_m, 'Label', 'Component time-frequency' , 'CallBack', cb_timef2,'Separator', 'on'); uimenu( spec_m, 'Label', 'Component cross-coherence' , 'CallBack', cb_crossf2); uimenu( std_m, 'Label', 'Edit study info' , 'userdata', onstudy, 'CallBack', cb_study3); uimenu( std_m, 'Label', 'Select/Edit study design(s)' , 'userdata', onstudy, 'CallBack', cb_studydesign); uimenu( std_m, 'Label', 'Precompute channel measures' , 'userdata', onstudy, 'CallBack', cb_precomp, 'separator', 'on'); uimenu( std_m, 'Label', 'Plot channel measures' , 'userdata', onstudy, 'CallBack', cb_chanplot); uimenu( std_m, 'Label', 'Precompute component measures' , 'userdata', onstudy, 'CallBack', cb_precomp2, 'separator', 'on'); clust_m = uimenu( std_m, 'Label', 'PCA clustering (original)' , 'userdata', onstudy); uimenu( clust_m, 'Label', 'Build preclustering array' , 'userdata', onstudy, 'CallBack', cb_preclust); uimenu( clust_m, 'Label', 'Cluster components' , 'userdata', onstudy, 'CallBack', cb_clust); uimenu( std_m, 'Label', 'Edit/plot clusters' , 'userdata', onstudy, 'CallBack', cb_clustedit); if ~iseeglabdeployed2 %newerVersionMenu = uimenu( help_m, 'Label', 'Upgrade to the Latest Version' , 'userdata', on, 'ForegroundColor', [0.6 0 0]); uimenu( help_m, 'Label', 'About EEGLAB' , 'userdata', on, 'CallBack', 'pophelp(''eeglab'');'); uimenu( help_m, 'Label', 'About EEGLAB help' , 'userdata', on, 'CallBack', 'pophelp(''eeg_helphelp'');'); uimenu( help_m, 'Label', 'EEGLAB menus' , 'userdata', on, 'CallBack', 'pophelp(''eeg_helpmenu'');','separator','on'); help_1 = uimenu( help_m, 'Label', 'EEGLAB functions', 'userdata', on); uimenu( help_1, 'Label', 'Admin. functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpadmin'');'); uimenu( help_1, 'Label', 'Interactive pop_ functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helppop'');'); uimenu( help_1, 'Label', 'Signal processing functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpsigproc'');'); uimenu( help_1, 'Label', 'Group data (STUDY) functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpstudy'');'); uimenu( help_1, 'Label', 'Time-frequency functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helptimefreq'');'); uimenu( help_1, 'Label', 'Statistical functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpstatistics'');'); uimenu( help_1, 'Label', 'Graphic interface builder functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpgui'');'); uimenu( help_1, 'Label', 'Misc. command line functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpmisc'');'); uimenu( help_m, 'Label', 'EEGLAB license' , 'userdata', on, 'CallBack', 'pophelp(''eeglablicense.txt'', 1);'); else uimenu( help_m, 'Label', 'About EEGLAB' , 'userdata', on, 'CallBack', 'abouteeglab;'); uimenu( help_m, 'Label', 'EEGLAB license' , 'userdata', on, 'CallBack', 'pophelp(''eeglablicense.txt'', 1);'); end; uimenu( help_m, 'Label', 'EEGLAB tutorial' , 'userdata', on, 'CallBack', 'tutorial;', 'Separator', 'on'); uimenu( help_m, 'Label', 'Email the EEGLAB team' , 'userdata', on, 'CallBack', 'web(''mailto:[email protected]'');'); end; if iseeglabdeployed2 disp('Adding FIELDTRIP toolbox functions'); disp('Adding BIOSIG toolbox functions'); disp('Adding FILE-IO toolbox functions'); funcname = { 'eegplugin_VisEd' ... 'eegplugin_eepimport' ... 'eegplugin_bdfimport' ... 'eegplugin_brainmovie' ... 'eegplugin_bva_io' ... 'eegplugin_ctfimport' ... 'eegplugin_dipfit' ... 'eegplugin_erpssimport' ... 'eegplugin_fmrib' ... 'eegplugin_iirfilt' ... 'eegplugin_ascinstep' ... 'eegplugin_loreta' ... 'eegplugin_miclust' ... 'eegplugin_4dneuroimaging' }; for indf = 1:length(funcname) try vers = feval(funcname{indf}, gcf, trystrs, catchstrs); disp(['EEGLAB: adding "' vers '" plugin' ]); catch feval(funcname{indf}, gcf, trystrs, catchstrs); disp(['EEGLAB: adding plugin function "' funcname{indf} '"' ]); end; end; else pluginlist = []; plugincount = 1; p = mywhich('eeglab.m'); p = p(1:findstr(p,'eeglab.m')-1); if strcmpi(p, './') || strcmpi(p, '.\'), p = [ pwd filesep ]; end; % scan deactivated plugin folder % ------------------------------ dircontent = dir(fullfile(p, 'deactivatedplugins')); dircontent = { dircontent.name }; for index = 1:length(dircontent) funcname = ''; pluginVersion = ''; if exist([p 'deactivatedplugins' filesep dircontent{index}]) == 7 if ~strcmpi(dircontent{index}, '.') & ~strcmpi(dircontent{index}, '..') tmpdir = dir([ p 'deactivatedplugins' filesep dircontent{index} filesep 'eegplugin*.m' ]); [ pluginName pluginVersion ] = parsepluginname(dircontent{index}); if ~isempty(tmpdir) funcname = tmpdir(1).name(1:end-2); end; end; else if ~isempty(findstr(dircontent{index}, 'eegplugin')) && dircontent{index}(end) == 'm' funcname = dircontent{index}(1:end-2); % remove .m [ pluginName pluginVersion ] = parsepluginname(dircontent{index}(10:end-2)); end; end; if ~isempty(pluginVersion) pluginlist(plugincount).plugin = pluginName; pluginlist(plugincount).version = pluginVersion; pluginlist(plugincount).foldername = dircontent{index}; if ~isempty(funcname) pluginlist(plugincount).funcname = funcname(10:end); else pluginlist(plugincount).funcname = ''; end if length(pluginlist(plugincount).funcname) > 1 && pluginlist(plugincount).funcname(1) == '_' pluginlist(plugincount).funcname(1) = []; end; pluginlist(plugincount).status = 'deactivated'; plugincount = plugincount+1; end; end; % scan plugin folder % ------------------ dircontent = dir(fullfile(p, 'plugins')); dircontent = { dircontent.name }; for index = 1:length(dircontent) % find function % ------------- funcname = ''; pluginVersion = []; if exist([p 'plugins' filesep dircontent{index}]) == 7 if ~strcmpi(dircontent{index}, '.') & ~strcmpi(dircontent{index}, '..') newpath = [ 'plugins' filesep dircontent{index} ]; tmpdir = dir([ p 'plugins' filesep dircontent{index} filesep 'eegplugin*.m' ]); addpathifnotinlist(fullfile(eeglabpath, newpath)); [ pluginName pluginVersion ] = parsepluginname(dircontent{index}); if ~isempty(tmpdir) %myaddpath(eeglabpath, tmpdir(1).name, newpath); funcname = tmpdir(1).name(1:end-2); end; % special case of subfolder for Fieldtrip % --------------------------------------- if ~isempty(findstr(lower(dircontent{index}), 'fieldtrip')) addpathifnotexist( fullfile(eeglabpath, newpath, 'compat') , 'electrodenormalize' ); addpathifnotexist( fullfile(eeglabpath, newpath, 'forward'), 'ft_sourcedepth.m'); addpathifnotexist( fullfile(eeglabpath, newpath, 'utilities'), 'ft_datatype.m'); ptopoplot = fileparts(mywhich('cbar')); ptopoplot2 = fileparts(mywhich('topoplot')); if ~isequal(ptopoplot, ptopoplot2) addpath(ptopoplot); end; end; % special case of subfolder for BIOSIG % ------------------------------------ if ~isempty(findstr(lower(dircontent{index}), 'biosig')) && isempty(findstr(lower(dircontent{index}), 'biosigplot')) addpathifnotexist( fullfile(eeglabpath, newpath, 'biosig', 't200_FileAccess'), 'sopen.m'); addpathifnotexist( fullfile(eeglabpath, newpath, 'biosig', 't250_ArtifactPreProcessingQualityControl'), 'regress_eog.m' ); addpathifnotexist( fullfile(eeglabpath, newpath, 'biosig', 'doc'), 'DecimalFactors.txt'); end; end; else if ~isempty(findstr(dircontent{index}, 'eegplugin')) && dircontent{index}(end) == 'm' funcname = dircontent{index}(1:end-2); % remove .m [ pluginName pluginVersion ] = parsepluginname(dircontent{index}(10:end-2)); end; end; % execute function % ---------------- if ~isempty(pluginVersion) || ~isempty(funcname) if isempty(funcname) disp([ 'EEGLAB: adding "' pluginName '" to the path; subfolders (if any) might be missing from the path' ]); pluginlist(plugincount).plugin = pluginName; pluginlist(plugincount).version = pluginVersion; pluginlist(plugincount).foldername = dircontent{index}; pluginlist(plugincount).status = 'ok'; plugincount = plugincount+1; else pluginlist(plugincount).plugin = pluginName; pluginlist(plugincount).version = pluginVersion; vers = pluginlist(plugincount).version; % version vers2 = ''; status = 'ok'; try, %eval( [ 'vers2 =' funcname '(gcf, trystrs, catchstrs);' ]); vers2 = feval(funcname, gcf, trystrs, catchstrs); catch try, eval( [ funcname '(gcf, trystrs, catchstrs)' ]); catch disp([ 'EEGLAB: error while adding plugin "' funcname '"' ] ); disp([ ' ' lasterr] ); status = 'error'; end; end; pluginlist(plugincount).funcname = funcname(10:end); pluginlist(plugincount).foldername = dircontent{index}; [tmp pluginlist(plugincount).versionfunc] = parsepluginname(vers2); if length(pluginlist(plugincount).funcname) > 1 && pluginlist(plugincount).funcname(1) == '_' pluginlist(plugincount).funcname(1) = []; end; if strcmpi(status, 'ok') if isempty(vers), vers = pluginlist(plugincount).versionfunc; end; if isempty(vers), vers = '?'; end; fprintf('EEGLAB: adding "%s" v%s (see >> help %s)\n', ... pluginlist(plugincount).plugin, vers, funcname); end; pluginlist(plugincount).status = status; plugincount = plugincount+1; end; end; end; global PLUGINLIST; PLUGINLIST = pluginlist; end; % iseeglabdeployed2 % Path exception for BIOSIG (sending BIOSIG down into the path) biosigpathlast; % fix str2double issue if ~ismatlab, return; end; % add other import ... % -------------------- cb_others = [ 'pophelp(''troubleshooting_data_formats'');' ]; uimenu( import_m, 'Label', 'Using the FILE-IO interface', 'CallBack', cb_fileio, 'separator', 'on'); uimenu( import_m, 'Label', 'Using the BIOSIG interface' , 'CallBack', cb_biosig); uimenu( import_m, 'Label', 'Troubleshooting data formats...', 'CallBack', cb_others); % changing plugin menu color % -------------------------- fourthsub_m = findobj('parent', tools_m); plotsub_m = findobj('parent', plot_m); importsub_m = findobj('parent', neuro_m); epochsub_m = findobj('parent', epoch_m); eventsub_m = findobj('parent', event_m); editsub_m = findobj('parent', edit_m); exportsub_m = findobj('parent', exportm); filter_m = findobj('parent', filter_m); icadefs; % containing PLUGINMENUCOLOR if length(fourthsub_m) > 11, set(fourthsub_m(1:end-11), 'foregroundcolor', PLUGINMENUCOLOR); end; if length(plotsub_m) > 17, set(plotsub_m (1:end-17), 'foregroundcolor', PLUGINMENUCOLOR); end; if length(importsub_m) > 9, set(importsub_m(1:end-9) , 'foregroundcolor', PLUGINMENUCOLOR); end; if length(epochsub_m ) > 3 , set(epochsub_m (1:end-3 ), 'foregroundcolor', PLUGINMENUCOLOR); end; if length(eventsub_m ) > 4 , set(eventsub_m (1:end-4 ), 'foregroundcolor', PLUGINMENUCOLOR); end; if length(exportsub_m) > 4 , set(exportsub_m(1:end-4 ), 'foregroundcolor', PLUGINMENUCOLOR); end; if length(editsub_m) > 10, set(editsub_m( 1:end-10), 'foregroundcolor', PLUGINMENUCOLOR); end; if length(filter_m) > 3 , set(filter_m (1:end-1 ), 'foregroundcolor', PLUGINMENUCOLOR); end; EEGMENU = uimenu( set_m, 'Label', '------', 'Enable', 'off'); eval('set(W_MAIN, ''userdat'', { EEGUSERDAT{1} EEGMENU javaobj });'); eeglab('redraw'); if nargout < 1 clear ALLEEG; end; %% automatic updater try [dummy eeglabVersionNumber currentReleaseDateString] = eeg_getversion; if isempty(eeglabVersionNumber) eeglabVersionNumber = 'dev'; end; eeglabUpdater = up.updater(eeglabVersionNumber, 'http://sccn.ucsd.edu/eeglab/updater/latest_version.php', 'EEGLAB', currentReleaseDateString); % create a new GUI item (e.g. under Help) %newerVersionMenu = uimenu(help_m, 'Label', 'Upgrade to the Latest Version', 'visible', 'off', 'userdata', 'startup:on;study:on'); % set the callback to bring up the updater GUI icadefs; % for getting background color eeglabFolder = fileparts(mywhich('eeglab.m')); %eeglabUpdater.menuItemHandle = []; %newerVersionMenu; %eeglabUpdater.menuItemCallback = {@command_on_update_menu_click, eeglabUpdater, eeglabFolder, true, BACKEEGLABCOLOR}; % place it in the base workspace. assignin('base', 'eeglabUpdater', eeglabUpdater); % only start timer if the function is called from the command line % (which means that the stack should only contain one element) stackVar = dbstack; if length(stackVar) == 1 if option_checkversion eeglabUpdater.checkForNewVersion({'eeglab_event' 'setup'}); if strcmpi(eeglabVersionNumber, 'dev') return; end; newMajorRevision = 0; if ~isempty(eeglabUpdater.newMajorRevision) fprintf('\nA new major version of EEGLAB (EEGLAB%s - beta) is now <a href="http://sccn.ucsd.edu/eeglab/">available</a>.\n', eeglabUpdater.newMajorRevision); newMajorRevision = 1; end; if eeglabUpdater.newerVersionIsAvailable eeglabv = num2str(eeglabUpdater.latestVersionNumber); posperiod = find(eeglabv == '.'); if isempty(posperiod), posperiod = length(eeglabv)+1; eeglabv = [ eeglabv '.0' ]; end; if length(eeglabv(posperiod+1:end)) < 2, eeglabv = [ eeglabv '0' ]; end; %if length(eeglabv(posperiod+1:end)) < 3, eeglabv = [ eeglabv '0' ]; end; eeglabv = [ eeglabv(1:posperiod+1) '.' eeglabv(posperiod+2) ]; %'.' eeglabv(posperiod+3) ]; stateWarning = warning('backtrace'); warning('backtrace', 'off'); if newMajorRevision fprintf('\n'); warning( sprintf(['\nA critical revision of EEGLAB%d (%s) is also available <a href="%s">here</a>\n' ... eeglabUpdater.releaseNotes 'See <a href="matlab: web(''%s'', ''-browser'')">Release notes</a> for more informations\n' ... 'You may disable this message in the Option menu but will miss critical updates.\n' ], ... floor(eeglabVersionNumber), eeglabv, eeglabUpdater.downloadUrl, ... [ 'http://sccn.ucsd.edu/wiki/EEGLAB_revision_history_version_13' ])); else warning( sprintf(['\nA newer version of EEGLAB (%s) is available <a href="%s">here</a>\n' ... eeglabUpdater.releaseNotes 'See <a href="matlab: web(''%s'', ''-browser'')">Release notes</a> for more informations.\n' ... 'You may disable this message in the Option menu but will miss critical updates.\n' ], ... eeglabv, eeglabUpdater.downloadUrl, ... [ 'http://sccn.ucsd.edu/wiki/EEGLAB_revision_history_version_13' ])); end; warning('backtrace', stateWarning.state); % make the Help menu item dark red set(help_m, 'foregroundColor', [0.6, 0 0]); elseif isempty(eeglabUpdater.lastTimeChecked) fprintf('Could not check for the latest EEGLAB version (internet may be disconnected).\n'); fprintf('To prevent long startup time, disable checking for new EEGLAB version (FIle > Memory and other options).\n'); else if ~newMajorRevision fprintf('You are using the latest version of EEGLAB.\n'); else fprintf('You are currently using the latest revision of EEGLAB%d (no critical update available).\n', floor(eeglabVersionNumber)); end; end; else eeglabtimers = timerfind('name', 'eeglabupdater'); if ~isempty(eeglabtimers) stop(eeglabtimers); delete(eeglabtimers); end; % This is disabled because it cause Matlab to hang in case % there is no connection or the connection is available but not % usable % start(timer('TimerFcn','try, eeglabUpdater.checkForNewVersion({''eeglab_event'' ''setup''}); catch, end; clear eeglabUpdater;', 'name', 'eeglabupdater', 'StartDelay', 20.0)); end; end; catch if option_checkversion fprintf('Updater could not be initialized.\n'); end; end; % REMOVED MENUS %uimenu( tools_m, 'Label', 'Automatic comp. reject', 'enable', 'off', 'CallBack', '[EEG LASTCOM] = pop_rejcomp(EEG); eegh(LASTCOM); if ~isempty(LASTCOM), eeg_store(CURRENTSET); end;'); %uimenu( tools_m, 'Label', 'Reject (synthesis)' , 'Separator', 'on', 'CallBack', '[EEG LASTCOM] = pop_rejall(EEG); eegh(LASTCOM); if ~isempty(LASTCOM), eeg_store; end; eeglab(''redraw'');'); function command_on_update_menu_click(callerHandle, tmp, eeglabUpdater, installDirectory, goOneFolderLevelIn, backGroundColor) postInstallCallbackString = 'clear all function functions; eeglab'; eeglabUpdater.launchGui(installDirectory, goOneFolderLevelIn, backGroundColor, postInstallCallbackString); % % -------------------- % draw the main figure % -------------------- function tb = eeg_mainfig(onearg); icadefs; COLOR = BACKEEGLABCOLOR; WINMINX = 17; WINMAXX = 260; WINYDEC = 13; NBLINES = 16; WINY = WINYDEC*NBLINES; javaChatFlag = 1; BORDERINT = 4; BORDEREXT = 10; comp = computer; if strcmpi(comp(1:3), 'GLN') || strcmpi(comp(1:3), 'MAC') || strcmpi(comp(1:3), 'PCW') FONTNAME = 'courier'; FONTSIZE = 8; % Magnify figure under MATLAB 2012a vers = version; dotPos = find(vers == '.'); vernum = str2num(vers(1:dotPos(1)-1)); subvernum = str2num(vers(dotPos(1)+1:dotPos(2)-1)); if vernum > 7 || (vernum >= 7 && subvernum >= 14) FONTSIZE = FONTSIZE+2; WINMAXX = WINMAXX*1.3; WINY = WINY*1.3; end; else FONTNAME = ''; FONTSIZE = 11; end; hh = findobj('tag', 'EEGLAB'); if ~isempty(hh) disp('EEGLAB warning: there can be only one EEGLAB window, closing old one'); close(hh); end; if strcmpi(onearg, 'remote') figure( 'name', [ 'EEGLAB v' eeg_getversion ], ... 'numbertitle', 'off', ... 'Position',[200 100 (WINMINX+WINMAXX+2*BORDERINT+2*BORDEREXT) 30 ], ... 'color', COLOR, ... 'Tag','EEGLAB', ... 'Userdata', {[] []}); %'resize', 'off', ... return; end; W_MAIN = figure('Units','points', ... ... % 'Colormap','gray', ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'name', [ 'EEGLAB v' eeg_getversion ], ... 'numbertitle', 'off', ... 'Position',[200 100 (WINMINX+WINMAXX+2*BORDERINT+2*BORDEREXT) (WINY+2*BORDERINT+2*BORDEREXT) ], ... 'color', COLOR, ... 'Tag','EEGLAB', ... 'visible', 'off', ... 'Userdata', {[] []}); % 'resize', 'off', ... % java chat eeglab_options; if option_chat == 1 if is_sccn disp('Starting chat...'); tmpp = fileparts(mywhich('startpane.m')); if isempty(tmpp) || ~ismatlab disp('Cannot start chat'); tb = []; else disp(' ----------------------------------- '); disp('| EEGLAB chat 0.9 |'); disp('| The chat currently only works |'); disp('| at the University of CA San Diego |'); disp(' ----------------------------------- '); javaaddpath(fullfile(tmpp, 'Chat_with_pane.jar')); eval('import client.EEGLABchat.*;'); eval('import client.VisualToolbar;'); eval('import java.awt.*;'); eval('import javax.swing.*;'); try tb = VisualToolbar('137.110.244.26'); F = W_MAIN; tb.setPreferredSize(Dimension(0, 75)); javacomponent(tb,'South',F); javaclose = ['userdat = get(gcbf, ''userdata'');' ... 'try,'... ' tb = userdat{3};' ... 'clear userdat; delete(gcbf); tb.close; clear tb;'... 'catch,end;']; set(gcf, 'CloseRequestFcn',javaclose); refresh(F); catch, tb = []; end; end; else tb = []; end; else tb = []; end; try, set(W_MAIN, 'NextPlot','new'); catch, end; if ismatlab BackgroundColor = get(gcf, 'color'); %[0.701960784313725 0.701960784313725 0.701960784313725]; H_MAIN(1) = uicontrol('Parent',W_MAIN, ... 'Units','points', ... 'BackgroundColor',COLOR, ... 'ListboxTop',0, ... 'HorizontalAlignment', 'left',... 'Position',[BORDEREXT BORDEREXT (WINMINX+WINMAXX+2*BORDERINT) (WINY)], ... 'Style','frame', ... 'Tag','Frame1'); set(H_MAIN(1), 'unit', 'normalized'); geometry = { [1] [1] [1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1] }; listui = { { 'style', 'text', 'string', 'Parameters of the current set', 'tag', 'win0' } { } ... { 'style', 'text', 'tag', 'win1', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win2', 'string', 'Channels per frame', 'userdata', 'datinfo'} ... { 'style', 'text', 'tag', 'val2', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win3', 'string', 'Frames per epoch', 'userdata', 'datinfo'} ... { 'style', 'text', 'tag', 'val3', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win4', 'string', 'Epochs', 'userdata', 'datinfo'} ... { 'style', 'text', 'tag', 'val4', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win5', 'string', 'Events', 'userdata', 'datinfo'} ... { 'style', 'text', 'tag', 'val5', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win6', 'string', 'Sampling rate (Hz)', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'val6', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win7', 'string', 'Epoch start (sec)', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'val7', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win8', 'string', 'Epoch end (sec)', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'val8', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win9', 'string', 'Average reference', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'val9', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win10', 'string', 'Channel locations', 'userdata', 'datinfo'} ... { 'style', 'text', 'tag', 'val10', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win11', 'string', 'ICA weights', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'val11', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win12', 'string', 'Dataset size (Mb)', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'val12', 'string', ' ', 'userdata', 'datinfo' } {} }; supergui(gcf, geometry, [], listui{:}); geometry = { [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] }; listui = { { } ... { } ... { 'style', 'text', 'tag', 'mainwin1', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin2', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin3', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin4', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin5', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin6', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin7', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin8', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin9', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin10', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin11', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin12', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin13', 'string', ' ', 'userdata', 'fullline' } {} }; supergui(gcf, geometry, [], listui{:}); titleh = findobj('parent', gcf, 'tag', 'win0'); alltexth = findobj('parent', gcf, 'style', 'text'); alltexth = setdiff_bc(alltexth, titleh); set(gcf, 'Position',[200 100 (WINMINX+WINMAXX+2*BORDERINT+2*BORDEREXT) (WINY+2*BORDERINT+2*BORDEREXT) ]); set(titleh, 'fontsize', TEXT_FONTSIZE_L, 'fontweight', 'bold'); set(alltexth, 'fontname', FONTNAME, 'fontsize', FONTSIZE); set(W_MAIN, 'visible', 'on'); end; return; % eeglab(''redraw'')() - Update EEGLAB menus based on values of global variables. % % Usage: >> eeglab(''redraw'')( ); % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeg_global(), eeglab() % WHEN THIS FUNCTION WAS SEPARATED % Revision 1.21 2002/04/23 19:09:25 arno % adding automatic dataset search % Revision 1.20 2002/04/18 20:02:23 arno % retrIeve % Revision 1.18 2002/04/18 16:28:28 scott % EEG.averef printed as 'Yes' or 'No' -sm % Revision 1.16 2002/04/18 16:03:15 scott % editted "Events/epoch info (nb) -> Events -sm % Revision 1.14 2002/04/18 14:46:58 scott % editted main window help msg -sm % Revision 1.10 2002/04/18 03:02:17 scott % edited opening instructions -sm % Revision 1.9 2002/04/11 18:23:33 arno % Oups, typo which crashed EEGLAB % Revision 1.8 2002/04/11 18:07:59 arno % adding average reference variable % Revision 1.7 2002/04/11 17:49:40 arno % corrected operator precedence problem % Revision 1.6 2002/04/11 15:36:55 scott % added parentheses to final ( - & - ), line 84. ARNO PLEASE CHECK -sm % Revision 1.5 2002/04/11 15:34:50 scott % put isempty(CURRENTSET) first in line ~80 -sm % Revision 1.4 2002/04/11 15:31:47 scott % added test isempty(CURRENTSET) line 78 -sm % Revision 1.3 2002/04/11 01:41:27 arno % checking dataset ... and inteligent menu update % Revision 1.2 2002/04/09 20:47:41 arno % introducing event number into gui function updatemenu(); eeg_global; W_MAIN = findobj('tag', 'EEGLAB'); EEGUSERDAT = get(W_MAIN, 'userdata'); H_MAIN = EEGUSERDAT{1}; EEGMENU = EEGUSERDAT{2}; if length(EEGUSERDAT) > 2 tb = EEGUSERDAT{3}; else tb = []; end; if ~isempty(tb) && ~isstr(tb) eval('tb.RefreshToolbar();'); end; if exist('CURRENTSET') ~= 1, CURRENTSET = 0; end; if isempty(ALLEEG), ALLEEG = []; end; if isempty(EEG), EEG = []; end; % test if the menu is present try figure(W_MAIN); set_m = findobj( 'parent', W_MAIN, 'Label', 'Datasets'); catch, return; end; index = 1; indexmenu = 1; MAX_SET = max(length( ALLEEG ), length(EEGMENU)-1); tmp = warning; warning off; clear functions; warning(tmp); eeglab_options; if isempty(ALLEEG) && ~isempty(EEG) && ~isempty(EEG.data) ALLEEG = EEG; end; % setting the dataset menu % ------------------------ while( index <= MAX_SET) try set( EEGMENU(index), 'Label', '------', 'checked', 'off'); catch, if mod(index, 30) == 0 tag = [ 'More (' int2str(index/30) ') ->' ]; tmp_m = findobj('label', tag); if isempty(tmp_m) set_m = uimenu( set_m, 'Label', tag, 'userdata', 'study:on'); else set_m = tmp_m; end; end; try set( EEGMENU(index), 'Label', '------', 'checked', 'off'); catch, EEGMENU(index) = uimenu( set_m, 'Label', '------', 'Enable', 'on'); end; end; set( EEGMENU(index), 'Enable', 'on', 'separator', 'off' ); try, ALLEEG(index).data; if ~isempty( ALLEEG(index).data) cb_retrieve = [ '[ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''retrieve'', ' int2str(index) ', ''study'', ~isempty(STUDY)+0);' ... 'if CURRENTSTUDY & ~isempty(LASTCOM), CURRENTSTUDY = 0; LASTCOM = [ ''CURRENTSTUDY = 0;'' LASTCOM ]; end; eegh(LASTCOM);' ... 'eeglab(''redraw'');' ]; menutitle = sprintf('Dataset %d:%s', index, ALLEEG(index).setname); set( EEGMENU(index), 'Label', menutitle, 'userdata', 'study:on'); set( EEGMENU(index), 'CallBack', cb_retrieve ); set( EEGMENU(index), 'Enable', 'on' ); if any(index == CURRENTSET), set( EEGMENU(index), 'checked', 'on' ); end; end; catch, end; index = index+1; end; hh = findobj( 'parent', set_m, 'Label', '------'); set(hh, 'Enable', 'off'); % menu for selecting several datasets % ----------------------------------- if index ~= 0 cb_select = [ 'nonempty = find(~cellfun(''isempty'', { ALLEEG.data } ));' ... 'tmpind = pop_chansel({ ALLEEG(nonempty).setname }, ''withindex'', nonempty);' ... 'if ~isempty(tmpind),' ... ' [ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''retrieve'', nonempty(tmpind), ''study'', ~isempty(STUDY)+0);' ... ' eegh(LASTCOM);' ... ' eeglab(''redraw'');' ... 'end;' ... 'clear tmpind nonempty;' ]; if MAX_SET == length(EEGMENU), EEGMENU(end+1) = uimenu( set_m, 'Label', '------', 'Enable', 'on'); end; set(EEGMENU(end), 'enable', 'on', 'Label', 'Select multiple datasets', ... 'callback', cb_select, 'separator', 'on', 'userdata', 'study:on'); end; % STUDY consistency % ----------------- exist_study = 0; if exist('STUDY') & exist('CURRENTSTUDY') % if study present, check study consistency with loaded datasets % -------------------------------------------------------------- if ~isempty(STUDY) if length(ALLEEG) > length(STUDY.datasetinfo) || ~isfield(ALLEEG, 'data') || any(cellfun('isempty', {ALLEEG.data})) if strcmpi(STUDY.saved, 'no') res = questdlg2( strvcat('The study is not compatible with the datasets present in memory', ... 'It is self consistent but EEGLAB is not be able to process it.', ... 'Do you wish to save the study as it is (EEGLAB will prompt you to', ... 'enter a file name) or do you wish to remove it'), 'Study inconsistency', 'Save and remove', 'Remove', 'Remove' ); if strcmpi(res, 'Remove') STUDY = []; CURRENTSTUDY = 0; else pop_savestudy(STUDY, ALLEEG); STUDY = []; CURRENTSTUDY = 0; end; else warndlg2( strvcat('The study was not compatible any more with the datasets present in memory.', ... 'Since it had not changed since last saved, it was simply removed from', ... 'memory.') ); STUDY = []; CURRENTSTUDY = 0; end; end; end; if ~isempty(STUDY) exist_study = 1; end; end; % menu for selecting STUDY set % ---------------------------- if exist_study cb_select = [ '[ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''retrieve'', [STUDY.datasetinfo.index], ''study'', 1);' ... 'if ~isempty(LASTCOM), CURRENTSTUDY = 1; LASTCOM = [ LASTCOM ''CURRENTSTUDY = 1;'' ]; end;' ... 'eegh(LASTCOM);' ... 'eeglab(''redraw'');' ]; tmp_m = findobj('label', 'Select the study set'); delete(tmp_m); % in case it is not at the end tmp_m = uimenu( set_m, 'Label', 'Select the study set', 'Enable', 'on', 'userdata', 'study:on'); set(tmp_m, 'enable', 'on', 'callback', cb_select, 'separator', 'on'); else delete( findobj('label', 'Select the study set') ); end; EEGUSERDAT{2} = EEGMENU; set(W_MAIN, 'userdata', EEGUSERDAT); if (isempty(CURRENTSET) | length(ALLEEG) < CURRENTSET(1) | CURRENTSET(1) == 0 | isempty(ALLEEG(CURRENTSET(1)).data)) CURRENTSET = 0; for index = 1:length(ALLEEG) if ~isempty(ALLEEG(index).data) CURRENTSET = index; break; end; end; if CURRENTSET ~= 0 eegh([ '[EEG ALLEEG CURRENTSET] = eeg_retrieve(ALLEEG,' int2str(CURRENTSET) ');' ]) [EEG ALLEEG] = eeg_retrieve(ALLEEG, CURRENTSET); else EEG = eeg_emptyset; end; end; if (isempty(EEG) | isempty(EEG(1).data)) & CURRENTSET(1) ~= 0 eegh([ '[EEG ALLEEG CURRENTSET] = eeg_retrieve(ALLEEG,' int2str(CURRENTSET) ');' ]) [EEG ALLEEG] = eeg_retrieve(ALLEEG, CURRENTSET); end; % test if dataset has changed % --------------------------- if length(EEG) == 1 if ~isempty(ALLEEG) & CURRENTSET~= 0 & ~isequal(EEG.data, ALLEEG(CURRENTSET).data) & ~isnan(EEG.data(1)) % the above comparison does not work for ome structures %tmpanswer = questdlg2(strvcat('The current EEG dataset has changed. What should eeglab do with the changes?', ' '), ... % 'Dataset change detected', ... % 'Keep changes', 'Delete changes', 'New dataset', 'Make new dataset'); disp('Warning: for some reason, the backup dataset in EEGLAB memory does not'); disp(' match the current dataset. The dataset in memory has been overwritten'); [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET); eegh('[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);'); %if tmpanswer(1) == 'D' % delete changes % [EEG ALLEEG] = eeg_retrieve(ALLEEG, CURRENTSET); % eegh('[EEG ALLEEG] = eeg_retrieve( ALLEEG, CURRENTSET);'); %elseif tmpanswer(1) == 'K' % keep changes % [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET); % eegh('[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);'); %else % make new dataset % [ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET); % eegh(LASTCOM); % MAX_SET = max(length( ALLEEG ), length(EEGMENU)); %end; end; end; % print some information on the main figure % ------------------------------------------ g = myguihandles(gcf); if ~isfield(g, 'win0') % no display return; end; study_selected = 0; if exist('STUDY') & exist('CURRENTSTUDY') if CURRENTSTUDY == 1, study_selected = 1; end; end; menustatus = {}; if study_selected menustatus = { menustatus{:} 'study' }; hh = findobj('parent', gcf, 'userdata', 'fullline'); set(hh, 'visible', 'off'); hh = findobj('parent', gcf, 'userdata', 'datinfo'); set(hh, 'visible', 'on'); % head string % ----------- set( g.win0, 'String', sprintf('STUDY set: %s', STUDY.name) ); % dataset type % ------------ datasettype = unique_bc( [ EEG.trials ] ); if datasettype(1) == 1 & length(datasettype) == 1, datasettype = 'continuous'; elseif datasettype(1) == 1, datasettype = 'epoched and continuous'; else datasettype = 'epoched'; end; % number of channels and channel locations % ---------------------------------------- chanlen = unique_bc( [ EEG.nbchan ] ); chanlenstr = vararg2str( mattocell(chanlen) ); anyempty = unique_bc( cellfun( 'isempty', { EEG.chanlocs }) ); if length(anyempty) == 2, chanlocs = 'mixed, yes and no'; elseif anyempty == 0, chanlocs = 'yes'; else chanlocs = 'no'; end; % ica weights % ----------- anyempty = unique_bc( cellfun( 'isempty', { EEG.icaweights }) ); if length(anyempty) == 2, studystatus = 'Missing ICA dec.'; elseif anyempty == 0, studystatus = 'Ready to precluster'; else studystatus = 'Missing ICA dec.'; end; % consistency & other parameters % ------------------------------ [EEG epochconsist] = eeg_checkset(EEG, 'epochconsist'); % epoch consistency [EEG chanconsist ] = eeg_checkset(EEG, 'chanconsist'); % channel consistency [EEG icaconsist ] = eeg_checkset(EEG, 'icaconsist'); % ICA consistency totevents = num2str(sum( cellfun( 'length', { EEG.event }) )); % total number of events totsize = whos('STUDY', 'ALLEEG'); % total size if isempty(STUDY.session), sessionstr = ''; else sessionstr = vararg2str(STUDY.session); end; if isempty(STUDY.condition), condstr = ''; else condstr = vararg2str(STUDY.condition); end; % determine study status % ---------------------- if isfield(STUDY.etc, 'preclust') if ~isempty( STUDY.etc.preclust ) studystatus = 'Pre-clustered'; elseif length(STUDY.cluster) > 1 studystatus = 'Clustered'; end; elseif length(STUDY.cluster) > 1 studystatus = 'Clustered'; end; % text % ---- set( g.win2, 'String', 'Study task name'); set( g.win3, 'String', 'Nb of subjects'); set( g.win4, 'String', 'Nb of conditions'); set( g.win5, 'String', 'Nb of sessions'); set( g.win6, 'String', 'Nb of groups'); set( g.win7, 'String', 'Epoch consistency'); set( g.win8, 'String', 'Channels per frame'); set( g.win9, 'String', 'Channel locations'); set( g.win10, 'String', 'Clusters'); set( g.win11, 'String', 'Status'); set( g.win12, 'String', 'Total size (Mb)'); % values % ------ fullfilename = fullfile( STUDY.filepath, STUDY.filename); if length(fullfilename) > 26 set( g.win1, 'String', sprintf('Study filename: ...%s\n', fullfilename(max(1,length(fullfilename)-26):end) )); else set( g.win1, 'String', sprintf('Study filename: %s\n' , fullfilename)); end; condconsist = std_checkconsist(STUDY, 'uniform', 'condition'); groupconsist = std_checkconsist(STUDY, 'uniform', 'group'); sessconsist = std_checkconsist(STUDY, 'uniform', 'session'); txtcond = fastif(condconsist , ' per subject', ' (some missing)'); txtgroup = fastif(groupconsist, ' per subject', ' (some missing)'); txtsess = fastif(sessconsist , ' per subject', ' (some missing)'); set( g.val2, 'String', STUDY.task); set( g.val3, 'String', int2str(max(1, length(STUDY.subject)))); set( g.val4, 'String', [ int2str(max(1, length(STUDY.condition))) txtcond ]); set( g.val5, 'String', [ int2str(max(1, length(STUDY.session))) txtsess ]); set( g.val6, 'String', [ int2str(max(1, length(STUDY.group))) txtgroup ]); set( g.val7, 'String', epochconsist); set( g.val8, 'String', chanlenstr); set( g.val9, 'String', chanlocs); set( g.val10, 'String', length(STUDY.cluster)); set( g.val11, 'String', studystatus); set( g.val12, 'String', num2str(round(sum( [ totsize.bytes] )/1E6*10)/10)); elseif (exist('EEG') == 1) & ~isnumeric(EEG) & ~isempty(EEG(1).data) hh = findobj('parent', gcf, 'userdata', 'fullline'); set(hh, 'visible', 'off'); hh = findobj('parent', gcf, 'userdata', 'datinfo'); set(hh, 'visible', 'on'); if length(EEG) > 1 % several datasets menustatus = { menustatus{:} 'multiple_datasets' }; % head string % ----------- strsetnum = 'Datasets '; for i = CURRENTSET strsetnum = [ strsetnum int2str(i) ',' ]; end; strsetnum = strsetnum(1:end-1); set( g.win0, 'String', strsetnum); % dataset type % ------------ datasettype = unique_bc( [ EEG.trials ] ); if datasettype(1) == 1 & length(datasettype) == 1, datasettype = 'continuous'; elseif datasettype(1) == 1, datasettype = 'epoched and continuous'; else datasettype = 'epoched'; end; % number of channels and channel locations % ---------------------------------------- chanlen = unique_bc( [ EEG.nbchan ] ); chanlenstr = vararg2str( mattocell(chanlen) ); anyempty = unique_bc( cellfun( 'isempty', { EEG.chanlocs }) ); if length(anyempty) == 2, chanlocs = 'mixed, yes and no'; elseif anyempty == 0, chanlocs = 'yes'; else chanlocs = 'no'; end; % ica weights % ----------- anyempty = unique_bc( cellfun( 'isempty', { EEG.icaweights }) ); if length(anyempty) == 2, icaweights = 'mixed, yes and no'; elseif anyempty == 0, icaweights = 'yes'; else icaweights = 'no'; end; % consistency & other parameters % ------------------------------ [EEG epochconsist] = eeg_checkset(EEG, 'epochconsist'); % epoch consistency [EEG chanconsist ] = eeg_checkset(EEG, 'chanconsist'); % channel consistency [EEG icaconsist ] = eeg_checkset(EEG, 'icaconsist'); % ICA consistency totevents = num2str(sum( cellfun( 'length', { EEG.event }) )); % total number of events srate = vararg2str( mattocell( unique( [ EEG.srate ] ) )); % sampling rate totsize = whos('EEG'); % total size % text % ---- set( g.win2, 'String', 'Number of datasets'); set( g.win3, 'String', 'Dataset type'); set( g.win4, 'String', 'Epoch consistency'); set( g.win5, 'String', 'Channels per frame'); set( g.win6, 'String', 'Channel consistency'); set( g.win7, 'String', 'Channel locations'); set( g.win8, 'String', 'Events (total)'); set( g.win9, 'String', 'Sampling rate (Hz)'); set( g.win10, 'String', 'ICA weights'); set( g.win11, 'String', 'Identical ICA'); set( g.win12, 'String', 'Total size (Mb)'); % values % ------ set( g.win1, 'String', sprintf('Groupname: -(soon)-\n')); set( g.val2, 'String', int2str(length(EEG))); set( g.val3, 'String', datasettype); set( g.val4, 'String', epochconsist); set( g.val5, 'String', chanlenstr); set( g.val6, 'String', chanconsist); set( g.val7, 'String', chanlocs); set( g.val8, 'String', totevents); set( g.val9, 'String', srate); set( g.val10, 'String', icaweights); set( g.val11, 'String', icaconsist); set( g.val12, 'String', num2str(round(totsize.bytes/1E6*10)/10)); else % one continous dataset selected menustatus = { menustatus{:} 'continuous_dataset' }; % text % ---- set( g.win2, 'String', 'Channels per frame'); set( g.win3, 'String', 'Frames per epoch'); set( g.win4, 'String', 'Epochs'); set( g.win5, 'String', 'Events'); set( g.win6, 'String', 'Sampling rate (Hz)'); set( g.win7, 'String', 'Epoch start (sec)'); set( g.win8, 'String', 'Epoch end (sec)'); set( g.win9, 'String', 'Reference'); set( g.win10, 'String', 'Channel locations'); set( g.win11, 'String', 'ICA weights'); set( g.win12, 'String', 'Dataset size (Mb)'); if CURRENTSET == 0, strsetnum = ''; else strsetnum = ['#' int2str(CURRENTSET) ': ']; end; maxchar = 28; if ~isempty( EEG.setname ) if length(EEG.setname) > maxchar+2 set( g.win0, 'String', [strsetnum EEG.setname(1:min(maxchar,length(EEG.setname))) '...' ]); else set( g.win0, 'String', [strsetnum EEG.setname ]); end; else set( g.win0, 'String', [strsetnum '(no dataset name)' ] ); end; fullfilename = fullfile(EEG.filepath, EEG.filename); if ~isempty(fullfilename) if length(fullfilename) > 26 set( g.win1, 'String', sprintf('Filename: ...%s\n', fullfilename(max(1,length(fullfilename)-26):end) )); else set( g.win1, 'String', sprintf('Filename: %s\n', fullfilename)); end; else set( g.win1, 'String', sprintf('Filename: none\n')); end; set( g.val2, 'String', int2str(fastif(isempty(EEG.data), 0, size(EEG.data,1)))); set( g.val3, 'String', int2str(EEG.pnts)); set( g.val4, 'String', int2str(EEG.trials)); set( g.val5, 'String', fastif(isempty(EEG.event), 'none', int2str(length(EEG.event)))); set( g.val6, 'String', int2str( round(EEG.srate)) ); if round(EEG.xmin) == EEG.xmin & round(EEG.xmax) == EEG.xmax set( g.val7, 'String', sprintf('%d\n', EEG.xmin)); set( g.val8, 'String', sprintf('%d\n', EEG.xmax)); else set( g.val7, 'String', sprintf('%6.3f\n', EEG.xmin)); set( g.val8, 'String', sprintf('%6.3f\n', EEG.xmax)); end; % reference if isfield(EEG(1).chanlocs, 'ref') [curref tmp allinds] = unique_bc( { EEG(1).chanlocs.ref }); maxind = 1; for ind = unique_bc(allinds) if length(find(allinds == ind)) > length(find(allinds == maxind)) maxind = ind; end; end; curref = curref{maxind}; if isempty(curref), curref = 'unknown'; end; else curref = 'unknown'; end; set( g.val9, 'String', curref); if isempty(EEG.chanlocs) set( g.val10, 'String', 'No'); else if ~isfield(EEG.chanlocs, 'theta') | all(cellfun('isempty', { EEG.chanlocs.theta })) set( g.val10, 'String', 'No (labels only)'); else set( g.val10, 'String', 'Yes'); end; end; set( g.val11, 'String', fastif(isempty(EEG.icasphere), 'No', 'Yes')); tmp = whos('EEG'); if ~isa(EEG.data, 'memmapdata') && ~isa(EEG.data, 'mmo') set( g.val12, 'String', num2str(round(tmp.bytes/1E6*10)/10)); else set( g.val12, 'String', [ num2str(round(tmp.bytes/1E6*10)/10) ' (file mapped)' ]); end; if EEG.trials > 1 || EEG.xmin ~= 0 menustatus = { menustatus{:} 'epoched_dataset' }; else menustatus = { menustatus{:} 'continuous_dataset' }; end if ~isfield(EEG.chanlocs, 'theta') menustatus = { menustatus{:} 'chanloc_absent' }; end; if isempty(EEG.icaweights) menustatus = { menustatus{:} 'ica_absent' }; end; end; else menustatus = { menustatus{:} 'startup' }; hh = findobj('parent', gcf, 'userdata', 'fullline'); set(hh, 'visible', 'on'); hh = findobj('parent', gcf, 'userdata', 'datinfo'); set(hh, 'visible', 'off'); set( g.win0, 'String', 'No current dataset'); set( g.mainwin1, 'String', '- Create a new or load an existing dataset:'); set( g.mainwin2, 'String', ' Use "File > Import data" (new)'); set( g.mainwin3, 'String', ' Or "File > Load existing dataset" (old)'); set( g.mainwin4, 'String', '- If new,'); set( g.mainwin5, 'String', ' "File > Import epoch info" (data epochs) else'); set( g.mainwin6, 'String', ' "File > Import event info" (continuous data)'); set( g.mainwin7, 'String', ' "Edit > Dataset info" (add/edit dataset info)'); set( g.mainwin8, 'String', ' "File > Save dataset" (save dataset)'); set( g.mainwin9, 'String', '- Prune data: "Edit > Select data"'); set( g.mainwin10,'String', '- Reject data: "Tools > Reject continuous data"'); set( g.mainwin11,'String', '- Epoch data: "Tools > Extract epochs"'); set( g.mainwin12,'String', '- Remove baseline: "Tools > Remove baseline"'); set( g.mainwin13,'String', '- Run ICA: "Tools > Run ICA"'); end; % ERPLAB if exist('ALLERP') == 1 && ~isempty(ALLERP) menustatus = { menustatus{:} 'erp_dataset' }; end; % enable selected menu items % -------------------------- allmenus = findobj( W_MAIN, 'type', 'uimenu'); allstrs = get(allmenus, 'userdata'); if any(strcmp(menustatus, 'startup')) set(allmenus, 'enable', 'on'); eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''startup:off''))), allstrs);'); set(allmenus(indmatchvar), 'enable', 'off'); elseif any(strcmp(menustatus, 'study')) eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''study:on''))), allstrs);'); set(allmenus , 'enable', 'off'); set(allmenus(indmatchvar), 'enable', 'on'); elseif any(strcmp(menustatus, 'multiple_datasets')) eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''study:on''))), allstrs);'); set(allmenus , 'enable', 'off'); set(allmenus(indmatchvar), 'enable', 'on'); set(findobj('parent', W_MAIN, 'label', 'Study'), 'enable', 'off'); % -------------------------------- % Javier Lopez-Calderon for ERPLAB elseif any(strcmp(menustatus, 'epoched_dataset')) set(allmenus, 'enable', 'on'); eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''epoch:off''))), allstrs);'); set(allmenus(indmatchvar), 'enable', 'off'); % end, Javier Lopez-Calderon for ERPLAB % -------------------------------- elseif any(strcmp(menustatus, 'continuous_dataset')) set(allmenus, 'enable', 'on'); eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''continuous:off''))), allstrs);'); set(allmenus(indmatchvar), 'enable', 'off'); end; if any(strcmp(menustatus, 'chanloc_absent')) eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''chanloc:on''))), allstrs);'); set(allmenus(indmatchvar), 'enable', 'off'); end; if any(strcmp(menustatus, 'ica_absent')) eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''ica:on''))), allstrs);'); set(allmenus(indmatchvar), 'enable', 'off'); end; % -------------------------------- % Javier Lopez-Calderon for ERPLAB if any(strcmp(menustatus, 'erp_dataset')) eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''erpset:on''))), allstrs);'); set(allmenus(indmatchvar), 'enable', 'on'); end % end, Javier Lopez-Calderon for ERPLAB % -------------------------------- % adjust title extent % ------------------- poswin0 = get(g.win0, 'position'); extwin0 = get(g.win0, 'extent'); set(g.win0, 'position', [poswin0(1:2) extwin0(3) extwin0(4)]); % adjust all font sizes (RMC fix MATLAB 2014 compatibility) % ------------------- handlesname = fieldnames(g); for i = 1:length(handlesname) if isprop(eval(['g.' handlesname{i}]),'Style') & ~strcmp(handlesname{i},'win0') propval = get(eval(['g.' handlesname{i}]), 'Style'); if strcmp(propval,'text') set(eval(['g.' handlesname{i}]),'FontSize',TEXT_FONTSIZE); end end 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 g = myguihandles(fig) g = []; hh = findobj('parent', gcf); for index = 1:length(hh) if ~isempty(get(hh(index), 'tag')) g = setfield(g, get(hh(index), 'tag'), hh(index)); end; end; function rmpathifpresent(newpath); comp = computer; if strcmpi(comp(1:2), 'PC') newpath = [ newpath ';' ]; else newpath = [ newpath ':' ]; end; if ismatlab p = matlabpath; else p = path; end; ind = strfind(p, newpath); if ~isempty(ind) rmpath(newpath); end; % add path only if it is not already in the list % ---------------------------------------------- function addpathifnotinlist(newpath); comp = computer; if strcmpi(comp(1:2), 'PC') newpathtest = [ newpath ';' ]; else newpathtest = [ newpath ':' ]; end; if ismatlab p = matlabpath; else p = path; end; ind = strfind(p, newpathtest); if isempty(ind) if exist(newpath) == 7 addpath(newpath); end; end; function addpathifnotexist(newpath, functionname); tmpp = mywhich(functionname); if isempty(tmpp) addpath(newpath); end; % find a function path and add path if not present % ------------------------------------------------ function myaddpath(eeglabpath, functionname, pathtoadd); tmpp = mywhich(functionname); tmpnewpath = [ eeglabpath 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 ]); addpathifnotinlist(tmpnewpath); end; function val = iseeglabdeployed2; %val = 1; return; if exist('isdeployed') val = isdeployed; else val = 0; end; function buildhelpmenu; % parse plugin function name % -------------------------- function [name, vers] = parsepluginname(dirName); ind = find( dirName >= '0' & dirName <= '9' ); if isempty(ind) name = dirName; vers = ''; else ind = length(dirName); while ind > 0 && ((dirName(ind) >= '0' & dirName(ind) <= '9') || dirName(ind) == '.' || dirName(ind) == '_') ind = ind - 1; end; name = dirName(1:ind); vers = dirName(ind+1:end); vers(find(vers == '_')) = '.'; end; % required here because path not added yet % to the admin folder function res = ismatlab; v = version; if v(1) > '4' res = 1; else res = 0; end; function res = mywhich(varargin); try res = which(varargin{:}); catch fprintf('Warning: permission error accesssing %s\n', varargin{1}); end;
github
lcnhappe/happe-master
WriteMatrix2Text.m
.m
happe-master/Packages/eeglab14_0_0b/CSDtoolbox/func/WriteMatrix2Text.m
1,415
utf_8
40fcf238991341aab27833a32ab9aeb5
% function WriteMatrix2Text ( X, FileName, FmtStg, CaseCol ) % % This is a generic routine to write a data matrix to an ASCII file. % % Usage: WriteMatrix2Text ( X, FileName, FmtStg, CaseCol ); % % Input arguments: X data matrix % FileName file name string % FmtStg formating string (default = '%9.3f') % CaseCol numeric value indicating column offset % requesting to also list case numbers % (default = 0 to suppress case numbers) % % Updated: $Date: 2009/05/15 15:55:00 $ $Author: jk $ % function WriteMatrix2File ( X, FileName, FmtStg, CaseCol ) if nargin < 2 help WriteMatrix2Text disp('*** Error: Specify at least <X> and <FileName> as input'); return end if nargin < 3 FmtStg = '%9.3f'; end; if nargin < 4 CaseCol = 0; end; disp(sprintf('Creating formatted (%s) matrix text file: %s',FmtStg,FileName)); if CaseCol > 0 disp(sprintf('Adding case numbers (%d chars)',CaseCol)); end; fid = fopen(FileName,'w'); % open output file for write for n = 1:size(X,1); if CaseCol > 0 fprintf(fid, strcat('%',int2str(CaseCol),'d'), n); % print case# end fprintf(fid, FmtStg, X(n,:) ); % print all columns fprintf(fid, char([13 10]) ); % print carriage return end; fclose(fid); % close output file
github
lcnhappe/happe-master
display.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@memmapdata/display.m
1,180
utf_8
d3d679b5764eca6d062540923f669f7b
% display() - display an EEG data class underlying structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 b = display(a) i.type = '()'; i.subs = { ':' ':' ':' }; b = subsref(a, i); % note that subsref cannot be called directly return; %struct(a) %return; if ~strcmpi(a.fileformat, 'transposed') a.data.data.x; else permute(a, [3 1 2]); end;
github
lcnhappe/happe-master
reshape.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@memmapdata/reshape.m
1,449
utf_8
d59a7e256f6fc43fe77f3be9319fcc46
% reshape() - reshape of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 a = reshape(a,d1,d2,d3) % decode length % ------------- if nargin > 3 d1 = [ d1 d2 d3 ]; elseif nargin > 2 d1 = [ d1 d2 ]; end; if prod(size(a)) ~= prod(d1) error('Wrong dimensions for reshaping'); end; if ~strcmpi(a.fileformat, 'transposed') a.data.format{2} = d1; else if length(d1) == 1 a.data.format{2} = d1; elseif length(d1) == 2 a.data.format{2} = [d1(2) d1(1)]; else a.data.format{2} = d1([2 3 1]); end; end;
github
lcnhappe/happe-master
end.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@memmapdata/end.m
901
utf_8
0e38d125a547083cb574fbd3bb455fbd
% end() - last index to memmapdata array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 s = end(a, k, n); s = size(a, k);
github
lcnhappe/happe-master
subsasgn.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@memmapdata/subsasgn.m
1,590
utf_8
6b2894eb17dab5aae0637b84992ffb7d
% subsasgn() - define index assignment for eegdata objects % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 b = subsasgn(a,index,val) i.type = '()'; i.subs = { ':' ':' ':' }; b = subsref(a, i); % note that subsref cannot be called directly c = subsref(val, i); b = builtin('subsasgn', b, index, c); return; switch index.type case '()' switch length(index.subs) case 1, a.data(index.subs{1}) = val; case 2, a.data(index.subs{1}, index.subs{2}) = val; case 3, a.data(index.subs{1}, index.subs{2}, index.subs{3}) = val; case 4, a.data(index.subs{1}, index.subs{2}, index.subs{3}, index.subs{4}) = val; end; case '.' switch index.subs case 'srate' a.srate = val; case 'nbchan' a.nbchan = val; otherwise error('Invalid field name') end end
github
lcnhappe/happe-master
isnumeric.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@memmapdata/isnumeric.m
877
utf_8
34baf204e1b984ee69cf7f462fe2e524
% isnumeric() - returns 1 % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 r = isnumeric(a) r = 1;
github
lcnhappe/happe-master
length.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@memmapdata/length.m
913
utf_8
f0841237745a123f3215e00164cc4a1a
% length() - length of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 s = length(a) s = size(a,1);
github
lcnhappe/happe-master
sum.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@memmapdata/sum.m
1,913
utf_8
dbd7353e16ccf6a1a0b69875cd9050cb
% sum() - sum of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 [s] = sum(a,dim) if nargin < 2 dim = 1; end; %b = (:,:,:); if ~strcmpi(a.fileformat, 'transposed') s = sum(a.data.data.x, dim); else alldim = [3 1 2]; if length(size(a)) == 3 dim = alldim(dim); s = sum(a.data.data.x, dim); s = permute(s, [3 1 2]); else if dim == 1 dim = 2; else dim = 1; end; s = sum(a.data.data.x, dim)'; end; end; return; % do pnts by pnts if dim = 1 % if dim == 1 & length( % % s = zeros(size(a,2), size(a,3)); % for i=1:size(a,2) % s(i,:) = mean(a.data.data.x(:,i,:)); % end; % elseif dim == 1 % s = zeros(size(a,1), size(a,1)); % for i=1:size(a,1) % s(i,:) = mean(a.data.data.x(:,:,:)); % end; % % % s = builtin('sum', rand(10,10), dim); %if length(size(a)) > 2 %else s = sum(a(:,:,:), dim); %end;
github
lcnhappe/happe-master
size.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@memmapdata/size.m
1,383
utf_8
c7033b3ab1405ded2c8794f2c214beb9
% size() - size of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 [s s2 s3] = size(a,dim) if isnumeric(a.data), s = size(a.data) else s = a.data.format{2}; if strcmpi(a.fileformat, 'transposed') if length(s) == 2, s = s([2 1]); elseif length(s) == 3 s = [s(3) s(1) s(2)]; end; end; end; if nargin > 1 s = [s 1]; s = s(dim); end; if nargout > 2 s3 = s(3); end; if nargout > 1 s2 = s(2); s = s(1); end;
github
lcnhappe/happe-master
subsref.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@memmapdata/subsref.m
4,622
utf_8
096fd75b6454f11ffee5a172000a64c1
% subsref() - index eegdata class % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 b = subsref(a,s) if s(1).type == '.' b = builtin('subsref', struct(a), s); return; end; subs = s(1).subs; finaldim = cellfun('length', subs); % one dimension input % ------------------- if length(s(1).subs) == 1 if isstr(subs{1}) subs{1} = [1:size(a,1)]; subs{2} = [1:size(a,2)]; if ndims(a) == 3, subs{3} = [1:size(a,3)]; end; finaldim = prod(size(a)); end; % two dimension input % ------------------- elseif length(s(1).subs) == 2 if isstr(subs{1}), subs{1} = [1:size(a,1)]; end; if isstr(subs{2}), subs{2} = [1:size(a,2)]; if ndims(a) == 3, subs{3} = [1:size(a,3)]; end; end; if length(subs) == 3 finaldim = [ length(subs{1}) length(subs{2})*length(subs{3}) ]; else finaldim = [ length(subs{1}) length(subs{2}) ]; end; % three dimension input % --------------------- elseif length(s(1).subs) == 3 if isstr(subs{1}), subs{1} = [1:size(a,1)]; end; if isstr(subs{2}), subs{2} = [1:size(a,2)]; end; if ndims(a) == 2, subs(3) = []; else if isstr(subs{3}), subs{3} = [1:size(a,3)]; end; end; finaldim = cellfun('length', subs); end; % non-transposed data % ------------------- if ~strcmpi(a.fileformat, 'transposed') if length(subs) == 1, b = a.data.data.x(subs{1}); end; if length(subs) == 2, b = a.data.data.x(subs{1}, subs{2}); end; if length(subs) == 3, b = a.data.data.x(subs{1}, subs{2}, subs{3}); end; else if ndims(a) == 2 %if length(s) == 0, b = transpose(a.data.data.x); return; end; if length(s(1).subs) == 1, b = a.data.data.x(s(1).subs{1})'; end; if length(s(1).subs) == 2, b = a.data.data.x(s(1).subs{2}, s(1).subs{1})'; end; if length(s(1).subs) == 3, b = a.data.data.x(s(1).subs{2}, s(1).subs{1})'; end; else %if length(s) == 0, b = permute(a.data.data.x, [3 1 2]); return; end; if length(subs) == 1, inds1 = mod(subs{1}-1, size(a,1))+1; inds2 = mod((subs{1}-inds1)/size(a,1), size(a,2))+1; inds3 = ((subs{1}-inds1)/size(a,1)-inds2+1)/size(a,2)+1; inds = (inds1-1)*size(a,2)*size(a,3) + (inds3-1)*size(a,2) + inds2; b = a.data.data.x(inds); else if length(subs) < 2, subs{3} = 1; end; % repmat if several indices in different dimensions % ------------------------------------------------- len = cellfun('length', subs); subs{1} = repmat(reshape(subs{1}, [len(1) 1 1]), [1 len(2) len(3)]); subs{2} = repmat(reshape(subs{2}, [1 len(2) 1]), [len(1) 1 len(3)]); subs{3} = repmat(reshape(subs{3}, [1 1 len(3)]), [len(1) len(2) 1]); inds = (subs{1}-1)*a.data.Format{2}(1)*a.data.Format{2}(2) + (subs{3}-1)*a.data.Format{2}(1) + subs{2}; inds = reshape(inds, [1 prod(size(inds))]); b = a.data.data.x(inds); end; end; end; if length(finaldim) == 1, finaldim(2) = 1; end; b = reshape(b, finaldim); % 2 dims %inds1 = mod(myinds-1, size(a,1))+1; %inds2 = (myinds-inds1)/size(a,1)+1; %inds = (inds2-1)*size(a,1) + inds1; % 3 dims %inds1 = mod(myinds-1, size(a,1))+1; %inds2 = mod((myinds-inds1)/size(a,1), size(a,2))+1; %inds3 = ((myinds-inds1)/size(a,1)-inds2)/size(a,2)+1; %inds = (inds3-1)*size(a,1)*size(a,2) + inds2*size(a,1) + inds1;
github
lcnhappe/happe-master
ndims.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@memmapdata/ndims.m
1,169
utf_8
8c3ed2dde450e1422a2552d22e9c150b
% ndims() - number of dimension of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 s = ndims(a) if ~strcmpi(a.fileformat, 'transposed') if a.data.Format{2}(3) == 1, s = 2; else s = 3; end; else if a.data.Format{2}(2) == 1, s = 2; else s = 3; end; end;
github
lcnhappe/happe-master
memmapdata.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@memmapdata/memmapdata.m
1,994
utf_8
5f967fcb7b637954900e09789144dde6
% memmapdata() - create a memory-mapped data class % % Usage: % >> data_class = memmapdata(data); % % Inputs: % data - input data or data file % % Outputs: % data_class - output dataset class % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 dataout = memmapdata(data, datadims); dataout.fileformat = 'normal'; if isstr(data) if length(data) > 3 if strcmpi('.dat', data(end-3:end)) dataout.fileformat = 'transposed'; end; end; % check that the file is not empty % -------------------------------- a = dir(data); if isempty(a) error([ 'Data file ''' data '''not found' ]); elseif a(1).bytes == 0 error([ 'Empty data file ''' data '''' ]); end; if ~strcmpi(dataout.fileformat, 'transposed') dataout.data = memmapfile(data, 'writable', false, 'format', { 'single' datadims 'x' }); else dataout.data = memmapfile(data, 'writable', false, 'format', { 'single' [ datadims(2:end) datadims(1) ] 'x' }); end; dataout = class(dataout,'memmapdata'); else dataout = data; end;
github
lcnhappe/happe-master
display.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/display.m
1,161
utf_8
b43db5e3387d5dcb39fafa9aa03939f9
% display() - display an EEG data class underlying structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 display(obj); tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); if obj.transposed, disp('Warning: data does not display properly for memory mapped file which have been transposed'); end; disp(tmpMMO.data.x);
github
lcnhappe/happe-master
reshape.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/reshape.m
1,242
utf_8
cc03295fbaa6179eb2e8b266daf6b644
% reshape() - reshape of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 obj = reshape(obj,d1,d2,d3) % decode length % ------------- if nargin > 3 d1 = [ d1 d2 d3 ]; elseif nargin > 2 d1 = [ d1 d2 ]; end; if prod(size(obj)) ~= prod(d1) error('Wrong dimensions for reshaping'); end; if obj.transposed d1 = [d1(2:end) d1(1)]; end; obj.dimensions = d1;
github
lcnhappe/happe-master
subsasgn_old.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/subsasgn_old.m
9,802
utf_8
0fc68a1bfa60e3118b3a4b6efd10fa52
% subsasgn() - define index assignment for eegdata objects % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 obj = subsasgn(obj,ss,val) % check stack % ----------- stack = dbstack; stack(1) = []; stack = rmfield(stack, 'line'); ncopies = 0; if ~isempty(stack) % check if we are in a different workspace if ~isequal(stack, obj.workspace) % if subfunction, must be a copie if ~isempty(obj.workspace) && strcmpi(stack(end).file, obj.workspace(end).file) && ... ~strcmpi(stack(end).name, obj.workspace(end).name) % We are within a subfunction. The MMO must have % been passed as an argument (otherwise the current % workspace and the workspace variable would be % equal). ncopies = 2; else tmpVar = evalin('caller', 'nargin;'); % this does not work if ~isscript(stack(1).file) ncopies = 2; % we are within a function. The MMO must have % been passed as an argument (otherwise the current % workspace and the workspace variable would be % equal). else % we cannot be in a function with 0 argument % (otherwise the current workspace and the workspace % variable would be equal). We must assume that % we are in a script. while ~isempty(stack) && ~isequal(stack, obj.workspace) stack(1) = []; end; if ~isequal(stack, obj.workspace) ncopies = 2; end; end; end; end; end; % check local variables % --------------------- if ncopies < 2 s = evalin('caller', 'whos'); for index = 1:length(s) if strcmpi(s(index).class, 'struct') || strcmpi(s(index).class, 'cell') tmpVar = evalin('caller', s(index).name); ncopies = ncopies + checkcopies_local(obj, tmpVar); elseif strcmpi(s(index).class, 'mmo') if s(index).persistent || s(index).global disp('Warning: mmo objects should not be made persistent or global. Behavior is unpredictable.'); end; tmpVar = evalin('caller', s(index).name); if isequal(tmpVar, obj), ncopies = ncopies + 1; end; if ncopies > 1, break; end; end; end; end; % removing some entries % --------------------- if isempty(val) newdim1 = obj.dimensions; newdim2 = obj.dimensions; % create new array of new size % ---------------------------- tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); newFileName = sprintf('memapdata_%.9d%.9d.fdt', round(rand(1)*10^9), round(rand(1)*10^9)); % find non singleton dimension % ---------------------------- nonSingleton = []; for index = 1:length(subs) if ~isstr(subs{index}) % can only be ":" nonSingleton(end+1) = index; subs2 = setdiff_bc([1:newdim1(index)], subs{index}); % invert selection end; end; if length(nonSingleton) > 1, error('A null assignment can have only one non-colon index'); end; if isempty(nonSingleton), obj = []; return; end; % compute new final dimension % --------------------------- if length(ss(1).subs) == 1 fid = fopen(newFileName, 'w'); newdim2 = prod(newdim2)-length(ss(1).subs{1}); newindices = setdiff_bc([1:prod(newdim1)], ss(1).subs{1}); for index = newindices fwrite(fid, tmpMMO.Data.x(index), 'float'); end; fclose(fid); else newdim2(nonSingleton) = newdim2(nonSingleton)-length(subs{index}); tmpdata = builtin('subsref', tmpMMO.Data.x, s); fid = fopen(newFileName, 'w'); fwrite(fid, tmpMMO.Data.x(index), 'float'); fclose(fid); end; % delete file if necessary if ncopies == 1 && obj.writable delete(obj.dataFile); end; if obj.debug, disp('new copy created, old deleted (length 1)'); end; obj.dimensions = [1 newdim2]; obj.dataFile = newFileName; obj.writable = true; clear tmpMMO; return; elseif ncopies == 1 && obj.writable for index = 1:length(ss(1).subs) newdim2(notOneDim) = newdim2(notOneDim)-length(ss(1).subs{1}); if index > length(newdim2) newdim2(index) = max(ss(1).subs{index}); else newdim2(index) = max(max(ss(1).subs{index}), newdim2(index)); end; end; % create new array of new size % ----------------------------------------- tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); newFileName = sprintf('memapdata_%.9d%.9d.fdt', round(rand(1)*10^9), round(rand(1)*10^9)); % copy file row by row % -------------------- fid = fopen(newFileName, 'w'); tmpdata = zeros(prod(newdim2(1)) - prod(newdim1(1)), 1, 'single'); for index = 1:prod(newdim1(2:end)) fwrite(fid, tmpMMO.Data.x(:,index), 'float'); fwrite(fid, tmpdata, 'float'); end; if prod(newadim1(2:end)) ~= prod(newdim2(2:end)) tmpdata = zeros(newdim2(1), 1, 'single'); for index = prod(newdim1(2:end))+1:prod(newdim2(2:end)) fwrite(fid, tmpdata, 'float'); end; end; fclose(fid); % delete file if necessary if ncopies == 1 && obj.writable delete(obj.dataFile); end; if obj.debug, disp('new copy created, old deleted'); end; obj.dimensions = newdim2; obj.dataFile = newFileName; obj.writable = true; clear tmpMMO; else % check size % ---------- newdim1 = obj.dimensions; newdim2 = obj.dimensions; if length(ss(1).subs) == 1 if max(ss(1).subs{1}) > prod(newdim2) notOneDim = find(newdim2 > 1); if length(notOneDim) == 1 newdim2(notOneDim) = max(ss(1).subs{1}); end; end; else for index = 1:length(ss(1).subs) if index > length(newdim2) newdim2(index) = max(ss(1).subs{index}); else newdim2(index) = max(max(ss(1).subs{index}), newdim2(index)); end; end; end; % create new array of new size if necessary % ----------------------------------------- if ~isequal(newdim1, newdim2) tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); newFileName = sprintf('memapdata_%.9d%.9d.fdt', round(rand(1)*10^9), round(rand(1)*10^9)); % copy file row by row % -------------------- fid = fopen(newFileName, 'w'); tmpdata = zeros(prod(newdim2(1)) - prod(newdim1(1)), 1, 'single'); for index = 1:prod(newdim1(2:end)) fwrite(fid, tmpMMO.Data.x(:,index), 'float'); fwrite(fid, tmpdata, 'float'); end; if prod(newdim1(2:end)) ~= prod(newdim2(2:end)) tmpdata = zeros(newdim2(1), 1, 'single'); for index = prod(newdim1(2:end))+1:prod(newdim2(2:end)) fwrite(fid, tmpdata, 'float'); end; end; fclose(fid); % delete file if necessary if ncopies == 1 && obj.writable delete(obj.dataFile); end; if obj.debug, disp('new copy created, old deleted'); end; obj.dimensions = newdim2; obj.dataFile = newFileName; obj.writable = true; clear tmpMMO; % create copy if necessary % ------------------------ elseif ncopies > 1 || ~obj.writable newFileName = sprintf('memapdata_%.9d%.9d.fdt', round(rand(1)*10^9), round(rand(1)*10^9)); copyfile(obj.dataFile, newFileName); obj.dataFile = newFileName; obj.writable = true; if obj.debug, disp('new copy created'); end; else if obj.debug, disp('using same copy'); end; end; tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); tmpMMO.Data.x = builtin('subsasgn', tmpMMO.Data.x, ss, val); end; return; % i.type = '()'; % i.subs = { ':' ':' ':' }; % res = subsref(obj, i); % note that subsref cannot be called directly % subfunction checking the number of copies % ----------------------------------------- function ncopies = checkcopies_local(obj, arg); ncopies = 0; if isstruct(arg) for ilen = 1:length(arg) for index = fieldnames(arg)' ncopies = ncopies + checkcopies_local(obj, arg(ilen).(index{1})); if ncopies > 1, return; end; end; end; elseif iscell(arg) for index = 1:length(arg(:)) ncopies = ncopies + checkcopies_local(obj, arg{index}); if ncopies > 1, return; end; end; elseif isa(arg, 'mmo') && isequal(obj, arg) ncopies = 1; else ncopies = 0; end;
github
lcnhappe/happe-master
end.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/end.m
901
utf_8
0e38d125a547083cb574fbd3bb455fbd
% end() - last index to memmapdata array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 s = end(a, k, n); s = size(a, k);
github
lcnhappe/happe-master
subsasgn.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/subsasgn.m
10,655
utf_8
c4514f5b1f0fec385eeb19fee7a5db56
% subsasgn() - define index assignment for eegdata objects % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 obj = subsasgn(obj,ss,val) % check empty assignement % ----------------------- for index = 1:length(ss(1).subs) if isempty(ss(1).subs{index}), return; end; end; % remove useless ":" % ------------------ while length(obj.dimensions) < length(ss(1).subs) if isequal(ss(1).subs{end}, ':') ss(1).subs(end) = []; else break; end; end; % deal with transposed data % ------------------------- if obj.transposed, ss = transposeindices(obj, ss); end; % check stack and local variables % --------------------- ncopies = checkworkspace(obj); if ncopies < 2 if isempty(inputname(1)) vers = version; indp = find(vers == '.'); if str2num(vers(indp(1)+1)) > 1, vers = [ vers(1:indp(1)) '0' vers(indp(1)+1:end) ]; end; indp = find(vers == '.'); vers = str2num(vers(1:indp(2)-1)); if vers >= 7.13 % the problem with Matlab 2012a/2011b is that if the object called is % in a field of a structure (empty inputname), the evaluation % in the caller of the object variable is empty in 2012a. A bug % repport has been submitted to Matlab - Arno ncopies = ncopies + 1; end; end; s = evalin('caller', 'whos'); for index = 1:length(s) if strcmpi(s(index).class, 'struct') || strcmpi(s(index).class, 'cell') tmpVar = evalin('caller', s(index).name); ncopies = ncopies + checkcopies_local(obj, tmpVar); elseif strcmpi(s(index).class, 'mmo') if s(index).persistent || s(index).global disp('Warning: mmo objects should not be made persistent or global. Behavior is unpredictable.'); end; tmpVar = evalin('caller', s(index).name); if isequal(tmpVar, obj), ncopies = ncopies + 1; end; if ncopies > 1, break; end; end; end; end; % removing some entries % --------------------- if isempty(val) newdim1 = obj.dimensions; newdim2 = obj.dimensions; % create new array of new size % ---------------------------- tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); newFileName = mmo.getnewfilename; % find non singleton dimension % ---------------------------- nonSingleton = []; ss2 = ss; for index = 1:length(ss(1).subs) if ~isstr(ss(1).subs{index}) % can only be ":" nonSingleton(end+1) = index; ss2(1).subs{index} = setdiff_bc([1:newdim1(index)], ss(1).subs{index}); % invert selection end; end; if length(nonSingleton) > 1, error('A null assignment can have only one non-colon index'); end; if isempty(nonSingleton), obj = []; return; end; % compute new final dimension and copy data % ----------------------------------------- if length(ss(1).subs) == 1 fid = fopen(newFileName, 'w'); newdim2 = [ prod(newdim2)-length(ss(1).subs{1}) ]; if ~(newdim1(1) > 1 && all(newdim1(2:end) == 1)), newdim2 = [1 newdim2]; else newdim2 = [newdim2 1]; end; newindices = setdiff_bc([1:prod(newdim1)], ss(1).subs{1}); for index = newindices fwrite(fid, tmpMMO.Data.x(index), 'float'); end; fclose(fid); fprintf('Warning: memory mapped object writing might not be up to date in cache on network drive'); else if length(ss(1).subs) < length(newdim2) newdim2(length(ss(1).subs)) = prod(newdim2(length(ss(1).subs):end)); newdim2(length(ss(1).subs)+1:end) = []; if nonSingleton == length(ss(1).subs) ss2(1).subs{end} = setdiff_bc([1:newdim2(end)], ss(1).subs{end}); end; end; newdim2(nonSingleton) = newdim2(nonSingleton)-length(ss(1).subs{nonSingleton}); if isstr(ss2.subs{end}) ss2.subs{end} = [1:prod(newdim1(length(ss2.subs):end))]; end; ss3 = ss2; fid = fopen(newFileName, 'w'); % copy large blocks alllen = cellfun(@length, ss2.subs); inc = ceil(250000/prod(alllen(1:end-1))); % 1Mb block for index = 1:inc:length(ss2.subs{end}) ss3.subs{end} = ss2.subs{end}(index:min(index+inc, length(ss2.subs{end}))); tmpdata = subsref(tmpMMO.Data.x, ss3); fwrite(fid, tmpdata, 'float'); end; fclose(fid); fprintf('Warning: memory mapped object writing might not be up to date in cache on network drive'); end; % delete file if necessary if ncopies == 1 && obj.writable delete(obj.dataFile); end; if obj.debug, disp('new copy created, old deleted (length 1)'); end; obj.dimensions = newdim2; obj.dataFile = newFileName; obj.writable = true; obj = updateWorkspace(obj); clear tmpMMO; return; else % check size to see if it increases % --------------------------------- newdim1 = obj.dimensions; newdim2 = newdim1; if length(ss(1).subs) == 1 if ~isstr(ss(1).subs{1}) && max(ss(1).subs{1}) > prod(newdim1) if length(newdim1) > 2 error('Attempt to grow array along ambiguous dimension.'); end; end; if max(ss(1).subs{1}) > prod(newdim2) notOneDim = find(newdim2 > 1); if length(notOneDim) == 1 newdim2(notOneDim) = max(ss(1).subs{1}); end; end; else if length(newdim1) == 3 && newdim1(3) == 1, newdim1(end) = []; end; if length(ss(1).subs) == 2 && length(newdim1) == 3 if ~isstr(ss(1).subs{2}) && max(ss(1).subs{2}) > prod(newdim1(2:end)) error('Attempt to grow array along ambiguous dimension.'); end; if isnumeric(ss(1).subs{1}), newdim2(1) = max(max(ss(1).subs{1}), newdim2(1)); end; else for index = 1:length(ss(1).subs) if isnumeric(ss(1).subs{index}) if index > length(newdim2) newdim2(index) = max(ss(1).subs{index}); else newdim2(index) = max(max(ss(1).subs{index}), newdim2(index)); end; end; end; end; end; % create new array of new size if necessary % ----------------------------------------- if ~isequal(newdim1, newdim2) tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); newFileName = mmo.getnewfilename; % copy file row by row % -------------------- fid = fopen(newFileName, 'w'); dim1 = [ newdim1 1 1 1 1 ]; dim2 = [ newdim2 1 1 1 1 ]; tmpdata1 = zeros(prod(dim2(1:1)) - prod(dim1(1:1)), 1, 'single'); tmpdata2 = zeros((dim2(2) - dim1(2))*dim2(1), 1, 'single'); tmpdata3 = zeros((dim2(3) - dim1(3))*prod(dim2(1:2)), 1, 'single'); % copy new data (copy first array) % ------------- for index3 = 1:dim1(3) if dim1(1) == dim2(1) && dim1(2) == dim2(2) fwrite(fid, tmpMMO.Data.x(:,:,index3), 'float'); else for index2 = 1:dim1(2) if dim1(1) == dim2(1) fwrite(fid, tmpMMO.Data.x(:,index2,index3), 'float'); else for index1 = 1:dim1(1) fwrite(fid, tmpMMO.Data.x(index1,index2,index3), 'float'); end; end; fwrite(fid, tmpdata1, 'float'); end; end; fwrite(fid, tmpdata2, 'float'); end; fwrite(fid, tmpdata3, 'float'); fclose(fid); fprintf('Warning: memory mapped object writing might not be up to date in cache on network drive'); % delete file if necessary if ncopies == 1 && obj.writable delete(obj.dataFile); end; if obj.debug, disp('new copy created, old deleted'); end; obj.dimensions = newdim2; obj.dataFile = newFileName; obj.writable = true; clear tmpMMO; % create copy if necessary % ------------------------ elseif ncopies > 1 || ~obj.writable newFileName = mmo.getnewfilename; copyfile(obj.dataFile, newFileName); obj.dataFile = newFileName; obj.writable = true; if obj.debug, disp('new copy created'); end; else if obj.debug, disp('using same copy'); end; end; % copy new data tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); if ~isa(val, 'mmo') tmpMMO.Data.x = builtin('subsasgn', tmpMMO.Data.x, ss, val); else % copy memory mapped array if ndims(val) == 2 && (size(val,1) == 1 || size(val,2) == 1) % vector direct copy ss2.type = '()'; ss2.subs = { ':' ':' ':' }; tmpMMO.Data.x = builtin('subsasgn', tmpMMO.Data.x, ss, subsref(val,ss2)); else ss2.type = '()'; ss2.subs = { ':' ':' ':' }; ss3 = ss; % array, copy each channel for index1 = 1:size(val,1) ss2(1).subs{1} = index1; if isstr(ss(1).subs{1}) ss3(1).subs{1} = index1; else ss3(1).subs{1} = ss(1).subs{1}(index1); end; tmpMMO.Data.x = builtin('subsasgn', tmpMMO.Data.x, ss3, subsref(val,ss2)); end; end; end; obj = updateWorkspace(obj); end;
github
lcnhappe/happe-master
isnumeric.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/isnumeric.m
877
utf_8
34baf204e1b984ee69cf7f462fe2e524
% isnumeric() - returns 1 % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 r = isnumeric(a) r = 1;
github
lcnhappe/happe-master
checkcopies_local.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/checkcopies_local.m
634
utf_8
8eb8d5fec95c91346e91a09010082b47
% subfunction checking the number of local copies % ----------------------------------------------- function ncopies = checkcopies_local(obj, arg); ncopies = 0; if isstruct(arg) for ilen = 1:length(arg) for index = fieldnames(arg)' ncopies = ncopies + checkcopies_local(obj, arg(ilen).(index{1})); if ncopies > 1, return; end; end; end; elseif iscell(arg) for index = 1:length(arg(:)) ncopies = ncopies + checkcopies_local(obj, arg{index}); if ncopies > 1, return; end; end; elseif isa(arg, 'mmo') && isequal(obj, arg) ncopies = 1; else ncopies = 0; end;
github
lcnhappe/happe-master
changefile.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/changefile.m
187
utf_8
e75127c90da43ddce182d36cf0abbdee
% this function is called when the file is being saved function obj = changefile(obj, newfile) movefile(obj.dataFile, newfile); obj.dataFile = newfile; obj.writable = false;
github
lcnhappe/happe-master
var.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/var.m
1,416
utf_8
2360192fa42b3c35ebd7743ffe4fe8b6
% var() - variance of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 sumval = var(obj,flag,dim) if nargin < 2 flag = 0; end; if nargin < 3 dim = 1; end; meanvalsq = mean(obj,dim).^2; sumval = 0; s1 = size(obj); ss.type = '()'; ss.subs(1:length(s1)) = { ':' }; for index = 1:s1(dim) ss.subs{dim} = index; tmpdata = subsref(obj, ss); sumval = sumval + tmpdata.*tmpdata - meanvalsq; end; if isempty(flag) || flag == 0 sumval = sumval/(size(obj,dim)-1); else sumval = sumval/size(obj,dim); end;
github
lcnhappe/happe-master
length.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/length.m
913
utf_8
f0841237745a123f3215e00164cc4a1a
% length() - length of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 s = length(a) s = size(a,1);
github
lcnhappe/happe-master
sum.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/sum.m
1,212
utf_8
2fbce1d1b6e2a5edf32742897441a732
% sum() - sum of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 sumval = sum(obj,dim) if nargin < 2 dim = 1; end; s1 = size(obj); ss.type = '()'; ss.subs(1:length(s1)) = { ':' }; for index = 1:s1(dim) ss.subs{dim} = index; if index == 1 sumval = subsref(obj, ss); else sumval = sumval + subsref(obj, ss); end; end;
github
lcnhappe/happe-master
size.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/size.m
1,751
utf_8
daf6932de04161ccb2df3df31b45203a
% size() - size of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 [s varargout] = size(obj,dim) if obj.transposed if length(obj.dimensions) ~= 2 && length(obj.dimensions) ~= 3 error('Transposed array must be 2 or 3 dims'); end; if length(obj.dimensions) == 2 tmpdimensions = [obj.dimensions(2) obj.dimensions(1)]; else tmpdimensions = [obj.dimensions(3) obj.dimensions(1:end-1)]; end; else tmpdimensions = obj.dimensions; end; s = tmpdimensions; if nargin > 1 if dim >length(s) s = 1; else s = s(dim); end; else if nargout > 1 s = [s 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]; alls = s; s = s(1); for index = 1:max(nargout,1)-1 varargout{index} = alls(index+1); end; end; end;
github
lcnhappe/happe-master
subsref.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/subsref.m
2,711
utf_8
1da2db6dbbc53f36d6d2954f095f9064
% subsref() - index eegdata class % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 = subsref(obj,s) if strcmpi(s(1).type, '.') res = builtin('subsref', obj, s); return; end; tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); subs = s(1).subs; finaldim = cellfun('length', subs); % one dimension input % ------------------- if length(s) > 1 || ~strcmpi(s(1).type, '()') error('MMO can only map single array data files'); end; % deal with transposed data % ------------------------- if obj.transposed, s = transposeindices(obj, s); end; % convert : to real sizes % ----------------------- lastdim = length(subs); if isstr(subs{end}) && ndims(obj) > lastdim for index = lastdim+1:ndims(obj) if index > length(obj.dimensions) subs{index} = 1; else subs{index} = [1:obj.dimensions(index)]; end; end; end; for index = 1:length(subs) if isstr(subs{index}) % can only be ":" if index > length(obj.dimensions) subs{index} = 1; else subs{index} = [1:obj.dimensions(index)]; end; end; end; finaldim = cellfun(@length, subs); finaldim(lastdim) = prod(finaldim(lastdim:end)); finaldim(lastdim+1:end) = []; % non-transposed data % ------------------- res = tmpMMO.data.x(subs{:}); if length(finaldim) == 1, finaldim(2) = 1; end; res = reshape(res, finaldim); if obj.transposed if finaldim(end) == 1, finaldim(end) = []; end; if length(finaldim) <= 2, res = res'; else res = reshape(res, [finaldim(1)*finaldim(2) finaldim(3)])'; res = reshape(res, [finaldim(3) finaldim(1) finaldim(2)]); end; end;
github
lcnhappe/happe-master
ndims.m
.m
happe-master/Packages/eeglab14_0_0b/functions/@mmo/ndims.m
1,095
utf_8
7ddcbafa2aaf95308a1a4de4a272f0ae
% ndims() - number of dimension of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % 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 = ndims(obj) if length(obj.dimensions) <= 2 || all(obj.dimensions(3:end) == 1), res = 2; else res = length(obj.dimensions); end;
github
lcnhappe/happe-master
correctfit.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/correctfit.m
3,222
utf_8
69c8b2f965023329820bdfd3c7e82176
% correctfit() - correct fit using observed p-values. Use this function % if for some reason, the distribution of p values is % not uniform between 0 and 1 % % Usage: % >> [p phat pci zerofreq] = correctfit(pval, 'key', 'val'); % % Inputs: % pval - input p value % % Optional inputs: % 'allpval' - [float array] collection of p values drawn from random % distributions (theoritically uniform). % 'gamparams' - [phat pci zerofreq] parameter for gamma function fitting. % zerofreq is the frequency of occurence of p=0. % 'zeromode' - ['on'|'off'] enable estimation of frequency of pval=0 % (this might lead to hight pval). Default is 'on'. % % Outputs: % p - corrected p value. % phat - phat gamfit() parameter. % pci - phat gamfit() parameter. % zerofreq - frequency of occurence of p=0. % % Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2003- % % See also: bootstat() % Copyright (C) 7/02/03 Arnaud Delorme, SCCN/INC/UCSD % % 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 [pval, PHAT, PCI, zerofreq] = correctfit(pval, varargin) if nargin < 2 help correctfit; disp('You need to specify one optional input'); return; end; g = finputcheck( varargin, { 'allpval' 'real' [0 1] []; 'zeromode' 'string' {'on','off'} 'on'; 'gamparams' 'real' [] []}, 'correctfit'); if isstr(g), error(g); end; if ~isempty(g.gamparams) PHAT = g.gamparams(1); PCI = g.gamparams(2); zerofreq = g.gamparams(3); elseif ~isempty(g.allpval) nonzero = find(g.allpval(:) ~= 0); zerofreq = (length(g.allpval(:))-length(nonzero))/ length(g.allpval(:)); tmpdat = -log10( g.allpval(nonzero) ) + 1E-10; [PHAT, PCI] = gamfit( tmpdat ); PHAT = PHAT(1); PCI = PCI(2); end; if pval == 0 if strcmpi(g.zeromode, 'on') pval = zerofreq; end; else tmppval = -log10( pval ) + 1E-10; pval = 1-gamcdf( tmppval, PHAT, PCI); end; if 1 % plotting if exist('tmpdat') == 1 figure; hist(tmpdat, 100); hold on; mult = ylim; tmpdat = linspace(0.00001,10, 300); normy = gampdf( tmpdat, PHAT, PCI); plot( tmpdat, normy/max(normy)*mult(2)*3, 'r'); end; end;
github
lcnhappe/happe-master
timef.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/timef.m
42,818
utf_8
6663467d76d01722baccf168fec18e1b
% timef() - Returns estimates and plots of mean event-related spectral % perturbation (ERSP) and inter-trial coherence (ITC) changes % across event-related trials (epochs) of a single input time series. % * Uses either fixed-window, zero-padded FFTs (fastest), wavelet % 0-padded DFTs (both Hanning-tapered), OR multitaper spectra ('mtaper'). % * For the wavelet and FFT methods, output frequency spacing % is the lowest frequency ('srate'/'winsize') divided by 'padratio'. % NaN input values (such as returned by eventlock()) are ignored. % * If 'alpha' is given, then bootstrap statistics are computed % (from a distribution of 'naccu' surrogate data trials) and % non-significant features of the output plots are zeroed out % (i.e., plotted in green). % * Given a 'topovec' scalp map weights vector and an 'elocs' electrode % location file or structure, the figure also shows a topoplot() % image of the specified scalp map. % % * Note: Left-click on subplots to view and zoom in separate windows. % Usage: % >> [ersp,itc,powbase,times,freqs,erspboot,itcboot,itcphase] = ... % timef(data,frames,tlimits,srate,cycles,... % 'key1',value1,'key2',value2, ... ); % NOTE: % * For more detailed information about timef(), >> timef details % * Default values may differ when called from pop_timef() % % Required inputs: % data = Single-channel data vector (1,frames*ntrials) (required) % frames = Frames per trial {def|[]: datalength} % tlimits = [mintime maxtime] (ms) Epoch time limits % {def|[]: from frames,srate} % srate = data sampling rate (Hz) {def:250} % cycles = If 0 -> Use FFTs (with constant window length) {0 = FFT} % If >0 -> Number of cycles in each analysis wavelet % If [wavecycles factor] -> wavelet cycles increase with % frequency beginning at wavecyles (0<factor<1; factor=1 % -> no increase, standard wavelets; factor=0 -> fixed epoch % length, as in FFT. Else, 'mtaper' -> multitaper decomp. % % Optional Inter-Irial Coherence (ITC) type: % 'type' = ['coher'|'phasecoher'] Compute either linear coherence % ('coher') or phase coherence ('phasecoher') also known % as the phase coupling factor {'phasecoher'}. % Optional detrending: % 'detret' = ['on'|'off'], Detrend data in time. {'off'} % 'detrep' = ['on'|'off'], Detrend data across trials {'off'} % % Optional FFT/DFT parameters: % 'winsize' = If cycles==0: data subwindow length (fastest, 2^n<frames); % If cycles >0: *longest* window length to use. This % determines the lowest output frequency {~frames/8} % 'timesout' = Number of output times (int<frames-winframes) {200} % 'padratio' = FFT-length/winframes (2^k) {2} % Multiplies the number of output frequencies by % dividing their spacing. When cycles==0, frequency % spacing is (low_freq/padratio). % 'maxfreq' = Maximum frequency (Hz) to plot (& to output if cycles>0) % If cycles==0, all FFT frequencies are output. {50} % 'baseline' = Spectral baseline window center end-time (in ms). {0} % 'powbase' = Baseline spectrum (power, not dB) to normalize the data. % {def|NaN->from data} % % Optional multitaper parameters: % 'mtaper' = If [N W], performs multitaper decomposition. % (N is the time resolution and W the frequency resolution; % maximum taper number is 2NW-1). Overwrites 'winsize' and % 'padratio'. % If [N W K], uses K Slepian tapers (if possible). % Phase is calculated using standard methods. % The use of mutitaper with wavelets (cycles>0) is not % recommended (as multiwavelets are not implemented). % Uses Matlab functions DPSS, PMTM. {no multitaper} % % Optional bootstrap parameters: % 'alpha' = If non-0, compute two-tailed bootstrap significance prob. % level. Show non-signif. output values in green {0} % 'naccu' = Number of bootstrap replications to accumulate {200} % 'baseboot' = Bootstrap baseline to subtract (1 -> use 'baseline'(above) % 0 -> use whole trial) {1} % Optional scalp map: % 'topovec' = Scalp topography (map) to plot {none} % 'elocs' = Electrode location file for scalp map % File should be ascii in format of >> topoplot example % May also be an EEG.chanlocs struct. % {default: file named in icadefs.m} % Optional plotting parameters: % 'hzdir' = ['up'|'down'] Direction of the frequency axes; reads default % from icadefs.m {'up'} % 'plotersp' = ['on'|'off'] Plot power spectral perturbations {'on'} % 'plotitc' = ['on'|'off'] Plot inter trial coherence {'on'} % 'plotphase' = ['on'|'off'] Plot sign of the phase in the ITC panel, i.e. % green->red, pos.-phase ITC, green->blue, neg.-phase ITC {'on'} % 'erspmax' = [real dB] set the ERSP max. for the scale (min= -max){auto} % 'itcmax' = [real<=1] set the ITC maximum for the scale {auto} % 'title' = Optional figure title {none} % 'marktimes' = Non-0 times to mark with a dotted vertical line (ms) {none} % 'linewidth' = Line width for 'marktimes' traces (thick=2, thin=1) {2} % 'pboot' = Bootstrap power limits (e.g., from timef()) {from data} % 'rboot' = Bootstrap ITC limits (e.g., from timef()) {from data} % 'axesfont' = Axes text font size {10} % 'titlefont' = Title text font size {8} % 'vert' = [times_vector] -> plot vertical dashed lines at given ms. % 'verbose' = ['on'|'off'] print text {'on'} % % Outputs: % ersp = Matrix (nfreqs,timesout) of log spectral diffs. from % baseline (in dB). NB: Not masked for significance. % Must do this using erspboot % itc = Matrix of inter-trial coherencies (nfreqs,timesout) % (range: [0 1]) NB: Not masked for significance. % Must do this using itcboot % powbase = Baseline power spectrum (NOT in dB, used to norm. the ERSP) % times = Vector of output times (sub-window centers) (in ms) % freqs = Vector of frequency bin centers (in Hz) % erspboot = Matrix (2,nfreqs) of [lower;upper] ERSP significance diffs % itcboot = Matrix (2,nfreqs) of [lower;upper] ITC thresholds (not diffs) % itcphase = Matrix (nfreqs,timesout) of ITC phase (in radians) % % Plot description: % Assuming both 'plotersp' and 'plotitc' options are 'on' (= default). % The upper panel presents the data ERSP (Event-Related Spectral Perturbation) % in dB, with mean baseline spectral activity (in dB) subtracted. Use % "'baseline', NaN" to prevent timef() from removing the baseline. % The lower panel presents the data ITC (Inter-Trial Coherence). % Click on any plot axes to pop up a new window (using 'axcopy()') % -- Upper left marginal panel presents the mean spectrum during the baseline % period (blue), and when significance is set, the significance threshold % at each frequency (dotted green-black trace). % -- The marginal panel under the ERSP image shows the maximum (green) and % minimum (blue) ERSP values relative to baseline power at each frequency. % -- The lower left marginal panel shows mean ITC across the imaged time range % (blue), and when significance is set, the significance threshold (dotted % green-black). % -- The marginal panel under the ITC image shows the ERP (which is produced by % ITC across the data spectral pass band). % % Author: Sigurd Enghoff, Arnaud Delorme & Scott Makeig % CNL / Salk Institute 1998- | SCCN/INC, UCSD 2002- % % Known problems: % Significance masking currently fails for linear coherence. % % See also: crossf() % Copyright (C) 1998 Sigurd Enghoff, Scott Makeig, Arnaud Delorme, % CNL / Salk Institute 8/1/98-8/28/01 % % 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 % 10-19-98 avoided division by zero (using MIN_ABS) -sm % 10-19-98 improved usage message and commandline info printing -sm % 10-19-98 made valid [] values for tvec and g.elocs -sm % 04-01-99 added missing freq in freqs and plots, fixed log scaling bug -se & -tpj % 06-29-99 fixed frequency indexing for constant-Q -se % 08-24-99 reworked to handle NaN input values -sm % 12-07-99 adjusted ERPtimes to plot ERP under ITC -sm % 12-22-99 debugged ERPtimes, added BASE_BOOT -sm % 01-10-00 debugged BASE_BOOT=0 -sm % 02-28-00 added NOTE on formula derivation below -sm % 03-16-00 added axcopy() feature -sm & tpj % 04-16-00 added multiple marktimes loop -sm % 04-20-00 fixed ITC cbar limits when spcified in input -sm % 07-29-00 changed frequencies displayed msg -sm % 10-12-00 fixed bug in freqs when cycles>0 -sm % 02-07-01 fixed inconsistency in BASE_BOOT use -sm % 08-28-01 matlab 'key' value arguments -ad % 08-28-01 multitaper decomposition -ad % 01-25-02 reformated help & license -ad % 03-08-02 debug & compare to old timef function -ad % 03-16-02 timeout automatically adjusted if too high -ad % 04-02-02 added 'coher' option -ad function [P,R,mbase,times,freqs,Pboot,Rboot,Rphase,PA] = timef(X,frames,tlimits,Fs,varwin,varargin); % Note: undocumented arg PA is output of 'phsamp','on' %varwin,winsize,g.timesout,g.padratio,g.maxfreq,g.topovec,g.elocs,g.alpha,g.marktimes,g.powbase,g.pboot,g.rboot) % ITC: Normally, R = |Sum(Pxy)| / (Sum(|Pxx|)*Sum(|Pyy|)) is linear coherence. % But here, we consider: Phase(Pyy) = 0 and |Pyy| = 1 -> Pxy = Pxx % Giving, R = |Sum(Pxx)|/Sum(|Pxx|), the inter-trial coherence (ITC) % Also called 'phase-locking factor' by Tallon-Baudry et al. (1996), % the ITC is the phase coherence between the data time series and the % time-locking event time series. % Read system-wide / dir-wide constants: icadefs % Constants set here: ERSP_CAXIS_LIMIT = 0; % 0 -> use data limits; else positive value % giving symmetric +/- caxis limits. ITC_CAXIS_LIMIT = 0; % 0 -> use data limits; else positive value % giving symmetric +/- caxis limits. % Commandline arg defaults: DEFAULT_EPOCH = NaN; % Frames per trial DEFAULT_TIMLIM = NaN; % Time range of g.frames (ms) DEFAULT_FS = 250; % Sampling frequency (Hz) DEFAULT_NWIN = 200; % Number of windows = horizontal resolution DEFAULT_VARWIN = 0; % Fixed window length or fixed number of cycles. % =0: fix window length to that determined by nwin % >0: set window length equal to varwin cycles % Bounded above by winsize, which determines % the min. freq. to be computed. DEFAULT_OVERSMP = 2; % Number of times to oversample frequencies DEFAULT_MAXFREQ = 50; % Maximum frequency to display (Hz) DEFAULT_TITLE = ''; % Figure title DEFAULT_ELOC = 'chan.locs'; % Channel location file DEFAULT_ALPHA = NaN; % Percentile of bins to keep DEFAULT_MARKTIME= NaN; % Font sizes: AXES_FONT = 10; % axes text FontSize TITLE_FONT = 8; if nargout>7 Rphase = []; % initialize in case Rphase asked for, but ITC not computed end if (nargin < 1) help timef return end if isstr(X) & strcmp(X,'details') more on help timefdetails more off return end if (min(size(X))~=1 | length(X)<2) error('Data must be a row or column vector.'); end if nargin < 2 | isempty(frames) | isnan(frames) frames = DEFAULT_EPOCH; elseif (~isnumeric(frames) | length(frames)~=1 | frames~=round(frames)) error('Value of frames must be an integer.'); elseif (frames <= 0) error('Value of frames must be positive.'); elseif (rem(length(X),frames) ~= 0) error('Length of data vector must be divisible by frames.'); end if isnan(frames) | isempty(frames) frames = length(X); end if nargin < 3 | isnan(tlimits) | isempty(tlimits) tlimits = DEFAULT_TIMLIM; elseif (~isnumeric(tlimits) | sum(size(tlimits))~=3) error('Value of tlimits must be a vector containing two numbers.'); elseif (tlimits(1) >= tlimits(2)) error('tlimits interval must be ascending.'); end if (nargin < 4) Fs = DEFAULT_FS; elseif (~isnumeric(Fs) | length(Fs)~=1) error('Value of srate must be a number.'); elseif (Fs <= 0) error('Value of srate must be positive.'); end if isnan(tlimits) | isempty(tlimits) hlim = 1000*frames/Fs; % fit default tlimits to srate and frames tlimits = [0 hlim]; end framesdiff = frames - Fs*(tlimits(2)-tlimits(1))/1000; if abs(framesdiff) > 1 error('Given time limits, frames and sampling rate are incompatible'); elseif framesdiff ~= 0 tlimits(1) = tlimits(1) - 0.5*framesdiff*1000/Fs; tlimits(2) = tlimits(2) + 0.5*framesdiff*1000/Fs; fprintf('Adjusted time limits slightly, to [%.1f,%.1f] ms, to match frames and srate.\n',tlimits(1),tlimits(2)); end if (nargin < 5) varwin = DEFAULT_VARWIN; elseif (~isnumeric(varwin) | length(varwin)>2) error('Value of cycles must be a number.'); elseif (varwin < 0) error('Value of cycles must be zero or positive.'); end % consider structure for these arguments % -------------------------------------- if ~isempty(varargin) try, g = struct(varargin{:}); catch, error('Argument error in the {''param'', value} sequence'); end; end; g.tlimits = tlimits; g.frames = frames; g.srate = Fs; g.cycles = varwin(1); if length(varwin)>1 g.cyclesfact = varwin(2); else g.cyclesfact = 1; end; try, g.title; catch, g.title = DEFAULT_TITLE; end; try, g.winsize; catch, g.winsize = max(pow2(nextpow2(g.frames)-3),4); end; try, g.pad; catch, g.pad = max(pow2(nextpow2(g.winsize)),4); end; try, g.timesout; catch, g.timesout = DEFAULT_NWIN; end; try, g.padratio; catch, g.padratio = DEFAULT_OVERSMP; end; try, g.maxfreq; catch, g.maxfreq = DEFAULT_MAXFREQ; end; try, g.topovec; catch, g.topovec = []; end; try, g.elocs; catch, g.elocs = DEFAULT_ELOC; end; try, g.alpha; catch, g.alpha = DEFAULT_ALPHA; end; try, g.marktimes; catch, g.marktimes = DEFAULT_MARKTIME; end; try, g.powbase; catch, g.powbase = NaN; end; try, g.pboot; catch, g.pboot = NaN; end; try, g.rboot; catch, g.rboot = NaN; end; try, g.plotersp; catch, g.plotersp = 'on'; end; try, g.plotitc; catch, g.plotitc = 'on'; end; try, g.detrep; catch, g.detrep = 'off'; end; try, g.detret; catch, g.detret = 'off'; end; try, g.baseline; catch, g.baseline = 0; end; try, g.baseboot; catch, g.baseboot = 1; end; try, g.linewidth; catch, g.linewidth = 2; end; try, g.naccu; catch, g.naccu = 200; end; try, g.mtaper; catch, g.mtaper = []; end; try, g.vert; catch, g.vert = []; end; try, g.type; catch, g.type = 'phasecoher'; end; try, g.phsamp; catch, g.phsamp = 'off'; end; try, g.plotphase; catch, g.plotphase = 'on'; end; try, g.itcmax; catch, g.itcmax = []; end; try, g.erspmax; catch, g.erspmax = []; end; try, g.verbose; catch, g.verbose = 'on'; end; try, g.chaninfo; catch, g.chaninfo = []; end; try, g.hzdir; catch, g.hzdir = HZDIR; end; % default from icadefs lasterr(''); % testing arguments consistency % ----------------------------- if strcmp(g.hzdir,'up') g.hzdir = 'normal'; elseif strcmp(g.hzdir,'down') g.hzdir = 'reverse'; else error('unknown ''hzdir'' value - not ''up'' or ''down'''); end switch lower(g.verbose) case { 'on', 'off' }, ; otherwise error('verbose must be either on or off'); end; if (~ischar(g.title)) error('Title must be a string.'); end if (~isnumeric(g.winsize) | length(g.winsize)~=1 | g.winsize~=round(g.winsize)) error('Value of winsize must be an integer number.'); elseif (g.winsize <= 0) error('Value of winsize must be positive.'); elseif (g.cycles == 0 & pow2(nextpow2(g.winsize)) ~= g.winsize) error('Value of winsize must be an integer power of two [1,2,4,8,16,...]'); elseif (g.winsize > g.frames) error('Value of winsize must be less than frames per epoch.'); end if (~isnumeric(g.timesout) | length(g.timesout)~=1 | g.timesout~=round(g.timesout)) error('Value of timesout must be an integer number.'); elseif (g.timesout <= 0) error('Value of timesout must be positive.'); end if (g.timesout > g.frames-g.winsize) g.timesout = g.frames-g.winsize; disp(['Value of timesout must be <= frames-winsize, timeout adjusted to ' int2str(g.timesout) ]); end if (~isnumeric(g.padratio) | length(g.padratio)~=1 | g.padratio~=round(g.padratio)) error('Value of padratio must be an integer.'); elseif (g.padratio <= 0) error('Value of padratio must be positive.'); elseif (pow2(nextpow2(g.padratio)) ~= g.padratio) error('Value of padratio must be an integer power of two [1,2,4,8,16,...]'); end if (~isnumeric(g.maxfreq) | length(g.maxfreq)~=1) error('Value of maxfreq must be a number.'); elseif (g.maxfreq <= 0) error('Value of maxfreq must be positive.'); elseif (g.maxfreq > Fs/2) myprintf(g.verbose,['Warning: value of maxfreq reduced to Nyquist rate' ... ' (%3.2f)\n\n'], Fs/2); g.maxfreq = Fs/2; end if isempty(g.topovec) g.topovec = []; if isempty(g.elocs) error('Channel location file must be specified.'); end; end if isempty(g.elocs) g.elocs = DEFAULT_ELOC; elseif (~ischar(g.elocs)) & ~isstruct(g.elocs) error('Channel location file must be a valid text file.'); end if (~isnumeric(g.alpha) | length(g.alpha)~=1) error('timef(): Value of g.alpha must be a number.\n'); elseif (round(g.naccu*g.alpha) < 2) myprintf(g.verbose,'Value of g.alpha is out of the normal range [%g,0.5]\n',2/g.naccu); g.naccu = round(2/g.alpha); myprintf(g.verbose,' Increasing the number of bootstrap iterations to %d\n',g.naccu); end if g.alpha>0.5 | g.alpha<=0 error('Value of g.alpha is out of the allowed range (0.00,0.5).'); end if ~isnan(g.alpha) if g.baseboot > 0 myprintf(g.verbose,'Bootstrap analysis will use data in baseline (pre-0 centered) subwindows only.\n') else myprintf(g.verbose,'Bootstrap analysis will use data in all subwindows.\n') end end if ~isnumeric(g.vert) error('vertical line(s) option must be a vector'); else if min(g.vert) < g.tlimits(1) | max(g.vert) > g.tlimits(2) error('vertical line(s) time out-of-bound'); end; end; if ~isnan (g.rboot) if size(g.rboot) == [1,1] if g.cycles == 0 g.rboot = g.rboot*ones(g.winsize*g.padratio/2); end end end; if ~isempty(g.mtaper) % mutitaper, inspired from Bijan Pesaran matlab function if length(g.mtaper) < 3 %error('mtaper arguement must be [N W] or [N W K]'); if g.mtaper(1) * g.mtaper(2) < 1 error('mtaper 2 first arguments'' product must be higher than 1'); end; if length(g.mtaper) == 2 g.mtaper(3) = floor( 2*g.mtaper(2)*g.mtaper(1) - 1); end if length(g.mtaper) == 3 if g.mtaper(3) > 2 * g.mtaper(1) * g.mtaper(2) -1 error('mtaper number too high (maximum (2*N*W-1))'); end; end disp(['Using ' num2str(g.mtaper(3)) ' tapers.']); NW = g.mtaper(1)*g.mtaper(2); % product NW N = g.mtaper(1)*g.srate; [e,v] = dpss(N, NW, 'calc'); e=e(:,1:g.mtaper(3)); g.alltapers = e; else g.alltapers = g.mtaper; disp('mtaper argument not [N W] or [N W K]; considering raw taper matrix'); end; g.winsize = size(g.alltapers, 1); g.pad = max(pow2(nextpow2(g.winsize)),256); % pad*nextpow %nfk = floor([0 g.maxfreq]./g.srate.*g.pad); % not used any more %g.padratio = 2*nfk(2)/g.winsize; g.padratio = g.pad/g.winsize; %compute number of frequencies %nf = max(256, g.pad*2^nextpow2(g.winsize+1)); %nfk = floor([0 g.maxfreq]./g.srate.*nf); %freqs = linspace( 0, g.maxfreq, diff(nfk)); % this also work in the case of a FFT end; switch lower(g.plotphase) case { 'on', 'off' }, ; otherwise error('plotphase must be either on or off'); end; switch lower(g.plotersp) case { 'on', 'off' }, ; otherwise error('plotersp must be either on or off'); end; switch lower(g.plotitc) case { 'on', 'off' }, ; otherwise error('plotitc must be either on or off'); end; switch lower(g.detrep) case { 'on', 'off' }, ; otherwise error('detrep must be either on or off'); end; switch lower(g.detret) case { 'on', 'off' }, ; otherwise error('detret must be either on or off'); end; switch lower(g.phsamp) case { 'on', 'off' }, ; otherwise error('phsamp must be either on or off'); end; if ~isnumeric(g.linewidth) error('linewidth must be numeric'); end; if ~isnumeric(g.naccu) error('naccu must be numeric'); end; if ~isnumeric(g.baseline) error('baseline must be numeric'); end; switch g.baseboot case {0,1}, ; otherwise, error('baseboot must be 0 or 1'); end; switch g.type case { 'coher', 'phasecoher', 'phasecoher2' },; otherwise error('Type must be either ''coher'' or ''phasecoher'''); end; if isnan(g.baseline) g.unitpower = 'uV/Hz'; else g.unitpower = 'dB'; end; if (g.cycles == 0) %%%%%%%%%%%%%% constant window-length FFTs %%%%%%%%%%%%%%%% freqs = linspace(0, g.srate/2, g.padratio*g.winsize/2+1); freqs = freqs(2:end); win = hanning(g.winsize); P = zeros(g.padratio*g.winsize/2,g.timesout); % summed power PP = zeros(g.padratio*g.winsize/2,g.timesout); % power R = zeros(g.padratio*g.winsize/2,g.timesout); % mean coherence RR = zeros(g.padratio*g.winsize/2,g.timesout); % (coherence) Pboot = zeros(g.padratio*g.winsize/2,g.naccu); % summed bootstrap power Rboot = zeros(g.padratio*g.winsize/2,g.naccu); % summed bootstrap coher Rn = zeros(1,g.timesout); Rbn = 0; switch g.type case { 'coher' 'phasecoher2' }, cumulX = zeros(g.padratio*g.winsize/2,g.timesout); cumulXboot = zeros(g.padratio*g.winsize/2,g.naccu); case 'phasecoher' switch g.phsamp case 'on' cumulX = zeros(g.padratio*g.winsize/2,g.timesout); end end; else % %%%%%%%%%%%%%%%%%% cycles>0, Constant-Q (wavelet) DFTs %%%%%%%%%%%%%%%%%%%% freqs = g.srate*g.cycles/g.winsize*[2:2/g.padratio:g.winsize]/2; dispf = find(freqs <= g.maxfreq); freqs = freqs(dispf); win = dftfilt(g.winsize,g.maxfreq/g.srate,g.cycles,g.padratio,g.cyclesfact); P = zeros(size(win,2),g.timesout); % summed power R = zeros(size(win,2),g.timesout); % mean coherence PP = repmat(NaN,size(win,2),g.timesout); % initialize with NaN RR = repmat(NaN,size(win,2),g.timesout); % initialize with NaN Pboot = zeros(size(win,2),g.naccu); % summed bootstrap power Rboot = zeros(size(win,2),g.naccu); % summed bootstrap coher Rn = zeros(1,g.timesout); Rbn = 0; switch g.type case { 'coher' 'phasecoher2' }, cumulX = zeros(size(win,2),g.timesout); cumulXboot = zeros(size(win,2),g.naccu); case 'phasecoher' switch g.phsamp case 'on' cumulX = zeros(size(win,2),g.timesout); end end; end switch g.phsamp case 'on' PA = zeros(size(P,1),size(P,1),g.timesout); % NB: (freqs,freqs,times) end % phs amp wintime = 1000/g.srate*(g.winsize/2); % (1000/g.srate)*(g.winsize/2); times = [g.tlimits(1)+wintime:(g.tlimits(2)-g.tlimits(1)-2*wintime)/(g.timesout-1):g.tlimits(2)-wintime]; ERPtimes = [g.tlimits(1):(g.tlimits(2)-g.tlimits(1))/(g.frames-1):g.tlimits(2)+0.000001]; ERPindices = []; for ti=times [tmp indx] = min(abs(ERPtimes-ti)); ERPindices = [ERPindices indx]; end ERPtimes = ERPtimes(ERPindices); % subset of ERP frames on t/f window centers if ~isempty(find(times < g.baseline)) baseln = find(times < g.baseline); % subtract means of pre-0 (centered) windows else baseln = 1:length(times); % use all times as baseline end if ~isnan(g.alpha) & length(baseln)==0 myprintf(g.verbose,'timef(): no window centers in baseline (times<%g) - shorten (max) window length.\n', g.baseline) return elseif ~isnan(g.alpha) & g.baseboot myprintf(g.verbose,' %d bootstrap windows in baseline (center times < %g).\n',... length(baseln), g.baseline) end dispf = find(freqs <= g.maxfreq); stp = (g.frames-g.winsize)/(g.timesout-1); myprintf(g.verbose,'Computing Event-Related Spectral Perturbation (ERSP) and\n'); switch g.type case 'phasecoher', myprintf(g.verbose,' Inter-Trial Phase Coherence (ITC) images based on %d trials\n',length(X)/g.frames); case 'phasecoher2', myprintf(g.verbose,' Inter-Trial Phase Coherence 2 (ITC) images based on %d trials\n',length(X)/g.frames); case 'coher', myprintf(g.verbose,' Linear Inter-Trial Coherence (ITC) images based on %d trials\n',length(X)/g.frames); end; myprintf(g.verbose,' of %d frames sampled at %g Hz.\n',g.frames,g.srate); myprintf(g.verbose,'Each trial contains samples from %d ms before to\n',g.tlimits(1)); myprintf(g.verbose,' %.0f ms after the timelocking event.\n',g.tlimits(2)); myprintf(g.verbose,'The window size used is %d samples (%g ms) wide.\n',g.winsize,2*wintime); myprintf(g.verbose,'The window is applied %d times at an average step\n',g.timesout); myprintf(g.verbose,' size of %g samples (%g ms).\n',stp,1000*stp/g.srate); myprintf(g.verbose,'Results are oversampled %d times; the %d frequencies\n',g.padratio,length(dispf)); myprintf(g.verbose,' displayed are from %2.1f Hz to %3.1f Hz.\n',freqs(dispf(1)),freqs(dispf(end))); if ~isnan(g.alpha) myprintf(g.verbose,'Only significant values (bootstrap p<%g) will be colored;\n',g.alpha) myprintf(g.verbose,' non-significant values will be plotted in green\n'); end trials = length(X)/g.frames; baselength = length(baseln); myprintf(g.verbose,'\nOf %d trials total, processing trial:',trials); % detrend over epochs (trials) if requested % ----------------------------------------- switch g.detrep case 'on' X = reshape(X, g.frames, length(X)/g.frames); X = X - mean(X,2)*ones(1, length(X(:))/g.frames); X = X(:)'; end; for i=1:trials if (rem(i,100)==0) myprintf(g.verbose,'\n'); end if (rem(i,10) == 0) myprintf(g.verbose,'%d',i); elseif (rem(i,2) == 0) myprintf(g.verbose,'.'); end ERP = blockave(X,g.frames); % compute the ERP trial average Wn = zeros(1,g.timesout); for j=1:g.timesout, tmpX = X([1:g.winsize]+floor((j-1)*stp)+(i-1)*g.frames); % pull out data g.frames tmpX = tmpX - mean(tmpX); % remove the mean for that window switch g.detret, case 'on', tmpX = detrend(tmpX); end; if ~any(isnan(tmpX)) if (g.cycles == 0) % FFT if ~isempty(g.mtaper) % apply multitaper (no hanning window) tmpXMT = fft(g.alltapers .* ... (tmpX(:) * ones(1,size(g.alltapers,2))), g.pad); %tmpXMT = tmpXMT(nfk(1)+1:nfk(2),:); tmpXMT = tmpXMT(2:g.padratio*g.winsize/2+1,:); PP(:,j) = mean(abs(tmpXMT).^2, 2); % power; can also ponderate multitaper by their eigenvalues v tmpX = win .* tmpX(:); tmpX = fft(tmpX, g.pad); tmpX = tmpX(2:g.padratio*g.winsize/2+1); else % TF and MC (12/2006): Calculation changes made so that % power can be correctly calculated from ERSP. tmpX = win .* tmpX(:); tmpX = fft(tmpX,g.padratio*g.winsize); tmpX = tmpX / g.winsize; % TF and MC (12/11/2006): normalization, divide by g.winsize tmpX = tmpX(2:g.padratio*g.winsize/2+1); PP(:,j) = 2/0.375*abs(tmpX).^2; % power % TF and MC (12/14/2006): multiply by 2 account for negative frequencies, % Counteract the reduction by a factor 0.375 % that occurs as a result of cosine (Hann) tapering. Refer to Bug 446 end; else % wavelet if ~isempty(g.mtaper) % apply multitaper tmpXMT = g.alltapers .* (tmpX(:) * ones(1,size(g.alltapers,2))); tmpXMT = transpose(win) * tmpXMT; PP(:,j) = mean(abs(tmpXMT).^2, 2); % power tmpX = transpose(win) * tmpX(:); else tmpX = transpose(win) * tmpX(:); PP(:,j) = abs(tmpX).^2; % power end end if abs(tmpX) < eps % If less than smallest possible machine value % (i.e. if it's zero) then call it 0. RR(:,j) = zeros(size(RR(:,j))); else switch g.type case { 'coher' }, RR(:,j) = tmpX; cumulX(:,j) = cumulX(:,j)+abs(tmpX).^2; case { 'phasecoher2' }, RR(:,j) = tmpX; cumulX(:,j) = cumulX(:,j)+abs(tmpX); case 'phasecoher', RR(:,j) = tmpX ./ abs(tmpX); % normalized cross-spectral vector switch g.phsamp case 'on' cumulX(:,j) = cumulX(:,j)+abs(tmpX); % accumulate for PA end end; end Wn(j) = 1; end switch g.phsamp case 'on' % PA (freq x freq x time) PA(:,:,j) = PA(:,:,j) + (tmpX ./ abs(tmpX)) * ((PP(:,j)))'; % cross-product: unit phase (column) % times amplitude (row) end end % window if ~isnan(g.alpha) % save surrogate data for bootstrap analysis j = 1; goodbasewins = find(Wn==1); if g.baseboot % use baseline windows only goodbasewins = find(goodbasewins<=baselength); end ngdbasewins = length(goodbasewins); if ngdbasewins>1 while j <= g.naccu i=ceil(rand*ngdbasewins); i=goodbasewins(i); Pboot(:,j) = Pboot(:,j) + PP(:,i); Rboot(:,j) = Rboot(:,j) + RR(:,i); switch g.type case 'coher', cumulXboot(:,j) = cumulXboot(:,j)+abs(tmpX).^2; case 'phasecoher2', cumulXboot(:,j) = cumulXboot(:,j)+abs(tmpX); end; j = j+1; end Rbn = Rbn + 1; end end % bootstrap Wn = find(Wn>0); if length(Wn)>0 P(:,Wn) = P(:,Wn) + PP(:,Wn); % add non-NaN windows R(:,Wn) = R(:,Wn) + RR(:,Wn); Rn(Wn) = Rn(Wn) + ones(1,length(Wn)); % count number of addends end end % trial % if coherence, perform the division % ---------------------------------- switch g.type case 'coher', R = R ./ ( sqrt( trials*cumulX ) ); if ~isnan(g.alpha) Rboot = Rboot ./ ( sqrt( trials*cumulXboot ) ); end; case 'phasecoher2', R = R ./ ( cumulX ); if ~isnan(g.alpha) Rboot = Rboot ./ cumulXboot; end; case 'phasecoher', R = R ./ (ones(size(R,1),1)*Rn); end; switch g.phsamp case 'on' tmpcx(1,:,:) = cumulX; % allow ./ below for j=1:g.timesout PA(:,:,j) = PA(:,:,j) ./ repmat(PP(:,j)', [size(PP,1) 1]); end end if min(Rn) < 1 myprintf(g.verbose,'timef(): No valid timef estimates for windows %s of %d.\n',... int2str(find(Rn==0)),length(Rn)); Rn(find(Rn<1))==1; return end P = P ./ (ones(size(P,1),1) * Rn); if isnan(g.powbase) myprintf(g.verbose,'\nComputing the mean baseline spectrum\n'); mbase = mean(P(:,baseln),2)'; else myprintf(g.verbose,'Using the input baseline spectrum\n'); mbase = g.powbase; end if ~isnan( g.baseline ) & ~isnan( mbase ) P = 10 * (log10(P) - repmat(log10(mbase(1:size(P,1)))',[1 g.timesout])); % convert to (10log10) dB else P = 10 * log10(P); end; Rsign = sign(imag(R)); if nargout > 7 for lp = 1:size(R,1) Rphase(lp,:) = rem(angle(R(lp,:)),2*pi); % replaced obsolete phase() -sm 2/1/6 end Rphase(find(Rphase>pi)) = 2*pi-Rphase(find(Rphase>pi)); Rphase(find(Rphase<-pi)) = -2*pi-Rphase(find(Rphase<-pi)); end R = abs(R); % convert coherence vector to magnitude if ~isnan(g.alpha) % if bootstrap analysis included . . . if Rbn>0 i = round(g.naccu*g.alpha); if isnan(g.pboot) Pboot = Pboot / Rbn; % normalize if ~isnan( g.baseline ) Pboot = 10 * (log10(Pboot) - repmat(log10(mbase)',[1 g.naccu])); else Pboot = 10 * log10(Pboot); end; Pboot = sort(Pboot'); Pboot = [mean(Pboot(1:i,:)) ; mean(Pboot(g.naccu-i+1:g.naccu,:))]; else Pboot = g.pboot; end if isnan(g.rboot) Rboot = abs(Rboot) / Rbn; Rboot = sort(Rboot'); Rboot = mean(Rboot(g.naccu-i+1:g.naccu,:)); else Rboot = g.rboot; end else myprintf(g.verbose,'No valid bootstrap trials...!\n'); end end switch lower(g.plotitc) case 'on', switch lower(g.plotersp), case 'on', ordinate1 = 0.67; ordinate2 = 0.1; height = 0.33; g.plot = 1; case 'off', ordinate2 = 0.1; height = 0.9; g.plot = 1; end; case 'off', ordinate1 = 0.1; height = 0.9; switch lower(g.plotersp), case 'on', ordinate1 = 0.1; height = 0.9; g.plot = 1; case 'off', g.plot = 0; end; end; if g.plot myprintf(g.verbose,'\nNow plotting...\n'); set(gcf,'DefaultAxesFontSize',AXES_FONT) colormap(jet(256)); pos = get(gca,'position'); q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]; end; switch lower(g.plotersp) case 'on' % %%%%%%% image the ERSP %%%%%%%%%%%%%%%%%%%%%%%%%% % h(1) = subplot('Position',[.1 ordinate1 .9 height].*s+q); PP = P; % PP will be ERSP power after if ~isnan(g.alpha) % zero out nonsignif. power differences PP(find((PP > repmat(Pboot(1,:)',[1 g.timesout])) ... & (PP < repmat(Pboot(2,:)',[1 g.timesout])))) = 0; end if ERSP_CAXIS_LIMIT == 0 ersp_caxis = [-1 1]*1.1*max(max(abs(P(dispf,:)))); else ersp_caxis = ERSP_CAXIS_LIMIT*[-1 1]; end if ~isnan( g.baseline ) imagesc(times,freqs(dispf),PP(dispf,:),ersp_caxis); else imagesc(times,freqs(dispf),PP(dispf,:)); end; set(gca,'ydir',g.hzdir); % make frequency ascend or descend if ~isempty(g.erspmax) caxis([-g.erspmax g.erspmax]); end; hold on plot([0 0],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth); % plot time 0 if ~isnan(g.marktimes) % plot marked time for mt = g.marktimes(:)' plot([mt mt],[0 freqs(max(dispf))],'--k','LineWidth',g.linewidth); end end hold off set(h(1),'YTickLabel',[],'YTick',[]) set(h(1),'XTickLabel',[],'XTick',[]) if ~isempty(g.vert) for index = 1:length(g.vert) line([g.vert(index), g.vert(index)], [min(freqs(dispf)) max(freqs(dispf))], 'linewidth', 1, 'color', 'm'); end; end; h(2) = gca; h(3) = cbar('vert'); % ERSP colorbar axes set(h(2),'Position',[.1 ordinate1 .8 height].*s+q) set(h(3),'Position',[.95 ordinate1 .05 height].*s+q) title([ 'ERSP(' g.unitpower ')' ]) E = [min(P(dispf,:));max(P(dispf,:))]; h(4) = subplot('Position',[.1 ordinate1-0.1 .8 .1].*s+q); % plot marginal ERSP means % below the ERSP image plot(times,E,[0 0],... [min(E(1,:))-max(max(abs(E)))/3 max(E(2,:))+max(max(abs(E)))/3], ... '--m','LineWidth',g.linewidth) axis([min(times) max(times) ... min(E(1,:))-max(max(abs(E)))/3 max(E(2,:))+max(max(abs(E)))/3]) tick = get(h(4),'YTick'); set(h(4),'YTick',[tick(1) ; tick(end)]) set(h(4),'YAxisLocation','right') set(h(4),'TickLength',[0.020 0.025]); xlabel('Time (ms)') ylabel( g.unitpower ) E = 10 * log10(mbase(dispf)); h(5) = subplot('Position',[0 ordinate1 .1 height].*s+q); % plot mean spectrum % to left of ERSP image plot(freqs(dispf),E,'LineWidth',g.linewidth) if ~isnan(g.alpha) hold on; plot(freqs(dispf),Pboot(:,dispf)+[E;E],'g', 'LineWidth',g.linewidth); plot(freqs(dispf),Pboot(:,dispf)+[E;E],'k:','LineWidth',g.linewidth) end axis([freqs(1) freqs(max(dispf)) min(E)-max(abs(E))/3 max(E)+max(abs(E))/3]) tick = get(h(5),'YTick'); if (length(tick)>1) set(h(5),'YTick',[tick(1) ; tick(end-1)]) end set(h(5),'TickLength',[0.020 0.025]); set(h(5),'View',[90 90]) xlabel('Frequency (Hz)') ylabel( g.unitpower ) if strcmp(g.hzdir,'normal') freqdir = 'reverse'; else freqdir = 'normal'; end set(h(5),'xdir',freqdir); % make frequency ascend or descend end; switch lower(g.plotitc) case 'on' % %%%%%%%%%%%% Image the ITC %%%%%%%%%%%%%%%%%% % h(6) = subplot('Position',[.1 ordinate2 .9 height].*s+q); % ITC image RR = R; % RR is the masked ITC (R) if ~isnan(g.alpha) RR(find(RR < repmat(Rboot(1,:)',[1 g.timesout]))) = 0; end if ITC_CAXIS_LIMIT == 0 coh_caxis = min(max(max(R(dispf,:))),1)*[-1 1]; % 1 WAS 0.4 ! else coh_caxis = ITC_CAXIS_LIMIT*[-1 1]; end if exist('Rsign') & strcmp(g.plotphase, 'on') imagesc(times,freqs(dispf),Rsign(dispf,:).*RR(dispf,:),coh_caxis); % <--- else imagesc(times,freqs(dispf),RR(dispf,:),coh_caxis); % <--- end if ~isempty(g.itcmax) caxis([-g.itcmax g.itcmax]); end; tmpcaxis = caxis; set(gca,'ydir',g.hzdir); % make frequency ascend or descend hold on plot([0 0],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth); if ~isnan(g.marktimes) for mt = g.marktimes(:)' plot([mt mt],[0 freqs(max(dispf))],'--k','LineWidth',g.linewidth); end end hold off set(h(6),'YTickLabel',[],'YTick',[]) set(h(6),'XTickLabel',[],'XTick',[]) if ~isempty(g.vert) for index = 1:length(g.vert) line([g.vert(index), g.vert(index)], ... [min(freqs(dispf)) max(freqs(dispf))], ... 'linewidth', 1, 'color', 'm'); end; end; h(7) = gca; h(8) = cbar('vert'); %h(9) = get(h(8),'Children'); set(h(7),'Position',[.1 ordinate2 .8 height].*s+q) set(h(8),'Position',[.95 ordinate2 .05 height].*s+q) set(h(8),'YLim',[0 tmpcaxis(2)]); title('ITC') % %%%%% plot the ERP below the ITC image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % E = mean(R(dispf,:)); ERPmax = max(ERP); ERPmin = min(ERP); ERPmax = ERPmax + 0.1*(ERPmax-ERPmin); ERPmin = ERPmin - 0.1*(ERPmax-ERPmin); h(10) = subplot('Position',[.1 ordinate2-0.1 .8 .1].*s+q); % ERP plot(ERPtimes,ERP(ERPindices),... [0 0],[ERPmin ERPmax],'--m','LineWidth',g.linewidth); hold on; plot([times(1) times(length(times))],[0 0], 'k'); axis([min(ERPtimes) max(ERPtimes) ERPmin ERPmax]); tick = get(h(10),'YTick'); set(h(10),'YTick',[tick(1) ; tick(end)]) set(h(10),'TickLength',[0.02 0.025]); set(h(10),'YAxisLocation','right') xlabel('Time (ms)') ylabel('\muV') if (~isempty(g.topovec)) if length(g.topovec) ~= 1, ylabel(''); end; % ICA component end; E = mean(R(dispf,:)'); h(11) = subplot('Position',[0 ordinate2 .1 height].*s+q); % plot the marginal mean % ITC left of the ITC image if ~isnan(g.alpha) plot(freqs(dispf),E,'LineWidth',g.linewidth); hold on; plot(freqs(dispf),Rboot(dispf),'g', 'LineWidth',g.linewidth); plot(freqs(dispf),Rboot(dispf),'k:','LineWidth',g.linewidth); axis([freqs(1) freqs(max(dispf)) 0 max([E Rboot(dispf)])+max(E)/3]) else plot(freqs(dispf),E,'LineWidth',g.linewidth) axis([freqs(1) freqs(max(dispf)) min(E)-max(E)/3 max(E)+max(E)/3]) end tick = get(h(11),'YTick'); set(h(11),'YTick',[tick(1) ; tick(length(tick))]) set(h(11),'View',[90 90]) set(h(11),'TickLength',[0.020 0.025]); xlabel('Frequency (Hz)') ylabel('ERP') if strcmp(g.hzdir,'normal') freqdir = 'reverse'; else freqdir = 'normal'; end set(gca,'xdir',freqdir); % make frequency ascend or descend % %%%%%%%%%%%%%%% plot a topoplot() %%%%%%%%%%%%%%%%%%%%%%% % if (~isempty(g.topovec)) h(12) = subplot('Position',[-.1 .43 .2 .14].*s+q); if length(g.topovec) == 1 topoplot(g.topovec,g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', g.chaninfo); else topoplot(g.topovec,g.elocs,'electrodes','off', 'chaninfo', g.chaninfo); end; axis('square') end end; % switch if g.plot try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if (length(g.title) > 0) axes('Position',pos,'Visible','Off'); h(13) = text(-.05,1.01,g.title); set(h(13),'VerticalAlignment','bottom') set(h(13),'HorizontalAlignment','left') set(h(13),'FontSize',TITLE_FONT); end axcopy(gcf); end; % symmetric Hanning tapering function % ----------------------------------- function w = hanning(n) if ~rem(n,2) w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end function myprintf(verbose, varargin) if strcmpi(verbose, 'on') fprintf(varargin{:}); end;
github
lcnhappe/happe-master
rsadjust.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/rsadjust.m
2,955
utf_8
45d8f416e2d360293ee83cb15f5e3976
% rsadjust() - adjust l-values (Ramberg-Schmeiser distribution) % with respect to signal mean and variance % % Usage: p = rsadjust(l3, l4, m, var, skew) % % Input: % l3 - value lambda3 for Ramberg-Schmeiser distribution % l4 - value lambda4 for Ramberg-Schmeiser distribution % m - mean of the signal distribution % var - variance of the signal distribution % skew - skewness of the signal distribution (only the sign of % this parameter is used). % % Output: % l1 - value lambda3 for Ramberg-Schmeiser distribution % l2 - value lambda4 for Ramberg-Schmeiser distribution % l3 - value lambda3 for Ramberg-Schmeiser distribution (copy % from input) % l4 - value lambda4 for Ramberg-Schmeiser distribution (copy % from input) % % Author: Arnaud Delorme, SCCN, 2003 % % See also: rsfit(), rsget() % % Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F. % A probability distribution and its uses in fitting data. % Technimetrics, 1979, 21: 201-214. % Copyright (C) 2003 Arnaud Delorme, SCCN, [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 [l1,l2,l3,l4] = rsadjust( l3, l4, mu, sigma2, m3); % swap l3 and l4 for negative skewness % ------------------------------------ if m3 < 0 ltmp = l4; l4 = l3; l3 = ltmp; end; A = 1/(1 + l3) - 1/(1 + l4); B = 1/(1 + 2*l3) + 1/(1 + 2*l4) - 2*beta(1+l3, 1+l4); C = 1/(1 + 3*l3) - 1/(1 + 3*l4) ... - 3*beta(1+2*l3, 1+l4) + 3*beta(1+l3, 1+2*l4); % compute l2 (and its sign) % ------------------------ l2 = sqrt( (B-A^2)/sigma2 ); if m3 == 0, m3 = -0.000000000000001; end; if (m3*(C - 2*A*B + 2*A^3)) < 0, l2 = -l2; end; %l22 = ((C - 2*A*B + 2*A^3)/m3)^(1/3) % also equal to l2 % compute l1 % ---------- l1 = mu - A/l2; return; % fitting table 1 of % --------------- [l1 l2] = pdffitsolv2(-.0187,-.0388, 0, 1, 1) [l1 l2] = pdffitsolv2(-.1359,-.1359, 0, 1, 0) % sign problem [l1 l2] = pdffitsolv2(1.4501,1.4501, 0, 1) % numerical problem for l1 [l1 l2] = pdffitsolv2(-.00000407,-.001076, 0, 1, 2) [l1 l2] = pdffitsolv2(0,-.000580, 0, 1, 2)
github
lcnhappe/happe-master
newcrossf.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/newcrossf.m
63,870
utf_8
cb2a530dbabd60d30681d5c293194574
% newcrossf() - Returns estimates and plots event-related coherence (ERCOH) % between two input data time series. A lower panel (optionally) shows % the coherence phase difference between the processes. In this panel: % In the plot output by > newcrossf(x,y,...); % 90 degrees (orange) means x leads y by a quarter cycle. % -90 degrees (blue) means y leads x by a quarter cycle. % Click on any subplot to view separately and zoom in/out. % % Function description: % Uses EITHER fixed-window, zero-padded FFTs (fastest) OR constant-Q % 0-padded wavelet DFTs (more even sensitivity across frequencies), % both Hanning-tapered. Output frequency spacing is the lowest % frequency ('srate'/'winsize') divided by the 'padratio'. % % If an 'alpha' value is given, then bootstrap statistics are % computed (from a distribution of 'naccu' (200) surrogate baseline % data epochs) for the baseline epoch, and non-significant features % of the output plots are zeroed (and shown in green). The baseline % epoch is all windows with center latencies < the given 'baseline' value % or, if 'baseboot' is 1, the whole epoch. % % Usage with single dataset: % >> [coh,mcoh,timesout,freqsout,cohboot,cohangles,... % allcoher,alltfX,alltfY] = newcrossf(x,y,frames,tlimits,srate, ... % cycles, 'key1', 'val1', 'key2', val2' ...); % % Example to compare two condition (coh. comp 1-2 EEG versus ALLEEG(2)): % >> [coh,mcoh,timesout,freqsout,cohboot,cohangles,... % allcoher,alltfX,alltfY] = newcrossf({EEG.icaact(1,:,:) ... % ALLEEG(2).icaact(1,:,:)},{{EEG.icaact(2,:,:) ... % ALLEEG(2).icaact(2,:,:)}},frames,tlimits,srate, ... % cycles, 'key1', 'val1', 'key2', val2' ...); % % Required inputs: % x = First single-channel data set (1,frames*nepochs) % Else, cell array {x1,x2} of two such data vectors to also % estimate (significant) coherence differences between two % conditions. % y = Second single-channel data set (1,frames*nepochs) % Else, cell array {y1,y2} of two such data vectors. % frames = Frames per epoch {750} % tlimits = [mintime maxtime] (ms) Epoch latency limits {[-1000 2000]} % srate = Data sampling rate (Hz) {250} % cycles = 0 -> Use FFTs (with constant window length) % = >0 -> Number of cycles in each analysis wavelet % = [cycles expfactor] -> if 0 < expfactor < 1, the number % of wavelet cycles expands with frequency from cycles % If expfactor = 1, no expansion; if = 0, constant % window length (as in FFT) {default cycles: 0} % % Optional Coherence Type: % 'type' = ['coher'|'phasecoher'|'amp'] Compute either linear coherence % ('coher'), phase coherence ('phasecoher') also known % as phase coupling factor', or amplitude correlations ('amp') % {default: 'phasecoher'}. Note that for amplitude correlation, % the significance threshold is computed using the corrcoef % function, so can be set arbitrary low without increase in % computation load. An additional type is 'crossspec' to compute % cross-spectrum between 2 processes (single-trial). This type % is automatically selected if user enter continuous data. % 'amplag' = [integer vector] allow to compute non 0 amplitude correlation % (using option 'amp' above). The vector given as parameter % indicates the point lags ([-4 -2 0 2 4] would compute the % correlation at time t-4, t-2, t, t+2, t+4, and return the % maximum correlation at these points). % 'subitc' = ['on'|'off'] Subtract stimulus locked Inter-Trial Coherence % from x and y. This computes the 'intrinsic' coherence % x and y not arising from common synchronization to % experimental events. For cell array input, one may provide % a cell array ({'on','off'} for example). {default: 'off'} % 'shuffle' = Integer indicating the number of estimates to compute % bootstrap coherence based on shuffled trials. This estimates % the coherence arising only from time locking of x and y % to experimental events (opposite of 'subitc'). For cell array % input, one may provide a cell array, for example { 1 0 }. % { default 0: no shuffling }. % % Optional Detrend: % 'detrend' = ['on'|'off'], Linearly detrend each data epoch {'off'} % 'rmerp' = ['on'|'off'], Remove epoch mean from data epochs {'off'} % % Optional FFT/DFT: % 'winsize' = If cycles==0: data subwindow length (fastest, 2^n<frames); % if cycles >0: *longest* window length to use. This % determines the lowest output frequency {~frames/8} % 'timesout' = Number of output latencies (int<frames-winframes). {200) % A negative value (-S) subsamples the original latencies % by S. An array of latencies computes spectral % decompositions at specific latency values (Note: the % algorithm finds the closest latencies in the data, % possibly resulting in slightly unevenly spaced % output latencies. % 'padratio' = FFT-length/winframes (2^k) {2} % Multiplies the number of output frequencies by dividing % their spacing (standard FFT padding). When cycles~=0, % frequency spacing is divided by padratio. % 'maxfreq' = Maximum frequency (Hz) to plot (& output if cycles>0) % If cycles==0, all FFT frequencies are output.{def: 50} % Note: NOW DEPRECATED, use 'freqs' instead, % 'freqs' = [min max] Frequency limits. {Default: [minfreq 50], % minfreq being determined by the number of data points, % cycles and sampling frequency}. % 'nfreqs' = Number of output frequencies. For FFT, closest computed % frequency will be returned. Overwrite 'padratio' effects % for wavelets. {Default: use 'padratio'}. % 'freqscale' = ['log'|'linear'] Frequency scaling. {Default: 'linear'}. % Note that for obtaining 'log' spaced freqs using FFT, % closest correspondant frequencies in the 'linear' space % are returned. % 'baseline' = Spectral baseline end-time (in ms). NaN imply that no % baseline is used. A range [min max] may also be entered % You may also enter one row per region for baseline % e.g. [0 100; 300 400] considers the window 0 to 100 ms and % 300 to 400 ms. This is only valid for the coherence amplitude % not for the coherence phase. { default NaN } % 'lowmem' = ['on'|'off'] {'off'} Compute frequency by frequency to % save memory. % % Optional Bootstrap: % 'alpha' = If non-0, compute two-tailed bootstrap significance prob. % level. Show non-signif output values in neutral green. {0} % 'naccu' = Number of bootstrap replications to compute {200} % 'boottype' = ['shuffle'|'shufftrials'|'rand'|'randall'] Bootstrap type: Either % shuffle time and trial windows ('shuffle' default) or trials only % using a separate bootstrap for each time window ('shufftrials'). % Option 'rand' randomize the phase. Option 'randall' randomize the % phase for each individual time/frequency point. % 'baseboot' = Bootstrap baseline subtract (1 -> use 'baseline'; Default % 0 -> use whole trial % [min max] -> use time range) % Default is to use the baseline unless no baseline is % specified (then the function uses all sample up to time 0) % You may also enter one row per region for baseline % e.g. [0 100; 300 400] considers the window 0 to 100 ms and % 300 to 400 ms. % 'condboot' = ['abs'|'angle'|'complex'] In comparing two conditions, % either subtract complex spectral values' absolute vales % ('abs'), angles ('angles') or the complex values themselves % ('complex'). {default: 'abs'} % 'rboot' = Input bootstrap coherence limits (e.g., from newcrossf()) % The bootstrap type should be identical to that used % to obtain the input limits. {default: compute from data} % Optional scalp map plot: % 'topovec' = (2,nchans) matrix. Scalp maps to plot {[]} % ELSE [c1,c2], plot two cartoons showing channel locations. % 'elocs' = Electrode location file for scalp map {none} % File should be ascii in format of >> topoplot example % 'chaninfo' = Electrode location additional information (nose position...) % {default: none} % % Optional plot and compute features: % 'plottype' = ['image'|'curve'] plot time frequency images or % curves (one curve per frequency). Default is 'image'. % 'plotmean' = ['on'|'off'] For 'curve' plots only. Average all % frequencies given as input. Default: 'on'. % 'highlightmode' = ['background'|'bottom'] For 'curve' plots only, % display significant time regions either in the plot background % or underneatht the curve. % 'plotamp' = ['on'|'off']. Plot coherence magnitude {'on'} % 'maxamp' = [real] Set the maximum for the amplitude scale {auto} % 'plotphase' = ['on'|'off']. Plot coherence phase angle {'on'} % 'angleunit' = Phase units: 'ms' for msec or 'deg' for degrees or 'rad' % for radians {'deg'} % 'title' = Optional figure title. If two conditions are given % as input, title can be a cell array with two text % string elements {none} % 'vert' = Latencies to mark with a dotted vertical line {none} % 'linewidth' = Line width for marktimes traces (thick=2, thin=1) {2} % 'newfig' = ['on'|'off'] Create new figure for difference plots {'on'} % 'axesfont' = Axes font size {10} % 'titlefont' = Title font size {8} % % Outputs: % coh = Matrix (nfreqs,timesout) of coherence magnitudes. Not % that for continuous data, the function is returning the % cross-spectrum. % mcoh = Vector of mean baseline coherence at each frequency % see 'baseline' parameter. % timesout = Vector of output latencies (window centers) (ms). % freqsout = Vector of frequency bin centers (Hz). % cohboot = Matrix (nfreqs) of upper coher signif. limits % if 'boottype' is 'trials', (nfreqs,timesout) % cohangle = (nfreqs,timesout) matrix of coherence angles in radian % allcoher = single trial coherence % alltfX = single trial spectral decomposition of X % alltfY = single trial spectral decomposition of Y % % Plot description: % Assuming both 'plotamp' and 'plotphase' options are 'on' (=default), the upper panel % presents the magnitude of either phase coherence or linear coherence, depending on % the 'type' parameter (above). The lower panel presents the coherence phase difference % (in degrees). Click on any plot to pop up a new window (using 'axcopy()'). % -- The upper left marginal panel shows mean coherence during the baseline period % (blue), and when significance is set, the significance threshold (dotted black-green). % -- The horizontal panel under the coherence magnitude image indicates the maximum % (green) and minimum (blue) coherence values across all frequencies. When significance % is set (using option 'trials' for 'boottype'), an additional curve indicates the % significance threshold (dotted black-green). % % Notes: 1) When cycles==0, nfreqs is total number of FFT frequencies. % 2) 'blue' coherence lag -> x leads y; 'red' -> y leads x % 3) The 'boottype' should be ideally 'timestrials', but this creates % large memory demands, so 'times' must be used in many cases. % 4) If 'boottype' is 'trials', the average of the complex bootstrap % is subtracted from the coherence to compensate for phase differences % (the average is also subtracted from the bootstrap distribution). % For other bootstraps, this is not necessary since there the phase % distribution should be random. % 5) If baseline is non-NaN, the baseline is subtracted from % the complex coherence. On the left hand side of the coherence % amplitude image, the baseline is displayed as a magenta line. % (If no baseline is selected, this curve represents the average % coherence at every given frequency). % % Authors: Arnaud Delorme, Sigurd Enghoff & Scott Makeig % CNL/Salk Institute 1998-2001; SCCN/INC/UCSD, La Jolla, 2002- % % See also: timef() % NOTE: one hidden parameter 'savecoher', 0 or 1 % Copyright (C) 8/1/98 Arnaud Delorme, Sigurd Enghoff & Scott Makeig, SCCN/INC/UCSD % % 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 % 11-20-98 defined g.linewidth constant -sm % 04-01-99 made number of frequencies consistent -se % 06-29-99 fixed constant-Q freq indexing -se % 08-13-99 added cohangle plotting -sm % 08-20-99 made bootstrap more efficient -sm % 08-24-99 allow nan values introduced by possible eventlock() preproc. -sm % 03-16-00 added lead/lag interpretation to help msg - sm & eric visser % 03-16-00 added axcopy() feature -sm & tpj % 04-20-00 fixed Rangle sign for wavelets, added verts array -sm % 01-22-01 corrected help msg when nargin<2 -sm & arno delorme % 01-25-02 reformated help & license, added links -ad % 03-09-02 function restructuration -ad % add 'key', val arguments (+ external baseboot, baseline, color axis, angleunit...) % add detrending (across time and trials) + 'coher' option for amplitude coherence % significance only if alpha is given, ploting options in 'plotamp' and 'plotphase' % 03-16-02 timeout automatically adjusted if too high -ad % 04-03-02 added new options for bootstrap -ad % There are 3 "objects" Tf, Coher and Boot which are handled % - by specific functions under Matlab % (Tf) function Tf = tfinit(...) - create object Time Frequency (Tf) associated with some data % (Tf) function [Tf, itcvals] = tfitc(...) - compute itc for the selected data % (Tf) function [Tf, itcvals] = tfitcpost(Tf, trials) - itc normlisation % (Tf) function [Tf, tmpX] = tfcomp(Tf, trials, times) - compute time freq. decomposition % (Coher) function Coher = coherinit(...) - initialize coherence object % (Coher) function Coher = cohercomp(Coher, tmpX, tmpY, trial, time) - compute coherence % (Coher) function Coher = cohercomppost(Coher, trials) - coherence normalization % (Boot) function Boot = bootinit(...) - intialize bootstrap object % (Boot) function Boot = bootcomp(...) - compute bootstrap % (Boot) function [Boot, Rbootout] = bootcomppost(...) - bootstrap normalization % - by real objects under C++ (see C++ code) function [R,mbase,timesout,freqs,Rbootout,Rangle, coherresout, alltfX, alltfY] = newcrossf(X, Y, frame, tlimits, Fs, varwin, varargin) %varwin,winsize,nwin,oversmp,maxfreq,alpha,verts,caxmax) % Commandline arg defaults: DEFAULT_ANGLEUNITS = 'deg'; % angle plotting units - 'ms' or 'deg' DEFAULT_EPOCH = 750; % Frames per epoch DEFAULT_TIMELIM = [-1000 2000]; % Time range of epochs (ms) DEFAULT_FS = 250; % Sampling frequency (Hz) DEFAULT_NWIN = 200; % Number of windows = horizontal resolution DEFAULT_VARWIN = 0; % Fixed window length or base on cycles. % =0: fix window length to nwin % >0: set window length equal varwin cycles % bounded above by winsize, also determines % the min. freq. to be computed. DEFAULT_OVERSMP = 2; % Number of times to oversample = vertical resolution DEFAULT_MAXFREQ = 50; % Maximum frequency to display (Hz) DEFAULT_TITLE = 'Event-Related Coherence'; % Figure title DEFAULT_ALPHA = NaN; % Default two-sided significance probability threshold %disp('WARNING: this function is not part of the EEGLAB toolbox and should not be distributed'); %disp(' you must contact Arnaud Delorme ([email protected]) for terms of use'); if (nargin < 2) help newcrossf return end coherresout = []; if ~iscell(X) if (min(size(X))~=1 | length(X)<2) fprintf('crossf(): x must be a row or column vector.\n'); return elseif (min(size(Y))~=1 | length(Y)<2) fprintf('crossf(): y must be a row or column vector.\n'); return elseif (length(X) ~= length(Y)) fprintf('crossf(): x and y must have same length.\n'); return end end; if (nargin < 3) frame = DEFAULT_EPOCH; elseif (~isnumeric(frame) | length(frame)~=1 | frame~=round(frame)) fprintf('crossf(): Value of frames must be an integer.\n'); return elseif (frame <= 0) fprintf('crossf(): Value of frames must be positive.\n'); return elseif ~iscell(X) & (rem(size(X,2),frame) ~= 0) & (rem(size(X,1),frame) ~= 0) fprintf('crossf(): Length of data vectors must be divisible by frames.\n'); return end if (nargin < 4) tlimits = DEFAULT_TIMELIM; elseif (~isnumeric(tlimits) | sum(size(tlimits))~=3) error('crossf(): Value of tlimits must be a vector containing two numbers.'); elseif (tlimits(1) >= tlimits(2)) error('crossf(): tlimits interval must be [min,max].'); end if (nargin < 5) Fs = DEFAULT_FS; elseif (~isnumeric(Fs) | length(Fs)~=1) error('crossf(): Value of srate must be a number.'); elseif (Fs <= 0) error('crossf(): Value of srate must be positive.'); end if (nargin < 6) varwin = DEFAULT_VARWIN; elseif (~isnumeric(varwin) | length(varwin)>2) error('crossf(): Value of cycles must be a number or a (1,2) vector.'); elseif (varwin < 0) error('crossf(): Value of cycles must be either zero or positive.'); end % consider structure for these arguments % -------------------------------------- vararginori = varargin; for index=1:length(varargin) if iscell(varargin{index}), varargin{index} = { varargin{index} }; end; end; if ~isempty(varargin) [tmp indices] = unique_bc(varargin(1:2:end)); % keep the first one varargin = varargin(sort(union(indices*2-1, indices*2))); % these 2 line remove duplicate arguments try, g = struct(varargin{:}); catch, error('Argument error in the {''param'', value} sequence'); end; else g = []; end; try, g.condboot; catch, g.condboot = 'abs'; end; try, g.shuffle; catch, g.shuffle = 0; end; try, g.title; catch, g.title = DEFAULT_TITLE; end; try, g.winsize; catch, g.winsize = max(pow2(nextpow2(frame)-3),4); end; try, g.pad; catch, g.pad = max(pow2(nextpow2(g.winsize)),4); end; try, g.timesout; catch, g.timesout = DEFAULT_NWIN; end; try, g.padratio; catch, g.padratio = DEFAULT_OVERSMP; end; try, g.topovec; catch, g.topovec = []; end; try, g.elocs; catch, g.elocs = ''; end; try, g.alpha; catch, g.alpha = DEFAULT_ALPHA; end; try, g.marktimes; catch, g.marktimes = []; end; % default no vertical lines try, g.marktimes = g.vert; catch, g.vert = []; end; % default no vertical lines try, g.rboot; catch, g.rboot = []; end; try, g.plotamp; catch, g.plotamp = 'on'; end; try, g.plotphase; catch, g.plotphase = 'on'; end; try, g.plotbootsub; catch, g.plotbootsub = 'on'; end; try, g.detrend; catch, g.detrend = 'off'; end; try, g.rmerp; catch, g.rmerp = 'off'; end; try, g.baseline; catch, g.baseline = NaN; end; try, g.baseboot; catch, g.baseboot = 1; end; try, g.linewidth; catch, g.linewidth = 2; end; try, g.maxfreq; catch, g.maxfreq = DEFAULT_MAXFREQ; end; try, g.freqs; catch, g.freqs = [0 g.maxfreq]; end; try, g.nfreqs; catch, g.nfreqs = []; end; try, g.freqscale; catch, g.freqscale = 'linear'; end; try, g.naccu; catch, g.naccu = 200; end; try, g.angleunit; catch, g.angleunit = DEFAULT_ANGLEUNITS; end; try, g.type; catch, g.type = 'phasecoher'; end; try, g.newfig; catch, g.newfig = 'on'; end; try, g.boottype; catch, g.boottype = 'shuffle'; end; try, g.subitc; catch, g.subitc = 'off'; end; try, g.compute; catch, g.compute = 'matlab'; end; try, g.maxamp; catch, g.maxamp = []; end; try, g.savecoher; catch, g.savecoher = 0; end; try, g.amplag; catch, g.amplag = 0; end; try, g.noinput; catch, g.noinput = 'no'; end; try, g.lowmem; catch, g.lowmem = 'off'; end; try, g.plottype; catch, g.plottype = 'image'; end; try, g.plotmean; catch, g.plotmean = 'on'; end; try, g.highlightmode; catch, g.highlightmode = 'background'; end; try, g.chaninfo; catch, g.chaninfo = []; end; if isfield(g, 'detret'), g.detrend = g.detret; end; if isfield(g, 'detrep'), g.rmerp = g.detrep; end; if ~isnan(g.alpha) && ndims(X) == 2 && (size(X,1) == 1 || size(X,2) == 1) error('Cannot compute significance for continuous data'); end; allfields = fieldnames(g); for index = 1:length(allfields) switch allfields{index} case { 'shuffle' 'title' 'winsize' 'pad' 'timesout' 'padratio' 'maxfreq' 'topovec' 'elocs' 'alpha' ... 'marktimes' 'vert' 'rboot' 'plotamp' 'plotphase' 'plotbootsub' 'detrep' 'rmerp' 'detret' 'detrend' ... 'baseline' 'baseboot' 'linewidth' 'naccu' 'angleunit' 'type' 'boottype' 'subitc' 'lowmem' 'plottype' ... 'compute' 'maxamp' 'savecoher' 'noinput' 'condboot' 'newfig' 'freqs' 'nfreqs' 'freqscale' 'amplag' ... 'highlightmode' 'plotmean' 'chaninfo' }; case {'plotersp' 'plotitc' }, disp(['crossf warning: timef option ''' allfields{index} ''' ignored']); otherwise disp(['crossf error: unrecognized option ''' allfields{index} '''']); beep; return; end; end; g.tlimits = tlimits; g.frame = frame; if ~iscell(X) g.trials = prod(size(X))/g.frame; else g.trials = prod(size(X{1}))/g.frame; end; g.srate = Fs; g.cycles = varwin; g.type = lower(g.type); g.boottype = lower(g.boottype); g.rmerp = lower(g.rmerp); g.detrend = lower(g.detrend); g.plotphase = lower(g.plotphase); g.plotbootsub = lower(g.plotbootsub); g.subitc = lower(g.subitc); g.plotamp = lower(g.plotamp); g.compute = lower(g.compute); g.AXES_FONT = 10; g.TITLE_FONT = 14; % change type if necessary if g.trials == 1 & ~strcmpi(g.type, 'crossspec') disp('Continuous data: switching to crossspectrum'); g.type = 'crossspec'; end; if strcmpi(g.freqscale, 'log') & g.freqs(1) == 0, g.freqs(1) = 3; end; % reshape 3D inputs % ----------------- if ndims(X) == 3 X = reshape(X, size(X,1), size(X,2)*size(X,3)); Y = reshape(Y, size(Y,1), size(Y,2)*size(Y,3)); end; % testing arguments consistency % ----------------------------- if strcmpi(g.title, DEFAULT_TITLE) switch g.type case 'coher', g.title = 'Event-Related Coherence'; % Figure title case 'phasecoher', g.title = 'Event-Related Phase Coherence'; case 'phasecoher2', g.title = 'Event-Related Phase Coherence 2'; case 'amp' , g.title = 'Event-Related Amplitude Correlation'; case 'crossspec', g.title = 'Event-Related Amplitude Correlation'; end; end; if ~ischar(g.title) & ~iscell(g.title) error('Title must be a string or a cell array.'); end if isempty(g.topovec) g.topovec = []; elseif min(size(g.topovec))==1 g.topovec = g.topovec(:); if size(g.topovec,1)~=2 error('topovec must be a row or column vector.'); end end; if isempty(g.elocs) g.elocs = ''; elseif (~ischar(g.elocs)) & ~isstruct(g.elocs) error('Channel location file must be a valid text file.'); end if (~isnumeric(g.alpha) | length(g.alpha)~=1) error('timef(): Value of g.alpha must be a number.\n'); elseif (round(g.naccu*g.alpha) < 2) fprintf('Value of g.alpha is out of the normal range [%g,0.5]\n',2/g.naccu); g.naccu = round(2/g.alpha); fprintf(' Increasing the number of bootstrap iterations to %d\n',g.naccu); end if g.alpha>0.5 | g.alpha<=0 error('Value of g.alpha is out of the allowed range (0.00,0.5).'); end switch lower(g.newfig) case { 'on', 'off' }, ; otherwise error('newfig must be either on or off'); end; switch g.angleunit case { 'ms', 'deg', 'rad' },; otherwise error('Angleunit must be either ''deg'', ''rad'', or ''ms'''); end; switch g.type case { 'coher', 'phasecoher' 'phasecoher2' 'amp' 'crossspec' },; otherwise error('Type must be either ''coher'', ''phasecoher'', ''crossspec'', or ''amp'''); end; switch g.boottype case { 'shuffle' 'shufftrials' 'rand' 'randall'},; otherwise error('Invalid boot type'); end; if ~isnumeric(g.shuffle) & ~iscell(g.shuffle) error('Shuffle argument type must be numeric'); end; switch g.compute case { 'matlab', 'c' },; otherwise error('compute must be either ''matlab'' or ''c'''); end; if ~strcmpi(g.condboot, 'abs') & ~strcmpi(g.condboot, 'angle') ... & ~strcmpi(g.condboot, 'complex') error('Condboot must be either ''abs'', ''angle'' or ''complex''.'); end; if g.tlimits(2)-g.tlimits(1) < 30 disp('Crossf WARNING: time range is very small (<30 ms). Times limits are in millisenconds not seconds.'); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute frequency by frequency if low memory %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmpi(g.lowmem, 'on') & ~iscell(X) & length(X) ~= g.frame & (isempty(g.nfreqs) | g.nfreqs ~= 1) % compute for first 2 trials to get freqsout XX = reshape(X, 1, frame, length(X)/g.frame); YY = reshape(Y, 1, frame, length(Y)/g.frame); [coh,mcoh,timesout,freqs] = newcrossf(XX(1,:,1), YY(1,:,1), frame, tlimits, Fs, varwin, 'plotamp', 'off', 'plotphase', 'off',varargin{:}); % scan all frequencies for index = 1:length(freqs) if nargout < 6 [R(index,:),mbase(index),timesout,tmpfreqs(index),Rbootout(index,:),Rangle(index,:)] = ... newcrossf(X, Y, frame, tlimits, Fs, varwin, 'freqs', [freqs(index) freqs(index)], 'nfreqs', 1, ... 'plotamp', 'off', 'plotphase', 'off',varargin{:}, 'lowmem', 'off', 'timesout', timesout); elseif nargout == 7 % requires RAM [R(index,:),mbase(index),timesout,tmpfreqs(index),Rbootout(index,:),Rangle(index,:), ... coherresout(index,:,:)] = ... newcrossf(X, Y, frame, tlimits, Fs, varwin, 'freqs', [freqs(index) freqs(index)], 'nfreqs', 1, ... 'plotamp', 'off', 'plotphase', 'off',varargin{:}, 'lowmem', 'off', 'timesout', timesout); else [R(index,:),mbase(index),timesout,tmpfreqs(index),Rbootout(index,:),Rangle(index,:), ... coherresout(index,:,:),alltfX(index,:,:),alltfY(index,:,:)] = ... newcrossf(X, Y, frame, tlimits, Fs, varwin, 'freqs', [freqs(index) freqs(index)], 'nfreqs', 1, ... 'plotamp', 'off', 'plotphase', 'off',varargin{:}, 'lowmem', 'off', 'timesout', timesout); end; end; % plot and return plotall(R.*exp(j*Rangle), Rbootout, timesout, freqs, mbase, g); return; end; %%%%%%%%%%%%%%%%%%%%%%%%%%% % compare 2 conditions part %%%%%%%%%%%%%%%%%%%%%%%%%%% if iscell(X) if length(X) ~= 2 | length(Y) ~= 2 error('crossf: to compare conditions, X and Y input must be 2-elements cell arrays'); end; % deal with titles % ---------------- for index = length(vararginori)-1:-2:1 if index<=length(vararginori) % needed: if elemenets are deleted if strcmp(vararginori{index}, 'title') , vararginori(index:index+1) = []; end; if strcmp(vararginori{index}, 'subitc'), vararginori(index:index+1) = []; end; if strcmp(vararginori{index}, 'shuffle'), vararginori(index:index+1) = []; end; end; end; if ~iscell(g.subitc) g.subitc = { g.subitc g.subitc }; end; if ~iscell(g.shuffle) g.shuffle = { g.shuffle g.shuffle }; end; if iscell(g.title) if length(g.title) <= 2, g.title{3} = 'Condition 1 - condition 2'; end; else g.title = { 'Condition 1', 'Condition 2', 'Condition 1 - condition 2' }; end; fprintf('Running newcrossf on condition 1 *********************\n'); fprintf('Note: if an out-of-memory error occurs, try reducing the\n'); fprintf(' number of time points or number of frequencies\n'); fprintf(' (the ''coher'' options takes 3 times more memory than other options)\n'); if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') if strcmpi(g.newfig, 'on'), figure; end; subplot(1,3,1); end; if ~strcmp(g.type, 'coher') & nargout < 9 [R1,mbase,timesout,freqs,Rbootout1,Rangle1, savecoher1] = newcrossf(X{1}, Y{1}, ... frame, tlimits, Fs, varwin, 'savecoher', 1, 'title', g.title{1}, ... 'shuffle', g.shuffle{1}, 'subitc', g.subitc{1}, vararginori{:}); else [R1,mbase,timesout,freqs,Rbootout1,Rangle1, savecoher1, Tfx1, Tfy1] = newcrossf(X{1}, Y{1}, ... frame, tlimits, Fs, varwin, 'savecoher', 1, 'title', g.title{1}, ... 'shuffle', g.shuffle{1}, 'subitc', g.subitc{1}, vararginori{:}); end; R1 = R1.*exp(j*Rangle1/180*pi); fprintf('\nRunning newcrossf on condition 2 *********************\n'); if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') subplot(1,3,2); end; if ~strcmp(g.type, 'coher') & nargout < 9 [R2,mbase,timesout,freqs,Rbootout2,Rangle2, savecoher2] = newcrossf(X{2}, Y{2}, ... frame, tlimits, Fs, varwin,'savecoher', 1, 'title', g.title{2}, ... 'shuffle', g.shuffle{2}, 'subitc', g.subitc{2}, vararginori{:}); else [R2,mbase,timesout,freqs,Rbootout2,Rangle2, savecoher2, Tfx2, Tfy2] = newcrossf(X{2}, Y{2}, ... frame, tlimits, Fs, varwin,'savecoher', 1, 'title', g.title{2}, ... 'shuffle', g.shuffle{2}, 'subitc', g.subitc{2}, vararginori{:} ); end; %figure; imagesc(abs( sum( savecoher1 ./ abs(savecoher1), 3)) - abs( sum( savecoher2 ./ abs(savecoher2), 3) )); cbar; return; %figure; imagesc(abs( R2 ) - abs( R1) ); cbar; return; R2 = R2.*exp(j*Rangle2/180*pi); if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') subplot(1,3,3); end; if isnan(g.alpha) switch(g.condboot) case 'abs', Rdiff = abs(R1)-abs(R2); case 'angle', Rdiff = angle(R1)-angle(R2); case 'complex', Rdiff = R1-R2; end; g.title = g.title{3}; if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') plotall(Rdiff, [], timesout, freqs, mbase, g); end; Rbootout = []; else % preprocess data and run condstat % -------------------------------- switch g.type case 'coher', % take the square of alltfx and alltfy first to speed up Tfx1 = Tfx1.*conj(Tfx1); Tfx2 = Tfx2.*conj(Tfx2); Tfy1 = Tfy1.*conj(Tfy1); Tfy2 = Tfy2.*conj(Tfy2); formula = 'sum(arg1(:,:,X),3) ./ sqrt(sum(arg2(:,:,X),3)) ./ sqrt(sum(arg3(:,:,X),3))'; if strcmpi(g.lowmem, 'on') for ind = 1:2:size(savecoher1,1) if ind == size(savecoher1,1), indarr = ind; else indarr = [ind:ind+1]; end; [Rdiff(indarr,:,:) coherimages(indarr,:,:) coher1(indarr,:,:) coher2(indarr,:,:)] = condstat(formula, g.naccu, g.alpha, ... 'both', g.condboot, { savecoher1(indarr,:,:) savecoher2(indarr,:,:) }, ... { Tfx1(indarr,:,:) Tfx2(indarr,:,:) }, { Tfy1(indarr,:,:) Tfy2(indarr,:,:) }); end; else [Rdiff coherimages coher1 coher2] = condstat(formula, g.naccu, g.alpha, ... 'both', g.condboot, { savecoher1 savecoher2 }, { Tfx1 Tfx2 }, { Tfy1 Tfy2 }); end; case 'amp' % amplitude correlation error('Cannot compute difference of amplitude correlation images yet'); case 'crossspec' % amplitude correlation error('Cannot compute difference of cross-spectral decomposition'); case 'phasecoher', % normalize first to speed up savecoher1 = savecoher1 ./ sqrt(savecoher1.*conj(savecoher1)); savecoher2 = savecoher2 ./ sqrt(savecoher2.*conj(savecoher2)); % twice faster than abs() formula = 'sum(arg1(:,:,X),3) ./ length(X)'; if strcmpi(g.lowmem, 'on') for ind = 1:2:size(savecoher1,1) if ind == size(savecoher1,1), indarr = ind; else indarr = [ind:ind+1]; end; [Rdiff(indarr,:,:) coherimages(indarr,:,:) coher1(indarr,:,:) coher2(indarr,:,:)] = condstat(formula, g.naccu, g.alpha, ... 'both', g.condboot, { savecoher1(indarr,:,:) savecoher2(indarr,:,:) } ); end; else [Rdiff coherimages coher1 coher2] = condstat(formula, g.naccu, g.alpha, 'both', g.condboot, ... { savecoher1 savecoher2 }); end; case 'phasecoher2', savecoher1 = savecoher1 ./ sqrt(savecoher1.*conj(savecoher1)); savecoher2 = savecoher2 ./ sqrt(savecoher2.*conj(savecoher2)); % twice faster than abs() formula = 'sum(arg1(:,:,X),3) ./ sum(sqrt(arg1(:,:,X).*conj(arg1(:,:,X)))),3)'; % sqrt(a.*conj(a)) is about twice faster than abs() if strcmpi(g.lowmem, 'on') for ind = 1:2:size(savecoher1,1) if ind == size(savecoher1,1), indarr = ind; else indarr = [ind:ind+1]; end; [Rdiff(indarr,:,:) coherimages(indarr,:,:) coher1(indarr,:,:) coher2(indarr,:,:)] = condstat(formula, g.naccu, g.alpha, ... 'both', g.condboot, { savecoher1(indarr,:,:) savecoher2(indarr,:,:) } ); end; else [Rdiff coherimages coher1 coher2] = condstat(formula, g.naccu, g.alpha, 'both', g.condboot, ... { savecoher1 savecoher2 }); end; end; %Boot = bootinit( [], size(savecoher1,1), g.timesout, g.naccu, 0, g.baseboot, 'noboottype', g.alpha, g.rboot); %Boot.Coherboot.R = coherimages; %Boot = bootcomppost(Boot, [], [], []); g.title = g.title{3}; g.boottype = 'shufftrials'; if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') plotall(Rdiff, coherimages, timesout, freqs, mbase, g); end; % outputs Rbootout = {Rbootout1 Rbootout2 coherimages}; end; if size(Rdiff,3) > 1, Rdiff = reshape(Rdiff, 1, size(Rdiff,3)); end; R = { abs(R1) abs(R2) fastif(isreal(Rdiff), Rdiff, abs(Rdiff)) }; Rangle = { angle(R1) angle(R2) angle(Rdiff) }; coherresout = []; if nargout >=9 alltfX = { Tfx1 Tfx2 }; alltfY = { Tfy1 Tfy2 }; end; return; % ********************************** END FOR SEVERAL CONDITIONS end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % shuffle trials if necessary %%%%%%%%%%%%%%%%%%%%%%%%%%%%% if g.shuffle ~= 0 fprintf('x and y data trials being shuffled %d times\n',g.shuffle); XX = reshape(X, 1, frame, length(X)/g.frame); YY = Y; X = []; Y = []; for index = 1:g.shuffle XX = shuffle(XX,3); X = [X XX(:,:)]; Y = [Y YY]; end; end; % detrend over epochs (trials) if requested % ----------------------------------------- switch g.rmerp case 'on' X = reshape(X, g.frame, length(X)/g.frame); X = X - mean(X,2)*ones(1, length(X(:))/g.frame); Y = reshape(Y, g.frame, length(Y)/g.frame); Y = Y - mean(Y,2)*ones(1, length(Y(:))/g.frame); end; %%%%%%%%%%%%%%%%%%%%%% % display text to user %%%%%%%%%%%%%%%%%%%%%% fprintf('\nComputing the Event-Related \n'); switch g.type case 'phasecoher', fprintf('Phase Coherence (ITC) images based on %d trials\n',g.trials); case 'phasecoher2', fprintf('Phase Coherence 2 (ITC) images based on %d trials\n',g.trials); case 'coher', fprintf('Linear Coherence (ITC) images based on %d trials\n',g.trials); case 'amp', fprintf('Amplitude correlation images based on %d trials\n',g.trials); case 'crossspec', fprintf('Cross-spectral images based on %d trials\n',g.trials); end; if ~isnan(g.alpha) fprintf('Bootstrap confidence limits will be computed based on alpha = %g\n', g.alpha); else fprintf('Bootstrap confidence limits will NOT be computed.\n'); end switch g.plotphase case 'on', fprintf(['Coherence angles will be imaged in ',g.angleunit,'\n']); end; %%%%%%%%%%%%%%%%%%%%%%% % main computation loop %%%%%%%%%%%%%%%%%%%%%%% % ------------------------------------- % compute time frequency decompositions % ------------------------------------- if length(g.timesout) > 1, tmioutopt = { 'timesout' , g.timesout }; else tmioutopt = { 'ntimesout', g.timesout }; end; spectraloptions = { tmioutopt{:}, 'winsize', g.winsize, 'tlimits', g.tlimits, 'detrend', ... g.detrend, 'subitc', g.subitc, 'wavelet', g.cycles, 'padratio', g.padratio, ... 'freqs' g.freqs 'freqscale' g.freqscale 'nfreqs' g.nfreqs }; if ~strcmpi(g.type, 'amp') & ~strcmpi(g.type, 'crossspec') spectraloptions = { spectraloptions{:} 'itctype' g.type }; end; fprintf('\nProcessing first input\n'); X = reshape(X, g.frame, g.trials); [alltfX freqs timesout] = timefreq(X, g.srate, spectraloptions{:}); fprintf('\nProcessing second input\n'); Y = reshape(Y, g.frame, g.trials); [alltfY] = timefreq(Y, g.srate, spectraloptions{:}); % ------------------ % compute coherences % ------------------ tmpprod = alltfX .* conj(alltfY); if nargout > 6 | strcmpi(g.type, 'phasecoher2') | strcmpi(g.type, 'phasecoher') coherresout = alltfX .* conj(alltfY); end; switch g.type case 'crossspec', coherres = alltfX .* conj(alltfY); % no normalization case 'coher', coherres = sum(alltfX .* conj(alltfY), 3) ./ sqrt( sum(abs(alltfX).^2,3) .* sum(abs(alltfY).^2,3) ); case 'amp' alltfX = abs(alltfX); alltfY = abs(alltfY); coherres = ampcorr(alltfX, alltfY, freqs, timesout, g); g.alpha = NaN; coherresout = []; case 'phasecoher2', coherres = sum(coherresout, 3) ./ sum(abs(coherresout),3); case 'phasecoher', coherres = sum( coherresout ./ abs(coherresout), 3) / g.trials; end; %%%%%%%%%% % baseline %%%%%%%%%% if size(g.baseline,2) == 2 baseln = []; for index = 1:size(g.baseline,1) tmptime = find(timesout >= g.baseline(index,1) & timesout <= g.baseline(index,2)); baseln = union_bc(baseln, tmptime); end; if length(baseln)==0 error('No point found in baseline'); end; else if ~isempty(find(timesout < g.baseline)) baseln = find(timesout < g.baseline); % subtract means of pre-0 (centered) windows else baseln = 1:length(timesout); % use all times as baseline end end; if ~isnan(g.alpha) & length(baseln)==0 fprintf('timef(): no window centers in baseline (times<%g) - shorten (max) window length.\n', g.baseline) return end mbase = mean(abs(coherres(:,baseln)')); % mean baseline coherence magnitude % ----------------- % compute bootstrap % ----------------- if ~isempty(g.rboot) Rbootout = g.rboot; else if ~isnan(g.alpha) % getting formula for coherence % ----------------------------- switch g.type case 'coher', inputdata = { alltfX alltfY }; % default formula = 'sum(arg1 .* conj(arg2), 3) ./ sqrt( sum(abs(arg1).^2,3) .* sum(abs(arg2).^2,3) );'; case 'amp', % not implemented inputdata = { abs(alltfX) abs(alltfY) }; % default case 'phasecoher2', inputdata = { alltfX alltfY }; % default formula = [ 'tmp = arg1 .* conj(arg2);' ... 'res = sum(tmp, 3) ./ sum(abs(tmp),3);' ]; case 'phasecoher', inputdata = { alltfX./abs(alltfX) alltfY./abs(alltfY) }; formula = [ 'mean(arg1 .* conj(arg2),3);' ]; case 'crossspec', inputdata = { alltfX./abs(alltfX) alltfY./abs(alltfY) }; formulainit = [ 'arg1 .* conj(arg2);' ]; end; % finding baseline for bootstrap % ------------------------------ if size(g.baseboot,2) == 1 if g.baseboot == 0, baselntmp = []; elseif ~isnan(g.baseline(1)) baselntmp = baseln; else baselntmp = find(timesout <= 0); % if it is empty use whole epoch end; else baselntmp = []; for index = 1:size(g.baseboot,1) tmptime = find(timesout >= g.baseboot(index,1) & timesout <= g.baseboot(index,2)); baselntmp = union_bc(baselntmp, tmptime); end; end; if prod(size(g.baseboot)) > 2 fprintf('Bootstrap analysis will use data in multiple selected windows.\n'); elseif size(g.baseboot,2) == 2 fprintf('Bootstrap analysis will use data in range %3.2g-%3.2g ms.\n', g.baseboot(1), g.baseboot(2)); elseif g.baseboot fprintf(' %d bootstrap windows in baseline (times<%g).\n', length(baselntmp), g.baseboot) end; if strcmpi(g.boottype, 'shuffle') | strcmpi(g.boottype, 'rand') Rbootout = bootstat(inputdata, formula, 'boottype', g.boottype, 'label', 'coherence', ... 'bootside', 'upper', 'shuffledim', [2 3], 'dimaccu', 2, ... 'naccu', g.naccu, 'alpha', g.alpha, 'basevect', baselntmp); elseif strcmpi(g.boottype, 'randall') % randomize phase but do not accumulate over time % dimension (NOT TESTED) % note the absence of dimaccu and the shuffledim 3 Rbootout = bootstat(inputdata, formula, 'boottype', 'rand', ... 'bootside', 'upper', 'shuffledim', 3, ... 'naccu', g.naccu, 'alpha', g.alpha, 'basevect', baselntmp); else % shuffle only trials (NOT TESTED) % note the absence of dimaccu and the shuffledim 3 Rbootout = bootstat(inputdata, formula, 'boottype', 'shuffle', ... 'bootside', 'upper', 'shuffledim', 3, ... 'naccu', g.naccu, 'alpha', g.alpha, 'basevect', baselntmp); end; else Rbootout = []; end; % note that the bootstrap thresholding is actually performed in the display subfunction plotall() end; % plot everything % --------------- if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') if strcmpi(g.plottype, 'image') plotall ( coherres, Rbootout, timesout, freqs, mbase, g); else plotallcurves( coherres, Rbootout, timesout, freqs, mbase, g); end; end; % proces outputs % -------------- Rangle = angle(coherres); R = abs(coherres); return; % *********************************************************************** % ------------------------------ % amplitude correlation function % ------------------------------ function [coherres, lagmap] = ampcorr(alltfX, alltfY, freqs, timesout, g) % initialize variables % -------------------- coherres = zeros(length(freqs), length(timesout), length(g.amplag)); alpha = zeros(length(freqs), length(timesout), length(g.amplag)); countlag = 1; for lag = g.amplag fprintf('Computing %d point lag amplitude correlation, please wait...\n', lag); for i1 = 1:length(freqs) for i2 = max(1, 1-lag):min(length(timesout)-lag, length(timesout)) if ~isnan(g.alpha) [tmp1 tmp2] = corrcoef( squeeze(alltfX(i1,i2,:)), squeeze(alltfY(i1,i2+lag,:)) ); coherres(i1,i2,countlag) = tmp1(1,2); alpha(i1,i2,countlag) = tmp2(1,2); else tmp1 = corrcoef( squeeze(alltfX(i1,i2,:)), squeeze(alltfY(i1,i2+lag,:)) ); coherres(i1,i2,countlag) = tmp1(1,2); end; end; end; countlag = countlag + 1; end; % find max corr if different lags % ------------------------------- if length(g.amplag) > 1 [coherres lagmap] = max(coherres, [], 3); dimsize = length(freqs)*length(timesout); alpha = reshape(alpha((lagmap(:)-1)*dimsize+[1:dimsize]'),length(freqs), length(timesout)); % above is same as (but faster) % for i1 = 1:length(freqs) % for i2 = 1:length(timesout) % alphanew(i1, i2) = alpha(i1, i2, lagmap(i1, i2)); % end; % end; lagmap = g.amplag(lagmap); % real lag coherres = coherres.*exp(j*lagmap/max(abs(g.amplag))); % encode lag in the phase else lagmap = []; end; % apply significance mask % ----------------------- if ~isnan(g.alpha) tmpind = find(alpha(:) > g.alpha); coherres(tmpind) = 0; end; % ------------------ % plotting functions % ------------------ function plotall(R, Rboot, times, freqs, mbase, g) switch lower(g.plotphase) case 'on', switch lower(g.plotamp), case 'on', ordinate1 = 0.67; ordinate2 = 0.1; height = 0.33; g.plot = 1; case 'off', ordinate2 = 0.1; height = 0.9; g.plot = 1; end; case 'off', ordinate1 = 0.1; height = 0.9; switch lower(g.plotamp), case 'on', ordinate1 = 0.1; height = 0.9; g.plot = 1; case 'off', g.plot = 0; end; end; % compute angles % -------------- Rangle = angle(R); if ~isreal(R) R = abs(R); Rraw =R; % raw coherence values setylim = 1; if ~isnan(g.baseline) R = R - repmat(mbase',[1 g.timesout]); % remove baseline mean end; else Rraw = R; setylim = 0; end; if g.plot fprintf('\nNow plotting...\n'); set(gcf,'DefaultAxesFontSize',g.AXES_FONT) colormap(jet(256)); pos = get(gca,'position'); % plot relative to current axes q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]; axis('off') end; switch lower(g.plotamp) case 'on' % % Image the coherence [% perturbations] % RR = R; if ~isnan(g.alpha) % zero out (and 'green out') nonsignif. R values switch dims(Rboot) case 3, RR (find(RR > Rboot(:,:,1) & (RR < Rboot(:,:,2)))) = 0; Rraw(find(RR > Rboot(:,:,1) & (RR < Rboot(:,:,2)))) = 0; case 2, RR (find(RR < Rboot)) = 0; Rraw(find(RR < Rboot)) = 0; case 1, RR (find(RR < repmat(Rboot(:),[1 size(RR,2)]))) = 0; Rraw(find(RR < repmat(Rboot(:),[1 size(Rraw,2)]))) = 0; end; end h(6) = axes('Units','Normalized', 'Position',[.1 ordinate1 .8 height].*s+q); map=hsv(300); % install circular color map - green=0, yellow, orng, red, violet = max % cyan, blue, violet = min map = flipud([map(251:end,:);map(1:250,:)]); map(151,:) = map(151,:)*0.9; % tone down the (0=) green! colormap(map); if ~strcmpi(g.freqscale, 'log') try, imagesc(times,freqs,RR,max(max(RR))*[-1 1]); % plot the coherence image catch, imagesc(times,freqs,RR,[-1 1]); end; else try, imagesclogy(times,freqs,RR,max(max(RR))*[-1 1]); % plot the coherence image catch, imagesclogy(times,freqs,RR,[-1 1]); end; end; set(gca,'ydir','norm'); if ~isempty(g.maxamp) caxis([-g.maxamp g.maxamp]); end; tmpscale = caxis; hold on plot([0 0],[0 freqs(end)],'--m','LineWidth',g.linewidth) for i=1:length(g.marktimes) plot([g.marktimes(i) g.marktimes(i)],[0 freqs(end)],'--m','LineWidth',g.linewidth); end; hold off set(h(6),'YTickLabel',[],'YTick',[]) set(h(6),'XTickLabel',[],'XTick',[]) h(8) = axes('Position',[.95 ordinate1 .05 height].*s+q); if setylim cbar(h(8),151:300, [0 tmpscale(2)]); % use only positive colors (gyorv) else cbar(h(8),1:300 , [-tmpscale(2) tmpscale(2)]); % use only positive colors (gyorv) end; % % Plot delta-mean min and max coherence at each time point on bottom of image % h(10) = axes('Units','Normalized','Position',[.1 ordinate1-0.1 .8 .1].*s+q); % plot marginal means below Emax = max(R); % mean coherence at each time point Emin = min(R); % mean coherence at each time point plot(times,Emin, times, Emax, 'LineWidth',g.linewidth); hold on; plot([times(1) times(length(times))],[0 0],'LineWidth',0.7); plot([0 0],[-500 500],'--m','LineWidth',g.linewidth); for i=1:length(g.marktimes) plot([g.marktimes(i) g.marktimes(i)],[-500 500],'--m','LineWidth',g.linewidth); end; if ~isnan(g.alpha) & dims(Rboot) > 1 % plot bootstrap significance limits (base mean +/-) switch dims(Rboot) case 2, plot(times,mean(Rboot(:,:),1),'g' ,'LineWidth',g.linewidth); plot(times,mean(Rboot(:,:),1),'k:','LineWidth',g.linewidth); case 3, plot(times,mean(Rboot(:,:,1),1),'g' ,'LineWidth',g.linewidth); plot(times,mean(Rboot(:,:,1),1),'k:','LineWidth',g.linewidth); plot(times,mean(Rboot(:,:,2),1),'g' ,'LineWidth',g.linewidth); plot(times,mean(Rboot(:,:,2),1),'k:','LineWidth',g.linewidth); end; axis([min(times) max(times) 0 max([Emax(:)' Rboot(:)'])*1.2]) else axis([min(times) max(times) 0 max(Emax)*1.2]) end; tick = get(h(10),'YTick'); set(h(10),'YTick',[tick(1) ; tick(length(tick))]) set(h(10),'YAxisLocation','right') xlabel('Time (ms)') ylabel('coh.') % % Plot mean baseline coherence at each freq on left side of image % h(11) = axes('Units','Normalized','Position',[0 ordinate1 .1 height].*s+q); % plot mean spectrum E = abs(mbase); % baseline mean coherence at each frequency if ~strcmpi(g.freqscale, 'log') plot(freqs,E,'b','LineWidth',g.linewidth); % plot mbase else semilogx(freqs,E,'b','LineWidth',g.linewidth); % plot mbase set(h(11),'View',[90 90]) divs = linspace(log(freqs(1)), log(freqs(end)), 10); set(gca, 'xtickmode', 'manual'); divs = ceil(exp(divs)); divs = unique_bc(divs); % ceil is critical here, round might misalign % out-of border label with within border ticks set(gca, 'xtick', divs); end; if ~isnan(g.alpha) % plot bootstrap significance limits (base mean +/-) hold on if ~strcmpi(g.freqscale, 'log') switch dims(Rboot) case 1, plot(freqs,Rboot(:),'g' ,'LineWidth',g.linewidth); plot(freqs,Rboot(:),'k:','LineWidth',g.linewidth); case 2, plot(freqs,mean(Rboot(:,:),2),'g' ,'LineWidth',g.linewidth); plot(freqs,mean(Rboot(:,:),2),'k:','LineWidth',g.linewidth); case 3, plot(freqs,mean(Rboot(:,:,1),2),'g' ,'LineWidth',g.linewidth); plot(freqs,mean(Rboot(:,:,1),2),'k:','LineWidth',g.linewidth); plot(freqs,mean(Rboot(:,:,2),2),'g' ,'LineWidth',g.linewidth); plot(freqs,mean(Rboot(:,:,2),2),'k:','LineWidth',g.linewidth); end; else switch dims(Rboot) case 1, semilogy(freqs,Rboot(:),'g' ,'LineWidth',g.linewidth); semilogy(freqs,Rboot(:),'k:','LineWidth',g.linewidth); case 2, semilogy(freqs,mean(Rboot(:,:),2),'g' ,'LineWidth',g.linewidth); semilogy(freqs,mean(Rboot(:,:),2),'k:','LineWidth',g.linewidth); case 3, semilogy(freqs,mean(Rboot(:,:,1),2),'g' ,'LineWidth',g.linewidth); semilogy(freqs,mean(Rboot(:,:,1),2),'k:','LineWidth',g.linewidth); semilogy(freqs,mean(Rboot(:,:,2),2),'g' ,'LineWidth',g.linewidth); semilogy(freqs,mean(Rboot(:,:,2),2),'k:','LineWidth',g.linewidth); end; end; if ~isnan(max(E)) axis([freqs(1) freqs(end) 0 max([E Rboot(:)'])*1.2]); end; else % plot marginal mean coherence only if ~isnan(max(E)) axis([freqs(1) freqs(end) 0 max(E)*1.2]); end; end set(gca,'xdir','rev'); % nima tick = get(h(11),'YTick'); set(h(11),'YTick',[tick(1) ; tick(length(tick))]); % crashes for log set(h(11),'View',[90 90]) xlabel('Freq. (Hz)') ylabel('coh.') end; switch lower(g.plotphase) case 'on' % % Plot coherence phase lags in bottom panel % h(13) = axes('Units','Normalized','Position',[.1 ordinate2 .8 height].*s+q); if setylim if strcmpi(g.type, 'amp') % currrently -1 to 1 maxangle = max(abs(g.amplag)) * mean(times(2:end) - times(1:end-1)); Rangle = Rangle * maxangle; maxangle = maxangle+5; % so that the min and the max does not mix else if strcmp(g.angleunit,'ms') % convert to ms Rangle = (Rangle/(2*pi)).*repmat(1000./freqs(:)',1,length(times)); maxangle = max(max(abs(Rangle))); elseif strcmpi(g.angleunit,'deg') % convert to degrees Rangle = Rangle*180/pi; % convert to degrees maxangle = 180; % use full-cycle plotting else maxangle = pi; end end; Rangle(find(Rraw==0)) = 0; % set angle at non-signif coher points to 0 if ~strcmpi(g.freqscale, 'log') imagesc(times,freqs,Rangle,[-maxangle maxangle]); % plot the coherence phase angles else imagesclogy(times,freqs,Rangle,[-maxangle maxangle]); % plot the coherence phase angles end; hold on plot([0 0],[0 freqs(end)],'--m','LineWidth',g.linewidth); % zero-time line for i=1:length(g.marktimes) plot([g.marktimes(i) g.marktimes(i)],[0 freqs(end)],'--m','LineWidth',g.linewidth); end; set(gca,'ydir','norm'); % nima ylabel('Freq. (Hz)') xlabel('Time (ms)') h(14)=axes('Position',[.95 ordinate2 .05 height].*s+q); cbar(h(14),0,[-maxangle maxangle]); % two-sided colorbar else axis off; text(0, 0.5, 'Real values, no angles'); end; end if g.plot try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if (length(g.title) > 0) % plot title axes('Position',pos,'Visible','Off'); h(13) = text(-.05,1.01,g.title); set(h(13),'VerticalAlignment','bottom') set(h(13),'HorizontalAlignment','left') set(h(13),'FontSize',g.TITLE_FONT) end % %%%%%%%%%%%%%%% plot topoplot() %%%%%%%%%%%%%%%%%%%%%%% % if (~isempty(g.topovec)) & strcmpi(g.plotamp, 'on') & strcmpi(g.plotphase, 'on') h(15) = subplot('Position',[-.1 .43 .2 .14].*s+q); if size(g.topovec,2) <= 2 topoplot(g.topovec(1),g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', g.chaninfo); else topoplot(g.topovec(1,:),g.elocs,'electrodes','off', 'chaninfo', g.chaninfo); end; axis('square') h(16) = subplot('Position',[.9 .43 .2 .14].*s+q); if size(g.topovec,2) <= 2 topoplot(g.topovec(2),g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', g.chaninfo); else topoplot(g.topovec(2,:),g.elocs,'electrodes','off', 'chaninfo', g.chaninfo); end; axis('square') end try, axcopy(gcf); catch, end; end; % --------------- % Plotting curves % --------------- function plotallcurves(R, Rboot, times, freqs, mbase, g) % compute angles % -------------- Rangle = angle(R); pos = get(gca,'position'); % plot relative to current axes q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]; if ~isreal(R) R = abs(R); Rraw =R; % raw coherence values if ~isnan(g.baseline) R = R - repmat(mbase',[1 g.timesout]); % remove baseline mean end; else Rraw = R; setylim = 0; end; % time unit % --------- if times(end) > 10000 times = times/1000; timeunit = 's'; else timeunit = 'ms'; end; % legend % ------ alllegend = {}; if strcmpi(g.plotmean, 'on') & freqs(1) ~= freqs(end) alllegend = { [ num2str(freqs(1)) '-' num2str(freqs(end)) 'Hz' ] }; else for index = 1:length(freqs) alllegend{index} = [ num2str(freqs(index)) 'Hz' ]; end; end; fprintf('\nNow plotting...\n'); if strcmpi(g.plotamp, 'on') % % Plot coherence amplitude in top panel % if strcmpi(g.plotphase, 'on'), subplot(2,1,1); end; if isempty(g.maxamp), g.maxamp = 0; end; plotcurve(times, R, 'maskarray', Rboot, 'title', 'Coherence amplitude', ... 'xlabel', [ 'Time (' timeunit ')' ], 'ylabel', '0-1', 'ylim', g.maxamp, ... 'vert', g.vert, 'marktimes', g.marktimes, 'legend', alllegend, ... 'linewidth', g.linewidth, 'highlightmode', g.highlightmode, 'plotmean', g.plotmean); end; if strcmpi(g.plotphase, 'on') % % Plot coherence phase lags in bottom panel % if strcmpi(g.plotamp, 'on'), subplot(2,1,2); end; plotcurve(times, Rangle/pi*180, 'maskarray', Rboot, 'val2mask', R, 'title', 'Coherence phase', ... 'xlabel', [ 'Time (' timeunit ')' ], 'ylabel', 'Angle (deg.)', 'ylim', [-180 180], ... 'vert', g.vert, 'marktimes', g.marktimes, 'legend', alllegend, ... 'linewidth', g.linewidth, 'highlightmode', g.highlightmode, 'plotmean', g.plotmean); end if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if (length(g.title) > 0) % plot title h(13) = textsc(g.title, 'title'); end % %%%%%%%%%%%%%%% plot topoplot() %%%%%%%%%%%%%%%%%%%%%%% % if (~isempty(g.topovec)) h(15) = subplot('Position',[-.1 .43 .2 .14].*s+q); if size(g.topovec,2) <= 2 topoplot(g.topovec(1),g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10); else topoplot(g.topovec(1,:),g.elocs,'electrodes','off'); end; axis('square') h(16) = subplot('Position',[.9 .43 .2 .14].*s+q); if size(g.topovec,2) <= 2 topoplot(g.topovec(2),g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10); else topoplot(g.topovec(2,:),g.elocs,'electrodes','off'); end; axis('square') end try, axcopy(gcf); catch, end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% COHERENCE OBSOLETE %%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function for coherence initialisation % ------------------------------------- function Coher = coherinit(nb_points, trials, timesout, type); Coher.R = zeros(nb_points,timesout); % mean coherence %Coher.RR = repmat(nan,nb_points,timesout); % initialize with nans Coher.type = type; Coher.Rn=zeros(trials,timesout); switch type case 'coher', Coher.cumulX = zeros(nb_points,timesout); Coher.cumulY = zeros(nb_points,timesout); case 'phasecoher2', Coher.cumul = zeros(nb_points,timesout); end; % function for coherence calculation % ------------------------------------- %function Coher = cohercomparray(Coher, tmpX, tmpY, trial); %switch Coher.type % case 'coher', % Coher.R = Coher.R + tmpX.*conj(tmpY); % complex coher. % Coher.cumulXY = Coher.cumulXY + abs(tmpX).*abs(tmpY); % case 'phasecoher', % Coher.R = Coher.R + tmpX.*conj(tmpY) ./ (abs(tmpX).*abs(tmpY)); % complex coher. % Coher.Rn(trial,:) = 1; %end % ~any(isnan()) function [Coher,tmptrialcoh] = cohercomp(Coher, tmpX, tmpY, trial, time); tmptrialcoh = tmpX.*conj(tmpY); switch Coher.type case 'coher', Coher.R(:,time) = Coher.R(:,time) + tmptrialcoh; % complex coher. Coher.cumulX(:,time) = Coher.cumulX(:,time) + abs(tmpX).^2; Coher.cumulY(:,time) = Coher.cumulY(:,time) + abs(tmpY).^2; case 'phasecoher2', Coher.R(:,time) = Coher.R(:,time) + tmptrialcoh; % complex coher. Coher.cumul(:,time) = Coher.cumul(:,time) + abs(tmptrialcoh); case 'phasecoher', Coher.R(:,time) = Coher.R(:,time) + tmptrialcoh ./ abs(tmptrialcoh); % complex coher. %figure; imagesc(abs(tmpX.*conj(tmpY) ./ (abs(tmpX).*abs(tmpY)))); Coher.Rn(trial,time) = Coher.Rn(trial,time)+1; end % ~any(isnan()) % function for post coherence calculation % --------------------------------------- function Coher = cohercomppost(Coher, trials); switch Coher.type case 'coher', Coher.R = Coher.R ./ sqrt(Coher.cumulX) ./ sqrt(Coher.cumulY); case 'phasecoher2', Coher.R = Coher.R ./ Coher.cumul; case 'phasecoher', Coher.Rn = sum(Coher.Rn, 1); Coher.R = Coher.R ./ (ones(size(Coher.R,1),1)*Coher.Rn); % coherence magnitude end; % function for 2 conditions coherence calculation % ----------------------------------------------- function [coherimage, coherimage1, coherimage2] = coher2conddiff( allsavedcoher, alltrials, cond1trials, type, tfx, tfy); t1s = alltrials(1:cond1trials); t2s = alltrials(cond1trials+1:end); switch type case 'coher', coherimage1 = sum(allsavedcoher(:,:,t1s),3) ./ sqrt(sum(tfx(:,:,t1s))) ./ sqrt(sum(tfy(:,:,t1s))); coherimage2 = sum(allsavedcoher(:,:,t2s),3) ./ sqrt(sum(tfx(:,:,t2s))) ./ sqrt(sum(tfy(:,:,t1s))); case 'phasecoher2', coherimage1 = sum(allsavedcoher(:,:,t1s),3) ./ sum(abs(allsavedcoher(:,:,t1s)),3); coherimage2 = sum(allsavedcoher(:,:,t2s),3) ./ sum(abs(allsavedcoher(:,:,t2s)),3); case 'phasecoher', coherimage1 = sum(allsavedcoher(:,:,t1s),3) / cond1trials; coherimage2 = sum(allsavedcoher(:,:,t2s),3) / (size(allsavedcoher,3)-cond1trials); end; coherimage = coherimage2 - coherimage1; function w = hanning(n) if ~rem(n,2) w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end function res = dims(array) res = min(ndims(array), max(size(array,2),size(array,3)));
github
lcnhappe/happe-master
crossf.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/crossf.m
59,295
utf_8
395468032fe3d1abba14d59dfe6d1317
% crossf() - Returns estimates and plots event-related coherence (ERCOH) % between two input data time series (X,Y). A lower panel (optionally) % shows the coherence phase difference between the processes. % In this panel, output by > crossf(X,Y,...); % 90 degrees (orange) means X leads Y by a quarter cycle. % -90 degrees (blue) means Y leads X by a quarter cycle. % Coherence phase units may be radians, degrees, or msec. % Click on any subplot to view separately and zoom in/out. % % Function description: % Uses EITHER fixed-window, zero-padded FFTs (fastest) OR constant-Q % 0-padded wavelet DFTs (more even sensitivity across frequencies), % both Hanning-tapered. Output frequency spacing is the lowest % frequency ('srate'/'winsize') divided by the 'padratio'. % % If an 'alpha' value is given, then bootstrap statistics are % computed (from a distribution of 'naccu' {200} surrogate baseline % data epochs) for the baseline epoch, and non-significant features % of the output plots are zeroed (and shown in green). The baseline % epoch is all windows with center latencies < the given 'baseline' % value, or if 'baseboot' is 1, the whole epoch. % Usage: % >> [coh,mcoh,timesout,freqsout,cohboot,cohangles] ... % = crossf(X,Y,frames,tlimits,srate,cycles, ... % 'key1', 'val1', 'key2', val2' ...); % Required inputs: % X = first single-channel data set (1,frames*nepochs) % Y = second single-channel data set (1,frames*nepochs) % frames = frames per epoch {default: 750} % tlimits = [mintime maxtime] (ms) epoch latency limits {def: [-1000 2000]} % srate = data sampling rate (Hz) {default: 250} % cycles = 0 -> Use FFTs (with constant window length) % = >0 -> Number of cycles in each analysis wavelet % = [cycles expfactor] -> if 0 < expfactor < 1, the number % of wavelet cycles expands with frequency from cycles % If expfactor = 1, no expansion; if = 0, constant % window length (as in FFT) {default: 0} % Optional Coherence Type: % 'type' = ['coher'|'phasecoher'] Compute either linear coherence % ('coher') or phase coherence ('phasecoher') also known % as phase coupling factor' {default: 'phasecoher'}. % 'subitc' = ['on'|'off'] subtract stimulus locked Inter-Trial Coherence % from X and Y. This computes the 'intrinsic' coherence % X and Y not arising from common synchronization to % experimental events. See notes. {default: 'off'} % 'shuffle' = integer indicating the number of estimates to compute % bootstrap coherence based on shuffled trials. This estimates % the coherence arising only from time locking of X and Y % to experimental events (opposite of 'subitc') {default: 0} % Optional Detrend: % 'detret' = ['on'|'off'], Linearly detrend data within epochs {def: 'off'} % 'detrep' = ['on'|'off'], Linearly detrend data across trials {def: 'off'} % % Optional FFT/DFT: % 'winsize' = If cycles==0: data subwindow length (fastest, 2^n<frames); % if cycles >0: *longest* window length to use. This % determines the lowest output frequency {default: ~frames/8} % 'timesout' = Number of output latencies (int<frames-winsize) {def: 200} % 'padratio' = FFTlength/winsize (2^k) {default: 2} % Multiplies the number of output frequencies by % dividing their spacing. When cycles==0, frequency % spacing is (low_frequency/padratio). % 'maxfreq' = Maximum frequency (Hz) to plot (& output if cycles>0) % If cycles==0, all FFT frequencies are output {default: 50} % 'baseline' = Coherence baseline end latency (ms). NaN -> No baseline % {default:NaN} % 'powbase' = Baseline spectrum to log-subtract {default: from data} % % Optional Bootstrap: % 'alpha' = If non-0, compute two-tailed bootstrap significance prob. % level. Show non-signif output values as green. {def: 0} % 'naccu' = Number of bootstrap replications to compute {def: 200} % 'boottype' = ['times'|'timestrials'] Bootstrap type: Either shuffle % windows ('times') or windows and trials ('timestrials') % Option 'timestrials' requires more memory {default: 'times'} % 'memory' = ['low'|'high'] 'low' -> decrease memory use {default: 'high'} % 'baseboot' = Extent of bootstrap shuffling (0=to 'baseline'; 1=whole epoch) % If no baseline is given (NaN), extent of bootstrap shuffling % is the whole epoch {default: 0} % 'rboot' = Input bootstrap coherence limits (e.g., from crossf()) % The bootstrap type should be identical to that used % to obtain the input limits. {default: compute from data} % Optional Scalp Map: % 'topovec' = (2,nchans) matrix, plot scalp maps to plot {default: []} % ELSE (c1,c2), plot two cartoons showing channel locations. % 'elocs' = Electrode location structure or file for scalp map % {default: none} % 'chaninfo' = Electrode location additional information (nose position...) % {default: none} % % Optional Plot and Compute Features: % 'compute' = ['matlab'|'c'] Use C subroutines to speed up the % computation (currently unimplemented) {def: 'matlab'} % 'savecoher' - [0|1] 1 --> Accumulate the individual trial coherence % vectors; output them as cohangles {default: 0 = off} % 'plotamp' = ['on'|'off'], Plot coherence magnitude {def: 'on'} % 'maxamp' = [real] Set the maximum for the amp. scale {def: auto} % 'plotphase' = ['on'|'off'], Plot coherence phase angle {def: 'on'} % 'angleunit' = Phase units: 'ms' -> msec, 'deg' -> degrees, % or 'rad' -> radians {default: 'deg'} % 'title' = Optional figure title {default: none} % 'vert' = Latencies to mark with a dotted vertical line % {default: none} % 'linewidth' = Line width for marktimes traces (thick=2, thin=1) % {default: 2} % 'cmax' = Maximum amplitude for color scale {def: data limits} % 'axesfont' = Axes font size {default: 10} % 'titlefont' = Title font size {default: 8} % % Outputs: % coh = Matrix (nfreqs,timesout) of coherence magnitudes % mcoh = Vector of mean baseline coherence at each frequency % timesout = Vector of output latencies (window centers) (ms). % freqsout = Vector of frequency bin centers (Hz). % cohboot = Matrix (nfreqs,2) of [lower;upper] coher signif. limits % if 'boottype' is 'trials', (nfreqs,timesout, 2) % cohangle = (nfreqs,timesout) matrix of coherence angles (in radians) % cohangles = (nfreqs,timesout,trials) matrix of single-trial coherence % angles (in radians), saved and output only if 'savecoher',1 % % Plot description: % Assuming both 'plotamp' and 'plotphase' options are 'on' (=default), the upper panel % presents the magnitude of either phase coherence or linear coherence, depending on % the 'type' parameter (above). The lower panel presents the coherence phase difference % (in degrees). Click on any plot to pop up a new window (using 'axcopy()'). % -- The upper left marginal panel shows mean coherence during the baseline period % (blue), and when significance is set, the significance threshold (dotted black-green). % -- The horizontal panel under the coherence magnitude image indicates the maximum % (green) and minimum (blue) coherence values across all frequencies. When significance % is set (using option 'trials' for 'boottype'), an additional curve indicates the % significance threshold (dotted black-green). % % Notes: 1) When cycles==0, nfreqs is total number of FFT frequencies. % 2) As noted above: 'blue' coherence angle -> X leads Y; 'red' -> Y leads X % 3) The 'boottype' should be ideally 'timesframes', but this creates high % memory demands, so the 'times' method must be used in many cases. % 4) If 'boottype' is 'trials', the average of the complex bootstrap % is subtracted from the coherence to compensate for phase differences % (the average is also subtracted from the bootstrap distribution). % For other bootstraps, this is not necessary since the phase is random. % 5) If baseline is non-NaN, the baseline is subtracted from % the complex coherence. On the left hand side of the coherence % amplitude image, the baseline is displayed as a magenta line % (if no baseline is selected, this curve represents the average % coherence at every given frequency). % 6) If a out-of-memory error occurs, set the 'memory' option to 'low' % (Makes computation time slower; Only the 'times' bootstrap method % can be used in this mode). % % Authors: Arnaud Delorme, Sigurd Enghoff & Scott Makeig % CNL/Salk Institute 1998-2001; SCCN/INC/UCSD, La Jolla, 2002- % % See also: timef() % Copyright (C) 8/1/98 Arnaud Delorme, Sigurd Enghoff & Scott Makeig, SCCN/INC/UCSD % % 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 % 11-20-98 defined g.linewidth constant -sm % 04-01-99 made number of frequencies consistent -se % 06-29-99 fixed constant-Q freq indexing -se % 08-13-99 added cohangle plotting -sm % 08-20-99 made bootstrap more efficient -sm % 08-24-99 allow nan values introduced by possible eventlock() preproc. -sm % 03-05-2007 eventlock.m deprecated to eegalign.m. -tf % 03-16-00 added lead/lag interpretation to help msg - sm & eric visser % 03-16-00 added axcopy() feature -sm & tpj % 04-20-00 fixed Rangle sign for wavelets, added verts array -sm % 01-22-01 corrected help msg when nargin<2 -sm & arno delorme % 01-25-02 reformated help & license, added links -ad % 03-09-02 function restructuration -ad % add 'key', val arguments (+ external baseboot, baseline, color axis, angleunit...) % add detrending (across time and trials) + 'coher' option for amplitude coherence % significance only if alpha is given, ploting options in 'plotamp' and 'plotphase' % 03-16-02 timeout automatically adjusted if too high -ad % 04-03-02 added new options for bootstrap -ad % Note: 3 "objects" (Tf, Coher and Boot) are handled by specific functions under Matlab % (Tf) function Tf = tfinit(...) - create object Time Frequency (Tf) associated with some data % (Tf) function [Tf, itcvals] = tfitc(...) - compute itc for the selected data % (Tf) function [Tf, itcvals] = tfitcpost(Tf, trials) - itc normlisation % (Tf) function [Tf, tmpX] = tfcomp(Tf, trials, times) - compute time freq. decomposition % (Coher) function Coher = coherinit(...) - initialize coherence object % (Coher) function Coher = cohercomp(Coher, tmpX, tmpY, trial, time) - compute coherence % (Coher) function Coher = cohercomppost(Coher, trials) - coherence normalization % (Boot) function Boot = bootinit(...) - intialize bootstrap object % (Boot) function Boot = bootcomp(...) - compute bootstrap % (Boot) function [Boot, Rbootout] = bootcomppost(...) - bootstrap normalization % and by real objects under C++ (C++ code, incomplete) function [R,mbase,times,freqs,Rbootout,Rangle, trialcoher, Tfx, Tfy] = crossf(X, Y, frame, tlimits, Fs, varwin, varargin) %varwin,winsize,nwin,oversmp,maxfreq,alpha,verts,caxmax) % ------------------------ % Commandline arg defaults: % ------------------------ DEFAULT_ANGLEUNIT = 'deg'; % angle plotting units - 'rad', 'ms', or 'deg' DEFAULT_EPOCH = 750; % Frames per epoch DEFAULT_TIMELIM = [-1000 2000]; % Time range of epochs (ms) DEFAULT_FS = 250; % Sampling frequency (Hz) DEFAULT_NWIN = 200; % Number of windows = horizontal resolution DEFAULT_VARWIN = 0; % Fixed window length or base on cycles. % =0: fix window length to nwin % >0: set window length equal varwin cycles % bounded above by winsize, also determines % the min. freq. to be computed. DEFAULT_OVERSMP = 2; % Number of times to oversample = vertical resolution DEFAULT_MAXFREQ = 50; % Maximum frequency to display (Hz) DEFAULT_TITLE = 'Event-Related Coherence'; % Figure title DEFAULT_ALPHA = NaN; % Default two-sided significance probability threshold if (nargin < 2) help crossf return end if ~iscell(X) if (min(size(X))~=1 | length(X)<2) fprintf('crossf(): X must be a row or column vector.\n'); return elseif (min(size(Y))~=1 | length(Y)<2) fprintf('crossf(): Y must be a row or column vector.\n'); return elseif (length(X) ~= length(Y)) fprintf('crossf(): X and Y must have same length.\n'); return end end; if (nargin < 3) frame = DEFAULT_EPOCH; elseif (~isnumeric(frame) | length(frame)~=1 | frame~=round(frame)) fprintf('crossf(): Value of frames must be an integer.\n'); return elseif (frame <= 0) fprintf('crossf(): Value of frames must be positive.\n'); return elseif ~iscell(X) & (rem(length(X),frame) ~= 0) fprintf('crossf(): Length of data vectors must be divisible by frames.\n'); return end if (nargin < 4) tlimits = DEFAULT_TIMELIM; elseif (~isnumeric(tlimits) | sum(size(tlimits))~=3) error('crossf(): Value of tlimits must be a vector containing two numbers.'); elseif (tlimits(1) >= tlimits(2)) error('crossf(): tlimits interval must be [min,max].'); end if (nargin < 5) Fs = DEFAULT_FS; elseif (~isnumeric(Fs) | length(Fs)~=1) error('crossf(): Value of srate must be a number.'); elseif (Fs <= 0) error('crossf(): Value of srate must be positive.'); end if (nargin < 6) varwin = DEFAULT_VARWIN; elseif (~isnumeric(varwin) | length(varwin)>2) error('crossf(): Value of cycles must be a number or a (1,2) vector.'); elseif (varwin < 0) error('crossf(): Value of cycles must be either zero or positive.'); end % consider structure for these arguments % -------------------------------------- vararginori = varargin; for index=1:length(varargin) if iscell(varargin{index}), varargin{index} = { varargin{index} }; end; end; if ~isempty(varargin) try, g = struct(varargin{:}); catch, error('Argument error in the {''param'', value} sequence'); end; else g = []; end; try, g.shuffle; catch, g.shuffle = 0; end; try, g.title; catch, g.title = DEFAULT_TITLE; end; try, g.winsize; catch, g.winsize = max(pow2(nextpow2(frame)-3),4); end; try, g.pad; catch, g.pad = max(pow2(nextpow2(g.winsize)),4); end; try, g.timesout; catch, g.timesout = DEFAULT_NWIN; end; try, g.padratio; catch, g.padratio = DEFAULT_OVERSMP; end; try, g.maxfreq; catch, g.maxfreq = DEFAULT_MAXFREQ; end; try, g.topovec; catch, g.topovec = []; end; try, g.elocs; catch, g.elocs = ''; end; try, g.alpha; catch, g.alpha = DEFAULT_ALPHA; end; try, g.marktimes; catch, g.marktimes = []; end; % default no vertical lines try, g.marktimes = g.vert; catch, g.vert = []; end; % default no vertical lines try, g.powbase; catch, g.powbase = nan; end; try, g.rboot; catch, g.rboot = nan; end; try, g.plotamp; catch, g.plotamp = 'on'; end; try, g.plotphase; catch, g.plotphase = 'on'; end; try, g.plotbootsub; catch, g.plotbootsub = 'on'; end; try, g.detrep; catch, g.detrep = 'off'; end; try, g.detret; catch, g.detret = 'off'; end; try, g.baseline; catch, g.baseline = NaN; end; try, g.baseboot; catch, g.baseboot = 0; end; try, g.linewidth; catch, g.linewidth = 2; end; try, g.naccu; catch, g.naccu = 200; end; try, g.angleunit; catch, g.angleunit = DEFAULT_ANGLEUNIT; end; try, g.cmax; catch, g.cmax = 0; end; % 0=use data limits try, g.type; catch, g.type = 'phasecoher'; end; try, g.boottype; catch, g.boottype = 'times'; end; try, g.subitc; catch, g.subitc = 'off'; end; try, g.memory; catch, g.memory = 'high'; end; try, g.compute; catch, g.compute = 'matlab'; end; try, g.maxamp; catch, g.maxamp = []; end; try, g.savecoher; catch, g.savecoher = 0; end; try, g.noinput; catch, g.noinput = 'no'; end; try, g.chaninfo; catch, g.chaninfo = []; end; allfields = fieldnames(g); for index = 1:length(allfields) switch allfields{index} case { 'shuffle' 'title' 'winsize' 'pad' 'timesout' 'padratio' 'maxfreq' 'topovec' 'elocs' 'alpha' ... 'marktimes' 'vert' 'powbase' 'rboot' 'plotamp' 'plotphase' 'plotbootsub' 'detrep' 'detret' ... 'baseline' 'baseboot' 'linewidth' 'naccu' 'angleunit' 'cmax' 'type' 'boottype' 'subitc' ... 'memory' 'compute' 'maxamp' 'savecoher' 'noinput' 'chaninfo' }; case {'plotersp' 'plotitc' }, disp(['crossf warning: timef option ''' allfields{index} ''' ignored']); otherwise disp(['crossf error: unrecognized option ''' allfields{index} '''']); beep; return; end; end; g.tlimits = tlimits; g.frame = frame; g.srate = Fs; g.cycles = varwin(1); if length(varwin)>1 g.cyclesfact = varwin(2); else g.cyclesfact = 1; end; g.type = lower(g.type); g.boottype = lower(g.boottype); g.detrep = lower(g.detrep); g.detret = lower(g.detret); g.plotphase = lower(g.plotphase); g.plotbootsub = lower(g.plotbootsub); g.subitc = lower(g.subitc); g.plotamp = lower(g.plotamp); g.shuffle = lower(g.shuffle); g.compute = lower(g.compute); g.AXES_FONT = 10; g.TITLE_FONT = 14; % testing arguments consistency % ----------------------------- if (~ischar(g.title)) error('Title must be a string.'); end if (~isnumeric(g.winsize) | length(g.winsize)~=1 | g.winsize~=round(g.winsize)) error('Value of winsize must be an integer number.'); elseif (g.winsize <= 0) error('Value of winsize must be positive.'); elseif (g.cycles == 0 & pow2(nextpow2(g.winsize)) ~= g.winsize) error('Value of winsize must be an integer power of two [1,2,4,8,16,...]'); elseif (g.winsize > g.frame) error('Value of winsize must be less than frame length.'); end if (~isnumeric(g.timesout) | length(g.timesout)~=1 | g.timesout~=round(g.timesout)) error('Value of timesout must be an integer number.'); elseif (g.timesout <= 0) error('Value of timesout must be positive.'); end if (g.timesout > g.frame-g.winsize) g.timesout = g.frame-g.winsize; disp(['Value of timesout must be <= frame-winsize, timeout adjusted to ' int2str(g.timesout) ]); end if (~isnumeric(g.padratio) | length(g.padratio)~=1 | g.padratio~=round(g.padratio)) error('Value of padratio must be an integer.'); elseif (g.padratio <= 0) error('Value of padratio must be positive.'); elseif (pow2(nextpow2(g.padratio)) ~= g.padratio) error('Value of padratio must be an integer power of two [1,2,4,8,16,...]'); end if (~isnumeric(g.maxfreq) | length(g.maxfreq)~=1) error('Value of g.maxfreq must be a number.'); elseif (g.maxfreq <= 0) error('Value of g.maxfreq must be positive.'); elseif (g.maxfreq > Fs/2) fprintf('Warning: input value of g.maxfreq larger that Nyquist frequency %3.4 Hz\n\n',Fs/2); end if isempty(g.topovec) g.topovec = []; elseif min(size(g.topovec))==1 g.topovec = g.topovec(:); if size(g.topovec,1)~=2 error('topovec must be a row or column vector.'); end end; if isempty(g.elocs) g.elocs = ''; elseif (~ischar(g.elocs)) & ~isstruct(g.elocs) error('Channel location file must be a valid text file.'); end if (~isnumeric(g.alpha) | length(g.alpha)~=1) error('timef(): Value of g.alpha must be a number.\n'); elseif (round(g.naccu*g.alpha) < 2) fprintf('Value of g.alpha is out of the normal range [%g,0.5]\n',2/g.naccu); g.naccu = round(2/g.alpha); fprintf(' Increasing the number of bootstrap iterations to %d\n',g.naccu); end if g.alpha>0.5 | g.alpha<=0 error('Value of g.alpha is out of the allowed range (0.00,0.5).'); end if ~isnan(g.alpha) if g.baseboot > 0 fprintf('Bootstrap analysis will use data in baseline (pre-0) subwindows only.\n') else fprintf('Bootstrap analysis will use data in all subwindows.\n') end end switch g.angleunit case { 'rad', 'ms', 'deg' },; otherwise error('Angleunit must be either ''rad'', ''deg'', or ''ms'''); end; switch g.type case { 'coher', 'phasecoher' 'phasecoher2' },; otherwise error('Type must be either ''coher'' or ''phasecoher'''); end; switch g.boottype case { 'times' 'timestrials' 'trials'},; otherwise error('Boot type must be either ''times'', ''trials'' or ''timestrials'''); end; if (~isnumeric(g.shuffle)) error('Shuffle argument type must be numeric'); end; switch g.memory case { 'low', 'high' },; otherwise error('memory must be either ''low'' or ''high'''); end; if strcmp(g.memory, 'low') & ~strcmp(g.boottype, 'times') error(['Bootstrap type ''' g.boottype ''' cannot be used in low memory mode']); end; switch g.compute case { 'matlab', 'c' },; otherwise error('compute must be either ''matlab'' or ''c'''); end; %%%%%%%%%%%%%%%%%%%%%%%%%%% % Compare 2 conditions %%%%%%%%%%%%%%%%%%%%%%%%%%% if iscell(X) if length(X) ~= 2 | length(Y) ~= 2 error('crossf: to compare conditions, X and Y input must be 2-elements cell arrays'); end; if ~strcmp(g.boottype, 'times') disp('crossf warning: The significance bootstrap type is irrelevant when comparing conditions'); end; for index = 1:2:length(vararginori) if index<=length(vararginori) % needed: if elemenets are deleted %if strcmp(vararginori{index}, 'alpha'), vararginori(index:index+1) = []; if strcmp(vararginori{index}, 'title'), vararginori(index:index+1) = []; end; end; end; if iscell(g.title) if length(g.title) <= 2, g.title{3} = 'Condition 2 - condition 1'; end; else g.title = { 'Condition 1', 'Condition 2', 'Condition 2 - condition 1' }; end; fprintf('Running crossf on condition 1 *********************\n'); fprintf('Note: If an out-of-memory error occurs, try reducing the\n'); fprintf(' number of time points or number of frequencies\n'); if ~strcmp(g.type, 'coher') fprintf('Note: Type ''coher'' takes 3 times as much memory as other options!)\n'); end figure; subplot(1,3,1); title(g.title{1}); if ~strcmp(g.type, 'coher') [R1,mbase,times,freqs,Rbootout1,Rangle1, savecoher1] = crossf(X{1}, Y{1}, ... frame, tlimits, Fs, varwin, 'savecoher', 1, 'title', ' ',vararginori{:}); else [R1,mbase,times,freqs,Rbootout1,Rangle1, savecoher1, Tfx1, Tfy1] = crossf(X{1}, Y{1}, ... frame, tlimits, Fs, varwin, 'savecoher', 1,'title', ' ',vararginori{:}); end; R1 = R1.*exp(j*Rangle1); % output Rangle is in radians % Asking user for memory limitations % if ~strcmp(g.noinput, 'yes') % tmp = whos('Tfx1'); % fprintf('This function will require an additional %d bytes, do you wish\n', ... % tmp.bytes*6+size(savecoher1,1)*size(savecoher1,2)*g.naccu*8); % res = input('to continue (y/n) (use the ''noinput'' option to disable this message):', 's'); % if res == 'n', return; end; % end; fprintf('\nRunning crossf on condition 2 *********************\n'); subplot(1,3,2); title(g.title{2}); if ~strcmp(g.type, 'coher') [R2,mbase,times,freqs,Rbootout2,Rangle2, savecoher2] = crossf(X{2}, Y{2}, ... frame, tlimits, Fs, varwin,'savecoher', 1, 'title', ' ',vararginori{:}); else [R2,mbase,times,freqs,Rbootout2,Rangle2, savecoher2, Tfx2, Tfy2] = crossf(X{2}, Y{2}, ... frame, tlimits, Fs, varwin,'savecoher', 1, 'title', ' ',vararginori{:}); end; R2 = R2.*exp(j*Rangle2); % output Rangle is in radians subplot(1,3,3); title(g.title{3}); if isnan(g.alpha) plotall(R2-R1, [], [], times, freqs, mbase, find(freqs <= g.maxfreq), g); else % accumulate coherence images (all arrays [nb_points * timesout * trials]) % --------------------------- allsavedcoher = zeros(size(savecoher1,1), ... size(savecoher1,2), ... size(savecoher1,3)+size(savecoher2,3)); allsavedcoher(:,:,1:size(savecoher1,3)) = savecoher1; allsavedcoher(:,:,size(savecoher1,3)+1:end) = savecoher2; clear savecoher1 savecoher2; if strcmp(g.type, 'coher') alltfx = zeros(size(Tfx1,1), size(Tfx2,2), size(Tfx1,3)+size(Tfx2,3)); alltfx(:,:,1:size(Tfx1,3)) = Tfx1; alltfx(:,:,size(Tfx1,3)+1:end) = Tfx2; clear Tfx1 Tfx2; alltfy = zeros(size(Tfy1,1), size(Tfy2,2), size(Tfy1,3)+size(Tfy2,3)); alltfy(:,:,1:size(Tfy1,3)) = Tfy1; alltfy(:,:,size(Tfy1,3)+1:end) = Tfy2; clear Tfy1 Tfy2; end; coherimages = zeros(size(allsavedcoher,1), size(allsavedcoher,2), g.naccu); cond1trials = length(X{1})/g.frame; cond2trials = length(X{2})/g.frame; alltrials = [1:cond1trials+cond2trials]; fprintf('Accumulating bootstrap:'); % preprocess data % --------------- switch g.type case 'coher', % take the square of alltfx and alltfy alltfx = alltfx.^2; alltfy = alltfy.^2; case 'phasecoher', % normalize allsavedcoher = allsavedcoher ./ abs(allsavedcoher); case 'phasecoher2', % don't do anything end; if strcmp(g.type, 'coher') [coherdiff coher1 coher2] = coher2conddiff( allsavedcoher, alltrials, ... cond1trials, g.type, alltfx, alltfy); else [coherdiff coher1 coher2] = coher2conddiff( allsavedcoher, alltrials, ... cond1trials, g.type); end; %figure; g.alpha = NaN; & to check that the new images are the same as the original %subplot(1,3,1); plotall(coher1, [], [], times, freqs, mbase, find(freqs <= g.maxfreq), g); %subplot(1,3,2); plotall(coher2, [], [], times, freqs, mbase, find(freqs <= g.maxfreq), g); %return; for index=1:g.naccu if rem(index,10) == 0, fprintf(' %d',index); end if rem(index,120) == 0, fprintf('\n'); end if strcmp(g.type, 'coher') coherimages(:,:,index) = coher2conddiff( allsavedcoher, shuffle(alltrials), ... cond1trials, g.type, alltfx, alltfy); else coherimages(:,:,index) = coher2conddiff( allsavedcoher, shuffle(alltrials), ... cond1trials, g.type); end; end; fprintf('\n'); % create articially a Bootstrap object to compute significance Boot = bootinit( [], size(allsavedcoher,1), g.timesout, g.naccu, 0, g.baseboot, ... 'noboottype', g.alpha, g.rboot); Boot.Coherboot.R = coherimages; Boot = bootcomppost(Boot, [], [], []); g.title = ''; plotall(coherdiff, Boot.Coherboot.R, Boot.Rsignif, times, freqs, mbase, ... find(freqs <= g.maxfreq), g); end; return; % ********************************** END PROCESSING TWO CONDITIONS end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % shuffle trials if necessary %%%%%%%%%%%%%%%%%%%%%%%%%%%%% if g.shuffle ~= 0 fprintf('x and y data trials being shuffled %d times\n',g.shuffle); XX = reshape(X, 1, frame, length(X)/g.frame); YY = Y; X = []; Y = []; for index = 1:g.shuffle XX = shuffle(XX,3); X = [X XX(:,:)]; Y = [Y YY]; end; end; % detrend over epochs (trials) if requested % ----------------------------------------- switch g.detrep case 'on' X = reshape(X, g.frame, length(X)/g.frame); X = X - mean(X,2)*ones(1, length(X(:))/g.frame); Y = reshape(Y, g.frame, length(Y)/g.frame); Y = Y - mean(Y,2)*ones(1, length(Y(:))/g.frame); end; % time limits wintime = 500*g.winsize/g.srate; times = [g.tlimits(1)+wintime:(g.tlimits(2)-g.tlimits(1)-2*wintime)/(g.timesout-1):g.tlimits(2)-wintime]; %%%%%%%%%% % baseline %%%%%%%%%% if ~isnan(g.baseline) baseln = find(times < g.baseline); % subtract means of pre-0 (centered) windows if isempty(baseln) baseln = 1:length(times); % use all times as baseline disp('Bootstrap baseline empty, using the whole epoch.'); end; baselength = length(baseln); else baseln = 1:length(times); % use all times as baseline baselength = length(times); % used for bootstrap end; %%%%%%%%%%%%%%%%%%%% % Initialize objects %%%%%%%%%%%%%%%%%%%% tmpsaveall = (~isnan(g.alpha) & isnan(g.rboot) & strcmp(g.memory, 'high')) ... | (strcmp(g.subitc, 'on') & strcmp(g.memory, 'high')); trials = length(X)/g.frame; if ~strcmp(g.compute, 'c') Tfx = tfinit(X, g.timesout, g.winsize, g.cycles, g.frame, g.padratio, g.detret, ... g.srate, g.maxfreq, g.subitc, g.type, g.cyclesfact, tmpsaveall); Tfy = tfinit(Y, g.timesout, g.winsize, g.cycles, g.frame, g.padratio, g.detret, ... g.srate, g.maxfreq, g.subitc, g.type, g.cyclesfact, tmpsaveall); Coher = coherinit(Tfx.nb_points, trials, g.timesout, g.type); Coherboot = coherinit(Tfx.nb_points, trials, g.naccu , g.type); Boot = bootinit( Coherboot, Tfx.nb_points, g.timesout, g.naccu, baselength, ... g.baseboot, g.boottype, g.alpha, g.rboot); freqs = Tfx.freqs; dispf = find(freqs <= g.maxfreq); freqs = freqs(dispf); else freqs = g.srate*g.cycles/g.winsize*[2:2/g.padratio:g.winsize]/2; end; dispf = find(Tfx.freqs <= g.maxfreq); %------------- % Reserve space %------------- % R = zeros(tfx.nb_points,g.timesout); % mean coherence % RR = repmat(nan,tfx.nb_points,g.timesout); % initialize with nans % Rboot = zeros(tfx.nb_points,g.naccu); % summed bootstrap coher % switch g.type % case 'coher', % cumulXY = zeros(tfx.nb_points,g.timesout); % cumulXYboot = zeros(tfx.nb_points,g.naccu); % end; % if g.bootsub > 0 % Rboottrial = zeros(tfx.nb_points, g.timesout, g.bootsub); % summed bootstrap coher % cumulXYboottrial = zeros(tfx.nb_points, g.timesout, g.bootsub); % end; % if ~isnan(g.alpha) & isnan(g.rboot) % tf.tmpalltimes = repmat(nan,tfx.nb_points,g.timesout); % end % -------------------- % Display text to user % -------------------- fprintf('\nComputing Event-Related '); switch g.type case 'phasecoher', fprintf('Phase Coherence (ITC) images for %d trials.\n',length(X)/g.frame); case 'phasecoher2', fprintf('Phase Coherence 2 (ITC) images for %d trials.\n',length(X)/g.frame); case 'coher', fprintf('Linear Coherence (ITC) images for %d trials.\n',length(X)/g.frame); end; fprintf('The trial latency range is from %4.5g ms before to %4.5g ms after\n the time-locking event.\n', g.tlimits(1),g.tlimits(2)); fprintf('The frequency range displayed will be %g-%g Hz.\n',min(freqs),g.maxfreq); if ~isnan(g.baseline) if length(baseln) == length(times) fprintf('Using the full trial latency range as baseline.\n'); else fprintf('Using trial latencies from %4.5g ms to %4.5g ms as baseline.\n', g.tlimits,g.baseline); end; else fprintf('No baseline time range was specified.\n'); end; if g.cycles==0 fprintf('The data window size will be %d samples (%g ms).\n',g.winsize,2*wintime); fprintf('The FFT length will be %d samples\n',g.winsize*g.padratio); else fprintf('The window size will be %2.3g cycles.\n',g.cycles); fprintf('The maximum window size will be %d samples (%g ms).\n',g.winsize,2*wintime); end fprintf('The window will be applied %d times\n',g.timesout); fprintf(' with an average step size of %2.2g samples (%2.4g ms).\n', Tfx.stp,1000*Tfx.stp/g.srate); fprintf('Results will be oversampled %d times.\n',g.padratio); if ~isnan(g.alpha) fprintf('Bootstrap confidence limits will be computed based on alpha = %g\n', g.alpha); else fprintf('Bootstrap confidence limits will NOT be computed.\n'); end switch g.plotphase case 'on', if strcmp(g.angleunit,'deg') fprintf(['Coherence angles will be imaged in degrees.\n']); elseif strcmp(g.angleunit,'rad') fprintf(['Coherence angles will be imaged in radians.\n']); elseif strcmp(g.angleunit,'ms') fprintf(['Coherence angles will be imaged in ms.\n']); end end; fprintf('\nProcessing trial (of %d): ',trials); % firstboot = 1; % Rn=zeros(trials,g.timesout); % X = X(:)'; % make X and Y column vectors % Y = Y(:)'; % tfy = tfx; if strcmp(g.compute, 'c') % C PART filename = [ 'tmpcrossf' num2str(round(rand(1)*1000)) ]; f = fopen([ filename '.in'], 'w'); fwrite(f, tmpsaveall, 'int32'); fwrite(f, g.detret, 'int32'); fwrite(f, g.srate, 'int32'); fwrite(f, g.maxfreq, 'int32'); fwrite(f, g.padratio, 'int32'); fwrite(f, g.cycles, 'int32'); fwrite(f, g.winsize, 'int32'); fwrite(f, g.timesout, 'int32'); fwrite(f, g.subitc, 'int32'); fwrite(f, g.type, 'int32'); fwrite(f, trials, 'int32'); fwrite(f, g.naccu, 'int32'); fwrite(f, length(X), 'int32'); fwrite(f, X, 'double'); fwrite(f, Y, 'double'); fclose(f); command = [ '!cppcrosff ' filename '.in ' filename '.out' ]; eval(command); f = fopen([ filename '.out'], 'r'); size1 = fread(f, 'int32', 1); size2 = fread(f, 'int32', 1); Rreal = fread(f, 'double', [size1 size2]); Rimg = fread(f, 'double', [size1 size2]); Coher.R = Rreal + j*Rimg; Boot.Coherboot.R = []; Boot.Rsignif = []; else % ------------------------ % MATLAB PART % compute ITC if necessary % ------------------------ if strcmp(g.subitc, 'on') for t=1:trials if rem(t,10) == 0, fprintf(' %d',t); end if rem(t,120) == 0, fprintf('\n'); end Tfx = tfitc( Tfx, t, 1:g.timesout); Tfy = tfitc( Tfy, t, 1:g.timesout); end; fprintf('\n'); Tfx = tfitcpost( Tfx, trials); Tfy = tfitcpost( Tfy, trials); end; % --------- % Main loop % --------- if g.savecoher, trialcoher = zeros(Tfx.nb_points, g.timesout, trials); else trialcoher = []; end; for t=1:trials if rem(t,10) == 0, fprintf(' %d',t); end if rem(t,120) == 0, fprintf('\n'); end Tfx = tfcomp( Tfx, t, 1:g.timesout); Tfy = tfcomp( Tfy, t, 1:g.timesout); if g.savecoher [Coher trialcoher(:,:,t)] = cohercomp( Coher, Tfx.tmpalltimes, ... Tfy.tmpalltimes, t, 1:g.timesout); else Coher = cohercomp( Coher, Tfx.tmpalltimes, Tfy.tmpalltimes, t, 1:g.timesout); end; Boot = bootcomp( Boot, Coher.Rn(t,:), Tfx.tmpalltimes, Tfy.tmpalltimes); end % t = trial [Boot Rbootout] = bootcomppost(Boot, Coher.Rn, Tfx.tmpall, Tfy.tmpall); % Note that the bootstrap thresholding is actually performed % in the display subfunction plotall() Coher = cohercomppost(Coher, trials); end; % ---------------------------------- % If coherence, perform the division % ---------------------------------- % switch g.type % case 'coher', % R = R ./ cumulXY; % if ~isnan(g.alpha) & isnan(g.rboot) % Rboot = Rboot ./ cumulXYboot; % end; % if g.bootsub > 0 % Rboottrial = Rboottrial ./ cumulXYboottrial; % end; % case 'phasecoher', % Rn = sum(Rn, 1); % R = R ./ (ones(size(R,1),1)*Rn); % coherence magnitude % if ~isnan(g.alpha) & isnan(g.rboot) % Rboot = Rboot / trials; % end; % if g.bootsub > 0 % Rboottrial = Rboottrial / trials; % end; % end; % ---------------- % Compute baseline % ---------------- mbase = mean(abs(Coher.R(:,baseln)')); % mean baseline coherence magnitude % --------------- % Plot everything % --------------- plotall(Coher.R, Boot.Coherboot.R, Boot.Rsignif, times, freqs, mbase, dispf, g); % -------------------------------------- % Convert output Rangle to degrees or ms - Disabled to keep original default: radians output % -------------------------------------- % Rangle = angle(Coher.R); % returns radians % if strcmp(g.angleunit,'ms') % convert to ms % Rangle = (Rangle/(2*pi)).*repmat(1000./freqs(dispf)',1,length(times)); % elseif strcmp(g.angleunit,'deg') % convert to deg % Rangle = Rangle*180/pi; % convert to degrees % else % angleunit is 'rad' % % Rangle = Rangle; % end % Rangle(find(Rraw==0)) = 0; % mask for significance - set angle at non-signif coher points to 0 R = abs(Coher.R); Rsignif = Boot.Rsignif; Tfx = permute(Tfx.tmpall, [3 2 1]); % from [trials timesout nb_points] % to [nb_points timesout trials] Tfy = permute(Tfy.tmpall, [3 2 1]); return; % end crossf() ************************************************* % % crossf() plotting functions % ---------------------------------------------------------------------- function plotall(R, Rboot, Rsignif, times, freqs, mbase, dispf, g) switch lower(g.plotphase) case 'on', switch lower(g.plotamp), case 'on', ordinate1 = 0.67; ordinate2 = 0.1; height = 0.33; g.plot = 1; case 'off', ordinate2 = 0.1; height = 0.9; g.plot = 1; end; case 'off', ordinate1 = 0.1; height = 0.9; switch lower(g.plotamp), case 'on', ordinate1 = 0.1; height = 0.9; g.plot = 1; case 'off', g.plot = 0; end; end; % % Compute cross-spectral angles % ----------------------------- Rangle = angle(R); % returns radians % % Optionally convert Rangle to degrees or ms % ------------------------------------------ if strcmp(g.angleunit,'ms') % convert to ms Rangle = (Rangle/(2*pi)).*repmat(1000./freqs(dispf)',1,length(times)); maxangle = max(max(abs(Rangle))); elseif strcmp(g.angleunit,'deg') % convert to degrees Rangle = Rangle*180/pi; % convert to degrees maxangle = 180; % use full-cycle plotting else maxangle = pi; % radians end R = abs(R); % if ~isnan(g.baseline) % R = R - repmat(mbase',[1 g.timesout]); % remove baseline mean % end; Rraw = R; % raw coherence (e.g., coherency) magnitude values output if g.plot fprintf('\nNow plotting...\n'); set(gcf,'DefaultAxesFontSize',g.AXES_FONT) colormap(jet(256)); pos = get(gca,'position'); % plot relative to current axes q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]; axis('off') end; switch lower(g.plotamp) case 'on' % % Image the coherence [% perturbations] % RR = R; if ~isnan(g.alpha) % zero out (and 'green out') nonsignif. R values RR(find(RR < repmat(Rboot(:),[1 g.timesout]))) = 0; Rraw(find(repmat(Rsignif(:),[1,size(Rraw,2)])>=Rraw))=0; end if g.cmax == 0 coh_caxis = max(max(R(dispf,:)))*[-1 1]; else coh_caxis = g.cmax*[-1 1]; end h(6) = axes('Units','Normalized', 'Position',[.1 ordinate1 .8 height].*s+q); map=hsv(300); % install circular color map - green=0, yellow, orng, red, violet = max % cyan, blue, violet = min map = flipud([map(251:end,:);map(1:250,:)]); map(151,:) = map(151,:)*0.9; % tone down the (0=) green! colormap(map); imagesc(times,freqs(dispf),RR(dispf,:),coh_caxis); % plot the coherence image if ~isempty(g.maxamp) caxis([-g.maxamp g.maxamp]); end; tmpscale = caxis; hold on plot([0 0],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth) for i=1:length(g.marktimes) plot([g.marktimes(i) g.marktimes(i)],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth); end; hold off set(h(6),'YTickLabel',[],'YTick',[]) set(h(6),'XTickLabel',[],'XTick',[]) %title('Event-Related Coherence') h(8) = axes('Position',[.95 ordinate1 .05 height].*s+q); cbar(h(8),151:300, [0 tmpscale(2)]); % use only positive colors (gyorv) % % Plot delta-mean min and max coherence at each time point on bottom of image % h(10) = axes('Units','Normalized','Position',[.1 ordinate1-0.1 .8 .1].*s+q); % plot marginal means below Emax = max(R(dispf,:)); % mean coherence at each time point Emin = min(R(dispf,:)); % mean coherence at each time point plot(times,Emin, times, Emax, 'LineWidth',g.linewidth); hold on; plot([times(1) times(length(times))],[0 0],'LineWidth',0.7); plot([0 0],[-500 500],'--m','LineWidth',g.linewidth); for i=1:length(g.marktimes) plot([g.marktimes(i) g.marktimes(i)],[-500 500],'--m','LineWidth',g.linewidth); end; if ~isnan(g.alpha) & strcmp(g.boottype, 'trials') % plot bootstrap significance limits (base mean +/-) plot(times,mean(Rboot(dispf,:)),'g','LineWidth',g.linewidth); hold on; plot(times,mean(Rsignif(dispf,:)),'k:','LineWidth',g.linewidth); axis([min(times) max(times) 0 max([Emax(:)' Rsignif(:)'])*1.2]) else axis([min(times) max(times) 0 max(Emax)*1.2]) end; tick = get(h(10),'YTick'); set(h(10),'YTick',[tick(1) ; tick(length(tick))]) set(h(10),'YAxisLocation','right') xlabel('Time (ms)') ylabel('coh.') % % Plot mean baseline coherence at each freq on left side of image % h(11) = axes('Units','Normalized','Position',[0 ordinate1 .1 height].*s+q); % plot mean spectrum E = abs(mbase(dispf)); % baseline mean coherence at each frequency plot(freqs(dispf),E,'LineWidth',g.linewidth); % plot mbase if ~isnan(g.alpha) % plot bootstrap significance limits (base mean +/-) hold on % plot(freqs(dispf),Rboot(:,dispf)+[E;E],'g','LineWidth',g.linewidth); plot(freqs(dispf),mean(Rboot (dispf,:),2),'g','LineWidth',g.linewidth); plot(freqs(dispf),mean(Rsignif(dispf,:),2),'k:','LineWidth',g.linewidth); axis([freqs(1) freqs(max(dispf)) 0 max([E Rsignif(:)'])*1.2]); else % plot marginal mean coherence only if ~isnan(max(E)) axis([freqs(1) freqs(max(dispf)) 0 max(E)*1.2]); end; end tick = get(h(11),'YTick'); set(h(11),'YTick',[tick(1) ; tick(length(tick))]) set(h(11),'View',[90 90]) xlabel('Freq. (Hz)') ylabel('coh.') end; switch lower(g.plotphase) case 'on' % % Plot coherence phase lags in bottom panel % h(13) = axes('Units','Normalized','Position',[.1 ordinate2 .8 height].*s+q); Rangle(find(Rraw==0)) = 0; % when plotting, mask for significance % = set angle at non-signif coher points to 0 imagesc(times,freqs(dispf),Rangle(dispf,:),[-maxangle maxangle]); % plot the hold on % coherence phase angles plot([0 0],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth); % zero-time line for i=1:length(g.marktimes) plot([g.marktimes(i) g.marktimes(i)],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth); end; ylabel('Freq. (Hz)') xlabel('Time (ms)') h(14)=axes('Position',[.95 ordinate2 .05 height].*s+q); cbar(h(14),0,[-maxangle maxangle]); % two-sided colorbar end if g.plot try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if (length(g.title) > 0) % plot title if h(6) ~= 0, axes(h(6)); else axes(h(13)); end; %h = subplot('Position',[0 0 1 1].*s+q, 'Visible','Off'); %h(13) = text(-.05,1.01,g.title); h(13) = title(g.title); %set(h(13),'VerticalAlignment','bottom') %set(h(13),'HorizontalAlignment','left') set(h(13),'FontSize',g.TITLE_FONT); end % %%%%%%%%%%%%%%% plot topoplot() %%%%%%%%%%%%%%%%%%%%%%% % if (~isempty(g.topovec)) h(15) = subplot('Position',[-.1 .43 .2 .14].*s+q); if size(g.topovec,2) <= 2 topoplot(g.topovec(1),g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', g.chaninfo); else topoplot(g.topovec(1,:),g.elocs,'electrodes','off', 'chaninfo', g.chaninfo); end; axis('square') h(16) = subplot('Position',[.9 .43 .2 .14].*s+q); if size(g.topovec,2) <= 2 topoplot(g.topovec(2),g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', g.chaninfo); else topoplot(g.topovec(2,:),g.elocs,'electrodes','off', 'chaninfo', g.chaninfo); end; axis('square') end axcopy(gcf); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TIME FREQUENCY %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function for time freq initialisation % ------------------------------------- function Tf = tfinit(X, timesout, winsize, ... cycles, frame, padratio, detret, srate, maxfreq, subitc, type, cyclesfact, saveall); Tf.X = X(:)'; % make X column vectors Tf.winsize = winsize; Tf.cycles = cycles; Tf.frame = frame; Tf.padratio = padratio; Tf.detret = detret; Tf.stp = (frame-winsize)/(timesout-1); Tf.subitc = subitc; % for ITC Tf.type = type; % for ITC Tf.saveall = saveall; if (Tf.cycles == 0) %%%%%%%%%%%%%% constant window-length FFTs %%%%%%%%%%%%%%%% % Tf.freqs = srate/winsize*[1:2/padratio:winsize]/2; % incorect for padratio > 2 Tf.freqs = linspace(0, srate/2, length([1:2/padratio:winsize])+1); Tf.freqs = Tf.freqs(2:end); Tf.win = hanning(winsize); Tf.nb_points = padratio*winsize/2; else % %%%%%%%%%%%%%%%%%% Constant-Q (wavelet) DFTs %%%%%%%%%%%%%%%%%%%%%%%%%%%% Tf.freqs = srate*cycles/winsize*[2:2/padratio:winsize]/2; Tf.win = dftfilt(winsize,maxfreq/srate,cycles,padratio,cyclesfact); Tf.nb_points = size(Tf.win,2); end; Tf.tmpalltimes = zeros(Tf.nb_points, timesout); trials = length(X)/frame; if saveall Tf.tmpall = repmat(nan,[trials timesout Tf.nb_points]); else Tf.tmpall = []; end Tf.tmpallbool = zeros(trials,timesout); Tf.ITCdone = 0; if Tf.subitc Tf.ITC = zeros(Tf.nb_points, timesout); switch Tf.type, case { 'coher' 'phasecoher2' } Tf.ITCcumul = zeros(Tf.nb_points, timesout); end; end; % function for itc % ---------------- function [Tf, itcvals] = tfitc(Tf, trials, times); Tf = tfcomp(Tf, trials, times); switch Tf.type case 'coher', Tf.ITC(:,times) = Tf.ITC(:,times) + Tf.tmpalltimes; % complex coher. Tf.ITCcumul(:,times) = Tf.ITCcumul(:,times)+abs(Tf.tmpalltimes).^2; case 'phasecoher2', Tf.ITC(:,times) = Tf.ITC(:,times) + Tf.tmpalltimes; % complex coher. Tf.ITCcumul(:,times) = Tf.ITCcumul(:,times)+abs(Tf.tmpalltimes); case 'phasecoher', Tf.ITC(:,times) = Tf.ITC(:,times) + Tf.tmpalltimes ./ abs(Tf.tmpalltimes); % complex coher. end % ~any(isnan()) return; function [Tf, itcvals] = tfitcpost(Tf, trials); switch Tf.type case 'coher', Tf.ITC = Tf.ITC ./ sqrt(trials * Tf.ITCcumul); case 'phasecoher2', Tf.ITC = Tf.ITC ./ Tf.ITCcumul; case 'phasecoher', Tf.ITC = Tf.ITC / trials; % complex coher. end % ~any(isnan()) if Tf.saveall Tf.ITC = transpose(Tf.ITC); % do not use ' otherwise conjugate %imagesc(abs(Tf.ITC)); colorbar; figure; %squeeze(Tf.tmpall(1,1,1:Tf.nb_points)) %squeeze(Tf.ITC (1,1,1:Tf.nb_points)) %Tf.ITC = shiftdim(Tf.ITC, -1); Tf.ITC = repmat(shiftdim(Tf.ITC, -1), [trials 1 1]); Tf.tmpall = (Tf.tmpall - abs(Tf.tmpall) .* Tf.ITC) ./ abs(Tf.tmpall); % for index = 1:trials % imagesc(squeeze(abs(Tf.tmpall(index,:,:)))); drawnow; figure; % Tf.tmpall(index,:,:) = (Tf.tmpall(index,:,:) - Tf.tmpall(index,:,:) .* Tf.ITC)./Tf.tmpall(index,:,:); % imagesc(squeeze(abs(Tf.tmpall(index,:,:)))); drawnow; % subplot(10,10, index); imagesc(squeeze(abs(Tf.tmpall(index,:,:)))); caxis([0 1]); drawnow; % end; % squeeze(Tf.tmpall(1,1,1:Tf.nb_points)) % figure; axcopy; end; Tf.ITCdone = 1; return; % function for time freq decomposition % ------------------------------------ function [Tf, tmpX] = tfcomp(Tf, trials, times); % tf is an structure containing all the information about the decomposition for trial = trials for index = times if ~Tf.tmpallbool(trial, index) % already computed tmpX = Tf.X([1:Tf.winsize]+floor((index-1)*Tf.stp)+(trial-1)*Tf.frame); if ~any(isnan(tmpX)) % perform the decomposition tmpX = tmpX - mean(tmpX); switch Tf.detret, case 'on', tmpX = detrend(tmpX); end; if Tf.cycles == 0 % use FFTs tmpX = Tf.win .* tmpX(:); tmpX = fft(tmpX,Tf.padratio*Tf.winsize); tmpX = tmpX(2:Tf.padratio*Tf.winsize/2+1); else tmpX = transpose(Tf.win) * tmpX(:); end else tmpX = NaN; end; if Tf.ITCdone tmpX = (tmpX - abs(tmpX) .* Tf.ITC(:,index)) ./ abs(tmpX); end; Tf.tmpalltimes(:,index) = tmpX; if Tf.saveall Tf.tmpall(trial, index,:) = tmpX; Tf.tmpallbool(trial, index) = 1; end else Tf.tmpalltimes(:,index) = Tf.tmpall(trial, index,:); end; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% COHERENCE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function for coherence initialisation % ------------------------------------- function Coher = coherinit(nb_points, trials, timesout, type); Coher.R = zeros(nb_points,timesout); % mean coherence % Coher.RR = repmat(nan,nb_points,timesout); % initialize with nans Coher.type = type; Coher.Rn=zeros(trials,timesout); switch type case 'coher', Coher.cumulX = zeros(nb_points,timesout); Coher.cumulY = zeros(nb_points,timesout); case 'phasecoher2', Coher.cumul = zeros(nb_points,timesout); end; % function for coherence calculation % ------------------------------------- % function Coher = cohercomparray(Coher, tmpX, tmpY, trial); % switch Coher.type % case 'coher', % Coher.R = Coher.R + tmpX.*conj(tmpY); % complex coher. % Coher.cumulXY = Coher.cumulXY + abs(tmpX).*abs(tmpY); % case 'phasecoher', % Coher.R = Coher.R + tmpX.*conj(tmpY) ./ (abs(tmpX).*abs(tmpY)); % complex coher. % Coher.Rn(trial,:) = 1; % end % ~any(isnan()) function [Coher,tmptrialcoh] = cohercomp(Coher, tmpX, tmpY, trial, time); tmptrialcoh = tmpX.*conj(tmpY); switch Coher.type case 'coher', Coher.R(:,time) = Coher.R(:,time) + tmptrialcoh; % complex coher. Coher.cumulX(:,time) = Coher.cumulX(:,time) + abs(tmpX).^2; Coher.cumulY(:,time) = Coher.cumulY(:,time) + abs(tmpY).^2; case 'phasecoher2', Coher.R(:,time) = Coher.R(:,time) + tmptrialcoh; % complex coher. Coher.cumul(:,time) = Coher.cumul(:,time) + abs(tmptrialcoh); case 'phasecoher', Coher.R(:,time) = Coher.R(:,time) + tmptrialcoh ./ abs(tmptrialcoh); % complex coher. %figure; imagesc(abs(tmpX.*conj(tmpY) ./ (abs(tmpX).*abs(tmpY)))); Coher.Rn(trial,time) = Coher.Rn(trial,time)+1; end % ~any(isnan()) % function for post coherence calculation % --------------------------------------- function Coher = cohercomppost(Coher, trials); switch Coher.type case 'coher', Coher.R = Coher.R ./ sqrt(Coher.cumulX) ./ sqrt(Coher.cumulY); case 'phasecoher2', Coher.R = Coher.R ./ Coher.cumul; case 'phasecoher', Coher.Rn = sum(Coher.Rn, 1); Coher.R = Coher.R ./ (ones(size(Coher.R,1),1)*Coher.Rn); % coherence magnitude end; % function for 2 conditions coherence calculation % ----------------------------------------------- function [coherimage, coherimage1, coherimage2] = coher2conddiff( allsavedcoher, alltrials, cond1trials, type, tfx, tfy); t1s = alltrials(1:cond1trials); t2s = alltrials(cond1trials+1:end); switch type case 'coher', coherimage1 = sum(allsavedcoher(:,:,t1s),3) ./ sqrt(sum(tfx(:,:,t1s),3)) ./ sqrt(sum(tfy(:,:,t1s),3)); coherimage2 = sum(allsavedcoher(:,:,t2s),3) ./ sqrt(sum(tfx(:,:,t2s),3)) ./ sqrt(sum(tfy(:,:,t1s),3)); case 'phasecoher2', coherimage1 = sum(allsavedcoher(:,:,t1s),3) ./ sum(abs(allsavedcoher(:,:,t1s)),3); coherimage2 = sum(allsavedcoher(:,:,t2s),3) ./ sum(abs(allsavedcoher(:,:,t2s)),3); case 'phasecoher', coherimage1 = sum(allsavedcoher(:,:,t1s),3) / cond1trials; coherimage2 = sum(allsavedcoher(:,:,t2s),3) / (size(allsavedcoher,3)-cond1trials); end; coherimage = coherimage2 - coherimage1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BOOTSTRAP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function for bootstrap initialisation % ------------------------------------- function Boot = bootinit(Coherboot, nb_points, timesout, naccu, baselength, baseboot, boottype, alpha, rboot); Boot.Rboot = zeros(nb_points,naccu); % summed bootstrap coher Boot.boottype = boottype; Boot.baselength = baselength; Boot.baseboot = baseboot; Boot.Coherboot = Coherboot; Boot.naccu = naccu; Boot.alpha = alpha; Boot.rboot = rboot; % function for bootstrap computation % ---------------------------------- function Boot = bootcomp(Boot, Rn, tmpalltimesx, tmpalltimesy); if ~isnan(Boot.alpha) & isnan(Boot.rboot) if strcmp(Boot.boottype, 'times') % get g.naccu bootstrap estimates for each trial goodbasewins = find(Rn==1); if Boot.baseboot % use baseline windows only goodbasewins = find(goodbasewins<=Boot.baselength); end ngdbasewins = length(goodbasewins); j=1; tmpsX = zeros(size(tmpalltimesx,1), Boot.naccu); tmpsY = zeros(size(tmpalltimesx,1), Boot.naccu); if ngdbasewins > 1 while j<=Boot.naccu s = ceil(rand([1 2])*ngdbasewins); % random ints [1,g.timesout] s = goodbasewins(s); if ~any(isnan(tmpalltimesx(:,s(1)))) & ~any(isnan(tmpalltimesy(:,s(2)))) tmpsX(:,j) = tmpalltimesx(:,s(1)); tmpsY(:,j) = tmpalltimesy(:,s(2)); j = j+1; end end Boot.Coherboot = cohercomp(Boot.Coherboot, tmpsX, tmpsY, 1, 1:Boot.naccu); end; end end; % handle other trial bootstrap types % ---------------------------------- function [Boot, Rbootout] = bootcomppost(Boot, allRn, alltmpsX, alltmpsY); trials = size(alltmpsX, 1); times = size(alltmpsX, 2); nb_points = size(alltmpsX, 3); if ~isnan(Boot.alpha) & isnan(Boot.rboot) if strcmp(Boot.boottype, 'trials') % get g.naccu bootstrap estimates for each trial fprintf('\nProcessing trial bootstrap (of %d):',times(end)); tmpsX = zeros(size(alltmpsX,3), Boot.naccu); tmpsY = zeros(size(alltmpsY,3), Boot.naccu ); Boot.fullcoherboot = zeros(nb_points, Boot.naccu, times); for index=1:times if rem(index,10) == 0, fprintf(' %d',index); end if rem(index,120) == 0, fprintf('\n'); end for allt=1:trials j=1; while j<=Boot.naccu t = ceil(rand([1 2])*trials); % random ints [1,g.timesout] if (allRn(t(1),index) == 1) & (allRn(t(2),index) == 1) tmpsX(:,j) = squeeze(alltmpsX(t(1),index,:)); tmpsY(:,j) = squeeze(alltmpsY(t(2),index,:)); j = j+1; end end Boot.Coherboot = cohercomp(Boot.Coherboot, tmpsX, tmpsY, 1, 1:Boot.naccu); end; Boot.Coherboot = cohercomppost(Boot.Coherboot); % CHECK IF NECSSARY FOR ALL BOOT TYPE Boot.fullcoherboot(:,:,index) = Boot.Coherboot.R; Boot.Coherboot = coherinit(nb_points, trials, Boot.naccu, Boot.Coherboot.type); end; Boot.Coherboot.R = Boot.fullcoherboot; Boot = rmfield(Boot, 'fullcoherboot'); elseif strcmp(Boot.boottype, 'timestrials') % handle timestrials bootstrap fprintf('\nProcessing time and trial bootstrap (of %d):',trials); tmpsX = zeros(size(alltmpsX,3), Boot.naccu); tmpsY = zeros(size(alltmpsY,3), Boot.naccu ); for allt=1:trials if rem(allt,10) == 0, fprintf(' %d',allt); end if rem(allt,120) == 0, fprintf('\n'); end j=1; while j<=Boot.naccu t = ceil(rand([1 2])*trials); % random ints [1,g.timesout] goodbasewins = find((allRn(t(1),:) & allRn(t(2),:)) ==1); if Boot.baseboot % use baseline windows only goodbasewins = find(goodbasewins<=baselength); end ngdbasewins = length(goodbasewins); if ngdbasewins>1 s = ceil(rand([1 2])*ngdbasewins); % random ints [1,g.timesout] s=goodbasewins(s); if all(allRn(t(1),s(1)) == 1) & all(allRn(t(2),s(2)) == 1) tmpsX(:,j) = squeeze(alltmpsX(t(1),s(1),:)); tmpsY(:,j) = squeeze(alltmpsY(t(2),s(2),:)); j = j+1; end end end Boot.Coherboot = cohercomp(Boot.Coherboot, tmpsX, tmpsY, 1, 1:Boot.naccu); end Boot.Coherboot = cohercomppost(Boot.Coherboot); elseif strcmp(Boot.boottype, 'times') % boottype is 'times' Boot.Coherboot = cohercomppost(Boot.Coherboot); end; end; % test if precomputed if ~isnan(Boot.alpha) & isnan(Boot.rboot) % if bootstrap analysis included . . . % 'boottype'='times' or 'timestrials', size(R)=nb_points*naccu % 'boottype'='trials', size(R)=nb_points*naccu*times Boot.Coherboot.R = abs (Boot.Coherboot.R); Boot.Coherboot.R = sort(Boot.Coherboot.R,2); % compute bootstrap significance level i = round(Boot.naccu*Boot.alpha); Boot.Rsignif = mean(Boot.Coherboot.R(:,Boot.naccu-i+1:Boot.naccu),2); % significance levels for Rraw Boot.Coherboot.R = squeeze(mean(Boot.Coherboot.R(:,Boot.naccu-i+1:Boot.naccu),2)); if size(Boot.Coherboot.R, 2) == 1 Rbootout(:,2) = Boot.Coherboot.R; else Rbootout(:,:,2) = Boot.Coherboot.R; end; % BEFORE %Rboot = [mean(Rboot(1:i,:)) ; mean(Rboot(g.naccu-i+1:g.naccu,:))]; elseif ~isnan(Boot.rboot) Boot.Coherboot.R = Boot.rboot; Boot.Rsignif = Boot.rboot; Rbootout = Boot.rboot; else Boot.Coherboot.R = []; Boot.Rsignif = []; Rbootout = []; end % NOTE: above, mean ????? function w = hanning(n) if ~rem(n,2) w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end
github
lcnhappe/happe-master
dftfilt2.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/dftfilt2.m
5,665
utf_8
fa2b4cd1d3a209b72ce506ee4e6fee46
% dftfilt2() - discrete complex wavelet filters % % Usage: % >> wavelet = dftfilt2( freqs, cycles, srate, cyclefact) % % Inputs: % freqs - frequency array % cycles - cycles array. If one value is given, all wavelets have % the same number of cycles. If two values are given, the % two values are used for the number of cycles at the lowest % frequency and at the highest frequency, with linear % interpolation between these values for intermediate % frequencies % srate - sampling rate (in Hz) % % cycleinc - ['linear'|'log'] increase mode if [min max] cycles is % provided in 'cycle' parameter. {default: 'linear'} % type - ['sinus'|'morlet'] wavelet type is a sinusoid with % cosine (real) and sine (imaginary) parts tapered by % a Hanning or Morlet function. 'morlet' is a typical Morlet % wavelet (with p=2*pi and sigma=0.7) best matching the % 'sinus' Hanning taper) {default: 'morlet'} % Output: % wavelet - cell array of wavelet filters % % Note: The length of the window is automatically computed from the % number of cycles and is always made odd. % % Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 3/28/2003 % Copyright (C) 3/28/2003 Arnaud Delorme 8, 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 wavelet = dftfilt2( freqs, cycles, srate, cycleinc, type); if nargin < 3 error('3 arguments required'); end; if nargin < 5 type = 'morlet'; end; % compute number of cycles at each frequency % ------------------------------------------ if length(cycles) == 1 cycles = cycles*ones(size(freqs)); elseif length(cycles) == 2 if nargin == 4 & strcmpi(cycleinc, 'log') % cycleinc cycles = linspace(log(cycles(1)), log(cycles(2)), length(freqs)); cycles = exp(cycles); else cycles = linspace(cycles(1), cycles(2), length(freqs)); end; end; % compute wavelet for index = 1:length(freqs) % number of cycles depend on window size % number of cycles automatically reduced if smaller window % note: as the number of cycle changes, the frequency shifts a little % this has to be fixed winlen = cycles(index)*srate/freqs(index); winlenint = floor(winlen); if mod(winlenint,2) == 1, winlenint = winlenint+1; end; winval = linspace(winlenint/2, -winlenint/2, winlenint+1); if strcmpi(type, 'sinus') % Hanning win = exp(2i*pi*freqs(index)*winval/srate); wavelet{index} = win .* hanning(length(winval))'; else % Morlet t = freqs(index)*winval/srate; p = 2*pi; s = cycles(index)/5; wavelet{index} = exp(j*t*p)/sqrt(2*pi) .* ... (exp(-t.^2/(2*s^2))-sqrt(2)*exp(-t.^2/(s^2)-p^2*s^2/4)); end; end; return; % testing % ------- wav1 = dftfilt2(5, 5, 256); wav1 = wav1{1}; abs1 = linspace(-floor(length(wav1)),floor(length(wav1)), length(wav1)); figure; plot(abs1, real(wav1), 'b'); wav2 = dftfilt2(5, 3, 256); wav2 = wav2{1}; abs2 = linspace(-floor(length(wav2)),floor(length(wav2)), length(wav2)); hold on; plot(abs2, real(wav2), 'r'); wav3 = dftfilt2(5, 1.4895990, 256); wav3 = wav3{1}; abs3 = linspace(-floor(length(wav3)),floor(length(wav3)), length(wav3)); hold on; plot(abs3, real(wav3), 'g'); wav4 = dftfilt2(5, 8.73, 256); wav4 = wav4{1}; abs4 = linspace(-floor(length(wav4)),floor(length(wav4)), length(wav4)); hold on; plot(abs4, real(wav4), 'm'); % more testing % ------------ freqs = exp(linspace(0,log(10),10)); win = dftfilt2(freqs, [3 3], 256, 'linear', 'sinus'); win = dftfilt2(freqs, [3 3], 256, 'linear', 'morlet'); freqs = [12.0008 13.2675 14.5341 15.8007 17.0674 18.3340 19.6007 20.8673 22.1339 23.4006 24.6672 25.9339 27.2005 28.4671 29.7338 31.0004 32.2670 33.5337 34.8003 36.0670 37.3336 38.6002 39.8669 41.1335 42.4002 43.6668 44.9334 46.2001 47.4667 ... 48.7334 50.0000]; win = dftfilt2(freqs, [3 12], 256, 'linear'); size(win) winsize = 0; for index = 1:length(win) winsize = max(winsize,length(win{index})); end; allwav = zeros(winsize, length(win)); for index = 1:length(win) wav1 = win{index}; abs1 = linspace(-(length(wav1)-1)/2,(length(wav1)-1)/2, length(wav1)); allwav(abs1+(winsize+1)/2,index) = wav1(:); end; figure; imagesc(imag(allwav)); % syemtric hanning function function w = hanning(n) if ~rem(n,2) w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end
github
lcnhappe/happe-master
newtimef.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/newtimef.m
97,481
utf_8
9b205e33083e0973b5d9e671eac0abb5
% newtimef() - Return estimates and plots of mean event-related (log) spectral % perturbation (ERSP) and inter-trial coherence (ITC) events across % event-related trials (epochs) of a single input channel time series. % % * Also can compute and statistically compare transforms for two time % series. Use this to compare ERSP and ITC means in two conditions. % % * Uses either fixed-window, zero-padded FFTs (fastest), or wavelet % 0-padded DFTs. FFT uses Hanning tapers; wavelets use (similar) Morlet % tapers. % % * For the wavelet and FFT methods, output frequency spacing % is the lowest frequency ('srate'/'winsize') divided by 'padratio'. % NaN input values (such as returned by eventlock()) are ignored. % % * If 'alpha' is given (see below), permutation statistics are computed % (from a distribution of 'naccu' surrogate data trials) and % non-significant features of the output plots are zeroed out % and plotted in green. % % * Given a 'topovec' topo vector and 'elocs' electrode location file, % the figure also shows a topoplot() view of the specified scalp map. % % * Note: Left-click on subplots to view and zoom in separate windows. % % Usage with single dataset: % >> [ersp,itc,powbase,times,freqs,erspboot,itcboot] = ... % newtimef(data, frames, epochlim, srate, cycles,... % 'key1',value1, 'key2',value2, ... ); % % Example to compare two condition (channel 1 EEG versus ALLEEG(2)): % >> [ersp,itc,powbase,times,freqs,erspboot,itcboot] = ... % newtimef({EEG.data(1,:,:) ALLEEG(2).data(1,:,:)}, % EEG.pnts, [EEG.xmin EEG.xmax]*1000, EEG.srate, cycles); % NOTE: % >> timef details % presents more detailed argument information % % Note: version timef() also computes multitaper transforms % % Required inputs: Value {default} % data = Single-channel data vector (1,frames*ntrials), else % 2-D array (frames,trials) or 3-D array (1,frames,trials). % To compare two conditions (data1 versus data2), in place of % a single data matrix enter a cell array {data1 data2} % frames = Frames per trial. Ignored if data are 2-D or 3-D. {750} % tlimits = [mintime maxtime] (ms). Note that these are the time limits % of the data epochs themselves, NOT A SUB-WINDOW TO EXTRACT % FROM THE EPOCHS as is the case for pop_newtimef(). {[-1000 2000]} % Fs = data sampling rate (Hz) {default: read from icadefs.m or 250} % varwin = [real] indicates the number of cycles for the time-frequency % decomposition {default: 0} % If 0, use FFTs and Hanning window tapering. % If [real positive scalar], the number of cycles in each Morlet % wavelet, held constant across frequencies. % If [cycles cycles(2)] wavelet cycles increase with % frequency beginning at cycles(1) and, if cycles(2) > 1, % increasing to cycles(2) at the upper frequency, % If cycles(2) = 0, use same window size for all frequencies % (similar to FFT when cycles(1) = 1) % If cycles(2) = 1, cycles do not increase (same as giving % only one value for 'cycles'). This corresponds to a pure % wavelet decomposition, same number of cycles at each frequency. % If 0 < cycles(2) < 1, cycles increase linearly with frequency: % from 0 --> FFT (same window width at all frequencies) % to 1 --> wavelet (same number of cycles at all frequencies). % The exact number of cycles in the highest frequency window is % indicated in the command line output. Typical value: 'cycles', [3 0.5] % % Optional inter-trial coherence (ITC) Type: % 'itctype' = ['coher'|'phasecoher'|'phasecoher2'] Compute either linear % coherence ('coher') or phase coherence ('phasecoher'). % Originall called 'phase-locking factor' {default: 'phasecoher'} % % Optional detrending: % 'detrend' = ['on'|'off'], Linearly detrend each data epoch {'off'} % 'rmerp' = ['on'|'off'], Remove epoch mean from data epochs {'off'} % % Optional FFT/DFT parameters: % 'winsize' = If cycles==0: data subwindow length (fastest, 2^n<frames); % If cycles >0: The *longest* window length to use. This % determines the lowest output frequency. Note: this parameter % is overwritten when the minimum frequency requires % a longer time window {default: ~frames/8} % 'timesout' = Number of output times (int<frames-winframes). Enter a % negative value [-S] to subsample original times by S. % Enter an array to obtain spectral decomposition at % specific times (Note: The algorithm finds the closest time % point in data; this could give a slightly unevenly spaced % time array {default: 200} % 'padratio' = FFT-length/winframes (2^k) {default: 2} % Multiplies the number of output frequencies by dividing % their spacing (standard FFT padding). When cycles~=0, % frequency spacing is divided by padratio. % 'maxfreq' = Maximum frequency (Hz) to plot (& to output, if cycles>0) % If cycles==0, all FFT frequencies are output. {default: 50} % DEPRECATED, use 'freqs' instead,and never both. % 'freqs' = [min max] frequency limits. {default [minfreq 50], % minfreq being determined by the number of data points, % cycles and sampling frequency. % 'nfreqs' = number of output frequencies. For FFT, closest computed % frequency will be returned. Overwrite 'padratio' effects % for wavelets. {default: use 'padratio'} % 'freqscale' = ['log'|'linear'] frequency scale. {default: 'linear'} % Note that for obtaining 'log' spaced freqs using FFT, % closest correspondant frequencies in the 'linear' space % are returned. % 'verbose' = ['on'|'off'] print text {'on'} % 'subitc' = ['on'|'off'] subtract stimulus locked Inter-Trial Coherence % (ITC) from x and y. This computes an 'intrinsic' coherence % of x and y not arising directly from common phase locking % to experimental events. See notes. {default: 'off'} % 'wletmethod' = ['dftfilt'|'dftfilt2'|'dftfilt3'] Wavelet type to use. % 'dftfilt2' -> Morlet-variant wavelets, or Hanning DFT. % 'dftfilt3' -> Morlet wavelets. See the timefreq() function % for more detials {default: 'dftfilt3'} % 'cycleinc' ['linear'|'log'] mode of cycles increase when [min max] cycles % are provided in 'cycle' parameter. Applies only to % 'wletmethod','dftfilt' {default: 'linear'} % % Optional baseline parameters: % 'baseline' = Spectral baseline end-time (in ms). NaN --> no baseline is used. % A [min max] range may also be entered % You may also enter one row per region for baseline % e.g. [0 100; 300 400] considers the window 0 to 100 ms and % 300 to 400 ms This parameter validly defines all baseline types % below. Again, [NaN] Prevent baseline subtraction. % {default: 0 -> all negative time values}. % 'powbase' = Baseline spectrum to log-subtract {default|NaN -> from data} % 'commonbase' = ['on'|'off'] use common baseline when comparing two % conditions {default: 'on'}. % 'basenorm' = ['on'|'off'] 'on' normalize baseline in the power spectral % average; else 'off', divide by the average power across % trials at each frequency (gain model). {default: 'off'} % 'trialbase' = ['on'|'off'|'full'] perform baseline (normalization or division % above in single trial instead of the trial average. Default % if 'off'. 'full' is an option that perform single % trial normalization (or simple division based on the % 'basenorm' input over the full trial length before % performing standard baseline removal. It has been % shown to be less sensitive to noisy trials in Grandchamp R, % Delorme A. (2011) Single-trial normalization for event-related % spectral decomposition reduces sensitivity to noisy trials. % Front Psychol. 2:236. % % Optional time warping parameter: % 'timewarp' = [eventms matrix] Time-warp amplitude and phase time- % courses(following time/freq transform but before % smoothing across trials). 'eventms' is a matrix % of size (all_trials,epoch_events) whose columns % specify the epoch times (latencies) (in ms) at which % the same series of successive events occur in each % trial. If two data conditions, eventms should be % [eventms1;eventms2] --> all trials stacked vertically. % 'timewarpms' = [warpms] optional vector of event times (latencies) (in ms) % to which the series of events should be warped. % (Note: Epoch start and end should not be declared % as eventms or warpms}. If 'warpms' is absent or [], % the median of each 'eventms' column will be used; % If two datasets, the grand medians of the two are used. % 'timewarpidx' = [plotidx] is an vector of indices telling which of % the time-warped 'eventms' columns (above) to show with % vertical lines. If undefined, all columns are plotted. % Overwrites the 'vert' argument (below) if any. % % Optional permutation parameters: % 'alpha' = If non-0, compute two-tailed permutation significance % probability level. Show non-signif. output values % as green. {default: 0} % 'mcorrect' = ['none'|'fdr'] correction for multiple comparison % 'fdr' uses false detection rate (see function fdr()). % Not available for condition comparisons. {default:'none'} % 'pcontour' = ['on'|'off'] draw contour around significant regions % instead of masking them. Not available for condition % comparisons. {default:'off'} % 'naccu' = Number of permutation replications to accumulate {200} % 'baseboot' = permutation baseline subtract (1 -> use 'baseline'; % 0 -> use whole trial % [min max] -> use time range) % You may also enter one row per region for baseline, % e.g. [0 100; 300 400] considers the window 0 to 100 ms % and 300 to 400 ms. {default: 1} % 'boottype' = ['shuffle'|'rand'|'randall'] 'shuffle' -> shuffle times % and trials; 'rand' -> invert polarity of spectral data % (for ERSP) or randomize phase (for ITC); 'randall' -> % compute significances by accumulating random-polarity % inversions for each time/frequency point (slow!). Note % that in the previous revision of this function, this % method was called 'bootstrap' though it is actually % permutation {default: 'shuffle'} % 'condboot' = ['abs'|'angle'|'complex'] to compare two conditions, % either subtract ITC absolute values ('abs'), angles % ('angles'), or complex values ('complex'). {default: 'abs'} % 'pboot' = permutation power limits (e.g., from newtimef()) {def: from data} % 'rboot' = permutation ITC limits (e.g., from newtimef()). % Note: Both 'pboot' and 'rboot' must be provided to avoid % recomputing the surrogate data! {default: from data} % % Optional Scalp Map: % 'topovec' = Scalp topography (map) to plot {none} % 'elocs' = Electrode location file for scalp map {none} % Value should be a string array containing the path % and name of the file. For file format, see % >> topoplot example % 'chaninfo' Passed to topoplot, if called. % [struct] optional structure containing fields % 'nosedir', 'plotrad', and/or 'chantype'. See these % field definitions above, below. % {default: nosedir +X, plotrad 0.5, all channels} % % Optional Plotting Parameters: % 'scale' = ['log'|'abs'] visualize power in log scale (dB) or absolute % scale. {default: 'log'} % 'plottype' = ['image'|'curve'] plot time/frequency images or traces % (curves, one curve per frequency). {default: 'image'} % 'plotmean' = ['on'|'off'] For 'curve' plots only. Average all % frequencies given as input. {default: 'on'} % 'highlightmode' = ['background'|'bottom'] For 'curve' plots only, % display significant time regions either in the plot background % or under the curve. % 'plotersp' = ['on'|'off'] Plot power spectral perturbations {'on'} % 'plotitc' = ['on'|'off'] Plot inter-trial coherence {'on'} % 'plotphasesign' = ['on'|'off'] Plot phase sign in the inter trial coherence {'on'} % 'plotphaseonly' = ['on'|'off'] Plot ITC phase instead of ITC amplitude {'off'} % 'erspmax' = [real] set the ERSP max. For the color scale (min= -max) {auto} % 'itcmax' = [real] set the ITC image maximum for the color scale {auto} % 'hzdir' = ['up' or 'normal'|'down' or 'reverse'] Direction of % the frequency axes {default: as in icadefs.m, or 'up'} % 'ydir' = ['up' or 'normal'|'down' or 'reverse'] Direction of % the ERP axis plotted below the ITC {as in icadefs.m, or 'up'} % 'erplim' = [min max] ERP limits for ITC (below ITC image) {auto} % 'itcavglim' = [min max] average ITC limits for all freq. (left of ITC) {auto} % 'speclim' = [min max] average spectrum limits (left of ERSP image) {auto} % 'erspmarglim' = [min max] average marginal ERSP limits (below ERSP image) {auto} % 'title' = Optional figure or (brief) title {none}. For multiple conditions % this must contain a cell array of 2 or 3 title strings. % 'marktimes' = Non-0 times to mark with a dotted vertical line (ms) {none} % 'linewidth' = Line width for 'marktimes' traces (thick=2, thin=1) {2} % 'axesfont' = Axes text font size {10} % 'titlefont' = Title text font size {8} % 'vert' = [times_vector] -> plot vertical dashed lines at specified times % in ms. {default: none} % 'newfig' = ['on'|'off'] Create new figure for difference plots {'on'} % 'caption' = Caption of the figure {none} % 'outputformat' = ['old'|'plot'] for compatibility with script that used the % old output format, set to 'old' (mbase in absolute amplitude (not % dB) and real itc instead of complex itc). 'plot' returns % the plotted result {default: 'plot'} % Outputs: % ersp = (nfreqs,timesout) matrix of log spectral diffs from baseline % (in dB log scale or absolute scale). Use the 'plot' output format % above to output the ERSP as shown on the plot. % itc = (nfreqs,timesout) matrix of complex inter-trial coherencies. % itc is complex -- ITC magnitude is abs(itc); ITC phase in radians % is angle(itc), or in deg phase(itc)*180/pi. % powbase = baseline power spectrum. Note that even, when selecting the % the 'trialbase' option, the average power spectrum is % returned (not trial based). To obtain the baseline of % each trial, recompute it manually using the tfdata % output described below. % times = vector of output times (spectral time window centers) (in ms). % freqs = vector of frequency bin centers (in Hz). % erspboot = (nfreqs,2) matrix of [lower upper] ERSP significance. % itcboot = (nfreqs) matrix of [upper] abs(itc) threshold. % tfdata = optional (nfreqs,timesout,trials) time/frequency decomposition % of the single data trials. Values are complex. % % Plot description: % Assuming both 'plotersp' and 'plotitc' options are 'on' (= default). % The upper panel presents the data ERSP (Event-Related Spectral Perturbation) % in dB, with mean baseline spectral activity (in dB) subtracted. Use % "'baseline', NaN" to prevent timef() from removing the baseline. % The lower panel presents the data ITC (Inter-Trial Coherence). % Click on any plot axes to pop up a new window (using 'axcopy()') % -- Upper left marginal panel presents the mean spectrum during the baseline % period (blue), and when significance is set, the significance threshold % at each frequency (dotted green-black trace). % -- The marginal panel under the ERSP image shows the maximum (green) and % minimum (blue) ERSP values relative to baseline power at each frequency. % -- The lower left marginal panel shows mean ITC across the imaged time range % (blue), and when significance is set, the significance threshold (dotted % green-black). % -- The marginal panel under the ITC image shows the ERP (which is produced by % ITC across the data spectral pass band). % % Authors: Arnaud Delorme, Jean Hausser from timef() by Sigurd Enghoff, Scott Makeig % CNL / Salk Institute 1998- | SCCN/INC, UCSD 2002- % % See also: timefreq(), condstat(), newcrossf(), tftopo() % Deprecated Multitaper Parameters: [not included here] % 'mtaper' = If [N W], performs multitaper decomposition. % (N is the time resolution and W the frequency resolution; % maximum taper number is 2NW-1). Overwrites 'winsize' and 'padratio'. % If [N W K], forces the use of K Slepian tapers (if possible). % Phase is calculated using standard methods. % The use of mutitaper with wavelets (cycles>0) is not % recommended (as multiwavelets are not implemented). % Uses Matlab functions DPSS, PMTM. {no multitaper} % Deprecated time warp keywords (working?) % 'timewarpfr' = {{[events], [warpfr], [plotidx]}} Time warp amplitude and phase % time-courses (after time/freq transform but before smoothingtimefreqfunc % across trials). 'events' is a matrix whose columns specify the % epoch frames [1 ... end] at which a series of successive events % occur in each trial. 'warpfr' is an optional vector of event % frames to which the series of events should be time locked. % (Note: Epoch start and end should not be declared as events or % warpfr}. If 'warpfr' is absent or [], the median of each 'events' % column will be used. [plotidx] is an optional vector of indices % telling which of the warpfr to plot with vertical lines. If % undefined, all marks are plotted. Overwrites 'vert' argument, % if any. [Note: In future releases, 'timewarpfr' will be deprecated % in favor of 'timewarp' using latencies in ms instead of frames]. % Deprecated original time warp keywords (working?) % 'timeStretchMarks' = [(marks,trials) matrix] Each trial data will be % linearly warped (after time/freq. transform) so that the % event marks are time locked to the reference frames % (see timeStretchRefs). Marks must be specified in frames % 'timeStretchRefs' = [1 x marks] Common reference frames to all trials. % If empty or undefined, median latency for each mark will be used.boottype % 'timeStretchPlot' = [vector] Indicates the indices of the reference frames % (in StretchRefs) should be overplotted on the ERSP and ITC. % % % Copyright (C) University of California San Diego, La Jolla, CA % % First built as timef.m at CNL / Salk Institute 8/1/98-8/28/01 by % Sigurd Enghoff and Scott Makeig, edited by Arnaud Delorme % SCCN/INC/UCSD/ reprogrammed as newtimef -Arnaud Delorme 2002- % SCCN/INC/UCSD/ added time warping capabilities -Jean Hausser 2005 % % 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 % 10-19-98 avoided division by zero (using MIN_ABS) -sm % 10-19-98 improved usage message and commandline info printing -sm % 10-19-98 made valid [] values for tvec and g.elocs -sm % 04-01-99 added missing freq in freqs and plots, fixed log scaling bug -se && -tpj % 06-29-99 fixed frequency indexing for constant-Q -se % 08-24-99 reworked to handle NaN input values -sm % 12-07-99 adjusted ERPtimes to plot ERP under ITC -sm % 12-22-99 debugged ERPtimes, added BASE_BOOT -sm % 01-10-00 debugged BASE_BOOT=0 -sm % 02-28-00 added NOTE on formula derivation below -sm % 03-16-00 added axcopy() feature -sm && tpj % 04-16-00 added multiple marktimes loop -sm % 04-20-00 fixed ITC cbar limits when spcified in input -sm % 07-29-00 changed frequencies displayed msg -sm % 10-12-00 fixed bug in freqs when cycles>0 -sm % 02-07-01 fixed inconsistency in BASE_BOOT use -sm % 08-28-01 matlab 'key' value arguments -ad % 08-28-01 multitaper decomposition -ad % 01-25-02 reformated help && license -ad % 03-08-02 debug && compare to old timef function -ad % 03-16-02 timeout automatically adjusted if too high -ad % 04-02-02 added 'coher' option -ad function [P,R,mbase,timesout,freqs,Pboot,Rboot,alltfX,PA] = newtimef( data, frames, tlimits, Fs, varwin, varargin); % Note: Above, PA is output of 'phsamp','on' % For future 'timewarp' keyword help: 'timewarp' 3rd element {colors} contains a % list of Matlab linestyles to use for vertical lines marking the occurence % of the time warped events. If '', no line will be drawn for this event % column. If fewer colors than event columns, cycles through the given color % labels. Note: Not compatible with 'vert' (below). %varwin,winsize,g.timesout,g.padratio,g.maxfreq,g.topovec,g.elocs,g.alpha,g.marktimes,g.powbase,g.pboot,g.rboot) % ITC: Normally, R = |Sum(Pxy)| / (Sum(|Pxx|)*Sum(|Pyy|)) is coherence. % But here, we consider Phase(Pyy) = 0 and |Pyy| = 1 -> Pxy = Pxx % Giving, R = |Sum(Pxx)|/Sum(|Pxx|), the inter-trial coherence (ITC) % Also called 'phase-locking factor' by Tallon-Baudry et al. (1996) if nargin < 1 help newtimef; return; end; % Read system (or directory) constants and preferences: % ------------------------------------------------------ icadefs % read local EEGLAB constants: HZDIR, YDIR, DEFAULT_SRATE, DEFAULT_TIMLIM if ~exist('HZDIR'), HZDIR = 'up'; end; % ascending freqs if ~exist('YDIR'), YDIR = 'up'; end; % positive up if YDIR == 1, YDIR = 'up'; end; % convert from [-1|1] as set in icadefs.m if YDIR == -1, YDIR = 'down'; end; % and read by other plotting functions if ~exist('DEFAULT_SRATE'), DEFAULT_SRATE = 250; end; % 250 Hz if ~exist('DEFAULT_TIMLIM'), DEFAULT_TIMLIM = [-1000 2000]; end; % [-1 2] s epochs % Constants set here: % ------------------ ERSP_CAXIS_LIMIT = 0; % 0 -> use data limits; else positive value % giving symmetric +/- caxis limits. ITC_CAXIS_LIMIT = 0; % 0 -> use data limits; else positive value % giving symmetric +/- caxis limits. MIN_ABS = 1e-8; % avoid division by ~zero % Command line argument defaults: % ------------------------------ DEFAULT_NWIN = 200; % Number of windows = horizontal resolution DEFAULT_VARWIN = 0; % Fixed window length or fixed number of cycles. % =0: fix window length to that determined by nwin % >0: set window length equal to varwin cycles % Bounded above by winsize, which determines % the min. freq. to be computed. DEFAULT_OVERSMP = 2; % Number of times to oversample frequencies DEFAULT_MAXFREQ = 50; % Maximum frequency to display (Hz) DEFAULT_TITLE = ''; % Figure title (no default) DEFAULT_ELOC = 'chan.locs'; % Channel location file DEFAULT_ALPHA = NaN; % Percentile of bins to keep DEFAULT_MARKTIME= NaN; % Font sizes: AXES_FONT = 10; % axes text FontSize TITLE_FONT = 8; if (nargin < 2) frames = floor((DEFAULT_TIMLIN(2)-DEFAULT_TIMLIM(1))/DEFAULT_SRATE); elseif (~isnumeric(frames) | length(frames)~=1 | frames~=round(frames)) error('Value of frames must be an integer.'); elseif (frames <= 0) error('Value of frames must be positive.'); end; DEFAULT_WINSIZE = max(pow2(nextpow2(frames)-3),4); DEFAULT_PAD = max(pow2(nextpow2(DEFAULT_WINSIZE)),4); if (nargin < 1) help newtimef return end if isstr(data) && strcmp(data,'details') more on help timefdetails more off return end if ~iscell(data) data = reshape_data(data, frames); trials = size(data,ndims(data)); else if ndims(data) == 3 && size(data,1) == 1 error('Cannot process multiple channel component in compare mode'); end; [data{1}, frames] = reshape_data(data{1}, frames); [data{2}, frames] = reshape_data(data{2}, frames); trials = size(data{1},2); end; if (nargin < 3) tlimits = DEFAULT_TIMLIM; elseif (~isnumeric(tlimits) | sum(size(tlimits))~=3) error('Value of tlimits must be a vector containing two numbers.'); elseif (tlimits(1) >= tlimits(2)) error('tlimits interval must be ascending.'); end if (nargin < 4) Fs = DEFAULT_SRATE; elseif (~isnumeric(Fs) | length(Fs)~=1) error('Value of srate must be a number.'); elseif (Fs <= 0) error('Value of srate must be positive.'); end if (nargin < 5) varwin = DEFAULT_VARWIN; elseif ~isnumeric(varwin) && strcmpi(varwin, 'cycles') varwin = varargin{1}; varargin(1) = []; elseif (varwin < 0) error('Value of cycles must be zero or positive.'); end % build a structure for keyword arguments % -------------------------------------- if ~isempty(varargin) [tmp indices] = unique_bc(varargin(1:2:end)); varargin = varargin(sort(union(indices*2-1, indices*2))); % these 2 lines remove duplicate arguments try, g = struct(varargin{:}); catch, error('Argument error in the {''param'', value} sequence'); end; end %} [ g timefreqopts ] = finputcheck(varargin, ... {'boottype' 'string' {'shuffle','rand','randall'} 'shuffle'; ... 'condboot' 'string' {'abs','angle','complex'} 'abs'; ... 'title' { 'string','cell' } { [] [] } DEFAULT_TITLE; ... 'title2' 'string' [] DEFAULT_TITLE; ... 'winsize' 'integer' [0 Inf] DEFAULT_WINSIZE; ... 'pad' 'real' [] DEFAULT_PAD; ... 'timesout' 'integer' [] DEFAULT_NWIN; ... 'padratio' 'integer' [0 Inf] DEFAULT_OVERSMP; ... 'topovec' 'real' [] []; ... 'elocs' {'string','struct'} [] DEFAULT_ELOC; ... 'alpha' 'real' [0 0.5] DEFAULT_ALPHA; ... 'marktimes' 'real' [] DEFAULT_MARKTIME; ... 'powbase' 'real' [] NaN; ... 'pboot' 'real' [] NaN; ... 'rboot' 'real' [] NaN; ... 'plotersp' 'string' {'on','off'} 'on'; ... 'plotamp' 'string' {'on','off'} 'on'; ... 'plotitc' 'string' {'on','off'} 'on'; ... 'detrend' 'string' {'on','off'} 'off'; ... 'rmerp' 'string' {'on','off'} 'off'; ... 'basenorm' 'string' {'on','off'} 'off'; ... 'commonbase' 'string' {'on','off'} 'on'; ... 'baseline' 'real' [] 0; ... 'baseboot' 'real' [] 1; ... 'linewidth' 'integer' [1 2] 2; ... 'naccu' 'integer' [1 Inf] 200; ... 'mtaper' 'real' [] []; ... 'maxfreq' 'real' [0 Inf] DEFAULT_MAXFREQ; ... 'freqs' 'real' [0 Inf] [0 DEFAULT_MAXFREQ]; ... 'cycles' 'integer' [] []; ... 'nfreqs' 'integer' [] []; ... 'freqscale' 'string' [] 'linear'; ... 'vert' 'real' [] []; ... 'newfig' 'string' {'on','off'} 'on'; ... 'type' 'string' {'coher','phasecoher','phasecoher2'} 'phasecoher'; ... 'itctype' 'string' {'coher','phasecoher','phasecoher2'} 'phasecoher'; ... 'phsamp' 'string' {'on','off'} 'off'; ... % phsamp not completed - Toby 9.28.2006 'plotphaseonly' 'string' {'on','off'} 'off'; ... 'plotphasesign' 'string' {'on','off'} 'on'; ... 'plotphase' 'string' {'on','off'} 'on'; ... % same as above for backward compatibility 'pcontour' 'string' {'on','off'} 'off'; ... 'outputformat' 'string' {'old','new','plot' } 'plot'; ... 'itcmax' 'real' [] []; ... 'erspmax' 'real' [] []; ... 'lowmem' 'string' {'on','off'} 'off'; ... 'verbose' 'string' {'on','off'} 'on'; ... 'plottype' 'string' {'image','curve'} 'image'; ... 'mcorrect' 'string' {'fdr','none'} 'none'; ... 'plotmean' 'string' {'on','off'} 'on'; ... 'plotmode' 'string' {} ''; ... % for metaplottopo 'highlightmode' 'string' {'background','bottom'} 'background'; ... 'chaninfo' 'struct' [] struct([]); ... 'erspmarglim' 'real' [] []; ... 'itcavglim' 'real' [] []; ... 'erplim' 'real' [] []; ... 'speclim' 'real' [] []; ... 'ntimesout' 'real' [] []; ... 'scale' 'string' { 'log','abs'} 'log'; ... 'timewarp' 'real' [] []; ... 'precomputed' 'struct' [] struct([]); ... 'timewarpms' 'real' [] []; ... 'timewarpfr' 'real' [] []; ... 'timewarpidx' 'real' [] []; ... 'timewarpidx' 'real' [] []; ... 'timeStretchMarks' 'real' [] []; ... 'timeStretchRefs' 'real' [] []; ... 'timeStretchPlot' 'real' [] []; ... 'trialbase' 'string' {'on','off','full'} 'off'; 'caption' 'string' [] ''; ... 'hzdir' 'string' {'up','down','normal','reverse'} HZDIR; ... 'ydir' 'string' {'up','down','normal','reverse'} YDIR; ... 'cycleinc' 'string' {'linear','log'} 'linear' }, 'newtimef', 'ignore'); if isstr(g), error(g); end; if strcmpi(g.plotamp, 'off'), g.plotersp = 'off'; end; if strcmpi(g.basenorm, 'on'), g.scale = 'abs'; end; if ~strcmpi(g.itctype , 'phasecoher'), g.type = g.itctype; end; g.tlimits = tlimits; g.frames = frames; g.srate = Fs; if isempty(g.cycles) g.cycles = varwin; end; g.AXES_FONT = AXES_FONT; % axes text FontSize g.TITLE_FONT = TITLE_FONT; g.ERSP_CAXIS_LIMIT = ERSP_CAXIS_LIMIT; g.ITC_CAXIS_LIMIT = ITC_CAXIS_LIMIT; if ~strcmpi(g.plotphase, 'on'), g.plotphasesign = g.plotphase; end; % unpack 'timewarp' (and undocumented 'timewarpfr') arguments %------------------------------------------------------------ if isfield(g,'timewarpfr') if iscell(g.timewarpfr) && length(g.timewarpfr) > 3 error('undocumented ''timewarpfr'' cell array may have at most 3 elements'); end end if ~isempty(g.nfreqs) verboseprintf(g.verbose, 'Warning: ''nfreqs'' input overwrite ''padratio''\n'); end; if strcmpi(g.basenorm, 'on') verboseprintf(g.verbose, 'Baseline normalization is on (results will be shown as z-scores)\n'); end; if isfield(g,'timewarp') && ~isempty(g.timewarp) if ndims(data) == 3 error('Cannot perform time warping on 3-D data input'); end; if ~isempty(g.timewarp) % convert timewarp ms to timewarpfr frames -sm fprintf('\n') if iscell(g.timewarp) error('timewarp argument must be a (total_trials,epoch_events) matrix'); end evntms = g.timewarp; warpfr = round((evntms - g.tlimits(1))/1000*g.srate)+1; g.timewarpfr{1} = warpfr'; if isfield(g,'timewarpms') refms = g.timewarpms; reffr = round((refms - g.tlimits(1))/1000*g.srate)+1; g.timewarpfr{2} = reffr'; end if isfield(g,'timewarpidx') g.timewarpfr{3} = g.timewarpidx; end end % convert again to timeStretch parameters % --------------------------------------- if ~isempty(g.timewarpfr) g.timeStretchMarks = g.timewarpfr{1}; if length(g.timewarpfr) > 1 g.timeStretchRefs = g.timewarpfr{2}; end if length(g.timewarpfr) > 2 if isempty(g.timewarpfr{3}) stretchevents = size(g.timeStretchMarks,1); g.timeStretchPlot = [1:stretchevents]; % default to plotting all lines else g.timeStretchPlot = g.timewarpfr{3}; end end if max(max(g.timeStretchMarks)) > frames-2 | min(min(g.timeStretchMarks)) < 3 error('Time warping events must be inside the epochs.'); end if ~isempty(g.timeStretchRefs) if max(g.timeStretchRefs) > frames-2 | min(g.timeStretchRefs) < 3 error('Time warping reference latencies must be within the epochs.'); end end end end % Determining source of the call % --------------------------------------% 'guicall'= 1 if newtimef is called callerstr = dbstack(1); % from EEGLAB GUI, otherwise 'guicall'= 0 if isempty(callerstr) % 7/3/2014, Ramon guicall = 0; elseif strcmp(callerstr(end).name,'pop_newtimef') guicall = 1; else guicall = 0; end % test argument consistency % -------------------------- if g.tlimits(2)-g.tlimits(1) < 30 verboseprintf(g.verbose, 'newtimef(): WARNING: Specified time range is very small (< 30 ms)???\n'); verboseprintf(g.verbose, ' Epoch time limits should be in msec, not seconds!\n'); end if (g.winsize > g.frames) error('Value of winsize must be smaller than epoch frames.'); end if length(g.timesout) == 1 && g.timesout > 0 if g.timesout > g.frames-g.winsize g.timesout = g.frames-g.winsize; disp(['Value of timesout must be <= frames-winsize, timeout adjusted to ' int2str(g.timesout) ]); end end; if (pow2(nextpow2(g.padratio)) ~= g.padratio) error('Value of padratio must be an integer power of two [1,2,4,8,16,...]'); end if (g.maxfreq > Fs/2) verboseprintf(g.verbose, ['Warning: value of maxfreq reduced to Nyquist rate' ... ' (%3.2f)\n\n'], Fs/2); g.maxfreq = Fs/2; end if g.maxfreq ~= DEFAULT_MAXFREQ, g.freqs(2) = g.maxfreq; end; if isempty(g.topovec) g.topovec = []; if isempty(g.elocs) error('Channel location file must be specified.'); end; end if (round(g.naccu*g.alpha) < 2) verboseprintf(g.verbose, 'Value of alpha is outside its normal range [%g,0.5]\n',2/g.naccu); g.naccu = round(2/g.alpha); verboseprintf(g.verbose, ' Increasing the number of iterations to %d\n',g.naccu); end if ~isnan(g.alpha) if length(g.baseboot) == 2 verboseprintf(g.verbose, 'Permutation analysis will use data from %3.2g to %3.2g ms.\n', ... g.baseboot(1), g.baseboot(2)) elseif g.baseboot > 0 verboseprintf(g.verbose, 'Permutation analysis will use data in (pre-0) baseline subwindows only.\n') else verboseprintf(g.verbose, 'Permutation analysis will use data in all subwindows.\n') end end if ~isempty(g.timeStretchMarks) % timeStretch code by Jean Hauser if isempty(g.timeStretchRefs) verboseprintf(g.verbose, ['Using median event latencies as reference event times for time warping.\n']); g.timeStretchRefs = median(g.timeStretchMarks,2); % Note: Uses (grand) median latencies for two conditions else verboseprintf(g.verbose, ['Using supplied latencies as reference event times for time warping.\n']); end if isempty(g.timeStretchPlot) verboseprintf(g.verbose, 'Will not overplot the reference event times on the ERSP.\n'); elseif length(g.timeStretchPlot) > 0 g.vert = ((g.timeStretchRefs(g.timeStretchPlot)-1) ... /g.srate+g.tlimits(1)/1000)*1000; fprintf('Plotting timewarp markers at ') for li = 1:length(g.vert), fprintf('%d ',g.vert(li)); end fprintf(' ms.\n') end end if min(g.vert) < g.tlimits(1) | max(g.vert) > g.tlimits(2) error('vertical line (''vert'') latency outside of epoch boundaries'); end if strcmp(g.hzdir,'up')| strcmp(g.hzdir,'normal') g.hzdir = 'normal'; % convert to Matlab graphics constants elseif strcmp(g.hzdir,'down') | strcmp(g.hzdir,'reverse')| g.hzdir==-1 g.hzdir = 'reverse'; else error('unknown ''hzdir'' argument'); end if strcmp(g.ydir,'up')| strcmp(g.ydir,'normal') g.ydir = 'normal'; % convert to Matlab graphics constants elseif strcmp(g.ydir,'down') | strcmp(g.ydir,'reverse') g.ydir = 'reverse'; else error('unknown ''ydir'' argument'); end % ----------------- % ERSP scaling unit % ----------------- if strcmpi(g.scale, 'log') if strcmpi(g.basenorm, 'on') g.unitpower = '10*log(std.)'; % impossible elseif isnan(g.baseline) g.unitpower = '10*log10(\muV^{2}/Hz)'; else g.unitpower = 'dB'; end; else if strcmpi(g.basenorm, 'on') g.unitpower = 'std.'; elseif isnan(g.baseline) g.unitpower = '\muV^{2}/Hz'; else g.unitpower = '% of baseline'; end; end; % Multitaper - used in timef % -------------------------- if ~isempty(g.mtaper) % multitaper, inspired from a Bijan Pesaran matlab function if length(g.mtaper) < 3 %error('mtaper arguement must be [N W] or [N W K]'); if g.mtaper(1) * g.mtaper(2) < 1 error('mtaper 2 first arguments'' product must be larger than 1'); end; if length(g.mtaper) == 2 g.mtaper(3) = floor( 2*g.mtaper(2)*g.mtaper(1) - 1); end if length(g.mtaper) == 3 if g.mtaper(3) > 2 * g.mtaper(1) * g.mtaper(2) -1 error('mtaper number too high (maximum (2*N*W-1))'); end; end disp(['Using ' num2str(g.mtaper(3)) ' tapers.']); NW = g.mtaper(1)*g.mtaper(2); % product NW N = g.mtaper(1)*g.srate; [e,v] = dpss(N, NW, 'calc'); e=e(:,1:g.mtaper(3)); g.alltapers = e; else g.alltapers = g.mtaper; disp('mtaper argument not [N W] or [N W K]; considering raw taper matrix'); end; g.winsize = size(g.alltapers, 1); g.pad = max(pow2(nextpow2(g.winsize)),256); % pad*nextpow nfk = floor([0 g.maxfreq]./g.srate.*g.pad); g.padratio = 2*nfk(2)/g.winsize; %compute number of frequencies %nf = max(256, g.pad*2^nextpow2(g.winsize+1)); %nfk = floor([0 g.maxfreq]./g.srate.*nf); %freqs = linspace( 0, g.maxfreq, diff(nfk)); % this also works in the case of a FFT end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute frequency by frequency if low memory %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmpi(g.lowmem, 'on') && numel(data) ~= g.frames && isempty(g.nfreqs) && ~iscell(data) disp('Lowmem is a deprecated option that is not functional any more'); return; % NOTE: the code below is functional but the graphical output is % different when the 'lowmem' option is used compared to when it is not % used - AD, 29 April 2011 % compute for first 2 trials to get freqsout XX = reshape(data, 1, frames, prod(size(data))/g.frames); [P,R,mbase,timesout,freqsout] = newtimef(XX(1,:,1), frames, tlimits, Fs, g.cycles, 'plotitc', 'off', 'plotamp', 'off',varargin{:}, 'lowmem', 'off'); % scan all frequencies for index = 1:length(freqsout) if nargout < 8 [P(index,:),R(index,:),mbase(index),timesout,tmpfreqs(index),Pboottmp,Rboottmp] = ... newtimef(data, frames, tlimits, Fs, g.cycles, ... 'freqs', [freqsout(index) freqsout(index)], 'nfreqs', 1, ... 'plotamp', 'off', 'plotitc', 'off', 'plotphasesign', 'off',varargin{:}, ... 'lowmem', 'off', 'timesout', timesout); if ~isempty(Pboottmp) Pboot(index,:) = Pboottmp; Rboot(index,:) = Rboottmp; else Pboot = []; Rboot = []; end; else [P(index,:),R(index,:),mbase(index),timesout,tmpfreqs(index),Pboot(index,:),Rboot(index,:), ... alltfX(index,:,:)] = ... newtimef(data, frames, tlimits, Fs, g.cycles, ... 'freqs', [freqsout(index) freqsout(index)], 'nfreqs', 1, ... 'plotamp', 'off', 'plotphasesign', 'off',varargin{:}, ... 'lowmem', 'off', 'timesout', timesout); end; end; % compute trial-average ERP % ------------------------- ERP = mean(data,2); % plot results %------------- plottimef(P, R, Pboot, Rboot, ERP, freqsout, timesout, mbase, [], [], g); return; % finished end; %%%%%%%%%%%%%%%%%%%%%%% % compare 2 conditions %%%%%%%%%%%%%%%%%%%%%%% if iscell(data) if ~guicall && (strcmp(g.basenorm, 'on') || strcmp(g.trialbase, 'on')) % ------------------------------------- Temporary fix for error when using error('EEGLAB error: basenorm and/or trialbase options cannot be used when processing 2 conditions'); % basenorm or trialbase with two conditions end; Pboot = []; Rboot = []; if ~strcmpi(g.mcorrect, 'none') error('Correction for multiple comparison not implemented for comparing conditions'); end; vararginori = varargin; if length(data) ~= 2 error('newtimef: to compare two conditions, data must be a length-2 cell array'); end; % deal with titles % ---------------- for index = 1:2:length(vararginori) if index<=length(vararginori) % needed if elements are deleted % if strcmp(vararginori{index}, 'title') | ... % Added by Jean Hauser % strcmp(vararginori{index}, 'title2') | ... if strcmp(vararginori{index}, 'timeStretchMarks') | ... strcmp(vararginori{index}, 'timeStretchRefs') | ... strcmp(vararginori{index}, 'timeStretchPlots') vararginori(index:index+1) = []; end; end; end; if iscell(g.title) && length(g.title) >= 2 % Changed that part because providing titles % as cells caused the function to crash (why?) % at line 704 (g.tlimits = tlimits) -Jean if length(g.title) == 2, g.title{3} = [ g.title{1} ' - ' g.title{2} ]; end; else disp('Warning: title must be a cell array'); g.title = { 'Condition 1' 'Condition 2' 'Condition 1 minus Condition 2' }; end; verboseprintf(g.verbose, '\nRunning newtimef() on Condition 1 **********************\n\n'); verboseprintf(g.verbose, 'Note: If an out-of-memory error occurs, try reducing the\n'); verboseprintf(g.verbose, ' the number of time points or number of frequencies\n'); verboseprintf(g.verbose, '(''coher'' options take 3 times the memory of other options)\n\n'); cond_1_epochs = size(data{1},2); if ~isempty(g.timeStretchMarks) [P1,R1,mbase1,timesout,freqs,Pboot1,Rboot1,alltfX1] = ... newtimef( data{1}, frames, tlimits, Fs, g.cycles, 'plotitc', 'off', ... 'plotersp', 'off', vararginori{:}, 'lowmem', 'off', ... 'timeStretchMarks', g.timeStretchMarks(:,1:cond_1_epochs), ... 'timeStretchRefs', g.timeStretchRefs); else [P1,R1,mbase1,timesout,freqs,Pboot1,Rboot1,alltfX1] = ... newtimef( data{1}, frames, tlimits, Fs, g.cycles, 'plotitc', 'off', ... 'plotersp', 'off', vararginori{:}, 'lowmem', 'off'); end verboseprintf(g.verbose,'\nRunning newtimef() on Condition 2 **********************\n\n'); [P2,R2,mbase2,timesout,freqs,Pboot2,Rboot2,alltfX2] = ... newtimef( data{2}, frames, tlimits, Fs, g.cycles, 'plotitc', 'off', ... 'plotersp', 'off', vararginori{:}, 'lowmem', 'off', ... 'timeStretchMarks', g.timeStretchMarks(:,cond_1_epochs+1:end), ... 'timeStretchRefs', g.timeStretchRefs); verboseprintf(g.verbose,'\nComputing difference **********************\n\n'); % recompute power baselines % ------------------------- if ~isnan( g.baseline(1) ) && ~isnan( mbase1(1) ) && isnan(g.powbase(1)) && strcmpi(g.commonbase, 'on') disp('Recomputing baseline power: using the grand mean of both conditions ...'); mbase = (mbase1 + mbase2)/2; P1 = P1 + repmat(mbase1(1:size(P1,1))',[1 size(P1,2)]); P2 = P2 + repmat(mbase2(1:size(P1,1))',[1 size(P1,2)]); P1 = P1 - repmat(mbase (1:size(P1,1))',[1 size(P1,2)]); P2 = P2 - repmat(mbase (1:size(P1,1))',[1 size(P1,2)]); if ~isnan(g.alpha) Pboot1 = Pboot1 + repmat(mbase1(1:size(Pboot1,1))',[1 size(Pboot1,2) size(Pboot1,3)]); Pboot2 = Pboot2 + repmat(mbase2(1:size(Pboot1,1))',[1 size(Pboot1,2) size(Pboot1,3)]); Pboot1 = Pboot1 - repmat(mbase (1:size(Pboot1,1))',[1 size(Pboot1,2) size(Pboot1,3)]); Pboot2 = Pboot2 - repmat(mbase (1:size(Pboot1,1))',[1 size(Pboot1,2) size(Pboot1,3)]); end; verboseprintf(g.verbose, '\nSubtracting the common power baseline ...\n'); meanmbase = mbase; mbase = { mbase mbase }; elseif strcmpi(g.commonbase, 'on') mbase = { NaN NaN }; meanmbase = mbase{1}; %Ramon :for bug 1657 else meanmbase = (mbase1 + mbase2)/2; mbase = { mbase1 mbase2 }; end; % plotting % -------- if strcmpi(g.plotersp, 'on') | strcmpi(g.plotitc, 'on') g.titleall = g.title; if strcmpi(g.newfig, 'on'), figure; end; % declare a new figure % using same color scale % ---------------------- if ~isfield(g, 'erspmax') g.erspmax = max( max(max(abs(Pboot1))), max(max(abs(Pboot2))) ); end; if ~isfield(g, 'itcmax') g.itcmax = max( max(max(abs(Rboot1))), max(max(abs(Rboot2))) ); end; subplot(1,3,1); % plot Condition 1 g.title = g.titleall{1}; g = plottimef(P1, R1, Pboot1, Rboot1, mean(data{1},2), freqs, timesout, mbase{1}, [], [], g); g.itcavglim = []; subplot(1,3,2); % plot Condition 2 g.title = g.titleall{2}; plottimef(P2, R2, Pboot2, Rboot2, mean(data{2},2), freqs, timesout, mbase{2}, [], [], g); subplot(1,3,3); % plot Condition 1 - Condition 2 g.title = g.titleall{3}; end; if isnan(g.alpha) switch(g.condboot) case 'abs', Rdiff = abs(R1)-abs(R2); case 'angle', Rdiff = angle(R1)-angle(R2); case 'complex', Rdiff = R1-R2; end; if strcmpi(g.plotersp, 'on') | strcmpi(g.plotitc, 'on') g.erspmax = []; g.itcmax = []; % auto scale inserted for diff plottimef(P1-P2, Rdiff, [], [], mean(data{1},2)-mean(data{2},2), freqs, timesout, meanmbase, [], [], g); end; else % preprocess data and run compstat() function % ------------------------------------------- alltfX1power = alltfX1.*conj(alltfX1); alltfX2power = alltfX2.*conj(alltfX2); if ~isnan(mbase{1}(1)) mbase1 = 10.^(mbase{1}(1:size(alltfX1,1))'/20); mbase2 = 10.^(mbase{2}(1:size(alltfX1,1))'/20); alltfX1 = alltfX1./repmat(mbase1/2,[1 size(alltfX1,2) size(alltfX1,3)]); alltfX2 = alltfX2./repmat(mbase2/2,[1 size(alltfX2,2) size(alltfX2,3)]); alltfX1power = alltfX1power./repmat(mbase1,[1 size(alltfX1power,2) size(alltfX1power,3)]); alltfX2power = alltfX2power./repmat(mbase2,[1 size(alltfX2power,2) size(alltfX2power,3)]); end; %formula = {'log10(mean(arg1,3))'}; % toby 10.02.2006 %formula = {'log10(mean(arg1(:,:,data),3))'}; formula = {'log10(mean(arg1(:,:,X),3))'}; switch g.type case 'coher', % take the square of alltfx and alltfy first to speed up formula = { formula{1} ['sum(arg2(:,:,data),3)./sqrt(sum(arg1(:,:,data),3)*length(data) )'] }; if strcmpi(g.lowmem, 'on') for ind = 1:2:size(alltfX1power,1) if ind == size(alltfX1,1), indarr = ind; else indarr = [ind:ind+1]; end; [resdifftmp resimagestmp res1tmp res2tmp] = ... condstat(formula, g.naccu, g.alpha, {'both' 'upper'}, { '' g.condboot}, ... { alltfX1power(indarr,:,:) alltfX2power(indarr,:,:) }, {alltfX1(indarr,:,:) alltfX2(indarr,:,:)}); resdiff{1}(indarr,:) = resdifftmp{1}; resdiff{2}(indarr,:) = resdifftmp{2}; resimages{1}(indarr,:,:) = resimagestmp{1}; resimages{2}(indarr,:,:) = resimagestmp{2}; res1{1}(indarr,:) = res1tmp{1}; res1{2}(indarr,:) = res1tmp{2}; res2{1}(indarr,:) = res2tmp{1}; res2{2}(indarr,:) = res2tmp{2}; end; else alltfXpower = { alltfX1power alltfX2power }; alltfX = { alltfX1 alltfX2 }; alltfXabs = { alltfX1abs alltfX2abs }; [resdiff resimages res1 res2] = condstat(formula, g.naccu, g.alpha, {'both' 'upper'}, { '' g.condboot}, alltfXpower, alltfX, alltfXabs); end; case 'phasecoher2', % normalize first to speed up %formula = { formula{1} ['sum(arg2(:,:,data),3)./sum(arg3(:,:,data),3)'] }; % toby 10/3/2006 formula = { formula{1} ['sum(arg2(:,:,X),3)./sum(arg3(:,:,X),3)'] }; alltfX1abs = sqrt(alltfX1power); % these 2 lines can be suppressed alltfX2abs = sqrt(alltfX2power); % by inserting sqrt(arg1(:,:,data)) instead of arg3(:,:,data)) if strcmpi(g.lowmem, 'on') for ind = 1:2:size(alltfX1abs,1) if ind == size(alltfX1,1), indarr = ind; else indarr = [ind:ind+1]; end; [resdifftmp resimagestmp res1tmp res2tmp] = ... condstat(formula, g.naccu, g.alpha, {'both' 'upper'}, { '' g.condboot}, ... { alltfX1power(indarr,:,:) alltfX2power(indarr,:,:) }, {alltfX1(indarr,:,:) ... alltfX2(indarr,:,:)}, { alltfX1abs(indarr,:,:) alltfX2abs(indarr,:,:) }); resdiff{1}(indarr,:) = resdifftmp{1}; resdiff{2}(indarr,:) = resdifftmp{2}; resimages{1}(indarr,:,:) = resimagestmp{1}; resimages{2}(indarr,:,:) = resimagestmp{2}; res1{1}(indarr,:) = res1tmp{1}; res1{2}(indarr,:) = res1tmp{2}; res2{1}(indarr,:) = res2tmp{1}; res2{2}(indarr,:) = res2tmp{2}; end; else alltfXpower = { alltfX1power alltfX2power }; alltfX = { alltfX1 alltfX2 }; alltfXabs = { alltfX1abs alltfX2abs }; [resdiff resimages res1 res2] = condstat(formula, g.naccu, g.alpha, {'both' 'upper'}, { '' g.condboot}, alltfXpower, alltfX, alltfXabs); end; case 'phasecoher', %formula = { formula{1} ['mean(arg2,3)'] }; % toby 10.02.2006 %formula = { formula{1} ['mean(arg2(:,:,data),3)'] }; formula = { formula{1} ['mean(arg2(:,:,X),3)'] }; if strcmpi(g.lowmem, 'on') for ind = 1:2:size(alltfX1,1) if ind == size(alltfX1,1), indarr = ind; else indarr = [ind:ind+1]; end; alltfX1norm = alltfX1(indarr,:,:)./sqrt(alltfX1(indarr,:,:).*conj(alltfX1(indarr,:,:))); alltfX2norm = alltfX2(indarr,:,:)./sqrt(alltfX2(indarr,:,:).*conj(alltfX2(indarr,:,:))); alltfXpower = { alltfX1power(indarr,:,:) alltfX2power(indarr,:,:) }; alltfXnorm = { alltfX1norm alltfX2norm }; [resdifftmp resimagestmp res1tmp res2tmp] = ... condstat(formula, g.naccu, g.alpha, {'both' 'both'}, { '' g.condboot}, ... alltfXpower, alltfXnorm); resdiff{1}(indarr,:) = resdifftmp{1}; resdiff{2}(indarr,:) = resdifftmp{2}; resimages{1}(indarr,:,:) = resimagestmp{1}; resimages{2}(indarr,:,:) = resimagestmp{2}; res1{1}(indarr,:) = res1tmp{1}; res1{2}(indarr,:) = res1tmp{2}; res2{1}(indarr,:) = res2tmp{1}; res2{2}(indarr,:) = res2tmp{2}; end; else alltfX1norm = alltfX1./sqrt(alltfX1.*conj(alltfX1)); alltfX2norm = alltfX2./sqrt(alltfX2.*conj(alltfX2)); % maybe have to suppress preprocessing -> lot of memory alltfXpower = { alltfX1power alltfX2power }; alltfXnorm = { alltfX1norm alltfX2norm }; [resdiff resimages res1 res2] = condstat(formula, g.naccu, g.alpha, {'both' 'both'}, { '' g.condboot}, ... alltfXpower, alltfXnorm); end; end; % same as below: plottimef(P1-P2, R2-R1, 10*resimages{1}, resimages{2}, mean(data{1},2)-mean(data{2},2), freqs, times, mbase, g); if strcmpi(g.plotersp, 'on') | strcmpi(g.plotitc, 'on') g.erspmax = []; % auto scale g.itcmax = []; % auto scale plottimef(10*resdiff{1}, resdiff{2}, 10*resimages{1}, resimages{2}, ... mean(data{1},2)-mean(data{2},2), freqs, timesout, meanmbase, [], [], g); end; R1 = res1{2}; R2 = res2{2}; Rdiff = resdiff{2}; Pboot = { Pboot1 Pboot2 10*resimages{1} }; Rboot = { Rboot1 Rboot2 resimages{2} }; end; P = { P1 P2 P1-P2 }; R = { R1 R2 Rdiff }; if nargout >= 8, alltfX = { alltfX1 alltfX2 }; end; return; % ********************************** END FOR MULTIPLE CONDITIONS end; %%%%%%%%%%%%%%%%%%%%%% % display text to user (computation perfomed only for display) %%%%%%%%%%%%%%%%%%%%%% verboseprintf(g.verbose, 'Computing Event-Related Spectral Perturbation (ERSP) and\n'); switch g.type case 'phasecoher', verboseprintf(g.verbose, ' Inter-Trial Phase Coherence (ITC) images based on %d trials\n',trials); case 'phasecoher2', verboseprintf(g.verbose, ' Inter-Trial Phase Coherence 2 (ITC) images based on %d trials\n',trials); case 'coher', verboseprintf(g.verbose, ' Linear Inter-Trial Coherence (ITC) images based on %d trials\n',trials); end; verboseprintf(g.verbose, ' of %d frames sampled at %g Hz.\n',g.frames,g.srate); verboseprintf(g.verbose, 'Each trial contains samples from %1.0f ms before to\n',g.tlimits(1)); verboseprintf(g.verbose, ' %1.0f ms after the timelocking event.\n',g.tlimits(2)); if ~isnan(g.alpha) verboseprintf(g.verbose, 'Only significant values (permutation statistics p<%g) will be colored;\n',g.alpha) verboseprintf(g.verbose, ' non-significant values will be plotted in green\n'); end verboseprintf(g.verbose,' Image frequency direction: %s\n',g.hzdir); if isempty(g.precomputed) % ----------------------------------------- % detrend over epochs (trials) if requested % ----------------------------------------- if strcmpi(g.rmerp, 'on') if ndims(data) == 2 data = data - mean(data,2)*ones(1, length(data(:))/g.frames); else data = data - repmat(mean(data,3), [1 1 trials]); end; end; % ---------------------------------------------------- % compute time frequency decompositions, power and ITC % ---------------------------------------------------- if length(g.timesout) > 1, tmioutopt = { 'timesout' , g.timesout }; elseif ~isempty(g.ntimesout) tmioutopt = { 'ntimesout', g.ntimesout }; else tmioutopt = { 'ntimesout', g.timesout }; end; [alltfX freqs timesout R] = timefreq(data, g.srate, tmioutopt{:}, ... 'winsize', g.winsize, 'tlimits', g.tlimits, 'detrend', g.detrend, ... 'itctype', g.type, 'wavelet', g.cycles, 'verbose', g.verbose, ... 'padratio', g.padratio, 'freqs', g.freqs, 'freqscale', g.freqscale, ... 'nfreqs', g.nfreqs, 'timestretch', {g.timeStretchMarks', g.timeStretchRefs}, timefreqopts{:}); else alltfX = g.precomputed.tfdata; timesout = g.precomputed.times; freqs = g.precomputed.freqs; if strcmpi(g.precomputed.recompute, 'ersp') R = []; else switch g.itctype case 'coher', R = alltfX ./ repmat(sqrt(sum(alltfX .* conj(alltfX),3) * size(alltfX,3)), [1 1 size(alltfX,3)]); case 'phasecoher2', R = alltfX ./ repmat(sum(sqrt(alltfX .* conj(alltfX)),3), [1 1 size(alltfX,3)]); case 'phasecoher', R = alltfX ./ sqrt(alltfX .* conj(alltfX)); end; P = []; mbase = []; return; end; end; if g.cycles(1) == 0 alltfX = 2/0.375*alltfX/g.winsize; % TF and MC (12/11/2006): normalization, divide by g.winsize P = alltfX.*conj(alltfX); % power % TF and MC (12/14/2006): multiply by 2 account for negative frequencies, % and ounteract the reduction by a factor 0.375 that occurs as a result of % cosine (Hann) tapering. Refer to Bug 446 % Modified again 04/29/2011 due to comment in bug 1032 else P = alltfX.*conj(alltfX); % power for wavelets end; % --------------- % baseline length % --------------- if size(g.baseline,2) == 2 baseln = []; for index = 1:size(g.baseline,1) tmptime = find(timesout >= g.baseline(index,1) & timesout <= g.baseline(index,2)); baseln = union_bc(baseln, tmptime); end; if length(baseln)==0 error( [ 'There are no sample points found in the default baseline.' 10 ... 'This may happen even though data time limits overlap with' 10 ... 'the baseline period (because of the time-freq. window width).' 10 ... 'Either disable the baseline, change the baseline limits.' ] ); end else if ~isempty(find(timesout < g.baseline)) baseln = find(timesout < g.baseline); % subtract means of pre-0 (centered) windows else baseln = 1:length(timesout); % use all times as baseline end end; if ~isnan(g.alpha) && length(baseln)==0 verboseprintf(g.verbose, 'timef(): no window centers in baseline (times<%g) - shorten (max) window length.\n', g.baseline) return end % ----------------------------------------- % remove baseline on a trial by trial basis % ----------------------------------------- if strcmpi(g.trialbase, 'on'), tmpbase = baseln; else tmpbase = 1:size(P,2); % full baseline end; if ndims(P) == 4 if ~strcmpi(g.trialbase, 'off') && isnan( g.powbase(1) ) mbase = mean(P(:,:,tmpbase,:),3); if strcmpi(g.basenorm, 'on') mstd = std(P(:,:,tmpbase,:),[],3); P = bsxfun(@rdivide, bsxfun(@minus, P, mbase), mstd); else P = bsxfun(@rdivide, P, mbase); end; end; else if ~strcmpi(g.trialbase, 'off') && isnan( g.powbase(1) ) mbase = mean(P(:,tmpbase,:),2); if strcmpi(g.basenorm, 'on') mstd = std(P(:,tmpbase,:),[],2); P = (P-repmat(mbase,[1 size(P,2) 1]))./repmat(mstd,[1 size(P,2) 1]); % convert to log then back to normal else P = P./repmat(mbase,[1 size(P,2) 1]); %P = 10 .^ (log10(P) - repmat(log10(mbase),[1 size(P,2) 1])); % same as above end; end; end; if ~isempty(g.precomputed) return; % return single trial power end; % ----------------------- % compute baseline values % ----------------------- if isnan(g.powbase(1)) verboseprintf(g.verbose, 'Computing the mean baseline spectrum\n'); if ndims(P) == 4 if ndims(P) > 3, Pori = mean(P, 4); else Pori = P; end; mbase = mean(Pori(:,:,baseln),3); else if ndims(P) > 2, Pori = mean(P, 3); else Pori = P; end; mbase = mean(Pori(:,baseln),2); end; else verboseprintf(g.verbose, 'Using the input baseline spectrum\n'); mbase = g.powbase; if strcmpi(g.scale, 'log'), mbase = 10.^(mbase/10); end; if size(mbase,1) == 1 % if input was a row vector, flip to be a column mbase = mbase'; end; end baselength = length(baseln); % ------------------------- % remove baseline (average) % ------------------------- % original ERSP baseline removal if ~strcmpi(g.trialbase, 'on') if ~isnan( g.baseline(1) ) && any(~isnan( mbase(1) )) && strcmpi(g.basenorm, 'off') P = bsxfun(@rdivide, P, mbase); % use single trials % ERSP baseline normalized elseif ~isnan( g.baseline(1) ) && ~isnan( mbase(1) ) && strcmpi(g.basenorm, 'on') if ndims(Pori) == 3, mstd = std(Pori(:,:,baseln),[],3); else mstd = std(Pori(:,baseln),[],2); end; P = bsxfun(@rdivide, bsxfun(@minus, P, mbase), mstd); end; end; % ---------------- % phase amp option % ---------------- if strcmpi(g.phsamp, 'on') disp( 'phsamp option is deprecated'); % switch g.phsamp % case 'on' %PA = zeros(size(P,1),size(P,1),g.timesout); % NB: (freqs,freqs,times) % $$$ end % phs amp %PA (freq x freq x time) %PA(:,:,j) = PA(:,:,j) + (tmpX ./ abs(tmpX)) * ((P(:,j)))'; % x-product: unit phase column % times amplitude row %tmpcx(1,:,:) = cumulX; % allow ./ below %for jj=1:g.timesout % PA(:,:,jj) = PA(:,:,jj) ./ repmat(P(:,jj)', [size(P,1) 1]); %end end % --------- % bootstrap % --------- % this ensures that if bootstrap limits provided that no % 'alpha' won't prevent application of the provided limits if ~isnan(g.alpha) | ~isempty(find(~isnan(g.pboot))) | ~isempty(find(~isnan(g.rboot)))% if bootstrap analysis requested . . . % ERSP bootstrap % -------------- if ~isempty(find(~isnan(g.pboot))) % if ERSP bootstrap limits provided already Pboot = g.pboot(:); else if size(g.baseboot,2) == 1 if g.baseboot == 0, baselntmp = []; elseif ~isnan(g.baseline(1)) baselntmp = baseln; else baselntmp = find(timesout <= 0); % if it is empty use whole epoch end; else baselntmp = []; for index = 1:size(g.baseboot,1) tmptime = find(timesout >= g.baseboot(index,1) & timesout <= g.baseboot(index,2)); if isempty(tmptime), fprintf('Warning: empty baseline interval [%3.2f %3.2f]\n', g.baseboot(index,1), g.baseboot(index,2)); end; baselntmp = union_bc(baselntmp, tmptime); end; end; if prod(size(g.baseboot)) > 2 fprintf('Permutation statistics will use data in multiple selected windows.\n'); elseif size(g.baseboot,2) == 2 fprintf('Permutation statistics will use data in range %3.2g-%3.2g ms.\n', g.baseboot(1), g.baseboot(2)); elseif g.baseboot fprintf(' %d permutation statistics windows in baseline (times<%g).\n', length(baselntmp), g.baseboot) end; % power significance % ------------------ if strcmpi(g.boottype, 'shuffle') formula = 'mean(arg1,3);'; [ Pboot Pboottrialstmp Pboottrials] = bootstat(P, formula, 'boottype', 'shuffle', ... 'label', 'ERSP', 'bootside', 'both', 'naccu', g.naccu, ... 'basevect', baselntmp, 'alpha', g.alpha, 'dimaccu', 2 ); clear Pboottrialstmp; else center = 0; if strcmpi(g.basenorm, 'off'), center = 1; end; % bootstrap signs Pboottmp = P; Pboottrials = zeros([ size(P,1) size(P,2) g.naccu ]); for index = 1:g.naccu Pboottmp = (Pboottmp-center).*(ceil(rand(size(Pboottmp))*2-1)*2-1)+center; Pboottrials(:,:,index) = mean(Pboottmp,3); end; Pboot = []; end; if size(Pboot,2) == 1, Pboot = Pboot'; end; end; % ITC bootstrap % ------------- if ~isempty(find(~isnan(g.rboot))) % if itc bootstrap provided Rboot = g.rboot; else if ~isempty(find(~isnan(g.pboot))) % if ERSP limits were provided (but ITC not) if size(g.baseboot,2) == 1 if g.baseboot == 0, baselntmp = []; elseif ~isnan(g.baseline(1)) baselntmp = baseln; else baselntmp = find(timesout <= 0); % if it is empty use whole epoch end; else baselntmp = []; for index = 1:size(g.baseboot,1) tmptime = find(timesout >= g.baseboot(index,1) && timesout <= g.baseboot(index,2)); if isempty(tmptime), fprintf('Warning: empty baseline interval [%3.2f %3.2f]\n', g.baseboot(index,1), g.baseboot(index,2)); end; baselntmp = union_bc(baselntmp, tmptime); end; end; if prod(size(g.baseboot)) > 2 fprintf('Permutation statistics will use data in multiple selected windows.\n'); elseif size(g.baseboot,2) == 2 fprintf('Permutation statistics will use data in range %3.2g-%3.2g ms.\n', g.baseboot(1), g.baseboot(2)); elseif g.baseboot fprintf(' %d permutation statistics windows in baseline (times<%g).\n', length(baselntmp), g.baseboot) end; end; % ITC significance % ---------------- inputdata = alltfX; switch g.type case 'coher', formula = [ 'sum(arg1,3)./sqrt(sum(arg1.*conj(arg1),3))/ sqrt(' int2str(size(alltfX,3)) ');' ]; case 'phasecoher', formula = [ 'mean(arg1,3);' ]; inputdata = alltfX./sqrt(alltfX.*conj(alltfX)); case 'phasecoher2', formula = [ 'sum(arg1,3)./sum(sqrt(arg1.*conj(arg1)),3);' ]; end; if strcmpi(g.boottype, 'randall'), dimaccu = []; g.boottype = 'rand'; else dimaccu = 2; end; [Rboot Rboottmp Rboottrials] = bootstat(inputdata, formula, 'boottype', g.boottype, ... 'label', 'ITC', 'bootside', 'upper', 'naccu', g.naccu, ... 'basevect', baselntmp, 'alpha', g.alpha, 'dimaccu', 2 ); fprintf('\n'); clear Rboottmp; end; else Pboot = []; Rboot = []; end % average the power % ----------------- PA = P; if ndims(P) == 4, P = mean(P, 4); elseif ndims(P) == 3, P = mean(P, 3); end; % correction for multiple comparisons % ----------------------------------- maskersp = []; maskitc = []; if ~isnan(g.alpha) if isempty(find(~isnan(g.pboot))) % if ERSP lims not provided if ndims(Pboottrials) < 3, Pboottrials = Pboottrials'; end; exactp_ersp = compute_pvals(P, Pboottrials); if strcmpi(g.mcorrect, 'fdr') alphafdr = fdr(exactp_ersp, g.alpha); if alphafdr ~= 0 fprintf('ERSP correction for multiple comparisons using FDR, alpha_fdr = %3.6f\n', alphafdr); else fprintf('ERSP correction for multiple comparisons using FDR, nothing significant\n', alphafdr); end; maskersp = exactp_ersp <= alphafdr; else maskersp = exactp_ersp <= g.alpha; end; end; if isempty(find(~isnan(g.rboot))) % if ITC lims not provided exactp_itc = compute_pvals(abs(R), abs(Rboottrials')); if strcmpi(g.mcorrect, 'fdr') alphafdr = fdr(exactp_itc, g.alpha); if alphafdr ~= 0 fprintf('ITC correction for multiple comparisons using FDR, alpha_fdr = %3.6f\n', alphafdr); else fprintf('ITC correction for multiple comparisons using FDR, nothing significant\n', alphafdr); end; maskitc = exactp_itc <= alphafdr; else maskitc = exactp_itc <= g.alpha; end end; end; % convert to log if necessary % --------------------------- if strcmpi(g.scale, 'log') if ~isnan( g.baseline(1) ) && ~isnan( mbase(1) ) && strcmpi(g.trialbase, 'off'), mbase = log10(mbase)*10; end; P = 10 * log10(P); if ~isempty(Pboot) Pboot = 10 * log10(Pboot); end; end; if isempty(Pboot) && exist('maskersp') Pboot = maskersp; end; % auto scalling % ------------- if isempty(g.erspmax) g.erspmax = [max(max(abs(P)))]/2; if strcmpi(g.scale, 'abs') && strcmpi(g.basenorm, 'off') % % of baseline g.erspmax = [max(max(abs(P)))]; if g.erspmax > 1 g.erspmax = [1-(g.erspmax-1) g.erspmax]; else g.erspmax = [g.erspmax 1+(1-g.erspmax)]; end; end; %g.erspmax = [-g.erspmax g.erspmax]+1; end; % -------- % plotting % -------- if strcmpi(g.plotersp, 'on') || strcmpi(g.plotitc, 'on') if ndims(P) == 3 P = squeeze(P(2,:,:,:)); R = squeeze(R(2,:,:,:)); mbase = squeeze(mbase(2,:)); ERP = mean(squeeze(data(1,:,:)),2); else ERP = mean(data,2); end; if strcmpi(g.plottype, 'image') plottimef(P, R, Pboot, Rboot, ERP, freqs, timesout, mbase, maskersp, maskitc, g); else plotallcurves(P, R, Pboot, Rboot, ERP, freqs, timesout, mbase, g); end; end; % -------------- % format outputs % -------------- if strcmpi(g.outputformat, 'old') R = abs(R); % convert coherence vector to magnitude if strcmpi(g.scale, 'log'), mbase = 10^(mbase/10); end; end; if strcmpi(g.verbose, 'on') disp('Note: Add output variables to command line call in history to'); disp(' retrieve results and use the tftopo function to replot them'); end; mbase = mbase'; if ~isempty(g.caption) h = textsc(g.caption, 'title'); set(h, 'FontWeight', 'bold'); end return; % ----------------- % plotting function % ----------------- function g = plottimef(P, R, Pboot, Rboot, ERP, freqs, times, mbase, maskersp, maskitc, g); persistent showwarning; if isempty(showwarning) warning( [ 'Some versions of Matlab crash on this function. If this is' 10 ... 'the case, simply comment the code line 1655-1673 in newtimef.m' 10 ... 'which aims at "ploting marginal ERSP mean below ERSP image"' ]); showwarning = 1; end; % % compute ERP % ERPtimes = [g.tlimits(1):(g.tlimits(2)-g.tlimits(1))/(g.frames-1):g.tlimits(2)+0.000001]; ERPindices = zeros(1, length(times)); for ti=1:length(times) [tmp ERPindices(ti)] = min(abs(ERPtimes-times(ti))); end ERPtimes = ERPtimes(ERPindices); % subset of ERP frames on t/f window centers ERP = ERP(ERPindices); if ~isreal(R) Rangle = angle(R); Rsign = sign(imag(R)); R = abs(R); % convert coherence vector to magnitude setylim = 1; else Rangle = zeros(size(R)); % Ramon: if isreal(R) then we get an error because Rangle does not exist Rsign = ones(size(R)); setylim = 0; end; switch lower(g.plotitc) case 'on', switch lower(g.plotersp), case 'on', ordinate1 = 0.67; ordinate2 = 0.1; height = 0.33; g.plot = 1; case 'off', ordinate2 = 0.1; height = 0.9; g.plot = 1; end; case 'off', ordinate1 = 0.1; height = 0.9; switch lower(g.plotersp), case 'on', ordinate1 = 0.1; height = 0.9; g.plot = 1; case 'off', g.plot = 0; end; end; if g.plot % verboseprintf(g.verbose, '\nNow plotting...\n'); set(gcf,'DefaultAxesFontSize',g.AXES_FONT) colormap(jet(256)); pos = get(gca,'position'); q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]; axis off; end; switch lower(g.plotersp) case 'on' % %%%%%%% image the ERSP %%%%%%%%%%%%%%%%%%%%%%%%%% % h(1) = axes('Position',[.1 ordinate1 .9 height].*s+q); set(h(1), 'tag', 'ersp'); PP = P; if strcmpi(g.scale, 'abs') && strcmpi(g.basenorm, 'off') baseval = 1; else baseval = 0; end; if ~isnan(g.alpha) if strcmpi(g.pcontour, 'off') && ~isempty(maskersp) % zero out nonsignif. power differences PP(~maskersp) = baseval; %PP = PP .* maskersp; elseif isempty(maskersp) if size(PP,1) == size(Pboot,1) && size(PP,2) == size(Pboot,2) PP(find(PP > Pboot(:,:,1) & (PP < Pboot(:,:,2)))) = baseval; Pboot = squeeze(mean(Pboot,2)); if size(Pboot,2) == 1, Pboot = Pboot'; end; else PP(find((PP > repmat(Pboot(:,1),[1 length(times)])) ... & (PP < repmat(Pboot(:,2),[1 length(times)])))) = baseval; end end; end; % find color limits % ----------------- if isempty(g.erspmax) if g.ERSP_CAXIS_LIMIT == 0 g.erspmax = [-1 1]*1.1*max(max(abs(P(:,:)))); else g.erspmax = g.ERSP_CAXIS_LIMIT*[-1 1]; end elseif length(g.erspmax) == 1 g.erspmax = [ -g.erspmax g.erspmax]; end if isnan( g.baseline(1) ) && g.erspmax(1) < 0 g.erspmax = [ min(min(P(:,:))) max(max(P(:,:)))]; end; % plot image % ---------- if ~strcmpi(g.freqscale, 'log') imagesc(times,freqs,PP(:,:), g.erspmax); else imagesclogy(times,freqs,PP(:,:),g.erspmax); end; set(gca,'ydir',g.hzdir); % make frequency ascend or descend % put contour for multiple comparison masking if ~isempty(maskersp) && strcmpi(g.pcontour, 'on') hold on; [tmpc tmph] = contour(times, freqs, maskersp); set(tmph, 'linecolor', 'k', 'linewidth', 0.25) end; hold on plot([0 0],[0 freqs(end)],'--m','LineWidth',g.linewidth); % plot time 0 if ~isnan(g.marktimes) % plot marked time for mt = g.marktimes(:)' plot([mt mt],[0 freqs(end)],'--k','LineWidth',g.linewidth); end end hold off set(h(1),'YTickLabel',[],'YTick',[]) set(h(1),'XTickLabel',[],'XTick',[]) if ~isempty(g.vert) for index = 1:length(g.vert) line([g.vert(index), g.vert(index)], [min(freqs) max(freqs)], 'linewidth', 1, 'color', 'm'); end; end; h(2) = gca; h(3) = cbar('vert'); % ERSP colorbar axes set(h(2),'Position',[.1 ordinate1 .8 height].*s+q) set(h(3),'Position',[.95 ordinate1 .05 height].*s+q) title([ 'ERSP(' g.unitpower ')' ]) % %%%%% plot marginal ERSP mean below ERSP image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % h(4) = axes('Position',[.1 ordinate1-0.1 .8 .1].*s+q); E = [min(P(:,:),[],1);max(P(:,:),[],1)]; % plotting limits if isempty(g.erspmarglim) g.erspmarglim = [min(E(1,:))-max(max(abs(E)))/3 max(E(2,:))+max(max(abs(E)))/3]; end; plot(times,E,[0 0],g.erspmarglim, '--m','LineWidth',g.linewidth) xlim([min(times) max(times)]) ylim(g.erspmarglim) tick = get(h(4),'YTick'); set(h(4),'YTick',[tick(1) ; tick(end)]) set(h(4),'YAxisLocation','right') set(h(4),'TickLength',[0.020 0.025]); xlabel('Time (ms)') ylabel(g.unitpower) % %%%%% plot mean spectrum to left of ERSP image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % h(5) = axes('Position',[0 ordinate1 .1 height].*s+q); if isnan(g.baseline) % Ramon :for bug 1657 E = zeros(size(freqs)); else E = mbase; end if ~isnan(E(1)) % plotting limits if isempty(g.speclim) % g.speclim = [min(E)-max(abs(E))/3 max(E)+max(abs(E))/3]; if all(~isnan(mbase)) g.speclim = [min(mbase)-max(abs(mbase))/3 max(mbase)+max(abs(mbase))/3]; % RMC: Just for plotting else g.speclim = [min(E)-max(abs(E))/3 max(E)+max(abs(E))/3]; end end; % plot curves if ~strcmpi(g.freqscale, 'log') plot(freqs,E,'LineWidth',g.linewidth); hold on; if ~isnan(g.alpha) && size(Pboot,2) == 2 try plot(freqs,Pboot(:,:)'+[E;E], 'g', 'LineWidth',g.linewidth) plot(freqs,Pboot(:,:)'+[E;E], 'k:','LineWidth',g.linewidth) catch plot(freqs,Pboot(:,:)+[E E], 'g', 'LineWidth',g.linewidth) plot(freqs,Pboot(:,:)+[E E], 'k:','LineWidth',g.linewidth) end; end if freqs(1) ~= freqs(end), xlim([freqs(1) freqs(end)]); end; if g.speclim(1) ~= g.speclim(2), ylim(g.speclim); end; % Ramon :for bug 1657 else % 'log' semilogx(freqs,E,'LineWidth',g.linewidth); hold on; if ~isnan(g.alpha) try semilogx(freqs,Pboot(:,:)'+[E;E],'g', 'LineWidth',g.linewidth) semilogx(freqs,Pboot(:,:)'+[E;E],'k:','LineWidth',g.linewidth) catch semilogx(freqs,Pboot(:,:)+[E E],'g', 'LineWidth',g.linewidth) semilogx(freqs,Pboot(:,:)+[E E],'k:','LineWidth',g.linewidth) end; end if freqs(1) ~= freqs(end), xlim([freqs(1) freqs(end)]); end; if g.speclim(1) ~= g.speclim(2), ylim(g.speclim); end; %RMC set(h(5),'View',[90 90]) divs = linspace(log(freqs(1)), log(freqs(end)), 10); set(gca, 'xtickmode', 'manual'); divs = ceil(exp(divs)); divs = unique_bc(divs); % ceil is critical here, round might misalign set(gca, 'xtick', divs); end; set(h(5),'TickLength',[0.020 0.025]); set(h(5),'View',[90 90]) xlabel('Frequency (Hz)') if strcmp(g.hzdir,'normal') set(gca,'xdir','reverse'); else set(gca,'xdir','normal'); end ylabel(g.unitpower) tick = get(h(5),'YTick'); if (length(tick)>2) set(h(5),'YTick',[tick(1) ; tick(end-1)]) end end; end; switch lower(g.plotitc) case 'on' % %%%%%%%%%%%% Image the ITC %%%%%%%%%%%%%%%%%% % h(6) = axes('Position',[.1 ordinate2 .9 height].*s+q); % ITC image if ishandle(h(1));set(h(1), 'tag', 'itc');end; if abs(R(1,1)-1) < 0.0001, g.plotphaseonly = 'on'; end; if strcmpi(g.plotphaseonly, 'on') RR = Rangle/pi*180; else RR = R; end; if ~isnan(g.alpha) if ~isempty(maskitc) && strcmpi(g.pcontour, 'off') RR = RR .* maskitc; elseif isempty(maskitc) if size(RR,1) == size(Rboot,1) && size(RR,2) == size(Rboot,2) tmp = gcf; if size(Rboot,3) == 2 RR(find(RR > Rboot(:,:,1) & RR < Rboot(:,:,2))) = 0; else RR(find(RR < Rboot)) = 0; end; Rboot = mean(Rboot(:,:,end),2); else RR(find(RR < repmat(Rboot(:),[1 length(times)]))) = 0; end; end; end if g.ITC_CAXIS_LIMIT == 0 coh_caxis = min(max(max(R(:,:))),1)*[-1 1]; % 1 WAS 0.4 ! else coh_caxis = g.ITC_CAXIS_LIMIT*[-1 1]; end if strcmpi(g.plotphaseonly, 'on') if ~strcmpi(g.freqscale, 'log') imagesc(times,freqs,RR(:,:)); % <--- else imagesclogy(times,freqs,RR(:,:)); % <--- end; g.itcmax = [-180 180]; setylim = 0; else if max(coh_caxis) == 0, % toby 10.02.2006 coh_caxis = [-1 1]; end if ~strcmpi(g.freqscale, 'log') if exist('Rsign') && strcmp(g.plotphasesign, 'on') imagesc(times,freqs,Rsign(:,:).*RR(:,:),coh_caxis); % <--- else imagesc(times,freqs,RR(:,:),coh_caxis); % <--- end else if exist('Rsign') && strcmp(g.plotphasesign, 'on') imagesclogy(times,freqs,Rsign(:,:).*RR(:,:),coh_caxis); % <--- else imagesclogy(times,freqs,RR(:,:),coh_caxis); % <--- end end; end; set(gca,'ydir',g.hzdir); % make frequency ascend or descend % plot contour if necessary if ~isempty(maskitc) && strcmpi(g.pcontour, 'on') hold on; [tmpc tmph] = contour(times, freqs, maskitc); set(tmph, 'linecolor', 'k', 'linewidth', 0.25) end; if isempty(g.itcmax) g.itcmax = caxis; elseif length(g.itcmax) == 1 g.itcmax = [ -g.itcmax g.itcmax ]; end; caxis(g.itcmax); hold on plot([0 0],[0 freqs(end)],'--m','LineWidth',g.linewidth); if ~isnan(g.marktimes) for mt = g.marktimes(:)' plot([mt mt],[0 freqs(end)],'--k','LineWidth',g.linewidth); end end hold off set(h(6),'YTickLabel',[],'YTick',[]) set(h(6),'XTickLabel',[],'XTick',[]) if ~isempty(g.vert) for index = 1:length(g.vert) line([g.vert(index), g.vert(index)], [min(freqs) max(freqs)], 'linewidth', 1, 'color', 'm'); end; end; h(7) = gca; h(8) = cbar('vert'); %h(9) = get(h(8),'Children'); % make the function crash set(h(7),'Position',[.1 ordinate2 .8 height].*s+q) set(h(8),'Position',[.95 ordinate2 .05 height].*s+q) if setylim set(h(8),'YLim',[0 g.itcmax(2)]); end; if strcmpi(g.plotphaseonly, 'on') title('ITC phase') else title('ITC') end; % %%%%% plot the ERP below the ITC image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % h(10) = axes('Position',[.1 ordinate2-0.1 .8 .1].*s+q); % ERP if isempty(g.erplim) ERPmax = max(ERP); ERPmin = min(ERP); g.erplim = [ ERPmin - 0.1*(ERPmax-ERPmin) ERPmax + 0.1*(ERPmax-ERPmin) ]; end; plot(ERPtimes,ERP, [0 0],g.erplim,'--m','LineWidth',g.linewidth); hold on; plot([times(1) times(length(times))],[0 0], 'k'); xlim([min(ERPtimes) max(ERPtimes)]); ylim(g.erplim) set(gca,'ydir',g.ydir); tick = get(h(10),'YTick'); set(h(10),'YTick',[tick(1) ; tick(end)]) set(h(10),'TickLength',[0.02 0.025]); set(h(10),'YAxisLocation','right') xlabel('Time (ms)') ylabel('\muV') if (~isempty(g.topovec)) if length(g.topovec) ~= 1, ylabel(''); end; % ICA component end; E = nan_mean(R(:,:)'); % don't let a few NaN's crash this % %%%%% plot the marginal mean left of the ITC image %%%%%%%%%%%%%%%%%%%%% % h(11) = axes('Position',[0 ordinate2 .1 height].*s+q); % plot the marginal mean % ITC left of the ITC image % set plotting limits if isempty(g.itcavglim) if ~isnan(g.alpha) g.itcavglim = [ min(E)-max(E)/3 max(Rboot)+max(Rboot)/3]; else g.itcavglim = [ min(E)-max(E)/3 max(E)+max(E)/3]; end; end; if max(g.itcavglim) == 0 || any(isnan(g.itcavglim)) g.itcavglim = [-1 1]; end % plot marginal ITC if ~strcmpi(g.freqscale, 'log') plot(freqs,E,'LineWidth',g.linewidth); hold on; if ~isnan(g.alpha) plot(freqs,Rboot,'g', 'LineWidth',g.linewidth) plot(freqs,Rboot,'k:','LineWidth',g.linewidth) end if freqs(1) ~= freqs(end), xlim([freqs(1) freqs(end)]); end ylim(g.itcavglim) else semilogx(freqs,E,'LineWidth',g.linewidth); hold on; if ~isnan(g.alpha) semilogx(freqs,Rboot(:),'g', 'LineWidth',g.linewidth) semilogx(freqs,Rboot(:),'k:','LineWidth',g.linewidth) end if freqs(1) ~= freqs(end), xlim([freqs(1) freqs(end)]); end; ylim(g.itcavglim) divs = linspace(log(freqs(1)), log(freqs(end)), 10); set(gca, 'xtickmode', 'manual'); divs = ceil(exp(divs)); divs = unique_bc(divs); % ceil is critical here, round might misalign set(gca, 'xtick', divs); end; % ITC plot details tick = get(h(11),'YTick'); if length(tick) > 1 set(h(11),'YTick',[tick(1) ; tick(length(tick))]) end; set(h(11),'View',[90 90]) %set(h(11),'TickLength',[0.020 0.025]); xlabel('Frequency (Hz)') if strcmp(g.hzdir,'normal') set(gca,'xdir','reverse'); else set(gca,'xdir','normal'); end ylabel('ERP') end; %switch % %%%%%%%%%%%%%%% plot a topoplot() %%%%%%%%%%%%%%%%%%%%%%% % if (~isempty(g.topovec)) && strcmpi(g.plotitc, 'on') && strcmpi(g.plotersp, 'on') if strcmp(g.plotersp,'off') h(12) = axes('Position',[-.207 .95 .2 .14].*s+q); % place the scalp map at top-left else h(12) = axes('Position',[-.1 .43 .2 .14].*s+q); % place the scalp map at middle-left end; if length(g.topovec) == 1 topoplot(g.topovec,g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', g.chaninfo); else topoplot(g.topovec,g.elocs,'electrodes','off', 'chaninfo', g.chaninfo); end; axis('square') end if g.plot try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if (length(g.title) > 0) && ~iscell(g.title) axes('Position',pos,'Visible','Off'); h(13) = text(-.05,1.01,g.title); set(h(13),'VerticalAlignment','bottom') set(h(13),'HorizontalAlignment','left') set(h(13),'FontSize',g.TITLE_FONT); end try, axcopy(gcf); catch, end; end; % --------------- % Plotting curves % --------------- function plotallcurves(P, R, Pboot, Rboot, ERP, freqs, times, mbase, g); if ~isreal(R) Rangle = angle(R); R = abs(R); % convert coherence vector to magnitude setylim = 1; else Rangle = zeros(size(R)); % Ramon: if isreal(R) then we get an error because Rangle does not exist Rsign = ones(size(R)); setylim = 0; end; if strcmpi(g.plotitc, 'on') | strcmpi(g.plotersp, 'on') verboseprintf(g.verbose, '\nNow plotting...\n'); pos = get(gca,'position'); q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]; end; % time unit % --------- if times(end) > 10000 times = times/1000; timeunit = 's'; else timeunit = 'ms'; end; if strcmpi(g.plotersp, 'on') % %%%%%%% image the ERSP %%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(g.plotitc, 'on'), subplot(2,1,1); end; set(gca, 'tag', 'ersp'); alllegend = {}; for index = 1:length(freqs) alllegend{index} = [ num2str(freqs(index)) 'Hz baseline ' num2str(mbase(index)) ' dB' ]; end; if strcmpi(g.plotmean, 'on') && freqs(1) ~= freqs(end) alllegend = { alllegend{:} [ num2str(freqs(1)) '-' num2str(freqs(end)) ... 'Hz mean baseline ' num2str(mean(mbase)) ' dB' ] }; end; plotcurve(times, P, 'maskarray', Pboot, 'title', 'ERSP', ... 'xlabel', [ 'Time (' timeunit ')' ], 'ylabel', 'dB', 'ylim', [-g.erspmax g.erspmax], ... 'vert', g.vert, 'marktimes', g.marktimes, 'legend', alllegend, ... 'linewidth', g.linewidth, 'highlightmode', g.highlightmode, 'plotmean', g.plotmean); end; if strcmpi(g.plotitc, 'on') % %%%%%%%%%%%% Image the ITC %%%%%%%%%%%%%%%%%% % if strcmpi(g.plotersp, 'on'), subplot(2,1,2); end; set(gca, 'tag', 'itc'); if abs(R(1,1)-1) < 0.0001, g.plotphaseonly = 'on'; end; if strcmpi(g.plotphaseonly, 'on') % plot ITC phase instead of amplitude (e.g. for continuous data) RR = Rangle/pi*180; else RR = R; end; % find regions of significance % ---------------------------- alllegend = {}; for index = 1:length(freqs) alllegend{index} = [ num2str(freqs(index)) 'Hz baseline ' num2str(mbase(index)) ' dB' ]; end; if strcmpi(g.plotmean, 'on') && freqs(1) ~= freqs(end) alllegend = { alllegend{:} [ num2str(freqs(1)) '-' num2str(freqs(end)) ... 'Hz mean baseline ' num2str(mean(mbase)) ' dB' ] }; end; plotcurve(times, RR, 'maskarray', Rboot, 'val2mask', R, 'title', 'ITC', ... 'xlabel', [ 'Time (' timeunit ')' ], 'ylabel', 'dB', 'ylim', g.itcmax, ... 'vert', g.vert, 'marktimes', g.marktimes, 'legend', alllegend, ... 'linewidth', g.linewidth, 'highlightmode', g.highlightmode, 'plotmean', g.plotmean); end; if strcmpi(g.plotitc, 'on') | strcmpi(g.plotersp, 'on') % %%%%%%%%%%%%%%% plot a topoplot() %%%%%%%%%%%%%%%%%%%%%%% % if (~isempty(g.topovec)) h(12) = axes('Position',[-.1 .43 .2 .14].*s+q); if length(g.topovec) == 1 topoplot(g.topovec,g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10); else topoplot(g.topovec,g.elocs,'electrodes','off'); end; axis('square') end try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if (length(g.title) > 0) && ~iscell(g.title) axes('Position',pos,'Visible','Off'); h(13) = text(-.05,1.01,g.title); set(h(13),'VerticalAlignment','bottom') set(h(13),'HorizontalAlignment','left') set(h(13),'FontSize',g.TITLE_FONT); end try, axcopy(gcf); catch, end; end; % %%%%%%%%%%%%%%%%%%%%%%% Highlight regions %%%%%%%%%%%%%%%%%%%%%%%%%% % function highlight(ax, times, regions, highlightmode); color1 = [0.75 0.75 0.75]; color2 = [0 0 0]; yl = ylim; if ~strcmpi(highlightmode, 'background') yl2 = [ yl(1)-(yl(2)-yl(1))*0.15 yl(1)-(yl(2)-yl(1))*0.1 ]; tmph = patch([times(1) times(end) times(end) times(1)], ... [yl2(1) yl2(1) yl2(2) yl2(2)], [1 1 1]); hold on; ylim([ yl2(1) yl(2)]); set(tmph, 'edgecolor', [1 1 1]); end; if ~isempty(regions) axes(ax); in_a_region = 0; for index=1:length(regions) if regions(index) && ~in_a_region tmpreg(1) = times(index); in_a_region = 1; end; if ~regions(index) && in_a_region tmpreg(2) = times(index); in_a_region = 0; if strcmpi(highlightmode, 'background') tmph = patch([tmpreg(1) tmpreg(2) tmpreg(2) tmpreg(1)], ... [yl(1) yl(1) yl(2) yl(2)], color1); hold on; set(tmph, 'edgecolor', color1); else tmph = patch([tmpreg(1) tmpreg(2) tmpreg(2) tmpreg(1)], ... [yl2(1) yl2(1) yl2(2) yl2(2)], color2); hold on; set(tmph, 'edgecolor', color2); end; end; end; end; % reshaping data % ----------- function [data, frames] = reshape_data(data, frames) data = squeeze(data); if min(size(data)) == 1 if (rem(length(data),frames) ~= 0) error('Length of data vector must be divisible by frames.'); end data = reshape(data, frames, length(data)/frames); else frames = size(data,1); end function verboseprintf(verbose, varargin) if strcmpi(verbose, 'on') fprintf(varargin{:}); end; % reshaping data % ----------- function pvals = compute_pvals(oridat, surrog, tail) if nargin < 3 tail = 'both'; end; if myndims(oridat) > 1 if size(oridat,2) ~= size(surrog, 2) | myndims(surrog) == 2 if size(oridat,1) == size(surrog, 1) surrog = repmat( reshape(surrog, [size(surrog,1) 1 size(surrog,2)]), [1 size(oridat,2) 1]); elseif size(oridat,2) == size(surrog, 1) surrog = repmat( reshape(surrog, [1 size(surrog,1) size(surrog,2)]), [size(oridat,1) 1 1]); else error('Permutation statistics array size error'); end; end; end; surrog = sort(surrog, myndims(surrog)); % sort last dimension if myndims(surrog) == 1 surrog(end+1) = oridat; elseif myndims(surrog) == 2 surrog(:,end+1) = oridat; elseif myndims(surrog) == 3 surrog(:,:,end+1) = oridat; else surrog(:,:,:,end+1) = oridat; end; [tmp idx] = sort( surrog, myndims(surrog) ); [tmp mx] = max( idx,[], myndims(surrog)); len = size(surrog, myndims(surrog) ); pvals = 1-(mx-0.5)/len; if strcmpi(tail, 'both') pvals = min(pvals, 1-pvals); pvals = 2*pvals; end; function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end;
github
lcnhappe/happe-master
rspdfsolv.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/rspdfsolv.m
2,680
utf_8
f54da2906c104216b972ff3b6bbf6f3e
% rspdfsolv() - sub-function used by rsfit() to searc for optimal % parameter for Ramberg-Schmeiser distribution % % Usage: res = rspdfsolv(l, l3, l4) % % Input: % l - [lambda3 lamda4] parameters to optimize % skew - expected skewness % kurt - expected kurtosis % % Output: % res - residual % % Author: Arnaud Delorme, SCCN, 2003 % % See also: rsget() % % Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F. % A probability distribution and its uses in fitting data. % Technimetrics, 1979, 21: 201-214. % Copyright (C) 2003 Arnaud Delorme, SCCN, [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 = rspdfsolv( l, a3, a4); A = 1/(1 + l(1)) - 1/(1 + l(2)); B = 1/(1 + 2*l(1)) + 1/(1 + 2*l(2)) - 2*beta(1+l(1), 1+l(2)); C = 1/(1 + 3*l(1)) - 1/(1 + 3*l(2)) ... - 3*beta(1+2*l(1), 1+l(2)) + 3*beta(1+l(1), 1+2*l(2)); D = 1/(1 + 4*l(1)) + 1/(1 + 4*l(2)) ... - 4*beta(1+3*l(1), 1+l(2)) - 4*beta(1+l(1), 1+3*l(2)) ... + 6*beta(1+2*l(1), 1+2*l(2)); estim_a3 = (C - 3*A*B + 2*A^3)/(B-A^2)^(3/2); estim_a4 = (D - 4*A*C + 6*A^2*B - 3*A^4)/(B-A^2)^2; res = (estim_a3 - a3)^2 + (estim_a4 - a4)^2; % the last term try to ensures that l(1) and l(2) are of the same sign if sign(l(1)*l(2)) == -1, res = 2*res; end; return; % original equations % $$$ A = 1(1 + l(3)) - 1/(1 + l(4)); % $$$ B = 1(1 + 2*l(3)) + 1/(1 + 2*l(4)) - 2*beta(1+l(3), 1+l(4)); % $$$ C = 1(1 + 3*l(3)) - 1/(1 + 3*l(4)) ... % $$$ - 3*beta(1+2*l(3), 1+l(4)) + 3*beta(1+l(3), 1+2*l(4)); % $$$ D = 1(1 + 4*l(3)) + 1/(1 + 4*l(4)) ... % $$$ - 4*beta(1+3*l(3), 1+l(4)) - 4*beta(1+l(3), 1+3*l(4)) ... % $$$ + 6*beta(1+2*l(3), 1+2*l(4)); % $$$ % $$$ R(1) = l(1) + A/l(2); % $$$ R(2) = (B-A^2)/l(2)^2; % $$$ R(3) = (C - 3*A*B + 2*A^3)/l(2)^3; % $$$ R(4) = (D - 4*A*C + 6*A^2*B - 3*A^4)/l(2)^4;
github
lcnhappe/happe-master
dftfilt.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/dftfilt.m
2,686
utf_8
b950c4302f749a1e9cffcd4c7f4ebe6a
% dftfilt() - discrete Fourier filter % % Usage: % >> b = dftfilt(n,W,c,k,q) % % Inputs: % n - number of input samples % W - maximum angular freq. relative to n, 0 < W <= .5 % c - cycles % k - oversampling % q - [0;1] 0->fft, 1->c cycles % % Authors: Sigurd Enghoff, Arnaud Delorme & Scott Makeig, % SCCN/INC/UCSD, La Jolla, 8/1/98 % Copyright (C) 8/1/98 Sigurd Enghoff & Scott Makei, 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 % 01-25-02 reformated help & license -ad % future developments % ------------------- % input into dftfilt: % - lowfreq and maxfreq (of interest) % - lowcycle and maxcyle (ex: 3 cycles at low freq and 10 cycles at maxfreq) % - the delta in frequency: ex 0.5 Hz % The function should: compute the number of points (len) automatically % Warning with FFT compatibility % Still, something has to be done about the masking so that it would be comaptible function b = dftfilt(len,maxfreq,cycle,oversmp,wavfact) count = 1; for index = 1:1/oversmp:maxfreq*len/cycle % scan frequencies w(:,count) = j * index * cycle * linspace(-pi+2*pi/len, pi-2*pi/len, len)'; % exp(-w) is a sinus curve count = count+1; % -2*pi/len ensures that we really scan from -pi to pi without redundance (-pi=+pi) end; b = exp(-w); %srate = 2*pi/len; % Angular increment. %w = j * cycle * [0:srate:2*pi-srate/2]'; % Column. %x = 1:1/oversmp:maxfreq*len/cycle; % Row. %b = exp(-w*x); % Exponentiation of outer product. for i = 1:size(b,2), m = round(wavfact*len*(i-1)/(i+oversmp-1)); % Number of elements to discard. mu = round(m/2); % Number of upper elemnts. ml = m-round(m/2); % Number of lower elemnts. b(:,i) = b(:,i) .* [zeros(mu,1) ; hanning(len-m) ; zeros(ml,1)]; end % syemtric hanning function function w = hanning(n) if ~rem(n,2) w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end
github
lcnhappe/happe-master
rspfunc.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/rspfunc.m
1,468
utf_8
d6a6d26022ec2e38fa4adca9a28a5dde
% rspfunc() - sub-function used by rsget() % % Usage: res = rspfunc(pval, l, rval) % % Input: % pval - p-value to optimize % l - [l1 l2 l3 l4] l-values for Ramberg-Schmeiser distribution % rval - expected r-value % % Output: % res - residual % % Author: Arnaud Delorme, SCCN, 2003 % % See also: rsget() % % Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F. % A probability distribution and its uses in fitting data. % Technimetrics, 1979, 21: 201-214. % Copyright (C) 2003 Arnaud Delorme, SCCN, [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 rp = rspfunc( pval, l, rval); % for fiting rp with fminsearch % ----------------------------- rp = l(1) + (pval.^l(3) - (1-pval).^l(4))/l(2); rp = abs(rval-rp);
github
lcnhappe/happe-master
correct_mc.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/correct_mc.m
5,698
utf_8
92f18a363d2fec001a50fafbcf9e06b5
% correct_mc() - compute an upper limit for the number of independant % time-frequency estimate in a given time-frequency image. % This number can be used to correct for multiple comparisons. % % Usage: % [ncorrect array] = correct_mc( EEG, cycles, maxfreq, timesout); % % Inputs: % EEG - EEGLAB structure % cycles - [float] same as the cycle input to timef(). Default is [3 0.5]. % freqrange - [float] minimum and maximum frequency. Default is [2 50] Hz. % timesout - [integer] array of number of time points to test. % % Output: % ncorrect - number of independant tf estimate in the time-freq image % array - array of size (freqs x timesout) containing pvalues. % % Method details: % % Dividing by the total number of time-frequency estimate in the 2-D % time-frequency image decomposition would be too conservative since % spectral estimates of neighboring time-frequency points are highly % correlated. One must thus estimate the number of independent % time-frequency points in the TF image. Here, I used geometrical wavelets % which are optimal in terms of image compression, so neighboring % frequencies can be assume to carry independent spectral estimates. % We thus had time-frequency decompositions at only X frequencies (e.g. 120, % 60, 30, 15, 7.5, 3.25, 1.625 Hz). For each frequency, I then found % the minimum number of time points for which there was a significant % correlation of the spectral estimates between neighboring time points % (for each frequency and number of time point, I computed the correlation % from 0 to 1 for all data channel to obtain an a probability distribution % of correlation; we then fitted this distribution using a 4th order curve % (Ramberg, J. S., E. J. Dudewicz, et al. (1979). "A probability % distribution and its uses in fitting data." Technometrics 21(2)) and % assessed the probability of significance for the value 0 (no correlation) % to be within the distribution of estimated correlation). For instance, % using 28 time points at 120 Hz, there was no significant (p>0.05 taking % into account Bonferoni correction for multiple comparisons) correlation % between neighboring time-frequency power estimate, but there was a % significant correlation using 32 time points instead of 28 (p<0.05). % Applying the same approach for the X geometrical frequencies and summing % the minimum number of time points for observing a significant correlation % at all frequencies, ones obtain in general a number below 200 (with the % defaults above and 3-second data epochs) independent estimates. In all % the time-frequency plots, one has to used a significance mask at p<0.00025 % (0.05/200). An alternative method for correcting for multiple comparisons % is presented in Nichols & Holmes, Human Brain Mapping, 2001. % % Author: Arnaud Delorme, SCCN, Jan 17, 2004 % Copyright (C) 2004 Arnaud Delorme, SCCN, [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 [ncorrect, pval] = correct_mc( EEG, cycles, freqrange, timesout); if nargin < 1 help correct_mc; return; end; if nargin < 2 cycles = [3 0.5]; end; if nargin < 3 freqrange = [2 50]; end; if nargin < 4 % possible number of time outputs % ------------------------------- timesout = [5 6 7 8 9 10 12 14 16 18 20 24 28 32 36 40]; end; nfreqs = ceil(log2(freqrange(2))); % scan times % ---------- for ti = 1:length(timesout) clear tmpf % scan data channels % ------------------ for index = 1:EEG.nbchan clf; [ersp,itc,powbase,times,freqs,erspboot,itcboot] = newtimef(EEG.data(index,:),EEG.pnts, ... [EEG.xmin EEG.xmax]*1000,EEG.srate, cycles, 'timesout', timesout(ti), ... 'freqscale', 'log', 'nfreqs', nfreqs, 'freqrange', freqrange, 'plotitc', 'off', 'plotersp', 'off'); % compute correlation % ------------------- for fi = 1:length(freqs) tmp = corrcoef(ersp(fi,1:end-1), ersp(fi,2:end)); tmpf(index,fi) = tmp(2,1); end; end; % fit curve and determine if the result is significant % ---------------------------------------------------- for fi = 1:length(freqs) pval(fi, ti) = rsfit(tmpf(:,fi)', 0); if pval(fi,ti) > 0.9999, pval(fi,ti) = NaN; end; end; end; % find minimum number of points for each frequency % ------------------------------------------------ ncorrect = 0; threshold = 0.05 / prod(size(pval)); for fi = 1:size(pval,1) ti = 1; while ti <= size(pval,2) if pval(fi,ti) < threshold ncorrect = ncorrect + timesout(ti); ti = size(pval,2)+1; end; ti = ti+1; end; end;
github
lcnhappe/happe-master
pac.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/pac.m
21,849
utf_8
a7d13b249d1c873e24a0f43a7cda2c5c
% pac() - compute phase-amplitude coupling (power of first input % correlation with phase of second). There is no graphical output % to this function. % % Usage: % >> pac(x,y,srate); % >> [coh,timesout,freqsout1,freqsout2,cohboot] ... % = pac(x,y,srate,'key1', 'val1', 'key2', val2' ...); % Inputs: % x = [float array] 2-D data array of size (times,trials) or % 3-D (1,times,trials) % y = [float array] 2-D or 3-d data array % srate = data sampling rate (Hz) % % Most important optional inputs % 'method' = ['mod'|'corrsin'|'corrcos'|'latphase'] modulation % method or correlation of amplitude with sine or cosine of % angle (see ref). 'laphase' compute the phase % histogram at a specific time and requires the % 'powerlat' option to be set. % 'freqs' = [min max] frequency limits. Default [minfreq 50], % minfreq being determined by the number of data points, % cycles and sampling frequency. Use 0 for minimum frequency % to compute default minfreq. You may also enter an % array of frequencies for the spectral decomposition % (for FFT, closest computed frequency will be returned; use % 'padratio' to change FFT freq. resolution). % 'freqs2' = [float array] array of frequencies for the second % argument. 'freqs' is used for the first argument. % By default it is the same as 'freqs'. % 'wavelet' = 0 -> Use FFTs (with constant window length) { Default } % = >0 -> Number of cycles in each analysis wavelet % = [cycles expfactor] -> if 0 < expfactor < 1, the number % of wavelet cycles expands with frequency from cycles % If expfactor = 1, no expansion; if = 0, constant % window length (as in FFT) {default wavelet: 0} % = [cycles array] -> cycle for each frequency. Size of array % must be the same as the number of frequencies % {default cycles: 0} % 'wavelet2' = same as 'wavelet' for the second argument. Default is % same as cycles. Note that if the lowest frequency for X % and Y are different and cycle is [cycles expfactor], it % may result in discrepencies in the number of cycles at % the same frequencies for X and Y. % 'ntimesout' = Number of output times (int<frames-winframes). Enter a % negative value [-S] to subsample original time by S. % 'timesout' = Enter an array to obtain spectral decomposition at % specific time values (note: algorithm find closest time % point in data and this might result in an unevenly spaced % time array). Overwrite 'ntimesout'. {def: automatic} % 'powerlat' = [float] latency in ms at which to compute phase % histogram % 'tlimits' = [min max] time limits in ms. % % Optional Detrending: % 'detrend' = ['on'|'off'], Linearly detrend each data epoch {'off'} % 'rmerp' = ['on'|'off'], Remove epoch mean from data epochs {'off'} % % Optional FFT/DFT Parameters: % 'winsize' = If cycles==0: data subwindow length (fastest, 2^n<frames); % If cycles >0: *longest* window length to use. This % determines the lowest output frequency. Note that this % parameter is overwritten if the minimum frequency has been set % manually and requires a longer time window {~frames/8} % 'padratio' = FFT-length/winframes (2^k) {2} % Multiplies the number of output frequencies by dividing % their spacing (standard FFT padding). When cycles~=0, % frequency spacing is divided by padratio. % 'nfreqs' = number of output frequencies. For FFT, closest computed % frequency will be returned. Overwrite 'padratio' effects % for wavelets. Default: use 'padratio'. % 'freqscale' = ['log'|'linear'] frequency scale. Default is 'linear'. % Note that for obtaining 'log' spaced freqs using FFT, % closest correspondant frequencies in the 'linear' space % are returned. % 'subitc' = ['on'|'off'] subtract stimulus locked Inter-Trial Coherence % (ITC) from x and y. This computes the 'intrinsic' coherence % x and y not arising from common synchronization to % experimental events. See notes. {default: 'off'} % 'itctype' = ['coher'|'phasecoher'] For use with 'subitc', see timef() % for more details {default: 'phasecoher'}. % 'subwin' = [min max] sub time window in ms (this windowing is % performed after the spectral decomposition). % % Outputs: % pac = Matrix (nfreqs1,nfreqs2,timesout) of coherence (complex). % Use 20*log(abs(crossfcoh)) to vizualize log spectral diffs. % timesout = Vector of output times (window centers) (ms). % freqsout1 = Vector of frequency bin centers for first argument (Hz). % freqsout2 = Vector of frequency bin centers for second argument (Hz). % alltfX = single trial spectral decomposition of X % alltfY = single trial spectral decomposition of Y % % Author: Arnaud Delorme, SCCN/INC, UCSD 2005- % % Ref: Testing for Nested Oscilations (2008) J Neuro Methods 174(1):50-61 % % See also: timefreq(), crossf() % Copyright (C) 2002 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [crossfcoh, timesout1, freqs1, freqs2, crossfcohall, alltfX, alltfY] = pac(X, Y, srate, varargin); if nargin < 1 help pac; return; end; % deal with 3-D inputs % -------------------- if ndims(X) == 3, X = reshape(X, size(X,2), size(X,3)); end; if ndims(Y) == 3, Y = reshape(Y, size(Y,2), size(Y,3)); end; frame = size(X,2); g = finputcheck(varargin, ... { 'alpha' 'real' [0 0.2] []; 'baseboot' 'float' [] 0; 'boottype' 'string' {'times','trials','timestrials'} 'timestrials'; 'detrend' 'string' {'on','off'} 'off'; 'freqs' 'real' [0 Inf] [0 srate/2]; 'freqs2' 'real' [0 Inf] []; 'freqscale' 'string' { 'linear','log' } 'linear'; 'itctype' 'string' {'phasecoher','phasecoher2','coher'} 'phasecoher'; 'nfreqs' 'integer' [0 Inf] []; 'lowmem' 'string' {'on','off'} 'off'; 'method' 'string' { 'mod','corrsin','corrcos','latphase' } 'mod'; 'naccu' 'integer' [1 Inf] 250; 'newfig' 'string' {'on','off'} 'on'; 'padratio' 'integer' [1 Inf] 2; 'rmerp' 'string' {'on','off'} 'off'; 'rboot' 'real' [] []; 'subitc' 'string' {'on','off'} 'off'; 'subwin' 'real' [] []; ... 'gammapowerlim' 'real' [] []; ... 'powerlim' 'real' [] []; ... 'powerlat' 'real' [] []; ... 'gammabase' 'real' [] []; ... 'timesout' 'real' [] []; ... 'ntimesout' 'integer' [] 200; ... 'tlimits' 'real' [] [0 frame/srate]; 'title' 'string' [] ''; 'vert' { 'real','cell' } [] []; 'wavelet' 'real' [0 Inf] 0; 'wavelet2' 'real' [0 Inf] []; 'winsize' 'integer' [0 Inf] max(pow2(nextpow2(frame)-3),4) }, 'pac'); if isstr(g), error(g); end; % more defaults % ------------- if isempty(g.wavelet2), g.wavelet2 = g.wavelet; end; if isempty(g.freqs2), g.freqs2 = g.freqs; end; % remove ERP if necessary % ----------------------- X = squeeze(X); Y = squeeze(Y);X = squeeze(X); trials = size(X,2); if strcmpi(g.rmerp, 'on') X = X - repmat(mean(X,2), [1 trials]); Y = Y - repmat(mean(Y,2), [1 trials]); end; % perform timefreq decomposition % ------------------------------ [alltfX freqs1 timesout1] = timefreq(X, srate, 'ntimesout', g.ntimesout, 'timesout', g.timesout, 'winsize', g.winsize, ... 'tlimits', g.tlimits, 'detrend', g.detrend, 'itctype', g.itctype, ... 'subitc', g.subitc, 'wavelet', g.wavelet, 'padratio', g.padratio, ... 'freqs', g.freqs, 'freqscale', g.freqscale, 'nfreqs', g.nfreqs); [alltfY freqs2 timesout2] = timefreq(Y, srate, 'ntimesout', g.ntimesout, 'timesout', g.timesout, 'winsize', g.winsize, ... 'tlimits', g.tlimits, 'detrend', g.detrend, 'itctype', g.itctype, ... 'subitc', g.subitc, 'wavelet', g.wavelet2, 'padratio', g.padratio, ... 'freqs', g.freqs2, 'freqscale', g.freqscale, 'nfreqs', g.nfreqs); % check time limits % ----------------- if ~isempty(g.subwin) ind1 = find(timesout1 > g.subwin(1) & timesout1 < g.subwin(2)); ind2 = find(timesout2 > g.subwin(1) & timesout2 < g.subwin(2)); alltfX = alltfX(:, ind1, :); alltfY = alltfY(:, ind2, :); timesout1 = timesout1(ind1); timesout2 = timesout2(ind2); end; if length(timesout1) ~= length(timesout2) | any( timesout1 ~= timesout2) disp('Warning: Time points are different for X and Y. Use ''timesout'' to specify common time points'); [vals ind1 ind2 ] = intersect_bc(timesout1, timesout2); fprintf('Searching for common time points: %d found\n', length(vals)); if length(vals) < 10, error('Less than 10 common data points'); end; timesout1 = vals; timesout2 = vals; alltfX = alltfX(:, ind1, :); alltfY = alltfY(:, ind2, :); end; % scan accross frequency and time % ------------------------------- %if isempty(g.alpha) % disp('Warning: if significance mask is not applied, result might be slightly') % disp('different (since angle is not made uniform and amplitude interpolated)') %end; cohboot =[]; if ~strcmpi(g.method, 'latphase') for find1 = 1:length(freqs1) for find2 = 1:length(freqs2) for ti = 1:length(timesout1) % get data % -------- tmpalltfx = squeeze(alltfX(find1,ti,:)); tmpalltfy = squeeze(alltfY(find2,ti,:)); %if ~isempty(g.alpha) % tmpalltfy = angle(tmpalltfy); % tmpalltfx = abs( tmpalltfx); % [ tmp cohboot(find1,find2,ti,:) newamp newangle ] = ... % bootcircle(tmpalltfx, tmpalltfy, 'naccu', g.naccu); % crossfcoh(find1,find2,ti) = sum ( newamp .* exp(j*newangle) ); %else tmpalltfy = angle(tmpalltfy); tmpalltfx = abs( tmpalltfx); if strcmpi(g.method, 'mod') crossfcoh(find1,find2,ti) = sum( tmpalltfx .* exp(j*tmpalltfy) ); elseif strcmpi(g.method, 'corrsin') tmp = corrcoef( sin(tmpalltfy), tmpalltfx); crossfcoh(find1,find2,ti) = tmp(2); else tmp = corrcoef( cos(tmpalltfy), tmpalltfx); crossfcoh(find1,find2,ti) = tmp(2); end; end; end; end; elseif 1 % this option computes power at a given latency % then computes the same as above (vectors) %if isempty(g.powerlat) % error('You need to specify a latency for the ''powerlat'' option'); %end; gammapower = mean(10*log10(alltfX(:,:,:).*conj(alltfX)),1); % average all frequencies for power if isempty(g.gammapowerlim) g.gammapowerlim = [ min(gammapower(:)) max(gammapower(:)) ]; end; fprintf('Gamma power limits: %3.2f to %3.2f\n', g.gammapowerlim(1), g.gammapowerlim(2)); power = 10*log10(alltfY(:,:,:).*conj(alltfY)); if isempty(g.powerlim) for freq = 1:size(power,1) g.powerlim(freq,:) = [ min(power(freq,:)) max(power(freq,:)) ]; end; end; for freq = 1:size(power,1) fprintf('Freq %d power limits: %3.2f to %3.2f\n', freqs2(freq), g.powerlim(freq,1), g.powerlim(freq,2)); end; % power plot %figure; plot(timesout2/1000, (mean(power(9,:,:),3)-mean(power(9,:)))/50); %hold on; plot(linspace(0, length(Y)/srate, length(Y)), mean(Y'), 'g'); % phase with power % figure; plot(timesout2/1000, (mean(phaseangle(9,:,:),3)-mean(phaseangle(9,:)))/50); % hold on; plot(timesout1/1000, (mean(gammapower,3)-mean(gammapower(:)))/100, 'r'); %figure; plot((mean(phaseangle(9,:,:),3)-mean(phaseangle(9,:)))/50+j*(mean(gammapower,3)-mean(gammapower(:)))/100, '.'); matsize = 32; matcenter = (matsize-1)/2+1; matrixfinalgammapower = zeros(size(alltfY,1),size(alltfX,3),matsize,matsize); matrixfinalcount = zeros(size(alltfY,1),size(alltfX,3),matsize,matsize); % get power indices if isempty(g.gammabase) g.gammabase = mean(gammapower(:)); end; fprintf('Gamma power average: %3.2f\n', g.gammabase); gammapoweradd = gammapower-g.gammabase; gammapower = floor((gammapower-g.gammapowerlim(1))/(g.gammapowerlim(2)-g.gammapowerlim(1))*(matsize-2))+1; phaseangle = angle(alltfY); posx = zeros(size(power)); posy = zeros(size(power)); for freq = 1:length(freqs2) fprintf('Processing frequency %3.2f\n', freqs2(freq)); power(freq,:,:) = (power(freq,:,:)-g.powerlim(freq,1))/(g.powerlim(freq,2)-g.powerlim(freq,1))*(matsize-3)/2+1; complexval = power(freq,:,:).*exp(j*phaseangle(freq,:,:)); posx(freq,:,:) = round(real(complexval)+matcenter); posy(freq,:,:) = round(imag(complexval)+matcenter); for trial = 1:size(alltfX,3) % scan trials for time = 1:size(alltfX,2) %matrixfinal(freq,posx(freq,time,trial),posy(freq,time,trial),gammapower(1,time,trial)) = ... % matrixfinal(freq,posx(freq,time,trial),posy(freq,time,trial),gammapower(1,time,trial))+1; matrixfinalgammapower(freq,trial,posx(freq,time,trial),posy(freq,time,trial)) = ... matrixfinalgammapower(freq,trial,posx(freq,time,trial),posy(freq,time,trial))+gammapoweradd(1,time,trial); matrixfinalcount(freq,trial,posx(freq,time,trial),posy(freq,time,trial)) = ... matrixfinalcount(freq,trial,posx(freq,time,trial),posy(freq,time,trial))+1; end; end; %matrixfinal(freq,:,:,:) = convn(squeeze(matrixfinal(freq,:,:,:)), gs, 'same'); %tmpmat = posx(index,:)+(posy(index,:)-1)*64+(gammapower(:)-1)*64*64; matrixfinalcount(freq, find(matrixfinalcount(freq,:) == 0)) = 1; matrixfinalgammapower(freq,:,:,:) = matrixfinalgammapower(freq,:,:,:)./matrixfinalcount(freq,:,:,:); end; % average and smooth matrixfinalgammapowermean = squeeze(mean(matrixfinalgammapower,2)); for freq = 1:length(freqs2) matrixfinalgammapowermean(freq,:,:) = conv2(squeeze(matrixfinalgammapowermean(freq,:,:)), gauss2d(5,5), 'same'); end; %matrixfinalgammapower = matrixfinalgammapower/size(alltfX,3)/size(alltfX,2); %vect = linspace(-pi,pi,50); %for f = 1:length(freqs2) % crossfcoh(f,:) = hist(tmpalltfy(f,:), vect); %end; % smoothing of output image % ------------------------- %gs = gauss2d(6, 6, 6); %crossfcoh = convn(crossfcoh, gs, 'same'); %freqs1 = freqs2; %timesout1 = linspace(-180, 180, size(crossfcoh,2)); crossfcoh = matrixfinalgammapowermean; crossfcohall = matrixfinalgammapower; else % this option computes power at a given latency % then computes the same as above (vectors) %if isempty(g.powerlat) % error('You need to specify a latency for the ''powerlat'' option'); %end; gammapower = mean(10*log10(alltfX(:,:,:).*conj(alltfX)),1); % average all frequencies for power if isempty(g.gammapowerlim) g.gammapowerlim = [ min(gammapower(:)) max(gammapower(:)) ]; end; power = 10*log10(alltfY(:,:,:).*conj(alltfY)); if isempty(g.powerlim) for freq = 1:size(power,1) g.powerlim(freq,:) = [ min(power(freq,:)) max(power(freq,:)) ]; end; end; % power plot %figure; plot(timesout2/1000, (mean(power(9,:,:),3)-mean(power(9,:)))/50); %hold on; plot(linspace(0, length(Y)/srate, length(Y)), mean(Y'), 'g'); % phase with power % figure; plot(timesout2/1000, (mean(phaseangle(9,:,:),3)-mean(phaseangle(9,:)))/50); % hold on; plot(timesout1/1000, (mean(gammapower,3)-mean(gammapower(:)))/100, 'r'); %figure; plot((mean(phaseangle(9,:,:),3)-mean(phaseangle(9,:)))/50+j*(mean(gammapower,3)-mean(gammapower(:)))/100, '.'); matsize = 64; matcenter = (matsize-1)/2+1; matrixfinal = zeros(size(alltfY,1),64,64,64); matrixfinalgammapower = zeros(size(alltfY,1),matsize,matsize); matrixfinalcount = zeros(size(alltfY,1),matsize,matsize); % get power indices gammapoweradd = gammapower-mean(gammapower(:)); gammapower = floor((gammapower-g.gammapowerlim(1))/(g.gammapowerlim(2)-g.gammapowerlim(1))*(matsize-1))+1; phaseangle = angle(alltfY); posx = zeros(size(power)); posy = zeros(size(power)); gs = gauss3d(6, 6, 6); for freq = 1:size(alltfY) fprintf('Processing frequency %3.2f\n', freqs2(freq)); power(freq,:,:) = (power(freq,:,:)-g.powerlim(freq,1))/(g.powerlim(freq,2)-g.powerlim(freq,1))*(matsize-2)/2; complexval = power(freq,:,:).*exp(j*phaseangle(freq,:,:)); posx(freq,:,:) = round(real(complexval)+matcenter); posy(freq,:,:) = round(imag(complexval)+matcenter); for trial = 1:size(alltfX,3) % scan trials for time = 1:size(alltfX,2) %matrixfinal(freq,posx(freq,time,trial),posy(freq,time,trial),gammapower(1,time,trial)) = ... % matrixfinal(freq,posx(freq,time,trial),posy(freq,time,trial),gammapower(1,time,trial))+1; matrixfinalgammapower(freq,posx(freq,time,trial),posy(freq,time,trial)) = ... matrixfinalgammapower(freq,posx(freq,time,trial),posy(freq,time,trial))+gammapoweradd(1,time,trial); matrixfinalcount(freq,posx(freq,time,trial),posy(freq,time,trial)) = ... matrixfinalcount(freq,posx(freq,time,trial),posy(freq,time,trial))+1; end; end; %matrixfinal(freq,:,:,:) = convn(squeeze(matrixfinal(freq,:,:,:)), gs, 'same'); %tmpmat = posx(index,:)+(posy(index,:)-1)*64+(gammapower(:)-1)*64*64; matrixfinalcount(freq, find(matrixfinalcount(freq,:) == 0)) = 1; matrixfinalgammapower(freq,:,:) = matrixfinalgammapower(freq,:,:)./matrixfinalcount(freq, :,:); matrixfinalgammapower(freq,:,:) = conv2(squeeze(matrixfinalgammapower(freq,:,:)), gauss2d(5,5), 'same'); end; %matrixfinalgammapower = matrixfinalgammapower/size(alltfX,3)/size(alltfX,2); %vect = linspace(-pi,pi,50); %for f = 1:length(freqs2) % crossfcoh(f,:) = hist(tmpalltfy(f,:), vect); %end; % smoothing of output image % ------------------------- %gs = gauss2d(6, 6, 6); %crossfcoh = convn(crossfcoh, gs, 'same'); %freqs1 = freqs2; %timesout1 = linspace(-180, 180, size(crossfcoh,2)); crossfcoh = matrixfinalgammapower; end; % 7/31/2014 Ramon: crossfcohall sometimes does not exist depending on choice of input options if ~exist('crossfcohall', 'var') crossfcohall = []; end
github
lcnhappe/happe-master
bootstat.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/bootstat.m
20,825
utf_8
406a9744b6812cd9f9f1eed16ca63e82
% bootstat() - accumulate surrogate data to assess significance by permutation of some % measure of two input variables. % % If 'distfit','on', fits the psd with a 4th-order polynomial using the % data kurtosis, as in Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., % Mykkytka, E.F. "A probability distribution and its uses in fitting data." % Technometrics, 21:201-214, 1979. % Usage: % >> [rsignif,rboot] = bootstat( { arg1 arg2 ...}, formula, varargin ...); % Inputs: % arg1 - [array] 1-D, 2-D or 3-D array of values % arg2 - [array] 1-D, 2-D or 3-D array of values % formula - [string] formula to compute the given measure. Takes arguments % 'arg1', 'arg2' as inputs and 'res' (result, by default) as output. % For data arrays of more than 1 dimension, the formula must be iterative % so that shuffling can occur at each step while scanning the last % array dimension. Examples: % 'res = arg1 - arg2' % difference of two 1-D data arrays % 'res = mean( arg1 .* arg2)' % mean projection of two 1-D data arrays % 'res = res + arg1 .* conj(arg2)' % iterative, for use with 2|3-D arrays % Optional inputs: % 'boottype ' - ['rand'|'shuffle'] % 'rand' = do not shuffle data. Only flip polarity randomly (for real % number) or phase (for complex numbers). % 'shuffle' = shuffle values of first argument (see two options below). % Default. % 'shuffledim' - [integer] indices of dimensions to shuffle. For instance, [1 2] will % shuffle the first two dimensions. Default is to shuffle along % dimension 2. % 'shufflemode' - ['swap'|'regular'] shuffle mode. Either swap dimensions (for instance % swap rows then columns if dimension [1 2] are selected) or shuffle % in each dimension independently (slower). If only one dimension is % selected for shuffling, this option does not change the result. % 'randmode' - ['opposite'|'inverse'] randomize sign (or phase for complex number, % or randomly set half the value to reference. % 'alpha' - [real] significance level (between 0 and 1) {default 0.05}. % 'naccu' - [integer] number of exemplars to accumulate {default 200}. % 'bootside' - ['both'|'upper'] side of the surrogate distribution to % consider for significance. This parameter affects the size % of the last dimension of the accumulation array ('accres') % (size is 2 for 'both' and 1 for 'upper') {default: 'both'}. % 'basevect' - [integer vector] time vector indices for baseline in second dimension. % {default: all time points}. % 'rboot' - accumulation array (from a previous call). Allows faster % computation of the 'rsignif' output {default: none}. % 'formulaout' - [string] name of the computed variable {default: 'res'}. % 'dimaccu' - [integer] use dimension in result to accumulate data. % For instance if the result array is size [60x50] and this value is 2, % the function will consider than 50 times 60 value have been accumulated. % % Fitting distribution: % 'distfit' - ['on'|'off'] fit distribution with known function to compute more accurate % limits or exact p-value (see 'vals' option). The MATLAB statistical toolbox % is required. This option is currently implemented only for 1-D data. % 'vals' - [float array] significance values. 'alpha' is ignored and % rsignif returns the p-values. Requires 'distfit' (see above). % This option currently implemented only for 1-D data. % 'correctp' - [phat pci zerofreq] parameters for correcting for a biased probability % distribution (requires 'distfit' above). See help of correctfit(). % Outputs: % rsignif - significance arrays. 2 values (low high) for each point (use % 'alpha' to change these limits). % rboot - accumulated surrogate data values. % % Authors: Arnaud Delorme, Bhaktivedcanta Institute, Mumbai, India, Nov 2004 % % See also: timef() % NOTE: There is an undocumented parameter, 'savecoher', [0|1] % HELP TEXT REMOVED: (Ex: Using option 'both', coherence during baseline would be % ignored since times are shuffled during each accumulation. % Copyright (C) 9/2002 Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD % % 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 % ************************************* % To fit the psd with as 4th order polynomial using the distribution kurtosis, % Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F. % "A probability distribution and its uses in fitting data." % Technimetrics, 1979, 21: 201-214. % ************************************* function [accarrayout, Rbootout, Rbootout2] = bootstat(oriargs, formula, varargin) % nb_points, timesout, naccu, baselength, baseboot, boottype, alpha, rboot); if nargin < 2 help bootstat; return; end; if ~isstr(formula) error('The second argument must be a string formula'); end; g = finputcheck(varargin, ... { 'dims' 'integer' [] []; ... 'naccu' 'integer' [0 10000] 200; ... 'bootside' 'string' { 'both','upper' } 'both'; ... 'basevect' 'integer' [] []; ... 'boottype' 'string' { 'rand','shuffle' } 'shuffle'; ... 'shufflemode' 'string' { 'swap','regular' } 'swap'; ... 'randmode' 'string' { 'opposite','inverse' } 'opposite'; ... 'shuffledim' 'integer' [0 Inf] []; ... 'label' 'string' [] formula; ... 'alpha' 'real' [0 1] 0.05; ... 'vals' 'real' [] []; ... 'distfit' 'string' {'on','off' } 'off'; ... 'dimaccu' 'integer' [1 Inf] []; ... 'correctp' 'real' [] []; ... 'rboot' 'real' [] NaN }); if isstr(g) error(g); end; if isempty(g.shuffledim) & strcmpi(g.boottype, 'rand') g.shuffledim = []; elseif isempty(g.shuffledim) g.shuffledim = 2; end; unitname = ''; if 2/g.alpha > g.naccu if strcmpi(g.distfit, 'off') | ~((size(oriarg1,1) == 1 | size(oriarg1,2) == 1) & size(oriarg1,3) == 1) g.naccu = 2/g.alpha; fprintf('Adjusting naccu to compute alpha value'); end; end; if isempty(g.rboot) g.rboot = NaN; end; % function for bootstrap computation % ---------------------------------- if ~iscell(oriargs) | length(oriargs) == 1, oriarg1 = oriargs; oriarg2 = []; else oriarg1 = oriargs{1}; oriarg2 = oriargs{2}; end; [nb_points times trials] = size(oriarg1); if times == 1, disp('Warning 1 value only for shuffling dimension'); end; % only consider baseline % ---------------------- if ~isempty(g.basevect) fprintf('\nPermutation statistics baseline length is %d (out of %d) points\n', length(g.basevect), times); arg1 = oriarg1(:,g.basevect,:); if ~isempty(oriarg2) arg2 = oriarg2(:,g.basevect,:); end; else arg1 = oriarg1; arg2 = oriarg2; end; % formula for accumulation array % ------------------------------ % if g.dimaccu is not empty, accumulate over that dimension % of the resulting array to speed up computation formula = [ 'res=' formula ]; g.formulapost = [ 'if index == 1, ' ... ' if ~isempty(g.dimaccu), ' ... ' Rbootout= zeros([ ceil(g.naccu/size(res,g.dimaccu)) size( res ) ]);' ... ' else,' ... ' Rbootout= zeros([ g.naccu size( res ) ]);' ... ' end;' ... 'end,' ... 'Rbootout(count,:,:,:) = res;' ... 'count = count+1;' ... 'if ~isempty(g.dimaccu), ' ... ' index = index + size(res,g.dimaccu);' ... ' fprintf(''%d '', index-1);' ... 'else ' ... ' index=index+1;' ... ' if rem(index,10) == 0, fprintf(''%d '', index); end;' ... ' if rem(index,100) == 0, fprintf(''\n''); end;' ... 'end;' ]; % ************************** % case 1: precomputed values % ************************** if ~isnan(g.rboot) Rbootout = g.rboot; % *********************************** % case 2: randomize polarity or phase % *********************************** elseif strcmpi(g.boottype, 'rand') & strcmpi(g.randmode, 'inverse') fprintf('Bootstat function: randomize inverse values\n'); fprintf('Processing permutation statistics for %s (naccu=%d):', g.label, g.naccu); % compute random array % -------------------- multarray = ones(size(arg1)); totlen = prod(size(arg1)); if isreal(arg1), multarray(1:round(totlen/2)) = 0; end; for shuff = 1:ndims(multarray) multarray = supershuffle(multarray,shuff); % initial shuffling end; if isempty(g.shuffledim), g.shuffledim = 1:ndims(multarray); end; invarg1 = 1./arg1; % accumulate % ---------- index = 1; count = 1; while index <= g.naccu for shuff = g.shuffledim multarray = supershuffle(multarray,shuff); end; tmpinds = find(reshape(multarray, 1, prod(size(multarray)))); arg1 = oriarg1; arg1(tmpinds) = invarg1(tmpinds); eval([ formula ';' ]); eval( g.formulapost ); % also contains index = index+1 end elseif strcmpi(g.boottype, 'rand') % opposite fprintf('Bootstat function: randomize polarity or phase\n'); fprintf('Processing permutation statistics for %s (naccu=%d):', g.label, g.naccu); % compute random array % -------------------- multarray = ones(size(arg1)); totlen = prod(size(arg1)); if isreal(arg1), multarray(1:round(totlen/2)) = -1; else tmparray = exp(j*linspace(0,2*pi,totlen+1)); multarray(1:totlen) = tmparray(1:end-1); end; for shuff = 1:ndims(multarray) multarray = supershuffle(multarray,shuff); % initial shuffling end; if isempty(g.shuffledim), g.shuffledim = 1:ndims(multarray); end; % accumulate % ---------- index = 1; count = 1; while index <= g.naccu for shuff = g.shuffledim multarray = supershuffle(multarray,shuff); end; arg1 = arg1.*multarray; eval([ formula ';' ]); eval( g.formulapost ); % also contains index = index+1 end % ******************************************** % case 3: shuffle vector of only one dimension % ******************************************** elseif length(g.shuffledim) == 1 fprintf('Bootstat function: shuffling along dimension %d only\n', g.shuffledim); fprintf('Processing permutation statistics for %s (naccu=%d):', g.label, g.naccu); index = 1; count = 1; while index <= g.naccu arg1 = shuffleonedim(arg1,g.shuffledim); eval([ formula ';' ]); eval( g.formulapost ); end % *********************************************** % case 5: shuffle vector along several dimensions % *********************************************** else if strcmpi(g.shufflemode, 'swap') % swap mode fprintf('Bootstat function: shuffling along dimension %s (swap mode)\n', int2str(g.shuffledim)); fprintf('Processing permutation statistics for %s (naccu=%d):', g.label, g.naccu); index = 1; count = 1; while index <= g.naccu for shuff = g.shuffledim arg1 = supershuffle(arg1,shuff); end; eval([ formula ';' ]); eval( g.formulapost ); end else % regular shuffling fprintf('Bootstat function: shuffling along dimension %s (regular mode)\n', int2str(g.shuffledim)); fprintf('Processing permutation statistics for %s (naccu=%d):', g.label, g.naccu); index = 1; count = 1; while index <= g.naccu for shuff = g.shuffledim arg1 = shuffleonedim(arg1,shuff); end; eval([ formula ';' ]); eval( g.formulapost ); end end; end; Rbootout(count:end,:,:,:) = []; % ********************** % assessing significance % ********************** % get accumulation array % ---------------------- accarray = Rbootout; if ~isreal(accarray) accarray = sqrt(accarray .* conj(accarray)); % faster than abs() end; % reshape the output if necessary % ------------------------------- if ~isempty(g.dimaccu) if g.dimaccu+1 == 3 accarray = permute( accarray, [1 3 2]); end; accarray = reshape( accarray, size(accarray,1)*size(accarray,2), size(accarray,3) ); end; if size(accarray,1) == 1, accarray = accarray'; end; % first dim contains g.naccu % ****************************************************** % compute thresholds on array not fitting a distribution % ****************************************************** if strcmpi(g.distfit, 'off') % compute bootstrap significance level % ------------------------------------ accarray = sort(accarray,1); % always sort on naccu Rbootout2 = accarray; i = round(size(accarray,1)*g.alpha); accarray1 = squeeze(mean(accarray(size(accarray,1)-i+1:end,:,:),1)); accarray2 = squeeze(mean(accarray(1:i ,:,:),1)); if abs(accarray(1,1,1) - accarray(end,1,1)) < abs(accarray(1,1,1))*1e-15 accarray1(:) = NaN; accarray2(:) = NaN; end; else % ******************* % fit to distribution % ******************* sizerboot = size (accarray); accarray1 = zeros(sizerboot(2:end)); accarray2 = zeros(sizerboot(2:end)); if ~isempty(g.vals{index}) if ~all(size(g.vals{index}) == sizerboot(2:end) ) error('For fitting, vals must have the same dimension as the output array (try transposing)'); end; end; % fitting with Ramberg-Schmeiser distribution % ------------------------------------------- if ~isempty(g.vals{index}) % compute significance for value for index1 = 1:size(accarrayout,1) for index2 = 1:size(accarrayout,2) accarray1(index1,index2) = 1 - rsfit(squeeze(accarray(:,index1,index2)), g.vals{index}(index1, index2)); if length(g.correctp) == 2 accarray1(index1,index2) = correctfit(accarray1, 'gamparams', [g.correctp 0]); % no correction for p=0 else accarray1(index1,index2) = correctfit(accarray1, 'gamparams', g.correctp); end; end; end; else % compute value for significance for index1 = 1:size(accarrayout,1) for index2 = 1:size(accarrayout,2) [p c l chi2] = rsfit(Rbootout(:),0); pval = g.alpha; accarray1(index1,index2) = l(1) + (pval.^l(3) - (1-pval).^l(4))/l(2); pval = 1-g.alpha; accarray2(index1,index2) = l(1) + (pval.^l(3) - (1-pval).^l(4))/l(2); end; end; end; % plot results % ------------------------------------- % figure; % hist(abs(Rbootout)); tmpax = axis; % hold on; % valcomp = linspace(min(abs(Rbootout(:))), max(abs(Rbootout(:))), 100); % normy = normpdf(valcomp, mu, sigma); % plot(valcomp, normy/max(normy)*tmpax(4), 'r'); % return; end; % set output array: backward compatible % ------------------------------------- if strcmpi(g.bootside, 'upper'); % only upper significance accarrayout = accarray1; else if size(accarray1,1) ~= 1 & size(accarray1,2) ~= 1 accarrayout = accarray2; accarrayout(:,:,2) = accarray1; else accarrayout = [ accarray2(:) accarray1(:) ]; end; end; accarrayout = squeeze(accarrayout); if size(accarrayout,1) == 1 & size(accarrayout,3) == 1, accarrayout = accarrayout'; end; % better but not backward compatible % ---------------------------------- % accarrayout = { accarray1 accarray2 }; return; % fitting with normal distribution (deprecated) % -------------------------------- [mu sigma] = normfit(abs(Rbootout(:))); accarrayout = 1 - normcdf(g.vals, mu, sigma); % cumulative density distribution % formula of normal distribution % y = 1/sqrt(2) * exp( -(x-mu).^2/(sigma*sigma*2) ) / (sqrt(pi)*sigma); % % Gamma and Beta fits: % elseif strcmpi(g.distfit, 'gamma') % [phatgam pcigam] = gamfit(abs(Rbootout(:))); % gamy = gampdf(valcomp, phatgam(1), pcigam(2)) % p = 1 - gamcdf(g.vals, phatgam(1), pcigam(2)); % cumulative density distribution % elseif strcmpi(g.distfit, 'beta') % [phatbeta pcibeta] = betafit(abs(Rbootout(:))); % betay = betapdf(valcomp, phatbeta(1), pcibeta(1)); % p = 1 - betacdf(g.vals, phatbeta(1), pcibeta(1)); % cumulative density distribution % end if strcmpi(g.distfit, 'off') tmpsort = sort(Rbootout); i = round(g.alpha*g.naccu); sigval = [mean(tmpsort(1:i)) mean(tmpsort(g.naccu-i+1:g.naccu))]; if strcmpi(g.bootside, 'upper'), sigval = sigval(2); end; accarrayout = sigval; end; % this shuffling preserve the number of -1 and 1 % for cloumns and rows (assuming matrix size is multiple of 2 % ----------------------------------------------------------- function array = supershuffle(array, dim) if size(array, 1) == 1 | size(array,2) == 1 array = shuffle(array); return; end; if size(array, dim) == 1, return; end; if dim == 1 indrows = shuffle(1:size(array,1)); for index = 1:2:length(indrows)-rem(length(indrows),2) % shuffle rows tmparray = array(indrows(index),:,:); array(indrows(index),:,:) = array(indrows(index+1),:,:); array(indrows(index+1),:,:) = tmparray; end; elseif dim == 2 indcols = shuffle(1:size(array,2)); for index = 1:2:length(indcols)-rem(length(indcols),2) % shuffle colums tmparray = array(:,indcols(index),:); array(:,indcols(index),:) = array(:,indcols(index+1),:); array(:,indcols(index+1),:) = tmparray; end; else ind3d = shuffle(1:size(array,3)); for index = 1:2:length(ind3d)-rem(length(ind3d),2) % shuffle colums tmparray = array(:,:,ind3d(index)); array(:,:,ind3d(index)) = array(:,:,ind3d(index+1)); array(:,:,ind3d(index+1)) = tmparray; end; end; % shuffle one dimension, one row/colums at a time % ----------------------------------------------- function array = shuffleonedim(array, dim) if size(array, 1) == 1 | size(array,2) == 1 array = shuffle(array, dim); else if dim == 1 for index1 = 1:size(array,3) for index2 = 1:size(array,2) array(:,index2,index1) = shuffle(array(:,index2,index1)); end; end; elseif dim == 2 for index1 = 1:size(array,3) for index2 = 1:size(array,1) array(index2,:,index1) = shuffle(array(index2,:,index1)); end; end; else for index1 = 1:size(array,1) for index2 = 1:size(array,2) array(index1,index2,:) = shuffle(array(index1,index2,:)); end; end; end; end;
github
lcnhappe/happe-master
timefreq.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/timefreq.m
33,427
utf_8
dc70f7b5afd51d05bcf926a934072865
% timefreq() - compute time/frequency decomposition of data trials. This % function is a compute-only function called by % the more complete time/frequency functions newtimef() % and newcrossf() which also plot timefreq() results. % % Usage: % >> [tf, freqs, times] = timefreq(data, srate); % >> [tf, freqs, times, itcvals] = timefreq(data, srate, ... % 'key1', 'val1', 'key2', 'val2' ...) % Inputs: % data = [float array] 2-D data array of size (times,trials) % srate = sampling rate % % Optional inputs: % 'cycles' = [real] indicates the number of cycles for the % time-frequency decomposition {default: 0} % if 0, use FFTs and Hanning window tapering. % or [real positive scalar] Number of cycles in each Morlet % wavelet, constant across frequencies. % or [cycles cycles(2)] wavelet cycles increase with % frequency starting at cycles(1) and, % if cycles(2) > 1, increasing to cycles(2) at % the upper frequency, % or if cycles(2) = 0, same window size at all % frequencies (similar to FFT if cycles(1) = 1) % or if cycles(2) = 1, not increasing (same as giving % only one value for 'cycles'). This corresponds to pure % wavelet with the same number of cycles at each frequencies % if 0 < cycles(2) < 1, linear variation in between pure % wavelets (1) and FFT (0). The exact number of cycles % at the highest frequency is indicated on the command line. % 'wavelet' = DEPRECATED, please use 'cycles'. This function does not % support multitaper. For multitaper, use timef(). % 'wletmethod' = ['dftfilt2'|'dftfilt3'] Wavelet method/program to use. % {default: 'dftfilt3'} % 'dftfilt' DEPRECATED. Method used in regular timef() % program. Not available any more. % 'dftfilt2' Morlet-variant or Hanning DFT (calls dftfilt2() % to generate wavelets). % 'dftfilt3' Morlet wavelet or Hanning DFT (exact Tallon % Baudry). Calls dftfilt3(). % 'ffttaper' = ['none'|'hanning'|'hamming'|'blackmanharris'] FFT tapering % function. Default is 'hanning'. Note that 'hamming' and % 'blackmanharris' require the signal processing toolbox. % Optional ITC type: % 'type' = ['coher'|'phasecoher'] Compute either linear coherence % ('coher') or phase coherence ('phasecoher') also known % as phase coupling factor' {default: 'phasecoher'}. % 'subitc' = ['on'|'off'] subtract stimulus locked Inter-Trial Coherence % (ITC) from x and y. This computes the 'intrinsic' coherence % x and y not arising from common synchronization to % experimental events. See notes. {default: 'off'} % % Optional detrending: % 'detrend' = ['on'|'off'], Linearly detrend each data epoch {'off'} % % Optional FFT/DFT parameters: % 'tlimits' = [min max] time limits in ms. % 'winsize' = If cycles==0 (FFT, see 'wavelet' input): data subwindow % length (fastest, 2^n<frames); % if cycles >0: *longest* window length to use. This % determines the lowest output frequency {~frames/8} % 'ntimesout' = Number of output times (int<frames-winsize). Enter a % negative value [-S] to subsample original time by S. % 'timesout' = Enter an array to obtain spectral decomposition at % specific time values (note: algorithm find closest time % point in data and this might result in an unevenly spaced % time array). Overwrite 'ntimesout'. {def: automatic} % 'freqs' = [min max] frequency limits. Default [minfreq srate/2], % minfreq being determined by the number of data points, % cycles and sampling frequency. Enter a single value % to compute spectral decompisition at a single frequency % (note: for FFT the closest frequency will be estimated). % For wavelet, reducing the max frequency reduce % the computation load. % 'padratio' = FFTlength/winsize (2^k) {def: 2} % Multiplies the number of output frequencies by % dividing their spacing. When cycles==0, frequency % spacing is (low_frequency/padratio). % 'nfreqs' = number of output frequencies. For FFT, closest computed % frequency will be returned. Overwrite 'padratio' effects % for wavelets. Default: use 'padratio'. % 'freqscale' = ['log'|'linear'] frequency scale. Default is 'linear'. % Note that for obtaining 'log' spaced freqs using FFT, % closest correspondant frequencies in the 'linear' space % are returned. % 'wletmethod'= ['dftfilt2'|'dftfilt3'] Wavelet method/program to use. % Default is 'dftfilt3' % 'dftfilt3' Morlet wavelet or Hanning DFT % 'dftfilt2' Morlet-variant or Hanning DFT. % Note that there are differences betweeen the Hanning % DFTs in the two programs. % 'causal' = ['on'|'off'] apply FFT or time-frequency in a causal % way where only data before any given latency can % influence the spectral decomposition. (default: 'off'} % % Optional time warping: % 'timestretch' = {[Refmarks], [Refframes]} % Stretch amplitude and phase time-course before smoothing. % Refmarks is a (trials,eventframes) matrix in which rows are % event marks to time-lock to for a given trial. Each trial % will be stretched so that its marked events occur at frames % Refframes. If Refframes is [], the median frame, across trials, % of the Refmarks latencies will be used. Both Refmarks and % Refframes are given in frames in this version - will be % changed to ms in future. % Outputs: % tf = complex time frequency array for all trials (freqs, % times, trials) % freqs = vector of computed frequencies (Hz) % times = vector of computed time points (ms) % itcvals = time frequency "average" for all trials (freqs, times). % In the coherence case, it is the real mean of the time % frequency decomposition, but in the phase coherence case % (see 'type' input'), this is the mean of the normalized % spectral estimate. % % Authors: Arnaud Delorme, Jean Hausser & Scott Makeig % CNL/Salk Institute 1998-2001; SCCN/INC/UCSD, La Jolla, 2002- % Fix FFT frequency innacuracy, bug 874 by WuQiang % % See also: timef(), newtimef(), crossf(), newcrossf() % Note: it is not advised to use a FFT decomposition in a log scale. Output % value are accurate but plotting might not be because of the non-uniform % frequency output values in log-space. If you have to do it, use a % padratio as large as possible, or interpolate time-freq image at % exact log scale values before plotting. % Copyright (C) 8/1/98 Arnaud Delorme, Sigurd Enghoff & Scott Makeig, SCCN/INC/UCSD % % 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 [tmpall, freqs, timesout, itcvals] = timefreq(data, srate, varargin) if nargin < 2 help timefreq; return; end; [chan frame trials]= size(data); if trials == 1 && chan ~= 1 trials = frame; frame = chan; chan = 1; end; g = finputcheck(varargin, ... { 'ntimesout' 'integer' [] []; ... 'timesout' 'real' [] []; ... 'winsize' 'integer' [0 Inf] []; ... 'tlimits' 'real' [] []; ... 'detrend' 'string' {'on','off'} 'off'; ... 'causal' 'string' {'on','off'} 'off'; ... 'verbose' 'string' {'on','off'} 'on'; ... 'freqs' 'real' [0 Inf] []; ... 'nfreqs' 'integer' [0 Inf] []; ... 'freqscale' 'string' { 'linear','log','' } 'linear'; ... 'ffttaper' 'string' { 'hanning','hamming','blackmanharris','none' } 'hanning'; 'wavelet' 'real' [0 Inf] 0; ... 'cycles' {'real','integer'} [0 Inf] 0; ... 'padratio' 'integer' [1 Inf] 2; ... 'itctype' 'string' {'phasecoher','phasecoher2','coher'} 'phasecoher'; ... 'subitc' 'string' {'on','off'} 'off'; ... 'timestretch' 'cell' [] {}; ... 'wletmethod' 'string' {'dftfilt2','dftfilt3'} 'dftfilt3'; ... }); if isstr(g), error(g); end; if isempty(g.freqscale), g.freqscale = 'linear'; end; if isempty(g.winsize), g.winsize = max(pow2(nextpow2(frame)-3),4); end; if isempty(g.ntimesout), g.ntimesout = 200; end; if isempty(g.freqs), g.freqs = [0 srate/2]; end; if isempty(g.tlimits), g.tlimits = [0 frame/srate*1000]; end; % checkin parameters % ------------------ % Use 'wavelet' if 'cycles' undefined for backwards compatibility if g.cycles == 0 g.cycles = g.wavelet; end if (g.winsize > frame) error('Value of winsize must be less than frame length.'); end if (pow2(nextpow2(g.padratio)) ~= g.padratio) error('Value of padratio must be an integer power of two [1,2,4,8,16,...]'); end % finding frequency limits % ------------------------ if g.cycles(1) ~= 0 & g.freqs(1) == 0, g.freqs(1) = srate*g.cycles(1)/g.winsize; end; % finding frequencies % ------------------- if length(g.freqs) == 2 % min and max % ----------- if g.freqs(1) == 0 & g.cycles(1) ~= 0 g.freqs(1) = srate*g.cycles(1)/g.winsize; end; % default number of freqs using padratio % -------------------------------------- if isempty(g.nfreqs) g.nfreqs = g.winsize/2*g.padratio+1; % adjust nfreqs depending on frequency range tmpfreqs = linspace(0, srate/2, g.nfreqs); tmpfreqs = tmpfreqs(2:end); % remove DC (match the output of PSD) % adjust limits for FFT (only linear scale) if g.cycles(1) == 0 & ~strcmpi(g.freqscale, 'log') if ~any(tmpfreqs == g.freqs(1)) [tmp minind] = min(abs(tmpfreqs-g.freqs(1))); g.freqs(1) = tmpfreqs(minind); verboseprintf(g.verbose, 'Adjust min freq. to %3.2f Hz to match FFT output frequencies\n', g.freqs(1)); end; if ~any(tmpfreqs == g.freqs(2)) [tmp minind] = min(abs(tmpfreqs-g.freqs(2))); g.freqs(2) = tmpfreqs(minind); verboseprintf(g.verbose, 'Adjust max freq. to %3.2f Hz to match FFT output frequencies\n', g.freqs(2)); end; end; % find number of frequencies % -------------------------- g.nfreqs = length(tmpfreqs( intersect( find(tmpfreqs >= g.freqs(1)), find(tmpfreqs <= g.freqs(2))))); if g.freqs(1)==g.freqs(2), g.nfreqs = 1; end; end; % find closest freqs for FFT % -------------------------- if strcmpi(g.freqscale, 'log') g.freqs = linspace(log(g.freqs(1)), log(g.freqs(end)), g.nfreqs); g.freqs = exp(g.freqs); else g.freqs = linspace(g.freqs(1), g.freqs(2), g.nfreqs); % this should be OK for FFT % because of the limit adjustment end; end; g.nfreqs = length(g.freqs); % function for time freq initialisation % ------------------------------------- if (g.cycles(1) == 0) %%%%%%%%%%%%%% constant window-length FFTs %%%%%%%%%%%%%%%% freqs = linspace(0, srate/2, g.winsize*g.padratio/2+1); freqs = freqs(2:end); % remove DC (match the output of PSD) %srate/g.winsize*[1:2/g.padratio:g.winsize]/2 verboseprintf(g.verbose, 'Using %s FFT tapering\n', g.ffttaper); switch g.ffttaper case 'hanning', g.win = hanning(g.winsize); case 'hamming', g.win = hamming(g.winsize); case 'blackmanharris', g.win = blackmanharris(g.winsize); case 'none', g.win = ones(g.winsize,1); end; else % %%%%%%%%%%%%%%%%%% Constant-Q (wavelet) DFTs %%%%%%%%%%%%%%%%%%%%%%%%%%%% %freqs = srate*g.cycles/g.winsize*[2:2/g.padratio:g.winsize]/2; %g.win = dftfilt(g.winsize,g.freqs(2)/srate,g.cycles,g.padratio,g.cyclesfact); freqs = g.freqs; if length(g.cycles) == 2 if g.cycles(2) < 1 g.cycles = [ g.cycles(1) g.cycles(1)*g.freqs(end)/g.freqs(1)*(1-g.cycles(2))]; end verboseprintf(g.verbose, 'Using %g cycles at lowest frequency to %g at highest.\n', g.cycles(1), g.cycles(2)); elseif length(g.cycles) == 1 verboseprintf(g.verbose, 'Using %d cycles at all frequencies.\n',g.cycles); else verboseprintf(g.verbose, 'Using user-defined cycle for each frequency\n'); end if strcmp(g.wletmethod, 'dftfilt2') g.win = dftfilt2(g.freqs,g.cycles,srate, g.freqscale); % uses Morlet taper by default elseif strcmp(g.wletmethod, 'dftfilt3') % Default g.win = dftfilt3(g.freqs,g.cycles,srate, 'cycleinc', g.freqscale); % uses Morlet taper by default else return end g.winsize = 0; for index = 1:length(g.win) g.winsize = max(g.winsize,length(g.win{index})); end; end; % compute time vector % ------------------- [ g.timesout g.indexout ] = gettimes(frame, g.tlimits, g.timesout, g.winsize, g.ntimesout, g.causal, g.verbose); % ------------------------------- % compute time freq decomposition % ------------------------------- verboseprintf(g.verbose, 'The window size used is %d samples (%g ms) wide.\n',g.winsize, 1000/srate*g.winsize); if strcmpi(g.freqscale, 'log') % fastif was having strange "function not available" messages scaletoprint = 'log'; else scaletoprint = 'linear'; end verboseprintf(g.verbose, 'Estimating %d %s-spaced frequencies from %2.1f Hz to %3.1f Hz.\n', length(g.freqs), ... scaletoprint, g.freqs(1), g.freqs(end)); %verboseprintf(g.verbose, 'Estimating %d %s-spaced frequencies from %2.1f Hz to %3.1f Hz.\n', length(g.freqs), ... % fastif(strcmpi(g.freqscale, 'log'), 'log', 'linear'), g.freqs(1), g.freqs(end)); if g.cycles(1) == 0 if 1 % build large matrix to compute FFT % --------------------------------- indices = repmat([-g.winsize/2+1:g.winsize/2]', [1 length(g.indexout) trials]); indices = indices + repmat(g.indexout, [size(indices,1) 1 trials]); indices = indices + repmat(reshape(([1:trials]-1)*frame,1,1,trials), [size(indices,1) length(g.indexout) 1]); if chan > 1 tmpall = repmat(nan,[chan length(freqs) length(g.timesout) trials]); tmpX = reshape(data(:,indices), [ size(data,1) size(indices)]); tmpX = bsxfun(@minus, tmpX, mean( tmpX, 2)); % avoids repmat - faster than tmpX = tmpX - repmat(mean(tmpX), [size(tmpX,1) 1 1]); tmpX = bsxfun(@times, tmpX, g.win'); tmpX = fft(tmpX,g.padratio*g.winsize,2); tmpall = squeeze(tmpX(:,2:g.padratio*g.winsize/2+1,:,:)); else tmpall = repmat(nan,[length(freqs) length(g.timesout) trials]); tmpX = data(indices); tmpX = bsxfun(@minus, tmpX, mean( tmpX, 1)); % avoids repmat - faster than tmpX = tmpX - repmat(mean(tmpX), [size(tmpX,1) 1 1]); tmpX = bsxfun(@times, tmpX, g.win); %tmpX = fft(tmpX,2^ceil(log2(g.padratio*g.winsize))); %tmpall = tmpX(2:g.padratio*g.winsize/2+1,:,:); tmpX = fft(tmpX,g.padratio*g.winsize); tmpall = tmpX(2:g.padratio*g.winsize/2+1,:,:); end; else % old iterative computation tmpall = repmat(nan,[length(freqs) length(g.timesout) trials]); verboseprintf(g.verbose, 'Processing trial (of %d):',trials); for trial = 1:trials if rem(trial,10) == 0, verboseprintf(g.verbose, ' %d',trial); end if rem(trial,120) == 0, verboseprintf(g.verbose, '\n'); end for index = 1:length(g.indexout) if strcmpi(g.causal, 'off') tmpX = data([-g.winsize/2+1:g.winsize/2]+g.indexout(index)+(trial-1)*frame); % 1 point imprecision else tmpX = data([-g.winsize+1:0]+g.indexout(index)+(trial-1)*frame); % 1 point imprecision end; tmpX = tmpX - mean(tmpX); if strcmpi(g.detrend, 'on'), tmpX = detrend(tmpX); end; tmpX = g.win .* tmpX(:); tmpX = fft(tmpX,g.padratio*g.winsize); tmpX = tmpX(2:g.padratio*g.winsize/2+1); tmpall(:,index, trial) = tmpX(:); end; end; end; else % wavelet if chan > 1 % wavelets are processed in groups of the same size % to speed up computation. Wavelet of groups of different size % can be processed together but at a cost of a lot of RAM and % a lot of extra computation -> not efficient tmpall = repmat(nan,[chan length(freqs) length(g.timesout) trials]); wt = [ 1 find(diff(cellfun(@length,g.win)))+1 length(g.win)+1]; verboseprintf(g.verbose, 'Computing of %d:', length(wt)); for ind = 1:length(wt)-1 verboseprintf(g.verbose, '.'); wavarray = reshape([ g.win{wt(ind):wt(ind+1)-1} ], [ length(g.win{wt(ind)}) wt(ind+1)-wt(ind) ]); sizewav = size(wavarray,1)-1; indices = repmat([-sizewav/2:sizewav/2]', [1 size(wavarray,2) length(g.indexout) trials]); indices = indices + repmat(reshape(g.indexout, 1,1,length(g.indexout)), [size(indices,1) size(indices,2) 1 trials]); indices = indices + repmat(reshape(([1:trials]-1)*frame,1,1,1,trials), [size(indices,1) size(indices,2) size(indices,3) 1]); szfreqdata = [ size(data,1) size(indices) ]; tmpX = reshape(data(:,indices), szfreqdata); tmpX = bsxfun(@minus, tmpX, mean( tmpX, 2)); % avoids repmat - faster than tmpX = tmpX - repmat(mean(tmpX), [size(tmpX,1) 1 1]); wavarray = reshape(wavarray, [1 size(wavarray,1) size(wavarray,2)]); tmpall(:,wt(ind):wt(ind+1)-1,:,:,:) = reshape(sum(bsxfun(@times, tmpX, wavarray),2), [szfreqdata(1) szfreqdata(3:end)]); end; verboseprintf(g.verbose, '\n'); %tmpall = squeeze(tmpall(1,:,:,:)); elseif 0 tmpall = repmat(nan,[length(freqs) length(g.timesout) trials]); % wavelets are processed in groups of the same size % to speed up computation. Wavelet of groups of different size % can be processed together but at a cost of a lot of RAM and % a lot of extra computation -> not faster than the regular % iterative method wt = [ 1 find(diff(cellfun(@length,g.win)))+1 length(g.win)+1]; for ind = 1:length(wt)-1 wavarray = reshape([ g.win{wt(ind):wt(ind+1)-1} ], [ length(g.win{wt(ind)}) wt(ind+1)-wt(ind) ]); sizewav = size(wavarray,1)-1; indices = repmat([-sizewav/2:sizewav/2]', [1 size(wavarray,2) length(g.indexout) trials]); indices = indices + repmat(reshape(g.indexout, 1,1,length(g.indexout)), [size(indices,1) size(indices,2) 1 trials]); indices = indices + repmat(reshape(([1:trials]-1)*frame,1,1,1,trials), [size(indices,1) size(indices,2) size(indices,3) 1]); tmpX = data(indices); tmpX = bsxfun(@minus, tmpX, mean( tmpX, 1)); % avoids repmat - faster than tmpX = tmpX - repmat(mean(tmpX), [size(tmpX,1) 1 1]); tmpall(wt(ind):wt(ind+1)-1,:,:) = squeeze(sum(bsxfun(@times, tmpX, wavarray),1)); end; elseif 0 % wavelets are processed one by one but all windows simultaneously % -> not faster than the regular iterative method tmpall = repmat(nan,[length(freqs) length(g.timesout) trials]); sizewav = length(g.win{1})-1; % max window size mainc = sizewav/2; indices = repmat([-sizewav/2:sizewav/2]', [1 length(g.indexout) trials]); indices = indices + repmat(g.indexout, [size(indices,1) 1 trials]); indices = indices + repmat(reshape(([1:trials]-1)*frame,1,1,trials), [size(indices,1) length(g.indexout) 1]); for freqind = 1:length(g.win) winc = (length(g.win{freqind})-1)/2; wins = length(g.win{freqind})-1; wini = [-wins/2:wins/2]+winc+mainc-winc+1; tmpX = data(indices(wini,:,:)); tmpX = bsxfun(@minus, tmpX, mean( tmpX, 1)); % avoids repmat - faster than tmpX = tmpX - repmat(mean(tmpX), [size(tmpX,1) 1 1]); tmpX = sum(bsxfun(@times, tmpX, g.win{freqind}'),1); tmpall(freqind,:,:) = tmpX; end; else % prepare wavelet filters % ----------------------- for index = 1:length(g.win) g.win{index} = transpose(repmat(g.win{index}, [trials 1])); end; % apply filters % ------------- verboseprintf(g.verbose, 'Processing time point (of %d):',length(g.timesout)); tmpall = zeros(length(g.win), length(g.indexout), size(data,2)); for index = 1:length(g.indexout) if rem(index,10) == 0, verboseprintf(g.verbose, ' %d',index); end if rem(index,120) == 0, verboseprintf(g.verbose, '\n'); end for freqind = 1:length(g.win) wav = g.win{freqind}; sizewav = size(wav,1)-1; %g.indexout(index), size(wav,1), g.freqs(freqind) if strcmpi(g.causal, 'off') tmpX = data([-sizewav/2:sizewav/2]+g.indexout(index),:); else tmpX = data([-sizewav:0]+g.indexout(index),:); end; tmpX = tmpX - ones(size(tmpX,1),1)*mean(tmpX); if strcmpi(g.detrend, 'on'), for trial = 1:trials tmpX(:,trial) = detrend(tmpX(:,trial)); end; end; tmpX = sum(wav .* tmpX); tmpall( freqind, index, :) = tmpX; end; end; end; end; verboseprintf(g.verbose, '\n'); % time-warp code begins -Jean % --------------------------- if ~isempty(g.timestretch) && length(g.timestretch{1}) > 0 timemarks = g.timestretch{1}'; if isempty(g.timestretch{2}) | length(g.timestretch{2}) == 0 timerefs = median(g.timestretch{1}',2); else timerefs = g.timestretch{2}; end trials = size(tmpall,3); % convert timerefs to subsampled ERSP space % ----------------------------------------- [dummy refsPos] = min(transpose(abs( ... repmat(timerefs, [1 length(g.indexout)]) - repmat(g.indexout, [length(timerefs) 1])))); refsPos(end+1) = 1; refsPos(end+1) = length(g.indexout); refsPos = sort(refsPos); for t=1:trials % convert timemarks to subsampled ERSP space % ------------------------------------------ %[dummy pos]=min(abs(repmat(timemarks(2:7,1), [1 length(g.indexout)])-repmat(g.indexout,[6 1]))); outOfTimeRangeTimeWarpMarkers = find(timemarks(:,t) < min(g.indexout) | timemarks(:,t) > max(g.indexout)); % if ~isempty(outOfTimeRangeTimeWarpMarkers) % verboseprintf(g.verbose, 'Timefreq warning: time-warp latencies in epoch %d are out of time range defined for calculation of ERSP.\n', t); % end; [dummy marksPos] = min(transpose( ... abs( ... repmat(timemarks(:,t), [1 length(g.indexout)]) ... - repmat(g.indexout, [size(timemarks,1) 1]) ... ) ... )); marksPos(end+1) = 1; marksPos(end+1) = length(g.indexout); marksPos = sort(marksPos); %now warp tmpall mytmpall = tmpall(:,:,t); r = sqrt(mytmpall.*conj(mytmpall)); theta = angle(mytmpall); % So mytmpall is almost equal to r.*exp(i*theta) % whos marksPos refsPos M = timewarp(marksPos, refsPos); TSr = transpose(M*r'); TStheta = zeros(size(theta,1), size(theta,2)); for freqInd=1:size(TStheta,1) TStheta(freqInd, :) = angtimewarp(marksPos, refsPos, theta(freqInd, :)); end TStmpall = TSr.*exp(i*TStheta); % $$$ keyboard; tmpall(:,:,t) = TStmpall; end end %time-warp ends zerovals = tmpall == 0; if any(reshape(zerovals, 1, prod(size(zerovals)))) tmpall(zerovals) = Inf; minval = min(tmpall(:)); % remove bug tmpall(zerovals) = minval; end; % compute and subtract ITC % ------------------------ if nargout > 3 || strcmpi(g.subitc, 'on') itcvals = tfitc(tmpall, g.itctype); end; if strcmpi(g.subitc, 'on') %a = gcf; figure; imagesc(abs(itcvals)); cbar; figure(a); if ndims(tmpall) <= 3 tmpall = (tmpall - abs(tmpall) .* repmat(itcvals, [1 1 trials])) ./ abs(tmpall); else tmpall = (tmpall - abs(tmpall) .* repmat(itcvals, [1 1 1 trials])) ./ abs(tmpall); end; end; % find closest output frequencies % ------------------------------- if length(g.freqs) ~= length(freqs) || any(g.freqs ~= freqs) allindices = zeros(1,length(g.freqs)); for index = 1:length(g.freqs) [dum ind] = min(abs(freqs-g.freqs(index))); allindices(index) = ind; end; verboseprintf(g.verbose, 'finding closest frequencies: %d freqs removed\n', length(freqs)-length(allindices)); freqs = freqs(allindices); if ndims(tmpall) <= 3 tmpall = tmpall(allindices,:,:); else tmpall = tmpall(:,allindices,:,:); end; if nargout > 3 | strcmpi(g.subitc, 'on') if ndims(tmpall) <= 3 itcvals = itcvals(allindices,:,:); else itcvals = itcvals(:,allindices,:,:); end; end; end; timesout = g.timesout; %figure; imagesc(abs(sum(itcvals,3))); cbar; return; % function for itc % ---------------- function [itcvals] = tfitc(tfdecomp, itctype); % first dimension are trials nd = max(3,ndims(tfdecomp)); switch itctype case 'coher', try, itcvals = sum(tfdecomp,nd) ./ sqrt(sum(tfdecomp .* conj(tfdecomp),nd) * size(tfdecomp,nd)); catch, % scan rows if out of memory for index =1:size(tfdecomp,1) itcvals(index,:,:) = sum(tfdecomp(index,:,:,:),nd) ./ sqrt(sum(tfdecomp(index,:,:,:) .* conj(tfdecomp(index,:,:,:)),nd) * size(tfdecomp,nd)); end; end; case 'phasecoher2', try, itcvals = sum(tfdecomp,nd) ./ sum(sqrt(tfdecomp .* conj(tfdecomp)),nd); catch, % scan rows if out of memory for index =1:size(tfdecomp,1) itcvals(index,:,:) = sum(tfdecomp(index,:,:,:),nd) ./ sum(sqrt(tfdecomp(index,:,:,:) .* conj(tfdecomp(index,:,:,:))),nd); end; end; case 'phasecoher', try, itcvals = sum(tfdecomp ./ sqrt(tfdecomp .* conj(tfdecomp)) ,nd) / size(tfdecomp,nd); catch, % scan rows if out of memory for index =1:size(tfdecomp,1) itcvals(index,:,:) = sum(tfdecomp(index,:,:,:) ./ sqrt(tfdecomp(index,:,:,:) .* conj(tfdecomp(index,:,:,:))) ,nd) / size(tfdecomp,nd); end; end; end % ~any(isnan()) return; function w = hanning(n) if ~rem(n,2) w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end % get time points % --------------- function [ timevals, timeindices ] = gettimes(frames, tlimits, timevar, winsize, ntimevar, causal, verbose); timevect = linspace(tlimits(1), tlimits(2), frames); srate = 1000*(frames-1)/(tlimits(2)-tlimits(1)); if isempty(timevar) % no pre-defined time points if ntimevar(1) > 0 % generate linearly space vector % ------------------------------ if (ntimevar > frames-winsize) ntimevar = frames-winsize; if ntimevar < 0 error('Not enough data points, reduce the window size or lowest frequency'); end; verboseprintf(verbose, ['Value of ''timesout'' must be <= frame-winsize, ''timesout'' adjusted to ' int2str(ntimevar) '\n']); end npoints = ntimevar(1); wintime = 500*winsize/srate; if strcmpi(causal, 'on') timevals = linspace(tlimits(1)+2*wintime, tlimits(2), npoints); else timevals = linspace(tlimits(1)+wintime, tlimits(2)-wintime, npoints); end; verboseprintf(verbose, 'Generating %d time points (%1.1f to %1.1f ms)\n', npoints, min(timevals), max(timevals)); else % subsample data % -------------- nsub = -ntimevar(1); if strcmpi(causal, 'on') timeindices = [ceil(winsize+nsub):nsub:length(timevect)]; else timeindices = [ceil(winsize/2+nsub/2):nsub:length(timevect)-ceil(winsize/2)-1]; end; timevals = timevect( timeindices ); % the conversion at line 741 leaves timeindices unchanged verboseprintf(verbose, 'Subsampling by %d (%1.1f to %1.1f ms)\n', nsub, min(timevals), max(timevals)); end; else timevals = timevar; % check boundaries % ---------------- wintime = 500*winsize/srate; if strcmpi(causal, 'on') tmpind = find( (timevals >= tlimits(1)+2*wintime-0.0001) & (timevals <= tlimits(2)) ); else tmpind = find( (timevals >= tlimits(1)+wintime-0.0001) & (timevals <= tlimits(2)-wintime+0.0001) ); end; % 0.0001 account for numerical innacuracies on opteron computers if isempty(tmpind) error('No time points. Reduce time window or minimum frequency.'); end; if length(timevals) ~= length(tmpind) verboseprintf(verbose, 'Warning: %d out of %d time values were removed (now %3.2f to %3.2f ms) so the lowest\n', ... length(timevals)-length(tmpind), length(timevals), timevals(tmpind(1)), timevals(tmpind(end))); verboseprintf(verbose, ' frequency could be computed with the requested accuracy\n'); end; timevals = timevals(tmpind); end; % find closet points in data % -------------------------- timeindices = round(eeg_lat2point(timevals, 1, srate, tlimits, 1E-3)); if length(timeindices) < length(unique(timeindices)) timeindices = unique_bc(timeindices) verboseprintf(verbose, 'Warning: duplicate times, reduce the number of output times\n'); end; if length(unique(timeindices(2:end)-timeindices(1:end-1))) > 1 verboseprintf(verbose, 'Finding closest points for time variable\n'); verboseprintf(verbose, 'Time values for time/freq decomposition is not perfectly uniformly distributed\n'); else verboseprintf(verbose, 'Distribution of data point for time/freq decomposition is perfectly uniform\n'); end; timevals = timevect(timeindices); % DEPRECATED, FOR C INTERFACE function nofunction() % C PART %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% filename = [ 'tmpcrossf' num2str(round(rand(1)*1000)) ]; f = fopen([ filename '.in'], 'w'); fwrite(f, tmpsaveall, 'int32'); fwrite(f, g.detret, 'int32'); fwrite(f, g.srate, 'int32'); fwrite(f, g.maxfreq, 'int32'); fwrite(f, g.padratio, 'int32'); fwrite(f, g.cycles, 'int32'); fwrite(f, g.winsize, 'int32'); fwrite(f, g.timesout, 'int32'); fwrite(f, g.subitc, 'int32'); fwrite(f, g.type, 'int32'); fwrite(f, trials, 'int32'); fwrite(f, g.naccu, 'int32'); fwrite(f, length(X), 'int32'); fwrite(f, X, 'double'); fwrite(f, Y, 'double'); fclose(f); command = [ '!cppcrosff ' filename '.in ' filename '.out' ]; eval(command); f = fopen([ filename '.out'], 'r'); size1 = fread(f, 'int32', 1); size2 = fread(f, 'int32', 1); Rreal = fread(f, 'double', [size1 size2]); Rimg = fread(f, 'double', [size1 size2]); Coher.R = Rreal + j*Rimg; Boot.Coherboot.R = []; Boot.Rsignif = []; function verboseprintf(verbose, varargin) if strcmpi(verbose, 'on') fprintf(varargin{:}); end;
github
lcnhappe/happe-master
pac_cont.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/pac_cont.m
17,447
utf_8
9b94d431be58419e3715e54645687469
% pac_cont() - compute phase-amplitude coupling (power of first input % correlation with phase of second). There is no graphical output % to this function. % % Usage: % >> pac_cont(x,y,srate); % >> [pac timesout pvals] = pac_cont(x,y,srate,'key1', 'val1', 'key2', val2' ...); % % Inputs: % x = [float array] 1-D data vector of size (1xtimes) % y = [float array] 1-D data vector of size (1xtimes) % srate = data sampling rate (Hz) % % Optional time information intputs: % 'winsize' = If cycles==0: data subwindow length (fastest, 2^n<frames); % If cycles >0: *longest* window length to use. This % determines the lowest output frequency. Note that this % parameter is overwritten if the minimum frequency has been set % manually and requires a longer time window {~frames/8} % 'ntimesout' = Number of output times (int<frames-winframes). Enter a % negative value [-S] to subsample original time by S. % 'timesout' = Enter an array to obtain spectral decomposition at % specific time values (note: algorithm find closest time % point in data and this might result in an unevenly spaced % time array). Overwrite 'ntimesout'. {def: automatic} % 'tlimits' = [min max] time limits in ms. % % Optional PAC inputs: % 'method' = ['modulation'|'plv'|'corr'|'glm'] (see reference). % 'freqphase' = [min max] frequency limits. Default [minfreq 50], % minfreq being determined by the number of data points, % cycles and sampling frequency. Use 0 for minimum frequency % to compute default minfreq. You may also enter an % array of frequencies for the spectral decomposition % (for FFT, closest computed frequency will be returned; use % 'padratio' to change FFT freq. resolution). % 'freqamp' = [float array] array of frequencies for the second % argument. 'freqs' is used for the first argument. % By default it is the same as 'freqs'. % 'filterfunc' = ['eegfilt'|'iirfilt'|'eegfftfilt'] filtering function. % Default is iirfilt. Warning, filtering may dramatically % affect the result. With the 'corr' method, make sure you % have a large window size because each window is filtered % independently. % 'filterphase' = @f_handle. Function handle to filter the data for the % phase information. For example, @(x)iirfilt(x, 1000, 2, % 20). Note that 'freqphase' is ignore in this case. % 'filteramp' = @f_handle. Function handle to filter the data for the % amplitude information. Note that 'freqamp' is ignore in % this case. % % Inputs for statistics: % 'alpha' = [float] p-value threshold. Default is none (no statistics). % 'mcorrect' = ['none'|'fdr'] method to correct for multiple comparison. % Default is 'none'. % 'baseline' = [min max] baseline period for the Null distribution. Default % is the whole data range. Note that this option is ignored % for instanstaneous statistics. % 'instantstat' = ['on'|'off'] performs statistics for each time window % independently. Default is 'off'. % 'naccu' = [integer] number of accumulations for surrogate % statistics. % 'statlim' = ['parametric'|'surrogate'] use a parametric methods to % asseess the limit of the surrogate distribution or use % the tail of the distribution ('surrogate' method) % % Other inputs: % 'title' = [string] figure title. Default is none. % 'vert' = [float array] array of time value for which to plot % vertical lines. Default is none. % % Outputs: % pac = Phase-amplitude coupling values. % timesout = vector of time indices % pvals = Associated p-values % % Author: Arnaud Delorme and Makoto Miyakoshi, SCCN/INC, UCSD 2012- % % References: % Methods used here are introduced and compared in: % Penny, Duzel, Miller, Ojemann. (20089). Testing for Nested Oscilations. % J Neuro Methods. 174:50-61 % % Modulation Index is defined in: % Canolty, Edwards, Dalal, Soltani, Nagarajan, Kirsch, et al. (2006). Modulation index is defined in High Gamma Power Is Phase-Locked to Theta % Oscillations in Human Neocortex. Science. 313:1626-8. % % PLV (Phase locking value) is defined in: % Lachaux, Rodriguez, Martiniere, Varela. (1999). Measuring phase synchrony % in brain signal. Hum Brain Mapp. 8:194-208. % % corr (correlation) method is defined in: % Brunce, Eckhorn. (2004). Task-related coupling from high- to % low-frequency signals among visual cortical areas in human subdural % recordings. Int J Psychophysiol. 51:97-116. % % glm (general linear model) is defined in % Penny, Duzel, Miller, Ojemann. (20089). Testing for Nested Oscilations. % J Neuro Methods. 174:50-61 % Copyright (C) 2012 Arnaud Delorme, UCSD % % 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 [m_raw pvals indexout] = pac_cont(X, Y, srate, varargin); if nargin < 1 help pac_cont; return; end; % deal with 3-D inputs % -------------------- if ndims(X) == 3 || ndims(Y) == 3, error('Cannot process 3-D input'); end; if size(X,1) > 1, X = X'; end; if size(Y,1) > 1, Y = Y'; end; if size(X,1) ~= 1 || size(Y,1) ~= 1, error('Cannot only process vector input'); end; frame = size(X,2); pvals = []; g = finputcheck(varargin, ... { ... 'alpha' 'real' [0 0.2] []; 'baseline' 'float' [] []; 'freqphase' 'real' [0 Inf] [0 srate/2]; 'freqamp' 'real' [0 Inf] []; 'mcorrect' 'string' { 'none' 'fdr' } 'none'; 'method' 'string' { 'plv' 'modulation' 'glm' 'corr' } 'modulation'; 'naccu' 'integer' [1 Inf] 250; 'instantstat' 'string' {'on','off'} 'off'; 'newfig' 'string' {'on','off'} 'on'; 'nofig' 'string' {'on','off'} 'off'; 'statlim' 'string' {'surrogate','parametric'} 'parametric'; 'timesout' 'real' [] []; ... 'filterfunc' 'string' { 'eegfilt' 'iirfilt' 'eegfiltfft' } 'eegfiltfft'; ... 'filterphase' '' {} []; 'filteramp' '' {} []; 'ntimesout' 'integer' [] 200; ... 'tlimits' 'real' [] [0 frame/srate]; 'title' 'string' [] ''; 'vert' 'real' [] []; 'winsize' 'integer' [0 Inf] max(pow2(nextpow2(frame)-3),4) }, 'pac'); if isstr(g), error(g); end; if ~isempty(g.filterphase) x_freqphase = feval(g.filterphase, X(:)'); else x_freqphase = feval(g.filterfunc, X(:)', srate, g.freqphase(1), g.freqphase(end)); end; if ~isempty(g.filteramp) x_freqamp = feval(g.filteramp, Y(:)'); else x_freqamp = feval(g.filterfunc, Y(:)', srate, g.freqamp( 1), g.freqamp( end)); end; z_phasedata = hilbert(x_freqphase); z_ampdata = hilbert(x_freqamp); phase = angle(z_phasedata); amplitude = abs( z_ampdata); z = amplitude.*exp(i*phase); % this is the pac measure % get time windows % ---------------- g.verbose = 'on'; g.causal = 'off'; [ timesout1 indexout ] = gettimes(frame, g.tlimits, g.timesout, g.winsize, g.ntimesout, g.causal, g.verbose); % scan time windows % ----------------- if ~isempty(g.alpha) m_raw = zeros(1,length(indexout)); pvals = zeros(1,length(indexout)); end; fprintf('Computing PAC:\n'); for iWin = 1:length(indexout) x_phaseEpoch = x_freqphase(indexout(iWin)+[-g.winsize/2+1:g.winsize/2]); x_ampEpoch = x_freqamp( indexout(iWin)+[-g.winsize/2+1:g.winsize/2]); z_phaseEpoch = z_phasedata(indexout(iWin)+[-g.winsize/2+1:g.winsize/2]); z_ampEpoch = z_ampdata( indexout(iWin)+[-g.winsize/2+1:g.winsize/2]); z_epoch = z( indexout(iWin)+[-g.winsize/2+1:g.winsize/2]); numpoints=length(x_phaseEpoch); if rem(iWin,10) == 0, verboseprintf(g.verbose, ' %d',iWin); end if rem(iWin,120) == 0, verboseprintf(g.verbose, '\n'); end % Choose method % ------------- if strcmpi(g.method, 'modulation') % Modulation index m_raw(iWin) = abs(sum(z_epoch))/numpoints; elseif strcmpi(g.method, 'plv') if iWin == 145 %dsfsd; end; %amplitude_filt = sgolayfilt(amplitude, 3, 101); if ~isempty(g.filterphase) amplitude_filt = feval(g.filterphase, z_ampEpoch); else amplitude_filt = feval(g.filterfunc , z_ampEpoch, srate, g.freqphase(1), g.freqphase(end)); end; z_amplitude_filt = hilbert(amplitude_filt); phase_amp_modulation = angle(z_amplitude_filt); m_raw(iWin) = abs(sum(exp(i*(x_phaseEpoch - phase_amp_modulation)))/numpoints); elseif strcmpi(g.method, 'corr') if iWin == inf %145 figure; plot(abs(z_ampdata)) hold on; plot(x_phasedata/10000000000, 'r') x = X(indexout(iWin)+[-g.winsize/2+1:g.winsize/2]); hold on; plot(x, 'g'); dsfsd; end; [r_ESC pval_corr] = corrcoef(x_phaseEpoch, abs(z_ampEpoch)); m_raw(iWin) = r_ESC(1,2); pvals(iWin) = pval_corr(1,2); elseif strcmpi(g.method, 'glm') [b dev stats] = glmfit(x_phaseEpoch', abs(z_ampEpoch)', 'normal'); GLM_beta = stats.beta(2,1); pvals(iWin) = stats.p(2,1); m_raw(iWin) = b(1); end; %% compute statistics (instantaneous) % ----------------------------------- if ~isempty(g.alpha) && strcmpi(g.instantstat, 'on') && ~strcmpi(g.method, 'corr') && ~strcmpi(g.method, 'glm') % compute surrogate values numsurrogate=g.naccu; minskip=srate; maxskip=numpoints-srate; % max variation half a second if maxskip < 1 error('Window size shorter than 1 second; too short for computing surrogate data'); end; skip=ceil(numpoints.*rand(numsurrogate*4,1)); skip(skip>maxskip)=[]; skip(skip<minskip)=[]; skip=skip(1:numsurrogate,1); surrogate_m=zeros(numsurrogate,1); for s=1:numsurrogate surrogate_amplitude=[amplitude(skip(s):end) amplitude(1:skip(s)-1)]; % consider circular shifts surrogate_m(s)=abs(mean(surrogate_amplitude.*exp(i*phase))); %disp(numsurrogate-s) end if strcmpi(g.statlim, 'surrogate') pvals(iWin) = stat_surrogate_pvals(surrogate_m, m_raw(iWin), 'upper'); %fprintf('Raw PAC is %3.2f (p-value=%1.3f)\n', m_raw(iWin), pvals(iWin)); else % Canolty method below %% fit gaussian to surrogate data, uses normfit.m from MATLAB Statistics toolbox [surrogate_mean,surrogate_std]=normfit(surrogate_m); %% normalize length using surrogate data (z-score) m_norm_length=(abs(m_raw(iWin))-surrogate_mean)/surrogate_std; pvals(iWin) = normcdf(0, m_norm_length, 1); m_norm_phase=angle(m_raw(iWin)); m_norm=m_norm_length*exp(i*m_norm_phase); % compare parametric and non-parametric methods (return similar % results) if iWin == length(indexout) figure; plot(-log10(pvals)); hold on; plot(-log10(pvals2), 'r'); end; end; end; end; fprintf('\n'); % Computes alpha % -------------- if ~isempty(g.alpha) && strcmpi(g.instantstat, 'off') if isempty(g.baseline) g.baseline = [ timesout1(1) timesout1(end) ]; end; baselineInd = find(timesout1 >= g.baseline(1) & timesout1 <= g.baseline(end)); m_raw_base = abs(m_raw(baselineInd)); if strcmpi(g.statlim, 'surrogate') for index = 1:length(m_raw) pvals(index) = stat_surrogate_pvals(m_raw_base, m_raw(index), 'upper'); end; else [surrogate_mean,surrogate_std]=normfit(m_raw_base); m_norm_length=(abs(m_raw)-surrogate_mean)/surrogate_std; pvals = normcdf(0, m_norm_length, 1); end; if strcmpi(g.mcorrect, 'fdr') pvals = fdr(pvals); end; end; %% plot results % ------------- if strcmpi(g.nofig, 'on') return end; if strcmpi(g.newfig, 'on') figure; end; if ~isempty(g.alpha) plotcurve(timesout1, m_raw, 'maskarray', pvals < g.alpha); else plotcurve(timesout1, m_raw); end; xlabel('Time (ms)'); ylabel('PAC (0 to 1)'); title(g.title); % plot vertical lines % ------------------- if ~isempty(g.vert) hold on; yl = ylim; for index = 1:length(g.vert) plot([g.vert(index) g.vert(index)], yl, 'g'); end; end; % ------------- % gettime function identical to timefreq function % DO NOT MODIFY % ------------- function [ timevals, timeindices ] = gettimes(frames, tlimits, timevar, winsize, ntimevar, causal, verbose); timevect = linspace(tlimits(1), tlimits(2), frames); srate = 1000*(frames-1)/(tlimits(2)-tlimits(1)); if isempty(timevar) % no pre-defined time points if ntimevar(1) > 0 % generate linearly space vector % ------------------------------ if (ntimevar > frames-winsize) ntimevar = frames-winsize; if ntimevar < 0 error('Not enough data points, reduce the window size or lowest frequency'); end; verboseprintf(verbose, ['Value of ''timesout'' must be <= frame-winsize, ''timesout'' adjusted to ' int2str(ntimevar) '\n']); end npoints = ntimevar(1); wintime = 500*winsize/srate; if strcmpi(causal, 'on') timevals = linspace(tlimits(1)+2*wintime, tlimits(2), npoints); else timevals = linspace(tlimits(1)+wintime, tlimits(2)-wintime, npoints); end; verboseprintf(verbose, 'Generating %d time points (%1.1f to %1.1f ms)\n', npoints, min(timevals), max(timevals)); else % subsample data % -------------- nsub = -ntimevar(1); if strcmpi(causal, 'on') timeindices = [ceil(winsize+nsub):nsub:length(timevect)]; else timeindices = [ceil(winsize/2+nsub/2):nsub:length(timevect)-ceil(winsize/2)-1]; end; timevals = timevect( timeindices ); % the conversion at line 741 leaves timeindices unchanged verboseprintf(verbose, 'Subsampling by %d (%1.1f to %1.1f ms)\n', nsub, min(timevals), max(timevals)); end; else timevals = timevar; % check boundaries % ---------------- wintime = 500*winsize/srate; if strcmpi(causal, 'on') tmpind = find( (timevals >= tlimits(1)+2*wintime-0.0001) & (timevals <= tlimits(2)) ); else tmpind = find( (timevals >= tlimits(1)+wintime-0.0001) & (timevals <= tlimits(2)-wintime+0.0001) ); end; % 0.0001 account for numerical innacuracies on opteron computers if isempty(tmpind) error('No time points. Reduce time window or minimum frequency.'); end; if length(timevals) ~= length(tmpind) verboseprintf(verbose, 'Warning: %d out of %d time values were removed (now %3.2f to %3.2f ms) so the lowest\n', ... length(timevals)-length(tmpind), length(timevals), timevals(tmpind(1)), timevals(tmpind(end))); verboseprintf(verbose, ' frequency could be computed with the requested accuracy\n'); end; timevals = timevals(tmpind); end; % find closet points in data % -------------------------- timeindices = round(eeg_lat2point(timevals, 1, srate, tlimits, 1E-3)); if length(timeindices) < length(unique(timeindices)) timeindices = unique_bc(timeindices) verboseprintf(verbose, 'Warning: duplicate times, reduce the number of output times\n'); end; if length(unique(timeindices(2:end)-timeindices(1:end-1))) > 1 verboseprintf(verbose, 'Finding closest points for time variable\n'); verboseprintf(verbose, 'Time values for time/freq decomposition is not perfectly uniformly distributed\n'); else verboseprintf(verbose, 'Distribution of data point for time/freq decomposition is perfectly uniform\n'); end; timevals = timevect(timeindices); function verboseprintf(verbose, varargin) if strcmpi(verbose, 'on') fprintf(varargin{:}); end;
github
lcnhappe/happe-master
dftfilt3.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/dftfilt3.m
7,390
utf_8
7ef2a5114ee38513d5a55a8f38553cb1
% dftfilt3() - discrete complex wavelet filters % % Usage: % >> [wavelet,cycles,freqresol,timeresol] = dftfilt3( freqs, cycles, srate, varargin) % % Inputs: % freqs - vector of frequencies of interest. % cycles - cycles array. If cycles=0, then the Hanning tapered Short-term FFT is used. % If one value is given and cycles>0, all wavelets have % the same number of cycles. If two values are given, the % two values are used for the number of cycles at the lowest % frequency and at the highest frequency, with linear or % log-linear interpolation between these values for intermediate % frequencies % srate - sampling rate (in Hz) % % Optional Inputs: Input these as 'key/value pairs. % 'cycleinc' - ['linear'|'log'] increase mode if [min max] cycles is % provided in 'cycle' parameter. {default: 'linear'} % 'winsize' Use this option for Hanning tapered FFT or if you prefer to set the length of the % wavelets to be equal for all of them (e.g., to set the % length to 256 samples input: 'winsize',256). {default: []) % Note: the output 'wavelet' will be a matrix and it may be % incompatible with current versions of timefreq and newtimef. % 'timesupport' The number of temporal standard deviation used for wavelet lengths {default: 7) % % Output: % wavelet - cell array or matrix of wavelet filters % timeresol - temporal resolution of Morlet wavelets. % freqresol - frequency resolution of Morlet wavelets. % % Note: The length of the window is always made odd. % % Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 3/28/2003 % Rey Ramirez, SCCN/INC/UCSD, La Jolla, 9/26/2006 % Copyright (C) 3/28/2003 Arnaud Delorme 8, 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 % % Revision 1.12 2006/09/25 rey r % Almost complete rewriting of dftfilt2.m, changing both Morlet and Hanning % DFT to be more in line with conventional implementations. % % Revision 1.11 2006/09/07 19:05:34 scott % further clarified the Morlet/Hanning distinction -sm % % Revision 1.10 2006/09/07 18:55:15 scott % clarified window types in help msg -sm % % Revision 1.9 2006/05/05 16:17:36 arno % implementing cycle array % % Revision 1.8 2004/03/04 19:31:03 arno % email % % Revision 1.7 2004/02/25 01:45:55 arno % sinus test % % Revision 1.6 2004/02/15 22:23:08 arno % implementing morlet wavelet % % Revision 1.5 2003/05/09 20:55:10 arno % adding hanning function % % Revision 1.4 2003/04/29 16:02:54 arno % header typos % % Revision 1.3 2003/04/29 01:09:16 arno % debug imaginary part % % Revision 1.2 2003/04/28 23:01:13 arno % *** empty log message *** % % Revision 1.1 2003/04/28 22:46:49 arno % Initial revision % function [wavelet,cycles,freqresol,timeresol] = dftfilt3( freqs, cycles, srate, varargin); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Rey fixed all input parameter sorting. if nargin < 3 error(' A minimum of 3 arguments is required'); end; numargin=length(varargin); if rem(numargin,2) error('There is an uneven number key/value inputs. You are probably missing a keyword or its value.') end varargin(1:2:end)=lower(varargin(1:2:end)); % Setting default parameter values. cycleinc='linear'; winsize=[]; timesupport=7; % Setting default of 7 temporal standard deviations for wavelet's length. for n=1:2:numargin keyword=varargin{n}; if strcmpi('cycleinc',keyword) cycleinc=varargin{n+1}; elseif strcmpi('winsize',keyword) winsize=varargin{n+1}; if ~mod(winsize,2) winsize=winsize+1; % Always set to odd length wavelets and hanning windows; end elseif strcmpi('timesupport',keyword) timesupport=varargin{n+1}; else error(['What is ' keyword '? The only legal keywords are: type, cycleinc, winsize, or timesupport.']) end end if isempty(winsize) & cycles==0 error('If you are using a Hanning tapered FFT, please supply the winsize input-pair.') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute number of cycles at each frequency % ------------------------------------------ type='morlet'; if length(cycles) == 1 & cycles(1)~=0 cycles = cycles*ones(size(freqs)); elseif length(cycles) == 2 if strcmpi(cycleinc, 'log') % cycleinc cycles = linspace(log(cycles(1)), log(cycles(2)), length(freqs)); cycles = exp(cycles); %cycles=logspace(log10(cycles(1)),log10(cycles(2)),length(freqs)); %rey else cycles = linspace(cycles(1), cycles(2), length(freqs)); end; end; if cycles==0 type='sinus'; end sp=1/srate; % Rey added this line (i.e., sampling period). % compute wavelet for index = 1:length(freqs) fk=freqs(index); if strcmpi(type, 'morlet') % Morlet. sigf=fk/cycles(index); % Computing time and frequency standard deviations, resolutions, and normalization constant. sigt=1./(2*pi*sigf); A=1./sqrt(sigt*sqrt(pi)); timeresol(index)=2*sigt; freqresol(index)=2*sigf; if isempty(winsize) % bases will be a cell array. tneg=[-sp:-sp:-sigt*timesupport/2]; tpos=[0:sp:sigt*timesupport/2]; t=[fliplr(tneg) tpos]; psi=A.*(exp(-(t.^2)./(2*(sigt^2))).*exp(2*i*pi*fk*t)); wavelet{index}=psi; % These are the wavelets with variable number of samples based on temporal standard deviations (sigt). else % bases will be a matrix. tneg=[-sp:-sp:-sp*winsize/2]; tpos=[0:sp:sp*winsize/2]; t=[fliplr(tneg) tpos]; psi=A.*(exp(-(t.^2)./(2*(sigt^2))).*exp(2*i*pi*fk*t)); wavelet(index,:)=psi; % These are the wavelets with the same length. % This is useful for doing time-frequency analysis as a matrix vector or matrix matrix multiplication. end elseif strcmpi(type, 'sinus') % Hanning tneg=[-sp:-sp:-sp*winsize/2]; tpos=[0:sp:sp*winsize/2]; t=[fliplr(tneg) tpos]; win = exp(2*i*pi*fk*t); wavelet(index,:) = win .* hanning(winsize)'; %wavelet{index} = win .* hanning(winsize)'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end; end; % symmetric hanning function function w = hanning(n) if ~rem(n,2) w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end
github
lcnhappe/happe-master
rsget.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/rsget.m
1,800
utf_8
47daf6498859ced84787d07802f22789
% rsget() - get the p-value for a given collection of l-values % (Ramberg-Schmeiser distribution) % % Usage: p = getfit(l, val) % % Input: % l - [l1 l2 l3 l4] l-values for Ramberg-Schmeiser distribution % val - value in the distribution to get a p-value estimate at % % Output: % p - p-value % % Author: Arnaud Delorme, SCCN, 2003 % % see also: rspfunc() % % Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F. % A probability distribution and its uses in fitting data. % Technimetrics, 1979, 21: 201-214. % Copyright (C) 2003 Arnaud Delorme, SCCN, [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 p = rsget( l, val); % plot the curve % -------------- %pval = linspace(0,1, 102); pval(1) = []; pval(end) = []; %rp = l(1) + (pval.^l(3) - (1-pval).^l(4))/l(2); %fp = l(2)*1./(l(3).*(pval.^(l(3)-1)) + l(4).*((1-pval).^(l(4)-1))); %figure; plot(pval, rp); %figure; plot(rp, fp); % find p value for a given val % ---------------------------- p = fminbnd('rspfunc', 0, 1, optimset('TolX',1e-300), l, val);
github
lcnhappe/happe-master
rsfit.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/rsfit.m
6,481
utf_8
ea9ce35750ccb745a5f9471fc6554a91
% rsfit() - find p value for a given value in a given distribution % using Ramberg-Schmeiser distribution % % Usage: >> p = rsfit(x, val) % >> [p c l chi2] = rsfit(x, val, plot) % % Input: % x - [float array] accumulation values % val - [float] value to test % plot - [0|1|2] plot fit. Using 2, the function avoids creating % a new figure. Default: 0. % % Output: % p - p value % c - [mean var skewness kurtosis] distribution cumulants % l - [4x float vector] Ramberg-Schmeiser distribution best fit % parameters. % chi2 - [float] chi2 for goodness of fit (based on 12 bins). % Fit is significantly different from data histogram if % chi2 > 19 (5%) % % Author: Arnaud Delorme, SCCN, 2003 % % See also: rsadjust(), rsget(), rspdfsolv(), rspfunc() % % Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F. % A probability distribution and its uses in fitting data. % Technimetrics, 1979, 21: 201-214. % Copyright (C) 2003 Arnaud Delorme, SCCN, [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 [p, c, l, res] = rsfit(x, val, plotflag) if nargin < 2 help rsfit; return; end; if nargin < 3 plotflag = 0; end; % moments % ------- m1 = mean(x); m2 = sum((x-m1).^2)/length(x); m3 = sum((x-m1).^3)/length(x); m4 = sum((x-m1).^4)/length(x); xmean = m1; xvar = m2; xskew = m3/(m2^1.5); xkurt = m4/(m2^2); c = [ xmean xvar xskew xkurt ]; if xkurt < 0 disp('rsfit error: Can not fit negative kurtosis'); save('/home/arno/temp/dattmp.mat', '-mat', 'x'); disp('data saved to disk in /home/arno/temp/dattmp.mat'); end; % find fit % -------- try, [sol tmp exitcode] = fminsearch('rspdfsolv', [0.1 0.1], optimset('TolX',1e-12, 'MaxFunEvals', 100000000), abs(xskew), xkurt); catch, exitcode = 0; % did not converge end; if ~exitcode try, [sol tmp exitcode] = fminsearch('rspdfsolv', -[0.1 0.1], optimset('TolX',1e-12, 'MaxFunEvals', 100000000), abs(xskew), xkurt); catch, exitcode = 0; end; end; if ~exitcode, error('No convergence'); end; if sol(2)*sol(1) == -1, error('Wrong sign for convergence'); end; %fprintf(' l-val:%f\n', sol); res = rspdfsolv(sol, abs(xskew), xkurt); l3 = sol(1); l4 = sol(2); %load res; %[tmp indalpha3] = min( abs(rangealpha3 - xskew) ); %[tmp indalpha4] = min( abs(rangealpha4 - xkurt) ); %l3 = res(indalpha3,indalpha4,1); %l4 = res(indalpha3,indalpha4,2); %res = res(indalpha3,indalpha4,3); % adjust fit % ---------- [l1 l2 l3 l4] = rsadjust(l3, l4, xmean, xvar, xskew); l = [l1 l2 l3 l4]; p = rsget(l, val); % compute goodness of fit % ----------------------- if nargout > 3 | plotflag % histogram of value 12 bins % -------------------------- [N X] = hist(x, 25); interval = X(2)-X(1); X = [X-interval/2 X(end)+interval/2]; % borders % regroup bin with less than 5 values % ----------------------------------- indices2rm = []; for index = 1:length(N)-1 if N(index) < 5 N(index+1) = N(index+1) + N(index); indices2rm = [ indices2rm index]; end; end; N(indices2rm) = []; X(indices2rm+1) = []; indices2rm = []; for index = length(N):-1:2 if N(index) < 5 N(index-1) = N(index-1) + N(index); indices2rm = [ indices2rm index]; end; end; N(indices2rm) = []; X(indices2rm) = []; % compute expected values % ----------------------- for index = 1:length(X)-1 p1 = rsget( l, X(index+1)); p2 = rsget( l, X(index )); expect(index) = length(x)*(p1-p2); end; % value of X2 % ----------- res = sum(((expect - N).^2)./expect); % plot fit % -------- if plotflag if plotflag ~= 2, figure('paperpositionmode', 'auto'); end; hist(x, 10); % plot fit % -------- xdiff = X(end)-X(1); abscisia = linspace(X(1)-0.2*xdiff, X(end)+0.2*xdiff, 100); %abscisia = (X(1:end-1)+X(2:end))/2; expectplot = zeros(1,length(abscisia)-1); for index = 2:length(abscisia); p1 = rsget( l, abscisia(index-1)); p2 = rsget( l, abscisia(index )); expectplot(index-1) = length(x)*(p2-p1); % have to do this subtraction since this a cumulate density distribution end; abscisia = (abscisia(2:end)+abscisia(1:end-1))/2; hold on; plot(abscisia, expectplot, 'r'); % plot PDF % ---------- pval = linspace(0,1, 102); pval(1) = []; pval(end) = []; rp = l(1) + (pval.^l(3) - (1-pval).^l(4))/l(2); fp = l(2)*1./(l(3).*(pval.^(l(3)-1)) + l(4).*((1-pval).^(l(4)-1))); [maxval index] = max(expect); [tmp closestind] = min(abs(rp - abscisia(index))); fp = fp./fp(closestind)*maxval; plot(rp, fp, 'g'); legend('Chi2 fit (some bins have been grouped)', 'Pdf', 'Data histogram' ); xlabel('Bins'); ylabel('# of data point per bin'); title (sprintf('Fit of distribution using Ramberg-Schmeiser distribution (Chi2 = %2.4g)', res)); end; end; return
github
lcnhappe/happe-master
timewarp.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/timewarp.m
3,452
utf_8
910bc9b6a9fca6b6a50908d815239dc6
% timewarp() - Given two event marker vectors, computes a matrix % that can be used to warp a time series so that its % evlatencies match newlatencies. Values of the warped % timeserie that falls between two frames in the original % timeserie will be linear interpolated. % Usage: % >> warpmat = timewarp(evlatency, newlatency) % % Necessary inputs: % evlatency - [vector] event markers in the original time series, in frames % Markers must be ordered by increasing frame latency. % If you want to warp the entire time-series, make sure % the first (1) and last frames are in the vector. % newlatency - [vector] desired warped event time latencies. The original % time series will be warped so that the frame numbers of its % events (see evlatency above) match the frame numbers in % newlatency. newlatency frames must be sorted by ascending % latency. Both vectors must be the same length. % % Optional outputs: % warpmat - [matrix] Multiplying this matrix with the original % time series (column) vectors performs the warping. % % Example: % % In 10-frame vectors, warp frames 3 and 5 to frames 4 and 8, % % respectively. Generate a matrix to warp data epochs in % % variable 'data' of size (10,k) % >> warpmat = timewarp([1 3 5 10], [1 4 8 10]) % >> warped_data = warpmat*data; % % Authors: Jean Hausser, SCCN/INC/UCSD, 2006 % % See also: angtimewarp(), phasecoher(), erpimage() % function M=timewarp(evLatency, newLatency) M = [0]; if min(sort(evLatency) == evLatency) == 0 error('evLatency should be in ascending order'); return; end if min(sort(newLatency) == newLatency) == 0 error('newLatency should be in ascending order'); return; end if length(evLatency) ~= length(newLatency) error('evLatency and newLatency must have the same length.'); return; end if length(evLatency) < 2 | length(newLatency) < 2 error(['There should be at least two events in evlatency and ' ... 'newlatency (e.g., "begin" and "end")'] ); return; end if evLatency(1) ~= 1 disp(['Assuming old and new time series beginnings are synchronized.']); disp(['Make sure you have defined an ending event in both the old and new time series!']); evLatency(end+1)=1; newLatency(end+1)=1; evLatency = sort(evLatency); newLatency = sort(newLatency); end t = 1:max(evLatency); for k=1:length(evLatency)-1 for i=evLatency(k):evLatency(k+1)-1 tp(i) = (t(i)-evLatency(k)) * ... (newLatency(k+1) - newLatency(k))/... (evLatency(k+1) - evLatency(k)) + ... newLatency(k); end end % Check what's going on at tp(max(newLatency)), should equal t(max(evLatency)) tp(max(evLatency)) = max(newLatency); ts = tp-min(newLatency)+1; % $$$ M = sparse(max(newLatency)-min(newLatency)+1, max(evLatency)); M = zeros(max(newLatency)-min(newLatency)+1, max(evLatency)); k = 0; for i=1:size(M,1) while i > ts(k+1) k = k+1; end % $$$ k = k-1; if k == 0 % Check wether i == ts(1) and i == 1 % In that case, M(1,1) = 1 M(1,1) = 1; else M(i,k) = 1 - (i-ts(k))/(ts(k+1)-ts(k)); M(i,k+1) = 1 - (ts(k+1)-i)/(ts(k+1)-ts(k)); end end
github
lcnhappe/happe-master
angtimewarp.m
.m
happe-master/Packages/eeglab14_0_0b/functions/timefreqfunc/angtimewarp.m
4,683
utf_8
f46e870ae5d7873544a08ffa9a4ff38b
% angtimewarp() - Given two event marker vectors, computes a % warping of the input angular time series so that its % evlatencies match newlatencies. Values of the warped % timeserie that falls between two frames in the original % timeserie will be linearly interpolated under the % assumption that phase change is minimal between two % successive time points. % Usage: % >> warpAngs = angtimewarp(evlatency, newlatency, angData) % % Necessary inputs: % evlatency - [vector] time markers on the original time-series, in % frames. Markers must be ordered by increasing % latency. If you want to warp the entire time series, % make sure frame 1 and the last frame are in the vector. % newlatency - [vector] desired time marker latencies. The original % time series will be warped so that its time markers (see % evlatency) match the ones in newlatency. newlatency % frames must be sorted by ascending latencies in frames. % Both vectors have to be the same length. % angData - [vector] original angular time series (in radians). % Angles should be between -pi and pi. % % Optional outputs: % warpAngs - [vector] warped angular time-course, with values between % -pi and pi % % Example: % >> angs = 2*pi*rand(1,10)-pi; % >> warpangs = angtimewarp([1 5 10], [1 6 10], angs) % % Authors: Jean Hausser, SCCN/INC/UCSD, 2006 % % See also: timeWarp(), phasecoher(), erpimage(), newtimef() % function angdataw=angtimewarp(evLatency, newLatency, angdata) if min(sort(evLatency) == evLatency) == 0 error('evlatency should be sorted'); return; end if min(sort(newLatency) == newLatency) == 0 error('newlatency should be sorted'); return; end if length(evLatency) ~= length(newLatency) error('evlatency and newlatency must have the same length.'); return; end if length(evLatency) < 2 | length(newLatency) < 2 error(['There should be at least two events in evlatency and ' ... 'newlatency, that is "begin" and "end"' ]); return; end if evLatency(1) ~= 1 disp(['Assuming old and new time series beginnings are ' ... 'synchronized']); disp(['Make sure you defined an end event for both old and new time ' ... 'series !']); evLatency(end+1)=1; newLatency(end+1)=1; evLatency = sort(evLatency); newLatency = sort(newLatency); end t = 1:max(evLatency); for k=1:length(evLatency)-1 for i=evLatency(k):evLatency(k+1)-1 tp(i) = (t(i)-evLatency(k)) * ... (newLatency(k+1) - newLatency(k))/... (evLatency(k+1) - evLatency(k)) + ... newLatency(k); end end %Check what's going on at tp(max(newLatency)), should equal t(max(evLatency)) tp(max(evLatency)) = max(newLatency); ts = tp-min(newLatency)+1; angdataw = zeros(1, max(newLatency)-min(newLatency)+1); k = 0; for i=1:length(angdataw) while i > ts(k+1) k = k+1; end if k == 0 angdataw(1) = angdata(1); else %Linear interp angdataw(i) = angdata(k)*(1 - (i-ts(k))/(ts(k+1)-ts(k))) + ... angdata(k+1)*(1 - (ts(k+1)-i)/(ts(k+1)-ts(k))); % %Correction because angles have a ring structure % theta1 = [angdata(k) angdata(k+1) angdataw(i)]; % theta2 = theta1 - min(angdata(k), angdata(k+1)); % theta2max = max(theta2(1), theta2(2)); % if ~ ( (theta2max <= pi & theta2(3) <= theta2max) | ... % (theta2max >= pi & theta2(3) >= theta2max) | ... % theta2(3) == theta2(1) | theta2(3) == theta2(2) ) % angdataw(i) = angdataw(i) + pi; % end % if angdataw(i) > pi %Make sure we're still on [-pi, pi] % angdataw(i) = angdataw(i) - 2*pi; % end end end angdataw = wrap2pi(angdataw); function a = wrap2pi(a, a_center ) % function a = wrap(a,a_center) % % Wraps angles to a range of 2*pi. % Inverse of Matlab's "unwrap", and better than wrapToPi ( which has % redundant [-pi,pi]) % Optional input "a_center" defines the center angle. Default is 0, giving % angles from (-pi,pi], chosen to match angle(complex(-1,0)). Maximum % possible value is pi. % T.Hilmer, UH % 2010.10.18 version 2 % removed code from version 1. Have not bug-checked second input % "a_center" if nargin < 2, a_center = 0; end % new way a = mod(a,2*pi); % [0 2pi) % shift j = a > pi - a_center; a(j) = a(j) - 2*pi; j = a < a_center - pi; a(j) = a(j) + 2*pi;
github
lcnhappe/happe-master
shortread.m
.m
happe-master/Packages/eeglab14_0_0b/functions/miscfunc/shortread.m
2,642
utf_8
7efadd1fb9c9395f1cd3c917e6a93675
% shortread() - Read matrix from short file. % % Usage: % >> A = shortread(filename,size,'format',offset) % % Inputs: % filename - Read matrix a from specified file while assuming four byte % short integers. % size - The vector SIZE determine the number of short elements to be % read and the dimensions of the resulting matrix. If the last % element of SIZE is INF the size of the last dimension is determined % by the file length. % % Optional inputs: % 'format' - The option FORMAT argument specifies the storage format as % defined by fopen(). Default format ([]) is 'native'. % offset - The option OFFSET is offset in shorts from the beginning of file (=0) % to start reading (2-byte shorts assumed). % It uses fseek to read a portion of a large data file. % % Author: Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998 % % See also: floatread(), floatwrite(), fopen() % Copyright (C) Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998 % % 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 % xx-07-98 written by Sigurd Enghoff, Salk Institute % 04-26-99 modified by Sigurd Enghoff to handle variable-sized and % multi-dimensional data. % 07-08-99 modified by Sigurd Enghoff, FORMAT argument added. % 02-08-00 help updated for toolbox inclusion -sm % 02-14-00 added segment arg -sm function A = shortread(fname,Asize,fform,offset) if ~exist('fform') | isempty(fform)|fform==0 fform = 'native'; end fid = fopen(fname,'rb',fform); if fid>0 if exist('offset') stts = fseek(fid,2*offset,'bof'); if stts ~= 0 error('shortread(): fseek() error.'); return end end A = fread(fid,prod(Asize),'short'); else error('shortread(): fopen() error.'); return end fprintf(' %d shorts read\n',prod(size(A))); if Asize(end) == Inf Asize = Asize(1:end-1); A = reshape(A,[Asize length(A)/prod(Asize)]); else A = reshape(A,Asize); end fclose(fid);
github
lcnhappe/happe-master
scanfold.m
.m
happe-master/Packages/eeglab14_0_0b/functions/miscfunc/scanfold.m
2,396
utf_8
fc03538051488f1358961f46484d958d
% scanfold() - scan folder content % % Usage: % >> [cellres textres] = scanfold(foldname); % >> [cellres textres] = scanfold(foldname, ignorelist, maxdepth); % % Inputs: % foldname - [string] name of the folder % ignorelist - [cell] list of folders to ignore % maxdepth - [integer] maximum folder depth % % Outputs: % cellres - cell array containing all the files % textres - string array containing all the names preceeded by "-a" % % Authors: Arnaud Delorme, SCCN, INC, UCSD, 2009 % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 2004, [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 [ cellres, textres ] = scanfold(foldname, ignorelist, maxdepth) if nargin < 2, ignorelist = {}; end; if nargin < 3, maxdepth = 100; end; foldcontent = dir(foldname); textres = ''; cellres = {}; if maxdepth == 0, return; end; for i = 1:length(foldcontent) if (exist(foldcontent(i).name) == 7 || strcmpi(foldcontent(i).name, 'functions')) && ~ismember(foldcontent(i).name, ignorelist) if ~strcmpi(foldcontent(i).name, '..') && ~strcmpi(foldcontent(i).name, '.') disp(fullfile(foldname, foldcontent(i).name)); [tmpcellres tmpres] = scanfold(fullfile(foldname, foldcontent(i).name), ignorelist, maxdepth-1); textres = [ textres tmpres ]; cellres = { cellres{:} tmpcellres{:} }; end; elseif length(foldcontent(i).name) > 2 if strcmpi(foldcontent(i).name(end-1:end), '.m') textres = [ textres ' -a ' foldcontent(i).name ]; cellres = { cellres{:} foldcontent(i).name }; end; else disp( [ 'Skipping ' fullfile(foldname, foldcontent(i).name) ]); end; end; return;
github
lcnhappe/happe-master
datlim.m
.m
happe-master/Packages/eeglab14_0_0b/functions/miscfunc/datlim.m
641
utf_8
f4c0160c492f5049e9dbcc932cafe0e7
% datlim() - return min and max of a matrix % % Usage: % >> limits_vector = datlim(data); % % Input: % data - numeric array % Outputs: % limits_vector = [minval maxval] % % Author: Scott Makeig, SCCN/INC/UCSD, May 28, 2005 function [limits_vector] = datlim(data) if ~isnumeric(data) error('data must be a numeric array') return end limits_vector = [ min(data(:)) max(data(:)) ]; % thanks to Arno Delorme % minval = squeeze(min(data)); maxval = squeeze(max(data)); % while numel(minval) > 1 % minval = squeeze(min(minval)); maxval = squeeze(max(maxval)); % end % limits_vector = [minval maxval];
github
lcnhappe/happe-master
lapplot.m
.m
happe-master/Packages/eeglab14_0_0b/functions/miscfunc/lapplot.m
4,148
utf_8
bbfb726aee519b4b7b446c516439e24f
% lapplot() - Compute the discrete laplacian of EEG scalp distribution(s) % % Usage: % >> laplace = lapplot(map,eloc_file,draw) % % Inputs: % map - Activity levels, size (nelectrodes,nmaps) % eloc_file - Electrode location filename (.loc file) % For format, see >> topoplot example % draw - If defined, draw the map(s) {default: no} % % Output: % laplace - Laplacian map, size (nelectrodes,nmaps) % % Note: uses del2() % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 1998 % % See also: topoplot(), gradplot() % Copyright (C) Scott Makeig, SCCN/INC/UCSD, La Jolla, 1998 % % 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, added links -ad function [laplac] = lapplot(map,filename,draw) if nargin < 2 help lapplot; return; end; MAXCHANS = size(map,1); GRID_SCALE = 2*MAXCHANS+5; MAX_RADIUS = 0.5; % --------------------- % Read the channel file % --------------------- if isstr( filename ) fid = fopen(filename); locations = fscanf(fid,'%d %f %f %s',[7 MAXCHANS]); fclose(fid); locations = locations'; Th = pi/180*locations(:,2); % convert degrees to rads Rd = locations(:,3); ii = find(Rd <= MAX_RADIUS); % interpolate on-scalp channels only Th = Th(ii); Rd = Rd(ii); [x,y] = pol2cart(Th,Rd); else x = real(filename); y = imag(filename); end; % --------------------------------------------------- % Locate nearest position of an electrode in the grid % --------------------------------------------------- xi = linspace(-0.5,0.5,GRID_SCALE); % x-axis description (row vector) yi = linspace(-0.5,0.5,GRID_SCALE); % y-axis description (row vector) for i=1:MAXCHANS [useless_var horizidx(i)] = min(abs(y(i) - xi)); % find pointers to electrode [useless_var vertidx(i)] = min(abs(x(i) - yi)); % positions in Zi end; % ----------------- % Compute laplacian % ----------------- for i=1:size(map,2) [Xi,Yi,Zi] = griddata(y,x,map(:,i),yi',xi, 'v4'); % interpolate data laplac2D = del2(Zi); positions = horizidx + (vertidx-1)*GRID_SCALE; laplac(:,i) = laplac2D(positions(:)); % ------------------ % Draw laplacian map % ------------------ if exist('draw'); mask = (sqrt(Xi.^2+Yi.^2) <= MAX_RADIUS); laplac2D(find(mask==0)) = NaN; subplot(ceil(sqrt(size(map,2))), ceil(sqrt(size(map,2))), i); contour(laplac2D); title( int2str(i) ); % %%% Draw Head %%%% ax = axis; width = ax(2)-ax(1); axis([ax(1)-width/3 ax(2)+width/3 ax(3)-width/3 ax(4)+width/3]) steps = 0:2*pi/100:2*pi; basex = .18*MAX_RADIUS; tip = MAX_RADIUS*1.15; base = MAX_RADIUS-.004; EarX = [.497 .510 .518 .5299 .5419 .54 .547 .532 .510 .489]; EarY = [.0555 .0775 .0783 .0746 .0555 -.0055 -.0932 -.1313 -.1384 -.1199]; HCOLOR = 'k'; HLINEWIDTH = 1.8; % Plot Head, Ears, Nose hold on plot(1+width/2+cos(steps).*MAX_RADIUS*width,... 1+width/2+sin(steps).*MAX_RADIUS*width,... 'color',HCOLOR,'Linestyle','-','LineWidth',HLINEWIDTH); % head plot(1+width/2+[.18*MAX_RADIUS*width;0;-.18*MAX_RADIUS*width],... 1+width/2+[base;tip;base]*width,... 'Color',HCOLOR,'LineWidth',HLINEWIDTH); % nose plot(1+width/2+EarX*width,... 1+width/2+EarY*width,... 'color',HCOLOR,'LineWidth',HLINEWIDTH) % l ear plot(1+width/2-EarX*width,... 1+width/2+EarY*width,... 'color',HCOLOR,'LineWidth',HLINEWIDTH) % r ear hold off axis off end; end; return;
github
lcnhappe/happe-master
compmap.m
.m
happe-master/Packages/eeglab14_0_0b/functions/miscfunc/compmap.m
9,132
utf_8
91717f8d02db6c0193adc7ece08828ca
% compmap() - Plot multiple topoplot() maps of ICA component topographies % Click on an individual map to view separately. % Usage: % >> compmap (winv,'eloc_file',compnos,'title',rowscols,labels,printflag) % % Inputs: % winv - Inverse weight matrix = EEG scalp maps. Each column is a % map; the rows correspond to the electrode positions % defined in the eloc_file. Normally, winv = inv(weights*sphere). % 'eloc_file' - Name of the eloctrode position file in the style defined % by >> topoplot example {default|0 ->'chan_file'} % compnos - Vector telling which (order of) component maps to show % Indices <0 tell compmap to invert a map; = 0 leave blank sbplot % Example [1 0 -2 3 0 -6] {default|0 -> 1:columns_in_winv} % 'title' - Title string for each page {default|0 -> 'ICA Component Maps'} % rowscols - Vector of the form [m,n] where m is total vertical tiles and n % is horizontal tiles per page. If the number of maps exceeds m*n, % multiple figures will be produced {def|0 -> one near-square page}. % labels - Vector of numbers or a matrix of strings to use as labels for % each map, else ' ' -> no labels {default|0 -> 1:ncolumns_in_winv} % printflag - 0= screen-plot colors {default} % 1= printer-plot colors % % Note: Map scaling is to +/-max(abs(data); green = 0 % % Author: Colin Humphries, CNL / Salk Institute, Aug, 1996 % % See also: topoplot() % This function calls topoplot(). and cbar(). % Copyright (C) Colin Humphries & Scott Makeig, CNL / Salk Institute, Aug, 1996 % % 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 % Colin Humphries, CNL / Salk Institute, Aug, 1996 % 03-97 revised -CH % 11-05-97 revised for Matlab 5.0.0.4064; added negative compnnos option % improved help msg; added figure offsets -Scott Makeig & CH % 11-13-97 fixed compnos<0 bug -sm % 11-18-97 added test for labels=comps -sm % 12-08-97 added test for colorbar_tp() -sm % 12-15-97 added axis('square'), see SQUARE below -sm % 03-09-98 added test for eloc_file, fixed size checking for labels -sm % 02-09-00 added test for ' ' for srclabels(1,1) -sm % 02-23-00 added srclabels==' ' -> no labels -sm % 03-16-00 added axcopy() -sm & tpj % 02-25-01 added test for max(compnos) -sm % 05-24-01 added HEADPLOT logical flag below -sm % 01-25-02 reformated help & license -ad % NOTE: % There is a minor problem with the Matlab function colorbar(). % Use the toolbox cbar() instead. function compmap(Winv,eloc_file,compnos,titleval,pagesize,srclabels,printlabel,caxis) DEFAULT_TITLE = 'ICA Component Maps'; DEFAULT_EFILE = 'chan_file'; NUMCONTOUR = 5; % topoplot() style settings OUTPUT = 'screen'; % default: 'screen' for screen colors, % 'printer' for printer colors STYLE = 'both'; INTERPLIMITS = 'head'; MAPLIMITS = 'absmax'; SQUARE = 1; % 1/0 flag making topoplot() asex square -> round heads ELECTRODES = 'on'; % default: 'on' or 'off' ELECTRODESIZE = []; % defaults 1-10 set in topoplot text. HEADPLOT = 0; % 1/0 plot 3-D headplots instead of 2-d topoplots. if nargin<1 help compmap return end curaxes = gca; curpos = get(curaxes,'Position'); mapaxes = axes('Position',[curpos(1) curpos(2)+0.09 curpos(3) curpos(4)-0.09],... 'Visible','off'); % leave room for cbar set(mapaxes,'visible','off'); pos = get(mapaxes,'Position'); % delete(gca); % ax = axes('Position',pos); [chans, frames] = size (Winv); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check inputs and set defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin==8 if strcmp(caxis(1,1:2), 'mi') % min/max of data MAPLIMITS = [min(min(Winv(:,compnos))) max(max(Winv(:,compnos)))]; elseif caxis(1,1:2) == 'ab' % +/-max abs data absmax = max([abs(min(min(Winv(:,compnos)))) abs(max(max(Winv(:,compnos))))]); MAPLIMITS = [-absmax absmax]; elseif size(caxis) == [1,2] % given color axis limits MAPLIMITS = caxis; end % else default end if nargin < 7 printlabel = 0; end if printlabel == 0 printlabel = OUTPUT; % default set above else printlabel = 'printer'; end if nargin < 6 srclabels = 0; end if nargin < 5 pagesize = 0; end if nargin < 4 titleval = 0; end if nargin < 3 compnos = 0; end if nargin < 2 eloc_file = 0; end if srclabels == 0 srclabels = []; end if titleval == 0; titleval = DEFAULT_TITLE; end if compnos == 0 compnos = (1:frames); end if max(compnos)>frames fprintf('compmap(): Cannot show comp %d. Only %d components in inverse weights\n',... max(compnos),frames); return end if pagesize == 0 numsources = length(compnos); DEFAULT_PAGE_SIZE = ... [floor(sqrt(numsources)) ceil(numsources/floor(sqrt(numsources)))]; m = DEFAULT_PAGE_SIZE(1); n = DEFAULT_PAGE_SIZE(2); elseif length(pagesize) ==1 help compmap return else m = pagesize(1); n = pagesize(2); end if eloc_file == 0 eloc_file = DEFAULT_EFILE; end totalsources = length(compnos); if ~isempty(srclabels) if ~ischar(srclabels(1,1)) | srclabels(1,1)==' ' % if numbers if size(srclabels,1) == 1 srclabels = srclabels'; end end if size(srclabels,1)==1 & size(srclabels,2)==1 & srclabels==' ' srclabels = repmat(srclabels,totalsources,1); end if size(srclabels,1) ~= totalsources, fprintf('compmap(): numbers of components and component labels do not agree.\n'); return end end pages = ceil(totalsources/(m*n)); if pages > 1 fprintf('compmap(): will create %d figures of %d by %d maps: ',... pages,m,n); end off = [ 25 -25 0 0]; % position offsets for multiple figures fid = fopen(eloc_file); if fid<1, fprintf('compmap()^G: cannot open eloc_file (%s).\n',eloc_file); return end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%% plot the maps %%%%%%%%%%%%%%%%%%%%%%% for i = (1:pages) if i > 1 figure('Position',pos+(i-1)*off); % place figures in right-downward stack set(gca,'Color','w') %CJH - set background color to white curaxes = gca; curpos = get(curaxes,'Position'); % new whole-figure axes end if (totalsources > i*m*n) sbreak = n*m; else sbreak = totalsources - (i-1)*m*n; % change page/figure after this many end for j = (1:sbreak) % maps on this page/figure comp = j+(i-1)*m*n; % compno index if compnos(comp)~=0 if compnos(comp)>0 source_var = Winv(:,compnos(comp))'; % plot map elseif compnos(comp)<0 source_var = -1*Winv(:,-1*compnos(comp))'; % invert map end sbplot(m,n,j,'ax',mapaxes); if HEADPLOT headplot(source_var,eloc_file,'electrodes','off'); % 3-d image else topoplot(source_var,eloc_file,... 'style',STYLE,... 'electrodes',ELECTRODES,... 'emarkersize',ELECTRODESIZE,... 'numcontour',NUMCONTOUR,... 'interplimits',INTERPLIMITS,... 'maplimits',MAPLIMITS); % draw 2-d scalp map end if SQUARE, axis('square'); end if isempty(srclabels) title(int2str(compnos(comp))) ; else if ischar(srclabels) title(srclabels(comp,:)); else title(num2str(srclabels(comp))); end end drawnow % draw one map at a time end end % ax = axes('Units','Normal','Position',[.5 .06 .32 .05],'Visible','Off'); axes(curaxes); set(gca,'Visible','off','Units','normalized'); curpos = get(gca,'position'); ax = axes('Units','Normalized','Position',... [curpos(1)+0.5*curpos(3) curpos(2)+0.01*curpos(4) ... 0.32*curpos(3) 0.05*curpos(4)],'Visible','Off'); if exist('cbar') == 2 cbar(ax); % Slightly altered Matlab colorbar() % Write authors for further information. else colorbar(ax); % Note: there is a minor problem with this call. end axval = axis; Xlim = get(ax,'Xlim'); set(ax,'XTick',(Xlim(2)+Xlim(1))/2); set(ax,'XTickMode','manual'); set(ax,'XTickLabelMode','manual'); set(ax,'XTickLabel','0'); axes(curaxes); axis off; % axbig = axes('Units','Normalized','Position',[0 0 1 1],'Visible','off'); t1 = text(.25,.07,titleval,'HorizontalAlignment','center'); if pages > 1 fprintf('%d ',i); end axcopy(gcf); % allow popup window of single map with mouse click end if pages > 1 fprintf('\n'); end
github
lcnhappe/happe-master
topoimage.m
.m
happe-master/Packages/eeglab14_0_0b/functions/miscfunc/topoimage.m
21,312
utf_8
952b9066313797fa812f1352f2586565
% topoimage() - plot concatenated multichannel time/frequency images % in a topographic format % Uses a channel location file with the same format as topoplot() % or else plots data on a rectangular grid of axes. % Click on individual images to examine separately. % % Usage: % >> topoimage(data,'chan_locs',ntimes,limits); % >> topoimage(data,[rows cols],ntimes,limits); % >> topoimage(data,'chan_locs',ntimes,limits,title,... % channels,axsize,colors,ydir,rmbase) % % Inputs: % data = data consisting of nchans images, each size (rows,ntimes*chans) % 'chan_locs' = file of channel locations as in >> topoplot example % Else [rows cols] matrix of locations. Example: [6 4] % ntimes = columns per image % [limits] = [mintime maxtime minfreq maxfreq mincaxis maxcaxis] % Give times in msec {default|0 (|both caxis 0) -> use data limits) % 'title' = plot title {0 -> none} % channels = vector of channel numbers to plot & label {0 -> all} % axsize = [x y] axis size {default [.08 .07]} % 'colors' = file of color codes, 3 chars per line % ( '.' = space) {0 -> default color order} % ydir = y-axis polarity (pos-up = 1; neg-up = -1) {def -> pos-up} % rmbase = if ~=0, remove the mean value for times<=0 for each freq {def -> no} % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 12-10-1999 % % See also: topoplot(), timef() % Copyright (C) 12-10-99 Scott Makeig, 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 % 1-16-00 debugged help msg and improved presentation -sm % 3-16-00 added axcopy() -sm % 8-07-00 added logimagesc() via 'LOGIT' -sm % 9-02-00 added RMBASE option below, plus colorbar to key image -sm ??? % 1-25-02 reformated help & license, added link -ad function topoimage(data,loc_file,times,limits,plottitle,channels,axsize,colors,ydr,rmbas) % Options: % LOGIT = 1; % comment out for non-log imaging % YVAL = 10; % plot horizontal lines at 10 Hz (comment to omit) % RMBASE = 0; % remove <0 mean for each image row MAXCHANS = 256; DEFAULT_AXWIDTH = 0.08; DEFAULT_AXHEIGHT = 0.07; DEFAULT_SIGN = 1; % Default - plot positive-up LINEWIDTH = 2.0; FONTSIZE = 14; % font size to use for labels CHANFONTSIZE = 10; % font size to use for channel names TICKFONTSIZE=10; % font size to use for axis labels TITLEFONTSIZE = 16; PLOT_WIDTH = 0.75; % width and height of plot array on figure! PLOT_HEIGHT = 0.81; ISRECT = 0; % default if nargin < 1, help topoimage return end if nargin < 4, help topoimage error('topoimage(): needs four arguments'); end if times <0, help topoimage return elseif times==1, fprintf('topoimage: cannot plot less than 2 times per image.\n'); return else freqs = 0; end; axcolor= get(0,'DefaultAxesXcolor'); % find what the default x-axis color is plotfile = 'topoimage.ps'; ls_plotfile = 'ls -l topoimage.ps'; % %%%%%%%%%%%%%%%%%%%%%%%%%% Substitute defaults for missing parameters %%%%% % SIGN = DEFAULT_SIGN; if nargin < 10 rmbas = 0; end if nargin < 9 ydr = 0; end if ydr == -1 SIGN = -1; end if nargin < 8 colors = 0; end if nargin < 7, axwidth = DEFAULT_AXWIDTH; axheight = DEFAULT_AXHEIGHT; elseif size(axsize) == [1 1] & axsize(1) == 0 axwidth = DEFAULT_AXWIDTH; axheight = DEFAULT_AXHEIGHT; elseif size(axsize) == [1 2] axwidth = axsize(1); axheight = axsize(2); if axwidth > 1 | axwidth < 0 | axheight > 1 | axwidth < 0 help topoimage return end else help topoimage return end [freqs,framestotal]=size(data); % data size chans = framestotal/times; fprintf('\nPlotting data using axis size [%g,%g]\n',axwidth,axheight); if nargin < 6 channels = 0; end if channels == 0 channels = 1:chans; end if nargin < 5 plottitle = 0; %CJH end limitset = 0; if nargin < 4, limits = 0; elseif length(limits)>1 limitset = 1; end %%%%%%%%%%%%%%%%%%%%%%%%%%% Test parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % icadefs; % read MAXPLOTDATACHANS constant from icadefs.m if max(channels) > chans fprintf('topoimage(): max channel index > %d channels in data.\n',... chans); return end if min(channels) < 1 fprintf('topoimage(): min channel index (%g) < 1.\n',... min(channels)); return end; if length(channels)>MAXPLOTDATACHANS, fprintf('topoimage(): not set up to plot more than %d channels.\n',... MAXPLOTDATACHANS); return end; % %%%%%%%%%%%%% Extend the size of the plotting area in the window %%%%%%%%%%%% % curfig = gcf; h=figure(curfig); set(h,'Color',BACKCOLOR); % set the background color set(h,'PaperUnits','normalized'); % use percentages to avoid US/A4 difference set(h,'PaperPosition',[0.0235308 0.0272775 0.894169 0.909249]); % equivalent % orient portrait axis('normal'); % %%%%%%%%%%%%%%%%%%%% Read the channel names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if isstr(channels) == 0, % channames = zeros(MAXPLOTDATACHANS,4); % for c=1:length(channels), % channames(c,:)= sprintf('%4d',channels(c)); % end; channames = num2str(channels(:)); %%CJH else, if ~isstr(channels) fprintf('topoimage(): channel file name must be a string.\n'); return end chid = fopen(channels,'r'); if chid <3, fprintf('topoimage(): cannot open file %s.\n',channels); return end; channames = fscanf(chid,'%s',[4 MAXPLOTDATACHANS]); channames = channames'; [r c] = size(channames); for i=1:r for j=1:c if channames(i,j)=='.', channames(i,j)=' '; end; end; end; end; % setting channames % %%%%%%%%%%%%%%%%%%%%%%%%% Plot and label specified channels %%%%%%%%%%%%%%%%%% % data = matsel(data,times,0,0,channels); chans = length(channels); % %%%%%%%%%%%%%%%%%%%%%%%%% Read the color names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if colors ~=0, if ~isstr(colors) fprintf('topoimage(): color file name must be a string.\n'); return end cid = fopen(colors,'r'); % fprintf('cid = %d\n',cid); if cid <3, fprintf('topoimage: cannot open file %s.\n',colors); return end; colors = fscanf(cid,'%s',[3 MAXPLOTDATAEPOCHS]); colors = colors'; [r c] = size(colors); for i=1:r for j=1:c if colors(i,j)=='.', colors(i,j)=' '; end; end; end; else % use default color order (no yellow!) colors =['r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ';'r ';'b ';'g ';'c ';'m ']; colors = [colors; colors]; % make > 64 available end; for c=1:length(colors) % make white traces black unless axis color is white if colors(c,1)=='w' & axcolor~=[1 1 1] colors(c,1)='k'; end end % %%%%%%%%%%%%%%%%%%%%%%% Read and adjust limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if limits==0, % == 0 or [0 0 0 0] xmin=min(times); xmax=max(times); ymin=min(freqs); ymax=max(freqs); else if length(limits)~=6, fprintf( ... 'topoimage: limits should be 0 or an array [xmin xmax ymin ymax zmin zmax].\n'); return end; xmin = limits(1); xmax = limits(2); ymin = limits(3); ymax = limits(4); zmin = limits(5); zmax = limits(6); end; if xmax == 0 & xmin == 0, x = [0:1:times-1]; xmin = min(x); xmax = max(x); else dx = (xmax-xmin)/(times-1); x=xmin*ones(1,times)+dx*(0:times-1); % compute x-values xmax = xmax*times/times; end; if xmax<=xmin, fprintf('topoimage() - xmax must be > xmin.\n') return end if ymax == 0 & ymin == 0, y=[1:1:freqs]; ymax=freqs; ymin=1; else dy = (ymax-ymin)/(freqs-1); y=ymin*ones(1,freqs)+dy*(0:freqs-1); % compute y-values ymax = max(y); end if ymax<=ymin, fprintf('topoimage() - ymax must be > ymin.\n') return end if zmax == 0 & zmin == 0, zmax=max(max(data)); zmin=min(min(data)); fprintf('Color axis limits [%g,%g]\n',zmin,zmax); end if zmax<=zmin, fprintf('topoimage() - zmax must be > zmin.\n') return end xlabel = 'Time (ms)'; ylabel = 'Hz'; % %%%%%%%%%%%%%%%%%%%%%%%% Set up plotting environment %%%%%%%%%%%%%%%%%%%%%%%%% % h = gcf; % set(h,'YLim',[ymin ymax]); % set default plotting parameters % set(h,'XLim',[xmin xmax]); % set(h,'FontSize',18); % set(h,'DefaultLineLineWidth',1); % for thinner postscript lines % %%%%%%%%%%%%%%%%%%%%%%%%%% Print plot info %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % clf; % clear the current figure % print plottitle over (left) subplot 1 if plottitle==0, plottitle = ''; end h=gca;title(plottitle,'FontSize',TITLEFONTSIZE); % title plot and hold on msg = ['\nPlotting %d traces of %d frames with colors: ']; msg = [msg ' -> \n']; % print starting info on screen . . . fprintf(... '\nlimits: [xmin,xmax,ymin,ymax] = [%4.1f %4.1f %4.2f %4.2f]\n',... xmin,xmax,ymin,ymax); set(h,'YLim',[ymin ymax]); % set default plotting parameters set(h,'XLim',[xmin xmax]); set(h,'FontSize',FONTSIZE); % choose font size set(h,'FontSize',FONTSIZE); % choose font size set(h,'YLim',[ymin ymax]); % set default plotting parameters set(h,'XLim',[xmin xmax]); axis('off') % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Read chan_locs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if size(loc_file,2) == 2 % plot in a rectangular grid ISRECT = 1; ht = loc_file(1); wd = loc_file(2); if chans > ht*wd fprintf(... '\ntopoimage(): (d%) channels to be plotted > grid size [%d %d]\n\n',... chans,ht,wd); return end hht = (ht-1)/2; hwd = (wd-1)/2; xvals = zeros(ht*wd,1); yvals = zeros(ht*wd,1); dist = zeros(ht*wd,1); for i=1:wd for j=1:ht xvals(i+(j-1)*wd) = -hwd+(i-1); yvals(i+(j-1)*wd) = hht-(j-1); dist(i+(j-1)*wd) = sqrt(xvals(j+(i-1)*ht).^2+yvals(j+(i-1)*ht).^2); end end maxdist = max(dist); for i=1:wd for j=1:ht xvals(i+(j-1)*wd) = 0.499*xvals(i+(j-1)*wd)/maxdist; yvals(i+(j-1)*wd) = 0.499*yvals(i+(j-1)*wd)/maxdist; end end channames = repmat(' ',ht*wd,4); for i=1:ht*wd channum = num2str(i); channames(i,1:length(channum)) = channum; end else % read chan_locs file fid = fopen(loc_file); if fid<1, fprintf('topoimage(): cannot open eloc_file "%s"\n',loc_file) return end A = fscanf(fid,'%d %f %f %s',[7 MAXCHANS]); fclose(fid); A = A'; if length(channels) > size(A,1), error('topoimage(): data channels must be <= chan_locs channels') end channames = setstr(A(channels,4:7)); idx = find(channames == '.'); % some labels have dots channames(idx) = setstr(abs(' ')*ones(size(idx))); % replace them with spaces Th = pi/180*A(channels,2); % convert degrees to rads Rd = A(channels,3); % ii = find(Rd <= 0.5); % interpolate on-head channels only % Th = Th(ii); % Rd = Rd(ii); [yvals,xvals] = pol2cart(Th,Rd); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% xvals = 0.5+PLOT_WIDTH*xvals; % controls width of plot array on page! yvals = 0.5+PLOT_HEIGHT*yvals; % controls height of plot array on page! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%% Plot traces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % xdiff=xmax-xmin; rightmost = max(xvals); basetimes = find(x<=0); P=0; Axes = []; fprintf('\ntrace %d: ',P+1); for I=1:chans,%%%%%%%%%% for each data channel %%%%%%%%%%%%%%%%%%%%%%%%%% if P>0 axes(Axes(I)) hold on; % plot down left side of page first axis('off') else % P <= 0 % %%%%%%%%%%%%%%%%%%%%%%% Plot data images %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % xcenter = xvals(I); ycenter = yvals(I); Axes = [Axes axes('Units','Normal','Position', ... [xcenter-axwidth/2 ycenter-axheight/2 axwidth axheight])]; axes(Axes(I)) imageaxes = gca; axislcolor = get(gca,'Xcolor'); %%CJH dataimage = matsel(data,times,0,0,I); if rmbas~=0 % rm baseline dataimage = dataimage ... - repmat(mean(matsel(data,times,basetimes,0,I)')',1,times); end if exist('LOGIT') logimagesc(x,y,dataimage); % <---- plot logfreq image if exist('YVAL') YVAL = log(YVAL); end else imagesc(x,y,dataimage); % <---- plot image end hold on curax = axis; xtk = get(gca,'xtick'); % use these for cal axes below xtkl = get(gca,'xticklabel'); ytk = get(gca,'ytick'); ytkl = get(gca,'yticklabel'); set(gca,'tickdir','out'); set(gca,'ticklength',[0.02 0.05]); set(gca,'xticklabel',[]); set(gca,'yticklabel',[]); set(gca,'ydir','normal'); caxis([zmin zmax]); if exist('YVAL') & YVAL>=curax(3) & YVAL<=curax(4) hold on hp=plot([xmin xmax],[YVAL YVAL],'r-');%,'color',axislcolor); % draw horizontal axis set(hp,'Linewidth',1.0) end if xmin<0 & xmax>0 hold on vl= plot([0 0],[curax(3) curax(4)],'color',axislcolor); % draw vert axis set(vl,'linewidth',2); end % if xcenter == rightmost % colorbar % rightmost = Inf; % end % secondx = 200; % draw second vert axis % axis('off');plot([secondx secondx],[ymin ymax],'color',axislcolor); % %%%%%%%%%%%%%%%%%%%%%%% Print channel names %%%%%%%%%%%%%%%%%%%%%%%%%% % NAME_OFFSET = 0.01; if channels~=0, % print channames if ~ISRECT % print before topographically arrayed image % axis('off'); hold on h=text(xmin-NAME_OFFSET*xdiff,(curax(4)+curax(3))*0.5,[channames(I,:)]); set(h,'HorizontalAlignment','right'); set(h,'FontSize',CHANFONTSIZE); % choose font size else % print before rectangularly arrayed image if xmin<0 xmn = 0; else xmn = xmin; end % axis('off'); h=text(xmin-NAME_OFFSET*xdiff,ymax,[channames(I,:)]); set(h,'HorizontalAlignment','right'); set(h,'FontSize',TICKFONTSIZE); % choose font size end end; % channels end; % P=0 % if xcenter == rightmost % colorbar % rightmost = Inf; % end % if xmin<0 & xmax>0 % axes(imageaxes); % hold on; plot([0 0],[curax(3) curax(4)],'k','linewidth',2); % end drawnow fprintf(' %d',I); end; % %%%%%%%%%%%%%%% chan I %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fprintf('\n'); % %%%%%%%%%%%%%%%%%%%%% Make time and freq cal axis %%%%%%%%%%%%%%%%%%%%%%%%% % ax = axes('Units','Normal','Position', ... [0.80 0.1 axwidth axheight]); axes(ax) axis('off'); imagesc(x,y,zeros(size(dataimage))); hold on % <---- plot green caxis([zmin zmax]); set(gca,'ydir','normal'); if xmin <=0 py=plot([0 0],[curax(3) curax(4)],'color','k'); % draw vert axis at time zero else py=plot([xmin xmin],[curax(3) curax(4)],'color','k'); % vert axis at xmin end hold on if exist('YVAL') & YVAL>=curax(3) px=plot([xmin xmax],[YVAL YVAL],'color',axislcolor); % draw horiz axis at YVAL else px=plot([xmin xmax],[curax(3) curax(4)],'color',axislcolor); % draw horiz axis at ymin end axis(curax); set(gca,'xtick',xtk); % use these for cal axes set(gca,'xticklabel',xtkl); set(gca,'ytick',ytk); set(gca,'yticklabel',ytkl); set(gca,'ticklength',[0.02 0.05]); set(gca,'tickdir','out'); h = colorbar; cbp = get(h,'position'); set(h,'position',[cbp(1) cbp(2) 2*cbp(3) cbp(4)]); caxis([zmin zmax]); % secondx = 200; % draw second vert axis % axis('off');plot([secondx secondx],[curax(3) curax(4)],'color',axislcolor); % %%%%%%%%%%%%%%%%%%%%% Plot axis values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if 0 % DETOUR signx = xmin-0.15*xdiff; axis('off');h=text(signx,SIGN*curax(3),num2str(curax(3),3)); set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','right','Clipping','off'); textx = xmin-0.6*xdiff; axis('off');h=text(textx,(curax(3)+curax(4))/2,ylabel); % text Hz set(h,'Rotation',90); set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center','Clipping','off'); % axis('off');h=text(signx,SIGN*ymax,['+' num2str(ymax,3)]); % text +ymax axis('off');h=text(signx,SIGN*ymax,[ num2str(ymax,3)]); % text ymax set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','right','Clipping','off'); ytick = curax(3)-0.3*(curax(4)-curax(3)); tick = [int2str(xmin)]; h=text(xmin,ytick,tick); % text xmin set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text h=text(xmin+xdiff/2,ytick-0.5*(curax(4)-curax(3)),xlabel);% text Times set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text tick = [int2str(xmax)]; h=text(xmax,ytick,tick); % text xmax set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text axis on set(ax,'xticklabel',''); set(ax,'yticklabel',''); set(ax,'ticklength',[0.02 0.05]); set(ax,'tickdir','out'); caxis([zmin zmax]); hc=colorbar; cmapsize = size(colormap,1); set(hc,'ytick',[1 cmapsize]); % minlabel = num2str(zmin,3); while (length(minlabel)<4) if ~contains(minlabel,'.') minlabel = [minlabel '.']; else minlabel = [minlabel '0']; end end maxlabel = num2str(zmax,3); if zmin<0 & zmax>0 maxlabel = ['+' maxlabel]; end while (length(maxlabel)<length(minlabel)) if ~contains(maxlabel,'.') maxlabel = [maxlabel '.']; else maxlabel = [maxlabel '0']; end end while (length(maxlabel)>length(minlabel)) if ~contains(minlabel,'.') minlabel = [minlabel '.']; else minlabel = [minlabel '0']; end end set(hc,'yticklabel',[minlabel;maxlabel]); set(hc,'Color',BACKCOLOR); set(hc,'Zcolor',BACKCOLOR); end % DETOUR axcopy(gcf); % turn on pop-up axes % %%%%%%%%%%%%%%%%%% Make printed figure fill page %%%%%%%%%%%%%%%%%%%%%%%%%%% % % orient tall % curfig = gcf; % h=figure(curfig); % set(h,'PaperPosition',[0.2 0.3 7.6 10]); % stretch out the plot on the page function [returnval] = contains(strng,chr) returnval=0; for i=1:length(strng) if strng(i)==chr returnval=1; break end end
github
lcnhappe/happe-master
getallmenuseeglab.m
.m
happe-master/Packages/eeglab14_0_0b/functions/miscfunc/getallmenuseeglab.m
3,609
utf_8
3f20087025ca923857b9ce9ec4553255
% getallmenuseeglab() - get all submenus of a window or a menu and return % a tree. The function will also look for callback. % % Usage: % >> [tree nb] = getallmenuseeglab( handler ); % % Inputs: % handler - handler of the window or of a menu % % Outputs: % tree - text output % nb - number of elements in the tree % % 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 [txt, nb, labels] = getallmenuseeglab( handler, level ) NBBLANK = 6; % number of blank for each submenu input if nargin < 1 help getallmenuseeglab; return; end; if nargin < 2 level = 0; end; txt = ''; nb = 0; labels = {}; allmenu = findobj('parent', handler, 'type', 'uimenu'); allmenu = allmenu(end:-1:1); if ~isempty(allmenu) for i=length(allmenu):-1:1 [txtmp nbtmp tmplab] = getallmenuseeglab(allmenu(i), level+1); txtmp = [ '% ' blanks(level*NBBLANK) txtmp ]; txt = [ txtmp txt ]; labels = { tmplab labels{:} }; nb = nb+nbtmp; end; end; try lab = get(handler, 'Label'); cb = get(handler, 'Callback'); cb = extract_callback(cb); if ~isempty(cb) newtxt = [ lab ' - <a href="matlab:helpwin ' cb '">' cb '</a>']; else newtxt = [ lab ]; end; txt = [ newtxt 10 txt ]; %txt = [ get(handler, 'Label') 10 txt ]; nb = nb+1; catch, end; if isempty(labels) labels = { nb }; end; if level == 0 fid = fopen('tmpfile.m', 'w'); fprintf(fid, '%s', txt); fclose(fid); disp(' '); disp('Results saved in tmpfile.m'); end; % transform into array of text % ---------------------------- if nargin < 2 txt = [10 txt]; newtext = zeros(1000, 1000); maxlength = 0; lines = find( txt == 10 ); for index = 1:length(lines)-1 tmptext = txt(lines(index)+1:lines(index+1)-1); if maxlength < length( tmptext ), maxlength = length( tmptext ); end; newtext(index, 1:length(tmptext)) = tmptext; end; txt = char( newtext(1:index+1, 1:maxlength) ); end; % extract plugin name % ------------------- function cbout = extract_callback(cbin); funcList = { 'pop_' 'topoplot' 'eeg_' }; for iList = 1:3 indList = findstr(funcList{iList}, cbin); if ~isempty(indList), if strcmpi(cbin(indList(1):indList(1)+length('pop_stdwarn')-1), 'pop_stdwarn') indList = findstr(funcList{iList}, cbin(indList(1)+1:end))+indList(1); end; break; end; end; if ~isempty(indList) indEndList = find( cbin(indList(1):end) == '(' ); if isempty(indEndList) || indEndList(1) > 25 indEndList = find( cbin(indList(1):end) == ';' ); if cbin(indList(1)+indEndList(1)-2) == ')' indEndList = indEndList-2; end; end; cbout = cbin(indList(1):indList(1)+indEndList(1)-2); else cbout = ''; end;