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
|
lcnhappe/happe-master
|
efficiency.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/bct/efficiency.m
| 1,888 |
utf_8
|
6f4bd3c62d773c46f3e2ac7d16e67a86
|
function E=efficiency(G,local)
%EFFICIENCY Global efficiency, local efficiency.
%
% Eglob = efficiency(A);
% Eloc = efficiency(A,1);
%
% The global efficiency is the average of inverse shortest path length,
% and is inversely related to the characteristic path length.
%
% The local efficiency is the global efficiency computed on the
% neighborhood of the node, and is related to the clustering coefficient.
%
% Inputs: A, binary undirected connection matrix
% local, optional argument
% (local=1 computes local efficiency)
%
% Output: Eglob, global efficiency (scalar)
% Eloc, local efficiency (vector)
%
%
% Algorithm: algebraic path count
%
% Reference: Latora and Marchiori (2001) Phys Rev Lett 87:198701.
%
%
% Mika Rubinov, UNSW, 2008-2010
if ~exist('local','var')
local=0;
end
if local %local efficiency
N=length(G); %number of nodes
E=zeros(N,1); %local efficiency
for u=1:N
V=find(G(u,:)); %neighbors
k=length(V); %degree
if k>=2; %degree must be at least two
e=distance_inv(G(V,V));
E(u)=sum(e(:))./(k^2-k); %local efficiency
end
end
else
N=length(G);
e=distance_inv(G);
E=sum(e(:))./(N^2-N); %global efficiency
end
function D=distance_inv(g)
D=eye(length(g));
n=1;
nPATH=g; %n-path matrix
L=(nPATH~=0); %shortest n-path matrix
while find(L,1);
D=D+n.*L;
n=n+1;
nPATH=nPATH*g;
L=(nPATH~=0).*(D==0);
end
D(~D)=inf; %disconnected nodes are assigned d=inf;
D=1./D; %invert distance
D=D-eye(length(g));
|
github
|
lcnhappe/happe-master
|
generative_model.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/bct/generative_model.m
| 23,153 |
utf_8
|
dd5cd182d827c9ede9fb54855b0cafd8
|
function b = generative_model(A,D,m,modeltype,modelvar,params,epsilon)
%GENERATIVE_MODEL run generative model code
%
% B = GENERATIVE_MODEL(A,D,m,modeltype,modelvar,params)
%
% Generates synthetic networks using the models described in the study by
% Betzel et al (2016) in Neuroimage.
%
% Inputs:
% A, binary network of seed connections
% D, Euclidean distance/fiber length matrix
% m, number of connections that should be present in
% final synthetic network
% modeltype, specifies the generative rule (see below)
% modelvar, specifies whether the generative rules are based on
% power-law or exponential relationship
% ({'powerlaw'}|{'exponential})
% params, either a vector (in the case of the geometric
% model) or a matrix (for all other models) of
% parameters at which the model should be evaluated.
% epsilon, the baseline probability of forming a particular
% connection (should be a very small number
% {default = 1e-5}).
%
% Output:
% B, m x number of networks matrix of connections
%
%
% Full list of model types:
% (each model type realizes a different generative rule)
%
% 1. 'sptl' spatial model
% 2. 'neighbors' number of common neighbors
% 3. 'matching' matching index
% 4. 'clu-avg' average clustering coeff.
% 5. 'clu-min' minimum clustering coeff.
% 6. 'clu-max' maximum clustering coeff.
% 7. 'clu-diff' difference in clustering coeff.
% 8. 'clu-prod' product of clustering coeff.
% 9. 'deg-avg' average degree
% 10. 'deg-min' minimum degree
% 11. 'deg-max' maximum degree
% 12. 'deg-diff' difference in degree
% 13. 'deg-prod' product of degree
%
%
% Example usage:
%
% load demo_generative_models_data
%
% % get number of bi-directional connections
% m = nnz(A)/2;
%
% % get cardinality of network
% n = length(A);
%
% % set model type
% modeltype = 'neighbors';
%
% % set whether the model is based on powerlaw or exponentials
% modelvar = [{'powerlaw'},{'powerlaw'}];
%
% % choose some model parameters
% params = [-2,0.2; -5,1.2; -1,1.5];
% nparams = size(params,1);
%
% % generate synthetic networks
% B = generative_model(Aseed,D,m,modeltype,modelvar,params);
%
% % store them in adjacency matrix format
% Asynth = zeros(n,n,nparams);
% for i = 1:nparams;
% a = zeros(n); a(B(:,i)) = 1; a = a + a';
% Asynth(:,:,i) = a;
% end
%
% Reference: Betzel et al (2016) Neuroimage 124:1054-64.
%
% Richard Betzel, Indiana University/University of Pennsylvania, 2015
if ~exist('epsilon','var')
epsilon = 1e-5;
end
n = length(D);
nparams = size(params,1);
b = zeros(m,nparams);
switch modeltype
case 'clu-avg'
clu = clustering_coef_bu(A);
Kseed = bsxfun(@plus,clu(:,ones(1,n)),clu')/2;
for iparam = 1:nparams
eta = params(iparam,1);
gam = params(iparam,2);
b(:,iparam) = fcn_clu_avg(A,Kseed,D,m,eta,gam,modelvar,epsilon);
end
case 'clu-diff'
clu = clustering_coef_bu(A);
Kseed = abs(bsxfun(@minus,clu(:,ones(1,n)),clu'));
for iparam = 1:nparams
eta = params(iparam,1);
gam = params(iparam,2);
b(:,iparam) = fcn_clu_diff(A,Kseed,D,m,eta,gam,modelvar,epsilon);
end
case 'clu-max'
clu = clustering_coef_bu(A);
Kseed = bsxfun(@max,clu(:,ones(1,n)),clu');
for iparam = 1:nparams
eta = params(iparam,1);
gam = params(iparam,2);
b(:,iparam) = fcn_clu_max(A,Kseed,D,m,eta,gam,modelvar,epsilon);
end
case 'clu-min'
clu = clustering_coef_bu(A);
Kseed = bsxfun(@min,clu(:,ones(1,n)),clu');
for iparam = 1:nparams
eta = params(iparam,1);
gam = params(iparam,2);
b(:,iparam) = fcn_clu_min(A,Kseed,D,m,eta,gam,modelvar,epsilon);
end
case 'clu-prod'
clu = clustering_coef_bu(A);
Kseed = clu*clu';
for iparam = 1:nparams
eta = params(iparam,1);
gam = params(iparam,2);
b(:,iparam) = fcn_clu_prod(A,Kseed,D,m,eta,gam,modelvar,epsilon);
end
case 'deg-avg'
kseed = sum(A,2);
Kseed = bsxfun(@plus,kseed(:,ones(1,n)),kseed')/2;
for iparam = 1:nparams
eta = params(iparam,1);
gam = params(iparam,2);
b(:,iparam) = fcn_deg_avg(A,Kseed,D,m,eta,gam,modelvar,epsilon);
end
case 'deg-diff'
kseed = sum(A,2);
Kseed = abs(bsxfun(@minus,kseed(:,ones(1,n)),kseed'));
for iparam = 1:nparams
eta = params(iparam,1);
gam = params(iparam,2);
b(:,iparam) = fcn_deg_diff(A,Kseed,D,m,eta,gam,modelvar,epsilon);
end
case 'deg-max'
kseed = sum(A,2);
Kseed = bsxfun(@max,kseed(:,ones(1,n)),kseed');
for iparam = 1:nparams
eta = params(iparam,1);
gam = params(iparam,2);
b(:,iparam) = fcn_deg_max(A,Kseed,D,m,eta,gam,modelvar,epsilon);
end
case 'deg-min'
kseed = sum(A,2);
Kseed = bsxfun(@min,kseed(:,ones(1,n)),kseed');
for iparam = 1:nparams
eta = params(iparam,1);
gam = params(iparam,2);
b(:,iparam) = fcn_deg_min(A,Kseed,D,m,eta,gam,modelvar,epsilon);
end
case 'deg-prod'
kseed = sum(A,2);
Kseed = (kseed*kseed').*~eye(n);
for iparam = 1:nparams
eta = params(iparam,1);
gam = params(iparam,2);
b(:,iparam) = fcn_deg_prod(A,Kseed,D,m,eta,gam,modelvar,epsilon);
end
case 'neighbors'
Kseed = (A*A).*~eye(n);
for iparam = 1:nparams
eta = params(iparam,1);
gam = params(iparam,2);
b(:,iparam) = fcn_nghbrs(A,Kseed,D,m,eta,gam,modelvar,epsilon);
end
case 'matching'
Kseed = matching_ind(A);
Kseed = Kseed + Kseed';
for iparam = 1:nparams
eta = params(iparam,1);
gam = params(iparam,2);
b(:,iparam) = fcn_matching(A,Kseed,D,m,eta,gam,modelvar,epsilon);
end
case 'sptl'
for iparam = 1:nparams
eta = params(iparam,1);
b(:,iparam) = fcn_sptl(A,D,m,eta,modelvar{1});
end
end
function b = fcn_clu_avg(A,K,D,m,eta,gam,modelvar,epsilon)
K = K + epsilon;
n = length(D);
mseed = nnz(A)/2;
A = A > 0;
mv1 = modelvar{1};
mv2 = modelvar{2};
switch mv1
case 'powerlaw'
Fd = D.^eta;
case 'exponential'
Fd = exp(eta*D);
end
switch mv2
case 'powerlaw'
Fk = K.^gam;
case 'exponential'
Fk = exp(gam*K);
end
c = clustering_coef_bu(A);
k = sum(A,2);
Ff = Fd.*Fk.*~A;
[u,v] = find(triu(ones(n),1));
indx = (v - 1)*n + u;
P = Ff(indx);
for i = (mseed + 1):m
C = [0; cumsum(P)];
r = sum(rand*C(end) >= C);
uu = u(r);
vv = v(r);
A(uu,vv) = 1;
A(vv,uu) = 1;
k([uu,vv]) = k([uu,vv]) + 1;
bu = A(uu,:);
su = A(bu,bu);
bv = A(vv,:);
sv = A(bv,bv);
bth = bu & bv;
c(bth) = c(bth) + 2./(k(bth).^2 - k(bth));
c(uu) = nnz(su)/(k(uu)*(k(uu) - 1));
c(vv) = nnz(sv)/(k(vv)*(k(vv) - 1));
c(k <= 1) = 0;
bth([uu,vv]) = true;
K(:,bth) = bsxfun(@plus,c(:,ones(1,sum(bth))),c(bth,:)')/2 + epsilon;
K(bth,:) = bsxfun(@plus,c(:,ones(1,sum(bth))),c(bth,:)')'/2 + epsilon;
switch mv2
case 'powerlaw'
Ff(bth,:) = Fd(bth,:).*((K(bth,:)).^gam);
Ff(:,bth) = Fd(:,bth).*((K(:,bth)).^gam);
case 'exponential'
Ff(bth,:) = Fd(bth,:).*exp((K(bth,:))*gam);
Ff(:,bth) = Fd(:,bth).*exp((K(:,bth))*gam);
end
Ff = Ff.*~A;
P = Ff(indx);
end
b = find(triu(A,1));
function b = fcn_clu_diff(A,K,D,m,eta,gam,modelvar,epsilon)
K = K + epsilon;
n = length(D);
mseed = nnz(A)/2;
A = A > 0;
mv1 = modelvar{1};
mv2 = modelvar{2};
switch mv1
case 'powerlaw'
Fd = D.^eta;
case 'exponential'
Fd = exp(eta*D);
end
switch mv2
case 'powerlaw'
Fk = K.^gam;
case 'exponential'
Fk = exp(gam*K);
end
c = clustering_coef_bu(A);
k = sum(A,2);
Ff = Fd.*Fk.*~A;
[u,v] = find(triu(ones(n),1));
indx = (v - 1)*n + u;
P = Ff(indx);
for i = (mseed + 1):m
C = [0; cumsum(P)];
r = sum(rand*C(end) >= C);
uu = u(r);
vv = v(r);
A(uu,vv) = 1;
A(vv,uu) = 1;
k([uu,vv]) = k([uu,vv]) + 1;
bu = A(uu,:);
su = A(bu,bu);
bv = A(vv,:);
sv = A(bv,bv);
bth = bu & bv;
c(bth) = c(bth) + 2./(k(bth).^2 - k(bth));
c(uu) = nnz(su)/(k(uu)*(k(uu) - 1));
c(vv) = nnz(sv)/(k(vv)*(k(vv) - 1));
c(k <= 1) = 0;
bth([uu,vv]) = true;
K(:,bth) = abs(bsxfun(@minus,c(:,ones(1,sum(bth))),c(bth,:)')) + epsilon;
K(bth,:) = abs(bsxfun(@minus,c(:,ones(1,sum(bth))),c(bth,:)'))' + epsilon;
switch mv2
case 'powerlaw'
Ff(bth,:) = Fd(bth,:).*((K(bth,:)).^gam);
Ff(:,bth) = Fd(:,bth).*((K(:,bth)).^gam);
case 'exponential'
Ff(bth,:) = Fd(bth,:).*exp((K(bth,:))*gam);
Ff(:,bth) = Fd(:,bth).*exp((K(:,bth))*gam);
end
Ff = Ff.*~A;
P = Ff(indx);
end
b = find(triu(A,1));
function b = fcn_clu_max(A,K,D,m,eta,gam,modelvar,epsilon)
K = K + epsilon;
n = length(D);
mseed = nnz(A)/2;
A = A > 0;
mv1 = modelvar{1};
mv2 = modelvar{2};
switch mv1
case 'powerlaw'
Fd = D.^eta;
case 'exponential'
Fd = exp(eta*D);
end
switch mv2
case 'powerlaw'
Fk = K.^gam;
case 'exponential'
Fk = exp(gam*K);
end
c = clustering_coef_bu(A);
k = sum(A,2);
Ff = Fd.*Fk.*~A;
[u,v] = find(triu(ones(n),1));
indx = (v - 1)*n + u;
P = Ff(indx);
for i = (mseed + 1):m
C = [0; cumsum(P)];
r = sum(rand*C(end) >= C);
uu = u(r);
vv = v(r);
A(uu,vv) = 1;
A(vv,uu) = 1;
k([uu,vv]) = k([uu,vv]) + 1;
bu = A(uu,:);
su = A(bu,bu);
bv = A(vv,:);
sv = A(bv,bv);
bth = bu & bv;
c(bth) = c(bth) + 2./(k(bth).^2 - k(bth));
c(uu) = nnz(su)/(k(uu)*(k(uu) - 1));
c(vv) = nnz(sv)/(k(vv)*(k(vv) - 1));
c(k <= 1) = 0;
bth([uu,vv]) = true;
K(:,bth) = bsxfun(@max,c(:,ones(1,sum(bth))),c(bth,:)') + epsilon;
K(bth,:) = bsxfun(@max,c(:,ones(1,sum(bth))),c(bth,:)')' + epsilon;
switch mv2
case 'powerlaw'
Ff(bth,:) = Fd(bth,:).*((K(bth,:)).^gam);
Ff(:,bth) = Fd(:,bth).*((K(:,bth)).^gam);
case 'exponential'
Ff(bth,:) = Fd(bth,:).*exp((K(bth,:))*gam);
Ff(:,bth) = Fd(:,bth).*exp((K(:,bth))*gam);
end
Ff = Ff.*~A;
P = Ff(indx);
end
b = find(triu(A,1));
function b = fcn_clu_min(A,K,D,m,eta,gam,modelvar,epsilon)
K = K + epsilon;
n = length(D);
mseed = nnz(A)/2;
A = A > 0;
mv1 = modelvar{1};
mv2 = modelvar{2};
switch mv1
case 'powerlaw'
Fd = D.^eta;
case 'exponential'
Fd = exp(eta*D);
end
switch mv2
case 'powerlaw'
Fk = K.^gam;
case 'exponential'
Fk = exp(gam*K);
end
c = clustering_coef_bu(A);
k = sum(A,2);
Ff = Fd.*Fk.*~A;
[u,v] = find(triu(ones(n),1));
indx = (v - 1)*n + u;
P = Ff(indx);
for i = (mseed + 1):m
C = [0; cumsum(P)];
r = sum(rand*C(end) >= C);
uu = u(r);
vv = v(r);
A(uu,vv) = 1;
A(vv,uu) = 1;
k([uu,vv]) = k([uu,vv]) + 1;
bu = A(uu,:);
su = A(bu,bu);
bv = A(vv,:);
sv = A(bv,bv);
bth = bu & bv;
c(bth) = c(bth) + 2./(k(bth).^2 - k(bth));
c(uu) = nnz(su)/(k(uu)*(k(uu) - 1));
c(vv) = nnz(sv)/(k(vv)*(k(vv) - 1));
c(k <= 1) = 0;
bth([uu,vv]) = true;
K(:,bth) = bsxfun(@min,c(:,ones(1,sum(bth))),c(bth,:)') + epsilon;
K(bth,:) = bsxfun(@min,c(:,ones(1,sum(bth))),c(bth,:)')' + epsilon;
switch mv2
case 'powerlaw'
Ff(bth,:) = Fd(bth,:).*((K(bth,:)).^gam);
Ff(:,bth) = Fd(:,bth).*((K(:,bth)).^gam);
case 'exponential'
Ff(bth,:) = Fd(bth,:).*exp((K(bth,:))*gam);
Ff(:,bth) = Fd(:,bth).*exp((K(:,bth))*gam);
end
Ff = Ff.*~A;
P = Ff(indx);
end
b = find(triu(A,1));
function b = fcn_clu_prod(A,K,D,m,eta,gam,modelvar,epsilon)
K = K + epsilon;
n = length(D);
mseed = nnz(A)/2;
A = A > 0;
mv1 = modelvar{1};
mv2 = modelvar{2};
switch mv1
case 'powerlaw'
Fd = D.^eta;
case 'exponential'
Fd = exp(eta*D);
end
switch mv2
case 'powerlaw'
Fk = K.^gam;
case 'exponential'
Fk = exp(gam*K);
end
c = clustering_coef_bu(A);
k = sum(A,2);
Ff = Fd.*Fk.*~A;
[u,v] = find(triu(ones(n),1));
indx = (v - 1)*n + u;
P = Ff(indx);
for i = (mseed + 1):m
C = [0; cumsum(P)];
r = sum(rand*C(end) >= C);
uu = u(r);
vv = v(r);
A(uu,vv) = 1;
A(vv,uu) = 1;
k([uu,vv]) = k([uu,vv]) + 1;
bu = A(uu,:);
su = A(bu,bu);
bv = A(vv,:);
sv = A(bv,bv);
bth = bu & bv;
c(bth) = c(bth) + 2./(k(bth).^2 - k(bth));
c(uu) = nnz(su)/(k(uu)*(k(uu) - 1));
c(vv) = nnz(sv)/(k(vv)*(k(vv) - 1));
c(k <= 1) = 0;
bth([uu,vv]) = true;
K(bth,:) = (c(bth,:)*c') + epsilon;
K(:,bth) = (c*c(bth,:)') + epsilon;
switch mv2
case 'powerlaw'
Ff(bth,:) = Fd(bth,:).*((K(bth,:)).^gam);
Ff(:,bth) = Fd(:,bth).*((K(:,bth)).^gam);
case 'exponential'
Ff(bth,:) = Fd(bth,:).*exp((K(bth,:))*gam);
Ff(:,bth) = Fd(:,bth).*exp((K(:,bth))*gam);
end
Ff = Ff.*~A;
P = Ff(indx);
end
b = find(triu(A,1));
function b = fcn_deg_avg(A,K,D,m,eta,gam,modelvar,epsilon)
n = length(D);
mseed = nnz(A)/2;
k = sum(A,2);
[u,v] = find(triu(ones(n),1));
indx = (v - 1)*n + u;
D = D(indx);
mv1 = modelvar{1};
mv2 = modelvar{2};
switch mv1
case 'powerlaw'
Fd = D.^eta;
case 'exponential'
Fd = exp(eta*D);
end
K = K + epsilon;
switch mv2
case 'powerlaw'
Fk = K.^gam;
case 'exponential'
Fk = exp(gam*K);
end
P = Fd.*Fk(indx).*~A(indx);
b = zeros(m,1);
b(1:mseed) = find(A(indx));
for i = (mseed + 1):m
C = [0; cumsum(P)];
r = sum(rand*C(end) >= C);
w = [u(r),v(r)];
k(w) = k(w) + 1;
switch mv2
case 'powerlaw'
Fk(:,w) = [((k + k(w(1)))/2) + epsilon, ((k + k(w(2)))/2) + epsilon].^gam;
Fk(w,:) = ([((k + k(w(1)))/2) + epsilon, ((k + k(w(2)))/2) + epsilon].^gam)';
case 'exponential'
Fk(:,w) = exp([((k + k(w(1)))/2) + epsilon, ((k + k(w(2)))/2) + epsilon]*gam);
Fk(w,:) = exp([((k + k(w(1)))/2) + epsilon, ((k + k(w(2)))/2) + epsilon]*gam)';
end
P = Fd.*Fk(indx);
b(i) = r;
P(b(1:i)) = 0;
end
b = indx(b);
function b = fcn_deg_diff(A,K,D,m,eta,gam,modelvar,epsilon)
n = length(D);
mseed = nnz(A)/2;
k = sum(A,2);
[u,v] = find(triu(ones(n),1));
indx = (v - 1)*n + u;
D = D(indx);
mv1 = modelvar{1};
mv2 = modelvar{2};
switch mv1
case 'powerlaw'
Fd = D.^eta;
case 'exponential'
Fd = exp(eta*D);
end
K = K + epsilon;
switch mv2
case 'powerlaw'
Fk = K.^gam;
case 'exponential'
Fk = exp(gam*K);
end
P = Fd.*Fk(indx).*~A(indx);
b = zeros(m,1);
b(1:mseed) = find(A(indx));
for i = (mseed + 1):m
C = [0; cumsum(P)];
r = sum(rand*C(end) >= C);
w = [u(r),v(r)];
k(w) = k(w) + 1;
switch mv2
case 'powerlaw'
Fk(:,w) = (abs([k - k(w(1)), k - k(w(2))]) + epsilon).^gam;
Fk(w,:) = ((abs([k - k(w(1)), k - k(w(2))]) + epsilon).^gam)';
case 'exponential'
Fk(:,w) = exp((abs([k - k(w(1)), k - k(w(2))]) + epsilon)*gam);
Fk(w,:) = exp((abs([k - k(w(1)), k - k(w(2))]) + epsilon)*gam)';
end
P = Fd.*Fk(indx);
b(i) = r;
P(b(1:i)) = 0;
end
b = indx(b);
function b = fcn_deg_min(A,K,D,m,eta,gam,modelvar,epsilon)
n = length(D);
mseed = nnz(A)/2;
k = sum(A,2);
[u,v] = find(triu(ones(n),1));
indx = (v - 1)*n + u;
D = D(indx);
mv1 = modelvar{1};
mv2 = modelvar{2};
switch mv1
case 'powerlaw'
Fd = D.^eta;
case 'exponential'
Fd = exp(eta*D);
end
K = K + epsilon;
switch mv2
case 'powerlaw'
Fk = K.^gam;
case 'exponential'
Fk = exp(gam*K);
end
P = Fd.*Fk(indx).*~A(indx);
b = zeros(m,1);
b(1:mseed) = find(A(indx));
for i = (mseed + 1):m
C = [0; cumsum(P)];
r = sum(rand*C(end) >= C);
w = [u(r),v(r)];
k(w) = k(w) + 1;
switch mv2
case 'powerlaw'
Fk(:,w) = [min(k,k(w(1))) + epsilon, min(k,k(w(2))) + epsilon].^gam;
Fk(w,:) = ([min(k,k(w(1))) + epsilon, min(k,k(w(2))) + epsilon].^gam)';
case 'exponential'
Fk(:,w) = exp([min(k,k(w(1))) + epsilon, min(k,k(w(2))) + epsilon]*gam);
Fk(w,:) = exp([min(k,k(w(1))) + epsilon, min(k,k(w(2))) + epsilon]*gam)';
end
P = Fd.*Fk(indx);
b(i) = r;
P(b(1:i)) = 0;
end
b = indx(b);
function b = fcn_deg_max(A,K,D,m,eta,gam,modelvar,epsilon)
n = length(D);
mseed = nnz(A)/2;
k = sum(A,2);
[u,v] = find(triu(ones(n),1));
indx = (v - 1)*n + u;
D = D(indx);
mv1 = modelvar{1};
mv2 = modelvar{2};
switch mv1
case 'powerlaw'
Fd = D.^eta;
case 'exponential'
Fd = exp(eta*D);
end
K = K + epsilon;
switch mv2
case 'powerlaw'
Fk = K.^gam;
case 'exponential'
Fk = exp(gam*K);
end
P = Fd.*Fk(indx).*~A(indx);
b = zeros(m,1);
b(1:mseed) = find(A(indx));
for i = (mseed + 1):m
C = [0; cumsum(P)];
r = sum(rand*C(end) >= C);
w = [u(r),v(r)];
k(w) = k(w) + 1;
switch mv2
case 'powerlaw'
Fk(:,w) = [max(k,k(w(1))) + epsilon, max(k,k(w(2))) + epsilon].^gam;
Fk(w,:) = ([max(k,k(w(1))) + epsilon, max(k,k(w(2))) + epsilon].^gam)';
case 'exponential'
Fk(:,w) = exp([max(k,k(w(1))) + epsilon, max(k,k(w(2))) + epsilon]*gam);
Fk(w,:) = exp([max(k,k(w(1))) + epsilon, max(k,k(w(2))) + epsilon]*gam)';
end
P = Fd.*Fk(indx);
b(i) = r;
P(b(1:i)) = 0;
end
b = indx(b);
function b = fcn_deg_prod(A,K,D,m,eta,gam,modelvar,epsilon)
n = length(D);
mseed = nnz(A)/2;
k = sum(A,2);
[u,v] = find(triu(ones(n),1));
indx = (v - 1)*n + u;
D = D(indx);
mv1 = modelvar{1};
mv2 = modelvar{2};
switch mv1
case 'powerlaw'
Fd = D.^eta;
case 'exponential'
Fd = exp(eta*D);
end
K = K + epsilon;
switch mv2
case 'powerlaw'
Fk = K.^gam;
case 'exponential'
Fk = exp(gam*K);
end
P = Fd.*Fk(indx).*~A(indx);
b = zeros(m,1);
b(1:mseed) = find(A(indx));
for i = (mseed + 1):m
C = [0; cumsum(P)];
r = sum(rand*C(end) >= C);
w = [u(r),v(r)];
k(w) = k(w) + 1;
switch mv2
case 'powerlaw'
Fk(:,w) = ([k*k(w(1)) + epsilon, k*k(w(2)) + epsilon].^gam);
Fk(w,:) = (([k*k(w(1)) + epsilon, k*k(w(2)) + epsilon].^gam)');
case 'exponential'
Fk(:,w) = exp([k*k(w(1)) + epsilon, k*k(w(2)) + epsilon]*gam);
Fk(w,:) = exp([k*k(w(1)) + epsilon, k*k(w(2)) + epsilon]*gam)';
end
P = Fd.*Fk(indx);
b(i) = r;
P(b(1:i)) = 0;
end
b = indx(b);
function b = fcn_nghbrs(A,K,D,m,eta,gam,modelvar,epsilon)
K = K + epsilon;
n = length(D);
mseed = nnz(A)/2;
A = A > 0;
mv1 = modelvar{1};
mv2 = modelvar{2};
switch mv1
case 'powerlaw'
Fd = D.^eta;
case 'exponential'
Fd = exp(eta*D);
end
switch mv2
case 'powerlaw'
% gam = abs(gam);
Fk = K.^gam;
case 'exponential'
Fk = exp(gam*K);
end
Ff = Fd.*Fk.*~A;
[u,v] = find(triu(ones(n),1));
indx = (v - 1)*n + u;
P = Ff(indx);
for i = (mseed + 1):m
C = [0; cumsum(P)];
r = sum(rand*C(end) >= C);
uu = u(r);
vv = v(r);
x = A(uu,:);
y = A(:,vv);
A(uu,vv) = 1;
A(vv,uu) = 1;
K(uu,y) = K(uu,y) + 1;
K(y,uu) = K(y,uu) + 1;
K(vv,x) = K(vv,x) + 1;
K(x,vv) = K(x,vv) + 1;
switch mv2
case 'powerlaw'
Ff(uu,y) = Fd(uu,y).*(K(uu,y).^gam);
Ff(y,uu) = Ff(uu,y)';
Ff(vv,x) = Fd(vv,x).*(K(vv,x).^gam);
Ff(x,vv) = Ff(vv,x)';
case 'exponential'
Ff(uu,y) = Fd(uu,y).*exp(K(uu,y)*gam);
Ff(y,uu) = Ff(uu,y)';
Ff(vv,x) = Fd(vv,x).*exp(K(vv,x)*gam);
Ff(x,vv) = Ff(vv,x)';
end
Ff(A) = 0;
P = Ff(indx);
end
b = find(triu(A,1));
function b = fcn_matching(A,K,D,m,eta,gam,modelvar,epsilon)
K = K + epsilon;
n = length(D);
mseed = nnz(A)/2;
mv1 = modelvar{1};
mv2 = modelvar{2};
switch mv1
case 'powerlaw'
Fd = D.^eta;
case 'exponential'
Fd = exp(eta*D);
end
switch mv2
case 'powerlaw'
Fk = K.^gam;
case 'exponential'
Fk = exp(gam*K);
end
Ff = Fd.*Fk.*~A;
[u,v] = find(triu(ones(n),1));
indx = (v - 1)*n + u;
P = Ff(indx);
for ii = (mseed + 1):m
C = [0; cumsum(P)];
r = sum(rand*C(end) >= C);
uu = u(r);
vv = v(r);
A(uu,vv) = 1;
A(vv,uu) = 1;
updateuu = find(A*A(:,uu));
updateuu(updateuu == uu) = [];
updateuu(updateuu == vv) = [];
updatevv = find(A*A(:,vv));
updatevv(updatevv == uu) = [];
updatevv(updatevv == vv) = [];
c1 = [A(:,uu)', A(uu,:)];
for i = 1:length(updateuu)
j = updateuu(i);
c2 = [A(:,j)' A(j,:)];
use = ~(~c1&~c2);
use(uu) = 0; use(uu+n) = 0;
use(j) = 0; use(j+n) = 0;
ncon = sum(c1(use))+sum(c2(use));
if (ncon==0)
K(uu,j) = epsilon;
K(j,uu) = epsilon;
else
K(uu,j) = (2*(sum(c1(use)&c2(use))/ncon)) + epsilon;
K(j,uu) = K(uu,j);
end
end
c1 = [A(:,vv)', A(vv,:)];
for i = 1:length(updatevv)
j = updatevv(i);
c2 = [A(:,j)' A(j,:)];
use = ~(~c1&~c2);
use(vv) = 0; use(vv+n) = 0;
use(j) = 0; use(j+n) = 0;
ncon = sum(c1(use))+sum(c2(use));
if (ncon==0)
K(vv,j) = epsilon;
K(j,vv) = epsilon;
else
K(vv,j) = (2*(sum(c1(use)&c2(use))/ncon)) + epsilon;
K(j,vv) = K(vv,j);
end
end
switch mv2
case 'powerlaw'
Fk = K.^gam;
case 'exponential'
Fk = exp(gam*K);
end
Ff = Fd.*Fk.*~A;
P = Ff(indx);
end
b = find(triu(A,1));
function b = fcn_sptl(A,D,m,eta,modelvar)
n = length(D);
mseed = nnz(A)/2;
switch modelvar
case 'powerlaw'
Fd = D.^eta;
case 'exponential'
Fd = exp(eta*D);
end
[u,v] = find(triu(ones(n),1));
indx = (v - 1)*n + u;
P = Fd(indx).*~A(indx);
b = zeros(m,1);
b(1:mseed) = find(A(indx));
for i = (mseed + 1):m
C = [0; cumsum(P)];
r = sum(rand*C(end) >= C);
b(i) = r;
P = Fd(indx);
P(b(1:i)) = 0;
end
b = indx(b);
|
github
|
lcnhappe/happe-master
|
evaluate_generative_model.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/bct/evaluate_generative_model.m
| 3,625 |
utf_8
|
6c6df608db42f67c0908af434bff6aca
|
function [B,E,K] = evaluate_generative_model(A,Atgt,D,modeltype,modelvar,params)
% EVALUATE_GENERATIVE_MODEL generate and evaluate synthetic networks
%
% [B,E,K] = EVALUATE_GENERATIVE_MODEL(A,Atgt,D,m,modeltype,modelvar,params)
%
% Generates synthetic networks and evaluates their energy function (see
% below) using the models described in the study by Betzel et al (2016)
% in Neuroimage.
%
% Inputs:
% A, binary network of seed connections
% Atgt, binary network against which synthetic networks are
% compared
% D, Euclidean distance/fiber length matrix
% m, number of connections that should be present in
% final synthetic network
% modeltype, specifies the generative rule (see below)
% modelvar, specifies whether the generative rules are based on
% power-law or exponential relationship
% ({'powerlaw'}|{'exponential})
% params, either a vector (in the case of the geometric
% model) or a matrix (for all other models) of
% parameters at which the model should be evaluated.
%
% Outputs:
% B, m x number of networks matrix of connections
% E, energy for each synthetic network
% K, Kolmogorov-Smirnov statistics for each synthetic
% network.
%
% Full list of model types:
% (each model type realizes a different generative rule)
%
% 1. 'sptl' spatial model
% 2. 'neighbors' number of common neighbors
% 3. 'matching' matching index
% 4. 'clu-avg' average clustering coeff.
% 5. 'clu-min' minimum clustering coeff.
% 6. 'clu-max' maximum clustering coeff.
% 7. 'clu-diff' difference in clustering coeff.
% 8. 'clu-prod' product of clustering coeff.
% 9. 'deg-avg' average degree
% 10. 'deg-min' minimum degree
% 11. 'deg-max' maximum degree
% 12. 'deg-diff' difference in degree
% 13. 'deg-prod' product of degree
%
% Note: Energy is calculated in exactly the same way as in Betzel et
% al (2016). There are four components to the energy are KS statistics
% comparing degree, clustering coefficient, betweenness centrality, and
% edge length distributions. Energy is calculated as the maximum across
% all four statistics.
%
% Reference: Betzel et al (2016) Neuroimage 124:1054-64.
%
% Richard Betzel, Indiana University/University of Pennsylvania, 2015
m = nnz(Atgt)/2;
n = length(Atgt);
x = cell(4,1);
x{1} = sum(Atgt,2);
x{2} = clustering_coef_bu(Atgt);
x{3} = betweenness_bin(Atgt)';
x{4} = D(triu(Atgt,1) > 0);
B = generative_model(A,D,m,modeltype,modelvar,params);
nB = size(B,2);
K = zeros(nB,4);
for iB = 1:nB
b = zeros(n);
b(B(:,iB)) = 1;
b = b + b';
y = cell(4,1);
y{1} = sum(b,2);
y{2} = clustering_coef_bu(b);
y{3} = betweenness_bin(b)';
y{4} = D(triu(b,1) > 0);
for j = 1:4
K(iB,j) = fcn_ks(x{j},y{j});
end
end
E = max(K,[],2);
function kstat = fcn_ks(x1,x2)
binEdges = [-inf ; sort([x1;x2]) ; inf];
binCounts1 = histc (x1 , binEdges, 1);
binCounts2 = histc (x2 , binEdges, 1);
sumCounts1 = cumsum(binCounts1)./sum(binCounts1);
sumCounts2 = cumsum(binCounts2)./sum(binCounts2);
sampleCDF1 = sumCounts1(1:end-1);
sampleCDF2 = sumCounts2(1:end-1);
deltaCDF = abs(sampleCDF1 - sampleCDF2);
kstat = max(deltaCDF);
|
github
|
lcnhappe/happe-master
|
make_motif34lib.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/bct/make_motif34lib.m
| 2,838 |
utf_8
|
68f4ca45316fc99ab16adbd5bda80236
|
function make_motif34lib
%MAKE_MOTIF34LIB Auxiliary motif library function
%
% make_motif34lib;
%
% This function generates the motif34lib.mat library required for all
% other motif computations.
%
%
% Mika Rubinov, UNSW, 2007-2010
%#ok<*ASGLU>
[M3,M3n,ID3,N3]=motif3generate;
[M4,M4n,ID4,N4]=motif4generate;
save motif34lib;
function [M,Mn,ID,N]=motif3generate
n=0;
M=false(54,6); %isomorphs
CL=zeros(54,6,'uint8'); %canonical labels (predecessors of IDs)
cl=zeros(1,6,'uint8');
for i=0:2^6-1 %loop through all subgraphs
m=dec2bin(i);
m=[num2str(zeros(1,6-length(m)), '%d') m]; %#ok<AGROW>
G=str2num ([ ...
'0' ' ' m(3) ' ' m(5) ;
m(1) ' ' '0' ' ' m(6) ;
m(2) ' ' m(4) ' ' '0' ]); %#ok<ST2NM>
Ko=sum(G,2);
Ki=sum(G,1).';
if all(Ko|Ki), %if subgraph weakly-connected
n=n+1;
cl(:)=sortrows([Ko Ki]).';
CL(n,:)=cl; %assign motif label to isomorph
M(n,:)=G([2:4 6:8]);
end
end
[u1,u2,ID]=unique(CL,'rows'); %convert CLs into motif IDs
%convert IDs into Sporns & Kotter classification
id_mika= [1 3 4 6 7 8 11];
id_olaf= -[3 6 1 11 4 7 8];
for id=1:length(id_mika)
ID(ID==id_mika(id))=id_olaf(id);
end
ID=abs(ID);
[X,ind]=sortrows(ID);
ID=ID(ind,:); %sort IDs
M=M(ind,:); %sort isomorphs
N=sum(M,2); %number of edges
Mn=uint32(sum(repmat(10.^(5:-1:0),size(M,1),1).*M,2)); %M as a single number
function [M,Mn,ID,N]=motif4generate
n=0;
M=false(3834,12); %isomorphs
CL=zeros(3834,16,'uint8'); %canonical labels (predecessors of IDs)
cl=zeros(1,16,'uint8');
for i=0:2^12-1 %loop through all subgraphs
m=dec2bin(i);
m=[num2str(zeros(1,12-length(m)), '%d') m]; %#ok<AGROW>
G=str2num ([ ...
'0' ' ' m(4) ' ' m(7) ' ' m(10) ;
m(1) ' ' '0' ' ' m(8) ' ' m(11) ;
m(2) ' ' m(5) ' ' '0' ' ' m(12) ;
m(3) ' ' m(6) ' ' m(9) ' ' '0' ]); %#ok<ST2NM>
Gs=G+G.';
v=Gs(1,:);
for j=1:2,
v=any(Gs(v~=0,:),1)+v;
end
if v %if subgraph weakly connected
n=n+1;
G2=(G*G)~=0;
Ko=sum(G,2);
Ki=sum(G,1).';
Ko2=sum(G2,2);
Ki2=sum(G2,1).';
cl(:)=sortrows([Ki Ko Ki2 Ko2]).';
CL(n,:)=cl; %assign motif label to isomorph
M(n,:)=G([2:5 7:10 12:15]);
end
end
[u1,u2,ID]=unique(CL,'rows'); %convert CLs into motif IDs
[X,ind]=sortrows(ID);
ID=ID(ind,:); %sort IDs
M=M(ind,:); %sort isomorphs
N=sum(M,2); %number of edges
Mn=uint64(sum(repmat(10.^(11:-1:0),size(M,1),1).*M,2)); %M as a single number
|
github
|
lcnhappe/happe-master
|
LoadBinary.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neuroscope/LoadBinary.m
| 9,722 |
iso_8859_13
|
ac6b47d239db8b0b4e76bb90c8d6263b
|
function data = LoadBinary(filename,varargin)
%LoadBinary - Load data from a multiplexed binary file.
%
% Reading a subset of the data can be done in two different manners: either
% by specifying start time and duration (more intuitive), or by indicating
% the position and size of the subset in terms of number of records (more
% accurate) - a 'record' is a chunk of data containing one sample for each
% channel.
%
% LoadBinary can also deal with lists of start times and durations (or
% offsets and number of records).
%
% USAGE
%
% data = LoadBinary(filename,<options>)
%
% filename file to read
% <options> optional list of property-value pairs (see table below)
%
% =========================================================================
% Properties Values
% -------------------------------------------------------------------------
% 'frequency' sampling rate (in Hz, default = 20kHz)
% 'start' position to start reading (in s, default = 0)
% 'duration' duration to read (in s, default = Inf)
% 'offset' position to start reading (in records, default = 0)
% 'nRecords' number of records to read (default = Inf)
% 'samples' same as above (for backward compatibility reasons)
% 'nChannels' number of data channels in the file (default = 1)
% 'channels' channels to read (default = all)
% 'precision' sample precision (default = 'int16')
% 'skip' number of records to skip after each record is read
% (default = 0)
% =========================================================================
% Copyright (C) 2004-2013 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
% Default values
nChannels = 1;
precision = 'int16';
skip = 0;
frequency = 20000;
channels = [];
start = 0;
duration = Inf;
offset = 0;
nRecords = Inf;
time = false;
records = false;
if nargin < 1 | mod(length(varargin),2) ~= 0,
error('Incorrect number of parameters (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).');
end
% Parse options
for i = 1:2:length(varargin),
if ~ischar(varargin{i}),
error(['Parameter ' num2str(i+3) ' is not a property (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).']);
end
switch(lower(varargin{i})),
case 'frequency',
frequency = varargin{i+1};
if ~isdscalar(frequency,'>0'),
error('Incorrect value for property ''frequency'' (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).');
end
case 'start',
start = varargin{i+1};
if ~isdvector(start),
error('Incorrect value for property ''start'' (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).');
end
if start < 0, start = 0; end
time = true;
case 'duration',
duration = varargin{i+1};
if ~isdvector(duration,'>=0'),
error('Incorrect value for property ''duration'' (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).');
end
time = true;
case 'offset',
offset = varargin{i+1};
if ~isivector(offset),
error('Incorrect value for property ''offset'' (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).');
end
if offset < 0, offset = 0; end
records = true;
case {'nrecords','samples'},
nRecords = varargin{i+1};
if ~isivector(nRecords,'>=0'),
error('Incorrect value for property ''nRecords'' (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).');
end
if length(nRecords) > 1 && any(isinf(nRecords(1:end-1))),
error('Incorrect value for property ''nRecords'' (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).');
end
records = true;
case 'nchannels',
nChannels = varargin{i+1};
if ~isiscalar(nChannels,'>0'),
error('Incorrect value for property ''nChannels'' (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).');
end
case 'channels',
channels = varargin{i+1};
if ~isivector(channels,'>=0'),
error('Incorrect value for property ''channels'' (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).');
end
case 'precision',
precision = varargin{i+1};
if ~isstring(precision),
error('Incorrect value for property ''precision'' (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).');
end
case 'skip',
skip = varargin{i+1};
if ~isiscalar(skip,'>=0'),
error('Incorrect value for property ''skip'' (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).');
end
otherwise,
error(['Unknown property ''' num2str(varargin{i}) ''' (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).']);
end
end
% Either start+duration, or offset+size
if time && records,
error(['Data subset can be specified either in time or in records, but not both (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).']);
end
% By default, load all channels
if isempty(channels),
channels = 1:nChannels;
end
% Check consistency between channel IDs and number of channels
if any(channels>nChannels),
error('Cannot load specified channels (listed channel IDs inconsistent with total number of channels).');
end
% Open file
if ~exist(filename),
error(['File ''' filename ''' not found.']);
end
f = fopen(filename,'r');
if f == -1,
error(['Cannot read ' filename ' (insufficient access rights?).']);
end
% Size of one data point (in bytes)
sampleSize = 0;
switch precision,
case {'uchar','unsigned char','schar','signed char','int8','integer*1','uint8','integer*1'},
sampleSize = 1;
case {'int16','integer*2','uint16','integer*2'},
sampleSize = 2;
case {'int32','integer*4','uint32','integer*4','single','real*4','float32','real*4'},
sampleSize = 4;
case {'int64','integer*8','uint64','integer*8','double','real*8','float64','real*8'},
sampleSize = 8;
end
% Position and number of records of the data subset
if time,
if length(duration) == 1,
duration = repmat(duration,size(start,1),1);
elseif length(duration) ~= length(start),
error('Start and duration lists have different lengths (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).');
end
dataOffset = floor(start*frequency)*nChannels*sampleSize;
nRecords = floor(duration*frequency);
else
if length(nRecords) == 1,
nRecords = repmat(nRecords,size(offset,1),1);
elseif length(nRecords) ~= length(offset),
error('Offset and number of records lists have different lengths (type ''help <a href="matlab:help LoadBinary">LoadBinary</a>'' for details).');
end
dataOffset = offset*nChannels*sampleSize;
end
% Determine total number of records in file
fileStart = ftell(f);
status = fseek(f,0,'eof');
if status ~= 0,
fclose(f);
error('Error reading the data file (possible reasons include trying to read past the end of the file).');
end
fileStop = ftell(f);
% Last number of records may be infinite, compute explicit value
if isinf(nRecords(end)),
status = fseek(f,dataOffset(end),'bof');
if status ~= 0,
fclose(f);
error('Error reading the data file (possible reasons include trying to read past the end of the file).');
end
lastOffset = ftell(f);
lastNRecords = floor((fileStop-lastOffset)/nChannels/sampleSize);
nRecords(end) = lastNRecords;
end
% Preallocate memory
data = zeros(sum(nRecords)/(skip+1),length(channels));
% Loop through list of start+duration or offset+nRecords
i = 1;
for k = 1:length(dataOffset),
% Position file index for reading
status = fseek(f,dataOffset(k),'bof');
fileOffset = ftell(f);
if status ~= 0,
fclose(f);
error('Could not start reading (possible reasons include trying to read past the end of the file).');
end
% (floor in case all channels do not have the same number of samples)
maxNRecords = floor((fileStop-fileOffset)/nChannels/sampleSize);
if nRecords(k) > maxNRecords, nRecords(k) = maxNRecords; end
% For large amounts of data, read chunk by chunk
maxSamplesPerChunk = 10000;
nSamples = nRecords(k)*nChannels;
if nSamples <= maxSamplesPerChunk,
d = LoadChunk(f,nChannels,channels,nRecords(k),precision,skip*sampleSize);
[m,n] = size(d);
if m == 0, break; end
data(i:i+m-1,:) = d;
i = i+m;
else
% Determine chunk duration and number of chunks
nSamplesPerChunk = floor(maxSamplesPerChunk/nChannels)*nChannels;
nChunks = floor(nSamples/nSamplesPerChunk)/(skip+1);
% Read all chunks
for j = 1:nChunks,
d = LoadChunk(f,nChannels,channels,nSamplesPerChunk/nChannels,precision,skip*sampleSize);
[m,n] = size(d);
if m == 0, break; end
data(i:i+m-1,:) = d;
i = i+m;
end
% If the data size is not a multiple of the chunk size, read the remainder
remainder = nSamples - nChunks*nSamplesPerChunk;
if remainder ~= 0,
d = LoadChunk(f,nChannels,channels,remainder/nChannels,precision,skip*sampleSize);
[m,n] = size(d);
if m == 0, break; end
data(i:i+m-1,:) = d;
i = i+m;
end
end
end
fclose(f);
% ---------------------------------------------------------------------------------------------------------
function data = LoadChunk(fid,nChannels,channels,nSamples,precision,skip)
if skip ~= 0,
data = fread(fid,[nChannels nSamples],[int2str(nChannels) '*' precision],skip*nChannels);
else
data = fread(fid,[nChannels nSamples],precision);
end
data = data';
if isempty(data),
warning('No data read (trying to read past file end?)');
elseif ~isempty(channels),
data = data(:,channels);
end
|
github
|
lcnhappe/happe-master
|
isivector.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neuroscope/private/isivector.m
| 2,128 |
iso_8859_13
|
1468dbe277d48ba93d39a34470a2a792
|
%isivector - Test if parameter is a vector of integers satisfying an optional list of tests.
%
% USAGE
%
% test = isivector(x,test1,test2,...)
%
% x parameter to test
% test1... optional list of additional tests (see examples below)
%
% EXAMPLES
%
% % Test if x is a vector of doubles
% isivector(x)
%
% % Test if x is a vector of strictly positive doubles
% isivector(x,'>0')
%
% % Test if x is a vector of doubles included in [2,3]
% isivector(x,'>=2','<=3')
%
% % Special test: test if x is a vector of doubles of length 3
% isivector(x,'#3')
%
% % Special test: test if x is a vector of strictly ordered doubles
% isivector(x,'>')
%
% NOTE
%
% The tests ignore NaNs, e.g. isivector([500 nan]), isivector([1 nan 3],'>0') and
% isivector([nan -7],'<=0') all return 1.
%
% SEE ALSO
%
% See also isdmatrix, isdvector, isdscalar, isimatrix, isiscalar, isstring,
% islscalar, islvector, islmatrix.
%
% Copyright (C) 2010 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
function test = isivector(x,varargin)
% Check number of parameters
if nargin < 1,
error('Incorrect number of parameters (type ''help <a href="matlab:help isivector">isivector</a>'' for details).');
end
% Test: double, vector
test = isa(x,'double') & isvector(x);
% Ignore NaNs
x = x(~isnan(x));
% Test: integers?
test = test & all(round(x)==x);
% Optional tests
for i = 1:length(varargin),
try
if varargin{i}(1) == '#',
if length(x) ~= str2num(varargin{i}(2:end)), test = false; return; end
elseif isstring(varargin{i},'>','>=','<','<='),
dx = diff(x);
if ~eval(['all(0' varargin{i} 'dx);']), test = false; return; end
else
if ~eval(['all(x' varargin{i} ');']), test = false; return; end
end
catch err
error(['Incorrect test ''' varargin{i} ''' (type ''help <a href="matlab:help isivector">isivector</a>'' for details).']);
end
end
|
github
|
lcnhappe/happe-master
|
isradians.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neuroscope/private/isradians.m
| 1,179 |
iso_8859_13
|
b6d8ed7786fab2bd646134c1424d8304
|
%isradians - Test if parameter is in range [0,2pi] or [-pi,pi].
%
% USAGE
%
% test = isradians(x)
%
% x array to test (NaNs are ignored)
%
% OUTPUT
%
% range 0 if uncertain (issues a warning)
% 1 for [-pi,pi]
% 2 for [0,2pi]
% SEE ALSO
%
% See also wrap.
%
% Copyright (C) 2010 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
function test = isradians(x)
% Check number of parameters
if nargin < 1,
error('Incorrect number of parameters (type ''help <a href="matlab:help isradians">isradians</a>'' for details).');
end
if ~isa(x,'double'), test = 0; return; end
% Ignore NaN
x = x(~isnan(x));
if isempty(x), test = 0; return; end
% Min and max
x = x(:);
m = min(x);
M = max(x);
% Range test
if m >= -pi && M <= pi,
test = 1;
elseif m >=0 && M <= 2*pi,
test = 2;
else
warning('Angles are neither in [0,2pi] nor in [-pi,pi] (make sure they are in radians).');
test = 0;
end
|
github
|
lcnhappe/happe-master
|
isiscalar.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neuroscope/private/isiscalar.m
| 1,623 |
iso_8859_13
|
6b14f01efdb2893077da44a97760eecd
|
%isiscalar - Test if parameter is a scalar (integer) satisfying an optional list of tests.
%
% USAGE
%
% test = isiscalar(x,test1,test2,...)
%
% x parameter to test
% test1... optional list of additional tests
%
% EXAMPLES
%
% % Test if x is a scalar (double)
% isiscalar(x)
%
% % Test if x is a strictly positive scalar (double)
% isiscalar(x,'>0')
%
% % Test if x is a scalar (double) included in [2,3]
% isiscalar(x,'>=2','<=3')
%
% NOTE
%
% The tests ignore NaN, e.g. isiscalar(nan), isiscalar(nan,'>0') and isiscalar(nan,'<=0')
% all return 1.
%
% SEE ALSO
%
% See also isdmatrix, isdvector, isdscalar, isimatrix, isivector, isstring,
% islscalar, islvector, islmatrix.
%
% Copyright (C) 2010 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
function test = isiscalar(x,varargin)
% Check number of parameters
if nargin < 1,
error('Incorrect number of parameters (type ''help <a href="matlab:help isiscalar">isiscalar</a>'' for details).');
end
% Test: double, scalar
test = isa(x,'double') & isscalar(x);
if ~test, return; end
% Test: integers?
test = test & round(x)==x;
% Optional tests
for i = 1:length(varargin),
try
if ~eval(['x' varargin{i} ';']), test = false; return; end
catch err
error(['Incorrect test ''' varargin{i} ''' (type ''help <a href="matlab:help isiscalar">isiscalar</a>'' for details).']);
end
end
|
github
|
lcnhappe/happe-master
|
islvector.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neuroscope/private/islvector.m
| 1,685 |
iso_8859_13
|
0dfac49b5831a12166d7cfbeafcd5445
|
%islvector - Test if parameter is a (pseudo) logical vector satisfying an optional list of tests.
%
% USAGE
%
% test = islvector(x,test1,test2,...)
%
% x parameter to test
% test1... optional list of additional tests (see examples below)
%
% EXAMPLES
%
% % Test if x is a logical vector
% islvector(x)
%
% % Special test: test if x is a logical vector of length 3
% islvector(x,'#3')
%
% NOTE
%
% To be considered logical, the vector should contain only values 0 and 1, but it
% does not need to actually be of class 'logical' (class(x) could be e.g. 'double').
%
% SEE ALSO
%
% See also islscalar, islmatrix, isdmatrix, isdvector, isdscalar, isimatrix, isiscalar,
% isstring.
%
% Copyright (C) 2010-2011 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
function test = islvector(x,varargin)
% Check number of parameters
if nargin < 1,
error('Incorrect number of parameters (type ''help <a href="matlab:help islvector">islvector</a>'' for details).');
end
% Test: logical, vector
test = islogical(x) & isvector(x);
% Optional tests
for i = 1:length(varargin),
try
if varargin{i}(1) == '#',
if length(x) ~= str2num(varargin{i}(2:end)), test = false; return; end
end
catch err
error(['Incorrect test ''' varargin{i} ''' (type ''help <a href="matlab:help islvector">islvector</a>'' for details).']);
end
end
function test = islogical(x)
test = builtin('islogical',x) | all(x(:)==0|x(:)==1);
|
github
|
lcnhappe/happe-master
|
wrap.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neuroscope/private/wrap.m
| 974 |
iso_8859_13
|
9fba4315faafeb5a9184f843e7593872
|
%wrap - Set radian angles in range [0,2pi] or [-pi,pi].
%
% USAGE
%
% y = wrap(x,range)
%
% x angles in radians
% range optional: 1 for [-pi,pi] (default)
% 2 for [0,2pi]
%
% SEE ALSO
%
% See also isradians.
%
% Copyright (C) 2010-2011 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
function y = wrap(x,range)
% Check number of parameters
if nargin < 1,
error('Incorrect number of parameters (type ''help <a href="matlab:help wrap">wrap</a>'' for details).');
end
if nargin < 2,
range = 1;
end
if ~isa(x,'double'), y = []; return; end
% Determine angle in [0,2*pi]
y = mod(x,2*pi);
% Change range if necessary
if range == 1,
change = y > pi;
y(change) = y(change)-2*pi;
end
|
github
|
lcnhappe/happe-master
|
isimatrix.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neuroscope/private/isimatrix.m
| 1,711 |
iso_8859_13
|
301153c731a86f3cf9ab2cd3471a5d60
|
%isimatrix - Test if parameter is a matrix of integers (>= 2 columns).
%
% USAGE
%
% test = isimatrix(x,test1,test2,...)
%
% x parameter to test
% test1... optional list of additional tests
%
% EXAMPLES
%
% % Test if x is a matrix of doubles
% isimatrix(x)
%
% % Test if x is a matrix of strictly positive doubles
% isimatrix(x,'>0')
%
% NOTE
%
% The tests ignore NaNs, e.g. isimatrix([500 nan;4 79]), isimatrix([1 nan 3],'>0') and
% isimatrix([nan -7;nan nan;-2 -5],'<=0') all return 1.
%
% SEE ALSO
%
% See also isdmatrix, isdvector, isdscalar, isivector, isiscalar, isstring,
% islscalar, islvector, islmatrix.
%
% Copyright (C) 2010 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
function test = isimatrix(x,varargin)
% Check number of parameters
if nargin < 1,
error('Incorrect number of parameters (type ''help <a href="matlab:help isimatrix">isimatrix</a>'' for details).');
end
% Test: doubles, two dimensions, two or more columns?
test = isa(x,'double') & length(size(x)) == 2 & size(x,2) >= 2;
% Ignore NaNs (this reshapes the matrix, but it does not matter for the remaining tests)
x = x(~isnan(x));
% Test: integers?
test = test & all(round(x)==x);
% Optional tests
for i = 1:length(varargin),
try
if ~eval(['all(x(:)' varargin{i} ');']), test = false; return; end
catch err
error(['Incorrect test ''' varargin{i} ''' (type ''help <a href="matlab:help isimatrix">isimatrix</a>'' for details).']);
end
end
|
github
|
lcnhappe/happe-master
|
islscalar.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neuroscope/private/islscalar.m
| 1,077 |
iso_8859_13
|
af0d9269f1590dee3176575b0083aced
|
%islscalar - Test if parameter is a (pseudo) logical scalar.
%
% USAGE
%
% test = islscalar(x)
%
% x parameter to test
%
% NOTE
%
% To be considered logical, the scalar should be equal to 0 or 1, but it does
% not need to actually be of class 'logical' (class(x) could be e.g. 'double').
%
% SEE ALSO
%
% See also islvector, islmatrix, isdmatrix, isdvector, isdscalar, isimatrix, isivector,
% isstring.
%
% Copyright (C) 2010-2011 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
function test = islscalar(x)
% Check number of parameters
if nargin < 1,
error('Incorrect number of parameters (type ''help <a href="matlab:help islscalar">islscalar</a>'' for details).');
end
% Test: double, scalar
test = islogical(x) & isscalar(x);
function test = islogical(x)
test = builtin('islogical',x) | all(x(:)==0|x(:)==1);
|
github
|
lcnhappe/happe-master
|
isdvector.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neuroscope/private/isdvector.m
| 2,081 |
iso_8859_13
|
5ef70521f0fa1b770ada8d42d0fe9bee
|
%isdvector - Test if parameter is a vector of doubles satisfying an optional list of tests.
%
% USAGE
%
% test = isdvector(x,test1,test2,...)
%
% x parameter to test
% test1... optional list of additional tests (see examples below)
%
% EXAMPLES
%
% % Test if x is a vector of doubles
% isdvector(x)
%
% % Test if x is a vector of strictly positive doubles
% isdvector(x,'>0')
%
% % Test if x is a vector of doubles included in [2,3]
% isdvector(x,'>=2','<=3')
%
% % Special test: test if x is a vector of doubles of length 3
% isdvector(x,'#3')
%
% % Special test: test if x is a vector of strictly ordered doubles
% isdvector(x,'>')
%
% NOTE
%
% The tests ignore NaNs, e.g. isdvector([5e-3 nan]), isdvector([1.7 nan 3],'>0') and
% isdvector([nan -7.4],'<=0') all return 1.
%
% SEE ALSO
%
% See also isdmatrix, isdscalar, isimatrix, isivector, isiscalar, isstring,
% islscalar, islvector, islmatrix.
%
% Copyright (C) 2010 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
function test = isdvector(x,varargin)
% Check number of parameters
if nargin < 1,
error('Incorrect number of parameters (type ''help <a href="matlab:help isdvector">isdvector</a>'' for details).');
end
% Test: double, vector
test = isa(x,'double') & isvector(x);
% Ignore NaNs
x = x(~isnan(x));
% Optional tests
for i = 1:length(varargin),
try
if varargin{i}(1) == '#',
if length(x) ~= str2num(varargin{i}(2:end)), test = false; return; end
elseif isstring(varargin{i},'>','>=','<','<='),
dx = diff(x);
if ~eval(['all(0' varargin{i} 'dx);']), test = false; return; end
else
if ~eval(['all(x' varargin{i} ');']), test = false; return; end
end
catch err
error(['Incorrect test ''' varargin{i} ''' (type ''help <a href="matlab:help isdvector">isdvector</a>'' for details).']);
end
end
|
github
|
lcnhappe/happe-master
|
isstring.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neuroscope/private/isstring.m
| 992 |
iso_8859_13
|
3f0150034c5c2e51b50c80fc3828fd12
|
%isstring - Test if parameter is an (admissible) character string.
%
% USAGE
%
% test = isstring(x,string1,string2,...)
%
% x item to test
% string1... optional list of admissible strings
%
% SEE ALSO
%
% See also isdmatrix, isdvector, isdscalar, isimatrix, isivector, isiscalar.
%
% Copyright (C) 2004-2010 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
function test = isstring(x,varargin)
% Check number of parameters
if nargin < 1,
error('Incorrect number of parameters (type ''help <a href="matlab:help isstring">isstring</a>'' for details).');
end
test = true;
if ~ischar(x),
test = false;
return;
end
if isempty(varargin), return; end
for i = 1:length(varargin),
if strcmp(x,varargin{i}), return; end
end
test = false;
|
github
|
lcnhappe/happe-master
|
islmatrix.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neuroscope/private/islmatrix.m
| 1,149 |
iso_8859_13
|
2e0a52b0be376a939b2c68ef383358b2
|
%islmatrix - Test if parameter is a logical matrix (>= 2 columns).
%
% USAGE
%
% test = islmatrix(x)
%
% x parameter to test
%
% NOTE
%
% To be considered logical, the matrix should contain only values 0 and 1, but it
% does not need to actually be of class 'logical' (class(x) could be e.g. 'double').
%
% SEE ALSO
%
% See also islscalar, islvector, isdmatrix, isdvector, isdscalar, isivector, isiscalar,
% isstring.
%
% Copyright (C) 2010-2011 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
function test = islmatrix(x)
% Check number of parameters
if nargin < 1,
error('Incorrect number of parameters (type ''help <a href="matlab:help islmatrix">islmatrix</a>'' for details).');
end
% Test: logical, two dimensions, two or more columns?
test = islogical(x) & length(size(x)) == 2 & size(x,2) >= 2;
function test = islogical(x)
test = builtin('islogical',x) | all(x(:)==0|x(:)==1);
|
github
|
lcnhappe/happe-master
|
isdscalar.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neuroscope/private/isdscalar.m
| 1,575 |
iso_8859_13
|
01e7b8dfec919c2f708c7a25d96262e3
|
%isdscalar - Test if parameter is a scalar (double) satisfying an optional list of tests.
%
% USAGE
%
% test = isdscalar(x,test1,test2,...)
%
% x parameter to test
% test1... optional list of additional tests
%
% EXAMPLES
%
% % Test if x is a scalar (double)
% isdscalar(x)
%
% % Test if x is a strictly positive scalar (double)
% isdscalar(x,'>0')
%
% % Test if x is a scalar (double) included in [2,3]
% isdscalar(x,'>=2','<=3')
%
% NOTE
%
% The tests ignore NaN, e.g. isdscalar(nan), isdscalar(nan,'>0') and isdscalar(nan,'<=0')
% all return 1.
%
% SEE ALSO
%
% See also isdmatrix, isdvector, isimatrix, isivector, isiscalar, isstring,
% islscalar, islvector, islmatrix.
%
% Copyright (C) 2010 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
function test = isdscalar(x,varargin)
% Check number of parameters
if nargin < 1,
error('Incorrect number of parameters (type ''help <a href="matlab:help isdscalar">isdscalar</a>'' for details).');
end
% Test: double, scalar
test = isa(x,'double') & isscalar(x);
if ~test, return; end
% Optional tests
for i = 1:length(varargin),
try
if ~eval(['x' varargin{i} ';']), test = false; return; end
catch err
error(['Incorrect test ''' varargin{i} ''' (type ''help <a href="matlab:help isdscalar">isdscalar</a>'' for details).']);
end
end
|
github
|
lcnhappe/happe-master
|
isdmatrix.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neuroscope/private/isdmatrix.m
| 1,656 |
iso_8859_13
|
ba7943baf9c16023dd749f34097850df
|
%isdmatrix - Test if parameter is a matrix of doubles (>= 2 columns).
%
% USAGE
%
% test = isdmatrix(x,test1,test2,...)
%
% x parameter to test
% test1... optional list of additional tests
%
% EXAMPLES
%
% % Test if x is a matrix of doubles
% isdmatrix(x)
%
% % Test if x is a matrix of strictly positive doubles
% isdmatrix(x,'>0')
%
% NOTE
%
% The tests ignore NaNs, e.g. isdmatrix([5e-3 nan;4 79]), isdmatrix([1.7 nan 3],'>0') and
% isdmatrix([nan -7.4;nan nan;-2.3 -5],'<=0') all return 1.
%
% SEE ALSO
%
% See also isdvector, isdscalar, isimatrix, isivector, isiscalar, isstring,
% islscalar, islvector, islmatrix.
%
% Copyright (C) 2010 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
function test = isdmatrix(x,varargin)
% Check number of parameters
if nargin < 1,
error('Incorrect number of parameters (type ''help <a href="matlab:help isdmatrix">isdmatrix</a>'' for details).');
end
% Test: doubles, two dimensions, two or more columns?
test = isa(x,'double') & length(size(x)) == 2 & size(x,2) >= 2;
% Ignore NaNs (this reshapes the matrix, but it does not matter for the tests)
x = x(~isnan(x));
% Optional tests
for i = 1:length(varargin),
try
if ~eval(['all(x(:)' varargin{i} ');']), test = false; return; end
catch err
error(['Incorrect test ''' varargin{i} ''' (type ''help <a href="matlab:help isdmatrix">isdmatrix</a>'' for details).']);
end
end
|
github
|
lcnhappe/happe-master
|
readneuronedata.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neurone/readneuronedata.m
| 3,668 |
utf_8
|
8b13da2d37c92187282b24464ba2d0cf
|
% readneuronedata() - Read NeurOne Binary files
%
% Usage: >> data = readneuronedata(dataFiles,nChannels,chans)
%
% ===================================================================
% Inputs:
% dataFiles - A cell structure containing full paths for data
% files to be read. This is input argument is
% required.
% nChannels - Another required input argument:
% the total number of channels.
% chans - A vector containing the channel numbers to be
% read. They have to be arranged in an ascending
% order. This input argument is optional.
% ====================================================================
% Output:
% data - A matrix where all numerical data is stored.
% The data is arranged so that the data for each
% channel is stored in a row according
% to its number.
%
% ========================================================================
% NOTE:
% This file is part of the NeurOne data import plugin for EEGLAB.
% ========================================================================
%
% Current version: 1.0.3.4 (2016-06-17)
% Author: Mega Electronics
function data = readneuronedata(dataFiles,nChannels,chans)
%% Parse input arguments
p = inputParser;
p.addRequired('dataFiles', @iscellstr);
p.addRequired('nChannels', @isnumeric);
p.addOptional('chans', 0, @isnumeric);
p.parse(dataFiles, nChannels, chans);
arglist=p.Results;
%% Prepare reading data
nDataFiles = numel(arglist.dataFiles);
chans = arglist.chans;
nChannels = arglist.nChannels;
if chans==0
chans=1:nChannels;
end
% Get all file sizes
fSize=zeros(1,nDataFiles);
tmp={};
for k=1:nDataFiles
tmp{k,1}=dir(dataFiles{k,1});
fSize(1,k)=tmp{k,1}.bytes;
end
fSizes=cumsum(fSize);
% Total size of the data
totalSize=sum(fSize);
% Total number of data points (per channel)
dataPntsTotal=(totalSize/4)/nChannels;
% Number of data points in each binary file (per channel)
dataPnts=(fSize./4)./nChannels;
%% Read binary data
fprintf('Allocating memory...\n')
data=zeros(numel(chans),dataPntsTotal);
% Option 1: Read all channels at once (faster method)
if numel(chans)==nChannels
fprintf('Reading data...');
data=data(:);
readidx=[0 (fSizes/4)];
for n=1:nDataFiles
fid = fopen([dataFiles{n}], 'rb');
data((1+readidx(n)):readidx(n+1),1)=fread(fid, ...
fSize(n)/4,'int32');
fclose(fid);
end
data=reshape(data,nChannels,dataPntsTotal);
fprintf('%s','Done');
else
% Option 2: Read only specific channels to save memory
fprintf('Reading data... 0%%');
readidx=[0 (fSizes/4)./nChannels];
% Read channels one by one
for k=1:numel(chans)
for n=1:nDataFiles
fid = fopen([dataFiles{n}], 'rb');
fseek(fid, 4*(chans(k) - 1), 'bof');
data(k,(1+readidx(n)):readidx(n+1)) = fread(fid, ...
dataPnts(n),'int32',4*(nChannels-1))';
fclose(fid);
end
% Print progress to the command window
ii = floor(k/numel(chans)*100);
if ii<10
ii = [num2str(ii) '%'];
fprintf(1,'\b\b%s',ii);
elseif ii==100;
ii = 'Done';
fprintf(1,'\b\b\b%s',ii);
else
ii = [num2str(ii) '%'];
fprintf(1,'\b\b\b%s',ii);
end
end
end
fprintf('\n');
%% Convert data from nanovolts to microvolts
data=data./1000;
end
|
github
|
lcnhappe/happe-master
|
pop_readneurone.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neurone/pop_readneurone.m
| 8,116 |
utf_8
|
c755af0f65d561b1d3adaa77368be5ff
|
% pop_readneurone() - A function for reading NeurOne data.
%
% Usage: >> [EEGOUT,command] = pop_readneurone() % Launches GUI for user input
% OR
% >> [EEGOUT,command] = pop_readneurone(dataPath, sessionPhaseNumber, chans)
%
% Please note that if this function is called without using the menu item
% in EEGLAB, it will not be automatically stored in its memory.
% ========================================================================
% Inputs:
% dataPath - A string containing the full path for .ses
% -file to be read. This input argument is
% required.
% sessionPhaseNumber - A number indicating the session
% phase to be observed. This input argument is
% optional. If the session phase number is left
% empty, default value 1 will be used.
% chans - Another optional input argument to indicate
% the channels to be imported. Acceptable
% values are strings where the channels are
% in a vector form without brackets e.g.
% '1,3,5' or '1:4' (when the GUI is executed,
% the quotation marks should not be used).
% Note that only acceptable values
% are those between 1 and the total number of
% channels. It should also be noted that the
% number of the channel may not be the same as
% its input number since when an input
% number is missing, the channel numbering will
% continue with next available input number.
% Here is an example of the channel numbering
% (note the missing input numbers 3 and 4):
%
% Input number Channel number
% ------------ --------------
% 1 -----> 1
% 2 -----> 2
% 5 -----> 3
% 6 -----> 4
%
%
% Outputs:
% EEGOUT - A struct with the same fields as a standard
% EEG data structure under EEGLAB
% (see eeg_checkset.m).
% command - A string containing all the input parameters
% and the command used to execute this
% function.
% ========================================================================
% GUI help:
%
% When this function is used without any input arguments, it will open
% several windows to ask for required information as described above. The
% first pop-up window asks the user to specify the .ses -file to be loaded.
% If 'Cancel' -button is pressed at this point, the importing process will
% terminate. The next window is a GUI asking for information about the
% channels to be loaded and the number of the desired session phase to be
% observed. When 'Ok' -button is pressed, the data is sent to readneurone.m
% for further processing. Again, if 'Cancel' -button is pressed, the whole
% importing process will be terminated.
%
% IMPORTANT NOTE: For a computer with high memory capacity it is much more
% faster to import data by leaving the channel field empty
% and removing unnecessary channels afterwards. However,
% in case of limited memory it is recommended to first
% specify the channels to be imported.
%
% ========================================================================
% NOTE:
% This file is part of the NeurOne data import plugin for EEGLAB.
% ========================================================================
%
% Current version: 1.0.3.4 (2016-06-17)
% Author: Mega Electronics
%
% see also: eegplugin_neurone.m or readneurone.m
function [EEG,command] = pop_readneurone(dataPath,sessionPhaseNumber,chans)
%% Initialize empty structure for the data
EEG = {}; % Create empty space for data
command = '';
%% Check the number of input arguments
nargchk(0,1,nargin);
%% Use the GUI
if nargin==0
if isfield(evalin('base','EEG'),'history')
history = evalin('base','EEG.history');
if ~(isempty(strfind(history,'dataPath')))
dataPathIndex = strfind(history,'dataPath=''');
idx = strfind(history,'''');
idx = idx(idx>dataPathIndex);
dataPath = history(idx(1)+1:idx(2)-1);
dataPath = fileparts(dataPath);
[dataPath folder] = fileparts(dataPath);
else
dataPath = cd;
end
else
dataPath = cd;
end
[fname dataPath] = uigetfile({'*.ses', ...
'NeurOne session file (*.ses)'}, ...
'Load NeurOne session file',dataPath);
% If cancel is pressed, the import process will terminate
if fname==0
return
end
% If ok, manipulate the filename
fullpath = [dataPath fname];
a = dir(dataPath);
for k = 3:numel(a)
if a(k).isdir==1
if ~(isempty(regexpi(fullpath,a(k).name)))
dataPath = [dataPath a(k).name filesep];
end
end
end
fprintf('\n----------IMPORTING DATA----------\n')
fprintf('File to Import: %s\n',fullpath)
guifig=guireadneurone;
try
SETTINGS=guidata(guifig);
catch
return;
end
switch SETTINGS.loadStatus
% When cancel button is pressed, the GUI terminates
case 0
disp('NeurOne import cancelled')
delete(guifig);
return
% When ok button is pressed, proceed to read the data
case 1
delete(guifig);
SETTINGS.dataPath=dataPath;
if isempty(SETTINGS.chans)
fprintf('Channels to be read: all\n');
else
fprintf('Channels to be read: %s\n',SETTINGS.chans);
end
EEG = readneurone(SETTINGS.dataPath, ...
SETTINGS.sessionPhaseNumber,SETTINGS.chans);
EEG = eeg_checkset(EEG); % EEGLAB function to check consistency
EEG = eeg_checkset(EEG,'eventconsistency'); % check event structure
EEG = eeg_checkset(EEG,'makeur');
end
% ====================================================================
% Read data using direct command
else
if nargin>=1
fullpath=dataPath;
fprintf('\n----------IMPORTING DATA----------\n')
fprintf('File to Import: %s\n',fullpath)
% Manipulate the given path
[dataPath fname] = fileparts(fullpath);
a = dir(dataPath);
for k = 3:numel(a)
if a(k).isdir==1
if ~(isempty(regexpi(fullpath,a(k).name)))
dataPath = [dataPath filesep a(k).name filesep];
end
end
end
SETTINGS=struct();
SETTINGS.dataPath=dataPath;
if ~(exist('sessionPhaseNumber'))
SETTINGS.sessionPhaseNumber = 1;
else
SETTINGS.sessionPhaseNumber=sessionPhaseNumber;
end
if ~(exist('chans'))
SETTINGS.chans = '';
else
SETTINGS.chans=chans;
end
end
EEG = readneurone(SETTINGS.dataPath,SETTINGS.sessionPhaseNumber, ...
SETTINGS.chans);
EEG = eeg_checkset(EEG); % check EEG data structure
EEG = eeg_checkset(EEG,'eventconsistency'); % check event structure
EEG = eeg_checkset(EEG,'makeur');
end
comline = sprintf('dataPath=''%s'';',SETTINGS.dataPath);
comline = sprintf('%s sessionPhaseNumber=''%d'';',...
comline,SETTINGS.sessionPhaseNumber);
comline = sprintf('%s chans=''%s'';',...
comline,SETTINGS.chans);
command = sprintf('%s [EEG,COM]=pop_readneurone(dataPath,sessionPhaseNumber,chans);',comline);
return
|
github
|
lcnhappe/happe-master
|
eegplugin_neurone.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neurone/eegplugin_neurone.m
| 1,598 |
utf_8
|
1b5fe8ed27d31f4de4608dd4b652f905
|
% eegplugin_neurone() - EEGLAB plugin to import data from a NeurOne device.
%
% Usage:
% >> eegplugin_neurone(fig,try_strings,catch_strings)
%
% Inputs:
% fig - [integer] handle to EEGLAB figure
% try_strings - [struct] "try" strings for menu callbacks.
% catch_strings - [struct] "catch" strings for menu callbacks.
%
% NeurOne data import plugin consists of the following files:
% pop_readneurone.m
% guireadneurone.m
% guireadneurone.fig
% readneurone.m
% readneuronedata.m
% readneuroneevents.m
% neurone_logo.png
% mega_gradient_edit.png
%
% This plugin was created according to the instructions provided by the
% creators of EEGLAB. These instructions can be found e.g. from the website:
% http://sccn.ucsd.edu/wiki/A07:_Contributing_to_EEGLAB
%
% Current version: 1.0.3.4 (2016-06-17)
% Author: Mega Electronics
function vers = eegplugin_neurone(fig,try_strings,catch_strings)
vers='NeurOne data import 1.0.3.4';
% Check the number of input arguments
if nargin < 3
error('Not enough input arguments.');
end
% Add plugin folder to path
if ~exist('pop_readneurone.m')
path=which('eegplugin_neurone.m');
[path filename]=fileparts(path);
path=[path filesep];
addpath([path version] );
end
% Find the 'Import data' -menu
importmenu=findobj(fig,'tag','import data');
% Construct command
cmd = [try_strings.no_check '[EEG LASTCOM]=pop_readneurone;' catch_strings.new_and_hist];
% Create the menu for NeurOne import
uimenu(importmenu,'label','From a NeurOne file (.ses)',...
'Callback',cmd,'separator','on');
|
github
|
lcnhappe/happe-master
|
readneuroneevents.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neurone/readneuroneevents.m
| 4,947 |
utf_8
|
b51f19a943ed465494de552dfeb3b250
|
% readneuroneevents() - Read events from a Mega NeurOne device.
%
% Usage: >> event = readneuroneevents(dataPath)
%
% =======================================================================
% Input:
% dataPath - Direct path for the folder containing the event
% data (file 'events.bin') related to the current
% session phase number.
%
% Output:
% event - A struct created according to the event structure
% under EEGLAB. The used fields are type and
% latency. The field 'type' will be generated
% depending on the type of the event as follows:
%
% Event type Value of the type field
% ---------- -----------------------
% Unknown (Source port name) - Unknown
% Stimulation (Source port name) - Stimulation
% Video trigger (Source port name) - Video
% Mute trigger (Source port name) - Mute
% 8-bit trigger (8-bit trigger code, a value between
% 1-255)
% Comment (any user-entered comment related to
% the event)
% ClockSourceChange ClockSourceChange (when the source of
% SyncBox clock is changed)
%
% =======================================================================
% Additional information:
% The size of one event structure 'events.bin' file is 88 bytes. If user-
% entered comments are used, they will be read from file 'eventData.bin'
% which holds comment for each event in Unicode (2 bytes/character). See
% 'NeurOne Data Format' documentation for more info about the event
% structure.
%
% ========================================================================
% NOTE:
% This file is part of the NeurOne data import plugin for EEGLAB.
% ========================================================================
%
% Current version: 1.0.3.4 (2016-06-17)
% Author: Mega Electronics
function event = readneuroneevents(dataPath)
% Get the total number of events
eventsTmp = dir([dataPath filesep 'events.bin']);
nEvents = eventsTmp.bytes/88;
event = {}; % empty structure for event data
% Read events.bin (see NeurOne Data Format doc)
events = fopen([dataPath filesep 'events.bin'],'rb');
for k = 1:nEvents
% Read the whole event structure
Revision = fread(events,1,'int32');
RFU = fread(events,1,'int32');
Type = fread(events,1,'int32');
SourcePort = fread(events,1,'int32');
ChannelNumber = fread(events,1,'int32');
Code = fread(events,1,'int32');
StartSampleIndex = fread(events,1,'uint64');
StopSampleIndex = fread(events,1,'uint64');
DescriptionLength = fread(events,1,'uint64');
DescriptionOffset = fread(events,1,'uint64');
DataLength = fread(events,1,'uint64');
DataOffset = fread(events,1,'uint64');
TimeStamp = fread(events,1,'double');
MainUnitIndex = fread(events,1,'int32');
RFU = fread(events,1,'int32');
% Check if the data format has changed
if Revision > 6
warning(strcat('This reader does not support the revision of events.bin (', ...
num2str(Revision), '). Please contact [email protected] for an update.'))
end
% Determine the source port
switch SourcePort
case 0
SourcePort = 'N/A';
case 1
SourcePort = 'A';
case 2
SourcePort = 'B';
case 3
SourcePort = 'EightBit';
case 4
SourcePort = 'Syncbox Button';
case 5
SourcePort = 'SyncBox EXT';
case 6
SourcePort = 'Software';
otherwise
SourcePort = 'Unknown';
end
% Determine the type of the event
switch Type
case 0
Type = [SourcePort ' - N/A'];
case 1
Type = [SourcePort ' - Stimulation'];
case 2
Type = [SourcePort ' - Video'];
case 3
Type = [SourcePort ' - Mute'];
case 4
Type = num2str(Code);
case 5
Type = [SourcePort ' - Out' ];
case 6
% User-entered comments will be read from file eventData.bin
fid = fopen([dataPath filesep 'eventData.bin'],'rb');
offset = DataOffset/2;
length = DataLength/2;
comments = fread(fid,[1 offset],'int16');
comments = fread(fid,[1 length],'int16');
Type = char(comments);
fclose(fid);
case 1001
Type = [SourcePort ' - ClockSourceChange'];
otherwise
Type = 'Unknown';
end
% Store the obtained data
event(1,k).latency = StartSampleIndex;
event(1,k).type = Type;
end
fclose(events);
end
|
github
|
lcnhappe/happe-master
|
readneurone.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neurone/readneurone.m
| 11,773 |
utf_8
|
cf4bc45088b4719e91b7b6b87c7300f1
|
% readneurone() - Read data from a Mega NeurOne device and arrange it
% into a struct.
%
% Usage: >> NEURONE = readneurone(dataPath, sessionPhaseNumber, chans)
%
% =======================================================================
% Inputs:
% dataPath - Path to directory containing NeurOne data
% from a single measurement.
%
% Optional input arguments:
% sessionPhaseNumber - Defines which session phase will be read.
% Default value for sessionPhaseNumber is 1.
% chans - Defines which channels will be read. The
% channel numbers have to be strings containing
% numeric values between 1 and the total number
% of channels. In addition, they are arranged in
% vector form without brackets. For example,
% if the total number of channels is 64, the
% 'chans' input argument can be '1,6,3,7' or
% '1:12'. The default value for chans is an empty
% string which indicates that all channels will
% be read. The channel numbers can be arranged
% in a completely random order.
%
% =======================================================================
% Outputs:
% NEURONE is a struct with the same fields as a standard EEG
% structure under EEGLAB (see eeg_checkset.m).
%
% Used fields are:
% NEURONE.filename
% NEURONE.setname
% NEURONE.srate
% NEURONE.pnts
% NEURONE.xmin
% NEURONE.xmax
% NEURONE.filepath
% NEURONE.trials
% NEURONE.nbchan
% NEURONE.data
% NEURONE.ref
% NEURONE.times
% NEURONE.comments
% NEURONE.etc
% NEURONE.subject
% NEURONE.event (a struct containing all event data)
% NEURONE.eventdescription
% NEURONE.chanlocs (will be defined by EEGLAB if channel locations exist
% for used channel names)
% NEURONE.chaninfo
%
% The following fields were added as empty to ensure proper working:
% NEURONE.icawinv
% NEURONE.icaweights
% NEURONE.icasphere
% NEURONE.icaact
%
%
% ========================================================================
% NOTE:
% This file is part of the NeurOne data import plugin for EEGLAB.
% ========================================================================
%
% Current version: 1.0.3.4 (2016-06-17)
% Author: Mega Electronics
function NEURONE = readneurone(dataPath, varargin)
%% Parse input arguments
p = inputParser;
p.addRequired('dataPath', @ischar);
p.addOptional('sessionPhaseNumber', 1 ,@isnumeric);
p.addOptional('chans','', @isstr);
p.parse(dataPath, varargin{:});
arglist = p.Results;
%% Empty recording structure for output
NEURONE = {};
%% Read Session and Protocol xml-files
session = module_read_neurone_xml([dataPath 'Session.xml']);
protocol = module_read_neurone_xml([dataPath 'Protocol.xml']);
%% Obtain information from session and protocol
% Obtain sampling frequency (it is same for all channels)
srate = str2num(protocol.TableProtocol.SamplingFrequency);
% Get the total number of channels
nChannels = numel(protocol.TableInput);
NEURONE.comments = ['Protocol: ' session.TableSession.ProtocolName];
NEURONE.etc = strvcat( ['NeurOne Version: ' protocol.TableInfo.NeurOneVersion], ...
['Protocol File Revision: ' protocol.TableInfo.Revision], ...
['Session File Revision: ' session.TableInfo.Revision]);
NEURONE.subject = session.TablePerson.PersonID;
NEURONE.setname = session.TableSession.ProtocolName;
%% Check the session phase number
% Total number of sessions in recording
nSessionPhases = numel(session.TableSessionPhase);
disp(['Number of session phases: ' num2str(nSessionPhases)])
disp(['Current session phase number: ' num2str(arglist.sessionPhaseNumber)]);
% Check the validity of the sessionPhaseNumber taken from GUI
if arglist.sessionPhaseNumber>nSessionPhases
disp('Current session phase number exceeds the total number of session phases.')
disp('Defaulting to 1.')
sessionPhaseNumber = 1;
elseif arglist.sessionPhaseNumber<=0
disp('Invalid session phase number.')
disp('Defaulting to 1.')
sessionPhaseNumber = 1;
else
sessionPhaseNumber = arglist.sessionPhaseNumber;
end
%% Get correct channel names and locations
% Set the channels for data acquisition
if isempty(arglist.chans)
chans = 1:nChannels;
else
chans = [str2num(arglist.chans)];
chans = sort(chans); % ensure that the channels are in ascending order
end
% Check that no channel number exceeds the total number of channels
if any(chans>nChannels)
error('One or more of the given channel numbers exceeds the total number of channels. See pop_readneurone help.')
elseif any(chans<1)
error('One or more of the given channel numbers are invalid (zero or negative). See pop_readneurone help.')
end
% Get all channel names and corresponding input numbers
inputNumbersAll = zeros(1,nChannels);
inputNumbersAll(1) = str2num(protocol.TableInput(1).InputNumber);
channelnames = protocol.TableInput(1).Name;
for n = 2:nChannels
inputNumbersAll(n) = str2num(protocol.TableInput(n).InputNumber);
channelnames = char(channelnames,protocol.TableInput(n).Name);
end
channelnames = cellstr(channelnames);
% The value of the highest input number
maxInput = max(inputNumbersAll);
channelnames = channelnames';
% Sort channel names in ascending order based on their input number
for k = 1:nChannels
ii = 1;
while ~(any(inputNumbersAll(k)==ii)) && ii<=max(inputNumbersAll)
ii = ii+1;
end
sortIndex(ii) = ii; % Store the indices for future data arrangements
channelNames(ii) = channelnames(k);
end
inputNumbersTrue = 1:maxInput;
inputNumbersTrue = inputNumbersTrue(find(sortIndex));
% Remove empty channel names:
% Find empty cells...
emptyCells = cellfun(@isempty,channelNames);
% ...and remove them.
channelNames(emptyCells) = [];
% Take only the names of the selected channels
channelNames = channelNames(chans);
fprintf('Looking up channel locations...\n')
chanlocs=struct('labels', channelNames');
% NEURONE.chanlocs = pop_chanedit(chanlocs);
NEURONE.chanlocs = chanlocs;
%% Obtain additional information about the dataset
measurementMode = protocol.TableInput(1).AlternatingCurrent;
deviceFilter = protocol.TableInput(1).Filter;
for n = 2:nChannels
measurementMode = char(measurementMode,protocol.TableInput(n).AlternatingCurrent);
deviceFilter = char(deviceFilter,protocol.TableInput(n).Filter);
end
measurementMode = cellstr(measurementMode);
deviceFilter = cellstr(deviceFilter);
for k = 1:nChannels
if strcmp(measurementMode(k),'true')
measurementMode(k) = {'AC'};
else
measurementMode(k) = {'DC'};
end
end
% Arrange measurementModes according to the input number
ii = 1;
for k = inputNumbersAll
measurementMode(k) = measurementMode(ii);
deviceFilter(k) = deviceFilter(ii);
ii = ii+1;
end
measurementMode = measurementMode(inputNumbersTrue);
measurementMode = measurementMode(chans);
deviceFilter = deviceFilter(inputNumbersTrue);
deviceFilter = deviceFilter(chans);
measurementModeField = [char(channelNames(1)) ': ' char(measurementMode(1))];
deviceFilterField = [char(channelNames(1)) ': ' char(deviceFilter(1))];
for k = 2:length(chans)
measurementModeField = strvcat(measurementModeField,[char(channelNames(k)) ': ' char(measurementMode(k))]);
deviceFilterField = strvcat(deviceFilterField,[char(channelNames(k)) ': ' char(deviceFilter(k))]);
end
NEURONE.chaninfo.measurementMode = measurementModeField;
NEURONE.chaninfo.deviceFilter = deviceFilterField;
%% Preparing to read binary data
% If the size of the measurement in each session phase has exceeded the
% file size, the data may have been split into several files named as
% 1.bin, 2.bin etc. Usually there exists only one file: 1.bin. However, all
% this data needs to be read.
dataFiles = {}; % empty structure for data files
% Get all .bin files related to the chosen sessionPhaseNumber
sessionData = dir([dataPath num2str(sessionPhaseNumber) filesep '*.bin']);
ii = 1;
for k = 1:numel(sessionData); % total number of .bin files in current session phase data folder
[path,filename,ext] = fileparts(sessionData(k).name);
if ~isempty(regexpi(filename,'[123456789]'))
dataFiles{ii,1} = [dataPath num2str(sessionPhaseNumber) filesep sessionData(k).name];
ii = ii+1;
end
end
%% Read NeurOne binary data and calibrate it
% Read data. The data of a specific channel is arranged in a row based on its input
% number.
data = readneuronedata(dataFiles, nChannels, chans);
% Preallocate memory to read maximum and minimum values for calibration
rawMinimum = zeros(1,maxInput);
rawMaximum = zeros(1,maxInput);
calibratedMinimum = zeros(1,maxInput);
calibratedMaximum = zeros(1,maxInput);
% Get all minimum and maximum values
for n = 1:nChannels
rawMinimum(n) = str2num(protocol.TableInput(1,n).RangeMinimum);
rawMaximum(n) = str2num(protocol.TableInput(1,n).RangeMaximum);
calibratedMinimum(n) = str2num(protocol.TableInput(1,n).RangeAsCalibratedMinimum);
calibratedMaximum(n) = str2num(protocol.TableInput(1,n).RangeAsCalibratedMaximum);
end
% Arrange them in the correct according to the input number
ii = 1;
for k = inputNumbersAll
rawMinimum(inputNumbersAll) = rawMinimum(ii);
rawMaximum(inputNumbersAll) = rawMaximum(ii);
calibratedMinimum(inputNumbersAll) = calibratedMinimum(ii);
calibratedMaximum(inputNumbersAll) = calibratedMaximum(ii);
ii = ii+1;
end
% Remove unused input numbers
rawMinimum = rawMinimum(inputNumbersTrue);
rawMaximum = rawMaximum(inputNumbersTrue);
calibratedMinimum = calibratedMinimum(inputNumbersTrue);
calibratedMaximum = calibratedMaximum(inputNumbersTrue);
% Calibrate channels
for n = 1:numel(chans)
data(n,:) = calibratedMinimum(n) + ...
(data(n,:)-rawMinimum(n)) / (rawMaximum(n)-rawMinimum(n)) * (calibratedMaximum(n)-calibratedMinimum(n));
end
%% Read events
fprintf('Loading events...\n');
event = readneuroneevents([dataPath num2str(sessionPhaseNumber) filesep]);
NEURONE.event = event;
% Writing event description
latency = strvcat('Latency:','The index number indicating the point in the data when the particular event has occurred');
type = strvcat('Type:','A descriptive name for the event. Will be generated depending on the type of the event as follows:',' ', ...
'Event type', ...
'----------', ...
'1) Unknown', ...
'2) Stimulation', ...
'3) Video trigger', ...
'4) Mute trigger', ...
'5) 8-bit trigger', ...
'6) Comment', ' ', ...
'Corresponding value of the type field', ...
'-----------------------', ...
'1) (Source port name) - Unknown', ...
'2) (Source port name) - Stimulation', ...
'3) (Source port name) - Video', ...
'4) (Source port name) - Mute', ...
'5) (8-bit trigger code, a value between 1-255)',...
'6) (any user-entered comment related to the event)');
NEURONE.eventdescription = {latency type};
%% Store rest of the data
fprintf('Preparing output...\n');
% Basic dataset information:
NEURONE.srate = srate;
NEURONE.pnts = numel(data)/numel(chans);
NEURONE.xmin = 0;
NEURONE.xmax =(NEURONE.pnts-1)/srate;
NEURONE.trials = 1;
NEURONE.nbchan = length(chans);
NEURONE.data = data;
NEURONE.ref = 'common';
NEURONE.filepath = ''; % Will be generated by EEGLAB when saved
NEURONE.filename = ''; % Will be generated by EEGLAB when saved
% Additional dataset information:
NEURONE.icawinv = [];
NEURONE.icaweights = [];
NEURONE.icasphere = [];
NEURONE.icaact = [];
end
|
github
|
lcnhappe/happe-master
|
guireadneurone.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/neurone/guireadneurone.m
| 4,818 |
utf_8
|
88c8053fef247ef0eff9f0bcd3992657
|
function varargout = guireadneurone(varargin)
% GUIREADNEURONE Application M-file for guireadneurone.fig
% FIG = GUIREADNEURONE launch guireadneurone GUI.
% GUIREADNEURONE('callback_name', ...) invoke the named callback.
%
% ========================================================================
% NOTE:
% This file is part of the NeurOne data import plugin for EEGLAB.
% ========================================================================
%
% Current version: 1.0.3.4 (2016-06-17)
% Author: Mega Electronics
% If no input arguments are used, the GUI is launched
if nargin == 0
neuroneimportfig = openfig(mfilename,'new');
% Initialize a structure of handles to pass to callbacks.
handles = guihandles(neuroneimportfig);
% Load logos
bgcolor=[0.656 0.758 1.0];
megaLogo=imread('mega_gradient_edit.png','BackgroundColor',bgcolor);
axes(handles.mega_logo);
image(megaLogo)
axis off
axis image
neuroneLogo=imread('neurone_logo.png','BackgroundColor',bgcolor);
axes(handles.neurone_logo);
image(neuroneLogo)
axis off
axis image
% Declare variables
handles.chans='';
handles.sessionPhaseNumber=1;
handles.loadStatus=0;
% Store the structure
guidata(neuroneimportfig, handles)
% Wait for callbacks. 'Ok' or 'Cancel' to continue.
uiwait(neuroneimportfig);
if nargout > 0
varargout{1} = neuroneimportfig;
end
elseif ischar(varargin{1})
try
if (nargout)
[varargout{1:nargout}] = feval(varargin{:});
else
feval(varargin{:});
end
catch
disp(lasterr);
end
end
% --- Executes on button press in cancel_button.
function varargout = cancel_button_Callback(hObject, eventdata, handles)
% hObject handle to cancel_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.loadStatus=0;
guidata(hObject,handles);
uiresume(handles.guireadneurone_fig)
function varargout = channel_area_Callback(hObject, eventdata, handles)
% hObject handle to channel_area (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of channel_area as text
% str2double(get(hObject,'String')) returns contents of channel_area as a double
handles.chans=get(hObject,'string');
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function varargout = channel_area_CreateFcn(hObject, eventdata, handles)
% hObject handle to channel_area (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 varargout = session_area_Callback(hObject, eventdata, handles)
% hObject handle to channel_area (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(h,'String') returns contents of channel_area as text
% str2double(get(hObject,'String')) returns contents of channel_area as a double
handles.sessionPhaseNumber=str2num(get(hObject,'String'));
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function varargout = session_area_CreateFcn(hObject, eventdata, handles)
% hObject handle to channel_area (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 help_button.
function varargout = help_button_Callback(hObject, eventdata, handles)
% hObject handle to help_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
pophelp('pop_readneurone.m');
% --- Executes on button press in ok_button.
function varargout = ok_button_Callback(hObject, eventdata, handles)
% hObject handle to ok_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.loadStatus=1;
guidata(hObject,handles);
uiresume(handles.guireadneurone_fig);
|
github
|
lcnhappe/happe-master
|
floatread.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/eeglab/floatread.m
| 5,572 |
utf_8
|
942a49968bcce849dfc9d359ac7d2651
|
% floatread() - Read matrix from float file ssuming four byte floating point number
% Can use fseek() to read an arbitary (continguous) submatrix.
%
% Usage: >> a = floatread(filename,size,'format',offset)
%
% Inputs:
% filename - name of the file
% size - determine the number of float 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. If size is 'square,' floatread() attempts
% to read a square 2-D matrix.
%
% Optional inputs:
% 'format' - the option FORMAT argument specifies the storage format as
% defined by fopen(). Default format ([]) is 'native'.
% offset - either the number of first floats to skip from the beginning of the
% float file, OR a cell array containing the dimensions of the original
% data matrix and a starting position vector in that data matrix.
%
% Example: % Read a [3 10] submatrix of a four-dimensional float matrix
% >> a = floatread('mydata.fdt',[3 10],'native',{[[3 10 4 5],[1,1,3,4]});
% % Note: The 'size' and 'offset' arguments must be compatible both
% % with each other and with the size and ordering of the float file.
%
% Author: Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998
%
% See also: 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
% 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
% 08-14-00 added size 'square' option -sm
% 01-25-02 reformated help & license, added links -ad
function A = floatread(fname,Asize,fform,offset)
if nargin<2
help floatread
return
end
if ~exist('fform') | isempty(fform)|fform==0
fform = 'native';
end
if ~exist('offset')
offset = 0;
end
fid = fopen(fname,'rb',fform);
if fid>0
if exist('offset')
if iscell(offset)
if length(offset) ~= 2
error('offset must be a positive integer or a 2-item cell array');
end
datasize = offset{1};
startpos = offset{2};
if length(datasize) ~= length(startpos)
error('offset must be a positive integer or a 2-item cell array');
end
for k=1:length(datasize)
if startpos(k) < 1 | startpos(k) > datasize(k)
error('offset must be a positive integer or a 2-item cell array');
end
end
if length(Asize)> length(datasize)
error('offset must be a positive integer or a 2-item cell array');
end
for k=1:length(Asize)-1
if startpos(k) ~= 1
error('offset must be a positive integer or a 2-item cell array');
end
end
sizedim = length(Asize);
if Asize(sizedim) + startpos(sizedim) - 1 > datasize(sizedim)
error('offset must be a positive integer or a 2-item cell array');
end
for k=1:length(Asize)-1
if Asize(k) ~= datasize(k)
error('offset must be a positive integer or a 2-item cell array');
end
end
offset = 0;
jumpfac = 1;
for k=1:length(startpos)
offset = offset + jumpfac * (startpos(k)-1);
jumpfac = jumpfac * datasize(k);
end
elseif length(offset) > 1
error('offset must be a positive integer or a 2-item cell array');
end
% perform the fseek() operation
% -----------------------------
stts = fseek(fid,4*offset,'bof');
if stts ~= 0
error('floatread(): fseek() error.');
return
end
end
% determine what 'square' means
% -----------------------------
if ischar('Asize')
if iscell(offset)
if length(datasize) ~= 2 | datasize(1) ~= datasize(2)
error('size ''square'' must refer to a square 2-D matrix');
end
Asize = [datsize(1) datasize(2)];
elseif strcmp(Asize,'square')
fseek(fid,0,'eof'); % go to end of file
bytes = ftell(fid); % get byte position
fseek(fid,0,'bof'); % rewind
bytes = bytes/4; % nfloats
froot = sqrt(bytes);
if round(froot)*round(froot) ~= bytes
error('floatread(): filelength is not square.')
else
Asize = [round(froot) round(froot)];
end
end
end
A = fread(fid,prod(Asize),'float');
else
error('floatread() fopen() error.');
return
end
% fprintf(' %d floats read\n',prod(size(A)));
% interpret last element of Asize if 'Inf'
% ----------------------------------------
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
|
floatwrite.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/eeglab/floatwrite.m
| 3,169 |
utf_8
|
8472e61c3208f7a445ec052e9cc52b4b
|
% floatwrite() - Write data matrix to float file.
%
% Usage: >> floatwrite(data,filename, 'format')
%
% Inputs:
% data - write matrix data to specified file as four-byte floating point numbers.
% filename - name of the file
% 'format' - The option FORMAT argument specifies the storage format as
% defined by fopen. Default format is 'native'.
% 'transp|normal' - save the data transposed (.dat files) or not.
%
% Author: Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998
%
% See also: floatread(), 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
% 07-08-99 FORMAT argument added -se
% 02-08-00 new version included in toolbox -sm
% 01-25-02 reformated help & license, added links -ad
function A = floatwrite(A, fname, fform, transp)
if ~exist('fform')
fform = 'native';
end
if nargin < 4
transp = 'normal';
end;
if strcmpi(transp,'normal')
if strcmpi(class(A), 'mmo')
A = changefile(A, fname);
return;
elseif strcmpi(class(A), 'memmapdata')
% check file to overwrite
% -----------------------
[fpath1 fname1 ext1] = fileparts(fname);
[fpath2 fname2 ext2] = fileparts(A.data.Filename);
if isempty(fpath1), fpath1 = pwd; end;
fname1 = fullfile(fpath1, [fname1 ext1]);
fname2 = fullfile(fpath2, [fname2 ext2]);
if ~isempty(findstr(fname1, fname2))
disp('Warning: raw data already saved in memory mapped file (no need to resave it)');
return;
end;
fid = fopen(fname,'wb',fform);
if fid == -1, error('Cannot write output file, check permission and space'); end;
if size(A,3) > 1
for ind = 1:size(A,3)
tmpdata = A(:,:,ind);
fwrite(fid,tmpdata,'float');
end;
else
blocks = [ 1:round(size(A,2)/10):size(A,2)];
if blocks(end) ~= size(A,2), blocks = [blocks size(A,2)]; end;
for ind = 1:length(blocks)-1
tmpdata = A(:, blocks(ind):blocks(ind+1));
fwrite(fid,tmpdata,'float');
end;
end;
else
fid = fopen(fname,'wb',fform);
if fid == -1, error('Cannot write output file, check permission and space'); end;
fwrite(fid,A,'float');
end;
else
% save transposed
for ind = 1:size(A,1)
fwrite(fid,A(ind,:),'float');
end;
end;
fclose(fid);
|
github
|
lcnhappe/happe-master
|
eeglab2fieldtrip.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/eeglab/eeglab2fieldtrip.m
| 5,477 |
utf_8
|
bdb52aada07dc61861584ca6a70c7482
|
% eeglab2fieldtrip() - do this ...
%
% Usage: >> data = eeglab2fieldtrip( EEG, fieldbox, transform );
%
% Inputs:
% EEG - [struct] EEGLAB structure
% fieldbox - ['preprocessing'|'freqanalysis'|'timelockanalysis'|'companalysis']
% transform - ['none'|'dipfit'] transform channel locations for DIPFIT
% using the transformation matrix in the field
% 'coord_transform' of the dipfit substructure of the EEG
% structure.
% Outputs:
% data - FIELDTRIP structure
%
% Author: Robert Oostenveld, F.C. Donders Centre, May, 2004.
% Arnaud Delorme, SCCN, INC, UCSD
%
% See also:
% Copyright (C) 2004 Robert Oostenveld, F.C. Donders Centre, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function data = eeglab2fieldtrip(EEG, fieldbox, transform)
if nargin < 2
help eeglab2fieldtrip
return;
end;
% start with an empty data object
data = [];
% add the objects that are common to all fieldboxes
tmpchanlocs = EEG.chanlocs;
data.label = { tmpchanlocs(EEG.icachansind).labels };
data.fsample = EEG.srate;
% get the electrode positions from the EEG structure: in principle, the number of
% channels can be more or less than the number of channel locations, i.e. not
% every channel has a position, or the potential was not measured on every
% position. This is not supported by EEGLAB, but it is supported by FIELDTRIP.
if strcmpi(fieldbox, 'chanloc_withfid')
% insert "no data channels" in channel structure
% ----------------------------------------------
if isfield(EEG.chaninfo, 'nodatchans') && ~isempty( EEG.chaninfo.nodatchans )
chanlen = length(EEG.chanlocs);
fields = fieldnames( EEG.chaninfo.nodatchans );
for index = 1:length(EEG.chaninfo.nodatchans)
ind = chanlen+index;
for f = 1:length( fields )
EEG.chanlocs = setfield(EEG.chanlocs, { ind }, fields{f}, ...
getfield( EEG.chaninfo.nodatchans, { index }, fields{f}));
end;
end;
end;
end;
data.elec.pnt = zeros(length( EEG.chanlocs ), 3);
for ind = 1:length( EEG.chanlocs )
data.elec.label{ind} = EEG.chanlocs(ind).labels;
if ~isempty(EEG.chanlocs(ind).X)
data.elec.pnt(ind,1) = EEG.chanlocs(ind).X;
data.elec.pnt(ind,2) = EEG.chanlocs(ind).Y;
data.elec.pnt(ind,3) = EEG.chanlocs(ind).Z;
else
data.elec.pnt(ind,:) = [0 0 0];
end;
end;
if nargin > 2
if strcmpi(transform, 'dipfit')
if ~isempty(EEG.dipfit.coord_transform)
disp('Transforming electrode coordinates to match head model');
transfmat = traditionaldipfit(EEG.dipfit.coord_transform);
data.elec.pnt = transfmat * [ data.elec.pnt ones(size(data.elec.pnt,1),1) ]';
data.elec.pnt = data.elec.pnt(1:3,:)';
else
disp('Warning: no transformation of electrode coordinates to match head model');
end;
end;
end;
switch fieldbox
case 'preprocessing'
for index = 1:EEG.trials
data.trial{index} = EEG.data(:,:,index);
data.time{index} = linspace(EEG.xmin, EEG.xmax, EEG.pnts); % should be checked in FIELDTRIP
end;
data.label = { tmpchanlocs(1:EEG.nbchan).labels };
case 'timelockanalysis'
data.avg = mean(EEG.data, 3);
data.var = std(EEG.data, [], 3).^2;
data.time = linspace(EEG.xmin, EEG.xmax, EEG.pnts); % should be checked in FIELDTRIP
data.label = { tmpchanlocs(1:EEG.nbchan).labels };
case 'componentanalysis'
for index = 1:EEG.trials
% the trials correspond to the raw data trials, except that they
% contain the component activations
try,
data.trial{index} = EEG.icaact(:,:,index);
catch
end;
data.time{index} = linspace(EEG.xmin, EEG.xmax, EEG.pnts); % should be checked in FIELDTRIP
end;
for comp = 1:size(EEG.icawinv,2)
% the labels correspond to the component activations that are stored in data.trial
data.label{comp} = sprintf('ica_%03d', comp);
end
% get the spatial distribution and electrode positions
tmpchanlocs = EEG.chanlocs;
data.topolabel = { tmpchanlocs(EEG.icachansind).labels };
data.topo = EEG.icawinv;
case { 'chanloc' 'chanloc_withfid' }
case 'freqanalysis'
error('freqanalysis fieldbox not implemented yet')
otherwise
error('unsupported fieldbox')
end
try
% get the full name of the function
data.cfg.version.name = mfilename('fullpath');
catch
% required for compatibility with Matlab versions prior to release 13 (6.5)
[st, i] = dbstack;
data.cfg.version.name = st(i);
end
% add the version details of this function call to the configuration
data.cfg.version.id = '$Id$';
return
|
github
|
lcnhappe/happe-master
|
sobi.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/eeglab/sobi.m
| 5,094 |
utf_8
|
ce6035ad7a3d7312fee7cf1a37d8e04e
|
% sobi() - Second Order Blind Identification (SOBI) by joint diagonalization of
% correlation matrices. THIS CODE ASSUMES TEMPORALLY CORRELATED SIGNALS,
% and uses correlations across times in performing the signal separation.
% Thus, estimated time delayed covariance matrices must be nonsingular
% for at least some time delays.
% Usage:
% >> winv = sobi(data);
% >> [winv,act] = sobi(data,n,p);
% Inputs:
% data - data matrix of size [m,N] ELSE of size [m,N,t] where
% m is the number of sensors,
% N is the number of samples,
% t is the number of trials (avoid epoch boundaries)
% n - number of sources {Default: n=m}
% p - number of correlation matrices to be diagonalized
% {Default: min(100, N/3)} Note that for non-ideal data,
% the authors strongly recommend using at least 100 time delays.
%
% Outputs:
% winv - Matrix of size [m,n], an estimate of the *mixing* matrix. Its
% columns are the component scalp maps. NOTE: This is the inverse
% of the usual ICA unmixing weight matrix. Sphering (pre-whitening),
% used in the algorithm, is incorporated into winv. i.e.,
%
% >> icaweights = pinv(winv); icasphere = eye(m);
%
% act - matrix of dimension [n,N] an estimate of the source activities
%
% >> data = winv * act;
% [size m,N] [size m,n] [size n,N]
% >> act = pinv(winv) * data;
%
% Authors: A. Belouchrani and A. Cichocki (references: See function body)
% Note: Adapted by Arnaud Delorme and Scott Makeig to process data epochs by
% computing covariances while respecting epoch boundaries.
% REFERENCES:
% A. Belouchrani, K. Abed-Meraim, J.-F. Cardoso, and E. Moulines, ``Second-order
% blind separation of temporally correlated sources,'' in Proc. Int. Conf. on
% Digital Sig. Proc., (Cyprus), pp. 346--351, 1993.
%
% A. Belouchrani and K. Abed-Meraim, ``Separation aveugle au second ordre de
% sources correlees,'' in Proc. Gretsi, (Juan-les-pins),
% pp. 309--312, 1993.
%
% A. Belouchrani, and A. Cichocki,
% Robust whitening procedure in blind source separation context,
% Electronics Letters, Vol. 36, No. 24, 2000, pp. 2050-2053.
%
% A. Cichocki and S. Amari,
% Adaptive Blind Signal and Image Processing, Wiley, 2003.
function [H,S,D]=sobi(X,n,p),
% Authors note: For non-ideal data, use at least p=100 the time-delayed covariance matrices.
DEFAULT_LAGS = 100;
[m,N,ntrials]=size(X);
if nargin<1 | nargin > 3
help sobi
elseif nargin==1,
n=m; % Source detection (hum...)
p=min(DEFAULT_LAGS,ceil(N/3)); % Number of time delayed correlation matrices to be diagonalized
elseif nargin==2,
p=min(DEFAULT_LAGS,ceil(N/3)); % Default number of correlation matrices to be diagonalized
% Use < DEFAULT_LAGS delays if necessary for short data epochs
end;
%
% Make the data zero mean
%
X(:,:)=X(:,:)-kron(mean(X(:,:)')',ones(1,N*ntrials));
%
% Pre-whiten the data based directly on SVD
%
[UU,S,VV]=svd(X(:,:)',0);
Q= pinv(S)*VV';
X(:,:)=Q*X(:,:);
% Alternate whitening code
% Rx=(X*X')/T;
% if m<n, % assumes white noise
% [U,D]=eig(Rx);
% [puiss,k]=sort(diag(D));
% ibl= sqrt(puiss(n-m+1:n)-mean(puiss(1:n-m)));
% bl = ones(m,1) ./ ibl ;
% BL=diag(bl)*U(1:n,k(n-m+1:n))';
% IBL=U(1:n,k(n-m+1:n))*diag(ibl);
% else % assumes no noise
% IBL=sqrtm(Rx);
% Q=inv(IBL);
% end;
% X=Q*X;
%
% Estimate the correlation matrices
%
k=1;
pm=p*m; % for convenience
for u=1:m:pm,
k=k+1;
for t = 1:ntrials
if t == 1
Rxp=X(:,k:N,t)*X(:,1:N-k+1,t)'/(N-k+1)/ntrials;
else
Rxp=Rxp+X(:,k:N,t)*X(:,1:N-k+1,t)'/(N-k+1)/ntrials;
end;
end;
M(:,u:u+m-1)=norm(Rxp,'fro')*Rxp; % Frobenius norm =
end; % sqrt(sum(diag(Rxp'*Rxp)))
%
% Perform joint diagonalization
%
epsil=1/sqrt(N)/100;
encore=1;
V=eye(m);
step_n=0;
while encore,
encore=0;
for p=1:m-1,
for q=p+1:m,
% Perform Givens rotation
g=[ M(p,p:m:pm)-M(q,q:m:pm) ;
M(p,q:m:pm)+M(q,p:m:pm) ;
i*(M(q,p:m:pm)-M(p,q:m:pm)) ];
[vcp,D] = eig(real(g*g'));
[la,K]=sort(diag(D));
angles=vcp(:,K(3));
angles=sign(angles(1))*angles;
c=sqrt(0.5+angles(1)/2);
sr=0.5*(angles(2)-j*angles(3))/c;
sc=conj(sr);
oui = abs(sr)>epsil ;
encore=encore | oui ;
if oui , % Update the M and V matrices
colp=M(:,p:m:pm);
colq=M(:,q:m:pm);
M(:,p:m:pm)=c*colp+sr*colq;
M(:,q:m:pm)=c*colq-sc*colp;
rowp=M(p,:);
rowq=M(q,:);
M(p,:)=c*rowp+sc*rowq;
M(q,:)=c*rowq-sr*rowp;
temp=V(:,p);
V(:,p)=c*V(:,p)+sr*V(:,q);
V(:,q)=c*V(:,q)-sc*temp;
end%% if
end%% q loop
end%% p loop
step_n=step_n+1;
fprintf('%d step\n',step_n);
end%% while
%
% Estimate the mixing matrix
%
H = pinv(Q)*V;
%
% Estimate the source activities
%
if nargout>1
S=V'*X(:,:); % estimated source activities
end
|
github
|
lcnhappe/happe-master
|
varimax.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/eeglab/varimax.m
| 4,437 |
utf_8
|
d87cb189d37524e4920c2f9ad9c41aa4
|
% varimax() - Perform orthogonal Varimax rotation on rows of a data
% matrix.
%
% Usage: >> V = varimax(data);
% >> [V,rotdata] = varimax(data,tol);
% >> [V,rotdata] = varimax(data,tol,'noreorder')
%
% Inputs:
% data - data matrix
% tol - set the termination tolerance to tol {default: 1e-4}
% 'noreorder' - Perform the rotation without component reorientation
% or reordering by size. This suppression is desirable
% when doing a q-mode analysis. {default|0|[] -> reorder}
% Outputs:
% V - orthogonal rotation matrix, hence
% rotdata - rotated matrix, rotdata = V*data;
%
% Author: Sigurd Enghoff - CNL / Salk Institute, La Jolla 6/18/98
%
% See also: runica(), pcasvd(), promax()
% Copyright (C) Sigurd Enghoff - CNL / Salk Institute, La Jolla 6/18/98
%
% 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
% Reference: % Henry F. Kaiser (1958) The Varimx criterion for
% analytic rotation in factor analysis. Pychometrika 23:187-200.
%
% modified to return V alone by Scott Makeig, 6/23/98
% 01-25-02 reformated help & license, added link -ad
function [V,data] = varimax(data,tol,reorder)
if nargin < 1
help varimax
return
end
DEFAULT_TOL = 1e-4; % default tolerance, for use in stopping the iteration
DEFAULT_REORDER = 1; % default to reordering the output rows by size
% and adjusting their sign to be rms positive.
MAX_ITERATIONS = 50; % Default
qrtr = .25; % fixed value
if nargin < 3
reorder = DEFAULT_REORDER;
elseif isempty(reorder) | reorder == 0
reorder = 1; % set default
else
reorder = strcmp('reorder',reorder);
end
if nargin < 2
tol = 0;
end
if tol == 0
tol = DEFAULT_TOL;
end
if ischar(tol)
fprintf('varimax(): tol must be a number > 0\n');
help varimax
return
end
eps1 = tol; % varimax toler
eps2 = tol;
V = eye(size(data,1)); % do unto 'V' what is done to data
crit = [sum(sum(data'.^4)-sum(data'.^2).^2/size(data,2)) 0];
inoim = 0;
iflip = 1;
ict = 0;
fprintf(...
'Finding the orthogonal Varimax rotation using delta tolerance %d...\n',...
eps1);
while inoim < 2 & ict < MAX_ITERATIONS & iflip,
iflip = 0;
for j = 1:size(data,1)-1,
for k = j+1:size(data,1),
u = data(j,:).^2-data(k,:).^2;
v = 2*data(j,:).*data(k,:);
a = sum(u);
b = sum(v);
c = sum(u.^2-v.^2);
d = sum(u.*v);
fden = size(data,2)*c + b^2 - a^2;
fnum = 2 * (size(data,2)*d - a*b);
if abs(fnum) > eps1*abs(fden)
iflip = 1;
angl = qrtr*atan2(fnum,fden);
tmp = cos(angl)*V(j,:)+sin(angl)*V(k,:);
V(k,:) = -sin(angl)*V(j,:)+cos(angl)*V(k,:);
V(j,:) = tmp;
tmp = cos(angl)*data(j,:)+sin(angl)*data(k,:);
data(k,:) = -sin(angl)*data(j,:)+cos(angl)*data(k,:);
data(j,:) = tmp;
end
end
end
crit = [sum(sum(data'.^4)-sum(data'.^2).^2/size(data,2)) crit(1)];
inoim = inoim + 1;
ict = ict + 1;
fprintf('#%d - delta = %g\n',ict,(crit(1)-crit(2))/crit(1));
if (crit(1) - crit(2)) / crit(1) > eps2
inoim = 0;
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if reorder
fprintf('Reordering rows...');
[fnorm index] = sort(sum(data'.^2));
V = V .* ((2 * (sum(data') > 0) - 1)' * ones(1, size(V,2)));
data = data .* ((2 * (sum(data') > 0) - 1)' * ones(1, size(data,2)));
V = V(fliplr(index),:);
data = data(fliplr(index),:);
fprintf('\n');
else
fprintf('Not reordering rows.\n');
end
|
github
|
lcnhappe/happe-master
|
pcsquash.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/eeglab/pcsquash.m
| 2,802 |
utf_8
|
9e0a0372b72b09c731ef70785b8ce862
|
% pcsquash() - compress data using Principal Component Analysis (PCA)
% into a principal component subspace. To project back
% into the original channel space, use pcexpand()
%
% Usage:
% >> [eigenvectors,eigenvalues] = pcsquash(data,ncomps);
% >> [eigenvectors,eigenvalues,compressed,datamean] ...
% = pcsquash(data,ncomps);
%
% Inputs:
% data = (chans,frames) each row is a channel, each column a time point
% ncomps = numbers of components to retain
%
% Outputs:
% eigenvectors = square matrix of (column) eigenvectors
% eigenvalues = vector of associated eigenvalues
% compressed = data compressed into space of the ncomps eigenvectors
% with largest eigenvalues (ncomps,frames)
% Note that >> compressed = eigenvectors(:,1:ncomps)'*data;
% datamean = input data channel (row) means (used internally)
%
% Author: Tzyy-Ping Jung & Scott Makeig, SCCN/INC/UCSD, La Jolla, 6-97
%
% See also: pcexpand(), svd()
% Copyright (C) 2000 Tzyy-Ping Jung & 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
% 01-25-02 reformated help & license, added links -ad
function [EigenVectors,EigenValues,Compressed,Datamean]=pcsquash(matrix,ncomps)
if nargin < 1
help pcsquash
return
end
if nargin < 2
ncomps = 0;
end
if ncomps == 0
ncomps = size(matrix,1);
end
if ncomps < 1
help pcsquash
return
end
data = matrix'; % transpose data
[n,p]=size(data); % now p chans,n time points
if ncomps > p
fprintf('pcsquash(): components must be <= number of data rows (%d).\n',p);
return;
end
Datamean = mean(data,1); % remove column (channel) means
data = data-ones(n,1)*Datamean; % remove column (channel) means
out=data'*data/n;
[V,D] = eig(out); % get eigenvectors/eigenvalues
diag(D);
[eigenval,index] = sort(diag(D));
index=rot90(rot90(index));
EigenValues=rot90(rot90(eigenval))';
EigenVectors=V(:,index);
if nargout >= 3
Compressed = EigenVectors(:,1:ncomps)'*data';
end
|
github
|
lcnhappe/happe-master
|
binica.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/eeglab/binica.m
| 13,069 |
utf_8
|
e1bfb70b5edae53d01116b6f9cf42d51
|
% binica() - Run stand-alone binary version of runica() from the
% Matlab command line. Saves time and memory relative
% to runica(). If stored in a float file, data are not
% read into Matlab, and so may be larger than Matlab
% can handle owing to memory limitations.
% Usage:
% >> [wts,sph] = binica( datavar, 'key1', arg1, 'key2', arg2 ...);
% else
% >> [wts,sph] = binica('datafile', chans, frames, 'key1', arg1, ...);
%
% Inputs:
% datavar - (chans,frames) data matrix in the Matlab workspace
% datafile - quoted 'filename' of float data file multiplexed by channel
% channels - number of channels in datafile (not needed for datavar)
% frames - number of frames (time points) in datafile (only)
%
% Optional flag,argument pairs:
% 'extended' - int>=0 [0 default: assume no subgaussian comps]
% Search for subgaussian comps: 'extended',1 is recommended
% 'pca' - int>=0 [0 default: don't reduce data dimension]
% NB: 'pca' reduction not recommended unless necessary
% 'sphering' - 'on'/'off' first 'sphere' the data {default: 'on'}
% 'lrate' - (0<float<<1) starting learning rate {default: 1e-4}
% 'blocksize' - int>=0 [0 default: heuristic, from data size]
% 'maxsteps' - int>0 {default: 512}
% 'stop' - (0<float<<<1) stopping learning rate {default: 1e-7}
% NB: 'stop' <= 1e-7 recommended
% 'weightsin' - Filename string of inital weight matrix of size
% (comps,chans) floats, else a weight matrix variable
% in the current Matlab workspace (copied to a local
% .inwts files). You may want to reduce the starting
% 'lrate' arg (above) when resuming training, and/or
% to reduce the 'stop' arg (above). By default, binary
% ica begins with the identity matrix after sphering.
% 'verbose' - 'on'/'off' {default: 'off'}
% 'filenum' - the number to be used in the name of the output files.
% Otherwise chosen randomly. Will choose random number
% if file with that number already exists.
%
% Less frequently used input flags:
% 'posact' - ('on'/'off') Make maximum value for each comp positive.
% NB: 'off' recommended. {default: 'off'}
% 'annealstep' - (0<float<1) {default: 0.98}
% 'annealdeg' - (0<n<360) {default: 60}
% 'bias' - 'on'/'off' {default: 'on'}
% 'momentum' - (0<float<1) {default: 0 = off]
%
% Outputs:
% wts - output weights matrix, size (ncomps,nchans)
% sph - output sphere matrix, size (nchans,nchans)
% Both files are read from float files left on disk
% stem - random integer used in the names of the .sc, .wts,
% .sph, and if requested, .intwts files
%
% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 2000
%
% See also: runica()
% Calls binary translation of runica() by Sigurd Enghoff
% Copyright (C) 2000 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
% 08/07/00 Added warning to update icadefs.m -sm
% 09/08/00 Added tmpint to script, weights and sphere files to avoid
% conflicts when multiple binica sessions run in the same pwd -sm
% 10/07/00 Fixed bug in reading wts when 'pca' ncomps < nchans -sm
% 07/18/01 replaced var ICA with ICABINARY to try to avoid Matlab6 bug -sm
% 11/06/01 add absolute path of files (lines 157-170 & 198) -ad
% 01-25-02 reformated help & license, added links -ad
function [wts,sph,tmpint] = binica(data,var2,var3,var4,var5,var6,var7,var8,var9,var10,var11,var12,var13,var14,var15,var16,var17,var18,var19,var20,var21,var22,var23,var24,var25)
if nargin < 1 | nargin > 25
more on
help binica
more off
return
end
if size(data,3) > 1, data = reshape(data, size(data,1), size(data,2)*size(data,3) ); end;
icadefs % import ICABINARY and SC
if ~exist('SC')
fprintf('binica(): You need to update your icadefs file to include ICABINARY and SC.\n')
return
end;
if exist(SC) ~= 2
fprintf('binica(): No ica source file ''%s'' is in your Matlab path, check...\n', SC);
return
else
SC = which(SC);
fprintf('binica: using source file ''%s''\n', SC);
end
if exist(ICABINARY) ~= 2
fprintf('binica(): ica binary ''%s'' is not in your Matlab path, check\n', ICABINARY);
return
else
ICABINARYdir = which(ICABINARY);
if ~isempty(ICABINARYdir)
fprintf('binica(): using binary ica file ''%s''\n', ICABINARYdir);
else
fprintf('binica(): using binary ica file ''\?/%s''\n', ICABINARY);
end;
end
[flags,args] = read_sc(SC); % read flags and args in master SC file
%
% substitute the flags/args pairs in the .sc file
%
tmpint=[];
if ~ischar(data) % data variable given
firstarg = 2;
else % data filename given
firstarg = 4;
end
arg = firstarg;
if arg > nargin
fprintf('binica(): no optional (flag, argument) pairs received.\n');
else
if (nargin-arg+1)/2 > 1
fprintf('binica(): processing %d (flag, arg) pairs.\n',(nargin-arg+1)/2);
else
fprintf('binica(): processing one (flag, arg) pair.\n');
end
while arg <= nargin %%%%%%%%%%%% process flags & args %%%%%%%%%%%%%%%%
eval(['OPTIONFLAG = var' int2str(arg) ';']);
% NB: Found that here Matlab var 'FLAG' is (64,3) why!?!?
if arg == nargin
fprintf('\nbinica(): Flag %s needs an argument.\n',OPTIONFLAG)
return
end
eval(['Arg = var' int2str(arg+1) ';']);
if strcmpi(OPTIONFLAG,'pca')
ncomps = Arg; % get number of components out for reading wts.
end
if strcmpi(OPTIONFLAG,'weightsin')
wtsin = Arg;
if exist('wtsin') == 2 % file
fprintf(' setting %s, %s\n','weightsin',Arg);
elseif exist('wtsin') == 1 % variable
nchans = size(data,1); % by nima
if size(wtsin,2) ~= nchans
fprintf('weightsin variable must be of width %d\n',nchans);
return
end
else
fprintf('weightsin variable not found.\n');
return
end
end
if strcmpi(OPTIONFLAG,'filenum')
tmpint = Arg; % get number for name of output files
if ~isnumeric(tmpint)
fprintf('\nbinica(): FileNum argument needs to be a number. Will use random number instead.\n')
tmpint=[];
end;
tmpint=int2str(tmpint);
end
arg = arg+2;
nflags = length(flags);
for f=1:nflags % replace SC arg with Arg passed from commandline
if strcmp(OPTIONFLAG,flags{f})
args{f} = num2str(Arg);
fprintf(' setting %s, %s\n',flags{f},args{f});
end
end
end
end
%
% select random integer 1-10000 to index the binica data files
% make sure no such script file already exists in the pwd
%
scriptfile = ['binica' tmpint '.sc'];
while exist(scriptfile)
tmpint = int2str(round(rand*10000));
scriptfile = ['binica' tmpint '.sc'];
end
fprintf('scriptfile = %s\n',scriptfile);
nchans = 0;
tmpdata = [];
if ~ischar(data) % data variable given
if ~exist('data')
fprintf('\nbinica(): Variable name data not found.\n');
return
end
nchans = size(data,1);
nframes = size(data,2);
tmpdata = ['binica' tmpint '.fdt'];
if strcmpi(computer, 'MAC')
floatwrite(data,tmpdata,'ieee-be');
else
floatwrite(data,tmpdata);
end;
datafile = tmpdata;
else % data filename given
if ~exist(data)
fprintf('\nbinica(): File data not found.\n')
return
end
datafile = data;
if nargin<3
fprintf(...
'\nbinica(): Data file name must be followed by chans, frames\n');
return
end
nchans = var2;
nframes = var3;
if ischar(nchans) | ischar(nframes)
fprintf(...
'\nbinica(): chans, frames args must be given after data file name\n');
return
end
end
%
% insert name of data files, chans and frames
%
for x=1:length(flags)
if strcmp(flags{x},'DataFile')
datafile = [pwd '/' datafile];
args{x} = datafile;
elseif strcmp(flags{x},'WeightsOutFile')
weightsfile = ['binica' tmpint '.wts'];
weightsfile = [pwd '/' weightsfile];
args{x} = weightsfile;
elseif strcmp(flags{x},'WeightsTempFile')
weightsfile = ['binicatmp' tmpint '.wts'];
weightsfile = [pwd '/' weightsfile];
args{x} = weightsfile;
elseif strcmp(flags{x},'SphereFile')
spherefile = ['binica' tmpint '.sph'];
spherefile = [pwd '/' spherefile];
args{x} = spherefile;
elseif strcmp(flags{x},'chans')
args{x} = int2str(nchans);
elseif strcmp(flags{x},'frames')
args{x} = int2str(nframes);
end
end
%
% write the new .sc file
%
fid = fopen(scriptfile,'w');
for x=1:length(flags)
fprintf(fid,'%s %s\n',flags{x},args{x});
end
if exist('wtsin') % specify WeightsInfile from 'weightsin' flag, arg
if exist('wtsin') == 1 % variable
winfn = [pwd '/binica' tmpint '.inwts'];
if strcmpi(computer, 'MAC')
floatwrite(wtsin,winfn,'ieee-be');
else
floatwrite(wtsin,winfn);
end;
fprintf(' saving input weights:\n ');
weightsinfile = winfn; % weights in file name
elseif exist(wtsin) == 2 % file
weightsinfile = wtsin;
weightsinfile = [pwd '/' weightsinfile];
else
fprintf('binica(): weightsin file|variable not found.\n');
return
end
eval(['!ls -l ' weightsinfile]);
fprintf(fid,'%s %s\n','WeightsInFile',weightsinfile);
end
fclose(fid);
if ~exist(scriptfile)
fprintf('\nbinica(): ica script file %s not written.\n',...
scriptfile);
return
end
%
% %%%%%%%%%%%%%%%%%%%%%% run binary ica %%%%%%%%%%%%%%%%%%%%%%%%%
%
fprintf('\nRunning ica from script file %s\n',scriptfile);
if exist('ncomps')
fprintf(' Finding %d components.\n',ncomps);
end
eval_call = ['!' ICABINARY '<' pwd '/' scriptfile];
eval(eval_call);
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
% read in wts and sph results.
%
if ~exist('ncomps')
ncomps = nchans;
end
if strcmpi(computer, 'MAC')
wts = floatread(weightsfile,[ncomps Inf],'ieee-be',0);
sph = floatread(spherefile,[nchans Inf],'ieee-be',0);
else
wts = floatread(weightsfile,[ncomps Inf],[],0);
sph = floatread(spherefile,[nchans Inf],[],0);
end;
if isempty(wts)
fprintf('\nbinica(): weight matrix not read.\n')
return
end
if isempty(sph)
fprintf('\nbinica(): sphere matrix not read.\n')
return
end
fprintf('\nbinary ica files left in pwd:\n');
eval(['!ls -l ' scriptfile ' ' weightsfile ' ' spherefile]);
if exist('wtsin')
eval(['!ls -l ' weightsinfile]);
end
fprintf('\n');
if ischar(data)
whos wts sph
else
whos data wts sph
end
%
% If created by binica(), rm temporary data file
% NOTE: doesn't remove the .sc .wts and .fdt files
if ~isempty(tmpdata)
eval(['!rm -f ' datafile]);
end
%
%%%%%%%%%%%%%%%%%%% included functions %%%%%%%%%%%%%%%%%%%%%%
%
function sout = rmcomment(s,symb)
n =1;
while s(n)~=symb % discard # comments
n = n+1;
end
if n == 1
sout = [];
else
sout = s(1:n-1);
end
function sout = rmspace(s)
n=1; % discard leading whitespace
while n<length(s) & isspace(s(n))
n = n+1;
end
if n<length(s)
sout = s(n:end);
else
sout = [];
end
function [word,sout] = firstword(s)
n=1;
while n<=length(s) & ~isspace(s(n))
n = n+1;
end
if n>length(s)
word = [];
sout = s;
else
word = s(1:n-1);
sout = s(n:end);
end
function [flags,args] = read_sc(master_sc)
%
% read in the master ica script file SC
%
flags = [];
args = [];
fid = fopen(master_sc,'r');
if fid < 0
fprintf('\nbinica(): Master .sc file %s not read!\n',master_sc)
return
end
%
% read SC file info into flags and args lists
%
s = [];
f = 0; % flag number in file
while isempty(s) | s ~= -1
s = fgetl(fid);
if s ~= -1
if ~isempty(s)
s = rmcomment(s,'#');
if ~isempty(s)
f = f+1;
s = rmspace(s);
[w s]=firstword(s);
if ~isempty(s)
flags{f} = w;
s = rmspace(s);
[w s]=firstword(s);
args{f} = w;
end
end
end
end
end
fclose(fid);
|
github
|
lcnhappe/happe-master
|
loadcnt.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/eeglab/loadcnt.m
| 24,511 |
utf_8
|
4c5259259e1f529ae64cfe52eec5bd9a
|
% loadcnt() - Load a Neuroscan continuous signal file.
%
% Usage:
% >> cnt = loadcnt(file, varargin)
%
% Inputs:
% filename - name of the file with extension
%
% Optional inputs:
% 't1' - start at time t1, default 0. Warning, events latency
% might be innacurate (this is an open issue).
% 'sample1' - start at sample1, default 0, overrides t1. Warning,
% events latency might be innacurate.
% 'lddur' - duration of segment to load, default = whole file
% 'ldnsamples' - number of samples to load, default = whole file,
% overrides lddur
% 'scale' - ['on'|'off'] scale data to microvolt (default:'on')
% 'dataformat' - ['int16'|'int32'] default is 'int16' for 16-bit data.
% Use 'int32' for 32-bit data.
% 'blockread' - [integer] by default it is automatically determined
% from the file header, though sometimes it finds an
% incorect value, so you may want to enter a value manually
% here (1 is the most standard value).
% 'memmapfile' - ['memmapfile_name'] use this option if the .cnt file
% is too large to read in conventially. The suffix of
% the memmapfile_name must be .fdt. The memmapfile
% functions process files based on their suffix, and an
% error will occur if you use a different suffix.
%
% Outputs:
% cnt - structure with the continuous data and other informations
% cnt.header
% cnt.electloc
% cnt.data
% cnt.tag
%
% Authors: Sean Fitzgibbon, Arnaud Delorme, 2000-
%
% Note: function original name was load_scan41.m
%
% Known limitations:
% For more see http://www.cnl.salk.edu/~arno/cntload/index.html
% Copyright (C) 2000 Sean Fitzgibbon, <[email protected]>
% Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [f,lab,ev2p] = loadcnt(filename,varargin)
if ~isempty(varargin)
r=struct(varargin{:});
else r = [];
end;
try, r.t1; catch, r.t1=0; end
try, r.sample1; catch, r.sample1=[]; end
try, r.lddur; catch, r.lddur=[]; end
try, r.ldnsamples; catch, r.ldnsamples=[]; end
try, r.scale; catch, r.scale='on'; end
try, r.blockread; catch, r.blockread = []; end
try, r.dataformat; catch, r.dataformat = 'auto'; end
try, r.memmapfile; catch, r.memmapfile = ''; end
sizeEvent1 = 8 ; %%% 8 bytes for Event1
sizeEvent2 = 19 ; %%% 19 bytes for Event2
sizeEvent3 = 19 ; %%% 19 bytes for Event3
type='cnt';
if nargin ==1
scan=0;
end
fid = fopen(filename,'r', 'l');
disp(['Loading file ' filename ' ...'])
h.rev = fread(fid,12,'char');
h.nextfile = fread(fid,1,'long');
h.prevfile = fread(fid,1,'ulong');
h.type = fread(fid,1,'char');
h.id = fread(fid,20,'char');
h.oper = fread(fid,20,'char');
h.doctor = fread(fid,20,'char');
h.referral = fread(fid,20,'char');
h.hospital = fread(fid,20,'char');
h.patient = fread(fid,20,'char');
h.age = fread(fid,1,'short');
h.sex = fread(fid,1,'char');
h.hand = fread(fid,1,'char');
h.med = fread(fid,20, 'char');
h.category = fread(fid,20, 'char');
h.state = fread(fid,20, 'char');
h.label = fread(fid,20, 'char');
h.date = fread(fid,10, 'char');
h.time = fread(fid,12, 'char');
h.mean_age = fread(fid,1,'float');
h.stdev = fread(fid,1,'float');
h.n = fread(fid,1,'short');
h.compfile = fread(fid,38,'char');
h.spectwincomp = fread(fid,1,'float');
h.meanaccuracy = fread(fid,1,'float');
h.meanlatency = fread(fid,1,'float');
h.sortfile = fread(fid,46,'char');
h.numevents = fread(fid,1,'int');
h.compoper = fread(fid,1,'char');
h.avgmode = fread(fid,1,'char');
h.review = fread(fid,1,'char');
h.nsweeps = fread(fid,1,'ushort');
h.compsweeps = fread(fid,1,'ushort');
h.acceptcnt = fread(fid,1,'ushort');
h.rejectcnt = fread(fid,1,'ushort');
h.pnts = fread(fid,1,'ushort');
h.nchannels = fread(fid,1,'ushort');
h.avgupdate = fread(fid,1,'ushort');
h.domain = fread(fid,1,'char');
h.variance = fread(fid,1,'char');
h.rate = fread(fid,1,'ushort'); % A USER CLAIMS THAT SAMPLING RATE CAN BE
h.scale = fread(fid,1,'double'); % FRACTIONAL IN NEUROSCAN WHICH IS
h.veogcorrect = fread(fid,1,'char'); % OBVIOUSLY NOT POSSIBLE HERE (BUG 606)
h.heogcorrect = fread(fid,1,'char');
h.aux1correct = fread(fid,1,'char');
h.aux2correct = fread(fid,1,'char');
h.veogtrig = fread(fid,1,'float');
h.heogtrig = fread(fid,1,'float');
h.aux1trig = fread(fid,1,'float');
h.aux2trig = fread(fid,1,'float');
h.heogchnl = fread(fid,1,'short');
h.veogchnl = fread(fid,1,'short');
h.aux1chnl = fread(fid,1,'short');
h.aux2chnl = fread(fid,1,'short');
h.veogdir = fread(fid,1,'char');
h.heogdir = fread(fid,1,'char');
h.aux1dir = fread(fid,1,'char');
h.aux2dir = fread(fid,1,'char');
h.veog_n = fread(fid,1,'short');
h.heog_n = fread(fid,1,'short');
h.aux1_n = fread(fid,1,'short');
h.aux2_n = fread(fid,1,'short');
h.veogmaxcnt = fread(fid,1,'short');
h.heogmaxcnt = fread(fid,1,'short');
h.aux1maxcnt = fread(fid,1,'short');
h.aux2maxcnt = fread(fid,1,'short');
h.veogmethod = fread(fid,1,'char');
h.heogmethod = fread(fid,1,'char');
h.aux1method = fread(fid,1,'char');
h.aux2method = fread(fid,1,'char');
h.ampsensitivity = fread(fid,1,'float');
h.lowpass = fread(fid,1,'char');
h.highpass = fread(fid,1,'char');
h.notch = fread(fid,1,'char');
h.autoclipadd = fread(fid,1,'char');
h.baseline = fread(fid,1,'char');
h.offstart = fread(fid,1,'float');
h.offstop = fread(fid,1,'float');
h.reject = fread(fid,1,'char');
h.rejstart = fread(fid,1,'float');
h.rejstop = fread(fid,1,'float');
h.rejmin = fread(fid,1,'float');
h.rejmax = fread(fid,1,'float');
h.trigtype = fread(fid,1,'char');
h.trigval = fread(fid,1,'float');
h.trigchnl = fread(fid,1,'char');
h.trigmask = fread(fid,1,'short');
h.trigisi = fread(fid,1,'float');
h.trigmin = fread(fid,1,'float');
h.trigmax = fread(fid,1,'float');
h.trigdir = fread(fid,1,'char');
h.autoscale = fread(fid,1,'char');
h.n2 = fread(fid,1,'short');
h.dir = fread(fid,1,'char');
h.dispmin = fread(fid,1,'float');
h.dispmax = fread(fid,1,'float');
h.xmin = fread(fid,1,'float');
h.xmax = fread(fid,1,'float');
h.automin = fread(fid,1,'float');
h.automax = fread(fid,1,'float');
h.zmin = fread(fid,1,'float');
h.zmax = fread(fid,1,'float');
h.lowcut = fread(fid,1,'float');
h.highcut = fread(fid,1,'float');
h.common = fread(fid,1,'char');
h.savemode = fread(fid,1,'char');
h.manmode = fread(fid,1,'char');
h.ref = fread(fid,10,'char');
h.rectify = fread(fid,1,'char');
h.displayxmin = fread(fid,1,'float');
h.displayxmax = fread(fid,1,'float');
h.phase = fread(fid,1,'char');
h.screen = fread(fid,16,'char');
h.calmode = fread(fid,1,'short');
h.calmethod = fread(fid,1,'short');
h.calupdate = fread(fid,1,'short');
h.calbaseline = fread(fid,1,'short');
h.calsweeps = fread(fid,1,'short');
h.calattenuator = fread(fid,1,'float');
h.calpulsevolt = fread(fid,1,'float');
h.calpulsestart = fread(fid,1,'float');
h.calpulsestop = fread(fid,1,'float');
h.calfreq = fread(fid,1,'float');
h.taskfile = fread(fid,34,'char');
h.seqfile = fread(fid,34,'char');
h.spectmethod = fread(fid,1,'char');
h.spectscaling = fread(fid,1,'char');
h.spectwindow = fread(fid,1,'char');
h.spectwinlength = fread(fid,1,'float');
h.spectorder = fread(fid,1,'char');
h.notchfilter = fread(fid,1,'char');
h.headgain = fread(fid,1,'short');
h.additionalfiles = fread(fid,1,'int');
h.unused = fread(fid,5,'char');
h.fspstopmethod = fread(fid,1,'short');
h.fspstopmode = fread(fid,1,'short');
h.fspfvalue = fread(fid,1,'float');
h.fsppoint = fread(fid,1,'short');
h.fspblocksize = fread(fid,1,'short');
h.fspp1 = fread(fid,1,'ushort');
h.fspp2 = fread(fid,1,'ushort');
h.fspalpha = fread(fid,1,'float');
h.fspnoise = fread(fid,1,'float');
h.fspv1 = fread(fid,1,'short');
h.montage = fread(fid,40,'char');
h.eventfile = fread(fid,40,'char');
h.fratio = fread(fid,1,'float');
h.minor_rev = fread(fid,1,'char');
h.eegupdate = fread(fid,1,'short');
h.compressed = fread(fid,1,'char');
h.xscale = fread(fid,1,'float');
h.yscale = fread(fid,1,'float');
h.xsize = fread(fid,1,'float');
h.ysize = fread(fid,1,'float');
h.acmode = fread(fid,1,'char');
h.commonchnl = fread(fid,1,'uchar');
h.xtics = fread(fid,1,'char');
h.xrange = fread(fid,1,'char');
h.ytics = fread(fid,1,'char');
h.yrange = fread(fid,1,'char');
h.xscalevalue = fread(fid,1,'float');
h.xscaleinterval = fread(fid,1,'float');
h.yscalevalue = fread(fid,1,'float');
h.yscaleinterval = fread(fid,1,'float');
h.scaletoolx1 = fread(fid,1,'float');
h.scaletooly1 = fread(fid,1,'float');
h.scaletoolx2 = fread(fid,1,'float');
h.scaletooly2 = fread(fid,1,'float');
h.port = fread(fid,1,'short');
h.numsamples = fread(fid,1,'ulong');
h.filterflag = fread(fid,1,'char');
h.lowcutoff = fread(fid,1,'float');
h.lowpoles = fread(fid,1,'short');
h.highcutoff = fread(fid,1,'float');
h.highpoles = fread(fid,1,'short');
h.filtertype = fread(fid,1,'char');
h.filterdomain = fread(fid,1,'char');
h.snrflag = fread(fid,1,'char');
h.coherenceflag = fread(fid,1,'char');
h.continuoustype = fread(fid,1,'char');
h.eventtablepos = fread(fid,1,'ulong');
h.continuousseconds = fread(fid,1,'float');
h.channeloffset = fread(fid,1,'long');
h.autocorrectflag = fread(fid,1,'char');
h.dcthreshold = fread(fid,1,'uchar');
for n = 1:h.nchannels
e(n).lab = deblank(char(fread(fid,10,'char')'));
e(n).reference = fread(fid,1,'char');
e(n).skip = fread(fid,1,'char');
e(n).reject = fread(fid,1,'char');
e(n).display = fread(fid,1,'char');
e(n).bad = fread(fid,1,'char');
e(n).n = fread(fid,1,'ushort');
e(n).avg_reference = fread(fid,1,'char');
e(n).clipadd = fread(fid,1,'char');
e(n).x_coord = fread(fid,1,'float');
e(n).y_coord = fread(fid,1,'float');
e(n).veog_wt = fread(fid,1,'float');
e(n).veog_std = fread(fid,1,'float');
e(n).snr = fread(fid,1,'float');
e(n).heog_wt = fread(fid,1,'float');
e(n).heog_std = fread(fid,1,'float');
e(n).baseline = fread(fid,1,'short');
e(n).filtered = fread(fid,1,'char');
e(n).fsp = fread(fid,1,'char');
e(n).aux1_wt = fread(fid,1,'float');
e(n).aux1_std = fread(fid,1,'float');
e(n).senstivity = fread(fid,1,'float');
e(n).gain = fread(fid,1,'char');
e(n).hipass = fread(fid,1,'char');
e(n).lopass = fread(fid,1,'char');
e(n).page = fread(fid,1,'uchar');
e(n).size = fread(fid,1,'uchar');
e(n).impedance = fread(fid,1,'uchar');
e(n).physicalchnl = fread(fid,1,'uchar');
e(n).rectify = fread(fid,1,'char');
e(n).calib = fread(fid,1,'float');
end
% finding if 32-bits of 16-bits file
% ----------------------------------
begdata = ftell(fid);
if strcmpi(r.dataformat, 'auto')
r.dataformat = 'int16';
if (h.nextfile > 0)
fseek(fid,h.nextfile+52,'bof');
is32bit = fread(fid,1,'char');
if (is32bit == 1)
r.dataformat = 'int32';
end;
fseek(fid,begdata,'bof');
end;
end;
enddata = h.eventtablepos; % after data
if strcmpi(r.dataformat, 'int16')
nums = floor((enddata-begdata)/h.nchannels/2); % floor due to bug 1254
else nums = floor((enddata-begdata)/h.nchannels/4);
end;
% number of sample to read
% ------------------------
if ~isempty(r.sample1)
r.t1 = r.sample1/h.rate;
else
r.sample1 = r.t1*h.rate;
end;
if strcmpi(r.dataformat, 'int16')
startpos = r.t1*h.rate*2*h.nchannels;
else startpos = r.t1*h.rate*4*h.nchannels;
end;
if isempty(r.ldnsamples)
if ~isempty(r.lddur)
r.ldnsamples = round(r.lddur*h.rate);
else r.ldnsamples = nums;
end;
end;
% channel offset
% --------------
if ~isempty(r.blockread)
h.channeloffset = r.blockread;
end;
if h.channeloffset > 1
fprintf('WARNING: reading data in blocks of %d, if this fails, try using option "''blockread'', 1"\n', ...
h.channeloffset);
end;
disp('Reading data .....')
if type == 'cnt'
% while (ftell(fid) +1 < h.eventtablepos)
%d(:,i)=fread(fid,h.nchannels,'int16');
%end
% the following chunk has been added by Jan-Mathijs to deal
% with numeric accuracy issues (FieldTrip bug 2746)
if startpos~=round(startpos)
if abs(startpos-round(startpos))<1e-3
disp('Numeric accuracy issue with the first sample: Rounding off to the nearest integer value');
startpos = round(startpos);
else
error('The discrepancy between the requested sample and the nearest integer is too large');
end
end
fseek(fid, startpos, 0);
% **** This marks the beginning of the code modified for reading
% large .cnt files
% Switched to r.memmapfile for continuity. Check to see if the
% variable exists. If it does, then the user has indicated the
% file is too large to be processed in memory. If the variable
% is blank, the file is processed in memory.
if (~isempty(r.memmapfile))
% open a file for writing
foutid = fopen(r.memmapfile, 'w') ;
% This portion of the routine reads in a section of the EEG file
% and then writes it out to the harddisk.
samples_left = h.nchannels * r.ldnsamples ;
% the size of the data block to be read is limited to 4M
% samples. This equates to 16MB and 32MB of memory for
% 16 and 32 bit files, respectively.
data_block = 4000000 ;
max_rows = data_block / h.nchannels ;
%warning off ;
max_written = h.nchannels * uint32(max_rows) ;
%warning on ;
% This while look tracks the remaining samples. The
% data is processed in chunks rather than put into
% memory whole.
while (samples_left > 0)
% Check to see if the remaining data is smaller than
% the general processing block by looking at the
% remaining number of rows.
to_read = max_rows ;
if (data_block > samples_left)
to_read = samples_left / h.nchannels ;
end ;
% Read data in a relatively small chunk
temp_dat = fread(fid, [h.nchannels to_read], r.dataformat) ;
% The data is then scaled using the original routine.
% In the original routine, the entire data set was scaled
% after being read in. For this version, scaling occurs
% after every chunk is read.
if strcmpi(r.scale, 'on')
disp('Scaling data .....')
%%% scaling to microvolts
for i=1:h.nchannels
bas=e(i).baseline;sen=e(i).senstivity;cal=e(i).calib;
mf=sen*(cal/204.8);
temp_dat(i,:)=(temp_dat(i,:)-bas).*mf;
end
end
% Write out data in float32 form to the file name
% supplied by the user.
written = fwrite (foutid, temp_dat, 'float32') ;
if (written ~= max_written)
samples_left = 0 ;
else
samples_left = samples_left - written ;
end ;
end ;
fclose (foutid) ;
% Set the dat variable. This gets used later by other
% EEGLAB functions.
dat = r.memmapfile ;
% This variable tracks how the data should be read.
bReadIntoMemory = false ;
else
% The memmapfile variable is empty, read into memory.
bReadIntoMemory = true ;
end
% This ends the modifications made to read large files.
% Everything contained within the following if statement is the
% original code.
if (bReadIntoMemory == true)
if h.channeloffset <= 1
dat=fread(fid, [h.nchannels Inf], r.dataformat);
if size(dat,2) < r.ldnsamples
dat=single(dat);
r.ldnsamples = size(dat,2);
else
dat=single(dat(:,1:r.ldnsamples));
end;
else
h.channeloffset = h.channeloffset/2;
% reading data in blocks
dat = zeros( h.nchannels, r.ldnsamples, 'single');
dat(:, 1:h.channeloffset) = fread(fid, [h.channeloffset h.nchannels], r.dataformat)';
counter = 1;
while counter*h.channeloffset < r.ldnsamples
dat(:, counter*h.channeloffset+1:counter*h.channeloffset+h.channeloffset) = ...
fread(fid, [h.channeloffset h.nchannels], r.dataformat)';
counter = counter + 1;
end;
end ;
% ftell(fid)
if strcmpi(r.scale, 'on')
disp('Scaling data .....')
%%% scaling to microvolts
for i=1:h.nchannels
bas=e(i).baseline;sen=e(i).senstivity;cal=e(i).calib;
mf=sen*(cal/204.8);
dat(i,:)=(dat(i,:)-bas).*mf;
end % end for i=1:h.nchannels
end; % end if (strcmpi(r.scale, 'on')
end ;
ET_offset = (double(h.prevfile) * (2^32)) + double(h.eventtablepos); % prevfile contains high order bits of event table offset, eventtablepos contains the low order bits
fseek(fid, ET_offset, 'bof');
disp('Reading Event Table...')
eT.teeg = fread(fid,1,'uchar');
eT.size = fread(fid,1,'ulong');
eT.offset = fread(fid,1,'ulong');
if eT.teeg==2
nevents=eT.size/sizeEvent2;
if nevents > 0
ev2(nevents).stimtype = [];
for i=1:nevents
ev2(i).stimtype = fread(fid,1,'ushort');
ev2(i).keyboard = fread(fid,1,'char');
temp = fread(fid,1,'uint8');
ev2(i).keypad_accept = bitand(15,temp);
ev2(i).accept_ev1 = bitshift(temp,-4);
ev2(i).offset = fread(fid,1,'long');
ev2(i).type = fread(fid,1,'short');
ev2(i).code = fread(fid,1,'short');
ev2(i).latency = fread(fid,1,'float');
ev2(i).epochevent = fread(fid,1,'char');
ev2(i).accept = fread(fid,1,'char');
ev2(i).accuracy = fread(fid,1,'char');
end
else
ev2 = [];
end;
elseif eT.teeg==3 % type 3 is similar to type 2 except the offset field encodes the global sample frame
nevents=eT.size/sizeEvent3;
if nevents > 0
ev2(nevents).stimtype = [];
if r.dataformat == 'int32'
bytes_per_samp = 4; % I only have 32 bit data, unable to check whether this is necessary,
else % perhaps there is no type 3 file with 16 bit data
bytes_per_samp = 2;
end
for i=1:nevents
ev2(i).stimtype = fread(fid,1,'ushort');
ev2(i).keyboard = fread(fid,1,'char');
temp = fread(fid,1,'uint8');
ev2(i).keypad_accept = bitand(15,temp);
ev2(i).accept_ev1 = bitshift(temp,-4);
os = fread(fid,1,'ulong');
ev2(i).offset = os * bytes_per_samp * h.nchannels;
ev2(i).type = fread(fid,1,'short');
ev2(i).code = fread(fid,1,'short');
ev2(i).latency = fread(fid,1,'float');
ev2(i).epochevent = fread(fid,1,'char');
ev2(i).accept = fread(fid,1,'char');
ev2(i).accuracy = fread(fid,1,'char');
end
else
ev2 = [];
end;
elseif eT.teeg==1
nevents=eT.size/sizeEvent1;
if nevents > 0
ev2(nevents).stimtype = [];
for i=1:nevents
ev2(i).stimtype = fread(fid,1,'ushort');
ev2(i).keyboard = fread(fid,1,'char');
% modified by Andreas Widmann 2005/05/12 14:15:00
%ev2(i).keypad_accept = fread(fid,1,'char');
temp = fread(fid,1,'uint8');
ev2(i).keypad_accept = bitand(15,temp);
ev2(i).accept_ev1 = bitshift(temp,-4);
% end modification
ev2(i).offset = fread(fid,1,'long');
end;
else
ev2 = [];
end;
else
disp('Skipping event table (tag != 1,2,3 ; theoritically impossible)');
ev2 = [];
end
fseek(fid, -1, 'eof');
t = fread(fid,'char');
f.header = h;
f.electloc = e;
f.data = dat;
f.Teeg = eT;
f.event = ev2;
f.tag=t;
% Surgical addition of number of samples
f.ldnsamples = r.ldnsamples ;
%%%% channels labels
for i=1:h.nchannels
plab=sprintf('%c',f.electloc(i).lab);
if i>1
lab=str2mat(lab,plab);
else
lab=plab;
end
end
%%%% to change offest in bytes to points
if ~isempty(ev2)
if r.sample1 ~= 0
fprintf(2,'Warning: events imported with a time shift might be innacurate\n');
end;
ev2p=ev2;
ioff=900+(h.nchannels*75); %% initial offset : header + electordes desc
if strcmpi(r.dataformat, 'int16')
for i=1:nevents
ev2p(i).offset=(ev2p(i).offset-ioff)/(2*h.nchannels) - r.sample1; %% 2 short int end
end
else % 32 bits
for i=1:nevents
ev2p(i).offset=(ev2p(i).offset-ioff)/(4*h.nchannels) - r.sample1; %% 4 short int end
end
end;
f.event = ev2p;
end;
frewind(fid);
fclose(fid);
end
|
github
|
lcnhappe/happe-master
|
runica.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/eeglab/runica.m
| 64,715 |
utf_8
|
6d997fa33b536afd5abe7d1cac2c0c8d
|
% runica() - Perform Independent Component Analysis (ICA) decomposition
% of input data using the logistic infomax ICA algorithm of
% Bell & Sejnowski (1995) with the natural gradient feature
% of Amari, Cichocki & Yang, or optionally the extended-ICA
% algorithm of Lee, Girolami & Sejnowski, with optional PCA
% dimension reduction. Annealing based on weight changes is
% used to automate the separation process.
% Usage:
% >> [weights,sphere] = runica(data); % train using defaults
% else
% >> [weights,sphere,compvars,bias,signs,lrates,activations] ...
% = runica(data,'Key1',Value1',...);
% Input:
% data = input data (chans,frames*epochs).
% Note that if data consists of multiple discontinuous epochs,
% each epoch should be separately baseline-zero'd using
% >> data = rmbase(data,frames,basevector);
%
% Optional keywords [argument]:
% 'extended' = [N] perform tanh() "extended-ICA" with sign estimation
% N training blocks. If N > 0, automatically estimate the
% number of sub-Gaussian sources. If N < 0, fix number of
% sub-Gaussian comps to -N [faster than N>0] (default|0 -> off)
% 'pca' = [N] decompose a principal component (default -> 0=off)
% subspace of the data. Value is the number of PCs to retain.
% 'sphering' = ['on'/'off'] flag sphering of data (default -> 'on')
% 'weights' = [W] initial weight matrix (default -> eye())
% (Note: if 'sphering' 'off', default -> spher())
% 'lrate' = [rate] initial ICA learning rate (<< 1) (default -> heuristic)
% 'block' = [N] ICA block size (<< datalength) (default -> heuristic)
% 'anneal' = annealing constant (0,1] (defaults -> 0.90, or 0.98, extended)
% controls speed of convergence
% 'annealdeg' = [N] degrees weight change for annealing (default -> 70)
% 'stop' = [f] stop training when weight-change < this (default -> 1e-6
% if less than 33 channel and 1E-7 otherwise)
% 'maxsteps' = [N] max number of ICA training steps (default -> 512)
% 'bias' = ['on'/'off'] perform bias adjustment (default -> 'on')
% 'momentum' = [0<f<1] training momentum (default -> 0)
% 'specgram' = [srate loHz hiHz frames winframes] decompose a complex time/frequency
% transform of the data - though not optimally. (Note: winframes must
% divide frames) (defaults [srate 0 srate/2 size(data,2) size(data,2)])
% 'posact' = make all component activations net-positive(default 'off'}
% Requires time and memory; posact() may be applied separately.
% 'verbose' = give ascii messages ('on'/'off') (default -> 'on')
% 'logfile' = [filename] save all message in a log file in addition to showing them
% on screen (default -> none)
% 'interput' = ['on'|'off'] draw interupt figure. Default is off.
%
% Outputs: [Note: RO means output in reverse order of projected mean variance
% unless starting weight matrix passed ('weights' above)]
% weights = ICA weight matrix (comps,chans) [RO]
% sphere = data sphering matrix (chans,chans) = spher(data)
% Note that unmixing_matrix = weights*sphere {if sphering off -> eye(chans)}
% compvars = back-projected component variances [RO]
% bias = vector of final (ncomps) online bias [RO] (default = zeros())
% signs = extended-ICA signs for components [RO] (default = ones())
% [ -1 = sub-Gaussian; 1 = super-Gaussian]
% lrates = vector of learning rates used at each training step [RO]
% activations = activation time courses of the output components (ncomps,frames*epochs)
%
% Authors: Scott Makeig with contributions from Tony Bell, Te-Won Lee,
% Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky, Delorme Arnaud,
% CNL/The Salk Institute, La Jolla, 1996-
% Uses: posact()
% 'ncomps' = [N] number of ICA components to compute (default -> chans or 'pca' arg)
% using rectangular ICA decomposition. This parameter may return
% strange results. This is because the weight matrix is rectangular
% instead of being square. Do not use except to try to fix the problem.
% Reference (please cite):
%
% Makeig, S., Bell, A.J., Jung, T-P and Sejnowski, T.J.,
% "Independent component analysis of electroencephalographic data,"
% In: D. Touretzky, M. Mozer and M. Hasselmo (Eds). Advances in Neural
% Information Processing Systems 8:145-151, MIT Press, Cambridge, MA (1996).
%
% Toolbox Citation:
%
% Makeig, Scott et al. "EEGLAB: ICA Toolbox for Psychophysiological Research".
% WWW Site, Swartz Center for Computational Neuroscience, Institute of Neural
% Computation, University of San Diego California
% <www.sccn.ucsd.edu/eeglab/>, 2000. [World Wide Web Publication].
%
% For more information:
% http://www.sccn.ucsd.edu/eeglab/icafaq.html - FAQ on ICA/EEG
% http://www.sccn.ucsd.edu/eeglab/icabib.html - mss. on ICA & biosignals
% http://www.cnl.salk.edu/~tony/ica.html - math. mss. on ICA
% Copyright (C) 1996 Scott Makeig et al, 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
%%%%%%%%%%%%%%%%%%%%%%%%%%% Edit history %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% runica() - by Scott Makeig with contributions from Tony Bell, Te-Won Lee
% Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky et al.
% CNL / Salk Institute 1996-00
% 04-30-96 built from icatest.m and ~jung/.../wtwpwica.m -sm
% 07-28-97 new runica(), adds bias (default on), momentum (default off),
% extended-ICA (Lee & Sejnowski, 1997), cumulative angledelta
% (until lrate drops), keywords, signcount for speeding extended-ICA
% 10-07-97 put acos() outside verbose loop; verbose 'off' wasn't stopping -sm
% 11-11-97 adjusted help msg -sm
% 11-30-97 return eye(chans) if sphering 'off' or 'none' (undocumented option) -sm
% 02-27-98 use pinv() instead of inv() to rank order comps if ncomps < chans -sm
% 04-28-98 added 'posact' and 'pca' flags -sm
% 07-16-98 reduced length of randperm() for kurtosis subset calc. -se & sm
% 07-19-98 fixed typo in weights def. above -tl & sm
% 12-21-99 added 'specgram' option suggested by Michael Zibulevsky, UNM -sm
% 12-22-99 fixed rand() sizing inefficiency on suggestion of Mike Spratling, UK -sm
% 01-11-00 fixed rand() sizing bug on suggestion of Jack Foucher, Strasbourg -sm
% 12-18-00 test for existence of Sig Proc Tlbx function 'specgram'; improve
% 'specgram' option arguments -sm
% 01-25-02 reformated help & license -ad
% 01-25-02 lowered default lrate and block -ad
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [weights,sphere,meanvar,bias,signs,lrates,data,y] = runica(data,varargin) % NB: Now optionally returns activations as variable 'data' -sm 7/05
if nargin < 1
help runica
return
end
[chans frames] = size(data); % determine the data size
urchans = chans; % remember original data channels
datalength = frames;
if chans<2
fprintf('\nrunica() - data size (%d,%d) too small.\n\n', chans,frames);
return
end
%
%%%%%%%%%%%%%%%%%%%%%% Declare defaults used below %%%%%%%%%%%%%%%%%%%%%%%%
%
MAX_WEIGHT = 1e8; % guess that weights larger than this have blown up
DEFAULT_STOP = 0.000001; % stop training if weight changes below this
DEFAULT_ANNEALDEG = 60; % when angle change reaches this value,
DEFAULT_ANNEALSTEP = 0.90; % anneal by multiplying lrate by this
DEFAULT_EXTANNEAL = 0.98; % or this if extended-ICA
DEFAULT_MAXSTEPS = 512; % ]top training after this many steps
DEFAULT_MOMENTUM = 0.0; % default momentum weight
DEFAULT_BLOWUP = 1000000000.0; % = learning rate has 'blown up'
DEFAULT_BLOWUP_FAC = 0.8; % when lrate 'blows up,' anneal by this fac
DEFAULT_RESTART_FAC = 0.9; % if weights blowup, restart with lrate
% lower by this factor
MIN_LRATE = 0.000001; % if weight blowups make lrate < this, quit
MAX_LRATE = 0.1; % guard against uselessly high learning rate
DEFAULT_LRATE = 0.00065/log(chans);
% heuristic default - may need adjustment
% for large or tiny data sets!
% DEFAULT_BLOCK = floor(sqrt(frames/4)); % heuristic default
DEFAULT_BLOCK = ceil(min(5*log(frames),0.3*frames)); % heuristic
% - may need adjustment!
% Extended-ICA option:
DEFAULT_EXTENDED = 0; % default off
DEFAULT_EXTBLOCKS = 1; % number of blocks per kurtosis calculation
DEFAULT_NSUB = 1; % initial default number of assumed sub-Gaussians
% for extended-ICA
DEFAULT_EXTMOMENTUM = 0.5; % momentum term for computing extended-ICA kurtosis
MAX_KURTSIZE = 6000; % max points to use in kurtosis calculation
MIN_KURTSIZE = 2000; % minimum good kurtosis size (flag warning)
SIGNCOUNT_THRESHOLD = 25; % raise extblocks when sign vector unchanged
% after this many steps
SIGNCOUNT_STEP = 2; % extblocks increment factor
DEFAULT_SPHEREFLAG = 'on'; % use the sphere matrix as the default
% starting weight matrix
DEFAULT_INTERUPT = 'off'; % figure interuption
DEFAULT_PCAFLAG = 'off'; % don't use PCA reduction
DEFAULT_POSACTFLAG = 'off'; % don't use posact(), to save space -sm 7/05
DEFAULT_VERBOSE = 1; % write ascii info to calling screen
DEFAULT_BIASFLAG = 1; % default to using bias in the ICA update rule
DEFAULT_RESETRANDOMSEED = true; % default to reset the random number generator to a 'random state'
%
%%%%%%%%%%%%%%%%%%%%%%% Set up keyword default values %%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargout < 2,
fprintf('runica() - needs at least two output arguments.\n');
return
end
epochs = 1; % do not care how many epochs in data
pcaflag = DEFAULT_PCAFLAG;
sphering = DEFAULT_SPHEREFLAG; % default flags
posactflag = DEFAULT_POSACTFLAG;
verbose = DEFAULT_VERBOSE;
logfile = [];
block = DEFAULT_BLOCK; % heuristic default - may need adjustment!
lrate = DEFAULT_LRATE;
annealdeg = DEFAULT_ANNEALDEG;
annealstep = 0; % defaults declared below
nochange = NaN;
momentum = DEFAULT_MOMENTUM;
maxsteps = DEFAULT_MAXSTEPS;
weights = 0; % defaults defined below
ncomps = chans;
biasflag = DEFAULT_BIASFLAG;
interupt = DEFAULT_INTERUPT;
extended = DEFAULT_EXTENDED;
extblocks = DEFAULT_EXTBLOCKS;
kurtsize = MAX_KURTSIZE;
signsbias = 0.02; % bias towards super-Gaussian components
extmomentum= DEFAULT_EXTMOMENTUM; % exp. average the kurtosis estimates
nsub = DEFAULT_NSUB;
wts_blowup = 0; % flag =1 when weights too large
wts_passed = 0; % flag weights passed as argument
reset_randomseed = DEFAULT_RESETRANDOMSEED;
%
%%%%%%%%%% Collect keywords and values from argument list %%%%%%%%%%%%%%%
%
if (nargin> 1 & rem(nargin,2) == 0)
fprintf('runica(): Even number of input arguments???')
return
end
for i = 1:2:length(varargin) % for each Keyword
Keyword = varargin{i};
Value = varargin{i+1};
if ~isstr(Keyword)
fprintf('runica(): keywords must be strings')
return
end
Keyword = lower(Keyword); % convert upper or mixed case to lower
if strcmp(Keyword,'weights') | strcmp(Keyword,'weight')
if isstr(Value)
fprintf(...
'runica(): weights value must be a weight matrix or sphere')
return
else
weights = Value;
wts_passed =1;
end
elseif strcmp(Keyword,'ncomps')
if isstr(Value)
fprintf('runica(): ncomps value must be an integer')
return
end
if ncomps < urchans & ncomps ~= Value
fprintf('runica(): Use either PCA or ICA dimension reduction');
return
end
fprintf('*****************************************************************************************');
fprintf('************** WARNING: NCOMPS OPTION OFTEN DOES NOT RETURN ACCURATE RESULTS ************');
fprintf('************** WARNING: IF YOU FIND THE PROBLEM, PLEASE LET US KNOW ************');
fprintf('*****************************************************************************************');
ncomps = Value;
if ~ncomps,
ncomps = chans;
end
elseif strcmp(Keyword,'pca')
if ncomps < urchans & ncomps ~= Value
fprintf('runica(): Use either PCA or ICA dimension reduction');
return
end
if isstr(Value)
fprintf(...
'runica(): pca value should be the number of principal components to retain')
return
end
pcaflag = 'on';
ncomps = Value;
if ncomps > chans | ncomps < 1,
fprintf('runica(): pca value must be in range [1,%d]\n',chans)
return
end
chans = ncomps;
elseif strcmp(Keyword,'interupt')
if ~isstr(Value)
fprintf('runica(): interupt value must be on or off')
return
else
Value = lower(Value);
if ~strcmp(Value,'on') & ~strcmp(Value,'off'),
fprintf('runica(): interupt value must be on or off')
return
end
interupt = Value;
end
elseif strcmp(Keyword,'posact')
if ~isstr(Value)
fprintf('runica(): posact value must be on or off')
return
else
Value = lower(Value);
if ~strcmp(Value,'on') & ~strcmp(Value,'off'),
fprintf('runica(): posact value must be on or off')
return
end
posactflag = Value;
end
elseif strcmp(Keyword,'lrate')
if isstr(Value)
fprintf('runica(): lrate value must be a number')
return
end
lrate = Value;
if lrate>MAX_LRATE | lrate <0,
fprintf('runica(): lrate value is out of bounds');
return
end
if ~lrate,
lrate = DEFAULT_LRATE;
end
elseif strcmp(Keyword,'block') | strcmp(Keyword,'blocksize')
if isstr(Value)
fprintf('runica(): block size value must be a number')
return
end
block = floor(Value);
if ~block,
block = DEFAULT_BLOCK;
end
elseif strcmp(Keyword,'stop') | strcmp(Keyword,'nochange') ...
| strcmp(Keyword,'stopping')
if isstr(Value)
fprintf('runica(): stop wchange value must be a number')
return
end
nochange = Value;
elseif strcmp(Keyword,'logfile')
if ~isstr(Value)
fprintf('runica(): logfile value must be a string')
return
end
logfile = Value;
elseif strcmp(Keyword,'maxsteps') | strcmp(Keyword,'steps')
if isstr(Value)
fprintf('runica(): maxsteps value must be an integer')
return
end
maxsteps = Value;
if ~maxsteps,
maxsteps = DEFAULT_MAXSTEPS;
end
if maxsteps < 0
fprintf('runica(): maxsteps value (%d) must be a positive integer',maxsteps)
return
end
elseif strcmp(Keyword,'anneal') | strcmp(Keyword,'annealstep')
if isstr(Value)
fprintf('runica(): anneal step value (%2.4f) must be a number (0,1)',Value)
return
end
annealstep = Value;
if annealstep <=0 | annealstep > 1,
fprintf('runica(): anneal step value (%2.4f) must be (0,1]',annealstep)
return
end
elseif strcmp(Keyword,'annealdeg') | strcmp(Keyword,'degrees')
if isstr(Value)
fprintf('runica(): annealdeg value must be a number')
return
end
annealdeg = Value;
if ~annealdeg,
annealdeg = DEFAULT_ANNEALDEG;
elseif annealdeg > 180 | annealdeg < 0
fprintf('runica(): annealdeg (%3.1f) is out of bounds [0,180]',...
annealdeg);
return
end
elseif strcmp(Keyword,'momentum')
if isstr(Value)
fprintf('runica(): momentum value must be a number')
return
end
momentum = Value;
if momentum > 1.0 | momentum < 0
fprintf('runica(): momentum value is out of bounds [0,1]')
return
end
elseif strcmp(Keyword,'sphering') | strcmp(Keyword,'sphereing') ...
| strcmp(Keyword,'sphere')
if ~isstr(Value)
fprintf('runica(): sphering value must be on, off, or none')
return
else
Value = lower(Value);
if ~strcmp(Value,'on') & ~strcmp(Value,'off') & ~strcmp(Value,'none'),
fprintf('runica(): sphering value must be on or off')
return
end
sphering = Value;
end
elseif strcmp(Keyword,'bias')
if ~isstr(Value)
fprintf('runica(): bias value must be on or off')
return
else
Value = lower(Value);
if strcmp(Value,'on')
biasflag = 1;
elseif strcmp(Value,'off'),
biasflag = 0;
else
fprintf('runica(): bias value must be on or off')
return
end
end
elseif strcmp(Keyword,'specgram') | strcmp(Keyword,'spec')
if ~exist('specgram') < 2 % if ~exist or defined workspace variable
fprintf(...
'runica(): MATLAB Sig. Proc. Toolbox function "specgram" not found.\n')
return
end
if isstr(Value)
fprintf('runica(): specgram argument must be a vector')
return
end
srate = Value(1);
if (srate < 0)
fprintf('runica(): specgram srate (%4.1f) must be >=0',srate)
return
end
if length(Value)>1
loHz = Value(2);
if (loHz < 0 | loHz > srate/2)
fprintf('runica(): specgram loHz must be >=0 and <= srate/2 (%4.1f)',srate/2)
return
end
else
loHz = 0; % default
end
if length(Value)>2
hiHz = Value(3);
if (hiHz < loHz | hiHz > srate/2)
fprintf('runica(): specgram hiHz must be >=loHz (%4.1f) and <= srate/2 (%4.1f)',loHz,srate/2)
return
end
else
hiHz = srate/2; % default
end
if length(Value)>3
Hzframes = Value(5);
if (Hzframes<0 | Hzframes > size(data,2))
fprintf('runica(): specgram frames must be >=0 and <= data length (%d)',size(data,2))
return
end
else
Hzframes = size(data,2); % default
end
if length(Value)>4
Hzwinlen = Value(4);
if rem(Hzframes,Hzwinlen) % if winlen doesn't divide frames
fprintf('runica(): specgram Hzinc must divide frames (%d)',Hzframes)
return
end
else
Hzwinlen = Hzframes; % default
end
Specgramflag = 1; % set flag to perform specgram()
elseif strcmp(Keyword,'extended') | strcmp(Keyword,'extend')
if isstr(Value)
fprintf('runica(): extended value must be an integer (+/-)')
return
else
extended = 1; % turn on extended-ICA
extblocks = fix(Value); % number of blocks per kurt() compute
if extblocks < 0
nsub = -1*fix(extblocks); % fix this many sub-Gauss comps
elseif ~extblocks,
extended = 0; % turn extended-ICA off
elseif kurtsize>frames, % length of kurtosis calculation
kurtsize = frames;
if kurtsize < MIN_KURTSIZE
fprintf(...
'runica() warning: kurtosis values inexact for << %d points.\n',...
MIN_KURTSIZE);
end
end
end
elseif strcmp(Keyword,'verbose')
if ~isstr(Value)
fprintf('runica(): verbose flag value must be on or off')
return
elseif strcmp(Value,'on'),
verbose = 1;
elseif strcmp(Value,'off'),
verbose = 0;
else
fprintf('runica(): verbose flag value must be on or off')
return
end
elseif strcmp(Keyword,'reset_randomseed')
if ischar(Value)
if strcmp(Value,'yes')
reset_randomseed = true;
elseif strcmp(Value,'no')
reset_randomseed = false;
else
fprintf('runica(): not using the reset_randomseed flag, it should be ''yes'',''no'',0, or 1');
end
else
reset_randomseed = Value;
end
else
fprintf('runica(): unknown flag')
return
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Initialize weights, etc. %%%%%%%%%%%%%%%%%%%%%%%%
%
if ~annealstep,
if ~extended,
annealstep = DEFAULT_ANNEALSTEP; % defaults defined above
else
annealstep = DEFAULT_EXTANNEAL; % defaults defined above
end
end % else use annealstep from commandline
if ~annealdeg,
annealdeg = DEFAULT_ANNEALDEG - momentum*90; % heuristic
if annealdeg < 0,
annealdeg = 0;
end
end
if ncomps > chans | ncomps < 1
fprintf('runica(): number of components must be 1 to %d.\n',chans);
return
end
%
%%%%%%%%%%%%%%%%%%%%% Check keyword values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if frames<chans,
fprintf('runica(): data length (%d) < data channels (%d)!\n',frames,chans)
return
elseif block < 2,
fprintf('runica(): block size %d too small!\n',block)
return
elseif block > frames,
fprintf('runica(): block size exceeds data length!\n');
return
elseif floor(epochs) ~= epochs,
fprintf('runica(): data length is not a multiple of the epoch length!\n');
return
elseif nsub > ncomps
fprintf('runica(): there can be at most %d sub-Gaussian components!\n',ncomps);
return
end;
if ~isempty(logfile)
fid = fopen(logfile, 'w');
if fid == -1, error('Cannot open logfile for writing'); end;
else
fid = [];
end;
verb = verbose;
if weights ~= 0, % initialize weights
% starting weights are being passed to runica() from the commandline
if chans>ncomps & weights ~=0,
[r,c]=size(weights);
if r~=ncomps | c~=chans,
fprintf('runica(): weight matrix must have %d rows, %d columns.\n', ...
chans,ncomps);
return;
end
end
icaprintf(verb,fid,'Using starting weight matrix named in argument list ...\n');
end;
%
% adjust nochange if necessary
%
if isnan(nochange)
if ncomps > 32
nochange = 1E-7;
nochangeupdated = 1; % for fprinting purposes
else
nochangeupdated = 1; % for fprinting purposes
nochange = DEFAULT_STOP;
end;
else
nochangeupdated = 0;
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Process the data %%%%%%%%%%%%%%%%%%%%%%%%%%
%
icaprintf(verb,fid,'\nInput data size [%d,%d] = %d channels, %d frames/n', ...
chans,frames,chans,frames);
if strcmp(pcaflag,'on')
icaprintf(verb,fid,'After PCA dimension reduction,\n finding ');
else
icaprintf(verb,fid,'Finding ');
end
if ~extended
icaprintf(verb,fid,'%d ICA components using logistic ICA.\n',ncomps);
else % if extended
icaprintf(verb,fid,'%d ICA components using extended ICA.\n',ncomps);
if extblocks > 0
icaprintf(verb,fid,'Kurtosis will be calculated initially every %d blocks using %d data points.\n',...
extblocks, kurtsize);
else
icaprintf(verb,fid,'Kurtosis will not be calculated. Exactly %d sub-Gaussian components assumed.\n',nsub);
end
end
icaprintf(verb,fid,'Decomposing %d frames per ICA weight ((%d)^2 = %d weights, %d frames)\n',...
floor(frames/ncomps.^2),ncomps.^2,frames);
icaprintf(verb,fid,'Initial learning rate will be %g, block size %d.\n',...
lrate,block);
if momentum>0,
icaprintf(verb,fid,'Momentum will be %g.\n',momentum);
end
icaprintf(verb,fid,'Learning rate will be multiplied by %g whenever angledelta >= %g deg.\n', ...
annealstep,annealdeg);
if nochangeupdated
icaprintf(verb,fid,'More than 32 channels: default stopping weight change 1E-7\n');
end;
icaprintf(verb,fid,'Training will end when wchange < %g or after %d steps.\n', nochange,maxsteps);
if biasflag,
icaprintf(verb,fid,'Online bias adjustment will be used.\n');
else
icaprintf(verb,fid,'Online bias adjustment will not be used.\n');
end
%
%%%%%%%%%%%%%%%%% Remove overall row means of data %%%%%%%%%%%%%%%%%%%%%%%
%
icaprintf(verb,fid,'Removing mean of each channel ...\n');
%BLGBLGBLG replaced
% rowmeans = mean(data');
% data = data - rowmeans'*ones(1,frames); % subtract row means
%BLGBLGBLG replacement starts
rowmeans = mean(data,2)'; %BLG
% data = data - rowmeans'*ones(1,frames); % subtract row means
for iii=1:size(data,1) %avoids memory errors BLG
data(iii,:)=data(iii,:)-rowmeans(iii);
end
%BLGBLGBLG replacement ends
icaprintf(verb,fid,'Final training data range: %g to %g\n', min(min(data)),max(max(data)));
%
%%%%%%%%%%%%%%%%%%% Perform PCA reduction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmp(pcaflag,'on')
icaprintf(verb,fid,'Reducing the data to %d principal dimensions...\n',ncomps);
%BLGBLGBLG replaced
%[eigenvectors,eigenvalues,data] = pcsquash(data,ncomps);
% make data its projection onto the ncomps-dim principal subspace
%BLGBLGBLG replacement starts
%[eigenvectors,eigenvalues,data] = pcsquash(data,ncomps);
% no need to re-subtract row-means, it was done a few lines above!
PCdat2 = data'; % transpose data
[PCn,PCp]=size(PCdat2); % now p chans,n time points
PCdat2=PCdat2/PCn;
PCout=data*PCdat2;
clear PCdat2;
[PCV,PCD] = eig(PCout); % get eigenvectors/eigenvalues
[PCeigenval,PCindex] = sort(diag(PCD));
PCindex=rot90(rot90(PCindex));
PCEigenValues=rot90(rot90(PCeigenval))';
PCEigenVectors=PCV(:,PCindex);
%PCCompressed = PCEigenVectors(:,1:ncomps)'*data;
data = PCEigenVectors(:,1:ncomps)'*data;
eigenvectors=PCEigenVectors;
eigenvalues=PCEigenValues; %#ok<NASGU>
clear PCn PCp PCout PCV PCD PCeigenval PCindex PCEigenValues PCEigenVectors
%BLGBLGBLG replacement ends
end
%
%%%%%%%%%%%%%%%%%%% Perform specgram transformation %%%%%%%%%%%%%%%%%%%%%%%
%
if exist('Specgramflag') == 1
% [P F T] = SPECGRAM(A,NFFT,Fs,WINDOW,NOVERLAP) % MATLAB Sig Proc Toolbox
% Hzwinlen = fix(srate/Hzinc); % CHANGED FROM THIS 12/18/00 -sm
Hzfftlen = 2^(ceil(log(Hzwinlen)/log(2))); % make FFT length next higher 2^k
Hzoverlap = 0; % use sequential windows
%
% Get freqs and times from 1st channel analysis
%
[tmp,freqs,tms] = specgram(data(1,:),Hzfftlen,srate,Hzwinlen,Hzoverlap);
fs = find(freqs>=loHz & freqs <= hiHz);
icaprintf(verb,fid,'runica(): specified frequency range too narrow, exiting!\n');
specdata = reshape(tmp(fs,:),1,length(fs)*size(tmp,2));
specdata = [real(specdata) imag(specdata)];
% fprintf(' size(fs) = %d,%d\n',size(fs,1),size(fs,2));
% fprintf(' size(tmp) = %d,%d\n',size(tmp,1),size(tmp,2));
%
% Loop through remaining channels
%
for ch=2:chans
[tmp] = specgram(data(ch,:),Hzwinlen,srate,Hzwinlen,Hzoverlap);
tmp = reshape((tmp(fs,:)),1,length(fs)*size(tmp,2));
specdata = [specdata;[real(tmp) imag(tmp)]]; % channels are rows
end
%
% Print specgram confirmation and details
%
icaprintf(verb,fid,'Converted data to %d channels by %d=2*%dx%d points spectrogram data.\n',...
chans,2*length(fs)*length(tms),length(fs),length(tms));
if length(fs) > 1
icaprintf(verb,fid,' Low Hz %g, high Hz %g, Hz incr %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),freqs(fs(2))-freqs(fs(1)),Hzwinlen);
else
icaprintf(verb,fid,' Low Hz %g, high Hz %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),Hzwinlen);
end
%
% Replace data with specdata
%
data = specdata;
datalength=size(data,2);
end
%
%%%%%%%%%%%%%%%%%%% Perform sphering %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmp(sphering,'on'), %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
icaprintf(verb,fid,'Computing the sphering matrix...\n');
sphere = 2.0*inv(sqrtm(double(cov(data')))); % find the "sphering" matrix = spher()
if ~weights,
icaprintf(verb,fid,'Starting weights are the identity matrix ...\n');
weights = eye(ncomps,chans); % begin with the identity matrix
else % weights given on commandline
icaprintf(verb,fid,'Using starting weights named on commandline ...\n');
end
icaprintf(verb,fid,'Sphering the data ...\n');
data = sphere*data; % decorrelate the electrode signals by 'sphereing' them
elseif strcmp(sphering,'off') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~weights % is starting weights not given
icaprintf(verb,fid,'Using the sphering matrix as the starting weight matrix ...\n');
icaprintf(verb,fid,'Returning the identity matrix in variable "sphere" ...\n');
sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher()
weights = eye(ncomps,chans)*sphere; % begin with the identity matrix
sphere = eye(chans); % return the identity matrix
else % weights ~= 0
icaprintf(verb,fid,'Using starting weights from commandline ...\n');
icaprintf(verb,fid,'Returning the identity matrix in variable "sphere" ...\n');
sphere = eye(chans); % return the identity matrix
end
elseif strcmp(sphering,'none')
sphere = eye(chans,chans);% return the identity matrix
if ~weights
icaprintf(verb,fid,'Starting weights are the identity matrix ...\n');
icaprintf(verb,fid,'Returning the identity matrix in variable "sphere" ...\n');
weights = eye(ncomps,chans); % begin with the identity matrix
else % weights ~= 0
icaprintf(verb,fid,'Using starting weights named on commandline ...\n');
icaprintf(verb,fid,'Returning the identity matrix in variable "sphere" ...\n');
end
icaprintf(verb,fid,'Returned variable "sphere" will be the identity matrix.\n');
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Initialize ICA training %%%%%%%%%%%%%%%%%%%%%%%%%
%
lastt=fix((datalength/block-1)*block+1);
BI=block*eye(ncomps,ncomps);
delta=zeros(1,chans*ncomps);
changes = [];
degconst = 180./pi;
startweights = weights;
prevweights = startweights;
oldweights = startweights;
prevwtchange = zeros(chans,ncomps);
oldwtchange = zeros(chans,ncomps);
lrates = zeros(1,maxsteps);
onesrow = ones(1,block);
bias = zeros(ncomps,1);
signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1
for k=1:nsub
signs(k) = -1;
end
if extended & extblocks < 0,
icaprintf(verb,fid,'Fixed extended-ICA sign assignments: ');
for k=1:ncomps
icaprintf(verb,fid,'%d ',signs(k));
end; icaprintf(verb,fid,'\n');
end
signs = diag(signs); % make a diagonal matrix
oldsigns = zeros(size(signs));
signcount = 0; % counter for same-signs
signcounts = [];
urextblocks = extblocks; % original value, for resets
old_kk = zeros(1,ncomps); % for kurtosis momemtum
%
%%%%%%%% ICA training loop using the logistic sigmoid %%%%%%%%%%%%%%%%%%%
%
icaprintf(verb,fid,'Beginning ICA training ...');
if extended,
icaprintf(verb,fid,' first training step may be slow ...\n');
else
icaprintf(verb,fid,'\n');
end
step=0;
laststep=0;
blockno = 1; % running block counter for kurtosis interrupts
if reset_randomseed
rand('state',sum(100*clock)); % set the random number generator state to
end % a position dependent on the system clock
% interupt figure
% ---------------
if strcmpi(interupt, 'on')
fig = figure('visible', 'off');
supergui( fig, {1 1}, [], {'style' 'text' 'string' 'Press button to interrupt runica()' }, ...
{'style' 'pushbutton' 'string' 'Interupt' 'callback' 'setappdata(gcf, ''run'', 0);' } );
set(fig, 'visible', 'on');
setappdata(gcf, 'run', 1);
if strcmpi(interupt, 'on')
drawnow;
end;
end;
%% Compute ICA Weights
if biasflag & extended
while step < maxsteps, %%% ICA step = pass through all the data %%%%%%%%%
timeperm=randperm(datalength); % shuffle data order at each step
for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%%
if strcmpi(interupt, 'on')
drawnow;
flag = getappdata(fig, 'run');
if ~flag,
if ~isempty(fid), fclose(fid); end;
close; error('USER ABORT');
end;
end;
%% promote data block (only) to double to keep u and weights double
u=weights*double(data(:,timeperm(t:t+block-1))) + bias*onesrow;
y=tanh(u);
weights = weights + lrate*(BI-signs*y*u'-u*u')*weights;
bias = bias + lrate*sum((-2*y)')'; % for tanh() nonlin.
if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%%
weights = weights + momentum*prevwtchange;
prevwtchange = weights-prevweights;
prevweights = weights;
end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if max(max(abs(weights))) > MAX_WEIGHT
wts_blowup = 1;
change = nochange;
end
if ~wts_blowup
%
%%%%%%%%%%% Extended-ICA kurtosis estimation %%%%%%%%%%%%%%%%%%%%%
%while step < maxsteps
if extblocks > 0 & rem(blockno,extblocks) == 0,
% recompute signs vector using kurtosis
if kurtsize < frames % 12-22-99 rand() size suggestion by M. Spratling
rp = fix(rand(1,kurtsize)*datalength); % pick random subset
% Accout for the possibility of a 0 generation by rand
ou = find(rp == 0);
while ~isempty(ou) % 1-11-00 suggestion by J. Foucher
rp(ou) = fix(rand(1,length(ou))*datalength);
ou = find(rp == 0);
end
partact=weights*double(data(:,rp(1:kurtsize)));
else % for small data sets,
partact=weights*double(data); % use whole data
end
m2=mean(partact'.^2).^2;
m4= mean(partact'.^4);
kk= (m4./m2)-3.0; % kurtosis estimates
if extmomentum
kk = extmomentum*old_kk + (1.0-extmomentum)*kk; % use momentum
old_kk = kk;
end
signs=diag(sign(kk+signsbias)); % pick component signs
if signs == oldsigns,
signcount = signcount+1;
else
signcount = 0;
end
oldsigns = signs;
signcounts = [signcounts signcount];
if signcount >= SIGNCOUNT_THRESHOLD,
extblocks = fix(extblocks * SIGNCOUNT_STEP);% make kurt() estimation
signcount = 0; % less frequent if sign
end % is not changing
end % extblocks > 0 & . . .
end % if extended & ~wts_blowup %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
blockno = blockno + 1;
if wts_blowup
break
end
end % for t=1:block:lastt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~wts_blowup
oldwtchange = weights-oldweights;
step=step+1;
%
%%%%%%% Compute and print weight and update angle changes %%%%%%%%%
%
lrates(1,step) = lrate;
angledelta=0.;
delta=reshape(oldwtchange,1,chans*ncomps);
change=delta*delta';
end
%
%%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%%
%
if wts_blowup | isnan(change)|isinf(change), % if weights blow up,
icaprintf(verb,fid,'');
step = 0; % start again
change = nochange;
wts_blowup = 0; % re-initialize variables
blockno = 1;
lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate
weights = startweights; % and original weight matrix
oldweights = startweights;
change = nochange;
oldwtchange = zeros(chans,ncomps);
delta=zeros(1,chans*ncomps);
olddelta = delta;
extblocks = urextblocks;
prevweights = startweights;
prevwtchange = zeros(chans,ncomps);
lrates = zeros(1,maxsteps);
bias = zeros(ncomps,1);
signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1
for k=1:nsub
signs(k) = -1;
end
signs = diag(signs); % make a diagonal matrix
oldsigns = zeros(size(signs));;
if lrate> MIN_LRATE
r = rank(data); % determine if data rank is too low
if r<ncomps
icaprintf(verb,fid,'Data has rank %d. Cannot compute %d components.\n',...
r,ncomps);
return
else
icaprintf(verb,fid,...
'Lowering learning rate to %g and starting again.\n',lrate);
end
else
icaprintf(verb,fid, ...
'runica(): QUITTING - weight matrix may not be invertible!\n');
return;
end
else % if weights in bounds
%
%%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%%
%
if step> 2
angledelta=acos((delta*olddelta')/sqrt(change*oldchange));
end
places = -floor(log10(nochange));
icaprintf(verb,fid,'step %d - lrate %5f, wchange %8.8f, angledelta %4.1f deg\n', ...
step, lrate, change, degconst*angledelta);
%
%%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
changes = [changes change];
oldweights = weights;
%
%%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if degconst*angledelta > annealdeg,
lrate = lrate*annealstep; % anneal learning rate
olddelta = delta; % accumulate angledelta until
oldchange = change; % annealdeg is reached
elseif step == 1 % on first step only
olddelta = delta; % initialize
oldchange = change;
end
%
%%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if step >2 & change < nochange, % apply stopping rule
laststep=step;
step=maxsteps; % stop when weights stabilize
elseif change > DEFAULT_BLOWUP, % if weights blow up,
lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying
end; % with a smaller learning rate
end; % end if weights in bounds
end; % end while step < maxsteps (ICA Training) %%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
%% Compute ICA Weights
if biasflag & ~extended
while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
timeperm=randperm(datalength); % shuffle data order at each step
for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%%
if strcmpi(interupt, 'on')
drawnow;
flag = getappdata(fig, 'run');
if ~flag,
if ~isempty(fid), fclose(fid); end;
close; error('USER ABORT');
end;
end;
u=weights*double(data(:,timeperm(t:t+block-1))) + bias*onesrow;
y=1./(1+exp(-u));
weights = weights + lrate*(BI+(1-2*y)*u')*weights;
bias = bias + lrate*sum((1-2*y)')'; % for logistic nonlin. %
if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%%
weights = weights + momentum*prevwtchange;
prevwtchange = weights-prevweights;
prevweights = weights;
end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if max(max(abs(weights))) > MAX_WEIGHT
wts_blowup = 1;
change = nochange;
end
blockno = blockno + 1;
if wts_blowup
break
end
end % for t=1:block:lastt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~wts_blowup
oldwtchange = weights-oldweights;
step=step+1;
%
%%%%%%% Compute and print weight and update angle changes %%%%%%%%%
%
lrates(1,step) = lrate;
angledelta=0.;
delta=reshape(oldwtchange,1,chans*ncomps);
change=delta*delta';
end
%
%%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%%
%
if wts_blowup | isnan(change)|isinf(change), % if weights blow up,
icaprintf(verb,fid,'');
step = 0; % start again
change = nochange;
wts_blowup = 0; % re-initialize variables
blockno = 1;
lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate
weights = startweights; % and original weight matrix
oldweights = startweights;
change = nochange;
oldwtchange = zeros(chans,ncomps);
delta=zeros(1,chans*ncomps);
olddelta = delta;
extblocks = urextblocks;
prevweights = startweights;
prevwtchange = zeros(chans,ncomps);
lrates = zeros(1,maxsteps);
bias = zeros(ncomps,1);
if lrate> MIN_LRATE
r = rank(data); % determine if data rank is too low
if r<ncomps
icaprintf(verb,fid,'Data has rank %d. Cannot compute %d components.\n',r,ncomps);
return
else
icaprintf(verb,fid,'Lowering learning rate to %g and starting again.\n',lrate);
end
else
icaprintf(verb,fid,'runica(): QUITTING - weight matrix may not be invertible!\n');
return;
end
else % if weights in bounds
%
%%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%%
%
if step> 2
angledelta=acos((delta*olddelta')/sqrt(change*oldchange));
end
places = -floor(log10(nochange));
icaprintf(verb,fid,'step %d - lrate %5f, wchange %8.8f, angledelta %4.1f deg\n', ...
step, lrate, change, degconst*angledelta);
%
%%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
changes = [changes change];
oldweights = weights;
%
%%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if degconst*angledelta > annealdeg,
lrate = lrate*annealstep; % anneal learning rate
olddelta = delta; % accumulate angledelta until
oldchange = change; % annealdeg is reached
elseif step == 1 % on first step only
olddelta = delta; % initialize
oldchange = change;
end
%
%%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if step >2 & change < nochange, % apply stopping rule
laststep=step;
step=maxsteps; % stop when weights stabilize
elseif change > DEFAULT_BLOWUP, % if weights blow up,
lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying
end; % with a smaller learning rate
end; % end if weights in bounds
end; % end while step < maxsteps (ICA Training) %%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
%% Compute ICA Weights
if ~biasflag & extended
while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
timeperm=randperm(datalength); % shuffle data order at each step through data
for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%%
if strcmpi(interupt, 'on')
drawnow;
flag = getappdata(fig, 'run');
if ~flag,
if ~isempty(fid), fclose(fid); end;
close; error('USER ABORT');
end;
end;
u=weights*double(data(:,timeperm(t:t+block-1))); % promote block to dbl
y=tanh(u); %
weights = weights + lrate*(BI-signs*y*u'-u*u')*weights;
if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%%
weights = weights + momentum*prevwtchange;
prevwtchange = weights-prevweights;
prevweights = weights;
end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if max(max(abs(weights))) > MAX_WEIGHT
wts_blowup = 1;
change = nochange;
end
if ~wts_blowup
%
%%%%%%%%%%% Extended-ICA kurtosis estimation %%%%%%%%%%%%%%%%%%%%%
%while step < maxsteps
if extblocks > 0 & rem(blockno,extblocks) == 0,
% recompute signs vector using kurtosis
if kurtsize < frames % 12-22-99 rand() size suggestion by M. Spratling
rp = fix(rand(1,kurtsize)*datalength); % pick random subset
% Accout for the possibility of a 0 generation by rand
ou = find(rp == 0);
while ~isempty(ou) % 1-11-00 suggestion by J. Foucher
rp(ou) = fix(rand(1,length(ou))*datalength);
ou = find(rp == 0);
end
partact=weights*double(data(:,rp(1:kurtsize)));
else % for small data sets,
partact=weights*double(data); % use whole data
end
m2=mean(partact'.^2).^2;
m4= mean(partact'.^4);
kk= (m4./m2)-3.0; % kurtosis estimates
if extmomentum
kk = extmomentum*old_kk + (1.0-extmomentum)*kk; % use momentum
old_kk = kk;
end
signs=diag(sign(kk+signsbias)); % pick component signs
if signs == oldsigns,
signcount = signcount+1;
else
signcount = 0;
end
oldsigns = signs;
signcounts = [signcounts signcount];
if signcount >= SIGNCOUNT_THRESHOLD,
extblocks = fix(extblocks * SIGNCOUNT_STEP);% make kurt() estimation
signcount = 0; % less frequent if sign
end % is not changing
end % extblocks > 0 & . . .
end % if ~wts_blowup %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
blockno = blockno + 1;
if wts_blowup
break
end
end % for t=1:block:lastt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~wts_blowup
oldwtchange = weights-oldweights;
step=step+1;
%
%%%%%%% Compute and print weight and update angle changes %%%%%%%%%
%
lrates(1,step) = lrate;
angledelta=0.;
delta=reshape(oldwtchange,1,chans*ncomps);
change=delta*delta';
end
%
%%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%%
%
if wts_blowup | isnan(change)|isinf(change), % if weights blow up,
icaprintf(verb,fid,'');
step = 0; % start again
change = nochange;
wts_blowup = 0; % re-initialize variables
blockno = 1;
lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate
weights = startweights; % and original weight matrix
oldweights = startweights;
change = nochange;
oldwtchange = zeros(chans,ncomps);
delta=zeros(1,chans*ncomps);
olddelta = delta;
extblocks = urextblocks;
prevweights = startweights;
prevwtchange = zeros(chans,ncomps);
lrates = zeros(1,maxsteps);
bias = zeros(ncomps,1);
signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1
for k=1:nsub
signs(k) = -1;
end
signs = diag(signs); % make a diagonal matrix
oldsigns = zeros(size(signs));
if lrate> MIN_LRATE
r = rank(data); % find whether data rank is too low
if r<ncomps
icaprintf(verb,fid,'Data has rank %d. Cannot compute %d components.\n',...
r,ncomps);
return
else
icaprintf(verb,fid,...
'Lowering learning rate to %g and starting again.\n',lrate);
end
else
icaprintf(verb,fid, ...
'runica(): QUITTING - weight matrix may not be invertible!\n');
return;
end
else % if weights in bounds
%
%%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%%
%
if step> 2
angledelta=acos((delta*olddelta')/sqrt(change*oldchange));
end
places = -floor(log10(nochange));
icaprintf(verb,fid,'step %d - lrate %5f, wchange %8.8f, angledelta %4.1f deg\n', ...
step, lrate, change, degconst*angledelta);
%
%%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
changes = [changes change];
oldweights = weights;
%
%%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if degconst*angledelta > annealdeg,
lrate = lrate*annealstep; % anneal learning rate
olddelta = delta; % accumulate angledelta until
oldchange = change; % annealdeg is reached
elseif step == 1 % on first step only
olddelta = delta; % initialize
oldchange = change;
end
%
%%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if step >2 & change < nochange, % apply stopping rule
laststep=step;
step=maxsteps; % stop when weights stabilize
elseif change > DEFAULT_BLOWUP, % if weights blow up,
lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying
end; % with a smaller learning rate
end; % end if weights in bounds
end; % end while step < maxsteps (ICA Training) %%%%%%%%%%%%%%%%%%%%%%%%%
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Compute ICA Weights
if ~biasflag & ~extended
while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
timeperm=randperm(datalength); % shuffle data order at each step
for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%%
if strcmpi(interupt, 'on')
drawnow;
flag = getappdata(fig, 'run');
if ~flag,
if ~isempty(fid), fclose(fid); end;
close; error('USER ABORT');
end;
end;
u=weights*double(data(:,timeperm(t:t+block-1)));
y=1./(1+exp(-u)); %
weights = weights + lrate*(BI+(1-2*y)*u')*weights;
if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%%
weights = weights + momentum*prevwtchange;
prevwtchange = weights-prevweights;
prevweights = weights;
end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if max(max(abs(weights))) > MAX_WEIGHT
wts_blowup = 1;
change = nochange;
end
blockno = blockno + 1;
if wts_blowup
break
end
end % for t=1:block:lastt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~wts_blowup
oldwtchange = weights-oldweights;
step=step+1;
%
%%%%%%% Compute and print weight and update angle changes %%%%%%%%%
%
lrates(1,step) = lrate;
angledelta=0.;
delta=reshape(oldwtchange,1,chans*ncomps);
change=delta*delta';
end
%
%%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%%
%
if wts_blowup | isnan(change)|isinf(change), % if weights blow up,
icaprintf(verb,fid,'');
step = 0; % start again
change = nochange;
wts_blowup = 0; % re-initialize variables
blockno = 1;
lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate
weights = startweights; % and original weight matrix
oldweights = startweights;
change = nochange;
oldwtchange = zeros(chans,ncomps);
delta=zeros(1,chans*ncomps);
olddelta = delta;
extblocks = urextblocks;
prevweights = startweights;
prevwtchange = zeros(chans,ncomps);
lrates = zeros(1,maxsteps);
bias = zeros(ncomps,1);
if lrate> MIN_LRATE
r = rank(data); % find whether data rank is too low
if r<ncomps
icaprintf(verb,fid,'Data has rank %d. Cannot compute %d components.\n',...
r,ncomps);
return
else
icaprintf(verb,fid,...
'Lowering learning rate to %g and starting again.\n',lrate);
end
else
icaprintf(verb,fid, ...
'runica(): QUITTING - weight matrix may not be invertible!\n');
return;
end
else % if weights in bounds
%
%%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%%
%
if step> 2
angledelta=acos((delta*olddelta')/sqrt(change*oldchange));
end
places = -floor(log10(nochange));
icaprintf(verb,fid,'step %d - lrate %5f, wchange %8.8f, angledelta %4.1f deg\n', ...
step, lrate, change, degconst*angledelta);
%
%%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
changes = [changes change];
oldweights = weights;
%
%%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if degconst*angledelta > annealdeg,
lrate = lrate*annealstep; % anneal learning rate
olddelta = delta; % accumulate angledelta until
oldchange = change; % annealdeg is reached
elseif step == 1 % on first step only
olddelta = delta; % initialize
oldchange = change;
end
%
%%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if step >2 & change < nochange, % apply stopping rule
laststep=step;
step=maxsteps; % stop when weights stabilize
elseif change > DEFAULT_BLOWUP, % if weights blow up,
lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying
end; % with a smaller learning rate
end; % end if weights in bounds
end; % end while step < maxsteps (ICA Training) %%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
%% Finalize Computed Data for Output
if strcmpi(interupt, 'on')
close(fig);
end;
if ~laststep
laststep = step;
end;
lrates = lrates(1,1:laststep); % truncate lrate history vector
%
%%%%%%%%%%%%%% Orient components towards max positive activation %%%%%%
%
if nargout > 6 | strcmp(posactflag,'on')
% make activations from sphered and pca'd data; -sm 7/05
% add back the row means removed from data before sphering
if strcmp(pcaflag,'off')
sr = sphere * rowmeans';
for r = 1:ncomps
data(r,:) = data(r,:)+sr(r); % add back row means
end
data = weights*data; % OK in single
else
ser = sphere*eigenvectors(:,1:ncomps)'*rowmeans';
for r = 1:ncomps
data(r,:) = data(r,:)+ser(r); % add back row means
end
data = weights*data; % OK in single
end;
end
%
% NOTE: Now 'data' are the component activations = weights*sphere*raw_data
%
%
%%%%%%%%%%%%%% If pcaflag, compose PCA and ICA matrices %%%%%%%%%%%%%%%
%
if strcmp(pcaflag,'on')
icaprintf(verb,fid,'Composing the eigenvector, weights, and sphere matrices\n');
icaprintf(verb,fid,' into a single rectangular weights matrix; sphere=eye(%d)\n'...
,chans);
weights= weights*sphere*eigenvectors(:,1:ncomps)';
sphere = eye(urchans);
end
%
%%%%%% Sort components in descending order of max projected variance %%%%
%
icaprintf(verb,fid,'Sorting components in descending order of mean projected variance ...\n');
%
%%%%%%%%%%%%%%%%%%%% Find mean variances %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% meanvar = zeros(ncomps,1); % size of the projections
if ncomps == urchans % if weights are square . . .
winv = inv(weights*sphere);
else
icaprintf(verb,fid,'Using pseudo-inverse of weight matrix to rank order component projections.\n');
winv = pinv(weights*sphere);
end
%
% compute variances without backprojecting to save time and memory -sm 7/05
%
meanvar = sum(winv.^2).*sum((data').^2)/((chans*frames)-1); % from Rey Ramirez 8/07
%
%%%%%%%%%%%%%% Sort components by mean variance %%%%%%%%%%%%%%%%%%%%%%%%
%
[sortvar, windex] = sort(meanvar);
windex = windex(ncomps:-1:1); % order large to small
meanvar = meanvar(windex);
%
%%%%%%%%%%%% re-orient max(abs(activations)) to >=0 ('posact') %%%%%%%%
%
if strcmp(posactflag,'on') % default is now off to save processing and memory
icaprintf(verb,fid,'Making the max(abs(activations)) positive ...\n');
[tmp ix] = max(abs(data')); % = max abs activations
signsflipped = 0;
for r=1:ncomps
if sign(data(r,ix(r))) < 0
if nargout>6 % if activations are to be returned (only)
data(r,:) = -1*data(r,:); % flip activations so max(abs()) is >= 0
end
winv(:,r) = -1*winv(:,r); % flip component maps
signsflipped = 1;
end
end
if signsflipped == 1
weights = pinv(winv)*inv(sphere); % re-invert the component maps
end
% [data,winvout,weights] = posact(data,weights); % overwrite data with activations
% changes signs of activations (now = data) and weights
% to make activations (data) net rms-positive
% can call this outside of runica() - though it is inefficient!
end
%
%%%%%%%%%%%%%%%%%%%%% Filter data using final weights %%%%%%%%%%%%%%%%%%
%
if nargout>6, % if activations are to be returned
icaprintf(verb,fid,'Permuting the activation wave forms ...\n');
data = data(windex,:); % data is now activations -sm 7/05
else
clear data
end
weights = weights(windex,:);% reorder the weight matrix
bias = bias(windex); % reorder them
signs = diag(signs); % vectorize the signs matrix
signs = signs(windex); % reorder them
if ~isempty(fid), fclose(fid); end; % close logfile
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
return
% printing functions
% ------------------
function icaprintf(verb,fid, varargin);
if verb
if ~isempty(fid)
fprintf(fid, varargin{:});
end;
fprintf(varargin{:});
end;
|
github
|
lcnhappe/happe-master
|
jader.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/eeglab/jader.m
| 11,455 |
utf_8
|
8b74fa9e0345ee0857e1e564b74dd872
|
% jader() - blind separation of real signals using JADE (v1.5, Dec. 1997).
%
% Usage:
% >> B = jader(X);
% >> B = jader(X,m);
%
% Notes:
% 1) If X is an nxT data matrix (n sensors, T samples) then
% B=jader(X) is a nxn separating matrix such that S=B*X is an nxT
% matrix of estimated source signals.
% 2) If B=jader(X,m), then B has size mxn so that only m sources are
% extracted. This is done by restricting the operation of jader
% to the m first principal components.
% 3) Also, the rows of B are ordered such that the columns of pinv(B)
% are in order of decreasing norm; this has the effect that the
% `most energetically significant' components appear first in the
% rows of S=B*X.
%
% Author: Jean-Francois Cardoso ([email protected])
% Quick notes (more at the end of this file)
%
% o this code is for REAL-valued signals. An implementation of JADE
% for both real and complex signals is also available from
% http://sig.enst.fr/~cardoso/stuff.html
%
% o This algorithm differs from the first released implementations of
% JADE in that it has been optimized to deal more efficiently
% 1) with real signals (as opposed to complex)
% 2) with the case when the ICA model does not necessarily hold.
%
% o There is a practical limit to the number of independent
% components that can be extracted with this implementation. Note
% that the first step of JADE amounts to a PCA with dimensionality
% reduction from n to m (which defaults to n). In practice m
% cannot be `very large' (more than 40, 50, 60... depending on
% available memory)
%
% o See more notes, references and revision history at the end of
% this file and more stuff on the WEB
% http://sig.enst.fr/~cardoso/stuff.html
%
% o This code is supposed to do a good job! Please report any
% problem to [email protected]
% Copyright : Jean-Francois Cardoso. [email protected]
function B = jadeR(X,m)
verbose = 1 ; % Set to 0 for quiet operation
% Finding the number of sources
[n,T] = size(X);
if nargin==1, m=n ; end; % Number of sources defaults to # of sensors
if m>n , fprintf('jade -> Do not ask more sources than sensors here!!!\n'), return,end
if verbose, fprintf('jade -> Looking for %d sources\n',m); end ;
% Self-commenting code
%=====================
if verbose, fprintf('jade -> Removing the mean value\n'); end
X = X - mean(X')' * ones(1,T);
%%% whitening & projection onto signal subspace
% ===========================================
if verbose, fprintf('jade -> Whitening the data\n'); end
[U,D] = eig((X*X')/T) ;
[puiss,k] = sort(diag(D)) ;
rangeW = n-m+1:n ; % indices to the m most significant directions
scales = sqrt(puiss(rangeW)) ; % scales
W = diag(1./scales) * U(1:n,k(rangeW))' ; % whitener
iW = U(1:n,k(rangeW)) * diag(scales) ; % its pseudo-inverse
X = W*X;
%%% Estimation of the cumulant matrices.
% ====================================
if verbose, fprintf('jade -> Estimating cumulant matrices\n'); end
dimsymm = (m*(m+1))/2; % Dim. of the space of real symm matrices
nbcm = dimsymm ; % number of cumulant matrices
CM = zeros(m,m*nbcm); % Storage for cumulant matrices
R = eye(m); %%
Qij = zeros(m); % Temp for a cum. matrix
Xim = zeros(1,m); % Temp
Xjm = zeros(1,m); % Temp
scale = ones(m,1)/T ; % for convenience
%% I am using a symmetry trick to save storage. I should write a
%% short note one of these days explaining what is going on here.
%%
Range = 1:m ; % will index the columns of CM where to store the cum. mats.
for im = 1:m
Xim = X(im,:) ;
Qij = ((scale* (Xim.*Xim)) .* X ) * X' - R - 2 * R(:,im)*R(:,im)' ;
CM(:,Range) = Qij ;
Range = Range + m ;
for jm = 1:im-1
Xjm = X(jm,:) ;
Qij = ((scale * (Xim.*Xjm) ) .*X ) * X' - R(:,im)*R(:,jm)' - R(:,jm)*R(:,im)' ;
CM(:,Range) = sqrt(2)*Qij ;
Range = Range + m ;
end ;
end;
%%% joint diagonalization of the cumulant matrices
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Init
if 1, %% Init by diagonalizing a *single* cumulant matrix. It seems to save
%% some computation time `sometimes'. Not clear if initialization is
%% a good idea since Jacobi rotations are very efficient.
if verbose, fprintf('jade -> Initialization of the diagonalization\n'); end
[V,D] = eig(CM(:,1:m)); % For instance, this one
for u=1:m:m*nbcm, % updating accordingly the cumulant set given the init
CM(:,u:u+m-1) = CM(:,u:u+m-1)*V ;
end;
CM = V'*CM;
else, %% The dont-try-to-be-smart init
V = eye(m) ; % la rotation initiale
end;
seuil = 1/sqrt(T)/100; % A statistically significant threshold
encore = 1;
sweep = 0;
updates = 0;
g = zeros(2,nbcm);
gg = zeros(2,2);
G = zeros(2,2);
c = 0 ;
s = 0 ;
ton = 0 ;
toff = 0 ;
theta = 0 ;
%% Joint diagonalization proper
if verbose, fprintf('jade -> Contrast optimization by joint diagonalization\n'); end
while encore, encore=0;
if verbose, fprintf('jade -> Sweep #%d\n',sweep); end
sweep=sweep+1;
for p=1:m-1,
for q=p+1:m,
Ip = p:m:m*nbcm ;
Iq = q:m:m*nbcm ;
%%% computation of Givens angle
g = [ CM(p,Ip)-CM(q,Iq) ; CM(p,Iq)+CM(q,Ip) ];
gg = g*g';
ton = gg(1,1)-gg(2,2);
toff = gg(1,2)+gg(2,1);
theta = 0.5*atan2( toff , ton+sqrt(ton*ton+toff*toff) );
%%% Givens update
if abs(theta) > seuil, encore = 1 ;
updates = updates + 1;
c = cos(theta);
s = sin(theta);
G = [ c -s ; s c ] ;
pair = [p;q] ;
V(:,pair) = V(:,pair)*G ;
CM(pair,:) = G' * CM(pair,:) ;
CM(:,[Ip Iq]) = [ c*CM(:,Ip)+s*CM(:,Iq) -s*CM(:,Ip)+c*CM(:,Iq) ] ;
%% fprintf('jade -> %3d %3d %12.8f\n',p,q,s);
end%%of the if
end%%of the loop on q
end%%of the loop on p
end%%of the while loop
if verbose, fprintf('jade -> Total of %d Givens rotations\n',updates); end
%%% A separating matrix
% ===================
B = V'*W ;
%%% We permut its rows to get the most energetic components first.
%%% Here the **signals** are normalized to unit variance. Therefore,
%%% the sort is according to the norm of the columns of A = pinv(B)
if verbose, fprintf('jade -> Sorting the components\n',updates); end
A = iW*V ;
[vars,keys] = sort(sum(A.*A)) ;
B = B(keys,:);
B = B(m:-1:1,:) ; % Is this smart ?
% Signs are fixed by forcing the first column of B to have
% non-negative entries.
if verbose, fprintf('jade -> Fixing the signs\n',updates); end
b = B(:,1) ;
signs = sign(sign(b)+0.1) ; % just a trick to deal with sign=0
B = diag(signs)*B ;
return ;
% To do.
% - Implement a cheaper/simpler whitening (is it worth it?)
%
% Revision history:
%
%- V1.5, Dec. 24 1997
% - The sign of each row of B is determined by letting the first
% element be positive.
%
%- V1.4, Dec. 23 1997
% - Minor clean up.
% - Added a verbose switch
% - Added the sorting of the rows of B in order to fix in some
% reasonable way the permutation indetermination. See note 2)
% below.
%
%- V1.3, Nov. 2 1997
% - Some clean up. Released in the public domain.
%
%- V1.2, Oct. 5 1997
% - Changed random picking of the cumulant matrix used for
% initialization to a deterministic choice. This is not because
% of a better rationale but to make the ouput (almost surely)
% deterministic.
% - Rewrote the joint diag. to take more advantage of Matlab's
% tricks.
% - Created more dummy variables to combat Matlab's loose memory
% management.
%
%- V1.1, Oct. 29 1997.
% Made the estimation of the cumulant matrices more regular. This
% also corrects a buglet...
%
%- V1.0, Sept. 9 1997. Created.
%
% Main reference:
% @article{CS-iee-94,
% title = "Blind beamforming for non {G}aussian signals",
% author = "Jean-Fran\c{c}ois Cardoso and Antoine Souloumiac",
% HTML = "ftp://sig.enst.fr/pub/jfc/Papers/iee.ps.gz",
% journal = "IEE Proceedings-F",
% month = dec, number = 6, pages = {362-370}, volume = 140, year = 1993}
%
% Notes:
% ======
%
% Note 1)
%
% The original Jade algorithm/code deals with complex signals in
% Gaussian noise white and exploits an underlying assumption that the
% model of independent components actually holds. This is a
% reasonable assumption when dealing with some narrowband signals.
% In this context, one may i) seriously consider dealing precisely
% with the noise in the whitening process and ii) expect to use the
% small number of significant eigenmatrices to efficiently summarize
% all the 4th-order information. All this is done in the JADE
% algorithm.
%
% In this implementation, we deal with real-valued signals and we do
% NOT expect the ICA model to hold exactly. Therefore, it is
% pointless to try to deal precisely with the additive noise and it
% is very unlikely that the cumulant tensor can be accurately
% summarized by its first n eigen-matrices. Therefore, we consider
% the joint diagonalization of the whole set of eigen-matrices.
% However, in such a case, it is not necessary to compute the
% eigenmatrices at all because one may equivalently use `parallel
% slices' of the cumulant tensor. This part (computing the
% eigen-matrices) of the computation can be saved: it suffices to
% jointly diagonalize a set of cumulant matrices. Also, since we are
% dealing with reals signals, it becomes easier to exploit the
% symmetries of the cumulants to further reduce the number of
% matrices to be diagonalized. These considerations, together with
% other cheap tricks lead to this version of JADE which is optimized
% (again) to deal with real mixtures and to work `outside the model'.
% As the original JADE algorithm, it works by minimizing a `good set'
% of cumulants.
%
% Note 2)
%
% The rows of the separating matrix B are resorted in such a way that
% the columns of the corresponding mixing matrix A=pinv(B) are in
% decreasing order of (Euclidian) norm. This is a simple, `almost
% canonical' way of fixing the indetermination of permutation. It
% has the effect that the first rows of the recovered signals (ie the
% first rows of B*X) correspond to the most energetic *components*.
% Recall however that the source signals in S=B*X have unit variance.
% Therefore, when we say that the observations are unmixed in order
% of decreasing energy, the energetic signature is found directly as
% the norm of the columns of A=pinv(B).
%
% Note 3)
%
% In experiments where JADE is run as B=jadeR(X,m) with m varying in
% range of values, it is nice to be able to test the stability of the
% decomposition. In order to help in such a test, the rows of B can
% be sorted as described above. We have also decided to fix the sign
% of each row in some arbitrary but fixed way. The convention is
% that the first element of each row of B is positive.
%
%
% Note 4)
%
% Contrary to many other ICA algorithms, JADE (or least this version)
% does not operate on the data themselves but on a statistic (the
% full set of 4th order cumulant). This is represented by the matrix
% CM below, whose size grows as m^2 x m^2 where m is the number of
% sources to be extracted (m could be much smaller than n). As a
% consequence, (this version of) JADE will probably choke on a
% `large' number of sources. Here `large' depends mainly on the
% available memory and could be something like 40 or so. One of
% these days, I will prepare a version of JADE taking the `data'
% option rather than the `statistic' option.
%
%
% JadeR.m ends here.
|
github
|
lcnhappe/happe-master
|
spm_write_sn.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm2/spm_write_sn.m
| 16,446 |
utf_8
|
c5ee1fa9a0d128de2d7e3d4522ea5ad1
|
function VO = spm_write_sn(V,prm,flags,extras)
% Write Out Warped Images.
% FORMAT VO = spm_write_sn(V,prm,flags,msk)
% V - Images to transform (filenames or volume structure).
% matname - Transformation information (filename or structure).
% flags - flags structure, with fields...
% interp - interpolation method (0-7)
% wrap - wrap edges (e.g., [1 1 0] for 2D MRI sequences)
% vox - voxel sizes (3 element vector - in mm)
% Non-finite values mean use template vox.
% bb - bounding box (2x3 matrix - in mm)
% Non-finite values mean use template bb.
% preserve - either 0 or 1. A value of 1 will "modulate"
% the spatially normalised images so that total
% units are preserved, rather than just
% concentrations.
% msk - An optional cell array for masking the spatially
% normalised images (see below).
%
% Warped images are written prefixed by "w".
%
% Non-finite vox or bounding box suggests that values should be derived
% from the template image.
%
% Don't use interpolation methods greater than one for data containing
% NaNs.
% _______________________________________________________________________
%
% FORMAT msk = spm_write_sn(V,prm,flags,'mask')
% V - Images to transform (filenames or volume structure).
% matname - Transformation information (filename or structure).
% flags - flags structure, with fields...
% wrap - wrap edges (e.g., [1 1 0] for 2D MRI sequences)
% vox - voxel sizes (3 element vector - in mm)
% Non-finite values mean use template vox.
% bb - bounding box (2x3 matrix - in mm)
% Non-finite values mean use template bb.
% msk - a cell array for masking a series of spatially normalised
% images.
%
%
% _______________________________________________________________________
%
% FORMAT VO = spm_write_sn(V,prm,'modulate')
% V - Spatially normalised images to modulate (filenames or
% volume structure).
% prm - Transformation information (filename or structure).
%
% After nonlinear spatial normalization, the relative volumes of some
% brain structures will have decreased, whereas others will increase.
% The resampling of the images preserves the concentration of pixel
% units in the images, so the total counts from structures that have
% reduced volumes after spatial normalization will be reduced by an
% amount proportional to the volume reduction.
%
% This routine rescales images after spatial normalization, so that
% the total counts from any structure are preserved. It was written
% as an optional step in performing voxel based morphometry.
%
%_______________________________________________________________________
% @(#)spm_write_sn.m 2.20 John Ashburner 04/02/10
if isempty(V), return; end;
if ischar(prm), prm = load(prm); end;
if ischar(V), V = spm_vol(V); end;
if nargin==3 & ischar(flags) & strcmp(lower(flags),'modulate'),
if nargout==0,
modulate(V,prm);
else,
VO = modulate(V,prm);
end;
return;
end;
def_flags = struct('interp',1,'vox',NaN,'bb',NaN,'wrap',[0 0 0],'preserve',0);
[def_flags.bb, def_flags.vox] = bbvox_from_V(prm.VG(1));
if nargin < 3,
flags = def_flags;
else,
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));
end;
end;
end;
if ~all(isfinite(flags.vox(:))), flags.vox = def_flags.vox; end;
if ~all(isfinite(flags.bb(:))), flags.bb = def_flags.bb; end;
[x,y,z,mat] = get_xyzmat(prm,flags.bb,flags.vox);
if nargin==4,
if ischar(extras) & strcmp(lower(extras),'mask'),
VO = get_snmask(V,prm,x,y,z,flags.wrap);
return;
end;
if iscell(extras),
msk = extras;
end;
end;
if nargout>0 & length(V)>8,
error('Too many images to save in memory');
end;
if ~exist('msk','var')
msk = get_snmask(V,prm,x,y,z,flags.wrap);
end;
if nargout==0,
if isempty(prm.Tr),
affine_transform(V,prm,x,y,z,mat,flags,msk);
else,
nonlin_transform(V,prm,x,y,z,mat,flags,msk);
end;
else,
if isempty(prm.Tr),
VO = affine_transform(V,prm,x,y,z,mat,flags,msk);
else,
VO = nonlin_transform(V,prm,x,y,z,mat,flags,msk);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function VO = affine_transform(V,prm,x,y,z,mat,flags,msk)
[X,Y] = ndgrid(x,y);
d = [flags.interp*[1 1 1]' flags.wrap(:)];
spm_progress_bar('Init',prod(size(V)),'Resampling','volumes completed');
for i=1:prod(size(V)),
VO = make_hdr_struct(V(i),x,y,z,mat);
detAff = det(prm.VF.mat*prm.Affine/prm.VG(1).mat);
if flags.preserve, VO.pinfo(1:2,:) = VO.pinfo(1:2,:)/detAff; end;
if nargout>0,
%Dat= zeros(VO.dim(1:3));
Dat = single(0);
Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0;
else,
VO = spm_create_vol(VO);
end;
C = spm_bsplinc(V(i),d);
for j=1:length(z), % Cycle over planes
[X2,Y2,Z2] = mmult(X,Y,z(j),V(i).mat\prm.VF.mat*prm.Affine);
dat = spm_bsplins(C,X2,Y2,Z2,d);
if flags.preserve, dat = dat*detAff; end;
dat(msk{j}) = NaN;
if nargout>0,
Dat(:,:,j) = single(dat);
else,
VO = spm_write_plane(VO,dat,j);
end;
if prod(size(V))<5, spm_progress_bar('Set',i-1+j/length(z)); end;
end;
if nargout==0,
VO = spm_close_vol(VO);
else,
VO.pinfo = [1 0]';
VO.dim(4) = spm_type('float');
VO.dat = Dat;
end;
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function VO = nonlin_transform(V,prm,x,y,z,mat,flags,msk)
[X,Y] = ndgrid(x,y);
Tr = prm.Tr;
BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1);
BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1);
BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1);
if flags.preserve,
DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff');
DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff');
DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff');
end;
d = [flags.interp*[1 1 1]' flags.wrap(:)];
spm_progress_bar('Init',prod(size(V)),'Resampling','volumes completed');
for i=1:prod(size(V)),
VO = make_hdr_struct(V(i),x,y,z,mat);
detAff = det(prm.VF.mat*prm.Affine/prm.VG(1).mat);
if flags.preserve | nargout>0,
%Dat= zeros(VO.dim(1:3));
Dat = single(0);
Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0;
else,
VO = spm_create_vol(VO);
end;
C = spm_bsplinc(V(i),d);
for j=1:length(z), % Cycle over planes
% Nonlinear deformations
%----------------------------------------------------------------------------
tx = get_2Dtrans(Tr(:,:,:,1),BZ,j);
ty = get_2Dtrans(Tr(:,:,:,2),BZ,j);
tz = get_2Dtrans(Tr(:,:,:,3),BZ,j);
X1 = X + BX*tx*BY';
Y1 = Y + BX*ty*BY';
Z1 = z(j) + BX*tz*BY';
[X2,Y2,Z2] = mmult(X1,Y1,Z1,V(i).mat\prm.VF.mat*prm.Affine);
dat = spm_bsplins(C,X2,Y2,Z2,d);
dat(msk{j}) = NaN;
if ~flags.preserve,
if nargout>0,
Dat(:,:,j) = single(dat);
else,
VO = spm_write_plane(VO,dat,j);
end;
else,
j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY';
j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY';
j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1;
% The determinant of the Jacobian reflects relative volume changes.
%------------------------------------------------------------------
dat = dat .* (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff;
Dat(:,:,j) = single(dat);
end;
if prod(size(V))<5, spm_progress_bar('Set',i-1+j/length(z)); end;
end;
if nargout==0,
if flags.preserve,
VO = spm_write_vol(VO,Dat);
else,
VO = spm_close_vol(VO);
end;
else,
VO.pinfo = [1 0]';
VO.dim(4) = spm_type('float');
VO.dat = Dat;
end;
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function VO = modulate(V,prm)
spm_progress_bar('Init',prod(size(V)),'Modulating','volumes completed');
for i=1:prod(size(V)),
VO = V(i);
VO.fname = prepend(VO.fname,'m');
detAff = det(prm.VF.mat*prm.Affine/prm.VG(1).mat);
%Dat = zeros(VO.dim(1:3));
Dat = single(0);
Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0;
[bb, vox] = bbvox_from_V(VO);
[x,y,z,mat] = get_xyzmat(prm,bb,vox);
if sum((mat(:)-VO.mat(:)).^2)>1e-7, error('Orientations not compatible'); end;
Tr = prm.Tr;
if isempty(Tr),
for j=1:length(z), % Cycle over planes
dat = spm_slice_vol(V(i),spm_matrix([0 0 j]),V(i).dim(1:2),0);
Dat(:,:,j) = single(dat);
if prod(size(V))<5, spm_progress_bar('Set',i-1+j/length(z)); end;
end;
else,
BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1);
BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1);
BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1);
DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff');
DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff');
DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff');
for j=1:length(z), % Cycle over planes
tx = get_2Dtrans(Tr(:,:,:,1),BZ,j);
ty = get_2Dtrans(Tr(:,:,:,2),BZ,j);
tz = get_2Dtrans(Tr(:,:,:,3),BZ,j);
j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY';
j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY';
j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1;
% The determinant of the Jacobian reflects relative volume changes.
%------------------------------------------------------------------
dat = spm_slice_vol(V(i),spm_matrix([0 0 j]),V(i).dim(1:2),0);
dat = dat .* (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff;
Dat(:,:,j) = single(dat);
if prod(size(V))<5, spm_progress_bar('Set',i-1+j/length(z)); end;
end;
end;
if nargout==0,
VO = spm_write_vol(VO,Dat);
else,
VO.pinfo = [1 0]';
VO.dim(4) = spm_type('float');
VO.dat = Dat;
end;
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function VO = make_hdr_struct(V,x,y,z,mat)
VO = V;
VO.fname = prepend(V.fname,'w');
VO.mat = mat;
VO.dim(1:3) = [length(x) length(y) length(z)];
VO.descrip = ['spm - 3D normalized'];
return;
%_______________________________________________________________________
%_______________________________________________________________________
function T2 = get_2Dtrans(T3,B,j)
d = [size(T3) 1 1 1];
tmp = reshape(T3,d(1)*d(2),d(3));
T2 = reshape(tmp*B(j,:)',d(1),d(2));
return;
%_______________________________________________________________________
%_______________________________________________________________________
function PO = prepend(PI,pre)
[pth,nm,xt,vr] = fileparts(deblank(PI));
PO = fullfile(pth,[pre nm xt vr]);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function Mask = getmask(X,Y,Z,dim,wrp)
% Find range of slice
tiny = 5e-2;
Mask = logical(ones(size(X)));
if ~wrp(1), Mask = Mask & (X >= (1-tiny) & X <= (dim(1)+tiny)); end;
if ~wrp(2), Mask = Mask & (Y >= (1-tiny) & Y <= (dim(2)+tiny)); end;
if ~wrp(3), Mask = Mask & (Z >= (1-tiny) & Z <= (dim(3)+tiny)); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [X2,Y2,Z2] = mmult(X1,Y1,Z1,Mult);
if length(Z1) == 1,
X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + (Mult(1,3)*Z1 + Mult(1,4));
Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + (Mult(2,3)*Z1 + Mult(2,4));
Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + (Mult(3,3)*Z1 + Mult(3,4));
else,
X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + Mult(1,3)*Z1 + Mult(1,4);
Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + Mult(2,3)*Z1 + Mult(2,4);
Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + Mult(3,3)*Z1 + Mult(3,4);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [bb,vx] = bbvox_from_V(V)
vx = sqrt(sum(V.mat(1:3,1:3).^2));
if det(V.mat(1:3,1:3))<0, vx(1) = -vx(1); end;
o = V.mat\[0 0 0 1]';
o = o(1:3)';
bb = [-vx.*(o-1) ; vx.*(V.dim(1:3)-o)];
return;
%_______________________________________________________________________
%_______________________________________________________________________
function msk = get_snmask(V,prm,x,y,z,wrap)
% Generate a mask for where there is data for all images
%-----------------------------------------------------------------------
msk = cell(length(z),1);
t1 = cat(3,V.mat);
t2 = cat(1,V.dim);
t = [reshape(t1,[16 length(V)])' t2(:,1:3)];
Tr = prm.Tr;
[X,Y] = ndgrid(x,y);
BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1);
BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1);
BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1);
if prod(size(V))>1 & any(any(diff(t,1,1))),
spm_progress_bar('Init',length(z),'Computing available voxels','planes completed');
for j=1:length(z), % Cycle over planes
Count = zeros(length(x),length(y));
if isempty(Tr),
% Generate a mask for where there is data for all images
%----------------------------------------------------------------------------
for i=1:prod(size(V)),
[X2,Y2,Z2] = mmult(X,Y,z(j),V(i).mat\prm.VF.mat*prm.Affine);
Count = Count + getmask(X2,Y2,Z2,V(i).dim(1:3),wrap);
end;
else,
% Nonlinear deformations
%----------------------------------------------------------------------------
X1 = X + BX*get_2Dtrans(Tr(:,:,:,1),BZ,j)*BY';
Y1 = Y + BX*get_2Dtrans(Tr(:,:,:,2),BZ,j)*BY';
Z1 = z(j) + BX*get_2Dtrans(Tr(:,:,:,3),BZ,j)*BY';
% Generate a mask for where there is data for all images
%----------------------------------------------------------------------------
for i=1:prod(size(V)),
[X2,Y2,Z2] = mmult(X1,Y1,Z1,V(i).mat\prm.VF.mat*prm.Affine);
Count = Count + getmask(X2,Y2,Z2,V(i).dim(1:3),wrap);
end;
end;
msk{j} = uint32(find(Count ~= prod(size(V))));
spm_progress_bar('Set',j);
end;
spm_progress_bar('Clear');
else,
for j=1:length(z), msk{j} = uint32([]); end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [x,y,z,mat] = get_xyzmat(prm,bb,vox)
% The old voxel size and origin notation is used here.
% This requires that the position and orientation
% of the template is transverse. It would not be
% straitforward to account for templates that are
% in different orientations because the basis functions
% would no longer be seperable. The seperable basis
% functions mean that computing the deformation field
% from the parameters is much faster.
% bb = sort(bb);
% vox = abs(vox);
msk = find(vox<0);
bb = sort(bb);
bb(:,msk) = flipud(bb(:,msk));
% Adjust bounding box slightly - so it rounds to closest voxel.
bb(:,1) = round(bb(:,1)/vox(1))*vox(1);
bb(:,2) = round(bb(:,2)/vox(2))*vox(2);
bb(:,3) = round(bb(:,3)/vox(3))*vox(3);
M = prm.VG(1).mat;
vxg = sqrt(sum(M(1:3,1:3).^2));
if det(M(1:3,1:3))<0, vxg(1) = -vxg(1); end;
ogn = M\[0 0 0 1]';
ogn = ogn(1:3)';
% Convert range into range of voxels within template image
x = (bb(1,1):vox(1):bb(2,1))/vxg(1) + ogn(1);
y = (bb(1,2):vox(2):bb(2,2))/vxg(2) + ogn(2);
z = (bb(1,3):vox(3):bb(2,3))/vxg(3) + ogn(3);
og = -vxg.*ogn;
of = -vox.*(round(-bb(1,:)./vox)+1);
M1 = [vxg(1) 0 0 og(1) ; 0 vxg(2) 0 og(2) ; 0 0 vxg(3) og(3) ; 0 0 0 1];
M2 = [vox(1) 0 0 of(1) ; 0 vox(2) 0 of(2) ; 0 0 vox(3) of(3) ; 0 0 0 1];
mat = prm.VG(1).mat*inv(M1)*M2;
if (spm_flip_analyze_images & det(mat(1:3,1:3))>0) | (~spm_flip_analyze_images & det(mat(1:3,1:3))<0),
Flp = [-1 0 0 (length(x)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];
mat = mat*Flp;
x = flipud(x(:))';
end;
return;
|
github
|
lcnhappe/happe-master
|
spm_affreg.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm2/spm_affreg.m
| 18,476 |
utf_8
|
46e5122f9bf661904177ad3e3beb09c1
|
function [M,scal] = spm_affreg(VG,VF,flags,M,scal)
% Affine registration using least squares.
% FORMAT [M,scal] = spm_affreg(VG,VF,flags,M0,scal0)
%
% VG - Vector of template volumes.
% VF - Source volume.
% flags - a structure containing various options. The fields are:
% WG - Weighting volume for template image(s).
% WF - Weighting volume for source image
% Default to [].
% sep - Approximate spacing between sampled points (mm).
% Defaults to 5.
% regtype - regularisation type. Options are:
% 'none' - no regularisation
% 'rigid' - almost rigid body
% 'subj' - inter-subject registration (default).
% 'mni' - registration to ICBM templates
% globnorm - Global normalisation flag (1)
% M0 - (optional) starting estimate. Defaults to eye(4).
% scal0 - (optional) starting estimate.
%
% M - affine transform, such that voxels in VF map to those in
% VG by VG.mat\M*VF.mat
% scal - scaling factors for VG
%
% When only one template is used, then the cost function is approximately
% symmetric, although a linear combination of templates can be used.
% Regularisation is based on assuming a multi-normal distribution for the
% elements of the Henckey Tensor. See:
% "Non-linear Elastic Deformations". R. W. Ogden (Dover), 1984.
% Weighting for the regularisation is determined approximately according
% to:
% "Incorporating Prior Knowledge into Image Registration"
% J. Ashburner, P. Neelin, D. L. Collins, A. C. Evans & K. J. Friston.
% NeuroImage 6:344-352 (1997).
%
%_______________________________________________________________________
% @(#)spm_affreg.m 2.3 John Ashburner 03/02/18
if nargin<5, scal = ones(length(VG),1); end;
if nargin<4, M = eye(4); end;
def_flags = struct('sep',5, 'regtype','subj','WG',[],'WF',[],'globnorm',1,'debug',0);
if nargin < 2 | ~isstruct(flags),
flags = def_flags;
else,
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));
end;
end;
end;
% Check to ensure inputs are valid...
% ---------------------------------------------------------------
if length(VF)>1, error('Can not use more than one source image'); end;
if ~isempty(flags.WF),
if length(flags.WF)>1,
error('Can only use one source weighting image');
end;
if any(any(VF.mat-flags.WF.mat)),
error('Source and its weighting image must have same orientation');
end;
if any(any(VF.dim(1:3)-flags.WF.dim(1:3))),
error('Source and its weighting image must have same dimensions');
end;
end;
if ~isempty(flags.WG),
if length(flags.WG)>1,
error('Can only use one template weighting image');
end;
tmp = reshape(cat(3,VG(:).mat,flags.WG.mat),16,length(VG)+length(flags.WG));
else,
tmp = reshape(cat(3,VG(:).mat),16,length(VG));
end;
if any(any(diff(tmp,1,2))),
error('Reference images must all have the same orientation');
end;
if ~isempty(flags.WG),
tmp = cat(1,VG(:).dim,flags.WG.dim);
else,
tmp = cat(1,VG(:).dim);
end;
if any(any(diff(tmp(:,1:3),1,1))),
error('Reference images must all have the same dimensions');
end;
% ---------------------------------------------------------------
% Generate points to sample from, adding some jitter in order to
% make the cost function smoother.
% ---------------------------------------------------------------
rand('state',0); % want the results to be consistant.
dg = VG(1).dim(1:3);
df = VF(1).dim(1:3);
if length(VG)==1,
skip = sqrt(sum(VG(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;
[x1,x2,x3]=ndgrid(1:skip(1):dg(1)-.5, 1:skip(2):dg(2)-.5, 1:skip(3):dg(3)-.5);
x1 = x1 + rand(size(x1))*0.5; x1 = x1(:);
x2 = x2 + rand(size(x2))*0.5; x2 = x2(:);
x3 = x3 + rand(size(x3))*0.5; x3 = x3(:);
end;
skip = sqrt(sum(VF(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;
[y1,y2,y3]=ndgrid(1:skip(1):df(1)-.5, 1:skip(2):df(2)-.5, 1:skip(3):df(3)-.5);
y1 = y1 + rand(size(y1))*0.5; y1 = y1(:);
y2 = y2 + rand(size(y2))*0.5; y2 = y2(:);
y3 = y3 + rand(size(y3))*0.5; y3 = y3(:);
% ---------------------------------------------------------------
if flags.globnorm,
% Scale all images approximately equally
% ---------------------------------------------------------------
for i=1:length(VG),
VG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i));
end;
VF(1).pinfo(1:2,:) = VF(1).pinfo(1:2,:)/spm_global(VF(1));
end;
% ---------------------------------------------------------------
if length(VG)==1,
[G,dG1,dG2,dG3] = spm_sample_vol(VG(1),x1,x2,x3,1);
if ~isempty(flags.WG),
WG = abs(spm_sample_vol(flags.WG,x1,x2,x3,1))+eps;
end;
end;
[F,dF1,dF2,dF3] = spm_sample_vol(VF(1),y1,y2,y3,1);
if ~isempty(flags.WF),
WF = abs(spm_sample_vol(flags.WF,y1,y2,y3,1))+eps;
end;
% ---------------------------------------------------------------
n_main_its = 0;
ss = Inf;
W = [Inf Inf Inf];
est_smo = 1;
% ---------------------------------------------------------------
for iter=1:256,
pss = ss;
p0 = [0 0 0 0 0 0 1 1 1 0 0 0];
% Initialise the cost function and its 1st and second derivatives
% ---------------------------------------------------------------
n = 0;
ss = 0;
Beta = zeros(12+length(VG),1);
Alpha = zeros(12+length(VG));
if length(VG)==1,
% Make the cost function symmetric
% ---------------------------------------------------------------
% Build a matrix to rotate the derivatives by, converting from
% derivatives w.r.t. changes in the overall affine transformation
% matrix, to derivatives w.r.t. the parameters p.
% ---------------------------------------------------------------
dt = 0.0001;
R = eye(13);
MM0 = inv(VG.mat)*inv(spm_matrix(p0))*VG.mat;
for i1=1:12,
p1 = p0;
p1(i1) = p1(i1)+dt;
MM1 = (inv(VG.mat)*inv(spm_matrix(p1))*(VG.mat));
R(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1);
end;
% ---------------------------------------------------------------
[t1,t2,t3] = coords((M*VF(1).mat)\VG(1).mat,x1,x2,x3);
msk = find((t1>=1 & t1<=df(1) & t2>=1 & t2<=df(2) & t3>=1 & t3<=df(3)));
if length(msk)<32, error_message; end;
t1 = t1(msk);
t2 = t2(msk);
t3 = t3(msk);
t = spm_sample_vol(VF(1), t1,t2,t3,1);
% Get weights
% ---------------------------------------------------------------
if ~isempty(flags.WF) | ~isempty(flags.WG),
if isempty(flags.WF),
wt = WG(msk);
else,
wt = spm_sample_vol(flags.WF(1), t1,t2,t3,1)+eps;
if ~isempty(flags.WG), wt = 1./(1./wt + 1./WG(msk)); end;
end;
wt = sparse(1:length(wt),1:length(wt),wt);
else,
wt = speye(length(msk));
wt = [];
end;
% ---------------------------------------------------------------
clear t1 t2 t3
% Update the cost function and its 1st and second derivatives.
% ---------------------------------------------------------------
[AA,Ab,ss1,n1] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,scal^(-2)*t,G(msk)-(1/scal)*t,wt);
Alpha = Alpha + R'*AA*R;
Beta = Beta + R'*Ab;
ss = ss + ss1;
n = n + n1;
t = G(msk) - (1/scal)*t;
end;
if 1,
% Build a matrix to rotate the derivatives by, converting from
% derivatives w.r.t. changes in the overall affine transformation
% matrix, to derivatives w.r.t. the parameters p.
% ---------------------------------------------------------------
dt = 0.0001;
R = eye(12+length(VG));
MM0 = inv(M*VF.mat)*spm_matrix(p0)*M*VF.mat;
for i1=1:12,
p1 = p0;
p1(i1) = p1(i1)+dt;
MM1 = (inv(M*VF.mat)*spm_matrix(p1)*M*VF.mat);
R(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1);
end;
% ---------------------------------------------------------------
[t1,t2,t3] = coords(VG(1).mat\M*VF(1).mat,y1,y2,y3);
msk = find((t1>=1 & t1<=dg(1) & t2>=1 & t2<=dg(2) & t3>=1 & t3<=dg(3)));
if length(msk)<32, error_message; end;
if length(msk)<32, error_message; end;
t1 = t1(msk);
t2 = t2(msk);
t3 = t3(msk);
t = zeros(length(t1),length(VG));
% Get weights
% ---------------------------------------------------------------
if ~isempty(flags.WF) | ~isempty(flags.WG),
if isempty(flags.WG),
wt = WF(msk);
else,
wt = spm_sample_vol(flags.WG(1), t1,t2,t3,1)+eps;
if ~isempty(flags.WF), wt = 1./(1./wt + 1./WF(msk)); end;
end;
wt = sparse(1:length(wt),1:length(wt),wt);
else,
wt = speye(length(msk));
end;
% ---------------------------------------------------------------
if est_smo,
% Compute derivatives of residuals in the space of F
% ---------------------------------------------------------------
[ds1,ds2,ds3] = transform_derivs(VG(1).mat\M*VF(1).mat,dF1(msk),dF2(msk),dF3(msk));
for i=1:length(VG),
[t(:,i),dt1,dt2,dt3] = spm_sample_vol(VG(i), t1,t2,t3,1);
ds1 = ds1 - dt1*scal(i); clear dt1
ds2 = ds2 - dt2*scal(i); clear dt2
ds3 = ds3 - dt3*scal(i); clear dt3
end;
dss = [ds1'*wt*ds1 ds2'*wt*ds2 ds3'*wt*ds3];
clear ds1 ds2 ds3
else,
for i=1:length(VG),
t(:,i)= spm_sample_vol(VG(i), t1,t2,t3,1);
end;
end;
clear t1 t2 t3
% Update the cost function and its 1st and second derivatives.
% ---------------------------------------------------------------
[AA,Ab,ss2,n2] = costfun(y1,y2,y3,dF1,dF2,dF3,msk,-t,F(msk)-t*scal,wt);
Alpha = Alpha + R'*AA*R;
Beta = Beta + R'*Ab;
ss = ss + ss2;
n = n + n2;
end;
if est_smo,
% Compute a smoothness correction from the residuals and their
% derivatives. This is analagous to the one used in:
% "Analysis of fMRI Time Series Revisited"
% Friston KJ, Holmes AP, Poline JB, Grasby PJ, Williams SCR,
% Frackowiak RSJ, Turner R. Neuroimage 2:45-53 (1995).
% ---------------------------------------------------------------
vx = sqrt(sum(VG(1).mat(1:3,1:3).^2));
pW = W;
W = (2*dss/ss2).^(-.5).*vx;
W = min(pW,W);
if flags.debug, fprintf('\nSmoothness FWHM: %.3g x %.3g x %.3g mm\n', W*sqrt(8*log(2))); end;
if length(VG)==1, dens=2; else, dens=1; end;
smo = prod(min(dens*flags.sep/sqrt(2*pi)./W,[1 1 1]));
est_smo=0;
n_main_its = n_main_its + 1;
end;
% Update the parameter estimates
% ---------------------------------------------------------------
nu = n*smo;
sig2 = ss/nu;
[d1,d2] = reg(M,12+length(VG),flags.regtype);
soln = (Alpha/sig2+d2)\(Beta/sig2-d1);
scal = scal - soln(13:end);
M = spm_matrix(p0 + soln(1:12)')*M;
if flags.debug,
fprintf('%d\t%g\n', iter, ss/n);
piccies(VF,VG,M,scal,b)
end;
% If cost function stops decreasing, then re-estimate smoothness
% and try again. Repeat a few times.
% ---------------------------------------------------------------
ss = ss/n;
if iter>1, spm_chi2_plot('Set',ss); end;
if (pss-ss)/pss < 1e-6,
est_smo = 1;
end;
if n_main_its>3, break; end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [X1,Y1,Z1] = transform_derivs(Mat,X,Y,Z)
% Given the derivatives of a scalar function, return those of the
% affine transformed function
%_______________________________________________________________________
t1 = Mat(1:3,1:3);
t2 = eye(3);
if sum((t1(:)-t2(:)).^2) < 1e-12,
X1 = X;Y1 = Y; Z1 = Z;
else,
X1 = Mat(1,1)*X + Mat(1,2)*Y + Mat(1,3)*Z;
Y1 = Mat(2,1)*X + Mat(2,2)*Y + Mat(2,3)*Z;
Z1 = Mat(3,1)*X + Mat(3,2)*Y + Mat(3,3)*Z;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [d1,d2] = reg(M,n,typ)
% Analytically compute the first and second derivatives of a penalty
% function w.r.t. changes in parameters.
if nargin<3, typ = 'subj'; end;
if nargin<2, n = 13; end;
[mu,isig] = priors(typ);
ds = 0.000001;
d1 = zeros(n,1);
d2 = zeros(n);
p0 = [0 0 0 0 0 0 1 1 1 0 0 0];
h0 = penalty(p0,M,mu,isig);
for i=7:12, % derivatives are zero w.r.t. rotations and translations
p1 = p0;
p1(i) = p1(i)+ds;
h1 = penalty(p1,M,mu,isig);
d1(i) = (h1-h0)/ds; % First derivative
for j=7:12,
p2 = p0;
p2(j) = p2(j)+ds;
h2 = penalty(p2,M,mu,isig);
p3 = p1;
p3(j) = p3(j)+ds;
h3 = penalty(p3,M,mu,isig);
d2(i,j) = ((h3-h2)/ds-(h1-h0)/ds)/ds; % Second derivative
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function h = penalty(p,M,mu,isig)
% Return a penalty based on the elements of an affine transformation,
% which is given by:
% spm_matrix(p)*M
%
% The penalty is based on the 6 unique elements of the Hencky tensor
% elements being multinormally distributed.
%_______________________________________________________________________
% Unique elements of symmetric 3x3 matrix.
els = [1 2 3 5 6 9];
T = spm_matrix(p)*M;
T = T(1:3,1:3);
T = 0.5*logm(T'*T);
T = T(els)' - mu;
h = T'*isig*T;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [mu,isig] = priors(typ)
% The parameters for this distribution were derived empirically from 227
% scans, that were matched to the ICBM space.
%_______________________________________________________________________
mu = zeros(6,1);
isig = zeros(6);
switch deblank(lower(typ)),
case 'mni', % For registering with MNI templates...
mu = [0.0667 0.0039 0.0008 0.0333 0.0071 0.1071]';
isig = 1e4 * [
0.0902 -0.0345 -0.0106 -0.0025 -0.0005 -0.0163
-0.0345 0.7901 0.3883 0.0041 -0.0103 -0.0116
-0.0106 0.3883 2.2599 0.0113 0.0396 -0.0060
-0.0025 0.0041 0.0113 0.0925 0.0471 -0.0440
-0.0005 -0.0103 0.0396 0.0471 0.2964 -0.0062
-0.0163 -0.0116 -0.0060 -0.0440 -0.0062 0.1144];
case 'rigid', % Constrained to be almost rigid...
mu = zeros(6,1);
isig = eye(6)*1e9;
case 'isochoric', % Volume preserving...
error('Not implemented');
case 'isotropic', % Isotropic zoom in all directions...
error('Not implemented');
case 'subj', % For inter-subject registration...
mu = zeros(6,1);
isig = 1e3 * [
0.8876 0.0784 0.0784 -0.1749 0.0784 -0.1749
0.0784 5.3894 0.2655 0.0784 0.2655 0.0784
0.0784 0.2655 5.3894 0.0784 0.2655 0.0784
-0.1749 0.0784 0.0784 0.8876 0.0784 -0.1749
0.0784 0.2655 0.2655 0.0784 5.3894 0.0784
-0.1749 0.0784 0.0784 -0.1749 0.0784 0.8876];
case 'none', % No regularisation...
mu = zeros(6,1);
isig = zeros(6);
otherwise,
error(['"' typ '" not recognised as type of regularisation.']);
end;
return;
%_______________________________________________________________________
function [y1,y2,y3]=coords(M,x1,x2,x3)
% Affine transformation of a set of coordinates.
%_______________________________________________________________________
y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4);
y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4);
y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function A = make_A(x1,x2,x3,dG1,dG2,dG3,t)
% Generate part of a design matrix using the chain rule...
% df/dm = df/dy * dy/dm
% where
% df/dm is the rate of change of intensity w.r.t. affine parameters
% df/dy is the gradient of the image f
% dy/dm crange of position w.r.t. change of parameters
%_______________________________________________________________________
A = [x1.*dG1 x1.*dG2 x1.*dG3 ...
x2.*dG1 x2.*dG2 x2.*dG3 ...
x3.*dG1 x3.*dG2 x3.*dG3 ...
dG1 dG2 dG3 t];
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [AA,Ab,ss,n] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,lastcols,b,wt)
chunk = 10240;
lm = length(msk);
AA = zeros(12+size(lastcols,2));
Ab = zeros(12+size(lastcols,2),1);
ss = 0;
n = 0;
for i=1:ceil(lm/chunk),
ind = (((i-1)*chunk+1):min(i*chunk,lm))';
msk1 = msk(ind);
A1 = make_A(x1(msk1),x2(msk1),x3(msk1),dG1(msk1),dG2(msk1),dG3(msk1),lastcols(ind,:));
b1 = b(ind);
if ~isempty(wt),
wt1 = wt(ind,ind);
AA = AA + A1'*wt1*A1;
%Ab = Ab + A1'*wt1*b1;
Ab = Ab + (b1'*wt1*A1)';
ss = ss + b1'*wt1*b1;
n = n + trace(wt1);
clear wt1
else,
AA = AA + spm_atranspa(A1);
%Ab = Ab + A1'*b1;
Ab = Ab + (b1'*A1)';
ss = ss + b1'*b1;
n = n + length(msk1);
end;
clear A1 b1 msk1 ind
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function error_message
% Display an error message for when things go wrong.
str = { 'There is not enough overlap in the images',...
'to obtain a solution.',...
' ',...
'Please check that your header information is OK.'};
spm('alert*',str,mfilename,sqrt(-1));
error('insufficient image overlap')
return
%_______________________________________________________________________
%_______________________________________________________________________
function piccies(VF,VG,M,scal,b)
% This is for debugging purposes.
% It shows the linear combination of template images, the affine
% transformed source image, the residual image and a histogram of the
% residuals.
%_______________________________________________________________________
figure(2);
Mt = spm_matrix([0 0 (VG(1).dim(3)+1)/2]);
M = (M*VF(1).mat)\VG(1).mat;
t = zeros(VG(1).dim(1:2));
for i=1:length(VG);
t = t + spm_slice_vol(VG(i), Mt,VG(1).dim(1:2),1)*scal(i);
end;
u = spm_slice_vol(VF(1),M*Mt,VG(1).dim(1:2),1);
subplot(2,2,1);imagesc(t');axis image xy off
subplot(2,2,2);imagesc(u');axis image xy off
subplot(2,2,3);imagesc(u'-t');axis image xy off
subplot(2,2,4);hist(b,50); % Entropy of residuals may be a nice cost function?
drawnow;
return;
%_______________________________________________________________________
|
github
|
lcnhappe/happe-master
|
spm_vol.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm2/spm_vol.m
| 3,510 |
utf_8
|
fe778e6a833de2a9f5466018c571d5a6
|
function V = spm_vol(P)
% Get header information etc for images.
% FORMAT V = spm_vol(P)
% P - a matrix of filenames.
% V - a vector of structures containing image volume information.
% The elements of the structures are:
% V.fname - the filename of the image.
% V.dim - the x, y and z dimensions of the volume, and the
% datatype of the image.
% V.mat - a 4x4 affine transformation matrix mapping from
% voxel coordinates to real world coordinates.
% V.pinfo - plane info for each plane of the volume.
% V.pinfo(1,:) - scale for each plane
% V.pinfo(2,:) - offset for each plane
% The true voxel intensities of the jth image are given
% by: val*V.pinfo(1,j) + V.pinfo(2,j)
% V.pinfo(3,:) - offset into image (in bytes).
% If the size of pinfo is 3x1, then the volume is assumed
% to be contiguous and each plane has the same scalefactor
% and offset.
%____________________________________________________________________________
%
% The fields listed above are essential for the mex routines, but other
% fields can also be incorporated into the structure.
%
% The images are not memory mapped at this step, but are mapped when
% the mex routines using the volume information are called.
%
% This is a replacement for the spm_map_vol and spm_unmap_vol stuff of
% MatLab4 SPMs (SPM94-97), which is now obsolete.
%_______________________________________________________________________
% @(#)spm_vol.m 2.16 John Ashburner 03/05/23
% If is already a vol structure then just return;
if isstruct(P), V = P; return; end;
V = subfunc2(P);
return;
function V = subfunc2(P)
if iscell(P),
V = cell(size(P));
for j=1:prod(size(P)),
if iscell(P{j}),
V{j} = subfunc2(P{j});
else,
V{j} = subfunc1(P{j});
end;
end;
else
V = subfunc1(P);
end;
return;
function V = subfunc1(P)
if size(P,1)==0,
V=[];
else,
V(size(P,1),1) = struct('fname','', 'dim', [0 0 0 0], 'mat',eye(4), 'pinfo', [1 0 0]');
end;
for i=1:size(P,1),
v = subfunc(P(i,:));
if isempty(v),
hread_error_message(P(i,:));
error(['Can''t get volume information for ''' P(i,:) '''']);
end;
f = fieldnames(v);
for j=1:size(f,1),
eval(['V(i).' f{j} ' = v.' f{j} ';']);
%V(i) = setfield(V(i),f{j},getfield(v,f{j}));
end;
end;
return;
function V = subfunc(p)
p = deblank(p);
[pth,nam,ext] = fileparts(deblank(p));
t = find(ext==',');
n = [];
if ~isempty(t),
if length(t)==1,
n1 = ext((t+1):end);
if ~isempty(n1),
n = str2num(n1);
ext = ext(1:(t-1));
end;
end;
end;
p = fullfile(pth,[nam ext]);
if strcmp(ext,'.img') & exist(fullfile(pth,[nam '.hdr'])) == 2,
if isempty(n), V = spm_vol_ana(p);
else, V = spm_vol_ana(p,n); end;
if ~isempty(V), return; end;
else, % Try other formats
% Try MINC format
if isempty(n), V=spm_vol_minc(p);
else, V=spm_vol_minc(p,n); end;
if ~isempty(V), return; end;
% Try Ecat 7
if isempty(n), V=spm_vol_ecat7(p);
else, V=spm_vol_ecat7(p,n); end;
if ~isempty(V), return; end;
end;
return;
%_______________________________________________________________________
function hread_error_message(q)
str = {...
'Error reading information on:',...
[' ',spm_str_manip(q,'k40d')],...
' ',...
'Please check that it is in the correct format.'};
spm('alert*',str,mfilename,sqrt(-1));
return;
%_______________________________________________________________________
|
github
|
lcnhappe/happe-master
|
spm_read_netcdf.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm2/spm_read_netcdf.m
| 3,640 |
utf_8
|
9339212a576f5d67662107cebb087054
|
function cdf = spm_read_netcdf(fname)
% Read the header information from a NetCDF file into a data structure.
% FORMAT cdf = spm_read_netcdf(fname)
% fname - name of NetCDF file
% cdf - data structure
%
% See: http://www.unidata.ucar.edu/packages/netcdf/
% _______________________________________________________________________
% @(#)spm_read_netcdf.m 2.1 John Ashburner 02/07/30
dsiz = [1 1 2 4 4 8];
fp=fopen(fname,'r','ieee-be');
if fp==-1,
cdf = [];
return;
end;
% Return null if not a CDF file.
%-----------------------------------------------------------------------
mgc = fread(fp,4,'uchar')';
if ~all(['CDF' 1] == mgc),
cdf = [];
fclose(fp);
return;
end
% I've no idea what this is for
numrecs = fread(fp,1,'uint32');
cdf = struct('numrecs',numrecs,'dim_array',[], 'gatt_array',[], 'var_array', []);
dt = fread(fp,1,'uint32');
if dt == 10,
% Dimensions
nelem = fread(fp,1,'uint32');
for j=1:nelem,
str = readname(fp);
dim_length = fread(fp,1,'uint32');
cdf.dim_array(j).name = str;
cdf.dim_array(j).dim_length = dim_length;
end;
dt = fread(fp,1,'uint32');
end
while ~dt, dt = fread(fp,1,'uint32'); end;
if dt == 12,
% Attributes
nelem = fread(fp,1,'uint32');
for j=1:nelem,
str = readname(fp);
nc_type= fread(fp,1,'uint32');
nnelem = fread(fp,1,'uint32');
val = fread(fp,nnelem,dtypestr(nc_type));
if nc_type == 2, val = deblank([val' ' ']); end
padding= fread(fp,ceil(nnelem*dsiz(nc_type)/4)*4-nnelem*dsiz(nc_type),'uchar');
cdf.gatt_array(j).name = str;
cdf.gatt_array(j).nc_type = nc_type;
cdf.gatt_array(j).val = val;
end;
dt = fread(fp,1,'uint32');
end
while ~dt, dt = fread(fp,1,'uint32'); end;
if dt == 11,
% Variables
nelem = fread(fp,1,'uint32');
for j=1:nelem,
str = readname(fp);
nnelem = fread(fp,1,'uint32');
val = fread(fp,nnelem,'uint32');
cdf.var_array(j).name = str;
cdf.var_array(j).dimid = val+1;
cdf.var_array(j).nc_type = 0;
cdf.var_array(j).vsize = 0;
cdf.var_array(j).begin = 0;
dt0 = fread(fp,1,'uint32');
if dt0 == 12,
nelem0 = fread(fp,1,'uint32');
for jj=1:nelem0,
str = readname(fp);
nc_type= fread(fp,1,'uint32');
nnelem = fread(fp,1,'uint32');
val = fread(fp,nnelem,dtypestr(nc_type));
if nc_type == 2, val = deblank([val' ' ']); end
padding= fread(fp,...
ceil(nnelem*dsiz(nc_type)/4)*4-nnelem*dsiz(nc_type),'uchar');
cdf.var_array(j).vatt_array(jj).name = str;
cdf.var_array(j).vatt_array(jj).nc_type = nc_type;
cdf.var_array(j).vatt_array(jj).val = val;
end;
dt0 = fread(fp,1,'uint32');
end;
cdf.var_array(j).nc_type = dt0;
cdf.var_array(j).vsize = fread(fp,1,'uint32');
cdf.var_array(j).begin = fread(fp,1,'uint32');
end;
dt = fread(fp,1,'uint32');
end;
fclose(fp);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function str = dtypestr(i)
% Returns a string appropriate for reading or writing the CDF data-type.
types = str2mat('uint8','uint8','int16','int32','float','double');
str = deblank(types(i,:));
return;
%_______________________________________________________________________
%_______________________________________________________________________
function name = readname(fp)
% Extracts a name from a CDF file pointed to at the right location by
% fp.
stlen = fread(fp,1,'uint32');
name = deblank([fread(fp,stlen,'uchar')' ' ']);
padding= fread(fp,ceil(stlen/4)*4-stlen,'uchar');
return;
%_______________________________________________________________________
|
github
|
lcnhappe/happe-master
|
spm_figure.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm2/spm_figure.m
| 30,750 |
utf_8
|
93a783638e6b9249e4ea8bb6377a5308
|
function varargout=spm_figure(varargin)
% Setup and callback functions for Graphics window
% FORMAT varargout=spm_figure(varargin)
% - An embedded callback, multi-function function
% - For detailed programmers comments, see format specifications
% in main body of code
%_______________________________________________________________________
%
% spm_figure creates and manages the 'Graphics' window. This window and
% these facilities may be used independently of SPM, and any number of
% Graphics windows my be used within the same MatLab session. (Though
% only one SPM 'Graphics' 'Tag'ed window is permitted.
%
% The Graphics window is provided with a menu bar at the top that
% facilitates editing and printing of the current graphic display,
% enabling interactive editing of graphic output prior to printing
% (e.g. selection of color maps, deleting, moving and editing graphics
% objects or adding text). (This menu is also provided as a figure
% background "ContextMenu" - right-clicking on the figure background
% should bring up the menu.)
%
% Print: Creates a footnote (detailing the SPM version, user & date)
% and evaluates defaults.printstr (see spm_defaults.m). Graphics windows with
% multi-page axes are printed page by page.
%
% Clear: Clears the Graphics window. If in SPM usage (figure 'Tag'ed as
% 'Graphics') then all SPM windows are cleared and reset.
%
% Colormap options:
% * gray, hot, pink: Sets the colormap to its default values and loads
% either a grayscale, 'hot metal' or color map.
% * gray-hot, etc: Creates a 'split' colormap {128 x 3 matrix}.
% The lower half is a gray scale and the upper half
% is 'hot metal' or 'pink'. This color map is used for
% viewing 'rendered' SPMs on a PET, MRI or other background images
%
% Colormap effects:
% * Invert: Inverts (flips) the current color map.
% * Brighten and Darken: Brighten and Darken the current colourmap
% using the MatLab BRIGHTEN command, with beta's of +0.2 and -0.2
% respectively.
%
% Editing: Right button ('alt' button) cancels operations
% * Cut : Deletes the graphics object next selected (if deletable)
% Select with middle mouse button to delete blocks of text,
% or to delete individual elements from a plot.
% * Move : To re-position a text, uicontrol or axis object using a
% 'drag and drop' implementation (i.e. depress - move - release)
% Using the middle 'extend' mouse button on a text object moves
% the axes containing the text - i.e. blocks of text.
% * Size : Re-sizes the text, uicontrol or axis object next selected
% {left button - decrease, middle button - increase} by a factor
% of 1.24 (or increase/decrease FontSize by 2 dpi)
% * Text : Creates an editable text widget that produces a text object as
% its CallBack.
% The text object is provided with a ContextMenu, obtained by
% right-clicking ('alt') on the text, allowing text attributes
% to be changed. Alternatively, the edit facilities on the window
% menu bar or ContextMenu can be used.
% * Edit : To edit text, select a text object with the circle cursor,
% and edit the text in the editable text widget that appears.
% A middle 'extend' mouse click places a context menu on the text
% object, facilitating easy modification of text atributes.
%
% For SPM usage, the figure should be 'Tag'ed as 'Graphics'.
%
% For SPM power users, and programmers, spm_figure provides utility
% routines for using the SPM graphics interface. Of particular use are
% the GetWin, FindWin and Clear functions See the embedded callback
% reference in the main body of spm_figure, below the help text.
%
% See also: spm_print, spm_clf
%
%_______________________________________________________________________
% @(#)spm_figure.m 2.39 Andrew Holmes 03/05/16
%=======================================================================
% - FORMAT specifications for embedded CallBack functions
%=======================================================================
%( This is a multi function function, the first argument is an action )
%( string, specifying the particular action function to take. Recall )
%( MatLab's command-function duality: `spm_figure Create` is )
%( equivalent to `spm_figure('Create')`. )
%
% FORMAT F = spm_figure
% [ShortCut] Defaults to Action 'Create'
%
% FORMAT F = spm_figure(F) - numeric F
% [ShortCut] Defaults to spm_figure('CreateBar',F)
%
% FORMAT F = spm_figure('Create',Tag,Name,Visible)
% Create a full length WhiteBg figure 'Tag'ed Tag (if specified),
% with a ToolBar and background context menu.
% Equivalent to spm_figure('CreateWin','Tag') and spm_figure('CreateBar')
% Tag - 'Tag' string for figure.
% Name - Name for window
% Visible - 'on' or 'off'
% F - Figure used
%
% FORMAT F = spm_figure('FindWin',F)
% Finds window with 'Tag' or figure numnber F - returns empty F if not found
% F - (Input) Figure to use [Optional] - 'Tag' string or figure number.
% - Defaults to 'Graphics'
% F - (Output) Figure number (if found) or empty (if not).
%
% FORMAT F = spm_figure('GetWin',Tag)
% Like spm_figure('FindWin',Tag), except that if 'Tag' is 'Graphics' or
% 'Interactive' and no such 'Tag'ged figure is found, one is created. Further,
% the "got" window is made current.
% Tag - Figure 'Tag' to get, defaults to 'Graphics'
% F - Figure number (if found/created) or empty (if not).
%
% FORMAT F = spm_figure('ParentFig',h)
% Finds window containing the object whose handle is specified
% h - Handle of object whose parent figure is required
% - If a vector, then first object handle is used
% F - Number or parent figure
%
% FORMAT spm_figure('Clear',F,Tags)
% Clears figure, leaving ToolBar (& other objects with invisible handles)
% Optional third argument specifies 'Tag's of objects to delete.
% If figure F is 'Tag'ged 'Interactive' (SPM usage), then the window
% name and pointer are reset.
% F - 'Tag' string or figure number of figure to clear, defaults to gcf
% Tags - 'Tag's (string matrix or cell array of strings) of objects to delete
% *regardless* of 'HandleVisibility'. Only these objects are deleted.
% '!all' denotes all objects
%
% FORMAT str = spm_figure('DefPrintCmd')
% Returns default print command for SPM, as a string
%
% FORMAT spm_figure('Print',F)
% SPM print function: Appends footnote & executes PRINTSTR
% F - [Optional] Figure to print. ('Tag' or figure number)
% Defaults to figure 'Tag'ed as 'Graphics'.
% If none found, uses CurrentFigure if avaliable.
% defaults.printstr - global variable holding print command to be evaluated
% Defaults to 'print -dps2 fig.ps'
% If objects 'Tag'ed 'NextPage' and 'PrevPage' are found, then the
% pages are shown and printed in order. In breif, pages are held as
% seperate axes, with ony one 'Visible' at any one time. The handles of
% the "page" axes are stored in the 'UserData' of the 'NextPage'
% object, while the 'PrevPage' object holds the current page number.
% See spm_help('!Disp') for details on setting up paging axes.
%
% FORMAT [hNextPage, hPrevPage, hPageNo] = spm_figure('NewPage',hPage)
% SPM pagination function: Makes objects with handles hPage paginated
% Creates pagination buttons if necessary.
% hPage - Handles of objects to stick to this page
% hNextPage, hPrevPage, hPageNo - Handles of pagination controls
%
% FORMAT spm_figure('TurnPage',move,F)
% SPM pagination function: Turn to specified page
%
% FORMAT spm_figure('DeletePageControls',F)
% SPM pagination function: Deletes page controls
% F - [Optional] Figure in which to attempt to turn the page
% Defaults to 'Graphics' 'Tag'ged window
%
% FORMAT n = spm_figure('#page')
% Returns the current page number.
%
% FORMAT spm_figure('WaterMark',F,str,Tag,Angle,Perm)
% Adds watermark to figure windows.
% F - Figure for watermark. Defaults to gcf
% str - Watermark string. Defaults (missing or empty) to SPM
% Tag - Tag for watermark axes. Defaults to ''
% Angle - Angle for watermark. Defaults to -45
% Perm - If specified, then watermark is permanent (HandleVisibility 'off')
%
% FORMAT F = spm_figure('CreateWin',Tag,Name,Visible)
% Creates a full length WhiteBg figure 'Tag'ged Tag (if specified).
% F - Figure created
% Tag - Tag for window
% Name - Name for window
% Visible - 'on' or 'off'
%
% FORMAT WS = spm_figure('GetWinScale')
% Returns ratios of current display dimensions to that of a 1152 x 900
% Sun display. WS=[Xratio,Yratio,Xratio,Yratio]. Used for scaling other
% GUI elements.
% (Function duplicated in spm.m, repeated to reduce inter-dependencies.)
%
% FORMAT FS = spm_figure('FontSizes',FS)
% Returns fontsizes FS scaled for the current display.
% FS - (vector of) Font sizes to scale
% [default [08,09,11,13,14,6:36]]
%
% FORMAT spm_figure('CreateBar',F)
% Creates toolbar in figure F (defaults to gcf). F can be a 'Tag'
% If the figure is 'Tag'ed as 'Graphics' (SPM usage), then the Print button
% callback is set to attempt to clear an 'Interactive' figure too.
%
% FORMAT spm_figure('ColorMap')
% Callback for "ColorMap" buttons
%
% FORMAT h = spm_figure('GraphicsHandle',F)
% GUI choose object for handle identification. LeftMouse 'normal' returns
% handle, MiddleMouse 'extend' returns parents handle, RightMouse 'alt' cancels.
% F - figure to do a GUI "handle ID" in [Default gcbf]
%_______________________________________________________________________
%-Condition arguments
%-----------------------------------------------------------------------
if (nargin==0), Action = 'Create'; else, Action = varargin{1}; end
switch lower(Action), case 'create'
%=======================================================================
% F = spm_figure('Create',Tag,Name,Visible)
%-Condition arguments
if nargin<4, Visible='on'; else, Visible=varargin{4}; end
if nargin<3, Name=''; else, Name=varargin{3}; end
if nargin<2, Tag=''; else, Tag=varargin{2}; end
F = spm_figure('CreateWin',Tag,Name,Visible);
spm_figure('CreateBar',F);
spm_figure('FigContextMenu',F);
varargout = {F};
case 'findwin'
%=======================================================================
% F=spm_figure('FindWin',F)
% F=spm_figure('FindWin',Tag)
%-Find window: Find window with FigureNumber# / 'Tag' attribute
%-Returns empty if window cannot be found - deletes multiple tagged figs.
if nargin<2, F='Graphics'; else, F=varargin{2}; end
if isempty(F)
% Leave F empty
elseif ischar(F)
% Finds Graphics window with 'Tag' string - delete multiples
Tag=F;
F = findobj(get(0,'Children'),'Flat','Tag',Tag);
if length(F) > 1
% Multiple Graphics windows - close all but most recent
close(F(2:end))
F = F(1);
end
else
% F is supposed to be a figure number - check it
if ~any(F==get(0,'Children')), F=[]; end
end
varargout = {F};
case 'getwin'
%=======================================================================
% F=spm_figure('GetWin',Tag)
if nargin<2, Tag='Graphics'; else, Tag=varargin{2}; end
F = spm_figure('FindWin',Tag);
if isempty(F)
if ischar(Tag)
switch Tag, case 'Graphics'
F = spm_figure('Create','Graphics','Graphics');
case 'Interactive'
F = spm('CreateIntWin');
end
end
else
set(0,'CurrentFigure',F);
end
varargout = {F};
case 'parentfig'
%=======================================================================
% F=spm_figure('ParentFig',h)
if nargin<2, error('No object specified'), else, h=varargin{2}; end
F = get(h(1),'Parent');
while ~strcmp(get(F,'Type'),'figure'), F=get(F,'Parent'); end
varargout = {F};
case 'clear'
%=======================================================================
% spm_figure('Clear',F,Tags)
%-Sort out arguments
%-----------------------------------------------------------------------
if nargin<3, Tags=[]; else, Tags=varargin{3}; end
if nargin<2, F=get(0,'CurrentFigure'); else, F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end
%-Clear figure
%-----------------------------------------------------------------------
if isempty(Tags)
%-Clear figure of objects with 'HandleVisibility' 'on'
pos = get(F,'Position');
delete(findobj(get(F,'Children'),'flat','HandleVisibility','on'));
drawnow
set(F,'Position',pos);
%-Reset figures callback functions
set(F,'KeyPressFcn','',...
'WindowButtonDownFcn','',...
'WindowButtonMotionFcn','',...
'WindowButtonUpFcn','')
%-If this is the 'Interactive' window, reset name & UserData
if strcmp(get(F,'Tag'),'Interactive')
set(F,'Name','','UserData',[]), end
else
%-Clear specified objects from figure
cSHH = get(0,'ShowHiddenHandles');
set(0,'ShowHiddenHandles','on')
if ischar(Tags); Tags=cellstr(Tags); end
if any(strcmp(Tags(:),'!all'))
delete(get(F,'Children'))
else
for tag = Tags(:)'
delete(findobj(get(F,'Children'),'flat','Tag',tag{:}));
end
end
set(0,'ShowHiddenHandles',cSHH)
end
set(F,'Pointer','Arrow')
case 'defprintcmd'
%=======================================================================
% spm_figure('DefPrintCmd')
varargout = {'print -dpsc2 -painters -append -noui '};
case 'print'
%=======================================================================
% spm_figure('Print',F)
%-Arguments & defaults
if nargin<2, F='Graphics'; else, F=varargin{2}; end
%-Find window to print, default to gcf if specified figure not found
% Return if no figures
F=spm_figure('FindWin',F);
if isempty(F), F = get(0,'CurrentFigure'); end
if isempty(F), return, end
%-Note current figure, & switch to figure to print
cF = get(0,'CurrentFigure');
set(0,'CurrentFigure',F)
%-See if window has paging controls
hNextPage = findobj(F,'Tag','NextPage');
hPrevPage = findobj(F,'Tag','PrevPage');
hPageNo = findobj(F,'Tag','PageNo');
iPaged = ~isempty(hNextPage);
%-Construct print command
%-----------------------------------------------------------------------
global defaults
if ~isempty(defaults),
PRINTSTR = defaults.printstr;
else,
PRINTSTR = [spm_figure('DefPrintCmd'),'spm2.ps'];
end
%-Create footnote with SPM version, username, date and time.
%-----------------------------------------------------------------------
FNote = sprintf('%s%s: %s',spm('ver'),spm('GetUser',' (%s)'),spm('time'));
%-Delete old tag lines, and print new one
delete(findobj(F,'Tag','SPMprintFootnote'));
axes('Position',[0.005,0.005,0.1,0.1],...
'Visible','off',...
'Tag','SPMprintFootnote')
text(0,0,FNote,'FontSize',6);
%-Temporarily change all units to normalized prior to printing
% (Fixes bizzarre problem with stuff jumping around!)
%-----------------------------------------------------------------------
H = findobj(get(F,'Children'),'flat','Type','axes');
un = cellstr(get(H,'Units'));
set(H,'Units','normalized')
%-Print
%-----------------------------------------------------------------------
err = 0;
if ~iPaged
printstr = clean_PRINTSTR(PRINTSTR);
try, eval(printstr), catch, err=1; end
else
hPg = get(hNextPage,'UserData');
Cpage = get(hPageNo, 'UserData');
nPages = size(hPg,1);
set([hNextPage,hPrevPage,hPageNo],'Visible','off')
if Cpage~=1
set(hPg{Cpage,1},'Visible','off'), end
for p = 1:nPages
set(hPg{p,1},'Visible','on');
printstr = clean_PRINTSTR(PRINTSTR);
try, eval(printstr), catch, err=1; end
set(hPg{p,1},'Visible','off')
end
set(hPg{Cpage,1},'Visible','on')
set([hNextPage,hPrevPage,hPageNo],'Visible','on')
end
if err
errstr = lasterr;
tmp = [find(abs(errstr)==10),length(errstr)+1];
str = {errstr(1:tmp(1)-1)};
for i = 1:length(tmp)-1
if tmp(i)+1 < tmp(i+1)
str = [str, {errstr(tmp(i)+1:tmp(i+1)-1)}];
end
end
str = {str{:}, '','- print command is:',[' ',printstr],...
'','- current directory is:',[' ',pwd],...
'',' * nothing has been printed *'};
spm('alert!',str,'printing problem...',sqrt(-1));
end
set(H,{'Units'},un)
set(0,'CurrentFigure',cF)
case 'newpage'
%=======================================================================
% [hNextPage, hPrevPage, hPageNo] = spm_figure('NewPage',h)
if nargin<2 | isempty(varargin{2}), error('No handles to paginate')
else, h=varargin{2}(:)'; end
%-Work out which figure we're in
F = spm_figure('ParentFig',h(1));
hNextPage = findobj(F,'Tag','NextPage');
hPrevPage = findobj(F,'Tag','PrevPage');
hPageNo = findobj(F,'Tag','PageNo');
%-Create pagination widgets if required
%-----------------------------------------------------------------------
if isempty(hNextPage)
WS = spm('WinScale');
FS = spm('FontSizes');
SatFig = findobj('Tag','Satellite');
if ~isempty(SatFig)
SatFigPos = get(SatFig,'Position');
hNextPagePos = [SatFigPos(3)-25 15 15 15];
hPrevPagePos = [SatFigPos(3)-40 15 15 15];
hPageNo = [SatFigPos(3)-40 5 30 10];
else
hNextPagePos = [580 022 015 015].*WS;
hPrevPagePos = [565 022 015 015].*WS;
hPageNo = [550 005 060 015].*WS;
end
hNextPage = uicontrol(F,'Style','Pushbutton',...
'HandleVisibility','on',...
'String','>','FontSize',FS(10),...
'ToolTipString','next page',...
'Callback','spm_figure(''TurnPage'',''+1'',gcbf)',...
'Position',hNextPagePos,...
'ForegroundColor',[0 0 0],...
'Tag','NextPage','UserData',[]);
hPrevPage = uicontrol(F,'Style','Pushbutton',...
'HandleVisibility','on',...
'String','<','FontSize',FS(10),...
'ToolTipString','previous page',...
'Callback','spm_figure(''TurnPage'',''-1'',gcbf)',...
'Position',hPrevPagePos,...
'Visible','on',...
'Enable','off',...
'Tag','PrevPage');
hPageNo = uicontrol(F,'Style','Text',...
'HandleVisibility','on',...
'String','1',...
'FontSize',FS(6),...
'HorizontalAlignment','center',...
'BackgroundColor','w',...
'Position',hPageNo,...
'Visible','on',...
'UserData',1,...
'Tag','PageNo','UserData',1);
end
%-Add handles for this page to UserData of hNextPage
%-Make handles for this page invisible if PageNo>1
%-----------------------------------------------------------------------
mVis = strcmp('on',get(h,'Visible'));
hPg = get(hNextPage,'UserData');
if isempty(hPg)
hPg = {h(mVis), h(~mVis)};
else
hPg = [hPg; {h(mVis), h(~mVis)}];
set(h(mVis),'Visible','off')
end
set(hNextPage,'UserData',hPg)
%-Return handles to pagination controls if requested
if nargout>0, varargout = {[hNextPage, hPrevPage, hPageNo]}; end
case 'turnpage'
%=======================================================================
% spm_figure('TurnPage',move,F)
if nargin<3, F='Graphics'; else, F=varargin{3}; end
if nargin<2, move=1; else, move=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end
hNextPage = findobj(F,'Tag','NextPage');
hPrevPage = findobj(F,'Tag','PrevPage');
hPageNo = findobj(F,'Tag','PageNo');
if isempty(hNextPage), return, end
hPg = get(hNextPage,'UserData');
Cpage = get(hPageNo, 'UserData');
nPages = size(hPg,1);
%-Sort out new page number
if ischar(move), Npage = Cpage+eval(move); else, Npage = move; end
Npage = max(min(Npage,nPages),1);
%-Make current page invisible, new page visible, set page number string
set(hPg{Cpage,1},'Visible','off')
set(hPg{Npage,1},'Visible','on')
set(hPageNo,'UserData',Npage,'String',sprintf('%d / %d',Npage,nPages))
%-Disable appropriate page turning control if on first/last page (for neatness)
if Npage==1, set(hPrevPage,'Enable','off')
else, set(hPrevPage,'Enable','on'), end
if Npage==nPages, set(hNextPage,'Enable','off')
else, set(hNextPage,'Enable','on'), end
case 'deletepagecontrols'
%=======================================================================
% spm_figure('DeletePageControls',F)
if nargin<2, F='Graphics'; else, F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end
hNextPage = findobj(F,'Tag','NextPage');
hPrevPage = findobj(F,'Tag','PrevPage');
hPageNo = findobj(F,'Tag','PageNo');
delete([hNextPage hPrevPage hPageNo])
case '#page'
%=======================================================================
% n = spm_figure('#Page',F)
if nargin<2, F='Graphics'; else, F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end
hNextPage = findobj(F,'Tag','NextPage');
if isempty(hNextPage)
n = 1;
else
n = size(get(hNextPage,'UserData'),1)+1;
end
varargout = {n};
case 'watermark'
%=======================================================================
% spm_figure('WaterMark',F,str,Tag,Angle,Perm)
if nargin<6, HVis='on'; else, HVis='off'; end
if nargin<5, Angle=-45; else, Angle=varargin{5}; end
if nargin<4 | isempty(varargin{4}), Tag = 'WaterMark'; else, Tag=varargin{4}; end
if nargin<3 | isempty(varargin{3}), str = 'SPM'; else, str=varargin{3}; end
if nargin<2, if any(get(0,'Children')), F=gcf; else, F=''; end
else, F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end
%-Specify watermark color from background colour
%-----------------------------------------------------------------------
Colour = get(F,'Color');
%-Only mess with grayscale backgrounds
if ~all(Colour==Colour(1)), return, end
%-Work out colour - lighter unless grey value > 0.9
Colour = Colour+(2*(Colour(1)<0.9)-1)*0.02;
cF = get(0,'CurrentFigure');
set(0,'CurrentFigure',F)
Units=get(F,'Units');
set(F,'Units','normalized');
h = axes('Position',[0.45,0.5,0.1,0.1],...
'Units','normalized',...
'Visible','off',...
'Tag',Tag);
set(F,'Units',Units)
text(0.5,0.5,str,...
'FontSize',spm('FontSize',80),...
'FontWeight','Bold',...
'FontName',spm_platform('Font','times'),...
'Rotation',Angle,...
'HorizontalAlignment','Center',...
'VerticalAlignment','middle',...
'EraseMode','normal',...
'Color',Colour,...
'ButtonDownFcn',[...
'if strcmp(get(gcbf,''SelectionType''),''open''),',...
'delete(get(gcbo,''Parent'')),',...
'end'])
set(h,'HandleVisibility',HVis)
set(0,'CurrentFigure',cF)
case 'createwin'
%=======================================================================
% F=spm_figure('CreateWin',Tag,Name,Visible)
%-Condition arguments
%-----------------------------------------------------------------------
if nargin<4 | isempty(varargin{4}), Visible='on'; else, Visible=varargin{4}; end
if nargin<3, Name=''; else, Name = varargin{3}; end
if nargin<2, Tag=''; else, Tag = varargin{2}; end
WS = spm('WinScale'); %-Window scaling factors
FS = spm('FontSizes'); %-Scaled font sizes
PF = spm_platform('fonts'); %-Font names (for this platform)
Rect = spm('WinSize','Graphics','raw').*WS; %-Graphics window rectangle
F = figure(...
'Tag',Tag,...
'Position',Rect,...
'Resize','off',...
'Color','w',...
'ColorMap',gray(64),...
'DefaultTextColor','k',...
'DefaultTextInterpreter','none',...
'DefaultTextFontName',PF.helvetica,...
'DefaultTextFontSize',FS(10),...
'DefaultAxesColor','w',...
'DefaultAxesXColor','k',...
'DefaultAxesYColor','k',...
'DefaultAxesZColor','k',...
'DefaultAxesFontName',PF.helvetica,...
'DefaultPatchFaceColor','k',...
'DefaultPatchEdgeColor','k',...
'DefaultSurfaceEdgeColor','k',...
'DefaultLineColor','k',...
'DefaultUicontrolFontName',PF.helvetica,...
'DefaultUicontrolFontSize',FS(10),...
'DefaultUicontrolInterruptible','on',...
'PaperType','A4',...
'PaperUnits','normalized',...
'PaperPosition',[.0726 .0644 .854 .870],...
'InvertHardcopy','off',...
'Renderer','zbuffer',...
'Visible','off');
if ~isempty(Name)
set(F,'Name',sprintf('%s%s: %s',spm('ver'),...
spm('GetUser',' (%s)'),Name),'NumberTitle','off')
end
set(F,'Visible',Visible)
varargout = {F};
case 'getwinscale'
%=======================================================================
% WS = spm_figure('GetWinScale')
warning('spm_figure(''GetWinScale''... is Grandfathered: use spm(''WinScale''')
varargout = {spm('WinScale')};
case 'fontsizes'
%=======================================================================
% FS = spm_figure('FontSizes',FS)
warning('spm_figure(''FontSizes''... is Grandfathered: use spm(''FontSizes''')
if nargin<2, FS=[08,09,11,13,14,6:36]; else, FS=varargin{2}; end
varargout = {round(FS*min(spm('WinScale')))};
%=======================================================================
case 'createbar'
%=======================================================================
% spm_figure('CreateBar',F)
if nargin<2, if any(get(0,'Children')), F=gcf; else, F=''; end
else, F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end
cSHH = get(0,'ShowHiddenHandles');
set(0,'ShowHiddenHandles','on')
t0 = findobj(get(F,'Children'),'Flat','Label','&Help');
if isempty(t0), t0 = uimenu( F,'Label','&Help'); end;
set(findobj(t0,'Position',1),'Separator','on');
t1 = uimenu(t0,'Position',1,...
'Label','SPM web',...
'CallBack','web(''http://www.fil.ion.ucl.ac.uk/spm'');');
t1 = uimenu(t0,'Position',1,...
'Label','SPM help','ForegroundColor',[0 1 0],...
'CallBack','spm_help');
t0=uimenu( F,'Label','Colours','HandleVisibility','off');
t1=uimenu(t0,'Label','ColorMap');
t2=uimenu(t1,'Label','Gray','CallBack','spm_figure(''ColorMap'',''gray'')');
t2=uimenu(t1,'Label','Hot','CallBack','spm_figure(''ColorMap'',''hot'')');
t2=uimenu(t1,'Label','Pink','CallBack','spm_figure(''ColorMap'',''pink'')');
t2=uimenu(t1,'Label','Gray-Hot','CallBack','spm_figure(''ColorMap'',''gray-hot'')');
t2=uimenu(t1,'Label','Gray-Pink','CallBack','spm_figure(''ColorMap'',''gray-pink'')');
t1=uimenu(t0,'Label','Effects');
t2=uimenu(t1,'Label','Invert','CallBack','spm_figure(''ColorMap'',''invert'')');
t2=uimenu(t1,'Label','Brighten','CallBack','spm_figure(''ColorMap'',''brighten'')');
t2=uimenu(t1,'Label','Darken','CallBack','spm_figure(''ColorMap'',''darken'')');
t0=uimenu( F,'Label','Clear','HandleVisibility','off','CallBack','spm_figure(''Clear'',gcbf)');
t0=uimenu( F,'Label','SPM-Print','HandleVisibility','off','CallBack','spm_figure(''Print'',gcbf)');
% ### CODE FOR SATELLITE FIGURE ###
% Code checks if there is a satellite window and if results are currently displayed
% It assumes that if hReg is invalid then there are no results currently displayed
% Modified by DRG to display a satellite figure 02/14/01.
cb = ['global SatWindow,',...
'try,',...
'tmp = get(hReg);,',...
'ResFlag = 1;',...
'catch,',...
'ResFlag = 0;',...
'end,',...
'if SatWindow,',...
'figure(SatWindow),',...
'else,',...
'if ResFlag,',...
'spm_setup_satfig,',...
'end,',...
'end'];
t0=uimenu( F,'Label','Results-Fig','HandleVisibility','off','Callback',cb);
% ### END NEW CODE ###
set(0,'ShowHiddenHandles',cSHH)
%=======================================================================
case 'figcontextmenu'
%=======================================================================
% h = spm_figure('FigContextMenu',F)
if nargin<2
F = get(0,'CurrentFigure');
if isempty(F), error('no figure'), end
else
F = spm_figure('FindWin',varargin{2});
if isempty(F), error('no such figure'), end
end
h = uicontextmenu('Parent',F,'HandleVisibility','CallBack');
cSHH = get(0,'ShowHiddenHandles');
set(0,'ShowHiddenHandles','on')
copy_menu(F,h);
set(0,'ShowHiddenHandles',cSHH)
set(F,'UIContextMenu',h)
varargout = {h};
case 'colormap'
%=======================================================================
% spm_figure('ColorMap',ColAction,h)
if nargin<3, h=[]; else, h=varargin{3}; end
if nargin<2, ColAction='gray'; else, ColAction=varargin{2}; end
switch lower(ColAction), case 'gray'
colormap(gray(64))
case 'hot'
colormap(hot(64))
case 'pink'
colormap(pink(64))
case 'gray-hot'
tmp = hot(64 + 16); tmp = tmp([1:64] + 16,:);
colormap([gray(64); tmp])
case 'gray-pink'
tmp = pink(64 + 16); tmp = tmp([1:64] + 16,:);
colormap([gray(64); tmp])
case 'invert'
colormap(flipud(colormap))
case 'brighten'
colormap(brighten(colormap, 0.2))
case 'darken'
colormap(brighten(colormap, -0.2))
otherwise
error('Illegal ColAction specification')
end
case 'graphicshandle'
%=======================================================================
% h = spm_figure('GraphicsHandle',F)
if nargin<2, F=gcbf; else, F=spm_figure('FindWin',varargin{2}); end
if isempty(F), return, end
tmp = get(F,'Name');
set(F,'Name',...
'Handle: Select item to identify, MiddleMouse=parent, RightMouse=cancel...');
set(F,'Pointer','CrossHair')
waitforbuttonpress;
h = gco(F);
hType = get(h,'Type');
SelnType = get(gcf,'SelectionType');
set(F,'Pointer','Arrow','Name',tmp)
if ~strcmp(SelnType,'alt') & ~isempty(h) & gcf==F
str = sprintf('Selected (%s) object',get(h,'Type'));
if strcmp(SelnType,'normal')
str = sprintf('%s: handle',str);
else
h = get(h,'Parent');
str = sprintf('%s: handle of parent (%s) object',str,get(h,'Type'));
end
if nargout==0
assignin('base','ans',h)
fprintf('\n%s: \n',str)
ans = h
else
varargout={h};
end
else
varargout={[]};
end
otherwise
%=======================================================================
warning(['Illegal Action string: ',Action])
end
return;
%=======================================================================
%=======================================================================
function copy_menu(F,G)
%=======================================================================
handles = findobj(get(F,'Children'),'Flat','Type','uimenu','Visible','on');
if length(handles)==0, return; end;
for F1=handles',
if ~strcmp(get(F1,'Label'),'&Window'),
G1 = uimenu(G,'Label',get(F1,'Label'),...
'CallBack',get(F1,'CallBack'),...
'Position',get(F1,'Position'),...
'Separator',get(F1,'Separator'));
copy_menu(F1,G1);
end;
end;
return;
%=======================================================================
%=======================================================================
function PRINTSTR = clean_PRINTSTR(PRINTSTR)
%=======================================================================
% Matlab 6.5 printing doesn't like the -append option if the file does
% not already exist
%-----------------------------------------------------------------------
off = findstr('-append',PRINTSTR);
if ~isempty(off),
bl = [0 find(isspace(PRINTSTR)) (length(PRINTSTR)+1)];
for i=1:(length(bl)-1),
ca{i} = PRINTSTR((bl(i)+1):(bl(i+1)-1));
end;
ca = strvcat(ca);
off1 = find(ca(:,1)~='-'); % either 'print' or a filename
if length(off1)>1,
fname = deblank(ca(off1(end),:));
% If there is no path to the file, then make it the
% current directory
[pth,nam,ext] = fileparts(fname);
if isempty(pth), fname = ['.' filesep nam ext]; end;
fd = fopen(fname,'r');
if fd~=-1,
% File exists, so -append can be used
fclose(fd);
else,
% File does not exist, so remove -append option
PRINTSTR(off:(off+7))='';
end;
end;
end;
|
github
|
lcnhappe/happe-master
|
spm_smoothto8bit.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm2/spm_smoothto8bit.m
| 2,262 |
utf_8
|
b2475a56514dcda30f94612977b6f68a
|
function VO = spm_smoothto8bit(V,fwhm)
% 3 dimensional convolution of an image to 8bit data in memory
% FORMAT VO = spm_smoothto8bit(V,fwhm)
% V - mapped image to be smoothed
% fwhm - FWHM of Guassian filter width in mm
% VO - smoothed volume in a form that can be used by the
% spm_*_vol.mex* functions.
%_______________________________________________________________________
%
%_______________________________________________________________________
% @(#)spm_smoothto8bit.m 2.2 John Ashburner 03/03/04
if nargin>1 & fwhm>0,
VO = smoothto8bit(V,fwhm);
else,
VO = V;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function VO = smoothto8bit(V,fwhm)
% 3 dimensional convolution of an image to 8bit data in memory
% FORMAT VO = smoothto8bit(V,fwhm)
% V - mapped image to be smoothed
% fwhm - FWHM of Guassian filter width in mm
% VO - smoothed volume in a form that can be used by the
% spm_*_vol.mex* functions.
%_______________________________________________________________________
vx = sqrt(sum(V.mat(1:3,1:3).^2));
s = (fwhm./vx./sqrt(8*log(2)) + eps).^2;
r = cell(1,3);
for i=1:3,
r{i}.s = ceil(3.5*sqrt(s(i)));
x = -r{i}.s:r{i}.s;
r{i}.k = exp(-0.5 * (x.*x)/s(i))/sqrt(2*pi*s(i));
r{i}.k = r{i}.k/sum(r{i}.k);
end;
buff = zeros([V.dim(1:2) r{3}.s*2+1]);
VO = V;
VO.dim(4) = spm_type('uint8');
V0.dat = uint8(0);
V0.dat(VO.dim(1:3)) = uint8(0);
VO.pinfo = [];
for i=1:V.dim(3)+r{3}.s,
if i<=V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 i]),V.dim(1:2),0);
msk = find(~isfinite(img));
img(msk) = 0;
buff(:,:,rem(i-1,r{3}.s*2+1)+1) = ...
conv2(conv2(img,r{1}.k,'same'),r{2}.k','same');
else,
buff(:,:,rem(i-1,r{3}.s*2+1)+1) = 0;
end;
if i>r{3}.s,
kern = zeros(size(r{3}.k'));
kern(rem((i:(i+r{3}.s*2))',r{3}.s*2+1)+1) = r{3}.k';
img = reshape(buff,[prod(V.dim(1:2)) r{3}.s*2+1])*kern;
img = reshape(img,V.dim(1:2));
ii = i-r{3}.s;
mx = max(img(:));
mn = min(img(:));
if mx==mn, mx=mn+eps; end;
VO.pinfo(1:2,ii) = [(mx-mn)/255 mn]';
VO.dat(:,:,ii) = uint8(round((img-mn)*(255/(mx-mn))));
end;
end;
|
github
|
lcnhappe/happe-master
|
spm_platform.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm2/spm_platform.m
| 7,715 |
utf_8
|
c43c4cc00de257f7ef7f8f9e79552a22
|
function varargout=spm_platform(varargin)
% Platform specific configuration parameters for SPM
%
% FORMAT ans = spm_platform(arg)
% arg - optional string argument, can be
% - 'bigend' - return whether this architecture is bigendian
% - Inf - is not IEEE floating point
% - 0 - is little end
% - 1 - big end
% - 'filesys' - type of filesystem
% - 'unx' - UNIX
% - 'win' - DOS
% - 'mac' - Macintosh
% - 'vms' - VMS
% - 'sepchar' - returns directory separator
% - 'rootlen' - returns number of chars in root directory name
% - 'user' - returns username
% - 'tempdir' - returns name of temp directory
%
% FORMAT PlatFontNames = spm_platform('fonts')
% Returns structure with fields named after the generic (UNIX) fonts, the
% field containing the name of the platform specific font.
%
% FORMAT PlatFontName = spm_platform('font',GenFontName)
% Maps generic (UNIX) FontNames to platform specific FontNames
%
% FORMAT PLATFORM = spm_platform('init',comp)
% Initialises platform specific parameters in persistent PLATFORM
% (External gateway to init_platform(comp) subfunction)
% comp - computer to use [defaults to MatLab's `computer`]
% PLATFORM - copy of persistent PLATFORM
%
% FORMAT spm_platform
% Initialises platform specific parameters in persistent PLATFORM
% (External gateway to init_platform(computer) subfunction)
%
% ----------------
% SUBFUNCTIONS:
%
% FORMAT init_platform(comp)
% Initialise platform specific parameters in persistent PLATFORM
% comp - computer to use [defaults to MatLab's `computer`]
%
%-----------------------------------------------------------------------
%
% Since calls to spm_platform will be made frequently, most platform
% specific parameters are stored as a structure in the persistent variable
% PLATFORM. Subsequent calls use the information from this persistent
% variable, if it exists.
%
% Platform specific difinitions are contained in the data structures at
% the beginning of the init_platform subfunction at the end of this
% file.
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Matthew Brett
% $Id$
%-Initialise
%-----------------------------------------------------------------------
persistent PLATFORM
if isempty(PLATFORM), PLATFORM = init_platform; end
if nargin==0, return, end
switch lower(varargin{1}), case 'init' %-(re)initialise
%=======================================================================
init_platform(varargin{2:end})
varargout = {PLATFORM};
case 'bigend' %-Return endian for this architecture
%=======================================================================
varargout = {PLATFORM.bigend};
if ~isfinite(PLATFORM.bigend),
if isnan(PLATFORM.bigend)
error(['I don''t know if "',computer,'" is big-endian.'])
else
error(['I don''t think that "',computer,...
'" uses IEEE floating point ops.'])
end
end
case 'filesys' %-Return file system
%=======================================================================
varargout = {PLATFORM.filesys};
case 'sepchar' %-Return file separator character
%=======================================================================
warning('use filesep instead (supported by MathWorks)')
varargout = {PLATFORM.sepchar};
case 'rootlen' %-Return length in chars of root directory name
%=======================================================================
varargout = {PLATFORM.rootlen};
case 'user' %-Return user string
%=======================================================================
varargout = {PLATFORM.user};
case 'tempdir' %-Return temporary directory
%=======================================================================
twd = getenv('SPMTMP');
if isempty(twd)
twd = tempdir;
end
varargout = {twd};
case {'font','fonts'} %-Map default font names to platform font names
%=======================================================================
if nargin<2, varargout={PLATFORM.font}; return, end
switch lower(varargin{2})
case 'times'
varargout = {PLATFORM.font.times};
case 'courier'
varargout = {PLATFORM.font.courier};
case 'helvetica'
varargout = {PLATFORM.font.helvetica};
case 'symbol'
varargout = {PLATFORM.font.symbol};
otherwise
warning(['Unknown font ',varargin{2},', using default'])
varargout = {PLATFORM.font.helvetica};
end
otherwise %-Unknown Action string
%=======================================================================
error('Unknown Action string')
%=======================================================================
end
%=======================================================================
%- S U B - F U N C T I O N S
%=======================================================================
function PLATFORM = init_platform(comp) %-Initialise platform variables
%=======================================================================
if nargin<1, comp=computer; end
%-Platform definitions
%-----------------------------------------------------------------------
PDefs = { 'PCWIN', 'win', 0;...
'MAC', 'unx', 1;...
'SUN4', 'unx', 1;...
'SOL2', 'unx', 1;...
'HP700', 'unx', 1;...
'SGI', 'unx', 1;...
'SGI64', 'unx', 1;...
'IBM_RS', 'unx', 1;...
'ALPHA', 'unx', 0;...
'AXP_VMSG', 'vms', Inf;...
'AXP_VMSIEEE', 'vms', 0;...
'LNX86', 'unx', 0;...
'GLNX86', 'unx', 0;...
'GLNXA64', 'unx', 0;...
'VAX_VMSG', 'vms', Inf;...
'VAX_VMSD', 'vms', Inf };
PDefs = cell2struct(PDefs,{'computer','filesys','endian'},2);
%-Which computer?
%-----------------------------------------------------------------------
ci = find(strcmp({PDefs.computer},comp));
if isempty(ci), error([comp,' not supported architecture for SPM']), end
%-Set bigend
%-----------------------------------------------------------------------
PLATFORM.bigend = PDefs(ci).endian;
%-Set filesys
%-----------------------------------------------------------------------
PLATFORM.filesys = PDefs(ci).filesys;
%-Set filesystem dependent stuff
%-----------------------------------------------------------------------
%-File separators character
%-Length of root directory strings
%-User name finding
%-(mouse button labels?)
switch (PLATFORM.filesys)
case 'unx'
PLATFORM.sepchar = '/';
PLATFORM.rootlen = 1;
PLATFORM.user = getenv('USER');
case 'win'
PLATFORM.sepchar = '\';
PLATFORM.rootlen = 3;
PLATFORM.user = getenv('USERNAME');
if isempty(PLATFORM.user)
PLATFORM.user = spm_win32utils('username'); end
otherwise
error(['Don''t know filesystem ',PLATFORM.filesys])
end
%-Fonts
%-----------------------------------------------------------------------
switch comp
case {'SOL2'} %-Some Sol2 platforms give segmentation violations with Helvetica
PLATFORM.font.helvetica = 'Lucida';
PLATFORM.font.times = 'Times';
PLATFORM.font.courier = 'Courier';
PLATFORM.font.symbol = 'Symbol';
case {'SUN4','SOL2','HP700','SGI','SGI64','IBM_RS','ALPHA','LNX86','GLNX86','GLNXA64','MAC'}
PLATFORM.font.helvetica = 'Helvetica';
PLATFORM.font.times = 'Times';
PLATFORM.font.courier = 'Courier';
PLATFORM.font.symbol = 'Symbol';
case {'PCWIN'}
PLATFORM.font.helvetica = 'Arial Narrow';
PLATFORM.font.times = 'Times New Roman';
PLATFORM.font.courier = 'Courier New';
PLATFORM.font.symbol = 'Symbol';
end
|
github
|
lcnhappe/happe-master
|
spm_read_hdr.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm2/spm_read_hdr.m
| 5,294 |
utf_8
|
674302bc6310dd07e5c76a9cc58fc5ce
|
function [hdr,otherendian] = spm_read_hdr(fname)
% Read (SPM customised) Analyze header
% FORMAT [hdr,otherendian] = spm_read_hdr(fname)
% fname - .hdr filename
% hdr - structure containing Analyze header
% otherendian - byte swapping necessary flag
%_______________________________________________________________________
% @(#)spm_read_hdr.m 2.2 John Ashburner 03/07/17
fid = fopen(fname,'r','native');
otherendian = 0;
if (fid > 0)
dime = read_dime(fid);
if dime.dim(1)<0 | dime.dim(1)>15, % Appears to be other-endian
% Re-open other-endian
fclose(fid);
if spm_platform('bigend'), fid = fopen(fname,'r','ieee-le');
else, fid = fopen(fname,'r','ieee-be'); end;
otherendian = 1;
dime = read_dime(fid);
end;
hk = read_hk(fid);
hist = read_hist(fid);
hdr.hk = hk;
hdr.dime = dime;
hdr.hist = hist;
% SPM specific bit - unused
%if hdr.hk.sizeof_hdr > 348,
% spmf = read_spmf(fid,dime.dim(5));
% if ~isempty(spmf),
% hdr.spmf = spmf;
% end;
%end;
fclose(fid);
else,
hdr = [];
otherendian = NaN;
%error(['Problem opening header file (' fopen(fid) ').']);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function hk = read_hk(fid)
% read (struct) header_key
%-----------------------------------------------------------------------
fseek(fid,0,'bof');
hk.sizeof_hdr = fread(fid,1,'int32');
hk.data_type = mysetstr(fread(fid,10,'uchar'))';
hk.db_name = mysetstr(fread(fid,18,'uchar'))';
hk.extents = fread(fid,1,'int32');
hk.session_error = fread(fid,1,'int16');
hk.regular = mysetstr(fread(fid,1,'uchar'))';
hk.hkey_un0 = mysetstr(fread(fid,1,'uchar'))';
if isempty(hk.hkey_un0), error(['Problem reading "hk" of header file (' fopen(fid) ').']); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function dime = read_dime(fid)
% read (struct) image_dimension
%-----------------------------------------------------------------------
fseek(fid,40,'bof');
dime.dim = fread(fid,8,'int16')';
dime.vox_units = mysetstr(fread(fid,4,'uchar'))';
dime.cal_units = mysetstr(fread(fid,8,'uchar'))';
dime.unused1 = fread(fid,1,'int16');
dime.datatype = fread(fid,1,'int16');
dime.bitpix = fread(fid,1,'int16');
dime.dim_un0 = fread(fid,1,'int16');
dime.pixdim = fread(fid,8,'float')';
dime.vox_offset = fread(fid,1,'float');
dime.funused1 = fread(fid,1,'float');
dime.funused2 = fread(fid,1,'float');
dime.funused3 = fread(fid,1,'float');
dime.cal_max = fread(fid,1,'float');
dime.cal_min = fread(fid,1,'float');
dime.compressed = fread(fid,1,'int32');
dime.verified = fread(fid,1,'int32');
dime.glmax = fread(fid,1,'int32');
dime.glmin = fread(fid,1,'int32');
if isempty(dime.glmin), error(['Problem reading "dime" of header file (' fopen(fid) ').']); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function hist = read_hist(fid)
% read (struct) data_history
%-----------------------------------------------------------------------
fseek(fid,148,'bof');
hist.descrip = mysetstr(fread(fid,80,'uchar'))';
hist.aux_file = mysetstr(fread(fid,24,'uchar'))';
hist.orient = fread(fid,1,'uchar');
hist.origin = fread(fid,5,'int16')';
hist.generated = mysetstr(fread(fid,10,'uchar'))';
hist.scannum = mysetstr(fread(fid,10,'uchar'))';
hist.patient_id = mysetstr(fread(fid,10,'uchar'))';
hist.exp_date = mysetstr(fread(fid,10,'uchar'))';
hist.exp_time = mysetstr(fread(fid,10,'uchar'))';
hist.hist_un0 = mysetstr(fread(fid,3,'uchar'))';
hist.views = fread(fid,1,'int32');
hist.vols_added = fread(fid,1,'int32');
hist.start_field= fread(fid,1,'int32');
hist.field_skip = fread(fid,1,'int32');
hist.omax = fread(fid,1,'int32');
hist.omin = fread(fid,1,'int32');
hist.smax = fread(fid,1,'int32');
hist.smin = fread(fid,1,'int32');
if isempty(hist.smin), error(['Problem reading "hist" of header file (' fopen(fid) ').']); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function spmf = read_spmf(fid,n)
% Read SPM specific fields
% This bit may be used in the future for extending the Analyze header.
fseek(fid,348,'bof');
mgc = fread(fid,1,'int32'); % Magic number
if mgc ~= 20020417, spmf = []; return; end;
for j=1:n,
spmf(j).mat = fread(fid,16,'double'); % Orientation information
spmf(j).unused = fread(fid,384,'uchar'); % Extra unused stuff
if length(spmf(j).unused)<384,
error(['Problem reading "spmf" of header file (' fopen(fid) ').']);
end;
spmf(j).mat = reshape(spmf(j).mat,[4 4]);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function out = mysetstr(in)
tmp = find(in == 0);
tmp = min([min(tmp) length(in)]);
out = setstr([in(1:tmp)' zeros(1,length(in)-(tmp))])';
return;
%_______________________________________________________________________
%_______________________________________________________________________
|
github
|
lcnhappe/happe-master
|
spm_write_plane.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm2/spm_write_plane.m
| 4,446 |
utf_8
|
4112c03c69d90f524531bf05dc467067
|
function V = spm_write_plane(V,A,p)
% Write a transverse plane of image data.
% FORMAT V = spm_write_plane(V,A,p)
% V - data structure containing image information.
% - see spm_vol for a description.
% A - the two dimensional image to write.
% p - the plane number (beginning from 1).
%
% VO - (possibly) modified data structure containing image information.
% It is possible that future versions of spm_write_plane may
% modify scalefactors (for example).
%
%_______________________________________________________________________
% @(#)spm_write_plane.m 2.19 John Ashburner 03/07/16
if any(V.dim(1:2) ~= size(A)), error('Incompatible image dimensions'); end;
if p>V.dim(3), error('Plane number too high'); end;
% Write Analyze image by default
V = write_analyze_plane(V,A,p);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function V = write_analyze_plane(V,A,p)
types = [ 2 4 8 16 64 130 132 136, 512 1024 2048 4096 16384 33280 33792 34816];
maxval = [2^8-1 2^15-1 2^31-1 Inf Inf 2^7-1 2^16-1 2^32-1, 2^8-1 2^15-1 2^31-1 Inf Inf 2^8-1 2^16-1 2^32-1];
minval = [ 0 -2^15 -2^31 -Inf -Inf -2^7 0 0, 0 -2^15 -2^31 -Inf -Inf -2^7 0 0];
intt = [ 1 1 1 0 0 1 1 1, 1 1 1 0 0 1 1 1];
prec = str2mat('uint8','int16','int32','float','double','int8','uint16','uint32','uint8','int16','int32','float','double','int8','uint16','uint32');
swapped = [ 0 0 0 0 0 0 0 0, 1 1 1 1 1 1 1 1];
bits = [ 8 16 32 32 64 8 16 32, 8 16 32 32 64 8 16 32];
dt = find(types==V.dim(4));
if isempty(dt), error('Unknown datatype'); end;
A = double(A);
% Rescale to fit appropriate range
if intt(dt),
A(isnan(A)) = 0;
mxv = maxval(dt);
mnv = minval(dt);
A = round(A*(1/V.pinfo(1)) - V.pinfo(2));
A(A > mxv) = mxv;
A(A < mnv) = mnv;
end;
if ~isfield(V,'private') | ~isfield(V.private,'fid') | isempty(V.private.fid),
mach = 'native';
if swapped(dt),
if spm_platform('bigend'), mach = 'ieee-le'; else, mach = 'ieee-be'; end;
end;
[pth,nam,ext] = fileparts(V.fname);
fname = fullfile(pth,[nam, '.img']);
fid = fopen(fname,'r+',mach);
if fid == -1,
fid = fopen(fname,'w',mach);
if fid == -1,
error(['Error opening ' fname '. Check that you have write permission.']);
end;
end;
else,
if isempty(fopen(V.private.fid)),
mach = 'native';
if swapped(dt),
if spm_platform('bigend'), mach = 'ieee-le'; else, mach = 'ieee-be'; end;
end;
V.private.fid = fopen(fname,'r+',mach);
if V.private.fid == -1,
error(['Error opening ' fname '. Check that you have write permission.']);
end;
end;
fid = V.private.fid;
end;
% Seek to the appropriate offset
datasize = bits(dt)/8;
off = (p-1)*datasize*prod(V.dim(1:2)) + V.pinfo(3,1);
fseek(fid,0,'bof'); % A bug in Matlab 6.5 means that a rewind is needed
if fseek(fid,off,'bof')==-1,
% Need this because fseek in Matlab does not seek past the EOF
fseek(fid,0,'bof'); % A bug in Matlab 6.5 means that a rewind is needed
fseek(fid,0,'eof');
curr_off = ftell(fid);
blanks = zeros(off-curr_off,1);
if fwrite(fid,blanks,'uchar') ~= prod(size(blanks)),
write_error_message(V.fname);
error(['Error writing ' V.fname '.']);
end;
fseek(fid,0,'bof'); % A bug in Matlab 6.5 means that a rewind is needed
if fseek(fid,off,'bof') == -1,
write_error_message(V.fname);
error(['Error writing ' V.fname '.']);
return;
end;
end;
if fwrite(fid,A,deblank(prec(dt,:))) ~= prod(size(A)),
write_error_message(V.fname);
error(['Error writing ' V.fname '.']);
end;
if ~isfield(V,'private') | ~isfield(V.private,'fid') | isempty(V.private.fid), fclose(fid); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function write_error_message(q)
str = {...
'Error writing:',...
' ',...
[' ',spm_str_manip(q,'k40d')],...
' ',...
'Check disk space / disk quota.'};
spm('alert*',str,mfilename,sqrt(-1));
return;
%_______________________________________________________________________
|
github
|
lcnhappe/happe-master
|
spm_normalise.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm2/spm_normalise.m
| 12,887 |
utf_8
|
e8649290b7272eb0337aeae86fb737c0
|
function params = spm_normalise(VG,VF,matname,VWG,VWF,flags)
% Spatial (stereotactic) normalization
%
% FORMAT params = spm_normalise(VG,VF,matname,VWG,VWF,flags)
% VG - template handle(s)
% VF - handle of image to estimate params from
% matname - name of file to store deformation definitions
% VWG - template weighting image
% VWF - source weighting image
% flags - flags. If any field is not passed, then defaults are assumed.
% smosrc - smoothing of source image (FWHM of Gaussian in mm).
% Defaults to 8.
% smoref - smoothing of template image (defaults to 0).
% regtype - regularisation type for affine registration
% See spm_affreg.m (default = 'mni').
% cutoff - Cutoff of the DCT bases. Lower values mean more
% basis functions are used (default = 30mm).
% nits - number of nonlinear iterations (default=16).
% reg - amount of regularisation (default=0.1)
% ___________________________________________________________________________
%
% This module spatially (stereotactically) normalizes MRI, PET or SPECT
% images into a standard space defined by some ideal model or template
% image[s]. The template images supplied with SPM conform to the space
% defined by the ICBM, NIH P-20 project, and approximate that of the
% the space described in the atlas of Talairach and Tournoux (1988).
% The transformation can also be applied to any other image that has
% been coregistered with these scans.
%
%
% Mechanism
% Generally, the algorithms work by minimising the sum of squares
% difference between the image which is to be normalised, and a linear
% combination of one or more template images. For the least squares
% registration to produce an unbiased estimate of the spatial
% transformation, the image contrast in the templates (or linear
% combination of templates) should be similar to that of the image from
% which the spatial normalization is derived. The registration simply
% searches for an optimum solution. If the starting estimates are not
% good, then the optimum it finds may not find the global optimum.
%
% The first step of the normalization is to determine the optimum
% 12-parameter affine transformation. Initially, the registration is
% performed by matching the whole of the head (including the scalp) to
% the template. Following this, the registration proceeded by only
% matching the brains together, by appropriate weighting of the template
% voxels. This is a completely automated procedure (that does not
% require ``scalp editing'') that discounts the confounding effects of
% skull and scalp differences. A Bayesian framework is used, such that
% the registration searches for the solution that maximizes the a
% posteriori probability of it being correct. i.e., it maximizes the
% product of the likelihood function (derived from the residual squared
% difference) and the prior function (which is based on the probability
% of obtaining a particular set of zooms and shears).
%
% The affine registration is followed by estimating nonlinear deformations,
% whereby the deformations are defined by a linear combination of three
% dimensional discrete cosine transform (DCT) basis functions.
% The parameters represent coefficients of the deformations in
% three orthogonal directions. The matching involved simultaneously
% minimizing the bending energies of the deformation fields and the
% residual squared difference between the images and template(s).
%
% An option is provided for allowing weighting images (consisting of pixel
% values between the range of zero to one) to be used for registering
% abnormal or lesioned brains. These images should match the dimensions
% of the image from which the parameters are estimated, and should contain
% zeros corresponding to regions of abnormal tissue.
%
%
% Uses
% Primarily for stereotactic normalization to facilitate inter-subject
% averaging and precise characterization of functional anatomy. It is
% not necessary to spatially normalise the data (this is only a
% pre-requisite for intersubject averaging or reporting in the
% Talairach space).
%
% Inputs
% The first input is the image which is to be normalised. This image
% should be of the same modality (and MRI sequence etc) as the template
% which is specified. The same spatial transformation can then be
% applied to any other images of the same subject. These files should
% conform to the SPM data format (See 'Data Format'). Many subjects can
% be entered at once, and there is no restriction on image dimensions
% or voxel size.
%
% Providing that the images have a correct ".mat" file associated with
% them, which describes the spatial relationship between them, it is
% possible to spatially normalise the images without having first
% resliced them all into the same space. The ".mat" files are generated
% by "spm_realign" or "spm_coregister".
%
% Default values of parameters pertaining to the extent and sampling of
% the standard space can be changed, including the model or template
% image[s].
%
%
% Outputs
% All normalized *.img scans are written to the same subdirectory as
% the original *.img, prefixed with a 'n' (i.e. n*.img). The details
% of the transformations are displayed in the results window, and the
% parameters are saved in the "*_sn.mat" file.
%
%
%____________________________________________________________________________
% Refs:
% K.J. Friston, J. Ashburner, C.D. Frith, J.-B. Poline,
% J.D. Heather, and R.S.J. Frackowiak
% Spatial Registration and Normalization of Images.
% Human Brain Mapping 2:165-189(1995)
%
% J. Ashburner, P. Neelin, D.L. Collins, A.C. Evans and K. J. Friston
% Incorporating Prior Knowledge into Image Registration.
% NeuroImage 6:344-352 (1997)
%
% J. Ashburner and K. J. Friston
% Nonlinear Spatial Normalization using Basis Functions.
% Human Brain Mapping 7(4):in press (1999)
%_______________________________________________________________________
% @(#)spm_normalise.m 2.10 John Ashburner 04/01/27
if nargin<2, error('Incorrect usage.'); end;
if ischar(VF), VF = spm_vol(VF); end;
if ischar(VG), VG = spm_vol(VG); end;
if nargin<3,
if nargout==0,
[pth,nm,xt,vr] = fileparts(deblank(VF(1).fname));
matname = fullfile(pth,[nm '_sn.mat']);
else,
matname = '';
end;
end;
if nargin<4, VWG = ''; end;
if nargin<5, VWF = ''; end;
if ischar(VWG), VWG=spm_vol(VWG); end;
if ischar(VWF), VWF=spm_vol(VWF); end;
def_flags = struct('smosrc',8,'smoref',0,'regtype','mni',...
'cutoff',30,'nits',16,'reg',0.1,'graphics',1);
if nargin < 6,
flags = def_flags;
else,
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}), flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i})); end;
end;
end;
fprintf('Smoothing by %g & %gmm..\n', flags.smoref, flags.smosrc);
VF1 = spm_smoothto8bit(VF,flags.smosrc);
% Rescale images so that globals are better conditioned
VF1.pinfo(1:2,:) = VF1.pinfo(1:2,:)/spm_global(VF1);
for i=1:prod(size(VG)),
VG1(i) = spm_smoothto8bit(VG(i),flags.smoref);
VG1(i).pinfo(1:2,:) = VG1(i).pinfo(1:2,:)/spm_global(VG(i));
end;
% Affine Normalisation
%-----------------------------------------------------------------------
fprintf('Coarse Affine Registration..\n');
aflags = struct('sep',max(flags.smoref,flags.smosrc), 'regtype',flags.regtype,...
'WG',[],'WF',[],'globnorm',0);
M = eye(4); %spm_matrix(prms');
spm_chi2_plot('Init','Affine Registration','Mean squared difference','Iteration');
[M,scal] = spm_affreg(VG1, VF1, aflags, M);
fprintf('Fine Affine Registration..\n');
aflags.WG = VWG;
aflags.WF = VWF;
aflags.sep = max(flags.smoref,flags.smosrc)/2;
[M,scal] = spm_affreg(VG1, VF1, aflags, M,scal);
Affine = inv(VG(1).mat\M*VF1(1).mat);
spm_chi2_plot('Clear');
% Basis function Normalisation
%-----------------------------------------------------------------------
fov = VF1(1).dim(1:3).*sqrt(sum(VF1(1).mat(1:3,1:3).^2));
if any(fov<60),
fprintf('Field of view too small for nonlinear registration\n');
Tr = [];
elseif isfinite(flags.cutoff) & flags.nits & ~isinf(flags.reg),
fprintf('3D CT Norm...\n');
Tr = snbasis(VG1,VF1,VWG,VWF,Affine,...
max(flags.smoref,flags.smosrc),flags.cutoff,flags.nits,flags.reg);
else,
Tr = [];
end;
clear VF1 VG1
flags.version = '@(#)spm_normalise.m 2.10 04/01/27';
flags.date = date;
params = struct('Affine',Affine, 'Tr',Tr, 'VF',VF, 'VG',VG, 'flags',flags);
if flags.graphics, spm_normalise_disp(params,VF); end;
% Remove dat fields before saving
%-----------------------------------------------------------------------
if isfield(VF,'dat'), VF = rmfield(VF,'dat'); end;
if isfield(VG,'dat'), VG = rmfield(VG,'dat'); end;
if ~isempty(matname),
fprintf('Saving Parameters..\n');
save(matname,'Affine','Tr','VF','VG','flags');
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function Tr = snbasis(VG,VF,VWG,VWF,Affine,fwhm,cutoff,nits,reg)
% 3D Basis Function Normalization
% FORMAT Tr = snbasis(VG,VF,VWG,VWF,Affine,fwhm,cutoff,nits,reg)
% VG - Template volumes (see spm_vol).
% VF - Volume to normalize.
% VWG - weighting Volume - for template.
% VWF - weighting Volume - for object.
% Affine - A 4x4 transformation (in voxel space).
% fwhm - smoothness of images.
% cutoff - frequency cutoff of basis functions.
% nits - number of iterations.
% reg - regularisation.
% Tr - Discrete cosine transform of the warps in X, Y & Z.
%
% snbasis performs a spatial normalization based upon a 3D
% discrete cosine transform.
%
%______________________________________________________________________
% @(#)spm_normalise.m 2.10 John Ashburner FIL (& Matthew Brett MRCCU) 04/01/27
fwhm = [fwhm 30];
% Number of basis functions for x, y & z
%-----------------------------------------------------------------------
tmp = sqrt(sum(VG(1).mat(1:3,1:3).^2));
k = max(round((VG(1).dim(1:3).*tmp)/cutoff),[1 1 1]);
% Scaling is to improve stability.
%-----------------------------------------------------------------------
stabilise = 8;
basX = spm_dctmtx(VG(1).dim(1),k(1))*stabilise;
basY = spm_dctmtx(VG(1).dim(2),k(2))*stabilise;
basZ = spm_dctmtx(VG(1).dim(3),k(3))*stabilise;
dbasX = spm_dctmtx(VG(1).dim(1),k(1),'diff')*stabilise;
dbasY = spm_dctmtx(VG(1).dim(2),k(2),'diff')*stabilise;
dbasZ = spm_dctmtx(VG(1).dim(3),k(3),'diff')*stabilise;
vx1 = sqrt(sum(VG(1).mat(1:3,1:3).^2));
vx2 = vx1;
kx = (pi*((1:k(1))'-1)/VG(1).dim(1)/vx1(1)).^2; ox=ones(k(1),1);
ky = (pi*((1:k(2))'-1)/VG(1).dim(2)/vx1(2)).^2; oy=ones(k(2),1);
kz = (pi*((1:k(3))'-1)/VG(1).dim(3)/vx1(3)).^2; oz=ones(k(3),1);
if 1,
% BENDING ENERGY REGULARIZATION
% Estimate a suitable sparse diagonal inverse covariance matrix for
% the parameters (IC0).
%-----------------------------------------------------------------------
IC0 = (1*kron(kz.^2,kron(ky.^0,kx.^0)) +...
1*kron(kz.^0,kron(ky.^2,kx.^0)) +...
1*kron(kz.^0,kron(ky.^0,kx.^2)) +...
2*kron(kz.^1,kron(ky.^1,kx.^0)) +...
2*kron(kz.^1,kron(ky.^0,kx.^1)) +...
2*kron(kz.^0,kron(ky.^1,kx.^1)) );
IC0 = reg*IC0*stabilise^6;
IC0 = [IC0*vx2(1)^4 ; IC0*vx2(2)^4 ; IC0*vx2(3)^4 ; zeros(prod(size(VG))*4,1)];
IC0 = sparse(1:length(IC0),1:length(IC0),IC0,length(IC0),length(IC0));
else,
% MEMBRANE ENERGY (LAPLACIAN) REGULARIZATION
%-----------------------------------------------------------------------
IC0 = kron(kron(oz,oy),kx) + kron(kron(oz,ky),ox) + kron(kron(kz,oy),ox);
IC0 = reg*IC0*stabilise^6;
IC0 = [IC0*vx2(1)^2 ; IC0*vx2(2)^2 ; IC0*vx2(3)^2 ; zeros(prod(size(VG))*4,1)];
IC0 = sparse(1:length(IC0),1:length(IC0),IC0,length(IC0),length(IC0));
end;
% Generate starting estimates.
%-----------------------------------------------------------------------
s1 = 3*prod(k);
s2 = s1 + prod(size(VG))*4;
T = zeros(s2,1);
T(s1+(1:4:prod(size(VG))*4)) = 1;
pVar = Inf;
for iter=1:nits,
fprintf(' iteration %2d: ', iter);
[Alpha,Beta,Var,fw] = spm_brainwarp(VG,VF,Affine,basX,basY,basZ,dbasX,dbasY,dbasZ,T,fwhm,VWG, VWF);
if Var>pVar, scal = pVar/Var ; Var = pVar; else, scal = 1; end;
pVar = Var;
T = (Alpha + IC0*scal)\(Alpha*T + Beta);
fwhm(2) = min([fw fwhm(2)]);
fprintf(' FWHM = %6.4g Var = %g\n', fw,Var);
end;
% Values of the 3D-DCT - for some bizarre reason, this needs to be done
% as two seperate statements in Matlab 6.5...
%-----------------------------------------------------------------------
Tr = reshape(T(1:s1),[k 3]);
drawnow;
Tr = Tr*stabilise.^3;
return;
|
github
|
lcnhappe/happe-master
|
spm_create_vol.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm2/spm_create_vol.m
| 11,434 |
utf_8
|
f18edbf50d6186af1c5108b814690894
|
function V = spm_create_vol(V,varargin)
% Create an image file.
% FORMAT Vo = spm_create_vol(Vi,['noopen'])
% Vi - data structure containing image information.
% - see spm_vol for a description.
% 'noopen' - optional flag to say "don't open/create the image file".
% Vo - data structure after modification for writing.
%_______________________________________________________________________
% @(#)spm_create_vol.m 2.14 John Ashburner 03/07/31
for i=1:prod(size(V)),
if nargin>1,
v = create_vol(V(i),varargin{:});
else,
v = create_vol(V(i));
end;
f = fieldnames(v);
for j=1:size(f,1),
%eval(['V(i).' f{j} ' = v.' f{j} ';']);
V = setfield(V,{i},f{j},getfield(v,f{j}));
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function V = create_vol(V,varargin)
if ~isfield(V,'n') | isempty(V.n), V.n = 1; end;
if ~isfield(V,'descrip') | isempty(V.descrip), V.descrip = 'SPM2 compatible'; end;
V.private = struct('hdr',[]);
% Orientation etc...
M = V.mat;
if spm_flip_analyze_images, M = diag([-1 1 1 1])*M; end;
vx = sqrt(sum(M(1:3,1:3).^2));
if det(M(1:3,1:3))<0, vx(1) = -vx(1); end;
origin = M\[0 0 0 1]';
origin = round(origin(1:3));
[pth,nam,ext] = fileparts(V.fname);
fname = fullfile(pth,[nam, '.hdr']);
try,
[hdr,swapped] = spm_read_hdr(fname);
catch,
warning(['Could not read "' fname '"']);
swapped = 0;
hdr = [];
end;
if ~isempty(hdr) & (hdr.dime.dim(5)>1 | V.n>1),
% cannot simply overwrite the header
hdr.dime.dim(5) = max(V.n,hdr.dime.dim(5));
if any(V.dim(1:3) ~= hdr.dime.dim(2:4))
error('Incompatible image dimensions');
end;
if sum((vx-hdr.dime.pixdim(2:4)).^2)>1e-6,
error('Incompatible voxel sizes');
end;
V.dim(4) = spm_type(spm_type(hdr.dime.datatype));
mach = 'native';
if swapped,
V.dim(4) = V.dim(4)*256;
if spm_platform('bigend'),
mach = 'ieee-le';
else,
mach = 'ieee-be';
end;
end;
if isfinite(hdr.dime.funused1) & hdr.dime.funused1,
scal = hdr.dime.funused1;
if isfinite(hdr.dime.funused2),
dcoff = hdr.dime.funused2;
else,
dcoff = 0;
end;
else
if hdr.dime.glmax-hdr.dime.glmin & hdr.dime.cal_max-hdr.dime.cal_min,
scal = (hdr.dime.cal_max-hdr.dime.cal_min)/(hdr.dime.glmax-hdr.dime.glmin);
dcoff = hdr.dime.cal_min - scal*hdr.dime.glmin;
else,
scal = 1;
dcoff = 0;
warning(['Assuming a scalefactor of 1 for "' V.fname '".']);
end;
end;
V.pinfo(1:2) = [scal dcoff]';
V.private.hdr = hdr;
else,
V.private.hdr = create_defaults;
swapped = spm_type(V.dim(4),'swapped');
dt = spm_type(spm_type(V.dim(4)));
if any(dt == [128+2 128+4 128+8]),
% Convert to a form that Analyze will support
dt = dt - 128;
end;
V.dim(4) = dt;
mach = 'native';
if swapped,
V.dim(4) = V.dim(4)*256;
if spm_platform('bigend'),
mach = 'ieee-le';
else,
mach = 'ieee-be';
end;
end;
V.private.hdr.dime.datatype = dt;
V.private.hdr.dime.bitpix = spm_type(dt,'bits');
if spm_type(dt,'intt'),
V.private.hdr.dime.glmax = spm_type(dt,'maxval');
V.private.hdr.dime.glmin = spm_type(dt,'minval');
if 0, % Allow DC offset
V.private.hdr.dime.cal_max = max(V.private.hdr.dime.glmax*V.pinfo(1,:) + V.pinfo(2,:));
V.private.hdr.dime.cal_min = min(V.private.hdr.dime.glmin*V.pinfo(1,:) + V.pinfo(2,:));
V.private.hdr.dime.funused1 = 0;
scal = (V.private.hdr.dime.cal_max - V.private.hdr.dime.cal_min)/...
(V.private.hdr.dime.glmax - V.private.hdr.dime.glmin);
dcoff = V.private.hdr.dime.cal_min - V.private.hdr.dime.glmin*scal;
V.pinfo = [scal dcoff 0]';
else, % Don't allow DC offset
cal_max = max(V.private.hdr.dime.glmax*V.pinfo(1,:) + V.pinfo(2,:));
cal_min = min(V.private.hdr.dime.glmin*V.pinfo(1,:) + V.pinfo(2,:));
V.private.hdr.dime.funused1 = cal_max/V.private.hdr.dime.glmax;
if V.private.hdr.dime.glmin,
V.private.hdr.dime.funused1 = max(V.private.hdr.dime.funused1,...
cal_min/V.private.hdr.dime.glmin);
end;
V.private.hdr.dime.cal_max = V.private.hdr.dime.glmax*V.private.hdr.dime.funused1;
V.private.hdr.dime.cal_min = V.private.hdr.dime.glmin*V.private.hdr.dime.funused1;
V.pinfo = [V.private.hdr.dime.funused1 0 0]';
end;
else,
V.private.hdr.dime.glmax = 1;
V.private.hdr.dime.glmin = 0;
V.private.hdr.dime.cal_max = 1;
V.private.hdr.dime.cal_min = 0;
V.private.hdr.dime.funused1 = 1;
end;
V.private.hdr.dime.pixdim(2:4) = vx;
V.private.hdr.dime.dim(2:4) = V.dim(1:3);
V.private.hdr.dime.dim(5) = V.n;
V.private.hdr.hist.origin(1:3) = origin;
d = 1:min([length(V.descrip) 79]);
V.private.hdr.hist.descrip = char(zeros(1,80));
V.private.hdr.hist.descrip(d) = V.descrip(d);
V.private.hdr.hk.db_name = char(zeros(1,18));
[pth,nam,ext] = fileparts(V.fname);
d = 1:min([length(nam) 17]);
V.private.hdr.hk.db_name(d) = nam(d);
end;
V.pinfo(3) = prod(V.private.hdr.dime.dim(2:4))*V.private.hdr.dime.bitpix/8*(V.n-1);
fid = fopen(fname,'w',mach);
if (fid == -1),
error(['Error opening ' fname '. Check that you have write permission.']);
end;
write_hk(fid,V.private.hdr.hk);
write_dime(fid,V.private.hdr.dime);
write_hist(fid,V.private.hdr.hist);
fclose(fid);
fname = fullfile(pth,[nam, '.mat']);
off = -vx'.*origin;
mt = [vx(1) 0 0 off(1) ; 0 vx(2) 0 off(2) ; 0 0 vx(3) off(3) ; 0 0 0 1];
if spm_flip_analyze_images, mt = diag([-1 1 1 1])*mt; end;
if sum((V.mat(:) - mt(:)).*(V.mat(:) - mt(:))) > eps*eps*12 | exist(fname)==2,
if exist(fname)==2,
clear mat
str = load(fname);
if isfield(str,'mat'),
mat = str.mat;
elseif isfield(str,'M'),
mat = str.M;
if spm_flip_analyze_images,
for i=1:size(mat,3),
mat(:,:,i) = diag([-1 1 1 1])*mat(:,:,i);
end;
end;
end;
mat(:,:,V.n) = V.mat;
mat = fill_empty(mat,mt);
M = mat(:,:,1); if spm_flip_analyze_images, M = diag([-1 1 1 1])*M; end;
try,
save(fname,'mat','M','-append');
catch, % Mat-file was probably Matlab 4
save(fname,'mat','M');
end;
else,
clear mat
mat(:,:,V.n) = V.mat;
mat = fill_empty(mat,mt);
M = mat(:,:,1); if spm_flip_analyze_images, M = diag([-1 1 1 1])*M; end;
save(fname,'mat','M');
end;
end;
if nargin==1 | ~strcmp(varargin{1},'noopen'),
fname = fullfile(pth,[nam, '.img']);
V.private.fid = fopen(fname,'r+',mach);
if (V.private.fid == -1),
V.private.fid = fopen(fname,'w',mach);
if (V.private.fid == -1),
error(['Error opening ' fname '. Check that you have write permission.']);
end;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function Mo = fill_empty(Mo,Mfill)
todo = [];
for i=1:size(Mo,3),
if ~any(any(Mo(:,:,i))),
todo = [todo i];
end;
end;
if ~isempty(todo),
for i=1:length(todo),
Mo(:,:,todo(i)) = Mfill;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function write_hk(fid,hk)
% write (struct) header_key
%-----------------------------------------------------------------------
fseek(fid,0,'bof');
fwrite(fid,hk.sizeof_hdr, 'int32');
fwrite(fid,hk.data_type, 'char' );
fwrite(fid,hk.db_name, 'char' );
fwrite(fid,hk.extents, 'int32');
fwrite(fid,hk.session_error,'int16');
fwrite(fid,hk.regular, 'char' );
if fwrite(fid,hk.hkey_un0, 'char' )~= 1,
error(['Error writing ' fopen(fid) '. Check your disk space.']);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function write_dime(fid,dime)
% write (struct) image_dimension
%-----------------------------------------------------------------------
fseek(fid,40,'bof');
fwrite(fid,dime.dim, 'int16');
fwrite(fid,dime.vox_units, 'uchar' );
fwrite(fid,dime.cal_units, 'uchar' );
fwrite(fid,dime.unused1, 'int16' );
fwrite(fid,dime.datatype, 'int16');
fwrite(fid,dime.bitpix, 'int16');
fwrite(fid,dime.dim_un0, 'int16');
fwrite(fid,dime.pixdim, 'float');
fwrite(fid,dime.vox_offset, 'float');
fwrite(fid,dime.funused1, 'float');
fwrite(fid,dime.funused2, 'float');
fwrite(fid,dime.funused2, 'float');
fwrite(fid,dime.cal_max, 'float');
fwrite(fid,dime.cal_min, 'float');
fwrite(fid,dime.compressed, 'int32');
fwrite(fid,dime.verified, 'int32');
fwrite(fid,dime.glmax, 'int32');
if fwrite(fid,dime.glmin, 'int32')~=1,
error(['Error writing ' fopen(fid) '. Check your disk space.']);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function write_hist(fid,hist)
% write (struct) data_history
%-----------------------------------------------------------------------
fseek(fid,148,'bof');
fwrite(fid,hist.descrip, 'uchar');
fwrite(fid,hist.aux_file, 'uchar');
fwrite(fid,hist.orient, 'uchar');
fwrite(fid,hist.origin, 'int16');
fwrite(fid,hist.generated, 'uchar');
fwrite(fid,hist.scannum, 'uchar');
fwrite(fid,hist.patient_id, 'uchar');
fwrite(fid,hist.exp_date, 'uchar');
fwrite(fid,hist.exp_time, 'uchar');
fwrite(fid,hist.hist_un0, 'uchar');
fwrite(fid,hist.views, 'int32');
fwrite(fid,hist.vols_added, 'int32');
fwrite(fid,hist.start_field,'int32');
fwrite(fid,hist.field_skip, 'int32');
fwrite(fid,hist.omax, 'int32');
fwrite(fid,hist.omin, 'int32');
fwrite(fid,hist.smax, 'int32');
if fwrite(fid,hist.smin, 'int32')~=1,
error(['Error writing ' fopen(fid) '. Check your disk space.']);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function hdr = create_defaults
hk.sizeof_hdr = 348;
hk.data_type = ['dsr ' 0];
hk.db_name = char(zeros(1,18));
hk.extents = 0;
hk.session_error= 0;
hk.regular = 'r';
hk.hkey_un0 = 0;
dime.dim = [4 0 0 0 1 0 0 0];
dime.vox_units = ['mm ' 0];
dime.cal_units = char(zeros(1,8));
dime.unused1 = 0;
dime.datatype = -1;
dime.bitpix = 0;
dime.dim_un0 = 0;
dime.pixdim = [0 1 1 1 1 0 0 0];
dime.vox_offset = 0;
dime.funused1 = 1;
dime.funused2 = 0;
dime.funused3 = 0;
dime.cal_max = 1;
dime.cal_min = 0;
dime.compressed = 0;
dime.verified = 0;
dime.glmax = 1;
dime.glmin = 0;
hist.descrip = char(zeros(1,80));
hist.descrip(1:length('SPM2 compatible')) = 'SPM2 compatible';
hist.aux_file = char(zeros(1,24));
hist.orient = char(0);
hist.origin = [0 0 0 0 0];
hist.generated = char(zeros(1,10));
hist.scannum = char(zeros(1,10));
hist.patient_id = char(zeros(1,10));
hist.exp_date = char(zeros(1,10));
hist.exp_time = char(zeros(1,10));
hist.hist_un0 = char(zeros(1,3));
hist.generated(1:5) = 'today';
hist.views = 0;
hist.vols_added = 0;
hist.start_field= 0;
hist.field_skip = 0;
hist.omax = 0;
hist.omin = 0;
hist.smax = 0;
hist.smin = 0;
hdr.hk = hk;
hdr.dime = dime;
hdr.hist = hist;
return;
%_______________________________________________________________________
%_______________________________________________________________________
|
github
|
lcnhappe/happe-master
|
spm_segment.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm2/spm_segment.m
| 23,496 |
utf_8
|
9a46c30048feeec44530aa433c773546
|
function VO = spm_segment(VF,PG,flags)
% Segment an MR image into Gray, White & CSF.
%
% FORMAT VO = spm_segment(PF,PG,flags)
% PF - name(s) of image(s) to segment (must have same dimensions).
% PG - name(s) of template image(s) for realignment.
% - or a 4x4 transformation matrix which maps from the image to
% the set of templates.
% flags - a structure normally based on defaults.segment
% VO - optional output volume
%
% The algorithm is four step:
%
% 1) Determine the affine transform which best matches the image with a
% template image. If the name of more than one image is passed, then
% the first image is used in this step. This step is not performed if
% no template images are specified.
%
% 2) Perform Cluster Analysis with a modified Mixture Model and a-priori
% information about the likelihoods of each voxel being one of a
% number of different tissue types. If more than one image is passed,
% then they they are all assumed to be in register, and the voxel
% values are fitted to multi-normal distributions.
%
% 3) Perform morphometric operations on the grey and white partitions
% in order to more accurately identify brain tissue. This is then used
% to clean up the grey and white matter segments.
%
% 4) If no output argument is specified, then the segmented images are
% written to disk. The names of these images have "_seg1", "_seg2"
% & "_seg3" appended to the name of the first image passed.
%
%_______________________________________________________________________
% Refs:
%
% Ashburner J & Friston KJ (1997) Multimodal Image Coregistration and
% Partitioning - a Unified Framework. NeuroImage 6:209-217
%
%_______________________________________________________________________
%
% The template image, and a-priori likelihood images are modified
% versions of those kindly supplied by Alan Evans, MNI, Canada
% (ICBM, NIH P-20 project, Principal Investigator John Mazziotta).
%_______________________________________________________________________
% @(#)spm_segment.m 2.28a John Ashburner 04/04/01
% Create some suitable default values
%-----------------------------------------------------------------------
def_flags.estimate.priors = str2mat(...
fullfile(spm('Dir'),'apriori','gray.mnc'),...
fullfile(spm('Dir'),'apriori','white.mnc'),...
fullfile(spm('Dir'),'apriori','csf.mnc'));
def_flags.estimate.reg = 0.01;
def_flags.estimate.cutoff = 30;
def_flags.estimate.samp = 3;
def_flags.estimate.bb = [[-88 88]' [-122 86]' [-60 95]'];
def_flags.estimate.affreg.smosrc = 8;
def_flags.estimate.affreg.regtype = 'mni';
def_flags.estimate.affreg.weight = '';
def_flags.write.cleanup = 1;
def_flags.write.wrt_cor = 1;
def_flags.graphics = 1;
if nargin<3, flags = def_flags; end;
if ~isfield(flags,'estimate'), flags.estimate = def_flags.estimate; end;
if ~isfield(flags.estimate,'priors'), flags.estimate.priors = def_flags.estimate.priors; end;
if ~isfield(flags.estimate,'reg'), flags.estimate.reg = def_flags.estimate.reg; end;
if ~isfield(flags.estimate,'cutoff'), flags.estimate.cutoff = def_flags.estimate.cutoff; end;
if ~isfield(flags.estimate,'samp'), flags.estimate.samp = def_flags.estimate.samp; end;
if ~isfield(flags.estimate,'bb'), flags.estimate.bb = def_flags.estimate.bb; end;
if ~isfield(flags.estimate,'affreg'), flags.estimate.affreg = def_flags.estimate.affreg; end;
if ~isfield(flags.estimate.affreg,'smosrc'),
flags.estimate.affreg.smosrc = def_flags.estimate.affreg.smosrc;
end;
if ~isfield(flags.estimate.affreg,'regtype'),
flags.estimate.affreg.regtype = def_flags.estimate.affreg.regtype;
end;
if ~isfield(flags.estimate.affreg,'weight'),
flags.estimate.affreg.weight = def_flags.estimate.affreg.weight;
end;
if ~isfield(flags,'write'), flags.write = def_flags.write; end;
if ~isfield(flags.write,'cleanup'), flags.write.cleanup = def_flags.write.cleanup; end;
if ~isfield(flags.write,'wrt_cor'), flags.write.wrt_cor = def_flags.write.wrt_cor; end;
if ~isfield(flags,'graphics'), flags.graphics = def_flags.graphics; end;
%-----------------------------------------------------------------------
if ischar(VF), VF= spm_vol(VF); end;
SP = init_sp(flags.estimate,VF,PG);
[x1,x2,x3] = get_sampling(SP.MM,VF,flags.estimate.samp,flags.estimate.bb);
BP = init_bp(VF, flags.estimate.cutoff, flags.estimate.reg);
CP = init_cp(VF,x3);
sums = zeros(8,1);
for pp=1:length(x3),
[raw,msk] = get_raw(VF,x1,x2,x3(pp));
s = get_sp(SP,x1,x2,x3(pp));
CP = update_cp_est(CP,s,raw,msk,pp);
sums = sums + reshape(sum(sum(s,1),2),8,1);
end;
sums = sums/sum(sums);
CP = shake_cp(CP);
[CP,BP,SP] = run_segment(CP,BP,SP,VF,sums,x1,x2,x3);
%save segmentation_results.mat CP BP SP VF sums
[g,w,c] = get_gwc(VF,BP,SP,CP,sums,flags.write.wrt_cor);
if flags.write.cleanup, [g,w,c] = clean_gwc(g,w,c); end;
% Create the segmented images.
%-----------------------------------------------------------------------
%offs = cumsum(repmat(prod(VF(1).dim(1:2)),1,VF(1).dim(3)))-prod(VF(1).dim(1:2));
%pinfo = [repmat([1/255 0]',1,VF(1).dim(3)) ; offs];
[pth,nm,xt] = fileparts(deblank(VF(1).fname));
for j=1:3,
tmp = fullfile(pth,[nm '_seg' num2str(j) xt]);
VO(j) = struct(...
'fname',tmp,...
'dim', [VF(1).dim(1:3) 2],...
'mat', VF(1).mat,...
'pinfo', [1/255 0 0]',...
'descrip','Segmented image');
end;
if nargout==0,
VO = spm_create_vol(VO);
spm_progress_bar('Init',VF(1).dim(3),'Writing Segmented','planes completed');
for pp=1:VF(1).dim(3),
VO(1) = spm_write_plane(VO(1),double(g(:,:,pp))/255,pp);
VO(2) = spm_write_plane(VO(2),double(w(:,:,pp))/255,pp);
VO(3) = spm_write_plane(VO(3),double(c(:,:,pp))/255,pp);
spm_progress_bar('Set',pp);
end;
VO = spm_close_vol(VO);
spm_progress_bar('Clear');
end;
VO(1).dat = g; VO(1).pinfo = VO(1).pinfo(1:2,:);
VO(2).dat = w; VO(2).pinfo = VO(2).pinfo(1:2,:);
VO(3).dat = c; VO(3).pinfo = VO(3).pinfo(1:2,:);
if flags.graphics, display_graphics(VF,VO,CP.mn,CP.cv,CP.mg); end;
return;
%=======================================================================
%=======================================================================
function [y1,y2,y3] = affine_transform(x1,x2,x3,M)
y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4);
y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4);
y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4);
return;
%=======================================================================
%=======================================================================
function display_graphics(VF,VS,mn,cv,mg)
% Do the graphics
nb = 3;
spm_figure('Clear','Graphics');
fg = spm_figure('FindWin','Graphics');
if ~isempty(fg),
% Show some text
%-----------------------------------------------------------------------
ax = axes('Position',[0.05 0.8 0.9 0.2],'Visible','off','Parent',fg);
text(0.5,0.80, 'Segmentation','FontSize',16,'FontWeight','Bold',...
'HorizontalAlignment','center','Parent',ax);
text(0,0.65, ['Image: ' spm_str_manip(VF(1).fname,'k50d')],...
'FontSize',14,'FontWeight','Bold','Parent',ax);
text(0,0.40, 'Means:','FontSize',12,'FontWeight','Bold','Parent',ax);
text(0,0.30, 'Std devs:' ,'FontSize',12,'FontWeight','Bold','Parent',ax);
text(0,0.20, 'N vox:','FontSize',12,'FontWeight','Bold','Parent',ax);
for j=1:nb,
text((j+0.5)/(nb+1),0.40, num2str(mn(1,j)),...
'FontSize',12,'FontWeight','Bold',...
'HorizontalAlignment','center','Parent',ax);
text((j+0.5)/(nb+1),0.30, num2str(sqrt(cv(1,1,j))),...
'FontSize',12,'FontWeight','Bold',...
'HorizontalAlignment','center','Parent',ax);
text((j+0.5)/(nb+1),0.20, num2str(mg(1,j)/sum(mg(1,:))),...
'FontSize',12,'FontWeight','Bold',...
'HorizontalAlignment','center','Parent',ax);
end;
if length(VF) > 1,
text(0,0.10,...
'Note: only means and variances for the first image are shown',...
'Parent',ax,'FontSize',12);
end;
M1 = VS(1).mat;
M2 = VF(1).mat;
for i=1:5,
M = spm_matrix([0 0 i*VF(1).dim(3)/6]);
img = spm_slice_vol(VF(1),M,VF(1).dim(1:2),1);
img(1,1) = eps;
ax = axes('Position',...
[0.05 0.75*(1-i/5)+0.05 0.9/(nb+1) 0.75/5],...
'Visible','off','Parent',fg);
imagesc(rot90(img), 'Parent', ax);
set(ax,'Visible','off','DataAspectRatio',[1 1 1]);
for j=1:3,
img = spm_slice_vol(VS(j),M2\M1*M,VF(1).dim(1:2),1);
ax = axes('Position',...
[0.05+j*0.9/(nb+1) 0.75*(1-i/5)+0.05 0.9/(nb+1) 0.75/5],...
'Visible','off','Parent',fg);
image(rot90(img*64), 'Parent', ax);
set(ax,'Visible','off','DataAspectRatio',[1 1 1]);
end;
end;
spm_print;
drawnow;
end;
return;
%=======================================================================
%=======================================================================
function M = get_affine_mapping(VF,VG,aflags)
if ~isempty(VG) & ischar(VG), VG = spm_vol(VG); end;
if ~isempty(VG) & isstruct(VG),
% Affine registration so that a priori images match the image to
% be segmented.
%-----------------------------------------------------------------------
VFS = spm_smoothto8bit(VF(1),aflags.smosrc);
% Scale all images approximately equally
% ---------------------------------------------------------------
for i=1:length(VG),
VG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i));
end;
VFS(1).pinfo(1:2,:) = VFS(1).pinfo(1:2,:)/spm_global(VFS(1));
spm_chi2_plot('Init','Affine Registration','Mean squared difference','Iteration');
flags = struct('sep',aflags.smosrc, 'regtype',aflags.regtype,'WG',[],'globnorm',0,'debug',0);
M = eye(4);
[M,scal] = spm_affreg(VG, VFS, flags, M);
if ~isempty(aflags.weight), flags.WG = spm_vol(aflags.weight); end;
flags.sep = aflags.smosrc/2;
M = spm_affreg(VG, VFS, flags, M,scal);
spm_chi2_plot('Clear');
elseif all(size(VG) == [4 4])
% Assume that second argument is a matrix that will do the job
%-----------------------------------------------------------------------
M = VG;
else
% Assume that image is normalized
%-----------------------------------------------------------------------
M = eye(4);
end
return;
%=======================================================================
%=======================================================================
function [x1,x2,x3] = get_sampling(MM,VF,samp,bb1)
% Voxels to sample during the cluster analysis
%-----------------------------------------------------------------------
% A bounding box for the brain in Talairach space.
%bb = [ [-88 88]' [-122 86]' [-60 95]'];
%c = [bb(1,1) bb(1,2) bb(1,3) 1
% bb(1,1) bb(1,2) bb(2,3) 1
% bb(1,1) bb(2,2) bb(1,3) 1
% bb(1,1) bb(2,2) bb(2,3) 1
% bb(2,1) bb(1,2) bb(1,3) 1
% bb(2,1) bb(1,2) bb(2,3) 1
% bb(2,1) bb(2,2) bb(1,3) 1
% bb(2,1) bb(2,2) bb(2,3) 1]';
%tc = MM\c;
%tc = tc(1:3,:)';
%mx = max(tc);
%mn = min(tc);
%bb = [mn ; mx];
%vx = sqrt(sum(VF(1).mat(1:3,1:3).^2));
%samp = round(max(abs([4 4 4]./vx), [1 1 1]));
%x1 = bb(1,1):samp(1):bb(2,1);
%x2 = bb(1,2):samp(2):bb(2,2);
%x3 = bb(1,3):samp(3):bb(2,3);
%return;
% A bounding box for the brain in Talairach space.
if nargin<4, bb1 = [ [-88 88]' [-122 86]' [-60 95]']; end;
% A mapping from a unit radius sphere to a hyper-ellipse
% that is just enclosed by the bounding box in Talairach
% space.
M0 = [diag(diff(bb1)/2) mean(bb1)';[0 0 0 1]];
% The mapping from voxels to Talairach space is MM,
% so the ellipse in the space of the image becomes:
M0 = MM\M0;
% So to work out the bounding box in the space of the
% image that just encloses the hyper-ellipse.
tmp = M0(1:3,1:3);
tmp = diag(tmp*tmp'/diag(sqrt(diag(tmp*tmp'))));
bb = round([M0(1:3,4)-tmp M0(1:3,4)+tmp])';
bb = min(max(bb,[1 1 1 ; 1 1 1]),[VF(1).dim(1:3) ; VF(1).dim(1:3)]);
% Want to sample about every 3mm
tmp = sqrt(sum(VF(1).mat(1:3,1:3).^2))';
samp = round(max(abs(tmp.^(-1)*samp), [1 1 1]'));
x1 = bb(1,1):samp(1):bb(2,1);
x2 = bb(1,2):samp(2):bb(2,2);
x3 = bb(1,3):samp(3):bb(2,3);
return;
%=======================================================================
%=======================================================================
function [CP,BP,SP] = run_segment(CP,BP,SP,VF,sums,x1,x2,x3)
oll = -Inf;
spm_chi2_plot('Init','Segmenting','Log-likelihood','Iteration #');
for iter = 1:64,
ll= 0;
for pp = 1:length(x3), % Loop over planes
bf = get_bp(BP,x1,x2,x3(pp));
[raw,msk] = get_raw(VF,x1,x2,x3(pp));
s = get_sp(SP,x1,x2,x3(pp));
cor = bf.*raw;
[P,ll0] = get_p(cor,msk,s,sums,CP,bf);
ll = ll + ll0;
CP = update_cp_est(CP,P,cor,msk,pp);
BP = update_bp_est(BP,P,cor,CP,msk,x1,x2,x3(pp));
end;
BP = update_bp(BP);
if iter>1, spm_chi2_plot('Set',ll); end;
%fprintf('\t%g\n', ll);
% Stopping criterion
%-----------------------------------------------------------------------
if iter == 2,
ll2 = ll;
elseif iter > 2 & abs((ll-oll)/(ll-ll2)) < 0.0001
break;
end;
oll = ll;
end;
spm_chi2_plot('Clear');
return;
%=======================================================================
%=======================================================================
function BP = init_bp(VF,co,reg)
m = length(VF);
tmp = sqrt(sum(VF(1).mat(1:3,1:3).^2));
BP.nbas = max(round((VF(1).dim(1:3).*tmp)/co),[1 1 1]);
BP.B1 = spm_dctmtx(VF(1).dim(1),BP.nbas(1));
BP.B2 = spm_dctmtx(VF(1).dim(2),BP.nbas(2));
BP.B3 = spm_dctmtx(VF(1).dim(3),BP.nbas(3));
nbas = BP.nbas;
if prod(BP.nbas)>1,
% Set up a priori covariance matrix
vx = sqrt(sum(VF(1).mat(1:3,1:3).^2));
kx=(pi*((1:nbas(1))'-1)*pi/vx(1)/VF(1).dim(1)*10).^2;
ky=(pi*((1:nbas(2))'-1)*pi/vx(2)/VF(1).dim(2)*10).^2;
kz=(pi*((1:nbas(3))'-1)*pi/vx(3)/VF(1).dim(3)*10).^2;
% Cost function based on sum of squares of 4th derivatives
IC0 = (1*kron(kz.^4,kron(ky.^0,kx.^0)) +...
1*kron(kz.^0,kron(ky.^4,kx.^0)) +...
1*kron(kz.^0,kron(ky.^0,kx.^4)) +...
4*kron(kz.^3,kron(ky.^1,kx.^0)) +...
4*kron(kz.^3,kron(ky.^0,kx.^1)) +...
4*kron(kz.^1,kron(ky.^3,kx.^0)) +...
4*kron(kz.^0,kron(ky.^3,kx.^1)) +...
4*kron(kz.^1,kron(ky.^0,kx.^3)) +...
4*kron(kz.^0,kron(ky.^1,kx.^3)) +...
6*kron(kz.^2,kron(ky.^2,kx.^0)) +...
6*kron(kz.^2,kron(ky.^0,kx.^2)) +...
6*kron(kz.^0,kron(ky.^2,kx.^2)) +...
12*kron(kz.^2,kron(ky.^1,kx.^1)) +...
12*kron(kz.^1,kron(ky.^2,kx.^1)) +...
12*kron(kz.^1,kron(ky.^1,kx.^2)) )*reg;
%IC0(1) = max(IC0);
BP.IC0 = diag(IC0(2:end));
% Initial estimate for intensity modulation field
BP.T = zeros(nbas(1),nbas(2),nbas(3),length(VF));
%-----------------------------------------------------------------------
else
BP.T = zeros([1 1 1 length(VF)]);
BP.IC0 = [];
end;
BP.Alpha = zeros(prod(BP.nbas(1:3)),prod(BP.nbas(1:3)),m);
BP.Beta = zeros(prod(BP.nbas(1:3)),m);
return;
%=======================================================================
%=======================================================================
function BP = update_bp_est(BP,p,cor,CP,msk,x1,x2,x3)
if prod(BP.nbas)<=1, return; end;
B1 = BP.B1(x1,:);
B2 = BP.B2(x2,:);
B3 = BP.B3(x3,:);
for j=1:size(BP.Alpha,3),
cr = cor(:,:,j);
w1 = zeros(size(cr));
w2 = zeros(size(cr));
for i=[1 2 3 4 5 6 7 8],
tmp = p(:,:,i)*CP.cv(j,j,i)^(-1);
w1 = w1 + tmp.*(CP.mn(j,i) - cr);
w2 = w2 + tmp;
end;
wt1 = 1 + cr.*w1;
wt2 = cr.*(cr.*w2 - w1);
wt1(~msk) = 0;
wt2(~msk) = 0;
BP.Beta(:,j) = BP.Beta(:,j) + kron(B3',spm_krutil(wt1,B1,B2,0));
BP.Alpha(:,:,j) = BP.Alpha(:,:,j) + kron(B3'*B3,spm_krutil(wt2,B1,B2,1));
end;
return;
%=======================================================================
%=======================================================================
function BP = update_bp(BP)
if prod(BP.nbas)<=1, return; end;
for j=1:size(BP.Alpha,3),
x = BP.T(:,:,:,j);
x = x(:);
x = x(2:end);
Alpha = BP.Alpha(2:end,2:end,j);
Beta = BP.Beta(2:end,j);
x = (Alpha + BP.IC0)\(Alpha*x + Beta);
BP.T(:,:,:,j) = reshape([0 ; x],BP.nbas(1:3));
BP.Alpha = zeros(size(BP.Alpha));
BP.Beta = zeros(size(BP.Beta));
end;
return;
%=======================================================================
%=======================================================================
function bf = get_bp(BP,x1,x2,x3)
bf = ones(length(x1),length(x2),size(BP.Alpha,3));
if prod(BP.nbas)<=1, return; end;
B1 = BP.B1(x1,:);
B2 = BP.B2(x2,:);
B3 = BP.B3(x3,:);
for i=1:size(BP.Alpha,3),
t = reshape(reshape(BP.T(:,:,:,i),...
BP.nbas(1)*BP.nbas(2),BP.nbas(3))*B3', BP.nbas(1), BP.nbas(2));
bf(:,:,i) = exp(B1*t*B2');
end;
return;
%=======================================================================
%=======================================================================
function [dat,msk] = get_raw(VF,x1,x2,x3)
[X1,X2,X3] = ndgrid(x1,x2,x3);
for i=1:length(VF),
[Y1,Y2,Y3] = affine_transform(X1,X2,X3,VF(i).mat\VF(1).mat);
dat(:,:,i) = spm_sample_vol(VF(i),Y1,Y2,Y3,1);
end;
msk = all(dat,3) & all(isfinite(double(dat)),3);
return;
%=======================================================================
%=======================================================================
function CP = init_cp(VF,x3)
n = 8;
m = length(VF);
p = length(x3);
CP.mom0 = zeros(1,n,p)+eps;
CP.mom1 = zeros(m,n,p);
CP.mom2 = zeros(m,m,n,p)+eps;
% Occasionally the dynamic range of the images is such that many voxels
% all have the same intensity. Adding cv0 is an attempt to improve the
% stability of the algorithm if this occurs. The value 0.083 was obtained
% from var(rand(1000000,1)). It prbably isn't the best way of doing
% things, but it appears to work.
CP.cv0 = zeros(m,m);
for i=1:m,
if spm_type(VF(i).dim(4),'intt'),
CP.cv0(i,i)=0.083*mean(VF(i).pinfo(1,:));
end;
end;
return;
%=======================================================================
%=======================================================================
function CP = shake_cp(CP)
CP.mom0(:,5,:) = CP.mom0(:,1,:);
CP.mom0(:,6,:) = CP.mom0(:,2,:);
CP.mom0(:,7,:) = CP.mom0(:,3,:);
CP.mom1(:,5,:) = CP.mom1(:,1,:);
CP.mom1(:,6,:) = CP.mom1(:,2,:);
CP.mom1(:,7,:) = CP.mom1(:,3,:);
CP.mom1(:,8,:) = 0;
CP.mom2(:,:,5,:) = CP.mom2(:,:,1,:);
CP.mom2(:,:,6,:) = CP.mom2(:,:,2,:);
CP.mom2(:,:,7,:) = CP.mom2(:,:,3,:);
return;
%=======================================================================
%=======================================================================
function CP = update_cp_est(CP,P,dat,msk,p)
m = size(dat,3);
d = size(P);
P = reshape(P,[d(1)*d(2),d(3)]);
dat = reshape(dat,[d(1)*d(2),m]);
P(~msk(:),:) = [];
dat(~msk(:),:) = [];
for i=1:size(CP.mom0,2),
CP.mom0(1,i,p) = sum(P(:,i));
CP.mom1(:,i,p) = sum((P(:,i)*ones(1,m)).*dat)';
CP.mom2(:,:,i,p) = ((P(:,i)*ones(1,m)).*dat)'*dat;
end;
for i=1:size(CP.mom0,2),
CP.mg(1,i) = sum(CP.mom0(1,i,:),3);
CP.mn(:,i) = sum(CP.mom1(:,i,:),3)/CP.mg(1,i);
tmp = (CP.mg(1,i).*CP.mn(:,i))*CP.mn(:,i)';
tmp = tmp-eye(size(tmp))*eps*10000;
CP.cv(:,:,i) = (sum(CP.mom2(:,:,i,:),4) - tmp)/CP.mg(1,i) + CP.cv0;
end;
CP.mg = CP.mg/sum(CP.mg);
return;
%=======================================================================
%=======================================================================
function [p,ll] = get_p(cor,msk,s,sums,CP,bf)
d = [size(cor) 1 1];
n = size(CP.mg,2);
cor = reshape(cor,d(1)*d(2),d(3));
cor = cor(msk,:);
p = zeros(d(1)*d(2),n);
if ~any(msk), p = reshape(p,d(1),d(2),n); ll=0; return; end;
for i=1:n,
amp = 1/sqrt((2*pi)^d(3) * det(CP.cv(:,:,i)));
dst = (cor-ones(size(cor,1),1)*CP.mn(:,i)')/sqrtm(CP.cv(:,:,i));
dst = sum(dst.*dst,2);
tmp = s(:,:,i);
p(msk,i) = (amp*CP.mg(1,i)/sums(i))*exp(-0.5*dst).*tmp(msk) +eps;
end;
sp = sum(p,2);
ll = sum(log(sp(msk).*bf(msk)+eps));
sp(~msk) = Inf;
for i=1:n, p(:,i) = p(:,i)./sp; end;
p = reshape(p,d(1),d(2),n);
return;
%=======================================================================
%=======================================================================
function SP = init_sp(flags,VF,PG)
SP.VB = spm_vol(flags.priors);
MM = get_affine_mapping(VF,PG,flags.affreg);
%VF = spm_vol(PF);
SP.MM = MM*VF(1).mat;
SP.w = 0.98;
return;
%=======================================================================
%=======================================================================
function s = get_sp(SP,x1,x2,x3)
[X1,X2,X3] = ndgrid(x1,x2,x3);
[Y1,Y2,Y3] = affine_transform(X1,X2,X3,SP.VB(1).mat\SP.MM);
w1 = SP.w;
w2 = (1-w1)/2;
s = zeros([size(Y1),4]);
for i=1:3,
s(:,:,i) = spm_sample_vol(SP.VB(i),Y1,Y2,Y3,1)*w1+w2;
end;
s(:,:,4:8) = repmat(abs(1-sum(s(:,:,1:3),3))/5,[1 1 5]);
return;
%=======================================================================
%=======================================================================
function [g,w,c] = get_gwc(VF,BP,SP,CP,sums,wc)
if wc,
VC = VF;
for j=1:length(VF),
[pth,nm,xt,vr] = fileparts(deblank(VF(j).fname));
VC(j).fname = fullfile(pth,['m' nm xt vr]);
VC(j).descrip = 'Bias corrected image';
end;
VC = spm_create_vol(VC);
end;
spm_progress_bar('Init',VF(1).dim(3),'Creating Segmented','planes completed');
x1 = 1:VF(1).dim(1);
x2 = 1:VF(1).dim(2);
x3 = 1:VF(1).dim(3);
g = uint8(0); g(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;
w = uint8(0); w(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;
c = uint8(0); c(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;
for pp=1:length(x3),
bf = get_bp(BP,x1,x2,x3(pp));
[raw,msk] = get_raw(VF,x1,x2,x3(pp));
cor = raw.*bf;
if wc,
for j=1:length(VC),
VC(j) = spm_write_plane(VC(j),cor(:,:,j),pp);
end;
end;
s = get_sp(SP,x1,x2,x3(pp));
p = get_p(cor,msk,s,sums,CP,bf);
g(:,:,pp) = uint8(round(p(:,:,1)*255));
w(:,:,pp) = uint8(round(p(:,:,2)*255));
c(:,:,pp) = uint8(round(p(:,:,3)*255));
spm_progress_bar('Set',pp);
end;
spm_progress_bar('Clear');
if wc, spm_close_vol(VC); end;
return;
%=======================================================================
%=======================================================================
function [g,w,c] = clean_gwc(g,w,c)
b = w;
b(1) = w(1);
% Build a 3x3x3 seperable smoothing kernel
%-----------------------------------------------------------------------
kx=[0.75 1 0.75];
ky=[0.75 1 0.75];
kz=[0.75 1 0.75];
sm=sum(kron(kron(kz,ky),kx))^(1/3);
kx=kx/sm; ky=ky/sm; kz=kz/sm;
% Erosions and conditional dilations
%-----------------------------------------------------------------------
niter = 32;
spm_progress_bar('Init',niter,'Extracting Brain','Iterations completed');
for j=1:niter,
if j>2, th=0.15; else th=0.6; end; % Dilate after two its of erosion.
for i=1:size(b,3),
gp = double(g(:,:,i));
wp = double(w(:,:,i));
bp = double(b(:,:,i))/255;
bp = (bp>th).*(wp+gp);
b(:,:,i) = uint8(round(bp));
end;
spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);
spm_progress_bar('Set',j);
end;
th = 0.05;
for i=1:size(b,3),
gp = double(g(:,:,i))/255;
wp = double(w(:,:,i))/255;
cp = double(c(:,:,i))/255;
bp = double(b(:,:,i))/255;
bp = ((bp>th).*(wp+gp))>th;
g(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps)));
w(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps)));
c(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp))));
end;
spm_progress_bar('Clear');
return;
|
github
|
lcnhappe/happe-master
|
spm_vol_ecat7.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm2/spm_vol_ecat7.m
| 16,814 |
utf_8
|
7c015c4444d187b46b81134cf388711c
|
function V = spm_vol_ecat7(fname,required)
% Get header information etc. for ECAT 7 images.
% FORMAT V = spm_vol_ecat7(fname,required)
% P - an ECAT 7 filename.
% fname - a structure containing image volume information.
% required - an optional text argument specifying which volumes to
% use. The default is '1010001'. Also, the argument
% 'all' will result in all matrices being extracted.
%
% The elements of V are described by the help for spm_vol, except for
% additional fields (V.mh and V.sh) that contains the main- and sub-
% header information.
%
% _______________________________________________________________________
% @(#)spm_vol_ecat7.m 2.12 John Ashburner and Roger Gunn 03/05/23
V = [];
if nargin==1,
required = '1010001';
elseif ischar(required),
else,
if isfinite(required),
required = sprintf('%.7x',16842752+required);
else,
required = 'all';
end;
end;
fp = fopen(fname,'r','ieee-be');
if (fp == -1)
fname = [spm_str_manip(fname,'sr') '.v'];
fp = fopen(fname,'r','ieee-be');
if (fp == -1)
return;
end;
end
mh = ECAT7_mheader(fp);
if ~strcmp(mh.MAGIC_NUMBER,'MATRIX70v') & ~strcmp(mh.MAGIC_NUMBER,'MATRIX71v') & ~strcmp(mh.MAGIC_NUMBER,'MATRIX72v'),
fclose(fp);
return; % Quietly return.
end
if (mh.FILE_TYPE ~= 7)
error(['"' spm_str_manip(fname,'k20d') '" isn''t an image.']);
fclose(fp);
return;
end
list = s7_matlist(fp);
if strcmp(required(1,:),'all'),
matches = find((list(:,4) == 1) | (list(:,4) == 2));
llist = list(matches,:);
else,
for i=1:size(required,1),
matnum = sscanf(required(i,:),'%x');
matches = find( (list(:,1) == matnum) & ((list(:,4) == 1) | (list(:,4) == 2)));
if (size(matches,1) ~= 1)
Error(['"' spm_str_manip(fname,'k20d') '" doesn''t have the required image.']);
fclose(fp);
end;
llist(i,:) = list(matches,:);
end;
end;
frame_num = sscanf(required,'%x')-16842752;
private = struct('mh',[],'sh',[]);
V = struct('fname','','dim',[],'pinfo',[],'mat',[], 'descrip','','n',[],'private',private);
V(:) = [];
for i=1:size(llist,1),
sh = ECAT7_sheader(fp,llist(i,2));
dim = [sh.X_DIMENSION sh.Y_DIMENSION sh.Z_DIMENSION 4];
if ~spm_platform('bigend') & dim(4)~=2, dim(4) = dim(4)*256; end;
pinfo = [sh.SCALE_FACTOR*mh.ECAT_CALIBRATION_FACTOR ; 0 ; 512*llist(i,2)];
dircos = diag([-1 -1 -1]);
step = ([sh.X_PIXEL_SIZE sh.Y_PIXEL_SIZE sh.Z_PIXEL_SIZE]*10);
start = -(dim(1:3)'/2).*step';
mat = [[dircos*diag(step) dircos*start] ; [0 0 0 1]];
[pth,nam,ext] = fileparts(fname);
matname = fullfile(pth,[nam '.mat']);
if exist(matname) == 2,
str=load(matname);
if isfield(str,'mat'),
mat = str.mat;
elseif isfield(str,'M'),
mat = str.M;
end;
end;
V(i).fname = fname;
V(i).dim = dim;
V(i).mat = mat;
V(i).pinfo = pinfo;
V(i).n = llist(i,1)-16842752;
V(i).descrip = sh.ANNOTATION;
V(i).private.mh = mh;
V(i).private.sh = sh;
end;
fclose(fp);
return;
%_______________________________________________________________________
%_______________________________________________________________________
%S7_MATLIST List the available matrixes in an ECAT 7 file.
% LIST = S7_MATLIST(FP) lists the available matrixes
% in the file specified by FP.
%
% Columns in LIST:
% 1 - Matrix identifier.
% 2 - Matrix subheader record number
% 3 - Last record number of matrix data block.
% 4 - Matrix status:
% 1 - exists - rw
% 2 - exists - ro
% 3 - matrix deleted
%
function list = s7_matlist(fp);
% I believe fp should be opened with:
% fp = fopen(filename,'r','ieee-be');
fseek(fp,512,'bof');
block = fread(fp,128,'int');
if (size(block,1) ~= 128) list = []; return; end;
block = reshape(block,4,32);
list = [];
while (block(2,1) ~= 2)
if (block(1,1)+block(4,1) ~= 31)
list = []; return;
end
list = [list block(:,2:32)];
fseek(fp,512*(block(2,1)-1),'bof');
block = fread(fp,128,'int');
if (size(block,1) ~= 128) list = []; return; end;
block = reshape(block,4,32);
end
list = [list block(:,2:(block(4,1)+1))];
list = list';
return;
%_______________________________________________________________________
%_______________________________________________________________________
function SHEADER=ECAT7_sheader(fid,record)
%
% Sub header read routine for ECAT 7 image files
%
% Roger Gunn, 260298
off = (record-1)*512;
status = fseek(fid, off,'bof');
data_type = fread(fid,1,'uint16',0);
num_dimensions = fread(fid,1,'uint16',0);
x_dimension = fread(fid,1,'uint16',0);
y_dimension = fread(fid,1,'uint16',0);
z_dimension = fread(fid,1,'uint16',0);
x_offset = fread(fid,1,'float32',0);
y_offset = fread(fid,1,'float32',0);
z_offset = fread(fid,1,'float32',0);
recon_zoom = fread(fid,1,'float32',0);
scale_factor = fread(fid,1,'float32',0);
image_min = fread(fid,1,'int16',0);
image_max = fread(fid,1,'int16',0);
x_pixel_size = fread(fid,1,'float32',0);
y_pixel_size = fread(fid,1,'float32',0);
z_pixel_size = fread(fid,1,'float32',0);
frame_duration = fread(fid,1,'uint32',0);
frame_start_time = fread(fid,1,'uint32',0);
filter_code = fread(fid,1,'uint16',0);
x_resolution = fread(fid,1,'float32',0);
y_resolution = fread(fid,1,'float32',0);
z_resolution = fread(fid,1,'float32',0);
num_r_elements = fread(fid,1,'float32',0);
num_angles = fread(fid,1,'float32',0);
z_rotation_angle = fread(fid,1,'float32',0);
decay_corr_fctr = fread(fid,1,'float32',0);
corrections_applied = fread(fid,1,'uint32',0);
gate_duration = fread(fid,1,'uint32',0);
r_wave_offset = fread(fid,1,'uint32',0);
num_accepted_beats = fread(fid,1,'uint32',0);
filter_cutoff_frequency = fread(fid,1,'float32',0);
filter_resolution = fread(fid,1,'float32',0);
filter_ramp_slope = fread(fid,1,'float32',0);
filter_order = fread(fid,1,'uint16',0);
filter_scatter_fraction = fread(fid,1,'float32',0);
filter_scatter_slope = fread(fid,1,'float32',0);
annotation = fread(fid,40,'char',0);
mt_1_1 = fread(fid,1,'float32',0);
mt_1_2 = fread(fid,1,'float32',0);
mt_1_3 = fread(fid,1,'float32',0);
mt_2_1 = fread(fid,1,'float32',0);
mt_2_2 = fread(fid,1,'float32',0);
mt_2_3 = fread(fid,1,'float32',0);
mt_3_1 = fread(fid,1,'float32',0);
mt_3_2 = fread(fid,1,'float32',0);
mt_3_3 = fread(fid,1,'float32',0);
rfilter_cutoff = fread(fid,1,'float32',0);
rfilter_resolution = fread(fid,1,'float32',0);
rfilter_code = fread(fid,1,'uint16',0);
rfilter_order = fread(fid,1,'uint16',0);
zfilter_cutoff = fread(fid,1,'float32',0);
zfilter_resolution = fread(fid,1,'float32',0);
zfilter_code = fread(fid,1,'uint16',0);
zfilter_order = fread(fid,1,'uint16',0);
mt_4_1 = fread(fid,1,'float32',0);
mt_4_2 = fread(fid,1,'float32',0);
mt_4_3 = fread(fid,1,'float32',0);
scatter_type = fread(fid,1,'uint16',0);
recon_type = fread(fid,1,'uint16',0);
recon_views = fread(fid,1,'uint16',0);
fill = fread(fid,1,'uint16',0);
annotation = deblank(char(annotation.*(annotation>0))');
SHEADER = struct('DATA_TYPE', data_type, ...
'NUM_DIMENSIONS', num_dimensions, ...
'X_DIMENSION', x_dimension, ...
'Y_DIMENSION', y_dimension, ...
'Z_DIMENSION', z_dimension, ...
'X_OFFSET', x_offset, ...
'Y_OFFSET', y_offset, ...
'Z_OFFSET', z_offset, ...
'RECON_ZOOM', recon_zoom, ...
'SCALE_FACTOR', scale_factor, ...
'IMAGE_MIN', image_min, ...
'IMAGE_MAX', image_max, ...
'X_PIXEL_SIZE', x_pixel_size, ...
'Y_PIXEL_SIZE', y_pixel_size, ...
'Z_PIXEL_SIZE', z_pixel_size, ...
'FRAME_DURATION', frame_duration, ...
'FRAME_START_TIME', frame_start_time, ...
'FILTER_CODE', filter_code, ...
'X_RESOLUTION', x_resolution, ...
'Y_RESOLUTION', y_resolution, ...
'Z_RESOLUTION', z_resolution, ...
'NUM_R_ELEMENTS', num_r_elements, ...
'NUM_ANGLES', num_angles, ...
'Z_ROTATION_ANGLE', z_rotation_angle, ...
'DECAY_CORR_FCTR', decay_corr_fctr, ...
'CORRECTIONS_APPLIED', corrections_applied, ...
'GATE_DURATION', gate_duration, ...
'R_WAVE_OFFSET', r_wave_offset, ...
'NUM_ACCEPTED_BEATS', num_accepted_beats, ...
'FILTER_CUTOFF_FREQUENCY', filter_cutoff_frequency, ...
'FILTER_RESOLUTION', filter_resolution, ...
'FILTER_RAMP_SLOPE', filter_ramp_slope, ...
'FILTER_ORDER', filter_order, ...
'FILTER_SCATTER_CORRECTION', filter_scatter_fraction, ...
'FILTER_SCATTER_SLOPE', filter_scatter_slope, ...
'ANNOTATION', annotation, ...
'MT_1_1', mt_1_1, ...
'MT_1_2', mt_1_2, ...
'MT_1_3', mt_1_3, ...
'MT_2_1', mt_2_1, ...
'MT_2_2', mt_2_2, ...
'MT_2_3', mt_2_3, ...
'MT_3_1', mt_3_1, ...
'MT_3_2', mt_3_2, ...
'MT_3_3', mt_3_3, ...
'RFILTER_CUTOFF', rfilter_cutoff, ...
'RFILTER_RESOLUTION', rfilter_resolution, ...
'RFILTER_CODE', rfilter_code, ...
'RFILTER_ORDER', rfilter_order, ...
'ZFILTER_CUTOFF', zfilter_cutoff, ...
'ZFILTER_RESOLUTION', zfilter_resolution, ...
'ZFILTER_CODE', zfilter_code, ...
'ZFILTER_ORDER', zfilter_order, ...
'MT_4_1', mt_4_1, ...
'MT_4_2', mt_4_2, ...
'MT_4_3', mt_4_3, ...
'SCATTER_TYPE', scatter_type, ...
'RECON_TYPE', recon_type, ...
'RECON_VIEWS', recon_views, ...
'FILL', fill);
return;
%_______________________________________________________________________
function [MHEADER]=ECAT7_mheader(fid)
%
% Main header read routine for ECAT 7 image files
%
% Roger Gunn, 260298
status = fseek(fid, 0,'bof');
magic_number = fread(fid,14,'char',0);
original_file_name = fread(fid,32,'char',0);
sw_version = fread(fid,1,'uint16',0);
system_type = fread(fid,1,'uint16',0);
file_type = fread(fid,1,'uint16',0);
serial_number = fread(fid,10,'char',0);
scan_start_time = fread(fid,1,'uint32',0);
isotope_name = fread(fid,8,'char',0);
isotope_halflife = fread(fid,1,'float32',0);
radiopharmaceutical = fread(fid,32,'char',0);
gantry_tilt = fread(fid,1,'float32',0);
gantry_rotation = fread(fid,1,'float32',0);
bed_elevation = fread(fid,1,'float32',0);
intrinsic_tilt = fread(fid,1,'float32',0);
wobble_speed = fread(fid,1,'uint16',0);
transm_source_type = fread(fid,1,'uint16',0);
distance_scanned = fread(fid,1,'float32',0);
transaxial_fov = fread(fid,1,'float32',0);
angular_compression = fread(fid,1,'uint16',0);
coin_samp_mode = fread(fid,1,'uint16',0);
axial_samp_mode = fread(fid,1,'uint16',0);
ecat_calibration_factor = fread(fid,1,'float32',0);
calibration_units = fread(fid,1,'uint16',0);
calibration_units_type = fread(fid,1,'uint16',0);
compression_code = fread(fid,1,'uint16',0);
study_type = fread(fid,12,'char',0);
patient_id = fread(fid,16,'char',0);
patient_name = fread(fid,32,'char',0);
patient_sex = fread(fid,1,'char',0);
patient_dexterity = fread(fid,1,'char',0);
patient_age = fread(fid,1,'float32',0);
patient_height = fread(fid,1,'float32',0);
patient_weight = fread(fid,1,'float32',0);
patient_birth_date = fread(fid,1,'uint32',0);
physician_name = fread(fid,32,'char',0);
operator_name = fread(fid,32,'char',0);
study_description = fread(fid,32,'char',0);
acquisition_type = fread(fid,1,'uint16',0);
patient_orientation = fread(fid,1,'uint16',0);
facility_name = fread(fid,20,'char',0);
num_planes = fread(fid,1,'uint16',0);
num_frames = fread(fid,1,'uint16',0);
num_gates = fread(fid,1,'uint16',0);
num_bed_pos = fread(fid,1,'uint16',0);
init_bed_position = fread(fid,1,'float32',0);
bed_position = zeros(15,1);
for bed=1:15,
bed_position(bed) = fread(fid,1,'float32',0);
end;
plane_separation = fread(fid,1,'float32',0);
lwr_sctr_thres = fread(fid,1,'uint16',0);
lwr_true_thres = fread(fid,1,'uint16',0);
upr_true_thres = fread(fid,1,'uint16',0);
user_process_code = fread(fid,10,'char',0);
acquisition_mode = fread(fid,1,'uint16',0);
bin_size = fread(fid,1,'float32',0);
branching_fraction = fread(fid,1,'float32',0);
dose_start_time = fread(fid,1,'uint32',0);
dosage = fread(fid,1,'float32',0);
well_counter_corr_factor = fread(fid,1,'float32',0);
data_units = fread(fid,32,'char',0);
septa_state = fread(fid,1,'uint16',0);
fill = fread(fid,1,'uint16',0);
magic_number = deblank(char(magic_number.*(magic_number>32))');
original_file_name = deblank(char(original_file_name.*(original_file_name>0))');
serial_number = deblank(char(serial_number.*(serial_number>0))');
isotope_name = deblank(char(isotope_name.*(isotope_name>0))');
radiopharmaceutical = deblank(char(radiopharmaceutical.*(radiopharmaceutical>0))');
study_type = deblank(char(study_type.*(study_type>0))');
patient_id = deblank(char(patient_id.*(patient_id>0))');
patient_name = deblank(char(patient_name.*(patient_name>0))');
patient_sex = deblank(char(patient_sex.*(patient_sex>0))');
patient_dexterity = deblank(char(patient_dexterity.*(patient_dexterity>0))');
physician_name = deblank(char(physician_name.*(physician_name>0))');
operator_name = deblank(char(operator_name.*(operator_name>0))');
study_description = deblank(char(study_description.*(study_description>0))');
facility_name = deblank(char(facility_name.*(facility_name>0))');
user_process_code = deblank(char(user_process_code.*(user_process_code>0))');
data_units = deblank(char(data_units.*(data_units>0))');
MHEADER = struct('MAGIC_NUMBER', magic_number, ...
'ORIGINAL_FILE_NAME', original_file_name, ...
'SW_VERSION', sw_version, ...
'SYSTEM_TYPE', system_type, ...
'FILE_TYPE', file_type, ...
'SERIAL_NUMBER', serial_number, ...
'SCAN_START_TIME', scan_start_time, ...
'ISOTOPE_NAME', isotope_name, ...
'ISOTOPE_HALFLIFE', isotope_halflife, ...
'RADIOPHARMACEUTICAL', radiopharmaceutical, ...
'GANTRY_TILT', gantry_tilt, ...
'GANTRY_ROTATION', gantry_rotation, ...
'BED_ELEVATION', bed_elevation, ...
'INTRINSIC_TILT', intrinsic_tilt, ...
'WOBBLE_SPEED', wobble_speed, ...
'TRANSM_SOURCE_TYPE', transm_source_type, ...
'DISTANCE_SCANNED', distance_scanned, ...
'TRANSAXIAL_FOV', transaxial_fov, ...
'ANGULAR_COMPRESSION', angular_compression, ...
'COIN_SAMP_MODE', coin_samp_mode, ...
'AXIAL_SAMP_MODE', axial_samp_mode, ...
'ECAT_CALIBRATION_FACTOR', ecat_calibration_factor, ...
'CALIBRATION_UNITS', calibration_units, ...
'CALIBRATION_UNITS_TYPE', calibration_units_type, ...
'COMPRESSION_CODE', compression_code, ...
'STUDY_TYPE', study_type, ...
'PATIENT_ID', patient_id, ...
'PATIENT_NAME', patient_name, ...
'PATIENT_SEX', patient_sex, ...
'PATIENT_DEXTERITY', patient_dexterity, ...
'PATIENT_AGE', patient_age, ...
'PATIENT_HEIGHT', patient_height, ...
'PATIENT_WEIGHT', patient_weight, ...
'PATIENT_BIRTH_DATE', patient_birth_date, ...
'PHYSICIAN_NAME', physician_name, ...
'OPERATOR_NAME', operator_name, ...
'STUDY_DESCRIPTION', study_description, ...
'ACQUISITION_TYPE', acquisition_type, ...
'PATIENT_ORIENTATION', patient_orientation, ...
'FACILITY_NAME', facility_name, ...
'NUM_PLANES', num_planes, ...
'NUM_FRAMES', num_frames, ...
'NUM_GATES', num_gates, ...
'NUM_BED_POS', num_bed_pos, ...
'INIT_BED_POSITION', init_bed_position, ...
'BED_POSITION', bed_position, ...
'PLANE_SEPARATION', plane_separation, ...
'LWR_SCTR_THRES', lwr_sctr_thres, ...
'LWR_TRUE_THRES', lwr_true_thres, ...
'UPR_TRUE_THRES', upr_true_thres, ...
'USER_PROCESS_CODE', user_process_code, ...
'ACQUISITION_MODE', acquisition_mode, ...
'BIN_SIZE', bin_size, ...
'BRANCHING_FRACTION', branching_fraction, ...
'DOSE_START_TIME', dose_start_time, ...
'DOSAGE', dosage, ...
'WELL_COUNTER_CORR_FACTOR', well_counter_corr_factor, ...
'DATA_UNITS', data_units, ...
'SEPTA_STATE', septa_state, ...
'FILL', fill);
return;
%_______________________________________________________________________
|
github
|
lcnhappe/happe-master
|
read_wobj.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/wavefront/read_wobj.m
| 14,065 |
utf_8
|
9ba67412c5fae158393557fd39a68306
|
function OBJ=read_wobj(fullfilename)
% Read the objects from a Wavefront OBJ file
%
% OBJ=read_wobj(filename);
%
% OBJ struct containing:
%
% OBJ.vertices : Vertices coordinates
% OBJ.vertices_texture: Texture coordinates
% OBJ.vertices_normal : Normal vectors
% OBJ.vertices_point : Vertice data used for points and lines
% OBJ.material : Parameters from external .MTL file, will contain parameters like
% newmtl, Ka, Kd, Ks, illum, Ns, map_Ka, map_Kd, map_Ks,
% example of an entry from the material object:
% OBJ.material(i).type = newmtl
% OBJ.material(i).data = 'vase_tex'
% OBJ.objects : Cell object with all objects in the OBJ file,
% example of a mesh object:
% OBJ.objects(i).type='f'
% OBJ.objects(i).data.vertices: [n x 3 double]
% OBJ.objects(i).data.texture: [n x 3 double]
% OBJ.objects(i).data.normal: [n x 3 double]
%
% Example,
% OBJ=read_wobj('examples\example10.obj');
% FV.vertices=OBJ.vertices;
% FV.faces=OBJ.objects(3).data.vertices;
% figure, patch(FV,'facecolor',[1 0 0]); camlight
%
% Function is written by D.Kroon University of Twente (June 2010)
verbose=true;
if(exist('fullfilename','var')==0)
[filename, filefolder] = uigetfile('*.obj', 'Read obj-file');
fullfilename = [filefolder filename];
end
filefolder = fileparts( fullfilename);
if(verbose),disp(['Reading Object file : ' fullfilename]); end
% Read the DI3D OBJ textfile to a cell array
file_words = file2cellarray( fullfilename);
% Remove empty cells, merge lines split by "\" and convert strings with values to double
[ftype fdata]= fixlines(file_words);
% Vertex data
vertices=[]; nv=0;
vertices_texture=[]; nvt=0;
vertices_point=[]; nvp=0;
vertices_normal=[]; nvn=0;
material=[];
% Surface data
no=0;
% Loop through the Wavefront object file
for iline=1:length(ftype)
if(mod(iline,10000)==0),
if(verbose),disp(['Lines processed : ' num2str(iline)]); end
end
type=ftype{iline}; data=fdata{iline};
% Switch on data type line
switch(type)
case{'mtllib'}
if(iscell(data))
datanew=[];
for i=1:length(data)
datanew=[datanew data{i}];
if(i<length(data)), datanew=[datanew ' ']; end
end
data=datanew;
end
filename_mtl=fullfile(filefolder,data);
material=readmtl(filename_mtl,verbose);
case('v') % vertices
nv=nv+1;
if(length(data)==3)
% Reserve block of memory
if(mod(nv,10000)==1), vertices(nv+1:nv+10001,1:3)=0; end
% Add to vertices list X Y Z
vertices(nv,1:3)=data;
else
% Reserve block of memory
if(mod(nv,10000)==1), vertices(nv+1:nv+10001,1:4)=0; end
% Add to vertices list X Y Z W
vertices(nv,1:4)=data;
end
case('vp')
% Specifies a point in the parameter space of curve or surface
nvp=nvp+1;
if(length(data)==1)
% Reserve block of memory
if(mod(nvp,10000)==1), vertices_point(nvp+1:nvp+10001,1)=0; end
% Add to vertices point list U
vertices_point(nvp,1)=data;
elseif(length(data)==2)
% Reserve block of memory
if(mod(nvp,10000)==1), vertices_point(nvp+1:nvp+10001,1:2)=0; end
% Add to vertices point list U V
vertices_point(nvp,1:2)=data;
else
% Reserve block of memory
if(mod(nvp,10000)==1), vertices_point(nvp+1:nvp+10001,1:3)=0; end
% Add to vertices point list U V W
vertices_point(nvp,1:3)=data;
end
case('vn')
% A normal vector
nvn=nvn+1; if(mod(nvn,10000)==1), vertices_normal(nvn+1:nvn+10001,1:3)=0; end
% Add to vertices list I J K
vertices_normal(nvn,1:3)=data;
case('vt')
% Vertices Texture Coordinate in photo
% U V W
nvt=nvt+1;
if(length(data)==1)
% Reserve block of memory
if(mod(nvt,10000)==1), vertices_texture(nvt+1:nvt+10001,1)=0; end
% Add to vertices texture list U
vertices_texture(nvt,1)=data;
elseif(length(data)==2)
% Reserve block of memory
if(mod(nvt,10000)==1), vertices_texture(nvt+1:nvt+10001,1:2)=0; end
% Add to vertices texture list U V
vertices_texture(nvt,1:2)=data;
else
% Reserve block of memory
if(mod(nvt,10000)==1), vertices_texture(nvt+1:nvt+10001,1:3)=0; end
% Add to vertices texture list U V W
vertices_texture(nvt,1:3)=data;
end
case('l')
no=no+1; if(mod(no,10000)==1), objects(no+10001).data=0; end
array_vertices=[];
array_texture=[];
for i=1:length(data),
switch class(data)
case 'cell'
tvals=str2double(stringsplit(data{i},'/'));
case 'string'
tvals=str2double(stringsplit(data,'/'));
otherwise
tvals=data(i);
end
val=tvals(1);
if(val<0), val=val+1+nv; end
array_vertices(i)=val;
if(length(tvals)>1),
val=tvals(2);
if(val<0), val=val+1+nvt; end
array_texture(i)=val;
end
end
objects(no).type='l';
objects(no).data.vertices=array_vertices;
objects(no).data.texture=array_texture;
case('f')
no=no+1; if(mod(no,10000)==1), objects(no+10001).data=0; end
array_vertices=[];
array_texture=[];
array_normal=[];
for i=1:length(data);
switch class(data)
case 'cell'
tvals=str2double(stringsplit(data{i},'/'));
case 'string'
tvals=str2double(stringsplit(data,'/'));
otherwise
tvals=data(i);
end
val=tvals(1);
if(val<0), val=val+1+nv; end
array_vertices(i)=val;
if(length(tvals)>1),
if(isfinite(tvals(2)))
val=tvals(2);
if(val<0), val=val+1+nvt; end
array_texture(i)=val;
end
end
if(length(tvals)>2),
val=tvals(3);
if(val<0), val=val+1+nvn; end
array_normal(i)=val;
end
end
% A face of more than 3 indices is always split into
% multiple faces of only 3 indices.
objects(no).type='f';
findex=1:min (3,length(array_vertices));
objects(no).data = [];
objects(no).data.vertices=array_vertices(findex);
if(~isempty(array_texture)),objects(no).data.texture=array_texture(findex); end
if(~isempty(array_normal)),objects(no).data.normal=array_normal(findex); end
for i=1:length(array_vertices)-3;
no=no+1; if(mod(no,10000)==1), objects(no+10001).data=0; end
findex=[1 2+i 3+i];
findex(findex>length(array_vertices))=findex(findex>length(array_vertices))-length(array_vertices);
objects(no).type='f';
objects(no).data.vertices=array_vertices(findex);
if(~isempty(array_texture)),objects(no).data.texture=array_texture(findex); end
if(~isempty(array_normal)),objects(no).data.normal=array_normal(findex); end
end
case{'#','$'}
% Comment
tline=' %';
if(iscell(data))
for i=1:length(data), tline=[tline ' ' data{i}]; end
else
tline=[tline data];
end
if(verbose), disp(tline); end
case{''}
otherwise
no=no+1;
if(mod(no,10000)==1), objects(no+10001).data=0; end
objects(no).type=type;
objects(no).data=data;
end
end
% Initialize new object list, which will contain the "collapsed" objects
objects2(no).data=0;
index=0;
i=0;
while (i<no), i=i+1;
type=objects(i).type;
% First face found
if((length(type)==1)&&(type(1)=='f'))
% Get number of faces
for j=i:no
type=objects(j).type;
if((length(type)~=1)||(type(1)~='f'))
j=j-1; break;
end
end
numfaces=(j-i)+1;
index=index+1;
objects2(index).type='f';
% Process last face first to allocate memory
objects2(index).data.vertices(numfaces,:)= objects(i).data.vertices;
if(isfield(objects(i).data,'texture'))
objects2(index).data.texture(numfaces,:) = objects(i).data.texture;
else
objects2(index).data.texture=[];
end
if(isfield(objects(i).data,'normal'))
objects2(index).data.normal(numfaces,:) = objects(i).data.normal;
else
objects2(index).data.normal=[];
end
% All faces to arrays
for k=1:numfaces
objects2(index).data.vertices(k,:)= objects(i+k-1).data.vertices;
if(isfield(objects(i).data,'texture'))
objects2(index).data.texture(k,:) = objects(i+k-1).data.texture;
end
if(isfield(objects(i).data,'normal'))
objects2(index).data.normal(k,:) = objects(i+k-1).data.normal;
end
end
i=j;
else
index=index+1;
objects2(index).type=objects(i).type;
objects2(index).data=objects(i).data;
end
end
% Add all data to output struct
OBJ.objects=objects2(1:index);
OBJ.material=material;
OBJ.vertices=vertices(1:nv,:);
OBJ.vertices_point=vertices_point(1:nvp,:);
OBJ.vertices_normal=vertices_normal(1:nvn,:);
OBJ.vertices_texture=vertices_texture(1:nvt,:);
if(verbose),disp('Finished Reading Object file'); end
function twords=stringsplit(tline,tchar)
% Get start and end position of all "words" separated by a char
i=find(tline(2:end-1)==tchar)+1; i_start=[1 i+1]; i_end=[i-1 length(tline)];
% Create a cell array of the words
twords=cell(1,length(i_start)); for j=1:length(i_start), twords{j}=tline(i_start(j):i_end(j)); end
function file_words=file2cellarray(filename)
% Open a DI3D OBJ textfile
fid=fopen(filename,'r');
file_text=fread(fid, inf, 'uint8=>char')';
fclose(fid);
file_lines = regexp(file_text, '\n+', 'split');
file_words = regexp(file_lines, '\s+', 'split');
function [ftype fdata]=fixlines(file_words)
ftype=cell(size(file_words));
fdata=cell(size(file_words));
iline=0; jline=0;
while(iline<length(file_words))
iline=iline+1;
twords=removeemptycells(file_words{iline});
if(~isempty(twords))
% Add next line to current line when line end with '\'
while(strcmp(twords{end},'\')&&iline<length(file_words))
iline=iline+1;
twords(end)=[];
twords=[twords removeemptycells(file_words{iline})];
end
% Values to double
type=twords{1};
stringdold=true;
j=0;
switch(type)
case{'#','$'}
for i=2:length(twords)
j=j+1; twords{j}=twords{i};
end
otherwise
for i=2:length(twords)
str=twords{i};
if strcmpi(str, 'nan')
val=NaN;
stringd=false;
else
val=str2double(str);
stringd=~isfinite(val);
end
if(stringd)
j=j+1; twords{j}=str;
else
if(stringdold)
j=j+1; twords{j}=val;
else
twords{j}=[twords{j} val];
end
end
stringdold=stringd;
end
end
twords(j+1:end)=[];
jline=jline+1;
ftype{jline}=type;
if(length(twords)==1), twords=twords{1}; end
fdata{jline}=twords;
end
end
ftype(jline+1:end)=[];
fdata(jline+1:end)=[];
function b=removeemptycells(a)
j=0; b={};
for i=1:length(a);
if(~isempty(a{i})),j=j+1; b{j}=a{i}; end;
end
function objects=readmtl(filename_mtl,verbose)
if(verbose),disp(['Reading Material file : ' filename_mtl]); end
file_words=file2cellarray(filename_mtl);
% Remove empty cells, merge lines split by "\" and convert strings with values to double
[ftype fdata]= fixlines(file_words);
% Surface data
objects.type(length(ftype))=0;
objects.data(length(ftype))=0;
no=0;
% Loop through the Wavefront object file
for iline=1:length(ftype)
type=ftype{iline}; data=fdata{iline};
% Switch on data type line
switch(type)
case{'#','$'}
% Comment
tline=' %';
if(iscell(data))
for i=1:length(data), tline=[tline ' ' data{i}]; end
else
tline=[tline data];
end
if(verbose), disp(tline); end
case{''}
otherwise
no=no+1;
if(mod(no,10000)==1), objects(no+10001).data=0; end
objects(no).type=type;
objects(no).data=data;
end
end
objects=objects(1:no);
if(verbose),disp('Finished Reading Material file'); end
|
github
|
lcnhappe/happe-master
|
write_wobj.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/wavefront/write_wobj.m
| 7,933 |
utf_8
|
96f334af246b0a305d8e8d354ddc7bba
|
function write_wobj(OBJ,fullfilename)
% Write objects to a Wavefront OBJ file
%
% write_wobj(OBJ,filename);
%
% OBJ struct containing:
%
% OBJ.vertices : Vertices coordinates
% OBJ.vertices_texture: Texture coordinates
% OBJ.vertices_normal : Normal vectors
% OBJ.vertices_point : Vertice data used for points and lines
% OBJ.material : Parameters from external .MTL file, will contain parameters like
% newmtl, Ka, Kd, Ks, illum, Ns, map_Ka, map_Kd, map_Ks,
% example of an entry from the material object:
% OBJ.material(i).type = newmtl
% OBJ.material(i).data = 'vase_tex'
% OBJ.objects : Cell object with all objects in the OBJ file,
% example of a mesh object:
% OBJ.objects(i).type='f'
% OBJ.objects(i).data.vertices: [n x 3 double]
% OBJ.objects(i).data.texture: [n x 3 double]
% OBJ.objects(i).data.normal: [n x 3 double]
%
% example reading/writing,
%
% OBJ=read_wobj('examples\example10.obj');
% write_wobj(OBJ,'test.obj');
%
% example isosurface to obj-file,
%
% % Load MRI scan
% load('mri','D'); D=smooth3(squeeze(D));
% % Make iso-surface (Mesh) of skin
% FV=isosurface(D,1);
% % Calculate Iso-Normals of the surface
% N=isonormals(D,FV.vertices);
% L=sqrt(N(:,1).^2+N(:,2).^2+N(:,3).^2)+eps;
% N(:,1)=N(:,1)./L; N(:,2)=N(:,2)./L; N(:,3)=N(:,3)./L;
% % Display the iso-surface
% figure, patch(FV,'facecolor',[1 0 0],'edgecolor','none'); view(3);camlight
% % Invert Face rotation
% FV.faces=[FV.faces(:,3) FV.faces(:,2) FV.faces(:,1)];
%
% % Make a material structure
% material(1).type='newmtl';
% material(1).data='skin';
% material(2).type='Ka';
% material(2).data=[0.8 0.4 0.4];
% material(3).type='Kd';
% material(3).data=[0.8 0.4 0.4];
% material(4).type='Ks';
% material(4).data=[1 1 1];
% material(5).type='illum';
% material(5).data=2;
% material(6).type='Ns';
% material(6).data=27;
%
% % Make OBJ structure
% clear OBJ
% OBJ.vertices = FV.vertices;
% OBJ.vertices_normal = N;
% OBJ.material = material;
% OBJ.objects(1).type='g';
% OBJ.objects(1).data='skin';
% OBJ.objects(2).type='usemtl';
% OBJ.objects(2).data='skin';
% OBJ.objects(3).type='f';
% OBJ.objects(3).data.vertices=FV.faces;
% OBJ.objects(3).data.normal=FV.faces;
% write_wobj(OBJ,'skinMRI.obj');
%
% Function is written by D.Kroon University of Twente (June 2010)
if(exist('fullfilename','var')==0)
[filename, filefolder] = uiputfile('*.obj', 'Write obj-file');
fullfilename = [filefolder filename];
end
[filefolder,filename] = fileparts( fullfilename);
comments=cell(1,4);
comments{1}=' Produced by Matlab Write Wobj exporter ';
comments{2}='';
fid = fopen(fullfilename,'w');
write_comment(fid,comments);
if(isfield(OBJ,'material')&&~isempty(OBJ.material))
filename_mtl=fullfile(filefolder,[filename '.mtl']);
fprintf(fid,'mtllib %s\n',filename_mtl);
write_MTL_file(filename_mtl,OBJ.material)
end
if(isfield(OBJ,'vertices')&&~isempty(OBJ.vertices))
write_vertices(fid,OBJ.vertices,'v');
end
if(isfield(OBJ,'vertices_point')&&~isempty(OBJ.vertices_point))
write_vertices(fid,OBJ.vertices_point,'vp');
end
if(isfield(OBJ,'vertices_normal')&&~isempty(OBJ.vertices_normal))
write_vertices(fid,OBJ.vertices_normal,'vn');
end
if(isfield(OBJ,'vertices_texture')&&~isempty(OBJ.vertices_texture))
write_vertices(fid,OBJ.vertices_texture,'vt');
end
for i=1:length(OBJ.objects)
type=OBJ.objects(i).type;
data=OBJ.objects(i).data;
switch(type)
case 'usemtl'
fprintf(fid,'usemtl %s\n',data);
case 'f'
check1=(isfield(OBJ,'vertices_texture')&&~isempty(OBJ.vertices_texture));
check2=(isfield(OBJ,'vertices_normal')&&~isempty(OBJ.vertices_normal));
if(check1&&check2)
for j=1:size(data.vertices,1)
fprintf(fid,'f %d/%d/%d',data.vertices(j,1),data.texture(j,1),data.normal(j,1));
fprintf(fid,' %d/%d/%d', data.vertices(j,2),data.texture(j,2),data.normal(j,2));
fprintf(fid,' %d/%d/%d\n', data.vertices(j,3),data.texture(j,3),data.normal(j,3));
end
elseif(check1)
for j=1:size(data.vertices,1)
fprintf(fid,'f %d/%d',data.vertices(j,1),data.texture(j,1));
fprintf(fid,' %d/%d', data.vertices(j,2),data.texture(j,2));
fprintf(fid,' %d/%d\n', data.vertices(j,3),data.texture(j,3));
end
elseif(check2)
for j=1:size(data.vertices,1)
fprintf(fid,'f %d//%d',data.vertices(j,1),data.normal(j,1));
fprintf(fid,' %d//%d', data.vertices(j,2),data.normal(j,2));
fprintf(fid,' %d//%d\n', data.vertices(j,3),data.normal(j,3));
end
else
for j=1:size(data.vertices,1)
fprintf(fid,'f %d %d %d\n',data.vertices(j,1),data.vertices(j,2),data.vertices(j,3));
end
end
otherwise
fprintf(fid,'%s ',type);
if(iscell(data))
for j=1:length(data)
if(ischar(data{j}))
fprintf(fid,'%s ',data{j});
else
fprintf(fid,'%0.5g ',data{j});
end
end
elseif(ischar(data))
fprintf(fid,'%s ',data);
else
for j=1:length(data)
fprintf(fid,'%0.5g ',data(j));
end
end
fprintf(fid,'\n');
end
end
fclose(fid);
function write_MTL_file(filename,material)
fid = fopen(filename,'w');
comments=cell(1,2);
comments{1}=' Produced by Matlab Write Wobj exporter ';
comments{2}='';
write_comment(fid,comments);
for i=1:length(material)
type=material(i).type;
data=material(i).data;
switch(type)
case('newmtl')
fprintf(fid,'%s ',type);
fprintf(fid,'%s\n',data);
case{'Ka','Kd','Ks'}
fprintf(fid,'%s ',type);
fprintf(fid,'%5.5f %5.5f %5.5f\n',data);
case('illum')
fprintf(fid,'%s ',type);
fprintf(fid,'%d\n',data);
case {'Ns','Tr','d'}
fprintf(fid,'%s ',type);
fprintf(fid,'%5.5f\n',data);
otherwise
fprintf(fid,'%s ',type);
if(iscell(data))
for j=1:length(data)
if(ischar(data{j}))
fprintf(fid,'%s ',data{j});
else
fprintf(fid,'%0.5g ',data{j});
end
end
elseif(ischar(data))
fprintf(fid,'%s ',data);
else
for j=1:length(data)
fprintf(fid,'%0.5g ',data(j));
end
end
fprintf(fid,'\n');
end
end
comments=cell(1,2);
comments{1}='';
comments{2}=' EOF';
write_comment(fid,comments);
fclose(fid);
function write_comment(fid,comments)
for i=1:length(comments), fprintf(fid,'# %s\n',comments{i}); end
function write_vertices(fid,V,type)
switch size(V,2)
case 1
for i=1:size(V,1)
fprintf(fid,'%s %5.5f\n', type, V(i,1));
end
case 2
for i=1:size(V,1)
fprintf(fid,'%s %5.5f %5.5f\n', type, V(i,1), V(i,2));
end
case 3
for i=1:size(V,1)
fprintf(fid,'%s %5.5f %5.5f %5.5f\n', type, V(i,1), V(i,2), V(i,3));
end
otherwise
end
switch(type)
case 'v'
fprintf(fid,'# %d vertices \n', size(V,1));
case 'vt'
fprintf(fid,'# %d texture verticies \n', size(V,1));
case 'vn'
fprintf(fid,'# %d normals \n', size(V,1));
otherwise
fprintf(fid,'# %d\n', size(V,1));
end
|
github
|
lcnhappe/happe-master
|
mne_load_coil_def.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/mne/mne_load_coil_def.m
| 8,714 |
utf_8
|
27f6f7c6a6d28610885a9c1be788e73a
|
function [CoilDef,Header] = mne_load_coil_def(fname);
%
%
% [CoilDef,Header] = mne_load_coil_def(fname);
% CoilDef = mne_load_coil_def(fname);
%
% If file name is not specified, the standard coil definition file
% $MNE_ROOT/setup/mne/coil_def.dat or $MNE_ROOT/share/mne/coil_def.dat is read
%
% The content of the coil definition file is described in
% section 5.6 of the MNE manual
%
% This routine is modified from the original BrainStorm routine
% created by John C. Mosher
%
%
% John C. Mosher
% Los Alamos National Laboratory
%
% Author : Matti Hamalainen, MGH Martinos Center
% License : BSD 3-clause
%
% Copyright (c) 2005 BrainStorm MMIV by the University of Southern California
% Principal Investigator:
% ** Professor Richard M. Leahy, USC Signal & Image Processing Institute
%
%
% Revision 1.5 2006/09/08 19:27:13 msh
% Added KIT coil type to mne_load_coil_def
% Allow reading of measurement info by specifying just a file name.
%
% Revision 1.4 2006/04/25 12:29:10 msh
% Added Magnes and CTF reference coil drawings.
%
% Revision 1.3 2006/04/23 15:29:40 msh
% Added MGH to the copyright
%
% Revision 1.2 2006/04/17 15:01:34 msh
% More small improvements.
%
% Revision 1.1 2006/04/17 11:52:15 msh
% Added coil definition stuff
%
%
me='MNE:mne_load_coil_def';
%% Setup the default inputs
if nargin == 0
fname = mne_file_name('setup/mne/coil_def.dat');
if ~exist(fname,'file')
fname = mne_file_name('share/mne/coil_def.dat');
if ~exist(fname,'file')
error(me,'The standard coil definition file was not found');
end
end
end
% Read in the coil_def information
%% Open, Read in entire file, close
fid = fopen(fname,'rt');
if fid < 0
error(me,'Could not open coil definition file %s',fname);
end
istr = 1; % string indexer
str_array = cell(1000,1); % preallocate
str_array{istr} = fgetl(fid); % get first string
while ischar(str_array{istr}),
istr = istr + 1;
str_array{istr} = fgetl(fid); % get next string
end
fclose(fid);
str_array = str_array(1:(istr-1)); % trim allocation
%% Read the Header, find the structure
% Gather the header lines
HeaderLines = strmatch('#',str_array); % lines that begin with a comment
% where are the structure lines
StructureLines = strmatch('# struct',str_array); % subset of header lines
% should be two
if length(StructureLines) ~= 2,
error(me,'%s anticipates two lines of structures',mfilename)
end
% with each structure line is a format line
FormatLines = strmatch('# format',str_array); % subset of header lines
% assume there are also two
FieldNames = cell(1,2);
Format = cell(1,2);
% first structure is the coil information
% won't actually use the second structure, just its format
for i = 1:2,
FieldNames{i} = strread(str_array{StructureLines(i)},'%s');
FieldNames{i}(1:2) = []; % strip the comment symbol and struct keyword
[ignore,Format{i}] = strtok(str_array{FormatLines(i)},'''');
Format{i} = strrep(Format{i},'''',''); % strip the single quotes
end
%% Allocate the arrays for loading
% interleave every fieldname with a null value
struct_arg = [FieldNames{1} cell(length(FieldNames{1}),1)]';
% each column an argument pair
% Preallocate a structure
[CoilDef(1:100)] = deal(struct(struct_arg{:}));
% Convert the rest of the string array to a structure
iCoil = 0; % counter
iLine = HeaderLines(end); % next line after header
while iLine < length(str_array), % number of lines in file
iCoil = iCoil + 1; % next coil definition
iLine = iLine + 1; % next line
% first read the integer information on the coil
% begin by breaking the line into two parts, numeric and description
[numeric_items, description] = strtok(str_array{iLine},'"');
temp = sscanf(numeric_items,Format{1}); % extra %s doesn't matter
% assign temp in the order of the fields
for i = 1:(length(FieldNames{1})-1),
CoilDef(iCoil).(FieldNames{1}{i}) = temp(i);
end
% then assign the description
% let's strip the quotes first
description = strrep(description,'"','');
CoilDef(iCoil).(FieldNames{1}{end}) = description;
% now read the coil definition
CoilDef(iCoil).coildefs = zeros(CoilDef(iCoil).num_points,7);
for i = 1:CoilDef(iCoil).num_points,
iLine = iLine + 1;
CoilDef(iCoil).coildefs(i,:) = sscanf(str_array{iLine},...
Format{2})';
end
% now draw it
% local subfunction below
CoilDef(iCoil).FV = draw_sensor(CoilDef(iCoil));
end
CoilDef = CoilDef(1:iCoil); % trim allocation
Header = str_array(HeaderLines);
function FV = draw_sensor(CoilDef);
% create a patch based on the sensor type
% The definitions as of 14 October 2005:
% for i = 1:3:length(CoilDef),fprintf('%d %s\n',CoilDef(i).id,CoilDef(i).description);end
% 2 Neuromag-122 planar gradiometer size = 27.89 mm base = 16.20 mm
% 2000 Point magnetometer
% 3012 Vectorview planar gradiometer T1 size = 26.39 mm base = 16.80 mm
% 3013 Vectorview planar gradiometer T2 size = 26.39 mm base = 16.80 mm
% 3022 Vectorview magnetometer T1 size = 25.80 mm
% 3023 Vectorview magnetometer T2 size = 25.80 mm
% 3024 Vectorview magnetometer T3 size = 21.00 mm
% 4001 Magnes WH2500 magnetometer size = 11.50 mm
% 4002 Magnes WH3600 gradiometer size = 18.00 mm base = 50.00 mm
% 5001 CTF axial gradiometer size = 18.00 mm base = 50.00 mm
% 7001 BabySQUID I axial gradiometer size = 6.0 mm base = 50 mm
FV = struct('faces',[],'vertices',[]); % standard convention
% recall that vertices are 1 per ROW, not column, of matrix
switch CoilDef.id
case {2,3012,3013,3011}
% square figure eight
% wound by right hand rule such that +x side is "up" (+z)
LongSide = CoilDef.size*1000; % length of long side in mm
Offset = 2.5; % mm offset of the center portion of planar grad coil
FV.vertices = [0 0 0; Offset 0 0; ...
Offset -LongSide/2 0; LongSide/2 -LongSide/2 0; ...
LongSide/2 LongSide/2 0; ...
Offset LongSide/2 0; Offset 0 0; ...
0 0 0; -Offset 0 0; -Offset -LongSide/2 0; ...
-LongSide/2 -LongSide/2 0; ...
-LongSide/2 LongSide/2 0; ...
-Offset LongSide/2 0; -Offset 0 0]/1000;
FV.faces = [1:length(FV.vertices)];
case 2000
% point source
LongSide = 2; % mm, tiny square
FV.vertices = [-1 1 0;1 1 0;1 -1 0; -1 -1 0]*LongSide/1000/2;
FV.faces = [1:length(FV.vertices)];
case {3022, 3023, 3024}
% square magnetometer
LongSide = CoilDef.size*1000; % mm, length of one side
FV.vertices = [-1 1 0;1 1 0;1 -1 0; -1 -1 0]*LongSide/1000/2;
FV.faces = [1:length(FV.vertices)];
case {4001,4003,5002}
% round magnetometer
Radius = CoilDef.size*1000/2; % mm, radius of coil
Len_cir = 15; % number of points for circle
circle = cos(2*pi*[0:(Len_cir-1)]/Len_cir) + ...
sqrt(-1)*sin(2*pi*[0:(Len_cir-1)]/Len_cir); % complex circle unit
FV.vertices = ...
[real(circle)' imag(circle)' zeros(Len_cir,1)]*Radius/1000;
FV.faces = [1:length(FV.vertices)];
case {4002, 5001, 5003, 4004, 6001, 7001}
% round coil 1st order gradiometer
Radius = CoilDef.size*1000/2; % mm radius
Baseline = CoilDef.baseline*1000; % axial separation
Len_cir = 15; % number of points for circle
% This time, go all the way around circle to close it fully
circle = cos(2*pi*[0:Len_cir]/Len_cir) + ...
sqrt(-1)*sin(2*pi*[0:Len_cir]/Len_cir); % complex circle unit
circle = circle*Radius; % scaled
FV.vertices = ...
[[real(circle)' imag(circle)' zeros(Len_cir+1,1)];... % first coil
[real(circle)' -imag(circle)' zeros(Len_cir+1,1)+Baseline]]/1000; % 2nd coil
FV.faces = [1:length(FV.vertices)];
case {5004,4005}
% round coil 1st order off-diagonal gradiometer
Radius = CoilDef.size*1000/2; % mm radius
Baseline = CoilDef.baseline*1000; % axial separation
Len_cir = 15; % number of points for circle
% This time, go all the way around circle to close it fully
circle = cos(2*pi*[0:Len_cir]/Len_cir) + ...
sqrt(-1)*sin(2*pi*[0:Len_cir]/Len_cir); % complex circle unit
circle = circle*Radius; % scaled
FV.vertices = ...
[[real(circle)'+Baseline/2.0 imag(circle)' zeros(Len_cir+1,1)];... % first coil
[real(circle)'-Baseline/2.0 -imag(circle)' zeros(Len_cir+1,1)]]/1000; % 2nd coil
FV.faces = [1:length(FV.vertices)];
otherwise
FV = [];
end
|
github
|
lcnhappe/happe-master
|
fiff_find_evoked.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/mne/fiff_find_evoked.m
| 2,846 |
utf_8
|
f7c5e4fd4395754f0e87d3fe6e984d62
|
function [data_sets] = fiff_find_evoked(fname)
%
% [data_sets] = fiff_find_evoked(fname)
%
% Find all evoked data sets in a fif file and create a list of descriptors
%
%
% Author : Matti Hamalainen, MGH Martinos Center
% License : BSD 3-clause
%
global FIFF;
if isempty(FIFF)
FIFF = fiff_define_constants();
end
me = 'MNE:fiff_find_evoked';
%
% Open the file
%
[ fid, tree ] = fiff_open(fname);
data_sets = struct('comment',{},'aspect_kind',{},'aspect_name',{});
%
% Find all evoked data sets
%
evoked = fiff_dir_tree_find(tree, FIFF.FIFFB_EVOKED);
if length(evoked) == 0
fclose(fid);
return
end
%
% Identify the aspects
%
naspect = 0;
for k = 1:length(evoked)
sets(k).aspects = fiff_dir_tree_find(evoked(k), FIFF.FIFFB_ASPECT);
sets(k).naspect = length(sets(k).aspects);
naspect = naspect + sets(k).naspect;
end
%
% Collect the desired information
%
count = 1;
for k = 1:length(evoked)
evoked_comment = find_tag(evoked(k), FIFF.FIFF_COMMENT);
for a = 1:sets(k).naspect
aspect_comment = find_tag(sets(k).aspects(a), FIFF.FIFF_COMMENT);
aspect_kind = find_tag(sets(k).aspects(a), FIFF.FIFF_ASPECT_KIND);
if ~isempty(aspect_comment)
data_sets(count).comment = aspect_comment.data;
elseif ~isempty(evoked_comment)
data_sets(count).comment = evoked_comment.data;
else
data_sets(count).comment = 'No comment';
end
if ~isempty(aspect_kind)
data_sets(count).aspect_kind = aspect_kind.data;
else
data_sets(count).aspect_kind = -1;
end
switch data_sets(count).aspect_kind
case FIFF.FIFFV_ASPECT_AVERAGE
data_sets(count).aspect_name = 'Average';
case FIFF.FIFFV_ASPECT_STD_ERR
data_sets(count).aspect_name = 'Standard error';
case FIFF.FIFFV_ASPECT_SINGLE
data_sets(count).aspect_name = 'Single';
case FIFF.FIFFV_ASPECT_SUBAVERAGE
data_sets(count).aspect_name = 'Subaverage';
case FIFF.FIFFV_ASPECT_ALTAVERAGE
data_sets(count).aspect_name = 'Alt. subaverage';
case FIFF.FIFFV_ASPECT_SAMPLE
data_sets(count).aspect_name = 'Sample';
case FIFF.FIFFV_ASPECT_POWER_DENSITY
data_sets(count).aspect_name = 'Power density spectrum';
case FIFF.FIFFV_ASPECT_DIPOLE_WAVE
data_sets(count).aspect_name = 'Dipole source waveform';
otherwise
data_sets(count).aspect_name = 'Unknown';
end
count = count + 1;
end
end
fclose(fid);
return
function [tag] = find_tag(node, findkind)
for p = 1:node.nent
kind = node.dir(p).kind;
pos = node.dir(p).pos;
if kind == findkind
tag = fiff_read_tag(fid, pos);
return
end
end
tag = [];
return
end
end
|
github
|
lcnhappe/happe-master
|
load_dicom_series.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/freesurfer/load_dicom_series.m
| 3,258 |
utf_8
|
b4de6c347c9d4453d512c9f0b5cfa58a
|
function [vol, M, tmpdcminfo, mr_parms] = load_dicom_series(seriesno,dcmdir,dcmfile)
% [vol, M, dcminfo] = load_dicom_series(seriesno,<dcmdir>,<dcmfile>)
%
% Reads in a dicom series given:
% 1. The series number and directory, or
% 2. A dicom file from the desired series
%
% If the series number is given but no dcmdir is given, then the
% current directory is assumed. All files in the dcmdir are examined
% and the dicom files for the given series are then loaded.
%
% If a dicom file is given, then seriesno and dcmdir are determined
% from the file and file name.
%
% mr_parms = [tr flipangle te ti]
%
% Bugs: will not load multiple frames or mosaics properly.
%
%
% load_dicom_series.m
%
% Original Author: Doug Greve
% CVS Revision Info:
% $Author: nicks $
% $Date: 2011/03/02 00:04:12 $
% $Revision$
%
% Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH"
%
% Terms and conditions for use, reproduction, distribution and contribution
% are found in the 'FreeSurfer Software License Agreement' contained
% in the file 'LICENSE' found in the FreeSurfer distribution, and here:
%
% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense
%
% Reporting: [email protected]
%
if(nargin < 1 | nargin > 3)
fprintf('[vol, M, dcminfo] = load_dicom_series(seriesno,<dcmdir>,<dcmfile>)\n');
return;
end
if(nargin == 1) dcmdir = '.'; end
if(nargin == 3)
[isdcm dcminfo] = isdicomfile(dcmfile);
if(~isdcm)
fprintf('ERROR: %s is not a dicomfile \n',dcmfile);
return;
end
if(~isfield(dcminfo,'SeriesNumber'))
fprintf('ERROR: %s does not have a series number \n',dcmfile);
return;
end
seriesno = dcminfo.SeriesNumber;
dcmdir = getdcmdir(dcmfile);
end
% Get a list of files in the directory %
flist = dir(dcmdir);
nfiles = length(flist);
fprintf('INFO: Found %d files in %s\n',nfiles,dcmdir);
if(nfiles == 0)
fprintf('ERROR: no files in %s\n',dcmdir);
return;
end
% Determine which ones belong to series %
seriesflist = [];
nth = 1;
fprintf('INFO: searching files for dicom, series %d\n',seriesno);
tic;
for n = 1:nfiles
%if(n==1 | rem(n,20)==0) fprintf('n = %4d, t = %g\n',n,toc); end
pathname = sprintf('%s/%s',dcmdir,flist(n).name);
[isdcm dcminfo] = isdicomfile(pathname);
if(isdcm)
if(isfield(dcminfo,'SeriesNumber'))
if(dcminfo.SeriesNumber == seriesno)
seriesflist = strvcat(seriesflist,pathname);
dcminfolist(nth) = dcminfo;
dcminfo0 = dcminfo;
nth = nth+1;
end
end
end
end
if(nth==1)
fprintf('ERROR: could not find any dicom files in %s or none in series %d\n',dcmdir,seriesno);
return;
end
dcminfo = dcminfo0;
fprintf('INFO: search time %g sec\n',toc);
nfilesseries = size(seriesflist,1);
fprintf('INFO: Found %d files in series %d\n',nfilesseries,seriesno);
if(nfilesseries == 0)
fprintf('ERROR: no files in series\n');
return;
end
% Load the volume %
[vol M tmpdcminfo mr_parms] = load_dicom_fl(seriesflist);
return;
%---------------------------------------------------%
function dcmdir = getdcmdir(dcmfile)
ind = findstr(dcmfile,filesep);
if(~isempty(ind))
if(max(ind)~=1)
dcmdir = dcmfile(1:max(ind)-1);
else
dcmdir = filesep;
end
else
dcmdir = '.';
end
return;
|
github
|
lcnhappe/happe-master
|
load_dicom_fl.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/freesurfer/load_dicom_fl.m
| 5,504 |
utf_8
|
a1b99a4d200049ebdb809c0b684b98a1
|
function [vol, M, dcminfo, mr_parms] = load_dicom_fl(flist)
% [vol, M, dcminfo, mr_parms] = load_dicom_fl(flist)
%
% Loads a volume from the dicom files in flist.
%
% The volume dimensions are arranged such that the
% readout dimension is first, followed by the phase-encode,
% followed by the slices (this is not implemented yet)
%
% M is the 4x4 vox2ras transform such that
% vol(i1,i2,i3), xyz1 = M*[i1 i2 i3 1] where the
% indicies are 0-based.
%
% mr_parms = [tr flipangle te ti]
%
% Does not handle multiple frames correctly yet.
%
%
% load_dicom_fl.m
%
% Original Author: Doug Greve
% CVS Revision Info:
% $Author: nicks $
% $Date: 2011/03/02 00:04:12 $
% $Revision$
%
% Copyright ?? 2011 The General Hospital Corporation (Boston, MA) "MGH"
%
% Terms and conditions for use, reproduction, distribution and contribution
% are found in the 'FreeSurfer Software License Agreement' contained
% in the file 'LICENSE' found in the FreeSurfer distribution, and here:
%
% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense
%
% Reporting: [email protected]
%
vol=[];
M=[];
if(nargin ~= 1)
fprintf('[vol, M] = load_dicom_fl(flist)\n');
return;
end
nfiles = size(flist,1);
tic
fprintf('Loading dicom info foreach file \n');
for n = 1:nfiles
fname = deblank(flist(n,:));
% fprintf('n = %d/%d, %s %g\n',n,nfiles,fname,toc);
tmpinfo = dicominfo(fname);
if(isempty(tmpinfo))
fprintf('ERROR: reading %s\n',fname);
return;
end
if(n > 1)
% Check that the nth series number agrees with the first
if(tmpinfo.SeriesNumber ~= dcminfo0(1).SeriesNumber)
fprintf('ERROR: series number inconsistency (%s)\n',fname);
return;
end
end
tmpinfo.fname = fname;
dcminfo0(n) = tmpinfo;
end
% Sort by slice location %
dcminfo = sort_by_sliceloc(dcminfo0);
% Slice direction cosine %
sdc = dcminfo(nfiles).ImagePositionPatient-dcminfo(1).ImagePositionPatient;
sdc = sdc /sqrt(sum(sdc.^2));
% Distance between slices %
dslice = sqrt(sum((dcminfo(2).ImagePositionPatient-dcminfo(1).ImagePositionPatient).^2));
% Matrix of direction cosines %
Mdc = zeros(3,3);
Mdc(:,1) = dcminfo(1).ImageOrientationPatient(1:3);
Mdc(:,2) = dcminfo(1).ImageOrientationPatient(4:6);
Mdc(:,3) = sdc;
% Voxel resolution %
delta = [dcminfo(1).PixelSpacing; dslice];
D = diag(delta);
% XYZ of first voxel in first slice %
P0 = dcminfo(1).ImagePositionPatient;
% Change Siemens to be RAS %
% GE is also LPS - change it to be RAS, too - ebeth %
try
Manufacturer = dcminfo(1).Manufacturer;
catch
Manufacturer = 'unknown';
end
if(strcmpi(Manufacturer,'Siemens') | strcmpi(Manufacturer,'ge medical systems'))
% Change to RAS
Mdc(1,:) = -Mdc(1,:);
Mdc(2,:) = -Mdc(2,:);
P0(1) = -P0(1);
P0(2) = -P0(2);
end
% Compute vox2ras transform %
M = [Mdc*D P0; 0 0 0 1];
if (0&strcmpi(Manufacturer,'Siemens'))
% Correcting for P0 being at corner of
% the first voxel instead of at the center
M = M*[[eye(3) [0.5 0.5 0]']; 0 0 0 1]; %'
end
% Pre-allocate vol. Note: column and row designations do
% not really mean anything. The "column" is the fastest
% dimension. The "row" is the next fastest, etc.
ndim1 = dcminfo(1).Columns;
ndim2 = dcminfo(1).Rows;
ndim3 = nfiles;
vol = zeros(ndim1,ndim2,ndim3);
fprintf('Loading data from each file.\n');
for n = 1:nfiles
%fprintf('n = %d, %g\n',n,toc);
fname = dcminfo(n).fname;
x = dicomread(fname);
if(isempty(x))
fprintf('ERROR: could not load pixel data from %s\n',fname);
return;
end
% Note: dicomread will transposed the image. This is supposed
% to help. Anyway, to make the vox2ras transform agree with
% the volume, the image is transposed back.
vol(:,:,n) = x'; %'
end
% Reorder dimensions so that ReadOut dim is first %
if(0 & ~strcmpi(dcminfo(1).PhaseEncodingDirection,'ROW'))
% This does not work
fprintf('INFO: permuting vol so that ReadOut is first dim\n');
vol = permute(vol,[2 1 3]);
Mtmp = M;
M(:,1) = Mtmp(:,2);
M(:,2) = Mtmp(:,1);
end
% Lines below correct for the Z-offset in GE machines - ebeth %
% We're told ge machines recenter along superior/inferior axis but
% don't update c_ras - but now c_s should be zero.
if(strcmpi(Manufacturer,'ge medical systems'))
% Lines below correct for the Z-offset in GE machines
firstZ = dcminfo(1).ImagePositionPatient(3);
lastXYZ = M*[size(vol)';1]; %'
% size(imvol) = number of slices in all 3 dirs
lastZ = lastXYZ(3);
offsetZ = (lastZ + firstZ)/2.0;
% Z0 = Z + offsetZ; [XYZ1]' = M*[CRS1]', need to add to M(3,4)(?)
M(3,4) = M(3,4) - offsetZ;
end
% if(strcmpi(Manufacturer,'ge medical systems'))
% M(3,4) = 0; % Wow - that was actually completely wrong!
% end
% Pull out some info from the header %
if(isfield(dcminfo(1),'FlipAngle')) FlipAngle = pi*dcminfo(1).FlipAngle/180;
else FlipAngle = 0;
end
if(isfield(dcminfo(1),'EchoTime')) EchoTime = dcminfo(1).EchoTime;
else EchoTime = 0;
end
if(isfield(dcminfo(1),'RepetitionTime')) RepetitionTime = dcminfo(1).RepetitionTime;
else RepetitionTime = 0;
end
InversionTime = 0;
mr_parms = [RepetitionTime FlipAngle EchoTime InversionTime];
return;
%----------------------------------------------------------%
function dcminfo2 = sort_by_sliceloc(dcminfo)
nslices = length(dcminfo);
sliceloc = zeros(nslices,1);
for n = 1:nslices
sliceloc(n) = dcminfo(n).SliceLocation;
end
[tmp ind] = sort(sliceloc);
dcminfo2 = dcminfo(ind);
return;
%----------------------------------------------------------%
|
github
|
lcnhappe/happe-master
|
tukeywin.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/tukeywin.m
| 2,102 |
utf_8
|
92cee22ee44a0bf1650a07edd3ef943a
|
% Copyright (C) 2007 Laurent Mazet <[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 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program; if not, see <http://www.gnu.org/licenses/>.
%
% -*- texinfo -*-
% @deftypefn {Function File} {@var{w} =} tukeywin (@var{L}, @var{r})
% Return the filter coefficients of a Tukey window (also known as the
% cosine-tapered window) of length @var{L}. @var{r} defines the ratio
% between the constant section and and the cosine section. It has to be
% between 0 and 1. The function returns a Hanning window for @var{r}
% egals 0 and a full box for @var{r} egals 1. By default @var{r} is set
% to 1/2.
%
% For a definition of the Tukey window, see e.g. Fredric J. Harris,
% 'On the Use of Windows for Harmonic Analysis with the Discrete Fourier
% Transform, Proceedings of the IEEE', Vol. 66, No. 1, January 1978,
% Page 67, Equation 38.
% @end deftypefn
function w = tukeywin (L, r)
if nargin<2
r = 1/2;
end
if (nargin < 1 || nargin > 2)
help(mfilename);
elseif (nargin == 2)
% check that 0 < r < 1
if r > 1
r = 1;
elseif r < 0
r = 0;
end % if
end % if
% generate window
switch r
case 0,
% full box
w = ones (L, 1);
case 1,
% Hanning window
w = hanning (L);
otherwise
% cosine-tapered window
t = linspace(0,1,L);
t = t(1:end/2)';
w = (1 + cos(pi*(2*t/r-1)))/2;
w(floor(r*(L-1)/2)+2:end) = 1;
w = [w; ones(mod(L,2)); flipud(w)];
end % switch
end
%!demo
%! L = 100;
%! r = 1/3;
%! w = tukeywin (L, r);
%! title(sprintf('%d-point Tukey window, R = %d/%d', L, [p, q] = rat(r), q));
%! plot(w);
|
github
|
lcnhappe/happe-master
|
rectwin.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/rectwin.m
| 990 |
utf_8
|
6fcae9032382b3785fa1a5fc7d35d0bd
|
% Copyright (C) 2007 Sylvain Pelissier <[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 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program; if not, see <http://www.gnu.org/licenses/>.
%
% -*- texinfo -*-
% @deftypefn {Function File} {[@var{w}] =} rectwin(@var{L})
% Return the filter coefficients of a rectangle window of length L.
% @seealso{hamming, hanning}
% @end deftypefn
function w = rectwin(L)
if (nargin < 1); help(mfilename); end
w = ones(round(L),1);
end
|
github
|
lcnhappe/happe-master
|
triang.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/triang.m
| 2,254 |
utf_8
|
922302c6c872d9c51d61c97a76761328
|
% Copyright (C) 2000-2002 Paul Kienzle <[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 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program; if not, see <http://www.gnu.org/licenses/>.
%
% usage: w = triang (L)
%
% Returns the filter coefficients of a triangular window of length L.
% Unlike the bartlett window, triang does not go to zero at the edges
% of the window. For odd L, triang(L) is equal to bartlett(L+2) except
% for the zeros at the edges of the window.
function w = triang(L)
if (nargin ~= 1)
help(mfilename);
elseif (~isscalar(L) || L ~= fix (L) || L < 1)
error('triang: L has to be an integer > 0');
end % if
w = 1 - abs ([-(L-1):2:(L-1)]' / (L+rem(L,2)));
end
%!error triang
%!error triang(1,2)
%!error triang([1,2]);
%!assert (triang(1), 1)
%!assert (triang(2), [1; 1]/2)
%!assert (triang(3), [1; 2; 1]/2);
%!assert (triang(4), [1; 3; 3; 1]/4);
%!test
%! x = bartlett(5);
%! assert (triang(3), x(2:4));
%!demo
%! subplot(221); axis([-1, 1, 0, 1.3]); grid('on');
%! title('comparison with continuous for odd n');
%! n=7; k=(n-1)/2; t=[-k:0.1:k]/(k+1);
%! plot(t,1-abs(t),';continuous;',[-k:k]/(k+1),triang(n),'g*;discrete;');
%!
%! subplot(222); axis([-1, 1, 0, 1.3]); grid('on');
%! n=8; k=(n-1)/2; t=[-k:0.1:k]/(k+1/2);
%! title('note the higher peak for even n');
%! plot(t,1+1/n-abs(t),';continuous;',[-k:k]/(k+1/2),triang(n),'g*;discrete;');
%!
%! subplot(223); axis; grid('off');
%! title('n odd, triang(n)==bartlett(n+2)');
%! n=7;
%! plot(0:n+1,bartlett(n+2),'g-*;bartlett;',triang(n),'r-+;triang;');
%!
%! subplot(224); axis; grid('off');
%! title('n even, triang(n)!=bartlett(n+2)');
%! n=8;
%! plot(0:n+1,bartlett(n+2),'g-*;bartlett;',triang(n),'r-+;triang;');
%!
%! subplot(111); title('');
|
github
|
lcnhappe/happe-master
|
bohmanwin.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/bohmanwin.m
| 1,381 |
utf_8
|
b837d6f243c8cd46b91ac9846a12da56
|
% Copyright (C) 2007 Sylvain Pelissier <[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 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program; if not, see <http://www.gnu.org/licenses/>.
%
% -*- texinfo -*-
% @deftypefn {Function File} {[@var{w}] =} bohmanwin(@var{L})
% Compute the Bohman window of lenght L.
% @seealso{rectwin, bartlett}
% @end deftypefn
function [w] = bohmanwin(L)
if (nargin < 1)
help(mfilename)
elseif(~ isscalar(L))
error('L must be a number');
elseif(L < 0)
error('L must be positive');
end
if(L ~= floor(L))
L = round(L);
warning('L rounded to the nearest integer.');
end
if(L == 0)
w = [];
elseif(L == 1)
w = 1;
else
N = L-1;
n = -N/2:N/2;
w = (1-2.*abs(n)./N).*cos(2.*pi.*abs(n)./N) + (1./pi).*sin(2.*pi.*abs(n)./N);
w(1) = 0;
w(length(w))=0;
w = w';
end
end
|
github
|
lcnhappe/happe-master
|
hanning.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/hanning.m
| 1,970 |
utf_8
|
78215b654e6e105faa447902fa6cc81c
|
function [tap] = hanning(n, str)
%HANNING Hanning window.
% HANNING(N) returns the N-point symmetric Hanning window in a column
% vector. Note that the first and last zero-weighted window samples
% are not included.
%
% HANNING(N,'symmetric') returns the same result as HANNING(N).
%
% HANNING(N,'periodic') returns the N-point periodic Hanning window,
% and includes the first zero-weighted window sample.
%
% NOTE: Use the HANN function to get a Hanning window which has the
% first and last zero-weighted samples.
%
% See also BARTLETT, BLACKMAN, BOXCAR, CHEBWIN, HAMMING, HANN, KAISER
% and TRIANG.
%
% This is a drop-in replacement to bypass the signal processing toolbox
% Copyright (c) 2010, Jan-Mathijs Schoffelen, DCCN Nijmegen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$
if nargin==1,
str = 'symmetric';
end
switch str,
case 'periodic'
% Includes the first zero sample
tap = [0; hanningX(n-1)];
case 'symmetric'
% Does not include the first and last zero sample
tap = hanningX(n);
end
function tap = hanningX(n)
% compute taper
N = n+1;
tap = 0.5*(1-cos((2*pi*(1:n))./N))';
% make symmetric
halfn = floor(n/2);
tap( (n+1-halfn):n ) = flipud(tap(1:halfn));
|
github
|
lcnhappe/happe-master
|
filtfilt.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/filtfilt.m
| 3,297 |
iso_8859_1
|
d01a26a827bc3379f05bbc57f46ac0a9
|
% Copyright (C) 1999 Paul Kienzle
% Copyright (C) 2007 Francesco Potortì
% Copyright (C) 2008 Luca Citi
%
% 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, see <http://www.gnu.org/licenses/>.
% usage: y = filtfilt(b, a, x)
%
% Forward and reverse filter the signal. This corrects for phase
% distortion introduced by a one-pass filter, though it does square the
% magnitude response in the process. That's the theory at least. In
% practice the phase correction is not perfect, and magnitude response
% is distorted, particularly in the stop band.
%%
% Example
% [b, a]=butter(3, 0.1); % 10 Hz low-pass filter
% t = 0:0.01:1.0; % 1 second sample
% x=sin(2*pi*t*2.3)+0.25*randn(size(t)); % 2.3 Hz sinusoid+noise
% y = filtfilt(b,a,x); z = filter(b,a,x); % apply filter
% plot(t,x,';data;',t,y,';filtfilt;',t,z,';filter;')
% Changelog:
% 2000 02 [email protected]
% - pad with zeros to load up the state vector on filter reverse.
% - add example
% 2007 12 [email protected]
% - use filtic to compute initial and final states
% - work for multiple columns as well
% 2008 12 [email protected]
% - fixed instability issues with IIR filters and noisy inputs
% - initial states computed according to Likhterov & Kopeika, 2003
% - use of a "reflection method" to reduce end effects
% - added some basic tests
% TODO: (pkienzle) My version seems to have similar quality to matlab,
% but both are pretty bad. They do remove gross lag errors, though.
function y = filtfilt(b, a, x)
if (nargin ~= 3)
usage('y=filtfilt(b,a,x)');
end
rotate = (size(x, 1)==1);
if rotate % a row vector
x = x(:); % make it a column vector
end
lx = size(x,1);
a = a(:).';
b = b(:).';
lb = length(b);
la = length(a);
n = max(lb, la);
lrefl = 3 * (n - 1);
if la < n, a(n) = 0; end
if lb < n, b(n) = 0; end
% Compute a the initial state taking inspiration from
% Likhterov & Kopeika, 2003. "Hardware-efficient technique for
% minimizing startup transients in Direct Form II digital filters"
kdc = sum(b) / sum(a);
if (abs(kdc) < inf) % neither NaN nor +/- Inf
si = fliplr(cumsum(fliplr(b - kdc * a)));
else
si = zeros(size(a)); % fall back to zero initialization
end
si(1) = [];
y = zeros(size(x));
for c = 1:size(x, 2) % filter all columns, one by one
v = [2*x(1,c)-x((lrefl+1):-1:2,c); x(:,c);
2*x(end,c)-x((end-1):-1:end-lrefl,c)]; % a column vector
% Do forward and reverse filtering
v = filter(b,a,v,si*v(1)); % forward filter
v = flipud(filter(b,a,flipud(v),si*v(end))); % reverse filter
y(:,c) = v((lrefl+1):(lx+lrefl));
end
if (rotate) % x was a row vector
y = rot90(y); % rotate it back
end
|
github
|
lcnhappe/happe-master
|
nuttallwin.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/nuttallwin.m
| 1,316 |
utf_8
|
2a8b412e307f23d07700757c675abcc1
|
% Copyright (C) 2007 Sylvain Pelissier <[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 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program; if not, see <http://www.gnu.org/licenses/>.
%
% -*- texinfo -*-
% @deftypefn {Function File} {[@var{w}] =} nuttallwin(@var{L})
% Compute the Blackman-Harris window defined by Nuttall of length L.
% @seealso{blackman, blackmanharris}
% @end deftypefn
function [w] = nuttallwin(L)
if (nargin ~= 1); help(mfilename); end
if(L < 0)
error('L must be positive');
end
if(L ~= floor(L))
L = round(L);
warning('L rounded to the nearest integer.');
end
N = L-1;
a0 = 0.355768;
a1 = 0.487396;
a2 = 0.144232;
a3 = 0.012604;
n = -N/2:N/2;
w = a0 + a1.*cos(2.*pi.*n./N) + a2.*cos(4.*pi.*n./N) + a3.*cos(6.*pi.*n./N);
w = w';
end
|
github
|
lcnhappe/happe-master
|
hann.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/hann.m
| 66 |
utf_8
|
779d38839745c5c57530f4c470cc1352
|
% w = hann(n)
% see hanning
function w = hann(n), w=hanning(n);
|
github
|
lcnhappe/happe-master
|
kaiser.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/kaiser.m
| 1,745 |
utf_8
|
bae51aff1f9eb7c65b82a58fb3049d34
|
% Copyright (C) 1995, 1996, 1997 Kurt Hornik <[email protected]>
% Copyright (C) 2000 Paul Kienzle <[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 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program; if not, see <http://www.gnu.org/licenses/>.
%
% usage: kaiser (L, beta)
%
% Returns the filter coefficients of the L-point Kaiser window with
% parameter beta.
%
% For the definition of the Kaiser window, see A. V. Oppenheim &
% R. W. Schafer, 'Discrete-Time Signal Processing'.
%
% The continuous version of width L centered about x=0 is:
%
% besseli(0, beta * sqrt(1-(2*x/L).^2))
% k(x) = -------------------------------------, L/2 <= x <= L/2
% besseli(0, beta)
%
% See also: kaiserord
function w = kaiser (L, beta)
if nargin<2
beta = 0.5;
end
if (nargin < 1)
help(mfilename);
elseif ~(isscalar (L) && (L == round (L)) && (L > 0))
error ('kaiser: L has to be a positive integer');
elseif ~(isscalar (beta) && (beta == real (beta)))
error ('kaiser: beta has to be a real scalar');
end % if
if (L == 1)
w = 1;
else
m = L - 1;
k = (0 : m)';
k = 2 * beta / m * sqrt (k .* (m - k));
w = besseli (0, k) / besseli (0, beta);
end % if
end
%!demo
%! % use demo('kaiserord');
|
github
|
lcnhappe/happe-master
|
window.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/window.m
| 1,240 |
utf_8
|
a1ed726ea9ff030e26b60e47cd280d12
|
% Copyright (C) 2008 David Bateman
%
% This program is free software; you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation; either version 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program; if not, see <http://www.gnu.org/licenses/>.
%
% -*- texinfo -*-
% @deftypefn {Function File} {@var{w} =} window (@var{f}, @var{n}, @var{opts})
% Create a @var{n}-point windowing from the function @var{f}. The
% function @var{f} can be for example @code{@@blackman}. Any additional
% arguments @var{opt} are passed to the windowing function.
% @end deftypefn
function wout = window (f, n, varargin)
if (nargin == 0)
error ('window: UI tool not supported');
elseif (nargin > 1)
w = feval (f, n, varargin{:});
if (nargout > 0)
wout = w;
end % if
else
help(mfilename);
end % if
end
|
github
|
lcnhappe/happe-master
|
blackmanharris.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/blackmanharris.m
| 1,188 |
utf_8
|
58ad36fc97b524266d6a9db98fb6e6ee
|
% Copyright (C) 2007 Sylvain Pelissier <[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 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program; if not, see <http://www.gnu.org/licenses/>.
%
% -*- texinfo -*-
% @deftypefn {Function File} {[@var{w}] =} blackmanharris(@var{L})
% Compute the Blackman-Harris window.
% @seealso{rectwin, bartlett}
% @end deftypefn
function [w] = blackmanharris (L)
if (nargin < 1)
help(mfilename);
elseif(~ isscalar(L))
error('L must be a number');
end % if
N = L-1;
a0 = 0.35875;
a1 = 0.48829;
a2 = 0.14128;
a3 = 0.01168;
n = 0:N;
w = a0 - a1.*cos(2.*pi.*n./N) + a2.*cos(4.*pi.*n./N) - a3.*cos(6.*pi.*n./N);
end
|
github
|
lcnhappe/happe-master
|
butter.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/butter.m
| 3,578 |
utf_8
|
696de0a27da88cbdd29b04aed067dbce
|
% Copyright (C) 1999 Paul Kienzle
%
% 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, see <http://www.gnu.org/licenses/>.
% Generate a butterworth filter.
% Default is a discrete space (Z) filter.
%
% [b,a] = butter(n, Wc)
% low pass filter with cutoff pi*Wc radians
%
% [b,a] = butter(n, Wc, 'high')
% high pass filter with cutoff pi*Wc radians
%
% [b,a] = butter(n, [Wl, Wh])
% band pass filter with edges pi*Wl and pi*Wh radians
%
% [b,a] = butter(n, [Wl, Wh], 'stop')
% band reject filter with edges pi*Wl and pi*Wh radians
%
% [z,p,g] = butter(...)
% return filter as zero-pole-gain rather than coefficients of the
% numerator and denominator polynomials.
%
% [...] = butter(...,'s')
% return a Laplace space filter, W can be larger than 1.
%
% [a,b,c,d] = butter(...)
% return state-space matrices
%
% References:
%
% Proakis & Manolakis (1992). Digital Signal Processing. New York:
% Macmillan Publishing Company.
% Author: Paul Kienzle <[email protected]>
% Modified by: Doug Stewart <[email protected]> Feb, 2003
function [a, b, c, d] = butter (n, W, varargin)
if (nargin>4 || nargin<2) || (nargout>4 || nargout<2)
error ('usage: [b, a] or [z, p, g] or [a,b,c,d] = butter (n, W [, "ftype"][,"s"])');
end
% interpret the input parameters
if (~(length(n)==1 && n == round(n) && n > 0))
error ('butter: filter order n must be a positive integer');
end
stop = 0;
digital = 1;
for i=1:length(varargin)
switch varargin{i}
case 's', digital = 0;
case 'z', digital = 1;
case { 'high', 'stop' }, stop = 1;
case { 'low', 'pass', 'bandpass' }, stop = 0;
otherwise, error ('butter: expected [high|stop] or [s|z]');
end
end
[r, c]=size(W);
if (~(length(W)<=2 && (r==1 || c==1)))
error ('butter: frequency must be given as w0 or [w0, w1]');
elseif (~(length(W)==1 || length(W) == 2))
error ('butter: only one filter band allowed');
elseif (length(W)==2 && ~(W(1) < W(2)))
error ('butter: first band edge must be smaller than second');
end
if ( digital && ~all(W >= 0 & W <= 1))
error ('butter: critical frequencies must be in (0 1)');
elseif ( ~digital && ~all(W >= 0 ))
error ('butter: critical frequencies must be in (0 inf)');
end
% Prewarp to the band edges to s plane
if digital
T = 2; % sampling frequency of 2 Hz
W = 2/T*tan(pi*W/T);
end
% Generate splane poles for the prototype butterworth filter
% source: Kuc
C = 1; % default cutoff frequency
pole = C*exp(1i*pi*(2*[1:n] + n - 1)/(2*n));
if mod(n,2) == 1, pole((n+1)/2) = -1; end % pure real value at exp(i*pi)
zero = [];
gain = C^n;
% splane frequency transform
[zero, pole, gain] = sftrans(zero, pole, gain, W, stop);
% Use bilinear transform to convert poles to the z plane
if digital
[zero, pole, gain] = bilinear(zero, pole, gain, T);
end
% convert to the correct output form
if nargout==2,
a = real(gain*poly(zero));
b = real(poly(pole));
elseif nargout==3,
a = zero;
b = pole;
c = gain;
else
% output ss results
[a, b, c, d] = zp2ss (zero, pole, gain);
end
|
github
|
lcnhappe/happe-master
|
parzenwin.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/parzenwin.m
| 1,301 |
utf_8
|
5e0e2262856d9c53bb520b02b54f2653
|
% Copyright (C) 2007 Sylvain Pelissier <[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 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program; if not, see <http://www.gnu.org/licenses/>.
%
% -*- texinfo -*-
% @deftypefn {Function File} {[@var{w}] =} parzenwin(@var{L})
% Compute the Parzen window of lenght L.
% @seealso{rectwin, bartlett}
% @end deftypefn
function w = parzenwin (L)
if(nargin ~= 1)
help(mfilename);
elseif(L < 0)
error('L must be positive');
end
if(L ~= floor(L))
L = round(L);
end
N = L-1;
n = -(N/2):N/2;
n1 = n(find(abs(n) <= N/4));
n2 = n(find(n > N/4));
n3 = n(find(n < -N/4));
w1 = 1 -6.*(abs(n1)./(L/2)).^2 + 6*(abs(n1)./(L/2)).^3;
w2 = 2.*(1-abs(n2)./(L/2)).^3;
w3 = 2.*(1-abs(n3)./(L/2)).^3;
w = [w3 w1 w2]';
end
|
github
|
lcnhappe/happe-master
|
gausswin.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/gausswin.m
| 1,116 |
utf_8
|
17daab2749d4ce5c84bb5e676271e8f0
|
% Copyright (C) 1999 Paul Kienzle <[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 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program; if not, see <http://www.gnu.org/licenses/>.
%
% usage: w = gausswin(L, a)
%
% Generate an L-point gaussian window of the given width. Use larger a
% for a narrow window. Use larger L for a smoother curve.
%
% w = exp ( -(a*x)^2/2 )
%
% for x = linspace(-(L-1)/L, (L-1)/L, L)
function x = gausswin(L, w)
if nargin < 1 || nargin > 2
help(mfilename);
end
if nargin == 1, w = 2.5; end % if
x = exp ( -0.5 * ( w/L * [ -(L-1) : 2 : L-1 ]' ) .^ 2 );
end
|
github
|
lcnhappe/happe-master
|
barthannwin.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/barthannwin.m
| 1,173 |
utf_8
|
c90d57c40549a232f05664d193b8cb7a
|
% Copyright (C) 2007 Sylvain Pelissier <[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 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program; if not, see <http://www.gnu.org/licenses/>.
%
% -*- texinfo -*-
% @deftypefn {Function File} {[@var{w}] =} barthannwin(@var{L})
% Compute the modified Bartlett-Hann window of lenght L.
% @seealso{rectwin, bartlett}
% @end deftypefn
function [w] = barthannwin(L)
if (nargin < 1)
help(mfilename);
elseif (~ isscalar(L) || L < 0)
error('L must be a positive integer');
end % if
L = round(L);
N = L-1;
n = 0:N;
w = 0.62 -0.48.*abs(n./(L-1) - 0.5)+0.38*cos(2.*pi*(n./(L-1)-0.5));
w = w';
end
|
github
|
lcnhappe/happe-master
|
postpad.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/private/postpad.m
| 2,013 |
utf_8
|
2c9539d77ff0f85c9f89108f4dc811e0
|
% Copyright (C) 1994, 1995, 1996, 1997, 1998, 2000, 2002, 2004, 2005,
% 2006, 2007, 2008, 2009 John W. Eaton
%
% This file is part of Octave.
%
% Octave is free software; you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or (at
% your option) any later version.
%
% Octave 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 Octave; see the file COPYING. If not, see
% <http://www.gnu.org/licenses/>.
% -*- texinfo -*-
% @deftypefn {Function File} {} postpad (@var{x}, @var{l}, @var{c})
% @deftypefnx {Function File} {} postpad (@var{x}, @var{l}, @var{c}, @var{dim})
% @seealso{prepad, resize}
% @end deftypefn
% Author: Tony Richardson <[email protected]>
% Created: June 1994
function y = postpad (x, l, c, dim)
if nargin < 2 || nargin > 4
%print_usage ();
error('wrong number of input arguments, should be between 2 and 4');
end
if nargin < 3 || isempty(c)
c = 0;
else
if ~isscalar(c)
error ('postpad: third argument must be empty or a scalar');
end
end
nd = ndims(x);
sz = size(x);
if nargin < 4
% Find the first non-singleton dimension
dim = 1;
while dim < nd+1 && sz(dim)==1
dim = dim + 1;
end
if dim > nd
dim = 1;
elseif ~(isscalar(dim) && dim == round(dim)) && dim > 0 && dim< nd+1
error('postpad: dim must be an integer and valid dimension');
end
end
if ~isscalar(l) || l<0
error ('second argument must be a positive scalar');
end
if dim > nd
sz(nd+1:dim) = 1;
end
d = sz(dim);
if d >= l
idx = cell(1,nd);
for i = 1:nd
idx{i} = 1:sz(i);
end
idx{dim} = 1:l;
y = x(idx{:});
else
sz(dim) = l-d;
y = cat(dim, x, c * ones(sz));
end
|
github
|
lcnhappe/happe-master
|
sftrans.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/private/sftrans.m
| 7,947 |
utf_8
|
f64cb2e7d19bcdc6232b39d8a6d70e7c
|
% Copyright (C) 1999 Paul Kienzle
%
% 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, see <http://www.gnu.org/licenses/>.
% usage: [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop)
%
% Transform band edges of a generic lowpass filter (cutoff at W=1)
% represented in splane zero-pole-gain form. W is the edge of the
% target filter (or edges if band pass or band stop). Stop is true for
% high pass and band stop filters or false for low pass and band pass
% filters. Filter edges are specified in radians, from 0 to pi (the
% nyquist frequency).
%
% Theory: Given a low pass filter represented by poles and zeros in the
% splane, you can convert it to a low pass, high pass, band pass or
% band stop by transforming each of the poles and zeros individually.
% The following table summarizes the transformation:
%
% Transform Zero at x Pole at x
% ---------------- ------------------------- ------------------------
% Low Pass zero: Fc x/C pole: Fc x/C
% S -> C S/Fc gain: C/Fc gain: Fc/C
% ---------------- ------------------------- ------------------------
% High Pass zero: Fc C/x pole: Fc C/x
% S -> C Fc/S pole: 0 zero: 0
% gain: -x gain: -1/x
% ---------------- ------------------------- ------------------------
% Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl)
% S^2+FhFl pole: 0 zero: 0
% S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C
% S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2
% ---------------- ------------------------- ------------------------
% Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl)
% S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl)
% S -> C -------- gain: -x gain: -1/x
% S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2
% ---------------- ------------------------- ------------------------
% Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT)
% 2 z-1 pole: -1 zero: -1
% S -> - --- gain: (2-xT)/T gain: (2-xT)/T
% T z+1
% ---------------- ------------------------- ------------------------
%
% where C is the cutoff frequency of the initial lowpass filter, Fc is
% the edge of the target low/high pass filter and [Fl,Fh] are the edges
% of the target band pass/stop filter. With abundant tedious algebra,
% you can derive the above formulae yourself by substituting the
% transform for S into H(S)=S-x for a zero at x or H(S)=1/(S-x) for a
% pole at x, and converting the result into the form:
%
% H(S)=g prod(S-Xi)/prod(S-Xj)
%
% The transforms are from the references. The actual pole-zero-gain
% changes I derived myself.
%
% Please note that a pole and a zero at the same place exactly cancel.
% This is significant for High Pass, Band Pass and Band Stop filters
% which create numerous extra poles and zeros, most of which cancel.
% Those which do not cancel have a 'fill-in' effect, extending the
% shorter of the sets to have the same number of as the longer of the
% sets of poles and zeros (or at least split the difference in the case
% of the band pass filter). There may be other opportunistic
% cancellations but I will not check for them.
%
% Also note that any pole on the unit circle or beyond will result in
% an unstable filter. Because of cancellation, this will only happen
% if the number of poles is smaller than the number of zeros and the
% filter is high pass or band pass. The analytic design methods all
% yield more poles than zeros, so this will not be a problem.
%
% References:
%
% Proakis & Manolakis (1992). Digital Signal Processing. New York:
% Macmillan Publishing Company.
% Author: Paul Kienzle <[email protected]>
% 2000-03-01 [email protected]
% leave transformed Sg as a complex value since cheby2 blows up
% otherwise (but only for odd-order low-pass filters). bilinear
% will return Zg as real, so there is no visible change to the
% user of the IIR filter design functions.
% 2001-03-09 [email protected]
% return real Sg; don't know what to do for imaginary filters
function [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop)
if (nargin ~= 5)
usage('[Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop)');
end;
C = 1;
p = length(Sp);
z = length(Sz);
if z > p || p == 0
error('sftrans: must have at least as many poles as zeros in s-plane');
end
if length(W)==2
Fl = W(1);
Fh = W(2);
if stop
% ---------------- ------------------------- ------------------------
% Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl)
% S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl)
% S -> C -------- gain: -x gain: -1/x
% S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2
% ---------------- ------------------------- ------------------------
if (isempty(Sz))
Sg = Sg * real (1./ prod(-Sp));
elseif (isempty(Sp))
Sg = Sg * real(prod(-Sz));
else
Sg = Sg * real(prod(-Sz)/prod(-Sp));
end
b = (C*(Fh-Fl)/2)./Sp;
Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)];
extend = [sqrt(-Fh*Fl), -sqrt(-Fh*Fl)];
if isempty(Sz)
Sz = [extend(1+rem([1:2*p],2))];
else
b = (C*(Fh-Fl)/2)./Sz;
Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)];
if (p > z)
Sz = [Sz, extend(1+rem([1:2*(p-z)],2))];
end
end
else
% ---------------- ------------------------- ------------------------
% Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl)
% S^2+FhFl pole: 0 zero: 0
% S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C
% S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2
% ---------------- ------------------------- ------------------------
Sg = Sg * (C/(Fh-Fl))^(z-p);
b = Sp*((Fh-Fl)/(2*C));
Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)];
if isempty(Sz)
Sz = zeros(1,p);
else
b = Sz*((Fh-Fl)/(2*C));
Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)];
if (p>z)
Sz = [Sz, zeros(1, (p-z))];
end
end
end
else
Fc = W;
if stop
% ---------------- ------------------------- ------------------------
% High Pass zero: Fc C/x pole: Fc C/x
% S -> C Fc/S pole: 0 zero: 0
% gain: -x gain: -1/x
% ---------------- ------------------------- ------------------------
if (isempty(Sz))
Sg = Sg * real (1./ prod(-Sp));
elseif (isempty(Sp))
Sg = Sg * real(prod(-Sz));
else
Sg = Sg * real(prod(-Sz)/prod(-Sp));
end
Sp = C * Fc ./ Sp;
if isempty(Sz)
Sz = zeros(1,p);
else
Sz = [C * Fc ./ Sz];
if (p > z)
Sz = [Sz, zeros(1,p-z)];
end
end
else
% ---------------- ------------------------- ------------------------
% Low Pass zero: Fc x/C pole: Fc x/C
% S -> C S/Fc gain: C/Fc gain: Fc/C
% ---------------- ------------------------- ------------------------
Sg = Sg * (C/Fc)^(z-p);
Sp = Fc * Sp / C;
Sz = Fc * Sz / C;
end
end
|
github
|
lcnhappe/happe-master
|
bilinear.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/signal/private/bilinear.m
| 4,339 |
utf_8
|
17250db27826cad87fa3384823e1242f
|
% Copyright (C) 1999 Paul Kienzle
%
% 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, see <http://www.gnu.org/licenses/>.
% usage: [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T)
% [Zb, Za] = bilinear(Sb, Sa, T)
%
% Transform a s-plane filter specification into a z-plane
% specification. Filters can be specified in either zero-pole-gain or
% transfer function form. The input form does not have to match the
% output form. 1/T is the sampling frequency represented in the z plane.
%
% Note: this differs from the bilinear function in the signal processing
% toolbox, which uses 1/T rather than T.
%
% Theory: Given a piecewise flat filter design, you can transform it
% from the s-plane to the z-plane while maintaining the band edges by
% means of the bilinear transform. This maps the left hand side of the
% s-plane into the interior of the unit circle. The mapping is highly
% non-linear, so you must design your filter with band edges in the
% s-plane positioned at 2/T tan(w*T/2) so that they will be positioned
% at w after the bilinear transform is complete.
%
% The following table summarizes the transformation:
%
% +---------------+-----------------------+----------------------+
% | Transform | Zero at x | Pole at x |
% | H(S) | H(S) = S-x | H(S)=1/(S-x) |
% +---------------+-----------------------+----------------------+
% | 2 z-1 | zero: (2+xT)/(2-xT) | zero: -1 |
% | S -> - --- | pole: -1 | pole: (2+xT)/(2-xT) |
% | T z+1 | gain: (2-xT)/T | gain: (2-xT)/T |
% +---------------+-----------------------+----------------------+
%
% With tedious algebra, you can derive the above formulae yourself by
% substituting the transform for S into H(S)=S-x for a zero at x or
% H(S)=1/(S-x) for a pole at x, and converting the result into the
% form:
%
% H(Z)=g prod(Z-Xi)/prod(Z-Xj)
%
% Please note that a pole and a zero at the same place exactly cancel.
% This is significant since the bilinear transform creates numerous
% extra poles and zeros, most of which cancel. Those which do not
% cancel have a 'fill-in' effect, extending the shorter of the sets to
% have the same number of as the longer of the sets of poles and zeros
% (or at least split the difference in the case of the band pass
% filter). There may be other opportunistic cancellations but I will
% not check for them.
%
% Also note that any pole on the unit circle or beyond will result in
% an unstable filter. Because of cancellation, this will only happen
% if the number of poles is smaller than the number of zeros. The
% analytic design methods all yield more poles than zeros, so this will
% not be a problem.
%
% References:
%
% Proakis & Manolakis (1992). Digital Signal Processing. New York:
% Macmillan Publishing Company.
% Author: Paul Kienzle <[email protected]>
function [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T)
if nargin==3
T = Sg;
[Sz, Sp, Sg] = tf2zp(Sz, Sp);
elseif nargin~=4
usage('[Zz, Zp, Zg]=bilinear(Sz,Sp,Sg,T) or [Zb, Za]=blinear(Sb,Sa,T)');
end;
p = length(Sp);
z = length(Sz);
if z > p || p==0
error('bilinear: must have at least as many poles as zeros in s-plane');
end
% ---------------- ------------------------- ------------------------
% Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT)
% 2 z-1 pole: -1 zero: -1
% S -> - --- gain: (2-xT)/T gain: (2-xT)/T
% T z+1
% ---------------- ------------------------- ------------------------
Zg = real(Sg * prod((2-Sz*T)/T) / prod((2-Sp*T)/T));
Zp = (2+Sp*T)./(2-Sp*T);
if isempty(Sz)
Zz = -ones(size(Zp));
else
Zz = [(2+Sz*T)./(2-Sz*T)];
Zz = postpad(Zz, p, -1);
end
if nargout==2, [Zz, Zp] = zp2tf(Zz, Zp, Zg); end
|
github
|
lcnhappe/happe-master
|
fns_region_write.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/fns/fns_region_write.m
| 1,267 |
utf_8
|
45ac73e5dd89386923a808a25a65dc99
|
%% TODO: Need to remove this routine.
function fns_region_write(rgnfile,rgn)
%
% This routine write the region information to the HDF5 file
%
% rgnfile The output region file.
% rgn The region of interest data structure.
% @author Hung Dang, July 13, 2010
% Write the description of stored data to the output file
hdf5write(rgnfile,'/region/info',rgn.info);
% Write the locations matrix to the /region/locations dataset
hdf5write(rgnfile,'/region/locations',rgn.locations,'WriteMode', ...
'append');
% Write the gridlocs matrix to the /region/gridlocs dataset
hdf5write(rgnfile,'/region/gridlocs',rgn.gridlocs,'WriteMode', ...
'append');
% Write the voxel_sizes vector to the /region/voxel_sizes dataset
hdf5write(rgnfile,'/region/voxel_sizes',rgn.voxel_sizes, ...
'WriteMode','append');
% Write the node_sizes vector to the /region/node_sizes dataset
hdf5write(rgnfile,'/region/node_sizes',rgn.node_sizes,'WriteMode', ...
'append');
% Write the status vector to the /region/status dataset
hdf5write(rgnfile,'/region/status',rgn.status,'WriteMode', ...
'append');
% Write the values vector to the /region/status dataset
hdf5write(rgnfile,'/region/values',rgn.values,'WriteMode', ...
'append');
|
github
|
lcnhappe/happe-master
|
fns_contable_write.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/fns/fns_contable_write.m
| 2,490 |
utf_8
|
3a266284afc0ca72cdb64b914acdf643
|
function cond = fns_contable_write(varargin)
% Creates the default conductivity table
%
% Use as
% cond = fns_contable_write
%
% The FNS convention for tissue types is the following:
% 0 "Clear Label"
% 1 "CSF"
% 2 "Gray Matter"
% 3 "White Matter"
% 4 "Fat"
% 5 "Muscle"
% 6 "Muscle/Skin"
% 7 "Skull"
% 8 "Vessels"
% 9 "Around Fat"
% 10 "Dura Matter"
% 11 "Bone Marrow"
% 12 "Eyes"
%
% Copyright (C) 2011, Hung Dang, Cristiano Micheli
tissue = ft_getopt(varargin, 'tissue', []);
tissueval = ft_getopt(varargin, 'tissueval', []);
tissuecond = ft_getopt(varargin, 'tissuecond', []);
if isempty(tissue) && isempty(tissueval) && isempty(tissuecond)
cond = createCondMat;
elseif isempty(tissueval) || isempty(tissuecond)
error('Both tissue value and conductivity inputs are necessary')
else
cond = zeros(9,numel(tissueval));
for i=1:numel(tissueval)
cond([1,5,9],i) = tissuecond(i);
end
end
function cond = createCondMat
cond = zeros(9,13);
% Brain tissues index
HH_OUTSIDE = 0;
HH_CSF = 1;
HH_GRAY_MATTER = 2;
HH_WHITE_MATTER = 3;
HH_FAT = 4;
HH_MUSCLE = 5;
HH_SKIN = 6;
HH_SKULL = 7;
HH_VESSELS = 8;
HH_AROUND_FAT = 9;
HH_DURA = 10;
HH_BONE_MARROW = 11;
HH_EYES = 12;
% Brain tissue conductivities
HH_OUTSIDE_CON = 0.00;
HH_CSF_CON = 1.79;
HH_WHITE_MATTER_CON = 0.14;
HH_GRAY_MATTER_CON = 0.33;
HH_FAT_CON = 0.04;
HH_MUSCLE_CON = 0.11;
HH_SKIN_CON = 0.44;
HH_SKULL_CON = 0.018;
HH_VESSELS_CON = 0.68;
HH_AROUND_FAT_CON = 0.22;
HH_DURA_CON = 0.17;
HH_BONE_MARROW_CON = 0.085;
HH_EYES_CON = 0.5;
% $$$ Create the conductivity table
cond([1,5,9],HH_OUTSIDE + 1) = HH_OUTSIDE_CON;
cond([1,5,9],HH_CSF + 1) = HH_CSF_CON;
cond([1,5,9],HH_WHITE_MATTER + 1) = HH_WHITE_MATTER_CON;
cond([1,5,9],HH_GRAY_MATTER + 1) = HH_GRAY_MATTER_CON;
cond([1,5,9],HH_FAT + 1) = HH_FAT_CON;
cond([1,5,9],HH_MUSCLE + 1) = HH_MUSCLE_CON;
cond([1,5,9],HH_SKULL + 1) = HH_SKULL_CON;
cond([1,5,9],HH_SKIN + 1) = HH_SKIN_CON;
cond([1,5,9],HH_VESSELS + 1) = HH_VESSELS_CON;
cond([1,5,9],HH_AROUND_FAT + 1) = HH_AROUND_FAT_CON;
cond([1,5,9],HH_DURA + 1) = HH_DURA_CON;
cond([1,5,9],HH_BONE_MARROW + 1) = HH_BONE_MARROW_CON;
cond([1,5,9],HH_EYES + 1) = HH_EYES_CON;
|
github
|
lcnhappe/happe-master
|
denoise_energy.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dss/denoise_energy.m
| 2,548 |
utf_8
|
276746592d3b53d810d56acb6c3c952f
|
function [params, s_new] = denoise_energy(params, s, state)
% Energy based DSS denoising function
% [params, s_new] = denoise_energy(params, s, state)
% params Function specific modifiable parameters
% params.usepow ... (default: 1.3)
% params.c ... (default: ?)
% params.var_noise Initial noise variance estimate (default: constant)
% state DSS algorithm state
% s Source signal estimate, matrix of row vector signals
% s_new Denoised signal estimate
% Copyright (C) 2004, 2005 DSS MATLAB package team ([email protected]).
% Distributed by Laboratory of Computer and Information Science,
% Helsinki University of Technology. http://www.cis.hut.fi/projects/dss/.
% $Id$
if nargin<3 | ~isstruct(state)
params.name = 'Energy based denoising';
params.description = '';
params.param = {'iternoise', 'usepow', 'var_noise'};
params.param_value ={1, 1.3, 1};
params.param_type = {'scalar', 'scalar', 'scalar'};
params.param_desc = {'Number of iterations for noise estimate', '', 'Initial noise variance estimate.'};
params.approach = {'defl'};
params.beta = {'beta_global'};
return;
end
if ~isfield(params, 'initialized')
% -- Initialize parameters once
params.initialized = 1;
if ~isfield(params,'iternoise')
params.iternoise = 1;
end
if ~isfield(params,'usepow')
params.usepow = 1.3;
end
if ~isfield(params,'gamma')
[p, var_smooth] = denoise_filter(params, randn(1, length(s)).^2, state);
noise_var = est_noise_var(var_smooth, 0);
params.c = 1 / noise_var;
%fprintf('Noise variance: %f', noise_var);
end
if ~isfield(params,'var_noise')
% Initial value for noise variance estimate is 1
params.var_noise = 1;
end
end
[p, var_totsm] = denoise_filter(params, s.^2, state);
for i = 1 : params.iternoise
params.var_noise = est_noise_var(var_totsm, params.var_noise)*params.c;
end
noise_stretched = repmat(params.var_noise, 1, size(var_totsm, 2));
var_sig = sqrt(noise_stretched.^2 + var_totsm.^2) - noise_stretched;
mask = var_sig.^params.usepow ./ var_totsm;
% TODO: is saturation necessary? (test if ever above 4)
% saturation -> 4
%mask = mask .* (mask < 4) + 4 * (mask >= 4);
if max(mask)>5
fprintf('[denoise_energy.m] Denoise energy mask saturation: %d\n', max(mask));
end
%mask = mask ./ repmat(mean(mask, 2), 1, size(mask, 2));
s_new = mask .* s;
% --------
function noise_var = est_noise_var(var_tot, var_noise)
noise_var = exp(mean(log(var_tot+repmat(var_noise,1,size(var_tot,2))),2))-var_noise;
|
github
|
lcnhappe/happe-master
|
denoise_filter.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dss/denoise_filter.m
| 2,143 |
utf_8
|
ae3a9902113a9f9a705cf8295dce183c
|
function [params, s_new] = denoise_filter(params, s, state)
% Generic filter function. Can be used as DSS denoising function.
% [params, s_new] = denoise_filter(params, s, state)
% params Defines the used filter
% params.filter_conv Inpulse response for convolution filter
% params.filter_dct Mask for DCT filter
% params.filter_fft Mask for FFT filter
% none of above Pass the signal unfiltered
% state DSS algorithm state (not used)
% s Source signal, matrix of row vector signals
% s_new Filtered signal
% Copyright (C) 2004, 2005 DSS MATLAB package team ([email protected]).
% Distributed by Laboratory of Computer and Information Science,
% Helsinki University of Technology. http://www.cis.hut.fi/projects/dss/.
% $Id$
if nargin<3
params.name = 'Generic filter';
params.description = 'Generic filter function for convolutive, DCT and FFT filtering';
params.param = {'filter_conv', 'filter_dct', 'filter_fft'};
params.param_value ={[], [], []};
params.param_type = {'vector', 'vector', 'vector'};
params.param_desc = {'Convolution coefficients', 'DCT filter coefficients', 'FFT filter coefficients.'};
params.approach = {'pca', 'defl', 'symm'};
params.beta = {'beta_global'};
return;
end
if isfield(params, 'filter_conv')
% -- Filter with impulse response
%s_new = conv(s, repmat(params.filter_conv, size(s, 1), 1));
%s_new = s_new(round(length(params.filter_conv)/2)+[1:length(s)]);
s_new = convolution(s, repmat(params.filter_conv, size(s, 1), 1));
elseif isfield(params, 'filter_dct')
% DCT filtering
s_new = idct(repmat(params.filter_dct, size(s,1), 1)' .* dct(s'))';
elseif isfield(params, 'filter_fft')
% FFT filtering
s_new = real(ifft(repmat(params.filter_fft, size(s,1), 1)' .* fft(s'))');
else
% -- No filtering
s_new = s;
end
% --------
% Calculate convolution for multiple row vector pairs and
% cut tails based on length of B.
function R = convolution(A, B)
R = zeros(size(A, 1), size(A,2)+size(B,2)-1);
for i=1:size(A,1)
R(i,:) = conv(A(i,:), B(i,:));
end
R = R(:,round(size(B,2)/2)+[1:size(A,2)]);
|
github
|
lcnhappe/happe-master
|
report_convergence.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dss/report_convergence.m
| 1,476 |
utf_8
|
e97824a6b7f960c982c55b90b63cc8cf
|
function [report_data] = report_convergence(report_data, state)
% Report convergence of the algorithm
% Copyright (C) 2004, 2005 DSS MATLAB package team ([email protected]).
% Distributed by Laboratory of Computer and Information Science,
% Helsinki University of Technology. http://www.cis.hut.fi/projects/dss/.
% $Id$
if ~isfield(report_data, 'report_interval')
report_data.report_interval = 5;
dss_message(state, 2, sprintf('Setting default report interval to %d (report_data.report_interval)\n', report_data.report_interval));
end
% deflation
if state.iteration==1
% -- first iteration
if state.algorithm=='defl'
% deflation
report_data.change(state.component,1)=0;
report_data.deltaw_old=state.w;
else
% symmetric
report_data.change = zeros(size(state.W, 1),1);
report_data.dW_old = zeros(size(state.W));
report_data.W_old = state.W;
end
else
% -- iterations 2->
if (mod(state.iteration, report_data.report_interval)==0)
if state.algorithm=='defl'
% deflation
change = acos(state.w' * state.w_old/norm(state.w)/norm(state.w_old)) / pi * 180;
else
% symmetric
change = abs(angle(state.W, state.W_old)) / pi * 180;
end
message(state,1,sprintf('Change (angles): %d\n', change));
end
end
% -----------------------------------
function rad = angle(A, B)
sum_cross = sum(A .* B, 2);
sum_A = sum(A .* A, 2);
sum_B = sum(B .* B, 2);
rad = acos(sum_cross ./ sum_A.^(-1/2) ./ sum_B.^(-1/2));
|
github
|
lcnhappe/happe-master
|
denss.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dss/denss.m
| 3,216 |
utf_8
|
6682365eb0d33779435c21332112ad78
|
function [state, B, A] = denss(X_or_state, parameters)
% Main DSS algorithm
% [state, B, A] = denss(X or state)
% [state, B, A] = denss(X or state, [params])
% [state, B, A] = denss(X or state, {param1, 'value1', param2, 'value2', ...})
% X Mixed signals
% state Existing or new algorithm state structure
% parameters Optional parameters
% B Unmixing matrix S = B * X
% A Mixing matrix X = A * S
%
% Main entry point for DSS algorithm. When called with mixed
% signals (X) creates state structure. Given optional parameters
% are inserted into new or existing state structure.
% Calls algorithm core defined by 'algorithm' state/param
% variable.
%
% See dss_create_state for description of state and parameter
% variables.
% Copyright (C) 2004, 2005 DSS MATLAB package team ([email protected]).
% Distributed by Laboratory of Computer and Information Science,
% Helsinki University of Technology. http://www.cis.hut.fi/projects/dss/.
% $Id$
% -- Initialize state
if nargin>=2 | ~isstruct(X_or_state)
% -- user gave X or parameters, initialize state
if nargin<2; parameters = []; end
state = dss_create_state(X_or_state, parameters);
else
state = X_or_state;
end
% -- Contract input dimensions
state = contract_dim(state, 'X');
state = contract_dim(state, 'Y');
state = contract_dim(state, 'S');
% read the version information
VERSION = fopen('VERSION','r');
if VERSION ~= -1
version = fgets(VERSION);
version = version(1:end-1);
dss_message(state,1,sprintf('Calculating DSS (release v%s)\n',version));
else
dss_message(state,1,'Calculating DSS (unknown release version)\n');
end
% -- Preprocessing
if ~isfield(state, 'Y')
state = dss_preprocess(state.X, state);
else
% Sphered data is already available, set sphering to identity
dss_message(state,2,'Sphered data exists, using it.');
if ~isfield(state, 'V') | ~isfield(state, 'dV')
state.V = diag(ones(size(state.Y,1),1));
state.dV = state.V;
dss_message(state,2,' No sphering matrix given. Assuming identity matrix.\n');
else
% using given sphering matrix
dss_message(state,2,'\n');
end
end
state.wdim = size(state.Y, 1);
if ~isfield(state, 'sdim'); state.sdim = state.wdim; end
% -- Call correct DSS algorithm implementation
state = feval(['dss_core_' state.algorithm], state);
% -- return the results
state.B = state.W * state.V;
B = state.B;
state.A = state.dV * state.W';
A = state.A;
%----------------------
function state = contract_dim(state, field_name)
if isfield(state, field_name)
% for ML65+: dims = size(state.(field_name));
dims = size(getfield(state, field_name));
if length(dims)>2
if isfield(state, 'input_dims') if state.input_dims ~= dims
error('Input signal dimension mismatch');
end; end;
state.input_dims = dims(2:length(dims));
% for ML65+: state.(field_name) = reshape(state.(field_name), dims(1), []);
state = setfield(state, field_name, reshape(getfield(state, field_name), dims(1), []));
dss_message(state,1,sprintf('Contracting [%s] dimensional input %s to [%s] dimension.\n', tostring(dims), field_name, tostring(size(getfield(state,field_name)))));
end
end
|
github
|
lcnhappe/happe-master
|
default_stop.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dss/default_stop.m
| 1,441 |
utf_8
|
219744b4c15669056f70c9575f12440a
|
function [stop, params] = default_stop(params, state)
% Default stopping criteria function.
% [stop, params] = default_stop(params, state)
% params Function specific modifiable parameters
% params.maxiters Maximum number of allowed iterations
% params.epsilon Treshold angle, iteration is stopped when
% angle beween consecutive iteration
% projection vectors goes below treshold.
% state DSS algorithm state
% stop Boolean, true when stopping criteria has been met
% Copyright (C) 2004, 2005 DSS MATLAB package team ([email protected]).
% Distributed by Laboratory of Computer and Information Science,
% Helsinki University of Technology. http://www.cis.hut.fi/projects/dss/.
% $Id$
if ~isfield(params, 'maxiters') & ...
(~isfield(params, 'epsilon') | ~isfield(state, 'w'))
error('Either ''maxiters'' or ''epsilon'' must be defined as stopping criteria');
end
stop = 0;
if isfield(params, 'maxiters')
if state.iteration>=params.maxiters
stop = 1;
return;
end
end
if isfield(params, 'epsilon')
if isfield(state, 'w')
change = angle(state.w_old, state.w) / pi * 180;
else
change = angle(state.W_old, state.W) / pi * 180;
end
stop = all(change < params.epsilon);
end
% --------
function rad = angle(A, B)
sum_cross = sum(A .* B);
sum_A = sum(A .* A);
sum_B = sum(B .* B);
rad = acos(sum_cross .* sum_A.^(-1/2) .* sum_B.^(-1/2));
|
github
|
lcnhappe/happe-master
|
estimate_mask.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dss/estimate_mask.m
| 1,695 |
utf_8
|
2147549d4388aa7913a35d434f4aa692
|
function [mask] = estimate_mask(s, filter_params, iterations)
% Creates binary mask based on SNR estimate of the signal
% [mask] = estimate_mask(s, filter_params, iterations)
% s Source signal
% filter_params Filter parameters for smoothing variance estimate
% iterations Number of iterations for estimating noise variance
% Copyright (C) 2004, 2005 DSS MATLAB package team ([email protected]).
% Distributed by Laboratory of Computer and Information Science,
% Helsinki University of Technology. http://www.cis.hut.fi/projects/dss/.
% $Id$
filter_h = @denoise_filter;
if nargin<2;
% default filtering is lowpass DCT
T = length(s);
t = 1:T;
filter_params.filter_dct = exp(-0.5*(t-1).^2 / (T/64).^2 );
end
if nargin<3; iterations = 8; end
% noise variance estimate for gaussian noise
[p, var_smooth] = feval(filter_h, filter_params, randn(1, length(s)).^2, []);
noise_var = est_noise_var(var_smooth, 0);
normalization_c = 1 / noise_var;
% smoothed variance
[p, var_totsm] = feval(filter_h, filter_params, s.^2, []);
% iterate signal noise variance estimate
var_noise = 1;
for i = 1 : iterations
var_noise = est_noise_var(var_totsm, var_noise)*normalization_c;
end
% create binary mask
mask = var_totsm>var_noise;
%DEBUG
%fprintf('Noise: %d\n', var_noise);
%clf
%subplot(3, 1, 1);
%plot(s);
%subplot(3, 1, 2);
%plot(var_totsm);
%subplot(3, 1, 3);
%plot(mask);
%axis([0 length(s) -0.5 1.5])
% --------
function noise_var = est_noise_var(var_tot, var_noise)
% Estimates noise variance based on total variance estimate and
% previous noise variance estimate.
noise_var = exp(mean(log(var_tot+repmat(var_noise,1,size(var_tot,2))),2))-var_noise;
|
github
|
lcnhappe/happe-master
|
pcamat.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/fastica/pcamat.m
| 12,028 |
utf_8
|
b597f6c30d7c0ad437ab6a408e0cc1fb
|
function [E, D] = pcamat(vectors, firstEig, lastEig, s_interactive, ...
s_verbose);
%PCAMAT - Calculates the pca for data
%
% [E, D] = pcamat(vectors, firstEig, lastEig, ...
% interactive, verbose);
%
% Calculates the PCA matrices for given data (row) vectors. Returns
% the eigenvector (E) and diagonal eigenvalue (D) matrices containing the
% selected subspaces. Dimensionality reduction is controlled with
% the parameters 'firstEig' and 'lastEig' - but it can also be done
% interactively by setting parameter 'interactive' to 'on' or 'gui'.
%
% ARGUMENTS
%
% vectors Data in row vectors.
% firstEig Index of the largest eigenvalue to keep.
% Default is 1.
% lastEig Index of the smallest eigenvalue to keep.
% Default is equal to dimension of vectors.
% interactive Specify eigenvalues to keep interactively. Note that if
% you set 'interactive' to 'on' or 'gui' then the values
% for 'firstEig' and 'lastEig' will be ignored, but they
% still have to be entered. If the value is 'gui' then the
% same graphical user interface as in FASTICAG will be
% used. Default is 'off'.
% verbose Default is 'on'.
%
%
% EXAMPLE
% [E, D] = pcamat(vectors);
%
% Note
% The eigenvalues and eigenvectors returned by PCAMAT are not sorted.
%
% This function is needed by FASTICA and FASTICAG
% For historical reasons this version does not sort the eigenvalues or
% the eigen vectors in any ways. Therefore neither does the FASTICA or
% FASTICAG. Generally it seams that the components returned from
% whitening is almost in reversed order. (That means, they usually are,
% but sometime they are not - depends on the EIG-command of matlab.)
% @(#)$Id$
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Default values:
if nargin < 5, s_verbose = 'on'; end
if nargin < 4, s_interactive = 'off'; end
if nargin < 3, lastEig = size(vectors, 1); end
if nargin < 2, firstEig = 1; end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check the optional parameters;
switch lower(s_verbose)
case 'on'
b_verbose = 1;
case 'off'
b_verbose = 0;
otherwise
error(sprintf('Illegal value [ %s ] for parameter: ''verbose''\n', s_verbose));
end
switch lower(s_interactive)
case 'on'
b_interactive = 1;
case 'off'
b_interactive = 0;
case 'gui'
b_interactive = 2;
otherwise
error(sprintf('Illegal value [ %s ] for parameter: ''interactive''\n', ...
s_interactive));
end
oldDimension = size (vectors, 1);
if ~(b_interactive)
if lastEig < 1 | lastEig > oldDimension
error(sprintf('Illegal value [ %d ] for parameter: ''lastEig''\n', lastEig));
end
if firstEig < 1 | firstEig > lastEig
error(sprintf('Illegal value [ %d ] for parameter: ''firstEig''\n', firstEig));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Calculate PCA
% Calculate the covariance matrix.
if b_verbose, fprintf ('Calculating covariance...\n'); end
covarianceMatrix = cov(vectors', 1);
% Calculate the eigenvalues and eigenvectors of covariance
% matrix.
[E, D] = eig (covarianceMatrix);
% The rank is determined from the eigenvalues - and not directly by
% using the function rank - because function rank uses svd, which
% in some cases gives a higher dimensionality than what can be used
% with eig later on (eig then gives negative eigenvalues).
rankTolerance = 1e-7;
maxLastEig = sum (diag (D) > rankTolerance);
if maxLastEig == 0,
fprintf (['Eigenvalues of the covariance matrix are' ...
' all smaller than tolerance [ %g ].\n' ...
'Please make sure that your data matrix contains' ...
' nonzero values.\nIf the values are very small,' ...
' try rescaling the data matrix.\n'], rankTolerance);
error ('Unable to continue, aborting.');
end
% Sort the eigenvalues - decending.
eigenvalues = flipud(sort(diag(D)));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Interactive part - command-line
if b_interactive == 1
% Show the eigenvalues to the user
hndl_win=figure;
bar(eigenvalues);
title('Eigenvalues');
% ask the range from the user...
% ... and keep on asking until the range is valid :-)
areValuesOK=0;
while areValuesOK == 0
firstEig = input('The index of the largest eigenvalue to keep? (1) ');
lastEig = input(['The index of the smallest eigenvalue to keep? (' ...
int2str(oldDimension) ') ']);
% Check the new values...
% if they are empty then use default values
if isempty(firstEig), firstEig = 1;end
if isempty(lastEig), lastEig = oldDimension;end
% Check that the entered values are within the range
areValuesOK = 1;
if lastEig < 1 | lastEig > oldDimension
fprintf('Illegal number for the last eigenvalue.\n');
areValuesOK = 0;
end
if firstEig < 1 | firstEig > lastEig
fprintf('Illegal number for the first eigenvalue.\n');
areValuesOK = 0;
end
end
% close the window
close(hndl_win);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Interactive part - GUI
if b_interactive == 2
% Show the eigenvalues to the user
hndl_win = figure('Color',[0.8 0.8 0.8], ...
'PaperType','a4letter', ...
'Units', 'normalized', ...
'Name', 'FastICA: Reduce dimension', ...
'NumberTitle','off', ...
'Tag', 'f_eig');
h_frame = uicontrol('Parent', hndl_win, ...
'BackgroundColor',[0.701961 0.701961 0.701961], ...
'Units', 'normalized', ...
'Position',[0.13 0.05 0.775 0.17], ...
'Style','frame', ...
'Tag','f_frame');
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'BackgroundColor',[0.701961 0.701961 0.701961], ...
'HorizontalAlignment','left', ...
'Position',[0.142415 0.0949436 0.712077 0.108507], ...
'String','Give the indices of the largest and smallest eigenvalues of the covariance matrix to be included in the reduced data.', ...
'Style','text', ...
'Tag','StaticText1');
e_first = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'Callback',[ ...
'f=round(str2num(get(gcbo, ''String'')));' ...
'if (f < 1), f=1; end;' ...
'l=str2num(get(findobj(''Tag'',''e_last''), ''String''));' ...
'if (f > l), f=l; end;' ...
'set(gcbo, ''String'', int2str(f));' ...
], ...
'BackgroundColor',[1 1 1], ...
'HorizontalAlignment','right', ...
'Position',[0.284831 0.0678168 0.12207 0.0542535], ...
'Style','edit', ...
'String', '1', ...
'Tag','e_first');
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'BackgroundColor',[0.701961 0.701961 0.701961], ...
'HorizontalAlignment','left', ...
'Position',[0.142415 0.0678168 0.12207 0.0542535], ...
'String','Range from', ...
'Style','text', ...
'Tag','StaticText2');
e_last = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'Callback',[ ...
'l=round(str2num(get(gcbo, ''String'')));' ...
'lmax = get(gcbo, ''UserData'');' ...
'if (l > lmax), l=lmax; fprintf([''The selected value was too large, or the selected eigenvalues were close to zero\n'']); end;' ...
'f=str2num(get(findobj(''Tag'',''e_first''), ''String''));' ...
'if (l < f), l=f; end;' ...
'set(gcbo, ''String'', int2str(l));' ...
], ...
'BackgroundColor',[1 1 1], ...
'HorizontalAlignment','right', ...
'Position',[0.467936 0.0678168 0.12207 0.0542535], ...
'Style','edit', ...
'String', int2str(maxLastEig), ...
'UserData', maxLastEig, ...
'Tag','e_last');
% in the first version oldDimension was used instead of
% maxLastEig, but since the program would automatically
% drop the eigenvalues afte maxLastEig...
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'BackgroundColor',[0.701961 0.701961 0.701961], ...
'HorizontalAlignment','left', ...
'Position',[0.427246 0.0678168 0.0406901 0.0542535], ...
'String','to', ...
'Style','text', ...
'Tag','StaticText3');
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'Callback','uiresume(gcbf)', ...
'Position',[0.630697 0.0678168 0.12207 0.0542535], ...
'String','OK', ...
'Tag','Pushbutton1');
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'Callback',[ ...
'gui_help(''pcamat'');' ...
], ...
'Position',[0.767008 0.0678168 0.12207 0.0542535], ...
'String','Help', ...
'Tag','Pushbutton2');
h_axes = axes('Position' ,[0.13 0.3 0.775 0.6]);
set(hndl_win, 'currentaxes',h_axes);
bar(eigenvalues);
title('Eigenvalues');
uiwait(hndl_win);
firstEig = str2num(get(e_first, 'String'));
lastEig = str2num(get(e_last, 'String'));
% close the window
close(hndl_win);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% See if the user has reduced the dimension enought
if lastEig > maxLastEig
lastEig = maxLastEig;
if b_verbose
fprintf('Dimension reduced to %d due to the singularity of covariance matrix\n',...
lastEig-firstEig+1);
end
else
% Reduce the dimensionality of the problem.
if b_verbose
if oldDimension == (lastEig - firstEig + 1)
fprintf ('Dimension not reduced.\n');
else
fprintf ('Reducing dimension...\n');
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Drop the smaller eigenvalues
if lastEig < oldDimension
lowerLimitValue = (eigenvalues(lastEig) + eigenvalues(lastEig + 1)) / 2;
else
lowerLimitValue = eigenvalues(oldDimension) - 1;
end
lowerColumns = diag(D) > lowerLimitValue;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Drop the larger eigenvalues
if firstEig > 1
higherLimitValue = (eigenvalues(firstEig - 1) + eigenvalues(firstEig)) / 2;
else
higherLimitValue = eigenvalues(1) + 1;
end
higherColumns = diag(D) < higherLimitValue;
% Combine the results from above
selectedColumns = lowerColumns & higherColumns;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% print some info for the user
if b_verbose
fprintf ('Selected [ %d ] dimensions.\n', sum (selectedColumns));
end
if sum (selectedColumns) ~= (lastEig - firstEig + 1),
error ('Selected a wrong number of dimensions.');
end
if b_verbose
fprintf ('Smallest remaining (non-zero) eigenvalue [ %g ]\n', eigenvalues(lastEig));
fprintf ('Largest remaining (non-zero) eigenvalue [ %g ]\n', eigenvalues(firstEig));
fprintf ('Sum of removed eigenvalues [ %g ]\n', sum(diag(D) .* ...
(~selectedColumns)));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Select the colums which correspond to the desired range
% of eigenvalues.
E = selcol(E, selectedColumns);
D = selcol(selcol(D, selectedColumns)', selectedColumns);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Some more information
if b_verbose
sumAll=sum(eigenvalues);
sumUsed=sum(diag(D));
retained = (sumUsed / sumAll) * 100;
fprintf('[ %g ] %% of (non-zero) eigenvalues retained.\n', retained);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function newMatrix = selcol(oldMatrix, maskVector);
% newMatrix = selcol(oldMatrix, maskVector);
%
% Selects the columns of the matrix that marked by one in the given vector.
% The maskVector is a column vector.
% 15.3.1998
if size(maskVector, 1) ~= size(oldMatrix, 2),
error ('The mask vector and matrix are of uncompatible size.');
end
numTaken = 0;
for i = 1 : size (maskVector, 1),
if maskVector(i, 1) == 1,
takingMask(1, numTaken + 1) = i;
numTaken = numTaken + 1;
end
end
newMatrix = oldMatrix(:, takingMask);
|
github
|
lcnhappe/happe-master
|
icaplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/fastica/icaplot.m
| 13,211 |
utf_8
|
066670e2905b35f198920d743c74faf5
|
function icaplot(mode, varargin);
%ICAPLOT - plot signals in various ways
%
% ICAPLOT is mainly for plottinf and comparing the mixed signals and
% separated ica-signals.
%
% ICAPLOT has many different modes. The first parameter of the function
% defines the mode. Other parameters and their order depends on the
% mode. The explanation for the more common parameters is in the end.
%
% Classic
% icaplot('classic', s1, n1, range, xrange, titlestr)
%
% Plots the signals in the same manner as the FASTICA and FASTICAG
% programs do. All the signals are plotted in their own axis.
%
% Complot
% icaplot('complot', s1, n1, range, xrange, titlestr)
%
% The signals are plotted on the same axis. This is good for
% visualization of the shape of the signals. The scale of the signals
% has been altered so that they all fit nicely.
%
% Histogram
% icaplot('histogram', s1, n1, range, bins, style)
%
% The histogram of the signals is plotted. The number of bins can be
% specified with 'bins'-parameter. The style for the histograms can
% be either 'bar' (default) of 'line'.
%
% Scatter
% icaplot('scatter', s1, n1, s2, n2, range, titlestr, s1label,
% s2label, markerstr)
%
% A scatterplot is plotted so that the signal 1 is the 'X'-variable
% and the signal 2 is the 'Y'-variable. The 'markerstr' can be used
% to specify the maker used in the plot. The format for 'markerstr'
% is the same as for Matlab's PLOT.
%
% Compare
% icaplot('compare', s1, n1, s2, n2, range, xrange, titlestr,
% s1label, s2label)
%
% This for for comparing two signals. The main used in this context
% would probably be to see how well the separated ICA-signals explain
% the observed mixed signals. The s2 signals are first scaled with
% REGRESS function.
%
% Compare - Sum
% icaplot('sum', s1, n1, s2, n2, range, xrange, titlestr, s1label,
% s2label)
%
% The same as Compare, but this time the signals in s2 (specified by
% n2) are summed together.
%
% Compare - Sumerror
% icaplot('sumerror', s1, n1, s2, n2, range, xrange, titlestr,
% s1label, s2label)
%
% The same as Compare - Sum, but also the 'error' between the signal
% 1 and the summed IC's is plotted.
%
%
% More common parameters
% The signals to be plotted are in matrices s1 and s2. The n1 and n2
% are used to tell the index of the signal or signals to be plotted
% from s1 or s2. If n1 or n2 has a value of 0, then all the signals
% from corresponding matrix will be plotted. The values for n1 and n2
% can also be vectors (like: [1 3 4]) In some casee if there are more
% than 1 signal to be plotted from s1 or s2 then the plot will
% contain as many subplots as are needed.
%
% The range of the signals to be plotted can be limited with
% 'range'-parameter. It's value is a vector ( 10000:15000 ). If range
% is 0, then the whole range will be plotted.
%
% The 'xrange' is used to specify only the labels used on the
% x-axis. The value of 'xrange' is a vector containing the x-values
% for the plots or [start end] for begin and end of the range
% ( 10000:15000 or [10 15] ). If xrange is 0, then value of range
% will be used for x-labels.
%
% You can give a title for the plot with 'titlestr'. Also the
% 's1label' and 's2label' are used to give more meaningfull label for
% the signals.
%
% Lastly, you can omit some of the arguments from the and. You will
% have to give values for the signal matrices (s1, s2) and the
% indexes (n1, n2)
% @(#)$Id$
switch mode
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 'dispsig' is to replace the old DISPSIG
% '' & 'classic' are just another names - '' quite short one :-)
case {'', 'classic', 'dispsig'}
% icaplot(mode, s1, n1, range, xrange, titlestr)
if length(varargin) < 1, error('Not enough arguments.'); end
if length(varargin) < 5, titlestr = '';else titlestr = varargin{5}; end
if length(varargin) < 4, xrange = 0;else xrange = varargin{4}; end
if length(varargin) < 3, range = 0;else range = varargin{3}; end
if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end
s1 = varargin{1};
range=chkrange(range, s1);
xrange=chkxrange(xrange, range);
n1=chkn(n1, s1);
clf;
numSignals = size(n1, 2);
for i = 1:numSignals,
subplot(numSignals, 1, i);
plot(xrange, s1(n1(i), range));
end
subplot(numSignals,1, 1);
if (~isempty(titlestr))
title(titlestr);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'complot'
% icaplot(mode, s1, n1, range, xrange, titlestr)
if length(varargin) < 1, error('Not enough arguments.'); end
if length(varargin) < 5, titlestr = '';else titlestr = varargin{5}; end
if length(varargin) < 4, xrange = 0;else xrange = varargin{4}; end
if length(varargin) < 3, range = 0;else range = varargin{3}; end
if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end
s1 = remmean(varargin{1});
range=chkrange(range, s1);
xrange=chkxrange(xrange, range);
n1=chkn(n1, s1);
for i = 1:size(n1, 2)
S1(i, :) = s1(n1(i), range);
end
alpha = mean(max(S1')-min(S1'));
for i = 1:size(n1,2)
S2(i,:) = S1(i,:) - alpha*(i-1)*ones(size(S1(1,:)));
end
plot(xrange, S2');
axis([min(xrange) max(xrange) min(min(S2)) max(max(S2)) ]);
set(gca,'YTick',(-size(S1,1)+1)*alpha:alpha:0);
set(gca,'YTicklabel',fliplr(n1));
if (~isempty(titlestr))
title(titlestr);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'histogram'
% icaplot(mode, s1, n1, range, bins, style)
if length(varargin) < 1, error('Not enough arguments.'); end
if length(varargin) < 5, style = 'bar';else style = varargin{5}; end
if length(varargin) < 4, bins = 10;else bins = varargin{4}; end
if length(varargin) < 3, range = 0;else range = varargin{3}; end
if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end
s1 = varargin{1};
range = chkrange(range, s1);
n1 = chkn(n1, s1);
numSignals = size(n1, 2);
rows = floor(sqrt(numSignals));
columns = ceil(sqrt(numSignals));
while (rows * columns < numSignals)
columns = columns + 1;
end
switch style
case {'', 'bar'}
for i = 1:numSignals,
subplot(rows, columns, i);
hist(s1(n1(i), range), bins);
title(int2str(n1(i)));
drawnow;
end
case 'line'
for i = 1:numSignals,
subplot(rows, columns, i);
[Y, X]=hist(s1(n1(i), range), bins);
plot(X, Y);
title(int2str(n1(i)));
drawnow;
end
otherwise
fprintf('Unknown style.\n')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'scatter'
% icaplot(mode, s1, n1, s2, n2, range, titlestr, xlabelstr, ylabelstr, markerstr)
if length(varargin) < 4, error('Not enough arguments.'); end
if length(varargin) < 9, markerstr = '.';else markerstr = varargin{9}; end
if length(varargin) < 8, ylabelstr = 'Signal 2';else ylabelstr = varargin{8}; end
if length(varargin) < 7, xlabelstr = 'Signal 1';else xlabelstr = varargin{7}; end
if length(varargin) < 6, titlestr = '';else titlestr = varargin{6}; end
if length(varargin) < 5, range = 0;else range = varargin{5}; end
n2 = varargin{4};
s2 = varargin{3};
n1 = varargin{2};
s1 = varargin{1};
range = chkrange(range, s1);
n1 = chkn(n1, s1);
n2 = chkn(n2, s2);
rows = size(n1, 2);
columns = size(n2, 2);
for r = 1:rows
for c = 1:columns
subplot(rows, columns, (r-1)*columns + c);
plot(s1(n1(r), range),s2(n2(c), range),markerstr);
if (~isempty(titlestr))
title(titlestr);
end
if (rows*columns == 1)
xlabel(xlabelstr);
ylabel(ylabelstr);
else
xlabel([xlabelstr ' (' int2str(n1(r)) ')']);
ylabel([ylabelstr ' (' int2str(n2(c)) ')']);
end
drawnow;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case {'compare', 'sum', 'sumerror'}
% icaplot(mode, s1, n1, s2, n2, range, xrange, titlestr, s1label, s2label)
if length(varargin) < 4, error('Not enough arguments.'); end
if length(varargin) < 9, s2label = 'IC';else s2label = varargin{9}; end
if length(varargin) < 8, s1label = 'Mix';else s1label = varargin{8}; end
if length(varargin) < 7, titlestr = '';else titlestr = varargin{7}; end
if length(varargin) < 6, xrange = 0;else xrange = varargin{6}; end
if length(varargin) < 5, range = 0;else range = varargin{5}; end
s1 = varargin{1};
n1 = varargin{2};
s2 = varargin{3};
n2 = varargin{4};
range = chkrange(range, s1);
xrange = chkxrange(xrange, range);
n1 = chkn(n1, s1);
n2 = chkn(n2, s2);
numSignals = size(n1, 2);
if (numSignals > 1)
externalLegend = 1;
else
externalLegend = 0;
end
rows = floor(sqrt(numSignals+externalLegend));
columns = ceil(sqrt(numSignals+externalLegend));
while (rows * columns < (numSignals+externalLegend))
columns = columns + 1;
end
clf;
for j = 1:numSignals
subplot(rows, columns, j);
switch mode
case 'compare'
plotcompare(s1, n1(j), s2,n2, range, xrange);
[legendtext,legendstyle]=legendcompare(n1(j),n2,s1label,s2label,externalLegend);
case 'sum'
plotsum(s1, n1(j), s2,n2, range, xrange);
[legendtext,legendstyle]=legendsum(n1(j),n2,s1label,s2label,externalLegend);
case 'sumerror'
plotsumerror(s1, n1(j), s2,n2, range, xrange);
[legendtext,legendstyle]=legendsumerror(n1(j),n2,s1label,s2label,externalLegend);
end
if externalLegend
title([titlestr ' (' s1label ' ' int2str(n1(j)) ')']);
else
legend(char(legendtext));
if (~isempty(titlestr))
title(titlestr);
end
end
end
if (externalLegend)
subplot(rows, columns, numSignals+1);
legendsize = size(legendtext, 2);
hold on;
for i=1:legendsize
plot([0 1],[legendsize-i legendsize-i], char(legendstyle(i)));
text(1.5, legendsize-i, char(legendtext(i)));
end
hold off;
axis([0 6 -1 legendsize]);
axis off;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotcompare(s1, n1, s2, n2, range, xrange);
style=getStyles;
K = regress(s1(n1,:)',s2');
plot(xrange, s1(n1,range), char(style(1)));
hold on
for i=1:size(n2,2)
plotstyle=char(style(i+1));
plot(xrange, K(n2(i))*s2(n2(i),range), plotstyle);
end
hold off
function [legendText, legendStyle]=legendcompare(n1, n2, s1l, s2l, externalLegend);
style=getStyles;
if (externalLegend)
legendText(1)={[s1l ' (see the titles)']};
else
legendText(1)={[s1l ' ', int2str(n1)]};
end
legendStyle(1)=style(1);
for i=1:size(n2, 2)
legendText(i+1) = {[s2l ' ' int2str(n2(i))]};
legendStyle(i+1) = style(i+1);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotsum(s1, n1, s2, n2, range, xrange);
K = diag(regress(s1(n1,:)',s2'));
sigsum = sum(K(:,n2)*s2(n2,:));
plot(xrange, s1(n1, range),'k-', ...
xrange, sigsum(range), 'b-');
function [legendText, legendStyle]=legendsum(n1, n2, s1l, s2l, externalLegend);
if (externalLegend)
legendText(1)={[s1l ' (see the titles)']};
else
legendText(1)={[s1l ' ', int2str(n1)]};
end
legendText(2)={['Sum of ' s2l ': ', int2str(n2)]};
legendStyle={'k-';'b-'};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotsumerror(s1, n1, s2, n2, range, xrange);
K = diag(regress(s1(n1,:)',s2'));
sigsum = sum(K(:,n2)*s2(n2,:));
plot(xrange, s1(n1, range),'k-', ...
xrange, sigsum(range), 'b-', ...
xrange, s1(n1, range)-sigsum(range), 'r-');
function [legendText, legendStyle]=legendsumerror(n1, n2, s1l, s2l, externalLegend);
if (externalLegend)
legendText(1)={[s1l ' (see the titles)']};
else
legendText(1)={[s1l ' ', int2str(n1)]};
end
legendText(2)={['Sum of ' s2l ': ', int2str(n2)]};
legendText(3)={'"Error"'};
legendStyle={'k-';'b-';'r-'};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function style=getStyles;
color = {'k','r','g','b','m','c','y'};
line = {'-',':','-.','--'};
for i = 0:size(line,2)-1
for j = 1:size(color, 2)
style(j + i*size(color, 2)) = strcat(color(j), line(i+1));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function range=chkrange(r, s)
if r == 0
range = 1:size(s, 2);
else
range = r;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xrange=chkxrange(xr,r);
if xr == 0
xrange = r;
elseif size(xr, 2) == 2
xrange = xr(1):(xr(2)-xr(1))/(size(r,2)-1):xr(2);
elseif size(xr, 2)~=size(r, 2)
error('Xrange and range have different sizes.');
else
xrange = xr;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function n=chkn(n,s)
if n == 0
n = 1:size(s, 1);
end
|
github
|
lcnhappe/happe-master
|
cond_indep_fisher_z.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMstats/cond_indep_fisher_z.m
| 3,635 |
utf_8
|
74e2c5c915700e2f7a672113e333f813
|
function [CI, r, p] = cond_indep_fisher_z(X, Y, S, C, N, alpha)
% COND_INDEP_FISHER_Z Test if X indep Y given Z using Fisher's Z test
% CI = cond_indep_fisher_z(X, Y, S, C, N, alpha)
%
% C is the covariance (or correlation) matrix
% N is the sample size
% alpha is the significance level (default: 0.05)
%
% See p133 of T. Anderson, "An Intro. to Multivariate Statistical Analysis", 1984
if nargin < 6, alpha = 0.05; end
r = partial_corr_coef(C, X, Y, S);
z = 0.5*log( (1+r)/(1-r) );
z0 = 0;
W = sqrt(N - length(S) - 3)*(z-z0); % W ~ N(0,1)
cutoff = norminv(1 - 0.5*alpha); % P(|W| <= cutoff) = 0.95
%cutoff = mynorminv(1 - 0.5*alpha); % P(|W| <= cutoff) = 0.95
if abs(W) < cutoff
CI = 1;
else % reject the null hypothesis that rho = 0
CI = 0;
end
p = normcdf(W);
%p = mynormcdf(W);
%%%%%%%%%
function p = normcdf(x,mu,sigma)
%NORMCDF Normal cumulative distribution function (cdf).
% P = NORMCDF(X,MU,SIGMA) computes the normal cdf with mean MU and
% standard deviation SIGMA at the values in X.
%
% The size of P is the common size of X, MU and SIGMA. A scalar input
% functions as a constant matrix of the same size as the other inputs.
%
% Default values for MU and SIGMA are 0 and 1 respectively.
% References:
% [1] M. Abramowitz and I. A. Stegun, "Handbook of Mathematical
% Functions", Government Printing Office, 1964, 26.2.
% Copyright (c) 1993-98 by The MathWorks, Inc.
% $Revision$ $Date: 2004/02/10 18:58:56 $
if nargin < 3,
sigma = 1;
end
if nargin < 2;
mu = 0;
end
[errorcode x mu sigma] = distchck(3,x,mu,sigma);
if errorcode > 0
error('Requires non-scalar arguments to match in size.');
end
% Initialize P to zero.
p = zeros(size(x));
% Return NaN if SIGMA is not positive.
k1 = find(sigma <= 0);
if any(k1)
tmp = NaN;
p(k1) = tmp(ones(size(k1)));
end
% Express normal CDF in terms of the error function.
k = find(sigma > 0);
if any(k)
p(k) = 0.5 * erfc( - (x(k) - mu(k)) ./ (sigma(k) * sqrt(2)));
end
% Make sure that round-off errors never make P greater than 1.
k2 = find(p > 1);
if any(k2)
p(k2) = ones(size(k2));
end
%%%%%%%%
function x = norminv(p,mu,sigma);
%NORMINV Inverse of the normal cumulative distribution function (cdf).
% X = NORMINV(P,MU,SIGMA) finds the inverse of the normal cdf with
% mean, MU, and standard deviation, SIGMA.
%
% The size of X is the common size of the input arguments. A scalar input
% functions as a constant matrix of the same size as the other inputs.
%
% Default values for MU and SIGMA are 0 and 1 respectively.
% References:
% [1] M. Abramowitz and I. A. Stegun, "Handbook of Mathematical
% Functions", Government Printing Office, 1964, 7.1.1 and 26.2.2
% Copyright (c) 1993-98 by The MathWorks, Inc.
% $Revision$ $Date: 2004/02/10 18:58:56 $
if nargin < 3,
sigma = 1;
end
if nargin < 2;
mu = 0;
end
[errorcode p mu sigma] = distchck(3,p,mu,sigma);
if errorcode > 0
error('Requires non-scalar arguments to match in size.');
end
% Allocate space for x.
x = zeros(size(p));
% Return NaN if the arguments are outside their respective limits.
k = find(sigma <= 0 | p < 0 | p > 1);
if any(k)
tmp = NaN;
x(k) = tmp(ones(size(k)));
end
% Put in the correct values when P is either 0 or 1.
k = find(p == 0);
if any(k)
tmp = Inf;
x(k) = -tmp(ones(size(k)));
end
k = find(p == 1);
if any(k)
tmp = Inf;
x(k) = tmp(ones(size(k)));
end
% Compute the inverse function for the intermediate values.
k = find(p > 0 & p < 1 & sigma > 0);
if any(k),
x(k) = sqrt(2) * sigma(k) .* erfinv(2 * p(k) - 1) + mu(k);
end
|
github
|
lcnhappe/happe-master
|
logistK.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMstats/logistK.m
| 7,253 |
utf_8
|
9539c8105ebca14d632373f5f9f4b70d
|
function [beta,post,lli] = logistK(x,y,w,beta)
% [beta,post,lli] = logistK(x,y,beta,w)
%
% k-class logistic regression with optional sample weights
%
% k = number of classes
% n = number of samples
% d = dimensionality of samples
%
% INPUT
% x dxn matrix of n input column vectors
% y kxn vector of class assignments
% [w] 1xn vector of sample weights
% [beta] dxk matrix of model coefficients
%
% OUTPUT
% beta dxk matrix of fitted model coefficients
% (beta(:,k) are fixed at 0)
% post kxn matrix of fitted class posteriors
% lli log likelihood
%
% Let p(i,j) = exp(beta(:,j)'*x(:,i)),
% Class j posterior for observation i is:
% post(j,i) = p(i,j) / (p(i,1) + ... p(i,k))
%
% See also logistK_eval.
%
% David Martin <[email protected]>
% May 3, 2002
% Copyright (C) 2002 David R. Martin <[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, or see http://www.gnu.org/copyleft/gpl.html.
% TODO - this code would be faster if x were transposed
error(nargchk(2,4,nargin));
debug = 0;
if debug>0,
h=figure(1);
set(h,'DoubleBuffer','on');
end
% get sizes
[d,nx] = size(x);
[k,ny] = size(y);
% check sizes
if k < 2,
error('Input y must encode at least 2 classes.');
end
if nx ~= ny,
error('Inputs x,y not the same length.');
end
n = nx;
% make sure class assignments have unit L1-norm
sumy = sum(y,1);
if abs(1-sumy) > eps,
sumy = sum(y,1);
for i = 1:k, y(i,:) = y(i,:) ./ sumy; end
end
clear sumy;
% if sample weights weren't specified, set them to 1
if nargin < 3,
w = ones(1,n);
end
% normalize sample weights so max is 1
w = w / max(w);
% if starting beta wasn't specified, initialize randomly
if nargin < 4,
beta = 1e-3*rand(d,k);
beta(:,k) = 0; % fix beta for class k at zero
else
if sum(beta(:,k)) ~= 0,
error('beta(:,k) ~= 0');
end
end
stepsize = 1;
minstepsize = 1e-2;
post = computePost(beta,x);
lli = computeLogLik(post,y,w);
for iter = 1:100,
%disp(sprintf(' logist iter=%d lli=%g',iter,lli));
vis(x,y,beta,lli,d,k,iter,debug);
% gradient and hessian
[g,h] = derivs(post,x,y,w);
% make sure Hessian is well conditioned
if rcond(h) < eps,
% condition with Levenberg-Marquardt method
for i = -16:16,
h2 = h .* ((1 + 10^i)*eye(size(h)) + (1-eye(size(h))));
if rcond(h2) > eps, break, end
end
if rcond(h2) < eps,
warning(['Stopped at iteration ' num2str(iter) ...
' because Hessian can''t be conditioned']);
break
end
h = h2;
end
% save lli before update
lli_prev = lli;
% Newton-Raphson with step-size halving
while stepsize >= minstepsize,
% Newton-Raphson update step
step = stepsize * (h \ g);
beta2 = beta;
beta2(:,1:k-1) = beta2(:,1:k-1) - reshape(step,d,k-1);
% get the new log likelihood
post2 = computePost(beta2,x);
lli2 = computeLogLik(post2,y,w);
% if the log likelihood increased, then stop
if lli2 > lli,
post = post2; lli = lli2; beta = beta2;
break
end
% otherwise, reduce step size by half
stepsize = 0.5 * stepsize;
end
% stop if the average log likelihood has gotten small enough
if 1-exp(lli/n) < 1e-2, break, end
% stop if the log likelihood changed by a small enough fraction
dlli = (lli_prev-lli) / lli;
if abs(dlli) < 1e-3, break, end
% stop if the step size has gotten too small
if stepsize < minstepsize, brea, end
% stop if the log likelihood has decreased; this shouldn't happen
if lli < lli_prev,
warning(['Stopped at iteration ' num2str(iter) ...
' because the log likelihood decreased from ' ...
num2str(lli_prev) ' to ' num2str(lli) '.' ...
' This may be a bug.']);
break
end
end
if debug>0,
vis(x,y,beta,lli,d,k,iter,2);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% class posteriors
function post = computePost(beta,x)
[d,n] = size(x);
[d,k] = size(beta);
post = zeros(k,n);
bx = zeros(k,n);
for j = 1:k,
bx(j,:) = beta(:,j)'*x;
end
for j = 1:k,
post(j,:) = 1 ./ sum(exp(bx - repmat(bx(j,:),k,1)),1);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% log likelihood
function lli = computeLogLik(post,y,w)
[k,n] = size(post);
lli = 0;
for j = 1:k,
lli = lli + sum(w.*y(j,:).*log(post(j,:)+eps));
end
if isnan(lli),
error('lli is nan');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% gradient and hessian
%% These are computed in what seems a verbose manner, but it is
%% done this way to use minimal memory. x should be transposed
%% to make it faster.
function [g,h] = derivs(post,x,y,w)
[k,n] = size(post);
[d,n] = size(x);
% first derivative of likelihood w.r.t. beta
g = zeros(d,k-1);
for j = 1:k-1,
wyp = w .* (y(j,:) - post(j,:));
for ii = 1:d,
g(ii,j) = x(ii,:) * wyp';
end
end
g = reshape(g,d*(k-1),1);
% hessian of likelihood w.r.t. beta
h = zeros(d*(k-1),d*(k-1));
for i = 1:k-1, % diagonal
wt = w .* post(i,:) .* (1 - post(i,:));
hii = zeros(d,d);
for a = 1:d,
wxa = wt .* x(a,:);
for b = a:d,
hii_ab = wxa * x(b,:)';
hii(a,b) = hii_ab;
hii(b,a) = hii_ab;
end
end
h( (i-1)*d+1 : i*d , (i-1)*d+1 : i*d ) = -hii;
end
for i = 1:k-1, % off-diagonal
for j = i+1:k-1,
wt = w .* post(j,:) .* post(i,:);
hij = zeros(d,d);
for a = 1:d,
wxa = wt .* x(a,:);
for b = a:d,
hij_ab = wxa * x(b,:)';
hij(a,b) = hij_ab;
hij(b,a) = hij_ab;
end
end
h( (i-1)*d+1 : i*d , (j-1)*d+1 : j*d ) = hij;
h( (j-1)*d+1 : j*d , (i-1)*d+1 : i*d ) = hij;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% debug/visualization
function vis (x,y,beta,lli,d,k,iter,debug)
if debug<=0, return, end
disp(['iter=' num2str(iter) ' lli=' num2str(lli)]);
if debug<=1, return, end
if d~=3 | k>10, return, end
figure(1);
res = 100;
r = abs(max(max(x)));
dom = linspace(-r,r,res);
[px,py] = meshgrid(dom,dom);
xx = px(:); yy = py(:);
points = [xx' ; yy' ; ones(1,res*res)];
func = zeros(k,res*res);
for j = 1:k,
func(j,:) = exp(beta(:,j)'*points);
end
[mval,ind] = max(func,[],1);
hold off;
im = reshape(ind,res,res);
imagesc(xx,yy,im);
hold on;
syms = {'w.' 'wx' 'w+' 'wo' 'w*' 'ws' 'wd' 'wv' 'w^' 'w<'};
for j = 1:k,
[mval,ind] = max(y,[],1);
ind = find(ind==j);
plot(x(1,ind),x(2,ind),syms{j});
end
pause(0.1);
% eof
|
github
|
lcnhappe/happe-master
|
dhmm_em.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/hmm/dhmm_em.m
| 3,862 |
utf_8
|
83f088af19f326cf34ba80629cff4d01
|
function [LL, prior, transmat, obsmat] = dhmm_em(data, prior, transmat, obsmat, varargin)
% LEARN_DHMM Find the ML/MAP parameters of an HMM with discrete outputs using EM.
% [ll_trace, prior, transmat, obsmat] = learn_dhmm(data, prior0, transmat0, obsmat0, ...)
%
% Notation: Q(t) = hidden state, Y(t) = observation
%
% INPUTS:
% data{ex} or data(ex,:) if all sequences have the same length
% prior(i)
% transmat(i,j)
% obsmat(i,o)
%
% Optional parameters may be passed as 'param_name', param_value pairs.
% Parameter names are shown below; default values in [] - if none, argument is mandatory.
%
% 'max_iter' - max number of EM iterations [10]
% 'thresh' - convergence threshold [1e-4]
% 'verbose' - if 1, print out loglik at every iteration [1]
% 'obs_prior_weight' - weight to apply to uniform dirichlet prior on observation matrix [0]
%
% To clamp some of the parameters, so learning does not change them:
% 'adj_prior' - if 0, do not change prior [1]
% 'adj_trans' - if 0, do not change transmat [1]
% 'adj_obs' - if 0, do not change obsmat [1]
[max_iter, thresh, verbose, obs_prior_weight, adj_prior, adj_trans, adj_obs] = ...
process_options(varargin, 'max_iter', 10, 'thresh', 1e-4, 'verbose', 1, ...
'obs_prior_weight', 0, 'adj_prior', 1, 'adj_trans', 1, 'adj_obs', 1);
previous_loglik = -inf;
loglik = 0;
converged = 0;
num_iter = 1;
LL = [];
if ~iscell(data)
data = num2cell(data, 2); % each row gets its own cell
end
while (num_iter <= max_iter) & ~converged
% E step
[loglik, exp_num_trans, exp_num_visits1, exp_num_emit] = ...
compute_ess_dhmm(prior, transmat, obsmat, data, obs_prior_weight);
% M step
if adj_prior
prior = normalise(exp_num_visits1);
end
if adj_trans & ~isempty(exp_num_trans)
transmat = mk_stochastic(exp_num_trans);
end
if adj_obs
obsmat = mk_stochastic(exp_num_emit);
end
if verbose, fprintf(1, 'iteration %d, loglik = %f\n', num_iter, loglik); end
num_iter = num_iter + 1;
converged = em_converged(loglik, previous_loglik, thresh);
previous_loglik = loglik;
LL = [LL loglik];
end
%%%%%%%%%%%%%%%%%%%%%%%
function [loglik, exp_num_trans, exp_num_visits1, exp_num_emit, exp_num_visitsT] = ...
compute_ess_dhmm(startprob, transmat, obsmat, data, dirichlet)
% COMPUTE_ESS_DHMM Compute the Expected Sufficient Statistics for an HMM with discrete outputs
% function [loglik, exp_num_trans, exp_num_visits1, exp_num_emit, exp_num_visitsT] = ...
% compute_ess_dhmm(startprob, transmat, obsmat, data, dirichlet)
%
% INPUTS:
% startprob(i)
% transmat(i,j)
% obsmat(i,o)
% data{seq}(t)
% dirichlet - weighting term for uniform dirichlet prior on expected emissions
%
% OUTPUTS:
% exp_num_trans(i,j) = sum_l sum_{t=2}^T Pr(X(t-1) = i, X(t) = j| Obs(l))
% exp_num_visits1(i) = sum_l Pr(X(1)=i | Obs(l))
% exp_num_visitsT(i) = sum_l Pr(X(T)=i | Obs(l))
% exp_num_emit(i,o) = sum_l sum_{t=1}^T Pr(X(t) = i, O(t)=o| Obs(l))
% where Obs(l) = O_1 .. O_T for sequence l.
numex = length(data);
[S O] = size(obsmat);
exp_num_trans = zeros(S,S);
exp_num_visits1 = zeros(S,1);
exp_num_visitsT = zeros(S,1);
exp_num_emit = dirichlet*ones(S,O);
loglik = 0;
for ex=1:numex
obs = data{ex};
T = length(obs);
%obslik = eval_pdf_cond_multinomial(obs, obsmat);
obslik = multinomial_prob(obs, obsmat);
[alpha, beta, gamma, current_ll, xi] = fwdback(startprob, transmat, obslik);
loglik = loglik + current_ll;
exp_num_trans = exp_num_trans + sum(xi,3);
exp_num_visits1 = exp_num_visits1 + gamma(:,1);
exp_num_visitsT = exp_num_visitsT + gamma(:,T);
% loop over whichever is shorter
if T < O
for t=1:T
o = obs(t);
exp_num_emit(:,o) = exp_num_emit(:,o) + gamma(:,t);
end
else
for o=1:O
ndx = find(obs==o);
if ~isempty(ndx)
exp_num_emit(:,o) = exp_num_emit(:,o) + sum(gamma(:, ndx), 2);
end
end
end
end
|
github
|
lcnhappe/happe-master
|
mhmm_em.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/hmm/mhmm_em.m
| 5,562 |
utf_8
|
5a337291416185ebcf567e46e08a3d09
|
function [LL, prior, transmat, mu, Sigma, mixmat] = ...
mhmm_em(data, prior, transmat, mu, Sigma, mixmat, varargin);
% LEARN_MHMM Compute the ML parameters of an HMM with (mixtures of) Gaussians output using EM.
% [ll_trace, prior, transmat, mu, sigma, mixmat] = learn_mhmm(data, ...
% prior0, transmat0, mu0, sigma0, mixmat0, ...)
%
% Notation: Q(t) = hidden state, Y(t) = observation, M(t) = mixture variable
%
% INPUTS:
% data{ex}(:,t) or data(:,t,ex) if all sequences have the same length
% prior(i) = Pr(Q(1) = i),
% transmat(i,j) = Pr(Q(t+1)=j | Q(t)=i)
% mu(:,j,k) = E[Y(t) | Q(t)=j, M(t)=k ]
% Sigma(:,:,j,k) = Cov[Y(t) | Q(t)=j, M(t)=k]
% mixmat(j,k) = Pr(M(t)=k | Q(t)=j) : set to [] or ones(Q,1) if only one mixture component
%
% Optional parameters may be passed as 'param_name', param_value pairs.
% Parameter names are shown below; default values in [] - if none, argument is mandatory.
%
% 'max_iter' - max number of EM iterations [10]
% 'thresh' - convergence threshold [1e-4]
% 'verbose' - if 1, print out loglik at every iteration [1]
% 'cov_type' - 'full', 'diag' or 'spherical' ['full']
%
% To clamp some of the parameters, so learning does not change them:
% 'adj_prior' - if 0, do not change prior [1]
% 'adj_trans' - if 0, do not change transmat [1]
% 'adj_mix' - if 0, do not change mixmat [1]
% 'adj_mu' - if 0, do not change mu [1]
% 'adj_Sigma' - if 0, do not change Sigma [1]
%
% If the number of mixture components differs depending on Q, just set the trailing
% entries of mixmat to 0, e.g., 2 components if Q=1, 3 components if Q=2,
% then set mixmat(1,3)=0. In this case, B2(1,3,:)=1.0.
if ~isstr(varargin{1}) % catch old syntax
error('optional arguments should be passed as string/value pairs')
end
[max_iter, thresh, verbose, cov_type, adj_prior, adj_trans, adj_mix, adj_mu, adj_Sigma] = ...
process_options(varargin, 'max_iter', 10, 'thresh', 1e-4, 'verbose', 1, ...
'cov_type', 'full', 'adj_prior', 1, 'adj_trans', 1, 'adj_mix', 1, ...
'adj_mu', 1, 'adj_Sigma', 1);
previous_loglik = -inf;
loglik = 0;
converged = 0;
num_iter = 1;
LL = [];
if ~iscell(data)
data = num2cell(data, [1 2]); % each elt of the 3rd dim gets its own cell
end
numex = length(data);
O = size(data{1},1);
Q = length(prior);
if isempty(mixmat)
mixmat = ones(Q,1);
end
M = size(mixmat,2);
if M == 1
adj_mix = 0;
end
while (num_iter <= max_iter) & ~converged
% E step
[loglik, exp_num_trans, exp_num_visits1, postmix, m, ip, op] = ...
ess_mhmm(prior, transmat, mixmat, mu, Sigma, data);
% M step
if adj_prior
prior = normalise(exp_num_visits1);
end
if adj_trans
transmat = mk_stochastic(exp_num_trans);
end
if adj_mix
mixmat = mk_stochastic(postmix);
end
if adj_mu | adj_Sigma
[mu2, Sigma2] = mixgauss_Mstep(postmix, m, op, ip, 'cov_type', cov_type);
if adj_mu
mu = reshape(mu2, [O Q M]);
end
if adj_Sigma
Sigma = reshape(Sigma2, [O O Q M]);
end
end
if verbose, fprintf(1, 'iteration %d, loglik = %f\n', num_iter, loglik); end
num_iter = num_iter + 1;
converged = em_converged(loglik, previous_loglik, thresh);
previous_loglik = loglik;
LL = [LL loglik];
end
%%%%%%%%%
function [loglik, exp_num_trans, exp_num_visits1, postmix, m, ip, op] = ...
ess_mhmm(prior, transmat, mixmat, mu, Sigma, data)
% ESS_MHMM Compute the Expected Sufficient Statistics for a MOG Hidden Markov Model.
%
% Outputs:
% exp_num_trans(i,j) = sum_l sum_{t=2}^T Pr(Q(t-1) = i, Q(t) = j| Obs(l))
% exp_num_visits1(i) = sum_l Pr(Q(1)=i | Obs(l))
%
% Let w(i,k,t,l) = P(Q(t)=i, M(t)=k | Obs(l))
% where Obs(l) = Obs(:,:,l) = O_1 .. O_T for sequence l
% Then
% postmix(i,k) = sum_l sum_t w(i,k,t,l) (posterior mixing weights/ responsibilities)
% m(:,i,k) = sum_l sum_t w(i,k,t,l) * Obs(:,t,l)
% ip(i,k) = sum_l sum_t w(i,k,t,l) * Obs(:,t,l)' * Obs(:,t,l)
% op(:,:,i,k) = sum_l sum_t w(i,k,t,l) * Obs(:,t,l) * Obs(:,t,l)'
verbose = 0;
%[O T numex] = size(data);
numex = length(data);
O = size(data{1},1);
Q = length(prior);
M = size(mixmat,2);
exp_num_trans = zeros(Q,Q);
exp_num_visits1 = zeros(Q,1);
postmix = zeros(Q,M);
m = zeros(O,Q,M);
op = zeros(O,O,Q,M);
ip = zeros(Q,M);
mix = (M>1);
loglik = 0;
if verbose, fprintf(1, 'forwards-backwards example # '); end
for ex=1:numex
if verbose, fprintf(1, '%d ', ex); end
%obs = data(:,:,ex);
obs = data{ex};
T = size(obs,2);
if mix
[B, B2] = mixgauss_prob(obs, mu, Sigma, mixmat);
[alpha, beta, gamma, current_loglik, xi, gamma2] = ...
fwdback(prior, transmat, B, 'obslik2', B2, 'mixmat', mixmat);
else
B = mixgauss_prob(obs, mu, Sigma);
[alpha, beta, gamma, current_loglik, xi] = fwdback(prior, transmat, B);
end
loglik = loglik + current_loglik;
if verbose, fprintf(1, 'll at ex %d = %f\n', ex, loglik); end
exp_num_trans = exp_num_trans + sum(xi,3);
exp_num_visits1 = exp_num_visits1 + gamma(:,1);
if mix
postmix = postmix + sum(gamma2,3);
else
postmix = postmix + sum(gamma,2);
gamma2 = reshape(gamma, [Q 1 T]); % gamma2(i,m,t) = gamma(i,t)
end
for i=1:Q
for k=1:M
w = reshape(gamma2(i,k,:), [1 T]); % w(t) = w(i,k,t,l)
wobs = obs .* repmat(w, [O 1]); % wobs(:,t) = w(t) * obs(:,t)
m(:,i,k) = m(:,i,k) + sum(wobs, 2); % m(:) = sum_t w(t) obs(:,t)
op(:,:,i,k) = op(:,:,i,k) + wobs * obs'; % op(:,:) = sum_t w(t) * obs(:,t) * obs(:,t)'
ip(i,k) = ip(i,k) + sum(sum(wobs .* obs, 2)); % ip = sum_t w(t) * obs(:,t)' * obs(:,t)
end
end
end
if verbose, fprintf(1, '\n'); end
|
github
|
lcnhappe/happe-master
|
subv2ind.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMtools/subv2ind.m
| 1,574 |
utf_8
|
e85d0bab88fc0d35b803436fa1dc0e15
|
function ndx = subv2ind(siz, subv)
% SUBV2IND Like the built-in sub2ind, but the subscripts are given as row vectors.
% ind = subv2ind(siz,subv)
%
% siz can be a row or column vector of size d.
% subv should be a collection of N row vectors of size d.
% ind will be of size N * 1.
%
% Example:
% subv = [1 1 1;
% 2 1 1;
% ...
% 2 2 2];
% subv2ind([2 2 2], subv) returns [1 2 ... 8]'
% i.e., the leftmost digit toggles fastest.
%
% See also IND2SUBV.
if isempty(subv)
ndx = [];
return;
end
if isempty(siz)
ndx = 1;
return;
end
[ncases ndims] = size(subv);
%if length(siz) ~= ndims
% error('length of subscript vector and sizes must be equal');
%end
if all(siz==2)
%rbits = subv(:,end:-1:1)-1; % read from right to left, convert to 0s/1s
%ndx = bitv2dec(rbits)+1;
twos = pow2(0:ndims-1);
ndx = ((subv-1) * twos(:)) + 1;
%ndx = sum((subv-1) .* twos(ones(ncases,1), :), 2) + 1; % equivalent to matrix * vector
%ndx = sum((subv-1) .* repmat(twos, ncases, 1), 2) + 1; % much slower than ones
%ndx = ndx(:)';
else
%siz = siz(:)';
cp = [1 cumprod(siz(1:end-1))]';
%ndx = ones(ncases, 1);
%for i = 1:ndims
% ndx = ndx + (subv(:,i)-1)*cp(i);
%end
ndx = (subv-1)*cp + 1;
end
%%%%%%%%%%%
function d = bitv2dec(bits)
% BITV2DEC Convert a bit vector to a decimal integer
% d = butv2dec(bits)
%
% This is just like the built-in bin2dec, except the argument is a vector, not a string.
% If bits is an array, each row will be converted.
[m n] = size(bits);
twos = pow2(n-1:-1:0);
d = sum(bits .* twos(ones(m,1),:),2);
|
github
|
lcnhappe/happe-master
|
zipload.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMtools/zipload.m
| 1,611 |
utf_8
|
67412c21b14bebb640784443e9e3bbd8
|
%ZIPLOAD Load compressed data file created with ZIPSAVE
%
% [data] = zipload( filename )
% filename: string variable that contains the name of the
% compressed file (do not include '.zip' extension)
% Use only with files created with 'zipsave'
% pkzip25.exe has to be in the matlab path. This file is a compression utility
% made by Pkware, Inc. It can be dowloaded from: http://www.pkware.com
% Or directly from ftp://ftp.pkware.com/pk250c32.exe, for the Windows 95/NT version.
% This function was tested using 'PKZIP 2.50 Command Line for Windows 9x/NT'
% It is important to use version 2.5 of the utility. Otherwise the command line below
% has to be changed to include the proper options of the compression utility you
% wish to use.
% This function was tested in MATLAB Version 5.3 under Windows NT.
% Fernando A. Brucher - May/25/1999
%
% Example:
% [loadedData] = zipload('testfile');
%--------------------------------------------------------------------
function [data] = zipload( filename )
%--- Decompress data file by calling pkzip (comand line command) ---
% Options used:
% 'extract' = decompress file
% 'silent' = no console output
% 'over=all' = overwrite files
%eval( ['!pkzip25 -extract -silent -over=all ', filename, '.zip'] )
eval( ['!pkzip25 -extract -silent -over=all ', filename, '.zip'] )
%--- Load data from decompressed file ---
% try, catch takes care of cases when pkzip fails to decompress a
% valid matlab format file
try
tmpStruc = load( filename );
data = tmpStruc.data;
catch, return, end
%--- Delete decompressed file ---
delete( [filename,'.mat'] )
|
github
|
lcnhappe/happe-master
|
plot_ellipse.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMtools/plot_ellipse.m
| 507 |
utf_8
|
3a27bbd5c1bdfe99983171e96789da6d
|
% PLOT_ELLIPSE
% h=plot_ellipse(x,y,theta,a,b)
%
% This routine plots an ellipse with centre (x,y), axis lengths a,b
% with major axis at an angle of theta radians from the horizontal.
%
% Author: P. Fieguth
% Jan. 98
%
%http://ocho.uwaterloo.ca/~pfieguth/Teaching/372/plot_ellipse.m
function h=plot_ellipse(x,y,theta,a,b)
np = 100;
ang = [0:np]*2*pi/np;
R = [cos(theta) -sin(theta); sin(theta) cos(theta)];
pts = [x;y]*ones(size(ang)) + R*[cos(ang)*a; sin(ang)*b];
h=plot( pts(1,:), pts(2,:) );
|
github
|
lcnhappe/happe-master
|
conf2mahal.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMtools/conf2mahal.m
| 2,424 |
utf_8
|
682226ca8c1183325f4204e0c22de0a7
|
% CONF2MAHAL - Translates a confidence interval to a Mahalanobis
% distance. Consider a multivariate Gaussian
% distribution of the form
%
% p(x) = 1/sqrt((2 * pi)^d * det(C)) * exp((-1/2) * MD(x, m, inv(C)))
%
% where MD(x, m, P) is the Mahalanobis distance from x
% to m under P:
%
% MD(x, m, P) = (x - m) * P * (x - m)'
%
% A particular Mahalanobis distance k identifies an
% ellipsoid centered at the mean of the distribution.
% The confidence interval associated with this ellipsoid
% is the probability mass enclosed by it. Similarly,
% a particular confidence interval uniquely determines
% an ellipsoid with a fixed Mahalanobis distance.
%
% If X is an d dimensional Gaussian-distributed vector,
% then the Mahalanobis distance of X is distributed
% according to the Chi-squared distribution with d
% degrees of freedom. Thus, the Mahalanobis distance is
% determined by evaluating the inverse cumulative
% distribution function of the chi squared distribution
% up to the confidence value.
%
% Usage:
%
% m = conf2mahal(c, d);
%
% Inputs:
%
% c - the confidence interval
% d - the number of dimensions of the Gaussian distribution
%
% Outputs:
%
% m - the Mahalanobis radius of the ellipsoid enclosing the
% fraction c of the distribution's probability mass
%
% See also: MAHAL2CONF
% Copyright (C) 2002 Mark A. Paskin
%
% 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 = conf2mahal(c, d)
m = chi2inv(c, d);
|
github
|
lcnhappe/happe-master
|
plotgauss2d.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMtools/plotgauss2d.m
| 970 |
utf_8
|
768501b0264c4510e2724b15b5be4e97
|
function h=plotgauss2d(mu, Sigma, plot_cross)
% PLOTGAUSS2D Plot a 2D Gaussian as an ellipse with optional cross hairs
% h=plotgauss2(mu, Sigma)
%
% h=plotgauss2(mu, Sigma, 1) also plots the major and minor axes
%
% Example
% clf; S=[2 1; 1 2]; plotgauss2d([0;0], S, 1); axis equal
h = plotcov2(mu, Sigma);
return;
%%%%%%%%%%%%%%%%%%%%%%%%
function old
if nargin < 3, plot_cross = 0; end
[V,D]=eig(Sigma);
lam1 = D(1,1);
lam2 = D(2,2);
v1 = V(:,1);
v2 = V(:,2);
%assert(approxeq(v1' * v2, 0))
if v1(1)==0
theta = 0; % horizontal
else
theta = atan(v1(2)/v1(1));
end
a = sqrt(lam1);
b = sqrt(lam2);
h=plot_ellipse(mu(1), mu(2), theta, a,b);
if plot_cross
mu = mu(:);
held = ishold;
hold on
minor1 = mu-a*v1; minor2 = mu+a*v1;
hminor = line([minor1(1) minor2(1)], [minor1(2) minor2(2)]);
major1 = mu-b*v2; major2 = mu+b*v2;
hmajor = line([major1(1) major2(1)], [major1(2) major2(2)]);
%set(hmajor,'color','r')
if ~held
hold off
end
end
|
github
|
lcnhappe/happe-master
|
zipsave.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMtools/zipsave.m
| 1,480 |
utf_8
|
cc543374345b9e369d147c452008bc36
|
%ZIPSAVE Save data in compressed format
%
% zipsave( filename, data )
% filename: string variable that contains the name of the resulting
% compressed file (do not include '.zip' extension)
% pkzip25.exe has to be in the matlab path. This file is a compression utility
% made by Pkware, Inc. It can be dowloaded from: http://www.pkware.com
% This function was tested using 'PKZIP 2.50 Command Line for Windows 9x/NT'
% It is important to use version 2.5 of the utility. Otherwise the command line below
% has to be changed to include the proper options of the compression utility you
% wish to use.
% This function was tested in MATLAB Version 5.3 under Windows NT.
% Fernando A. Brucher - May/25/1999
%
% Example:
% testData = [1 2 3; 4 5 6; 7 8 9];
% zipsave('testfile', testData);
%
% Modified by Kevin Murphy, 26 Feb 2004, to use winzip
%------------------------------------------------------------------------
function zipsave( filename, data )
%--- Save data in a temporary file in matlab format (.mat)---
eval( ['save ''', filename, ''' data'] )
%--- Compress data by calling pkzip (comand line command) ---
% Options used:
% 'add' = add compressed files to the resulting zip file
% 'silent' = no console output
% 'over=all' = overwrite files
%eval( ['!pkzip25 -silent -add -over=all ', filename, '.zip ', filename,'.mat'] )
eval( ['!zip ', filename, '.zip ', filename,'.mat'] )
%--- Delete temporary matlab format file ---
delete( [filename,'.mat'] )
|
github
|
lcnhappe/happe-master
|
matprint.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMtools/matprint.m
| 1,020 |
utf_8
|
e92a96dad0e0b9f25d2fe56280ba6393
|
% MATPRINT - prints a matrix with specified format string
%
% Usage: matprint(a, fmt, fid)
%
% a - Matrix to be printed.
% fmt - C style format string to use for each value.
% fid - Optional file id.
%
% Eg. matprint(a,'%3.1f') will print each entry to 1 decimal place
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk @ csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% March 2002
function matprint(a, fmt, fid)
if nargin < 3
fid = 1;
end
[rows,cols] = size(a);
% Construct a format string for each row of the matrix consisting of
% 'cols' copies of the number formating specification
fmtstr = [];
for c = 1:cols
fmtstr = [fmtstr, ' ', fmt];
end
fmtstr = [fmtstr '\n']; % Add a line feed
fprintf(fid, fmtstr, a'); % Print the transpose of the matrix because
% fprintf runs down the columns of a matrix.
|
github
|
lcnhappe/happe-master
|
plotcov3.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMtools/plotcov3.m
| 4,040 |
utf_8
|
1f186acd56002148a3da006a9fc8b6a2
|
% PLOTCOV3 - Plots a covariance ellipsoid with axes for a trivariate
% Gaussian distribution.
%
% Usage:
% [h, s] = plotcov3(mu, Sigma[, OPTIONS]);
%
% Inputs:
% mu - a 3 x 1 vector giving the mean of the distribution.
% Sigma - a 3 x 3 symmetric positive semi-definite matrix giving
% the covariance of the distribution (or the zero matrix).
%
% Options:
% 'conf' - a scalar between 0 and 1 giving the confidence
% interval (i.e., the fraction of probability mass to
% be enclosed by the ellipse); default is 0.9.
% 'num-pts' - if the value supplied is n, then (n + 1)^2 points
% to be used to plot the ellipse; default is 20.
% 'plot-opts' - a cell vector of arguments to be handed to PLOT3
% to contol the appearance of the axes, e.g.,
% {'Color', 'g', 'LineWidth', 1}; the default is {}
% 'surf-opts' - a cell vector of arguments to be handed to SURF
% to contol the appearance of the ellipsoid
% surface; a nice possibility that yields
% transparency is: {'EdgeAlpha', 0, 'FaceAlpha',
% 0.1, 'FaceColor', 'g'}; the default is {}
%
% Outputs:
% h - a vector of handles on the axis lines
% s - a handle on the ellipsoid surface object
%
% See also: PLOTCOV2
% Copyright (C) 2002 Mark A. Paskin
%
% 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 [h, s] = plotcov3(mu, Sigma, varargin)
if size(Sigma) ~= [3 3], error('Sigma must be a 3 by 3 matrix'); end
if length(mu) ~= 3, error('mu must be a 3 by 1 vector'); end
[p, ...
n, ...
plot_opts, ...
surf_opts] = process_options(varargin, 'conf', 0.9, ...
'num-pts', 20, ...
'plot-opts', {}, ...
'surf-opts', {});
h = [];
holding = ishold;
if (Sigma == zeros(3, 3))
z = mu;
else
% Compute the Mahalanobis radius of the ellipsoid that encloses
% the desired probability mass.
k = conf2mahal(p, 3);
% The axes of the covariance ellipse are given by the eigenvectors of
% the covariance matrix. Their lengths (for the ellipse with unit
% Mahalanobis radius) are given by the square roots of the
% corresponding eigenvalues.
if (issparse(Sigma))
[V, D] = eigs(Sigma);
else
[V, D] = eig(Sigma);
end
if (any(diag(D) < 0))
error('Invalid covariance matrix: not positive semi-definite.');
end
% Compute the points on the surface of the ellipsoid.
t = linspace(0, 2*pi, n);
[X, Y, Z] = sphere(n);
u = [X(:)'; Y(:)'; Z(:)'];
w = (k * V * sqrt(D)) * u;
z = repmat(mu(:), [1 (n + 1)^2]) + w;
% Plot the axes.
L = k * sqrt(diag(D));
h = plot3([mu(1); mu(1) + L(1) * V(1, 1)], ...
[mu(2); mu(2) + L(1) * V(2, 1)], ...
[mu(3); mu(3) + L(1) * V(3, 1)], plot_opts{:});
hold on;
h = [h; plot3([mu(1); mu(1) + L(2) * V(1, 2)], ...
[mu(2); mu(2) + L(2) * V(2, 2)], ...
[mu(3); mu(3) + L(2) * V(3, 2)], plot_opts{:})];
h = [h; plot3([mu(1); mu(1) + L(3) * V(1, 3)], ...
[mu(2); mu(2) + L(3) * V(2, 3)], ...
[mu(3); mu(3) + L(3) * V(3, 3)], plot_opts{:})];
end
s = surf(reshape(z(1, :), [(n + 1) (n + 1)]), ...
reshape(z(2, :), [(n + 1) (n + 1)]), ...
reshape(z(3, :), [(n + 1) (n + 1)]), ...
surf_opts{:});
if (~holding) hold off; end
|
github
|
lcnhappe/happe-master
|
exportfig.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMtools/exportfig.m
| 30,663 |
utf_8
|
838a8ee93ca6a9b6a85a90fa68976617
|
function varargout = exportfig(varargin)
%EXPORTFIG Export a figure.
% EXPORTFIG(H, FILENAME) writes the figure H to FILENAME. H is
% a figure handle and FILENAME is a string that specifies the
% name of the output file.
%
% EXPORTFIG(H, FILENAME, OPTIONS) writes the figure H to FILENAME
% with options initially specified by the structure OPTIONS. The
% field names of OPTIONS must be legal parameters listed below
% and the field values must be legal values for the corresponding
% parameter. Default options can be set in releases prior to R12
% by storing the OPTIONS structure in the root object's appdata
% with the command
% setappdata(0,'exportfigdefaults', OPTIONS)
% and for releases after R12 by setting the preference with the
% command
% setpref('exportfig', 'defaults', OPTIONS)
%
% EXPORTFIG(...,PARAM1,VAL1,PARAM2,VAL2,...) specifies
% parameters that control various characteristics of the output
% file. Any parameter value can be the string 'auto' which means
% the parameter uses the default factory behavior, overriding
% any other default for the parameter.
%
% Format Paramter:
% 'Format' a string
% specifies the output format. Defaults to 'eps'. For a
% list of export formats type 'help print'.
% 'Preview' one of the strings 'none', 'tiff'
% specifies a preview for EPS files. Defaults to 'none'.
%
% Size Parameters:
% 'Width' a positive scalar
% specifies the width in the figure's PaperUnits
% 'Height' a positive scalar
% specifies the height in the figure's PaperUnits
% 'Bounds' one of the strings 'tight', 'loose'
% specifies a tight or loose bounding box. Defaults to 'tight'.
% 'Reference' an axes handle or a string
% specifies that the width and height parameters
% are relative to the given axes. If a string is
% specified then it must evaluate to an axes handle.
%
% Specifying only one dimension sets the other dimension
% so that the exported aspect ratio is the same as the
% figure's or reference axes' current aspect ratio.
% If neither dimension is specified the size defaults to
% the width and height from the figure's or reference
% axes' size. Tight bounding boxes are only computed for
% 2-D views and in that case the computed bounds enclose all
% text objects.
%
% Rendering Parameters:
% 'Color' one of the strings 'bw', 'gray', 'cmyk'
% 'bw' specifies that lines and text are exported in
% black and all other objects in grayscale
% 'gray' specifies that all objects are exported in grayscale
% 'rgb' specifies that all objects are exported in color
% using the RGB color space
% 'cmyk' specifies that all objects are exported in color
% using the CMYK color space
% 'Renderer' one of 'painters', 'zbuffer', 'opengl'
% specifies the renderer to use
% 'Resolution' a positive scalar
% specifies the resolution in dots-per-inch.
% 'LockAxes' one of 0 or 1
% specifies that all axes limits and ticks should be fixed
% while exporting.
%
% The default color setting is 'bw'.
%
% Font Parameters:
% 'FontMode' one of the strings 'scaled', 'fixed'
% 'FontSize' a positive scalar
% in 'scaled' mode multiplies with the font size of each
% text object to obtain the exported font size
% in 'fixed' mode specifies the font size of all text
% objects in points
% 'DefaultFixedFontSize' a positive scalar
% in 'fixed' mode specified the default font size in
% points
% 'FontSizeMin' a positive scalar
% specifies the minimum font size allowed after scaling
% 'FontSizeMax' a positive scalar
% specifies the maximum font size allowed after scaling
% 'FontEncoding' one of the strings 'latin1', 'adobe'
% specifies the character encoding of the font
% 'SeparateText' one of 0 or 1
% specifies that the text objects are stored in separate
% file as EPS with the base filename having '_t' appended.
%
% If FontMode is 'scaled' but FontSize is not specified then a
% scaling factor is computed from the ratio of the size of the
% exported figure to the size of the actual figure.
%
% The default 'FontMode' setting is 'scaled'.
%
% Line Width Parameters:
% 'LineMode' one of the strings 'scaled', 'fixed'
% 'LineWidth' a positive scalar
% 'DefaultFixedLineWidth' a positive scalar
% 'LineWidthMin' a positive scalar
% specifies the minimum line width allowed after scaling
% 'LineWidthMax' a positive scalar
% specifies the maximum line width allowed after scaling
% The semantics of 'Line' parameters are exactly the
% same as the corresponding 'Font' parameters, except that
% they apply to line widths instead of font sizes.
%
% Style Map Parameter:
% 'LineStyleMap' one of [], 'bw', or a function name or handle
% specifies how to map line colors to styles. An empty
% style map means styles are not changed. The style map
% 'bw' is a built-in mapping that maps lines with the same
% color to the same style and otherwise cycles through the
% available styles. A user-specified map is a function
% that takes as input a cell array of line objects and
% outputs a cell array of line style strings. The default
% map is [].
%
% Examples:
% exportfig(gcf,'fig1.eps','height',3);
% Exports the current figure to the file named 'fig1.eps' with
% a height of 3 inches (assuming the figure's PaperUnits is
% inches) and an aspect ratio the same as the figure's aspect
% ratio on screen.
%
% opts = struct('FontMode','fixed','FontSize',10,'height',3);
% exportfig(gcf, 'fig2.eps', opts, 'height', 5);
% Exports the current figure to 'fig2.eps' with all
% text in 10 point fonts and with height 5 inches.
%
% See also PREVIEWFIG, APPLYTOFIG, RESTOREFIG, PRINT.
% Copyright 2000 Ben Hinkle
% Email bug reports and comments to [email protected]
if (nargin < 2)
error('Too few input arguments');
end
% exportfig(H, filename, [options,] ...)
H = varargin{1};
if ~LocalIsHG(H,'figure')
error('First argument must be a handle to a figure.');
end
filename = varargin{2};
if ~ischar(filename)
error('Second argument must be a string.');
end
paramPairs = {varargin{3:end}};
if nargin > 2
if isstruct(paramPairs{1})
pcell = LocalToCell(paramPairs{1});
paramPairs = {pcell{:}, paramPairs{2:end}};
end
end
verstr = version;
majorver = str2num(verstr(1));
defaults = [];
if majorver > 5
if ispref('exportfig','defaults')
defaults = getpref('exportfig','defaults');
end
elseif exist('getappdata')
defaults = getappdata(0,'exportfigdefaults');
end
if ~isempty(defaults)
dcell = LocalToCell(defaults);
paramPairs = {dcell{:}, paramPairs{:}};
end
% Do some validity checking on param-value pairs
if (rem(length(paramPairs),2) ~= 0)
error(['Invalid input syntax. Optional parameters and values' ...
' must be in pairs.']);
end
auto.format = 'eps';
auto.preview = 'none';
auto.width = -1;
auto.height = -1;
auto.color = 'bw';
auto.defaultfontsize=10;
auto.fontsize = -1;
auto.fontmode='scaled';
auto.fontmin = 8;
auto.fontmax = 60;
auto.defaultlinewidth = 1.0;
auto.linewidth = -1;
auto.linemode=[];
auto.linemin = 0.5;
auto.linemax = 100;
auto.fontencoding = 'latin1';
auto.renderer = [];
auto.resolution = [];
auto.stylemap = [];
auto.applystyle = 0;
auto.refobj = -1;
auto.bounds = 'tight';
explicitbounds = 0;
auto.lockaxes = 1;
auto.separatetext = 0;
opts = auto;
% Process param-value pairs
args = {};
for k = 1:2:length(paramPairs)
param = lower(paramPairs{k});
if ~ischar(param)
error('Optional parameter names must be strings');
end
value = paramPairs{k+1};
switch (param)
case 'format'
opts.format = LocalCheckAuto(lower(value),auto.format);
if strcmp(opts.format,'preview')
error(['Format ''preview'' no longer supported. Use PREVIEWFIG' ...
' instead.']);
end
case 'preview'
opts.preview = LocalCheckAuto(lower(value),auto.preview);
if ~strcmp(opts.preview,{'none','tiff'})
error('Preview must be ''none'' or ''tiff''.');
end
case 'width'
opts.width = LocalToNum(value, auto.width);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.width)
error('Width must be a numeric scalar > 0');
end
end
case 'height'
opts.height = LocalToNum(value, auto.height);
if ~ischar(value) | ~strcmp(value,'auto')
if(~LocalIsPositiveScalar(opts.height))
error('Height must be a numeric scalar > 0');
end
end
case 'color'
opts.color = LocalCheckAuto(lower(value),auto.color);
if ~strcmp(opts.color,{'bw','gray','rgb','cmyk'})
error('Color must be ''bw'', ''gray'',''rgb'' or ''cmyk''.');
end
case 'fontmode'
opts.fontmode = LocalCheckAuto(lower(value),auto.fontmode);
if ~strcmp(opts.fontmode,{'scaled','fixed'})
error('FontMode must be ''scaled'' or ''fixed''.');
end
case 'fontsize'
opts.fontsize = LocalToNum(value,auto.fontsize);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.fontsize)
error('FontSize must be a numeric scalar > 0');
end
end
case 'defaultfixedfontsize'
opts.defaultfontsize = LocalToNum(value,auto.defaultfontsize);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.defaultfontsize)
error('DefaultFixedFontSize must be a numeric scalar > 0');
end
end
case 'fontsizemin'
opts.fontmin = LocalToNum(value,auto.fontmin);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.fontmin)
error('FontSizeMin must be a numeric scalar > 0');
end
end
case 'fontsizemax'
opts.fontmax = LocalToNum(value,auto.fontmax);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.fontmax)
error('FontSizeMax must be a numeric scalar > 0');
end
end
case 'fontencoding'
opts.fontencoding = LocalCheckAuto(lower(value),auto.fontencoding);
if ~strcmp(opts.fontencoding,{'latin1','adobe'})
error('FontEncoding must be ''latin1'' or ''adobe''.');
end
case 'linemode'
opts.linemode = LocalCheckAuto(lower(value),auto.linemode);
if ~strcmp(opts.linemode,{'scaled','fixed'})
error('LineMode must be ''scaled'' or ''fixed''.');
end
case 'linewidth'
opts.linewidth = LocalToNum(value,auto.linewidth);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.linewidth)
error('LineWidth must be a numeric scalar > 0');
end
end
case 'defaultfixedlinewidth'
opts.defaultlinewidth = LocalToNum(value,auto.defaultlinewidth);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.defaultlinewidth)
error(['DefaultFixedLineWidth must be a numeric scalar >' ...
' 0']);
end
end
case 'linewidthmin'
opts.linemin = LocalToNum(value,auto.linemin);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.linemin)
error('LineWidthMin must be a numeric scalar > 0');
end
end
case 'linewidthmax'
opts.linemax = LocalToNum(value,auto.linemax);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.linemax)
error('LineWidthMax must be a numeric scalar > 0');
end
end
case 'linestylemap'
opts.stylemap = LocalCheckAuto(value,auto.stylemap);
case 'renderer'
opts.renderer = LocalCheckAuto(lower(value),auto.renderer);
if ~ischar(value) | ~strcmp(value,'auto')
if ~strcmp(opts.renderer,{'painters','zbuffer','opengl'})
error(['Renderer must be ''painters'', ''zbuffer'' or' ...
' ''opengl''.']);
end
end
case 'resolution'
opts.resolution = LocalToNum(value,auto.resolution);
if ~ischar(value) | ~strcmp(value,'auto')
if ~(isnumeric(value) & (prod(size(value)) == 1) & (value >= 0));
error('Resolution must be a numeric scalar >= 0');
end
end
case 'applystyle' % means to apply the options and not export
opts.applystyle = 1;
case 'reference'
if ischar(value)
if strcmp(value,'auto')
opts.refobj = auto.refobj;
else
opts.refobj = eval(value);
end
else
opts.refobj = value;
end
if ~LocalIsHG(opts.refobj,'axes')
error('Reference object must evaluate to an axes handle.');
end
case 'bounds'
opts.bounds = LocalCheckAuto(lower(value),auto.bounds);
explicitbounds = 1;
if ~strcmp(opts.bounds,{'tight','loose'})
error('Bounds must be ''tight'' or ''loose''.');
end
case 'lockaxes'
opts.lockaxes = LocalToNum(value,auto.lockaxes);
case 'separatetext'
opts.separatetext = LocalToNum(value,auto.separatetext);
otherwise
error(['Unrecognized option ' param '.']);
end
end
% make sure figure is up-to-date
drawnow;
allLines = findall(H, 'type', 'line');
allText = findall(H, 'type', 'text');
allAxes = findall(H, 'type', 'axes');
allImages = findall(H, 'type', 'image');
allLights = findall(H, 'type', 'light');
allPatch = findall(H, 'type', 'patch');
allSurf = findall(H, 'type', 'surface');
allRect = findall(H, 'type', 'rectangle');
allFont = [allText; allAxes];
allColor = [allLines; allText; allAxes; allLights];
allMarker = [allLines; allPatch; allSurf];
allEdge = [allPatch; allSurf];
allCData = [allImages; allPatch; allSurf];
old.objs = {};
old.prop = {};
old.values = {};
% Process format
if strncmp(opts.format,'eps',3) & ~strcmp(opts.preview,'none')
args = {args{:}, ['-' opts.preview]};
end
hadError = 0;
oldwarn = warning;
try
% lock axes limits, ticks and labels if requested
if opts.lockaxes
old = LocalManualAxesMode(old, allAxes, 'TickMode');
old = LocalManualAxesMode(old, allAxes, 'TickLabelMode');
old = LocalManualAxesMode(old, allAxes, 'LimMode');
end
% Process size parameters
figurePaperUnits = get(H, 'PaperUnits');
oldFigureUnits = get(H, 'Units');
oldFigPos = get(H,'Position');
set(H, 'Units', figurePaperUnits);
figPos = get(H,'Position');
refsize = figPos(3:4);
if opts.refobj ~= -1
oldUnits = get(opts.refobj, 'Units');
set(opts.refobj, 'Units', figurePaperUnits);
r = get(opts.refobj, 'Position');
refsize = r(3:4);
set(opts.refobj, 'Units', oldUnits);
end
aspectRatio = refsize(1)/refsize(2);
if (opts.width == -1) & (opts.height == -1)
opts.width = refsize(1);
opts.height = refsize(2);
elseif (opts.width == -1)
opts.width = opts.height * aspectRatio;
elseif (opts.height == -1)
opts.height = opts.width / aspectRatio;
end
wscale = opts.width/refsize(1);
hscale = opts.height/refsize(2);
sizescale = min(wscale,hscale);
old = LocalPushOldData(old,H,'PaperPositionMode', ...
get(H,'PaperPositionMode'));
set(H, 'PaperPositionMode', 'auto');
newPos = [figPos(1) figPos(2)+figPos(4)*(1-hscale) ...
wscale*figPos(3) hscale*figPos(4)];
set(H, 'Position', newPos);
set(H, 'Units', oldFigureUnits);
% process line-style map
if ~isempty(opts.stylemap) & ~isempty(allLines)
oldlstyle = LocalGetAsCell(allLines,'LineStyle');
old = LocalPushOldData(old, allLines, {'LineStyle'}, ...
oldlstyle);
newlstyle = oldlstyle;
if ischar(opts.stylemap) & strcmpi(opts.stylemap,'bw')
newlstyle = LocalMapColorToStyle(allLines);
else
try
newlstyle = feval(opts.stylemap,allLines);
catch
warning(['Skipping stylemap. ' lasterr]);
end
end
set(allLines,{'LineStyle'},newlstyle);
end
% Process rendering parameters
switch (opts.color)
case {'bw', 'gray'}
if ~strcmp(opts.color,'bw') & strncmp(opts.format,'eps',3)
opts.format = [opts.format 'c'];
end
args = {args{:}, ['-d' opts.format]};
%compute and set gray colormap
oldcmap = get(H,'Colormap');
newgrays = 0.30*oldcmap(:,1) + 0.59*oldcmap(:,2) + 0.11*oldcmap(:,3);
newcmap = [newgrays newgrays newgrays];
old = LocalPushOldData(old, H, 'Colormap', oldcmap);
set(H, 'Colormap', newcmap);
%compute and set ColorSpec and CData properties
old = LocalUpdateColors(allColor, 'color', old);
old = LocalUpdateColors(allAxes, 'xcolor', old);
old = LocalUpdateColors(allAxes, 'ycolor', old);
old = LocalUpdateColors(allAxes, 'zcolor', old);
old = LocalUpdateColors(allMarker, 'MarkerEdgeColor', old);
old = LocalUpdateColors(allMarker, 'MarkerFaceColor', old);
old = LocalUpdateColors(allEdge, 'EdgeColor', old);
old = LocalUpdateColors(allEdge, 'FaceColor', old);
old = LocalUpdateColors(allCData, 'CData', old);
case {'rgb','cmyk'}
if strncmp(opts.format,'eps',3)
opts.format = [opts.format 'c'];
args = {args{:}, ['-d' opts.format]};
if strcmp(opts.color,'cmyk')
args = {args{:}, '-cmyk'};
end
else
args = {args{:}, ['-d' opts.format]};
end
otherwise
error('Invalid Color parameter');
end
if (~isempty(opts.renderer))
args = {args{:}, ['-' opts.renderer]};
end
if (~isempty(opts.resolution)) | ~strncmp(opts.format,'eps',3)
if isempty(opts.resolution)
opts.resolution = 0;
end
args = {args{:}, ['-r' int2str(opts.resolution)]};
end
% Process font parameters
if ~isempty(opts.fontmode)
oldfonts = LocalGetAsCell(allFont,'FontSize');
oldfontunits = LocalGetAsCell(allFont,'FontUnits');
set(allFont,'FontUnits','points');
switch (opts.fontmode)
case 'fixed'
if (opts.fontsize == -1)
set(allFont,'FontSize',opts.defaultfontsize);
else
set(allFont,'FontSize',opts.fontsize);
end
case 'scaled'
if (opts.fontsize == -1)
scale = sizescale;
else
scale = opts.fontsize;
end
newfonts = LocalScale(oldfonts,scale,opts.fontmin,opts.fontmax);
set(allFont,{'FontSize'},newfonts);
otherwise
error('Invalid FontMode parameter');
end
old = LocalPushOldData(old, allFont, {'FontSize'}, oldfonts);
old = LocalPushOldData(old, allFont, {'FontUnits'}, oldfontunits);
end
if strcmp(opts.fontencoding,'adobe') & strncmp(opts.format,'eps',3)
args = {args{:}, '-adobecset'};
end
% Process line parameters
if ~isempty(opts.linemode)
oldlines = LocalGetAsCell(allMarker,'LineWidth');
old = LocalPushOldData(old, allMarker, {'LineWidth'}, oldlines);
switch (opts.linemode)
case 'fixed'
if (opts.linewidth == -1)
set(allMarker,'LineWidth',opts.defaultlinewidth);
else
set(allMarker,'LineWidth',opts.linewidth);
end
case 'scaled'
if (opts.linewidth == -1)
scale = sizescale;
else
scale = opts.linewidth;
end
newlines = LocalScale(oldlines, scale, opts.linemin, opts.linemax);
set(allMarker,{'LineWidth'},newlines);
end
end
% adjust figure bounds to surround axes
if strcmp(opts.bounds,'tight')
if (~strncmp(opts.format,'eps',3) & LocalHas3DPlot(allAxes)) | ...
(strncmp(opts.format,'eps',3) & opts.separatetext)
if (explicitbounds == 1)
warning(['Cannot compute ''tight'' bounds. Using ''loose''' ...
' bounds.']);
end
opts.bounds = 'loose';
end
end
warning('off');
if ~isempty(allAxes)
if strncmp(opts.format,'eps',3)
if strcmp(opts.bounds,'loose')
args = {args{:}, '-loose'};
end
old = LocalPushOldData(old,H,'Position', oldFigPos);
elseif strcmp(opts.bounds,'tight')
oldaunits = LocalGetAsCell(allAxes,'Units');
oldapos = LocalGetAsCell(allAxes,'Position');
oldtunits = LocalGetAsCell(allText,'units');
oldtpos = LocalGetAsCell(allText,'Position');
set(allAxes,'units','points');
apos = LocalGetAsCell(allAxes,'Position');
oldunits = get(H,'Units');
set(H,'units','points');
origfr = get(H,'position');
fr = [];
for k=1:length(allAxes)
if ~strcmpi(get(allAxes(k),'Tag'),'legend')
axesR = apos{k};
r = LocalAxesTightBoundingBox(axesR, allAxes(k));
r(1:2) = r(1:2) + axesR(1:2);
fr = LocalUnionRect(fr,r);
end
end
if isempty(fr)
fr = [0 0 origfr(3:4)];
end
for k=1:length(allAxes)
ax = allAxes(k);
r = apos{k};
r(1:2) = r(1:2) - fr(1:2);
set(ax,'Position',r);
end
old = LocalPushOldData(old, allAxes, {'Position'}, oldapos);
old = LocalPushOldData(old, allText, {'Position'}, oldtpos);
old = LocalPushOldData(old, allText, {'Units'}, oldtunits);
old = LocalPushOldData(old, allAxes, {'Units'}, oldaunits);
old = LocalPushOldData(old, H, 'Position', oldFigPos);
old = LocalPushOldData(old, H, 'Units', oldFigureUnits);
r = [origfr(1) origfr(2)+origfr(4)-fr(4) fr(3:4)];
set(H,'Position',r);
else
args = {args{:}, '-loose'};
old = LocalPushOldData(old,H,'Position', oldFigPos);
end
end
% Process text in a separate file if needed
if opts.separatetext & ~opts.applystyle
% First hide all text and export
oldtvis = LocalGetAsCell(allText,'visible');
set(allText,'visible','off');
oldax = LocalGetAsCell(allAxes,'XTickLabel',1);
olday = LocalGetAsCell(allAxes,'YTickLabel',1);
oldaz = LocalGetAsCell(allAxes,'ZTickLabel',1);
null = cell(length(oldax),1);
[null{:}] = deal([]);
set(allAxes,{'XTickLabel'},null);
set(allAxes,{'YTickLabel'},null);
set(allAxes,{'ZTickLabel'},null);
print(H, filename, args{:});
set(allText,{'Visible'},oldtvis);
set(allAxes,{'XTickLabel'},oldax);
set(allAxes,{'YTickLabel'},olday);
set(allAxes,{'ZTickLabel'},oldaz);
% Now hide all non-text and export as eps in painters
[path, name, ext] = fileparts(filename);
tfile = fullfile(path,[name '_t.eps']);
tfile2 = fullfile(path,[name '_t2.eps']);
foundRenderer = 0;
for k=1:length(args)
if strncmp('-d',args{k},2)
args{k} = '-deps';
elseif strncmp('-zbuffer',args{k},8) | ...
strncmp('-opengl', args{k},6)
args{k} = '-painters';
foundRenderer = 1;
end
end
if ~foundRenderer
args = {args{:}, '-painters'};
end
allNonText = [allLines; allLights; allPatch; ...
allImages; allSurf; allRect];
oldvis = LocalGetAsCell(allNonText,'visible');
oldc = LocalGetAsCell(allAxes,'color');
oldaxg = LocalGetAsCell(allAxes,'XGrid');
oldayg = LocalGetAsCell(allAxes,'YGrid');
oldazg = LocalGetAsCell(allAxes,'ZGrid');
[null{:}] = deal('off');
set(allAxes,{'XGrid'},null);
set(allAxes,{'YGrid'},null);
set(allAxes,{'ZGrid'},null);
set(allNonText,'Visible','off');
set(allAxes,'Color','none');
print(H, tfile2, args{:});
set(allNonText,{'Visible'},oldvis);
set(allAxes,{'Color'},oldc);
set(allAxes,{'XGrid'},oldaxg);
set(allAxes,{'YGrid'},oldayg);
set(allAxes,{'ZGrid'},oldazg);
%hack up the postscript file
fid1 = fopen(tfile,'w');
fid2 = fopen(tfile2,'r');
line = fgetl(fid2);
while ischar(line)
if strncmp(line,'%%Title',7)
fprintf(fid1,'%s\n',['%%Title: ', tfile]);
elseif (length(line) < 3)
fprintf(fid1,'%s\n',line);
elseif ~strcmp(line(end-2:end),' PR') & ...
~strcmp(line(end-1:end),' L')
fprintf(fid1,'%s\n',line);
end
line = fgetl(fid2);
end
fclose(fid1);
fclose(fid2);
delete(tfile2);
elseif ~opts.applystyle
drawnow;
print(H, filename, args{:});
end
warning(oldwarn);
catch
warning(oldwarn);
hadError = 1;
end
% Restore figure settings
if opts.applystyle
varargout{1} = old;
else
for n=1:length(old.objs)
if ~iscell(old.values{n}) & iscell(old.prop{n})
old.values{n} = {old.values{n}};
end
set(old.objs{n}, old.prop{n}, old.values{n});
end
end
if hadError
error(deblank(lasterr));
end
%
% Local Functions
%
function outData = LocalPushOldData(inData, objs, prop, values)
outData.objs = {objs, inData.objs{:}};
outData.prop = {prop, inData.prop{:}};
outData.values = {values, inData.values{:}};
function cellArray = LocalGetAsCell(fig,prop,allowemptycell);
cellArray = get(fig,prop);
if nargin < 3
allowemptycell = 0;
end
if ~iscell(cellArray) & (allowemptycell | ~isempty(cellArray))
cellArray = {cellArray};
end
function newArray = LocalScale(inArray, scale, minv, maxv)
n = length(inArray);
newArray = cell(n,1);
for k=1:n
newArray{k} = min(maxv,max(minv,scale*inArray{k}(1)));
end
function gray = LocalMapToGray1(color)
gray = color;
if ischar(color)
switch color(1)
case 'y'
color = [1 1 0];
case 'm'
color = [1 0 1];
case 'c'
color = [0 1 1];
case 'r'
color = [1 0 0];
case 'g'
color = [0 1 0];
case 'b'
color = [0 0 1];
case 'w'
color = [1 1 1];
case 'k'
color = [0 0 0];
end
end
if ~ischar(color)
gray = 0.30*color(1) + 0.59*color(2) + 0.11*color(3);
end
function newArray = LocalMapToGray(inArray);
n = length(inArray);
newArray = cell(n,1);
for k=1:n
color = inArray{k};
if ~isempty(color)
color = LocalMapToGray1(color);
end
if isempty(color) | ischar(color)
newArray{k} = color;
else
newArray{k} = [color color color];
end
end
function newArray = LocalMapColorToStyle(inArray);
inArray = LocalGetAsCell(inArray,'Color');
n = length(inArray);
newArray = cell(n,1);
styles = {'-','--',':','-.'};
uniques = [];
nstyles = length(styles);
for k=1:n
gray = LocalMapToGray1(inArray{k});
if isempty(gray) | ischar(gray) | gray < .05
newArray{k} = '-';
else
if ~isempty(uniques) & any(gray == uniques)
ind = find(gray==uniques);
else
uniques = [uniques gray];
ind = length(uniques);
end
newArray{k} = styles{mod(ind-1,nstyles)+1};
end
end
function newArray = LocalMapCData(inArray);
n = length(inArray);
newArray = cell(n,1);
for k=1:n
color = inArray{k};
if (ndims(color) == 3) & isa(color,'double')
gray = 0.30*color(:,:,1) + 0.59*color(:,:,2) + 0.11*color(:,:,3);
color(:,:,1) = gray;
color(:,:,2) = gray;
color(:,:,3) = gray;
end
newArray{k} = color;
end
function outData = LocalUpdateColors(inArray, prop, inData)
value = LocalGetAsCell(inArray,prop);
outData.objs = {inData.objs{:}, inArray};
outData.prop = {inData.prop{:}, {prop}};
outData.values = {inData.values{:}, value};
if (~isempty(value))
if strcmp(prop,'CData')
value = LocalMapCData(value);
else
value = LocalMapToGray(value);
end
set(inArray,{prop},value);
end
function bool = LocalIsPositiveScalar(value)
bool = isnumeric(value) & ...
prod(size(value)) == 1 & ...
value > 0;
function value = LocalToNum(value,auto)
if ischar(value)
if strcmp(value,'auto')
value = auto;
else
value = str2num(value);
end
end
%convert a struct to {field1,val1,field2,val2,...}
function c = LocalToCell(s)
f = fieldnames(s);
v = struct2cell(s);
opts = cell(2,length(f));
opts(1,:) = f;
opts(2,:) = v;
c = {opts{:}};
function c = LocalIsHG(obj,hgtype)
c = 0;
if (length(obj) == 1) & ishandle(obj)
c = strcmp(get(obj,'type'),hgtype);
end
function c = LocalHas3DPlot(a)
zticks = LocalGetAsCell(a,'ZTickLabel');
c = 0;
for k=1:length(zticks)
if ~isempty(zticks{k})
c = 1;
return;
end
end
function r = LocalUnionRect(r1,r2)
if isempty(r1)
r = r2;
elseif isempty(r2)
r = r1;
elseif max(r2(3:4)) > 0
left = min(r1(1),r2(1));
bot = min(r1(2),r2(2));
right = max(r1(1)+r1(3),r2(1)+r2(3));
top = max(r1(2)+r1(4),r2(2)+r2(4));
r = [left bot right-left top-bot];
else
r = r1;
end
function c = LocalLabelsMatchTicks(labs,ticks)
c = 0;
try
t1 = num2str(ticks(1));
n = length(ticks);
tend = num2str(ticks(n));
c = strncmp(labs(1),t1,length(labs(1))) & ...
strncmp(labs(n),tend,length(labs(n)));
end
function r = LocalAxesTightBoundingBox(axesR, a)
r = [];
atext = findall(a,'type','text','visible','on');
if ~isempty(atext)
set(atext,'units','points');
res=LocalGetAsCell(atext,'extent');
for n=1:length(atext)
r = LocalUnionRect(r,res{n});
end
end
if strcmp(get(a,'visible'),'on')
r = LocalUnionRect(r,[0 0 axesR(3:4)]);
oldunits = get(a,'fontunits');
set(a,'fontunits','points');
label = text(0,0,'','parent',a,...
'units','points',...
'fontsize',get(a,'fontsize'),...
'fontname',get(a,'fontname'),...
'fontweight',get(a,'fontweight'),...
'fontangle',get(a,'fontangle'),...
'visible','off');
fs = get(a,'fontsize');
% handle y axis tick labels
ry = [0 -fs/2 0 axesR(4)+fs];
ylabs = get(a,'yticklabels');
yticks = get(a,'ytick');
maxw = 0;
if ~isempty(ylabs)
for n=1:size(ylabs,1)
set(label,'string',ylabs(n,:));
ext = get(label,'extent');
maxw = max(maxw,ext(3));
end
if ~LocalLabelsMatchTicks(ylabs,yticks) & ...
strcmp(get(a,'xaxislocation'),'bottom')
ry(4) = ry(4) + 1.5*ext(4);
end
if strcmp(get(a,'yaxislocation'),'left')
ry(1) = -(maxw+5);
else
ry(1) = axesR(3);
end
ry(3) = maxw+5;
r = LocalUnionRect(r,ry);
end
% handle x axis tick labels
rx = [0 0 0 fs+5];
xlabs = get(a,'xticklabels');
xticks = get(a,'xtick');
if ~isempty(xlabs)
if strcmp(get(a,'xaxislocation'),'bottom')
rx(2) = -(fs+5);
if ~LocalLabelsMatchTicks(xlabs,xticks);
rx(4) = rx(4) + 2*fs;
rx(2) = rx(2) - 2*fs;
end
else
rx(2) = axesR(4);
% exponent is still below axes
if ~LocalLabelsMatchTicks(xlabs,xticks);
rx(4) = rx(4) + axesR(4) + 2*fs;
rx(2) = -2*fs;
end
end
set(label,'string',xlabs(1,:));
ext1 = get(label,'extent');
rx(1) = -ext1(3)/2;
set(label,'string',xlabs(size(xlabs,1),:));
ext2 = get(label,'extent');
rx(3) = axesR(3) + (ext2(3) + ext1(3))/2;
r = LocalUnionRect(r,rx);
end
set(a,'fontunits',oldunits);
delete(label);
end
function c = LocalManualAxesMode(old, allAxes, base)
xs = ['X' base];
ys = ['Y' base];
zs = ['Z' base];
oldXMode = LocalGetAsCell(allAxes,xs);
oldYMode = LocalGetAsCell(allAxes,ys);
oldZMode = LocalGetAsCell(allAxes,zs);
old = LocalPushOldData(old, allAxes, {xs}, oldXMode);
old = LocalPushOldData(old, allAxes, {ys}, oldYMode);
old = LocalPushOldData(old, allAxes, {zs}, oldZMode);
set(allAxes,xs,'manual');
set(allAxes,ys,'manual');
set(allAxes,zs,'manual');
c = old;
function val = LocalCheckAuto(val, auto)
if ischar(val) & strcmp(val,'auto')
val = auto;
end
|
github
|
lcnhappe/happe-master
|
plotcov2.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMtools/plotcov2.m
| 3,013 |
utf_8
|
4305f11ba0280ef8ebcad4c8a4c4013c
|
% PLOTCOV2 - Plots a covariance ellipse with major and minor axes
% for a bivariate Gaussian distribution.
%
% Usage:
% h = plotcov2(mu, Sigma[, OPTIONS]);
%
% Inputs:
% mu - a 2 x 1 vector giving the mean of the distribution.
% Sigma - a 2 x 2 symmetric positive semi-definite matrix giving
% the covariance of the distribution (or the zero matrix).
%
% Options:
% 'conf' - a scalar between 0 and 1 giving the confidence
% interval (i.e., the fraction of probability mass to
% be enclosed by the ellipse); default is 0.9.
% 'num-pts' - the number of points to be used to plot the
% ellipse; default is 100.
%
% This function also accepts options for PLOT.
%
% Outputs:
% h - a vector of figure handles to the ellipse boundary and
% its major and minor axes
%
% See also: PLOTCOV3
% Copyright (C) 2002 Mark A. Paskin
%
% 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 h = plotcov2(mu, Sigma, varargin)
if size(Sigma) ~= [2 2], error('Sigma must be a 2 by 2 matrix'); end
if length(mu) ~= 2, error('mu must be a 2 by 1 vector'); end
[p, ...
n, ...
plot_opts] = process_options(varargin, 'conf', 0.9, ...
'num-pts', 100);
h = [];
holding = ishold;
if (Sigma == zeros(2, 2))
z = mu;
else
% Compute the Mahalanobis radius of the ellipsoid that encloses
% the desired probability mass.
k = conf2mahal(p, 2);
% The major and minor axes of the covariance ellipse are given by
% the eigenvectors of the covariance matrix. Their lengths (for
% the ellipse with unit Mahalanobis radius) are given by the
% square roots of the corresponding eigenvalues.
if (issparse(Sigma))
[V, D] = eigs(Sigma);
else
[V, D] = eig(Sigma);
end
% Compute the points on the surface of the ellipse.
t = linspace(0, 2*pi, n);
u = [cos(t); sin(t)];
w = (k * V * sqrt(D)) * u;
z = repmat(mu, [1 n]) + w;
% Plot the major and minor axes.
L = k * sqrt(diag(D));
h = plot([mu(1); mu(1) + L(1) * V(1, 1)], ...
[mu(2); mu(2) + L(1) * V(2, 1)], plot_opts{:});
hold on;
h = [h; plot([mu(1); mu(1) + L(2) * V(1, 2)], ...
[mu(2); mu(2) + L(2) * V(2, 2)], plot_opts{:})];
end
h = [h; plot(z(1, :), z(2, :), plot_opts{:})];
if (~holding) hold off; end
|
github
|
lcnhappe/happe-master
|
ind2subv.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMtools/ind2subv.m
| 1,206 |
utf_8
|
5c2e8689803ece8fca091e60c913809d
|
function sub = ind2subv(siz, ndx)
% IND2SUBV Like the built-in ind2sub, but returns the answer as a row vector.
% sub = ind2subv(siz, ndx)
%
% siz and ndx can be row or column vectors.
% sub will be of size length(ndx) * length(siz).
%
% Example
% ind2subv([2 2 2], 1:8) returns
% [1 1 1
% 2 1 1
% ...
% 2 2 2]
% That is, the leftmost digit toggle fastest.
%
% See also SUBV2IND
n = length(siz);
if n==0
sub = ndx;
return;
end
if all(siz==2)
sub = dec2bitv(ndx-1, n);
sub = sub(:,n:-1:1)+1;
return;
end
cp = [1 cumprod(siz(:)')];
ndx = ndx(:) - 1;
sub = zeros(length(ndx), n);
for i = n:-1:1 % i'th digit
sub(:,i) = floor(ndx/cp(i))+1;
ndx = rem(ndx,cp(i));
end
%%%%%%%%%%
function bits = dec2bitv(d,n)
% DEC2BITV Convert a decimal integer to a bit vector.
% bits = dec2bitv(d,n) is just like the built-in dec2bin, except the answer is a vector, not a string.
% n is an optional minimum length on the bit vector.
% If d is a vector, each row of the output array will be a bit vector.
if (nargin<2)
n=1; % Need at least one digit even for 0.
end
d = d(:);
[f,e]=log2(max(d)); % How many digits do we need to represent the numbers?
bits=rem(floor(d*pow2(1-max(n,e):0)),2);
|
github
|
lcnhappe/happe-master
|
process_options.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMtools/process_options.m
| 4,385 |
utf_8
|
bb0450331cd2e6af72679b642ca38e24
|
% PROCESS_OPTIONS - Processes options passed to a Matlab function.
% This function provides a simple means of
% parsing attribute-value options. Each option is
% named by a unique string and is given a default
% value.
%
% Usage: [var1, var2, ..., varn[, unused]] = ...
% process_options(args, ...
% str1, def1, str2, def2, ..., strn, defn)
%
% Arguments:
% args - a cell array of input arguments, such
% as that provided by VARARGIN. Its contents
% should alternate between strings and
% values.
% str1, ..., strn - Strings that are associated with a
% particular variable
% def1, ..., defn - Default values returned if no option
% is supplied
%
% Returns:
% var1, ..., varn - values to be assigned to variables
% unused - an optional cell array of those
% string-value pairs that were unused;
% if this is not supplied, then a
% warning will be issued for each
% option in args that lacked a match.
%
% Examples:
%
% Suppose we wish to define a Matlab function 'func' that has
% required parameters x and y, and optional arguments 'u' and 'v'.
% With the definition
%
% function y = func(x, y, varargin)
%
% [u, v] = process_options(varargin, 'u', 0, 'v', 1);
%
% calling func(0, 1, 'v', 2) will assign 0 to x, 1 to y, 0 to u, and 2
% to v. The parameter names are insensitive to case; calling
% func(0, 1, 'V', 2) has the same effect. The function call
%
% func(0, 1, 'u', 5, 'z', 2);
%
% will result in u having the value 5 and v having value 1, but
% will issue a warning that the 'z' option has not been used. On
% the other hand, if func is defined as
%
% function y = func(x, y, varargin)
%
% [u, v, unused_args] = process_options(varargin, 'u', 0, 'v', 1);
%
% then the call func(0, 1, 'u', 5, 'z', 2) will yield no warning,
% and unused_args will have the value {'z', 2}. This behaviour is
% useful for functions with options that invoke other functions
% with options; all options can be passed to the outer function and
% its unprocessed arguments can be passed to the inner function.
% Copyright (C) 2002 Mark A. Paskin
%
% 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] = process_options(args, varargin)
% Check the number of input arguments
n = length(varargin);
if (mod(n, 2))
error('Each option must be a string/value pair.');
end
% Check the number of supplied output arguments
if (nargout < (n / 2))
error('Insufficient number of output arguments given');
elseif (nargout == (n / 2))
warn = 1;
nout = n / 2;
else
warn = 0;
nout = n / 2 + 1;
end
% Set outputs to be defaults
varargout = cell(1, nout);
for i=2:2:n
varargout{i/2} = varargin{i};
end
% Now process all arguments
nunused = 0;
for i=1:2:length(args)
found = 0;
for j=1:2:n
if strcmpi(args{i}, varargin{j})
varargout{(j + 1)/2} = args{i + 1};
found = 1;
break;
end
end
if (~found)
if (warn)
warning('Option ''%s'' not used.', args{i});
args{i}
else
nunused = nunused + 1;
unused{2 * nunused - 1} = args{i};
unused{2 * nunused} = args{i + 1};
end
end
end
% Assign the unused arguments
if (~warn)
if (nunused)
varargout{nout} = unused;
else
varargout{nout} = cell(0);
end
end
|
github
|
lcnhappe/happe-master
|
nonmaxsup.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/murphy/KPMtools/nonmaxsup.m
| 1,708 |
utf_8
|
ad451680a9d414f907da2969e0809c22
|
% NONMAXSUP - Non-maximal Suppression
%
% Usage: cim = nonmaxsup(im, radius)
%
% Arguments:
% im - image to be processed.
% radius - radius of region considered in non-maximal
% suppression (optional). Typical values to use might
% be 1-3. Default is 1.
%
% Returns:
% cim - image with pixels that are not maximal within a
% square neighborhood zeroed out.
% Copyright (C) 2002 Mark A. Paskin
%
% 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 cim = nonmaxsup(m, radius)
if (nargin == 1) radius = 1; end
% Extract local maxima by performing a grey scale morphological
% dilation and then finding points in the corner strength image that
% match the dilated image and are also greater than the threshold.
sze = 2 * radius + 1; % Size of mask.
mx = ordfilt2(m, sze^2, ones(sze)); % Grey-scale dilate.
cim = sparse(m .* (m == mx));
|
github
|
lcnhappe/happe-master
|
laplacedegenerate_ep.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/bayesianlogreg/laplacedegenerate_ep.m
| 18,982 |
utf_8
|
f7c41d02425138606269031927275e33
|
function [Gauss,terms,logp,comptime] = laplacedegenerate_ep(y,X,K,varargin)
% specialized version of our fast variant of
% Expectation Propagation for Logistic Regression (2 classes) with a (correlated) Laplace prior
% in the degenerate case, i.e., when the number of features >> number of samples
% (also works when number of samples > number of features, but then less stable!!!)
%
% input:
% labels = an N x 1 vector of class labels [1,2]
% examples = an N x M matrix of input data
% K = the prior precision matrix of size M x M
%
% Note: the bias term should be explicitly added to K and the examples!
%
% regression parameters refers to betas
% auxiliary variables refers to u and v whose precision matrix auxK = inv(Lambda) couples the features.
%
% we have a precision matrix of the form
%
% | K_beta |
% | K_u |
% | K_v |
%
% priorGauss: struct with fields
%
% hatK diagonal of precision matrix (number of samples x 1);
% (initially zero)
% diagK diagonal of precision matrix (number of features x 1)
% (initially zero)
%
% precision matrix of regression parameters K_beta = A' hatK A + diagK
%
% h canonical mean (number of features x 1)
% (initially zero)
%
% auxK precision matrix of auxiliary variables (number of features x number of features; sparse)
% (contains the covariance structure of interest)
%
% A feature matrix (number of samples x number of features)
%
% terms: struct with fields
%
% hatK as priorGauss
% diagK as priorGauss
% hath canonical mean (number of samples x 1)
% h canonical mean (number of features x 1)
% canonical mean of regression parameters = h + A' hath
% auxK as priorGauss, but then only diagonal elements (number of features x 1)
%
% opt: struct with fields (all optional, defaults in brackets)
%
% maxstepsize maximum step size [1]
% fraction fraction or power for fractional/power EP [1]
% niter maximum number of iterations [100]
% tol convergence criterion [1e-5]
% nweights number of points for numerical integration [20]
% temperature temperature for simulated annealing [1]
% verbose give output during run [1]
%
% Gauss: struct with fields as in priorGauss plus
%
% hatB diagonal of projected covariance (number of samples x 1)
% hatB = A Covariance A'
% hatn projected mean (number of samples x 1)
% hatn = A m
% diagC diagonal of covariance matrix of regression parameters (number of features x 1)
% auxC diagonal of covariance matrix of auxiliary variables (number of features x 1)
%
%
% logp: estimated marginal loglikelihood (implementation doubtful...)
%
% comptime: computation time
%% initialization
% parse opt
opt = [];
for i=1:2:length(varargin)
opt.(varargin{i}) = varargin{i+1};
end
if ~isfield(opt,'maxstepsize'), opt.maxstepsize = 1; end
if ~isfield(opt,'fraction'), opt.fraction = 0.95; end
if ~isfield(opt,'niter'), opt.niter = 1000; end
if ~isfield(opt,'tol'), opt.tol = 1e-5; end
if ~isfield(opt,'nweights'), opt.nweights = 50; end
if ~isfield(opt,'temperature'), opt.temperature = 1; end
if ~isfield(opt,'lambda'), opt.lambda = 1; end
if ~isfield(opt,'verbose'), opt.verbose = 1; end
if opt.verbose
fprintf('starting EP\n');
end
tic
[nsamples,nfeatures] = size(X);
%% create priorGauss and terms
A = X.*repmat(y,1,nfeatures);
% construct Gaussian representation
priorGauss.A = A;
priorGauss.hatK = zeros(nsamples,1);
priorGauss.h = zeros(nfeatures,1);
priorGauss.diagK = zeros(nfeatures,1);
priorGauss.auxK = K;
% compute additional terms for the EP free energy
[cholK,dummy,S] = chol(K,'lower');
LogPriorRestAux2 = (2*sum(log(full(diag(cholK))))); % -nfeatures*log(2*pi)); % redundant MvG
% construct term representation
terms.hatK = ones(nsamples,1)/10;
terms.hath = zeros(nsamples,1);
terms.diagK = ones(nfeatures,1)./(10*opt.lambda);
terms.auxK = zeros(nfeatures,1);
terms.h = zeros(nfeatures,1);
%% precompute points and weights for numerical integration
[xhermite,whermite] = gausshermite(opt.nweights);
xhermite = xhermite(:); % nhermite x 1
whermite = whermite(:); % nhermite x 1
[xlaguerre,wlaguerre] = gausslaguerre(opt.nweights);
xlaguerre = xlaguerre(:); % nlaguerre x 1
wlaguerre = wlaguerre(:); % nlaguerre x 1
% divide all canonical parameters by the temperature
if opt.temperature ~= 1,
[priorGauss,terms] = correct_for_temperature(priorGauss,terms,opt.temperature);
end
%% build initial Gauss
% add terms to prior
Gauss = update_Gauss(priorGauss,terms);
Gauss = canonical_to_moments(Gauss);
[myGauss,ok] = project_all(Gauss,terms,opt.fraction);
if ~ok,
error('improper cavity distributions\n');
end
prior = Gauss; % save prior Gauss
%% enter the iterations
logp = 0;
logpold = 2*opt.tol;
change = 0;
teller = 0;
stepsize = opt.maxstepsize;
while abs(logp-logpold) > stepsize*opt.tol && teller < opt.niter,
teller = teller+1;
logpold = logp;
oldchange = change;
% compute the new term approximation by applying an adf update on all the cavity approximations
[fullterms,logreglogz,crosslogz] = ...
adfupdate_all(myGauss,terms,xhermite,whermite,xlaguerre,wlaguerre,opt.fraction,opt.temperature);
ok = 0;
ok1 = 1;
ok2 = 1;
while ~ok,
% try to replace the old term approximations by the new term approximations and check whether the new Gauss is still fine
[newGauss,newterms,ok1] = try_update(Gauss,fullterms,terms,stepsize);
%[newGauss,newterms,ok1] = try_update(Gauss,fullterms,terms,0.5);
if ok1,
% compute all cavity approximations needed for the next EP updates and check whether they are all fine
[newGauss,myGauss,logZappx,ok2] = try_project(newGauss,newterms,opt.fraction);
end
ok = (ok1 & ok2);
if ok, % accept
terms = newterms;
Gauss = newGauss;
stepsize = min(opt.maxstepsize,stepsize*1.9);
else % try with smaller stepsize
stepsize = stepsize/2;
if ~ok1,
fprintf('improper full covariance: lowering stepsize to %g\n',stepsize');
elseif ~ok2,
fprintf('improper cavity covariance: lowering stepsize to %g\n',stepsize');
end
if stepsize < 1e-10,
warning('Cannot find an update that leads to proper cavity approximations');
teller = opt.niter;
break;
end
end
end
% compute marginal moments
if ok,
% compute marginal loglikelihood
%logp = sum(logz) + sum(crosslogz) + logdet/2 + contribQ;
% CorrTermCross1 = (myGauss.m.^2)./myGauss.diagC - (newGauss.m.^2)./newGauss.diagC + log(myGauss.diagC/newGauss.diagC);
% CorrTermCross2 = log(myGauss.auxC/newGauss.auxC);
% CorrTerm = 0.5*CorrTermCross1 + 0.5*(CorrTermCross2 + CorrTermCross2);
logp = (sum(crosslogz) + sum(logreglogz))./opt.fraction + logZappx + LogPriorRestAux2;
if opt.verbose
fprintf('%d: %g (stepsize: %g)\n',teller,logp,stepsize);
end
% check whether marginal loglikelihood is going up and down, if so, lower stepsize
change = logp-logpold;
if change*oldchange < 0, % possibly cycling
stepsize = stepsize/2;
end
oldchange = change;
end
end
comptime = toc;
if opt.verbose
fprintf('EP finished in %s seconds\n',num2str(comptime));
end
Gauss.prior = prior;
%%% END MAIN
%%%%%%%%%
%
% compute the cavity approximations that result when subtracting a fraction of the term approximations
function [myGauss,ok] = project_all(Gauss,terms,fraction)
if nargin < 3,
fraction = 1;
end
% take out and project in moment form
% (1) regression parameters
[myGauss.hatB,myGauss.hatn] = ...
rank_one_update(Gauss.hatB,Gauss.hatn,-fraction*terms.hatK,-fraction*terms.hath);
% (2) cross terms between regression parameters and auxiliary parameters
[myGauss.diagC,myGauss.m] = ...
rank_one_update(Gauss.diagC,Gauss.m,-fraction*terms.diagK,-fraction*terms.h);
myGauss.auxC = rank_one_update(Gauss.auxC,[],-fraction*terms.auxK);
% check whether all precision matrices are strictly positive definite
if nargout > 1,
ok = (all(myGauss.hatB > 0) & all(myGauss.diagC > 0) & all(myGauss.auxC > 0));
end
%%%%%%%%%
%
% compute the new term approximation by applying an adf update on all the cavity approximations
function [fullterms,logreglogz,crosslogz] = ...
adfupdate_all(myGauss,terms,xhermite,whermite,xlaguerre,wlaguerre,fraction,temperature)
if nargin < 8,
temperature = 1;
end
if nargin < 7,
fraction = 1;
end
%% (1) regression parameters
oldm = myGauss.hatn;
oldC = myGauss.hatB;
sqrtC = sqrt(oldC);
nsamples = length(oldm);
nhermite = length(whermite);
% translate and scale the sample points to get the correct mean and variance
x = repmat(oldm,1,nhermite) + sqrtC*xhermite';
% compute the terms at the sample points
g = logist(x); % returns - log (1 + exp(-x)) with special attention for very small and very large x
% correct for fraction and temperature and incorporate the sample weights
g = fraction*g/temperature + log(repmat(whermite',nsamples,1));
maxg = max(g,[],2);
g = g-repmat(maxg,1,nhermite);
expg = exp(g);
denominator = sum(expg,2);
neww = expg./repmat(denominator,1,nhermite);
% compute the moments
Ex = sum(x.*neww,2);
Exx = sum(x.^2.*neww,2);
newm = Ex;
newC = Exx-Ex.^2;
% derive the term approximation from the change in mean and variance
[fullterms.hatK,fullterms.hath,logzextra] = compute_termproxy(newC,newm,oldC,oldm,fraction);
% contributions to marginal loglikelihood
logreglogz = maxg + log(denominator) + logzextra;
%% (2) cross terms between regression parameters and auxiliary variables
oldm = myGauss.m;
oldC = myGauss.diagC;
oldlambda = myGauss.auxC;
nfeatures = length(oldm);
nlaguerre = length(wlaguerre);
% this part heavily relies on the accompanying note
% basic idea:
% - the cavity approximation on U is an exponential distribution
% - we have analytical formulas for the moments of x conditioned upon U
% - marginal moments can then be computed through numerical integration with Gauss-Laguerre
% translate and scale the sample points to get the correct mean
U = 2*oldlambda*xlaguerre'; % nfeatures x nlaguerre
mm = repmat(oldm,1,nlaguerre);
CC = repmat(oldC,1,nlaguerre);
% compute the partition function (integral over x) given U and turn this into weights required for computing the marginal moments
g = (1-fraction)*log(U)/2 - fraction*mm.^2./(U + fraction*CC)/2 - log(U+ fraction*CC)/2;
g = bsxfun(@plus,g,log(wlaguerre'));
maxg = max(g,[],2);
g = bsxfun(@minus,g,maxg);
expg = exp(g);
denominator = sum(expg,2);
neww = bsxfun(@rdivide,expg,denominator);
% compute the marginal moments through numerical integration
ExgU = mm.*U./(U + fraction*CC);
Ex = sum(ExgU.*neww,2);
ExxgU = ExgU.^2 + CC.*U./(U+fraction*CC);
Exx = sum(ExxgU.*neww,2);
EU = sum(U.*neww,2);
newm = Ex;
newC = Exx-Ex.^2;
newlambda = EU/2;
% derive the term approximation from the change in mean and variance
[fullterms.diagK,fullterms.h,logzextra1] = compute_termproxy(newC,newm,oldC,oldm,fraction);
[fullterms.auxK,dummy,logzextra2] = compute_termproxy(newlambda,zeros(nfeatures,1),oldlambda,zeros(nfeatures,1),fraction);
crosslogz = maxg + log(denominator) + logzextra1 + 2*logzextra2;
% multiplied the last term by two
%%%%%%%%%%
%
% compute the moments corresponding to the canonical parameters
function [Gauss,logp] = canonical_to_moments(Gauss)
[nsamples,nfeatures] = size(Gauss.A);
%% (1) regression parameters
if nsamples > nfeatures, % in the non-degenerate case, this direct route is more stable and faster
scaledA = Gauss.A.*(repmat(Gauss.hatK,1,nfeatures));
K = Gauss.A'*scaledA + diag(Gauss.diagK);
[C,logdet1] = invert_chol(K);
Gauss.m = C*Gauss.h;
Gauss.hatB = zeros(nsamples,1); % only need diagonal
for k=1:nsamples,
Gauss.hatB(k) = Gauss.A(k,:)*C*Gauss.A(k,:)';
end
Gauss.diagC = diag(C);
Gauss.hatn = Gauss.A*Gauss.m;
else
% this part heavily relies on the appendix of the accompanying note
% basic idea:
% - the precision matrix K is of the form A' hatK A + diagK, where both hatK and diagK are diagonal matrices
% - apply Woodbury's formula to replace inverting an (nfeat x nfeat) matrix by an (nsample x nsample) alternative
% - projections of the covariance matrix and the mean onto the feature matrix then follow immediately
scaledA = bsxfun(@rdivide,Gauss.A,Gauss.diagK');
W = Gauss.A*scaledA';
W = (W + W')/2; % make symmetric
[Q,logdet1] = invert_chol(diag(1./Gauss.hatK) + W);
Gauss.hatB = zeros(nsamples,1);
for k=1:nsamples,
Gauss.hatB(k) = W(k,k) - W(k,:)*Q*W(:,k);
end
Gauss.m = Gauss.h./Gauss.diagK - scaledA'*(Q*(scaledA*Gauss.h));
Gauss.hatn = Gauss.A*Gauss.m;
Gauss.diagC = 1./Gauss.diagK;
% for i=1:nfeatures,
% Gauss.diagC(i) = Gauss.diagC(i) - scaledA(:,i)'*Q*scaledA(:,i);
% end
% adriana's recipe
z = scaledA' * Q; for i=1:size(z), Gauss.diagC(i) = Gauss.diagC(i) - z(i,:) * scaledA(:,i); end
logdet1 = logdet1 + sum(log(Gauss.diagK)) + sum(log(Gauss.hatK));
end
% compute quadratic term (BC)
qterm = sum(Gauss.m .* Gauss.diagK .* Gauss.m); % = m' * diagK * m
qterm = qterm + sum(Gauss.hatn .* Gauss.hatK .* Gauss.hatn);
logp1 = 0.5*(qterm - logdet1);
%% (2) auxiliary variables; i.e., wrt scale mixture representation of
% Laplace prior
% this is (by far) the most expensive step when nsamples << nfeatures
% and the precision matrix of the auxiliary variables is non-diagonal
[auxC,logdet2] = invert_chol(Gauss.auxK); % only need diagonal terms
Gauss.auxC = full(diag(auxC)); % turn into full vector
logp2 = 0.5*( - logdet2);
logp = logp1 + 2*logp2;
%%%%%%%%%%
%
% take out the old term proxies and add the new termproxies and check whether the resulting Gaussian is still normalizable
function [newGauss,newterms,ok] = try_update(Gauss,fullterms,terms,stepsize)
if nargin < 4,
stepsize = 1;
end
% take out the old term proxies
newGauss = update_Gauss(Gauss,terms,-1);
% compute the new term proxies as a weighted combi of the old ones and the "full" (stepsize 1) term proxies
newterms = combine_terms(fullterms,terms,stepsize);
% add the new term proxies
newGauss = update_Gauss(newGauss,newterms,1);
[L,check,dummy] = chol(newGauss.auxK,'lower'); % check whether full covariance matrix is ok
% note that this is bit inefficient, since we redo the Cholesky later when everything is fine
ok = (check == 0 & all(newGauss.hatK > 0) & all(newGauss.diagK > 0)); % perhaps a bit too strong???
%%%%%%%%%%%%
%
% compute the moment form of the current Gauss and all cavity approximations and check whether they are fine
function [Gauss,myGauss,logdet,ok] = try_project(Gauss,terms,fraction)
if nargin < 3,
fraction = 1;
end
[Gauss,logdet] = canonical_to_moments(Gauss);
[myGauss,ok] = project_all(Gauss,terms,fraction);
%%%%%%%%%%
%
% if we use a temperature < 1, to get closer to the MAP solution, we have to change the prior and initial term proxies accordingly
function [Gauss,terms] = correct_for_temperature(Gauss,terms,temperature)
% note: choose temperature small to implement MAP-like behavior
Gauss.hatK = Gauss.hatK/temperature;
Gauss.h = Gauss.h/temperature;
Gauss.auxK = Gauss.auxK/temperature;
Gauss.diagK = Gauss.diagK/temperature;
terms.hatK = terms.hatK/temperature;
terms.hath = terms.hath/temperature;
terms.diagK = terms.diagK/temperature;
terms.auxK = terms.auxK/temperature;
terms.h = terms.h/temperature;
%%%%%%%%%%
%
% invert a positive definite matrix using Cholesky factorization
function [invA,logdet] = invert_chol(A)
if issparse(A)
if 0 % matlab version; slower but useful in case of mex problems
[L,dummy,S] = chol(sparse(A),'lower'); % now A = S*(L*L')*S' and (L*L') = S'*A*S
n = length(L);
invdiagL2 = 1./spdiags(L,0).^2;
invA = A;
for i=n:-1:1,
I = i+find(L(i+1:n,i));
invA(I,i) = -(invA(I,I)*L(I,i))/L(i,i);
invA(i,I) = invA(I,i)';
invA(i,i) = invdiagL2(i) - (invA(i,I)*L(I,i))/L(i,i);
end
invA = S*invA*S';
else
[L,dummy,S] = chol(sparse(A),'lower'); % now A = S*(L*L')*S' and (L*L') = S'*A*S
if dummy
error('matrix is not p.d.');
end
invA = fastinvc(L);
invA = S*invA*S';
end
else
[L,dummy] = chol(A,'lower');
if dummy
error('matrix is not p.d.');
end
invA = inv(A);
end
if nargout > 1,
logdet = 2*sum(log(full(diag(L))));
end
%%%%%%%%%%
%
% compute the term proxy when [oldC,oldm] changes to [newC,newm]
function [K,h,logz] = compute_termproxy(newC,newm,oldC,oldm,fraction)
if nargin < 5,
fraction = 1;
end
K = (1./newC - 1./oldC)/fraction;
h = (newm./newC - oldm./oldC)/fraction;
logz = oldm.^2./oldC/2 - newm.^2./newC/2 + log(full(oldC./newC))/2 ;
%%%%%%%%%%
%
% Sherman-Morrison formula to compute the change from [oldC,oldm] to [newC,newm] when we add [K,h] to the corresponding canonical parameters
function [newC,newm] = rank_one_update(oldC,oldm,K,h)
dummy = K.*oldC;
oneminusdelta = 1./(1+dummy);
newC = oneminusdelta.*oldC;
if nargout > 1,
newm = oneminusdelta.*(oldm + h.*oldC);
end
%%%%%%%%%%%
%
% general procedure for a weighted combi of the fields of two structures
function terms = combine_terms(terms1,terms2,stepsize)
names1 = fieldnames(terms1);
names2 = fieldnames(terms2);
names = intersect(names1,names2);
terms = struct;
for i=1:length(names)
terms.(names{i}) = stepsize*terms1.(names{i}) + (1-stepsize)*terms2.(names{i});
end
%%%%%%%%%%%
%
% updates the Gaussian representation with new term proxies
function Gauss = update_Gauss(Gauss,terms,const)
if nargin < 3,
const = 1;
end
Gauss.h = Gauss.h + const*Gauss.A'*terms.hath + const*terms.h;
Gauss.hatK = Gauss.hatK + const*terms.hatK;
Gauss.diagK = Gauss.diagK + const*terms.diagK;
% get diagonal elements
diagidx = 1:(size(Gauss.auxK,1)+1):numel(Gauss.auxK);
Gauss.auxK(diagidx) = Gauss.auxK(diagidx) + const*terms.auxK';
|
github
|
lcnhappe/happe-master
|
bayesianlinreg_ep.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/bayesianlogreg/bayesianlinreg_ep.m
| 17,556 |
utf_8
|
64edf12e5451aa53b2d6ab3ff064778f
|
function [Gauss,terms,logp,comptime] = bayesianlinreg_ep(labels,examples,K,varargin)
% Bayesian linear regression with a multivariate Laplace prior using a fast
% variant of EP.
%HERE
% input:
% labels = an N x 1 vector of class labels [1,2]
% examples = an N x M matrix of input data
% K = the prior precision matrix of size M x M
%
% Note: the bias term should be explicitly added to K and the examples!
%
% regression parameters refers to betas
% auxiliary variables refers to u and v whose precision matrix auxK = inv(Lambda) couples the features.
%
% we have a precision matrix of the form
%
% | K_beta |
% | K_u |
% | K_v |
%
% priorGauss: struct with fields
%
% hatK diagonal of precision matrix (number of samples x 1);
% (initially zero)
% diagK diagonal of precision matrix (number of features x 1)
% (initially zero)
%
% precision matrix of regression parameters K_beta = A' hatK A + diagK
%
% h canonical mean (number of features x 1)
% (initially zero)
%
% auxK precision matrix of auxiliary variables (number of features x number of features; sparse)
% (contains the covariance structure of interest)
%
% A feature matrix (number of samples x number of features)
%
% terms: struct with fields
%
% hatK as priorGauss
% diagK as priorGauss
% hath canonical mean (number of samples x 1)
% h canonical mean (number of features x 1)
% canonical mean of regression parameters = h + A' hath
% auxK as priorGauss, but then only diagonal elements (number of features x 1)
%
% opt: struct with fields (all optional, defaults in brackets)
%
% maxstepsize maximum step size [1]
% fraction fraction or power for fractional/power EP [1]
% niter maximum number of iterations [100]
% tol convergence criterion [1e-5]
% nweights number of points for numerical integration [20]
% temperature temperature for simulated annealing [1]
%
% Gauss: struct with fields as in priorGauss plus
%
% hatB diagonal of projected covariance (number of samples x 1)
% hatB = A Covariance A'
% hatn projected mean (number of samples x 1)
% hatn = A m
% diagC diagonal of covariance matrix of regression parameters (number of features x 1)
% auxC diagonal of covariance matrix of auxiliary variables (number of features x 1)
%
%
% logp: estimated marginal loglikelihood (implementation doubtful...)
%
% comptime: computation time
fprintf('starting EP\n');
tic
%% initialization
% parse opt
opt = [];
for i=1:2:length(varargin)
opt.(varargin{i}) = varargin{i+1};
end
if ~isfield(opt,'maxstepsize'), opt.maxstepsize = 1; end
if ~isfield(opt,'fraction'), opt.fraction = 0.99; end
if ~isfield(opt,'niter'), opt.niter = 100; end
if ~isfield(opt,'tol'), opt.tol = 1e-5; end
if ~isfield(opt,'nweights'), opt.nweights = 50; end
if ~isfield(opt,'temperature'), opt.temperature = 1; end
if ~isfield(opt,'lambda'), opt.lambda = 0.001; end
stepsize = opt.maxstepsize;
[nsamples,nfeatures] = size(examples);
%% create priorGauss and terms
% transform data to +1/-1 representation
A = examples;
y = 3-2*labels;
A = A.*repmat(y,1,nfeatures);
% construct Gaussian representation
priorGauss.A = A;
priorGauss.hatK = zeros(nsamples,1);
priorGauss.h = zeros(nfeatures,1);
priorGauss.diagK = zeros(nfeatures,1);
priorGauss.auxK = K;
% construct term representation
terms.hatK = ones(nsamples,1)/10;
terms.hath = zeros(nsamples,1);
terms.diagK = ones(nfeatures,1)/opt.lambda/10;
terms.auxK = zeros(nfeatures,1);
terms.h = zeros(nfeatures,1);
%% precompute points and weights for numerical integration
[xhermite,whermite] = gausshermite(opt.nweights);
xhermite = xhermite(:); % nhermite x 1
whermite = whermite(:); % nhermite x 1
[xlaguerre,wlaguerre] = gausslaguerre(opt.nweights);
xlaguerre = xlaguerre(:); % nlaguerre x 1
wlaguerre = wlaguerre(:); % nlaguerre x 1
% divide all canonical parameters by the temperature
if opt.temperature ~= 1,
[priorGauss,terms] = correct_for_temperature(priorGauss,terms,opt.temperature);
end
% compute cholesky of the prior precision matrix
% used when computing the model evidence
[cholK,dummy,S] = chol(K,'lower');
contribQ = sum(log(diag(cholK).^2));
%% build initial Gauss
% add terms to prior
Gauss = update_Gauss(priorGauss,terms);
%% convert from canonical to moment form
Gauss = canonical_to_moments(Gauss);
%% compute all cavity approximations needed for the EP updates and check whether they are all fine
[myGauss,ok] = project_all(Gauss,terms,opt.fraction);
if ~ok,
error('improper cavity distributions\n');
end
%% enter the iterations
logp = 0;
logpold = 2*opt.tol;
change = 0;
teller = 0;
while abs(logp-logpold) > stepsize*opt.tol && teller < opt.niter,
teller = teller+1;
logpold = logp;
oldchange = change;
% compute the new term approximation by applying an adf update on all the cavity approximations
[fullterms,logz,crosslogz] = ...
adfupdate_all(myGauss,terms,xhermite,whermite,xlaguerre,wlaguerre,opt.fraction,opt.temperature);
ok = 0;
while ~ok,
% try to replace the old term approximations by the new term approximations and check whether the new Gauss is still fine
[newGauss,newterms,ok1] = try_update(Gauss,fullterms,terms,stepsize);
if ok1,
% compute all cavity approximations needed for the next EP updates and check whether they are all fine
[newGauss,myGauss,logdet,ok2] = try_project(newGauss,newterms,opt.fraction);
end
ok = (ok1 & ok2);
if ok, % accept
terms = newterms;
Gauss = newGauss;
stepsize = min(opt.maxstepsize,stepsize*1.9);
else % try with smaller stepsize
stepsize = stepsize/2;
if ~ok1,
fprintf('improper full covariance: lowering stepsize to %g\n',stepsize');
elseif ~ok2,
fprintf('improper cavity covariance: lowering stepsize to %g\n',stepsize');
end
if stepsize < 1e-10,
warning('Cannot find an update that leads to proper cavity approximations\ldots');
teller = opt.niter;
break;
end
end
end
% compute marginal moments
if ok,
% compute marginal loglikelihood
%logp = sum(logz) + sum(crosslogz) + logdet/2 + contribQ;
logp = sum(logz)./opt.fraction + sum(crosslogz)./opt.fraction + logdet/2 + contribQ;
% note:
%
% logdet/2 = 1/2 log |K| for the posterior K
% contribQ = log |Q| for the prior Q (MvG)
% quadratic term added (BC)
% don't trust the calculation anyway, in particular for fractional updates...
fprintf('%d: %g (stepsize: %g)\n',teller,logp,stepsize);
% check whether marginal loglikelihood is going up and down, if so, lower stepsize
change = logp-logpold;
if change*oldchange < 0, % possibly cycling
stepsize = stepsize/2;
end
oldchange = change;
end
end
comptime = toc;
fprintf('EP finished in %s seconds\n',num2str(comptime));
%%% END MAIN
%%%%%%%%%
%
% compute the cavity approximations that result when subtracting a fraction of the term approximations
function [myGauss,ok] = project_all(Gauss,terms,fraction)
if nargin < 3,
fraction = 1;
end
% take out and project in moment form
% (1) regression parameters
[myGauss.hatB,myGauss.hatn] = ...
rank_one_update(Gauss.hatB,Gauss.hatn,-fraction*terms.hatK,-fraction*terms.hath);
% (2) cross terms between regression parameters and auxiliary parameters
[myGauss.diagC,myGauss.m] = ...
rank_one_update(Gauss.diagC,Gauss.m,-fraction*terms.diagK,-fraction*terms.h);
myGauss.auxC = rank_one_update(Gauss.auxC,[],-fraction*terms.auxK);
% check whether all precision matrices are strictly positive definite
if nargout > 1,
ok = (all(myGauss.hatB > 0) & all(myGauss.diagC > 0) & all(myGauss.auxC > 0));
end
%%%%%%%%%
%
% compute the new term approximation by applying an adf update on all the cavity approximations
function [fullterms,logz,crosslogz] = ...
adfupdate_all(myGauss,terms,xhermite,whermite,xlaguerre,wlaguerre,fraction,temperature)
if nargin < 8,
temperature = 1;
end
if nargin < 7,
fraction = 1;
end
%% (1) regression parameters
oldm = myGauss.hatn;
oldC = myGauss.hatB;
sqrtC = sqrt(oldC);
nsamples = length(oldm);
nhermite = length(whermite);
% translate and scale the sample points to get the correct mean and variance
x = repmat(oldm,1,nhermite) + sqrtC*xhermite';
% compute the terms at the sample points
g = logistic(x); % returns - log (1 + exp(-x)) with special attention for very small and very large x
% correct for fraction and temperature and incorporate the sample weights
g = fraction*g/temperature + log(repmat(whermite',nsamples,1));
% some care take for numerical stability
maxg = max(g,[],2);
g = g-repmat(maxg,1,nhermite);
expg = exp(g);
denominator = sum(expg,2);
neww = expg./repmat(denominator,1,nhermite);
% compute the moments
Ex = sum(x.*neww,2);
Exx = sum(x.^2.*neww,2);
newm = Ex;
newC = Exx-Ex.^2;
% derive the term approximation from the change in mean and variance
[fullterms.hatK,fullterms.hath,logzextra] = ...
compute_termproxy(newC,newm,oldC,oldm,fraction);
% contributions to marginal loglikelihood
logz = maxg + log(denominator) + logzextra;
%% (2) cross terms between regression parameters and auxiliary variables
oldm = myGauss.m;
oldC = myGauss.diagC;
oldlambda = myGauss.auxC;
nfeatures = length(oldm);
nlaguerre = length(wlaguerre);
% this part heavily relies on the accompanying note
% basic idea:
% - the cavity approximation on U is an exponential distribution
% - we have analytical formulas for the moments of x conditioned upon U
% - marginal moments can then be computed through numerical integration with Gauss-Laguerre
% translate and scale the sample points to get the correct mean
U = 2*oldlambda*xlaguerre'; % nfeatures x nlaguerre
mm = repmat(oldm,1,nlaguerre);
CC = repmat(oldC,1,nlaguerre);
% compute the partition function (integral over x) given U and turn this into weights required for computing the marginal moments
g = -mm.^2./(U+CC)/2 - log(U+CC)/2 - log(2*pi)/2;
g = fraction*g + log(repmat(wlaguerre',nfeatures,1));
maxg = max(g,[],2);
g = g-repmat(maxg,1,nlaguerre);
expg = exp(g);
denominator = sum(expg,2);
neww = expg./repmat(denominator,1,nlaguerre);
% compute the marginal moments through numerical integration
ExgU = mm.*U./(U+CC);
Ex = sum(ExgU.*neww,2);
ExxgU = ExgU.^2 + CC.*U./(U+CC);
Exx = sum(ExxgU.*neww,2);
EU = sum(U.*neww,2);
newm = Ex;
newC = Exx-Ex.^2;
newlambda = EU/2;
% derive the term approximation from the change in mean and variance
[fullterms.diagK,fullterms.h,logzextra1] = ...
compute_termproxy(newC,newm,oldC,oldm,fraction);
% same for the auxiliary variables, where we note that the mean will always be zero
[fullterms.auxK,dummy,logzextra2] = ...
compute_termproxy(newlambda,zeros(nfeatures,1),oldlambda,zeros(nfeatures,1),fraction);
crosslogz = maxg + log(denominator) + logzextra1 + logzextra2;
%%%%%%%%%%
%
% compute the moments corresponding to the canonical parameters
function [Gauss,logdet] = canonical_to_moments(Gauss)
[nsamples,nfeatures] = size(Gauss.A);
%% (1) regression parameters
if nsamples > nfeatures, % in the non-degenerate case, this direct route is more stable and faster
scaledA = Gauss.A.*(repmat(Gauss.hatK,1,nfeatures));
K = Gauss.A'*scaledA + diag(Gauss.diagK);
[C,logdet1] = invert_chol(K);
Gauss.m = C*Gauss.h;
Gauss.hatB = zeros(nsamples,1); % only need diagonal
for k=1:nsamples,
Gauss.hatB(k) = Gauss.A(k,:)*C*Gauss.A(k,:)';
end
Gauss.diagC = diag(C);
Gauss.hatn = Gauss.A*Gauss.m;
%logdet1 = 2*sum(log(diag(L)));
else
% this part heavily relies on the appendix of the accompanying note
% basic idea:
% - the precision matrix K is of the form A' hatK A + diagK, where both hatK and diagK are diagonal matrices
% - apply Woodbury's formula to replace inverting an (nfeat x nfeat) matrix by an (nsample x nsample) alternative
% - projections of the covariance matrix and the mean onto the feature matrix then follow immediately
scaledA = Gauss.A./(repmat(Gauss.diagK',nsamples,1));
W = Gauss.A*scaledA';
W = (W + W')/2; % make symmetric
[Q,logdet1] = invert_chol(diag(1./Gauss.hatK) + W);
Gauss.hatB = zeros(nsamples,1);
for k=1:nsamples,
Gauss.hatB(k) = W(k,k) - W(k,:)*Q*W(:,k);
end
Gauss.m = Gauss.h./Gauss.diagK - scaledA'*(Q*(scaledA*Gauss.h));
Gauss.hatn = Gauss.A*Gauss.m;
Gauss.diagC = 1./Gauss.diagK;
for i=1:nfeatures,
Gauss.diagC(i) = Gauss.diagC(i) - scaledA(:,i)'*Q*scaledA(:,i);
end
logdet1 = logdet1 + sum(log(Gauss.diagK)) + sum(log(Gauss.hatK));
% compute quadratic term (BC)
qterm = sum(Gauss.m .* Gauss.diagK .* Gauss.m); % = m' * diagK * m
qterm = qterm + sum(Gauss.hatn .* Gauss.hatK .* Gauss.hatn);
logdet1 = -logdet1 + qterm;
end
%% (2) auxiliary variables; i.e., wrt scale mixture representation of
% Laplace prior
% this is (by far) the most expensive step when nsamples << nfeatures
% and the precision matrix of the auxiliary variables is non-diagonal
[auxC,logdet2] = invert_chol(Gauss.auxK); % only need diagonal terms
Gauss.auxC = full(diag(auxC)); % turn into full vector
logdet = logdet1 - 2*logdet2;
% added 2*logdet2
%%%%%%%%%%
%
% take out the old term proxies and add the new termproxies and check whether the resulting Gaussian is still normalizable
function [newGauss,newterms,ok] = try_update(Gauss,fullterms,terms,stepsize)
if nargin < 4,
stepsize = 1;
end
% take out the old term proxies
newGauss = update_Gauss(Gauss,terms,-1);
% compute the new term proxies as a weighted combi of the old ones and the "full" (stepsize 1) term proxies
newterms = combine_terms(fullterms,terms,stepsize);
% add the new term proxies
newGauss = update_Gauss(newGauss,newterms,1);
[L,check,dummy] = chol(newGauss.auxK,'lower'); % check whether full covariance matrix is ok
% note that this is bit inefficient, since we redo the Cholesky later when everything is fine
ok = (check == 0 & all(newGauss.hatK > 0) & all(newGauss.diagK > 0)); % perhaps a bit too strong???
%%%%%%%%%%%%
%
% compute the moment form of the current Gauss and all cavity approximations and check whether they are fine
function [Gauss,myGauss,logdet,ok] = try_project(Gauss,terms,fraction)
if nargin < 3,
fraction = 1;
end
[Gauss,logdet] = canonical_to_moments(Gauss);
[myGauss,ok] = project_all(Gauss,terms,fraction);
%%%%%%%%%%
%
% if we use a temperature < 1, to get closer to the MAP solution, we have to change the prior and initial term proxies accordingly
function [Gauss,terms] = correct_for_temperature(Gauss,terms,temperature)
% note: choose temperature small to implement MAP-like behavior
Gauss.hatK = Gauss.hatK/temperature;
Gauss.h = Gauss.h/temperature;
Gauss.auxK = Gauss.auxK/temperature;
Gauss.diagK = Gauss.diagK/temperature;
terms.hatK = terms.hatK/temperature;
terms.hath = terms.hath/temperature;
terms.diagK = terms.diagK/temperature;
terms.auxK = terms.auxK/temperature;
terms.h = terms.h/temperature;
%%%%%%%%%%
%
% invert a positive definite matrix using Cholesky factorization
function [invA,logdet] = invert_chol(A)
[L,dummy,S] = chol(sparse(A),'lower'); % now A = S*(L*L')*S' and (L*L') = S'*A*S
invA = fastinvc(L);
invA = S*invA*S';
if nargout > 1,
logdet = 2*sum(log(diag(L)));
end
%%%%%%%%%%
%
% compute the term proxy when [oldC,oldm] changes to [newC,newm]
function [K,h,logz] = compute_termproxy(newC,newm,oldC,oldm,fraction)
if nargin < 5,
fraction = 1;
end
K = (1./newC - 1./oldC)/fraction;
h = (newm./newC - oldm./oldC)/fraction;
logz = - log(newC./oldC)/2 + oldm.^2./oldC/2 - newm.^2./newC/2;
%%%%%%%%%%
%
% Sherman-Morrison formula to compute the change from [oldC,oldm] to [newC,newm] when we add [K,h] to the corresponding canonical parameters
function [newC,newm] = rank_one_update(oldC,oldm,K,h)
dummy = K.*oldC;
oneminusdelta = 1./(1+dummy);
newC = oneminusdelta.*oldC;
if nargout > 1,
newm = oneminusdelta.*(oldm + h.*oldC);
end
%%%%%%%%%%%
%
% general procedure for a weighted combi of the fields of two structures
function terms = combine_terms(terms1,terms2,stepsize)
names1 = fieldnames(terms1);
names2 = fieldnames(terms2);
names = intersect(names1,names2);
terms = struct;
for i=1:length(names)
terms.(names{i}) = stepsize*terms1.(names{i}) + (1-stepsize)*terms2.(names{i});
end
%%%%%%%%%%%
%
% updates the Gaussian representation with new term proxies
function Gauss = update_Gauss(Gauss,terms,const)
if nargin < 3,
const = 1;
end
Gauss.h = Gauss.h + const*Gauss.A'*terms.hath + const*terms.h;
Gauss.hatK = Gauss.hatK + const*terms.hatK;
Gauss.diagK = Gauss.diagK + const*terms.diagK;
% get diagonal elements
diagidx = 1:(size(Gauss.auxK,1)+1):numel(Gauss.auxK);
Gauss.auxK(diagidx) = Gauss.auxK(diagidx) + const*terms.auxK';
|
github
|
lcnhappe/happe-master
|
LinRegLaplaceEP.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/dmlt/external/bayesianlogreg/LinRegLaplaceEP.m
| 16,909 |
utf_8
|
1182837ca7d49d2ab0cd9588f826fffb
|
function [Gauss,terms,logp,EP_ERR,logphist] = LinRegLaplaceEP(y,X,K,sig2,varargin)
% specialized version of our fast variant of
% Expectation Propagation for Logistic Regression (2 classes) with a (correlated) Laplace prior
% in the degenerate case, i.e., when the number of features >> number of samples
% (also works when number of samples > number of features, but then less stable!!!)
%
% input:
% labels = an N x 1 vector of class labels [1,2]
% examples = an N x M matrix of input data
% K = the prior precision matrix of size M x M
%
% Note: the bias term should be explicitly added to K and the examples!
%
% regression parameters refers to betas
% auxiliary variables refers to u and v whose precision matrix auxK = inv(Lambda) couples the features.
%
% we have a precision matrix of the form
%
% | K_beta |
% | K_u |
% | K_v |
%
% priorGauss: struct with fields
%
% hatK diagonal of precision matrix (number of samples x 1);
% (initially zero)
% diagK diagonal of precision matrix (number of features x 1)
% (initially zero)
%
% precision matrix of regression parameters K_beta = A' hatK A + diagK
%
% h canonical mean (number of features x 1)
% (initially zero)
%
% auxK precision matrix of auxiliary variables (number of features x number of features; sparse)
% (contains the covariance structure of interest)
%
% A feature matrix (number of samples x number of features)
%
% terms: struct with fields
%
% hatK as priorGauss
% diagK as priorGauss
% hath canonical mean (number of samples x 1)
% h canonical mean (number of features x 1)
% canonical mean of regression parameters = h + A' hath
% auxK as priorGauss, but then only diagonal elements (number of features x 1)
%
% opt: struct with fields (all optional, defaults in brackets)
%
% maxstepsize maximum step size [1]
% fraction fraction or power for fractional/power EP [1]
% niter maximum number of iterations [100]
% tol convergence criterion [1e-5]
% nweights number of points for numerical integration [20]
% temperature temperature for simulated annealing [1]
%
% Gauss: struct with fields as in priorGauss plus
%
% hatB diagonal of projected covariance (number of samples x 1)
% hatB = A Covariance A'
% hatn projected mean (number of samples x 1)
% hatn = A m
% diagC diagonal of covariance matrix of regression parameters (number of features x 1)
% auxC diagonal of covariance matrix of auxiliary variables (number of features x 1)
%
%
% logp: estimated marginal loglikelihood (implementation doubtful...)
%
% comptime: computation time
fprintf('starting EP\n');
EP_ERR = 0;
tic
%% initialization
% parse opt
%disp(varargin{:})
%length(varargin{:})
opt = [];
for i=1:2:(length(varargin)-1)
opt.(varargin{i}) = varargin{i+1};
end
if ~isfield(opt,'maxstepsize'), opt.maxstepsize = 1; end
if ~isfield(opt,'fraction'), opt.fraction = 0.95; end
if ~isfield(opt,'niter'), opt.niter = 1000; end
if ~isfield(opt,'tol'), opt.tol = 1e-5; end
if ~isfield(opt,'nweights'), opt.nweights = 50; end
if ~isfield(opt,'temperature'), opt.temperature = 1; end
if ~isfield(opt,'lambda'), opt.lambda = 1; end
stepsize = opt.maxstepsize;
[nobs,nfeatures] = size(X);
%% create priorGauss and terms
% construct Gaussian representation
v = 1./sig2;
priorGauss.A = X;
priorGauss.hatK = v*ones(nobs,1);
priorGauss.h = v*X'*y;
priorGauss.diagK = zeros(nfeatures,1);
priorGauss.auxK = K;
% compute the additional terms coming form the prior for the evidence
cholK = chol(priorGauss.auxK,'lower');
LogPriorRestAux2 = (2*sum(log(full(diag(cholK))))-nfeatures*log(2*pi)); % no half because we need it two times
LogPriorRestLL = 0.5*(-v*y'*y - nobs*log(2*pi) + nobs*log(v) );
% construct term representation
%terms.hatK = zeros(nobs,1);
%terms.hath = zeros(nobs,1);
terms.diagK = ones(nfeatures,1)*opt.lambda/10;
terms.auxK = zeros(nfeatures,1);
terms.h = zeros(nfeatures,1);
%% precompute points and weights for numerical integration
[xhermite,whermite] = gausshermite(opt.nweights);
xhermite = xhermite(:); % nhermite x 1
whermite = whermite(:); % nhermite x 1
[xlaguerre,wlaguerre] = gausslaguerre(opt.nweights);
xlaguerre = xlaguerre(:); % nlaguerre x 1
wlaguerre = wlaguerre(:); % nlaguerre x 1
% divide all canonical parameters by the temperature
if opt.temperature ~= 1,
[priorGauss,terms] = correct_for_temperature(priorGauss,terms,opt.temperature);
end
%% build initial Gauss
Gauss = update_Gauss(priorGauss,terms);
Gauss = canonical_to_moments(Gauss);
[myGauss,ok] = project_all(Gauss,terms,opt.fraction);
if ~ok,
error('improper cavity distributions\n');
end
%% enter the iterations
logp = 0;
logpold = 2*opt.tol;
change = 0;
teller = 0;
logphist = zeros(1,opt.niter);
while abs(logp-logpold) > stepsize*opt.tol && teller < opt.niter,
teller = teller+1;
logpold = logp;
oldchange = change;
% compute the new term approximation by applying an adf update on all the cavity approximations
[fullterms,crosslogz] = ...
adfupdate_all(myGauss,terms,xhermite,whermite,xlaguerre,wlaguerre,opt.fraction,opt.temperature);
ok = 0;
ok1 = 1;
ok2 = 1;
while ~ok,
% try to replace the old term approximations by the new term approximations and check whether the new Gauss is still fine
% !!! THIS IS THE ORIGINAL LINE !!!
% [newGauss,newterms,ok1] = try_update(Gauss,fullterms,terms,stepsize);
% you might use this instead - sometimes it works better
[newGauss,newterms,ok1] = try_update(Gauss,fullterms,terms,0.1);
if ok1,
% compute all cavity approximations needed for the next EP updates and check whether they are all fine
[newGauss,myGauss,logZappx,ok2] = try_project(newGauss,newterms,opt.fraction);
end
ok = (ok1 & ok2);
if ok, % accept
terms = newterms;
Gauss = newGauss;
stepsize = min(opt.maxstepsize,stepsize*1.9);
else % try with smaller stepsize
stepsize = stepsize/2;
if ~ok1,
fprintf('improper full covariance: lowering stepsize to %g\n',stepsize');
elseif ~ok2,
fprintf('improper cavity covariance: lowering stepsize to %g\n',stepsize');
end
if stepsize < 1e-10,
warning('Cannot find an update that leads to proper cavity approximations.');
EP_ERR = 1;
teller = opt.niter;
break;
end
end
end
% compute marginal moments
if ok,
% compute marginal loglikelihood
%logp = sum(crosslogz) + logdet/2 + rest
CorrTerm1 = (myGauss.m.^2)./myGauss.diagC + log(full(myGauss.diagC)) - (newGauss.m.^2)./newGauss.diagC - log(full(newGauss.diagC));
CorrTerm2 = log(myGauss.auxC) - log(newGauss.auxC);
CorrTerm = 0.5*CorrTerm1 + 0.5*(CorrTerm2 + CorrTerm2);
logp = sum(crosslogz + CorrTerm)./opt.fraction + logZappx + (LogPriorRestLL + LogPriorRestAux2);
logphist(teller) = logp;
% don't trust the calculation anyway, in particular for fractional updates...
fprintf('%d: %g (stepsize: %g)\n',teller,logp,stepsize);
% check whether marginal loglikelihood is going up and down, if so, lower stepsize
change = logp-logpold;
if change*oldchange < 0, % possibly cycling
stepsize = stepsize/2;
end
oldchange = change;
end
end
if teller == opt.niter
EP_ERR = 2;
warning('Maximum number of iterations exceeded!\n');
end
logphist = logphist(1:teller);
comptime = toc;
fprintf('EP finished in %s seconds with EP_ERR=%d \n',num2str(comptime),EP_ERR);
%%% END MAIN
%%%%%%%%%
%
% compute the cavity approximations that result when subtracting a fraction of the term approximations
function [myGauss,ok] = project_all(Gauss,terms,fraction)
if nargin < 3,
fraction = 1;
end
% take out and project in moment form
% (2) cross terms between regression parameters and auxiliary parameters
[myGauss.diagC,myGauss.m] = ...
rank_one_update(Gauss.diagC,Gauss.m,-fraction*terms.diagK,-fraction*terms.h);
myGauss.auxC = rank_one_update(Gauss.auxC,[],-fraction*terms.auxK);
% check whether all precision matrices are strictly positive definite
if nargout > 1,
ok = (all(myGauss.diagC > 0) & all(myGauss.auxC > 0));
end
%%%%%%%%%
%
% compute the new term approximation by applying an adf update on all the cavity approximations
function [fullterms,crosslogz] = ...
adfupdate_all(myGauss,terms,xhermite,whermite,xlaguerre,wlaguerre,fraction,temperature)
if nargin < 8,
temperature = 1;
end
if nargin < 7,
fraction = 1;
end
%% (2) cross terms between regression parameters and auxiliary variables
oldm = myGauss.m;
oldC = myGauss.diagC;
oldlambda = myGauss.auxC;
nfeatures = length(oldm);
nlaguerre = length(wlaguerre);
% this part heavily relies on the accompanying note
% basic idea:
% - the cavity approximation on U is an exponential distribution
% - we have analytical formulas for the moments of x conditioned upon U
% - marginal moments can then be computed through numerical integration with Gauss-Laguerre
% translate and scale the sample points to get the correct mean
U = 2*oldlambda*xlaguerre'; % nfeatures x nlaguerre
mm = repmat(oldm,1,nlaguerre);
CC = repmat(oldC,1,nlaguerre);
% compute the partition function (integral over x) given U and turn this into weights required for computing the marginal moments
g = (1-fraction)*log(U)/2 - fraction*mm.^2./(U + fraction*CC)/2 - log(U+ fraction*CC)/2 - (1+2*fraction)*log(2*pi)/2;
g = g + log(repmat(wlaguerre',nfeatures,1));
maxg = max(g,[],2);
g = g-repmat(maxg,1,nlaguerre);
expg = exp(g);
denominator = sum(expg,2);
neww = expg./repmat(denominator,1,nlaguerre);
% compute the marginal moments through numerical integration
ExgU = mm.*U./(U + fraction*CC);
Ex = sum(ExgU.*neww,2);
ExxgU = ExgU.^2 + CC.*U./(U+fraction*CC);
Exx = sum(ExxgU.*neww,2);
EU = sum(U.*neww,2);
newm = Ex;
newC = Exx-Ex.^2;
newlambda = EU/2;
% derive the term approximation from the change in mean and variance
[fullterms.diagK,fullterms.h,logzextra1] = ...
compute_termproxy(newC,newm,oldC,oldm,fraction);
% same for the auxiliary variables, where we note that the mean will always be zero
[fullterms.auxK,dummy,logzextra2] = ...
compute_termproxy(newlambda,zeros(nfeatures,1),oldlambda,zeros(nfeatures,1),fraction);
%crosslogz = maxg + log(denominator) + logzextra1 + (logzextra2 + logzextra2);
crosslogz = maxg + log(denominator);
%%%%%%%%%%
%
% compute the moments corresponding to the canonical parameters
function [Gauss,logp] = canonical_to_moments(Gauss)
[nsamples,nfeatures] = size(Gauss.A);
%% (1) regression parameters
if nsamples > nfeatures, % in the non-degenerate case, this direct route is more stable and faster
scaledA = Gauss.A.*(repmat(Gauss.hatK,1,nfeatures));
K = Gauss.A'*scaledA + diag(Gauss.diagK);
[C,logdet1] = invert_chol(K);
Gauss.m = C*Gauss.h;
Gauss.diagC = diag(C);
else
% this part heavily relies on the appendix of the accompanying note
% basic idea:
% - the precision matrix K is of the form A' hatK A + diagK, where both hatK and diagK are diagonal matrices
% - apply Woodbury's formula to replace inverting an (nfeat x nfeat) matrix by an (nsample x nsample) alternative
% - projections of the covariance matrix and the mean onto the feature matrix then follow immediately
scaledA = Gauss.A./(repmat(Gauss.diagK',nsamples,1));
W = Gauss.A*scaledA';
W = (W + W')/2; % make symmetric
[Q,logdet1] = invert_chol(diag(1./Gauss.hatK) + W);
logdet1 = logdet1 + sum(log(Gauss.diagK)) + sum(log(Gauss.hatK));
Gauss.diagC = 1./Gauss.diagK;
for i=1:nfeatures,
Gauss.diagC(i) = Gauss.diagC(i) - scaledA(:,i)'*Q*scaledA(:,i);
end
Gauss.m = Gauss.h./Gauss.diagK - scaledA'*(Q*(scaledA*Gauss.h));
end
Gauss.hatn = Gauss.A*Gauss.m;
qterm = sum(Gauss.m .* Gauss.diagK .* Gauss.m); % = m' * diagK * m
qterm = qterm + sum(Gauss.hatn .* Gauss.hatK .* Gauss.hatn); % = m'*A'*K_hat*A*m
logp1 = 0.5*(qterm - logdet1);
%% (2) auxiliary variables; i.e., wrt scale mixture representation of
% Laplace prior
% this is (by far) the most expensive step when nsamples << nfeatures
% and the precision matrix of the auxiliary variables is non-diagonal
[auxC,logdet2] = invert_chol(Gauss.auxK); % only need diagonal terms
Gauss.auxC = full(diag(auxC)); % turn into full vector
logp2 = 0.5*( - logdet2);
logp = logp1 + 2*logp2;
%%%%%%%%%%
%
% take out the old term proxies and add the new termproxies and check whether the resulting Gaussian is still normalizable
function [newGauss,newterms,ok] = try_update(Gauss,fullterms,terms,stepsize)
if nargin < 4,
stepsize = 1;
end
% take out the old term proxies
newGauss = update_Gauss(Gauss,terms,-1);
% compute the new term proxies as a weighted combi of the old ones and the "full" (stepsize 1) term proxies
newterms = combine_terms(fullterms,terms,stepsize);
% add the new term proxies
newGauss = update_Gauss(newGauss,newterms,1);
[L,check] = chol(newGauss.auxK,'lower'); % check whether full covariance matrix is ok
% note that this is bit inefficient, since we redo the Cholesky later when everything is fine
ok = (check == 0 & all(newGauss.hatK > 0) & all(newGauss.diagK > 0)); % perhaps a bit too strong???
%%%%%%%%%%%%
%
% compute the moment form of the current Gauss and all cavity approximations and check whether they are fine
function [Gauss,myGauss,logdet,ok] = try_project(Gauss,terms,fraction)
if nargin < 3,
fraction = 1;
end
[Gauss,logdet] = canonical_to_moments(Gauss);
[myGauss,ok] = project_all(Gauss,terms,fraction);
%%%%%%%%%%
%
% if we use a temperature < 1, to get closer to the MAP solution, we have to change the prior and initial term proxies accordingly
function [Gauss,terms] = correct_for_temperature(Gauss,terms,temperature)
% note: choose temperature small to implement MAP-like behavior
Gauss.hatK = Gauss.hatK/temperature;
Gauss.h = Gauss.h/temperature;
Gauss.auxK = Gauss.auxK/temperature;
Gauss.diagK = Gauss.diagK/temperature;
% terms.hatK = terms.hatK/temperature;
% terms.hath = terms.hath/temperature;
terms.diagK = terms.diagK/temperature;
terms.auxK = terms.auxK/temperature;
terms.h = terms.h/temperature;
%%%%%%%%%%
%
% invert a positive definite matrix using Cholesky factorization
function [invA,logdet] = invert_chol(A)
[L,CHOL_ERR,S] = chol(sparse(A),'lower'); % now A = S*(L*L')*S' and (L*L') = S'*A*S
if CHOL_ERR
error('Matrix not p.d.!');
end
invA = fastinvc(L);
invA = S*invA*S';
if nargout > 1,
logdet = 2*sum(log(full(diag(L))));
end
%%%%%%%%%%
%
% compute the term proxy when [oldC,oldm] changes to [newC,newm]
function [K,h,logz] = compute_termproxy(newC,newm,oldC,oldm,fraction)
if nargin < 5,
fraction = 1;
end
K = (1./newC - 1./oldC)/fraction;
h = (newm./newC - oldm./oldC)/fraction;
logz = - log(newC./oldC)/2 + oldm.^2./oldC/2 - newm.^2./newC/2;
%%%%%%%%%%
%
% Sherman-Morrison formula to compute the change from [oldC,oldm] to [newC,newm] when we add [K,h] to the corresponding canonical parameters
function [newC,newm] = rank_one_update(oldC,oldm,K,h)
dummy = K.*oldC;
oneminusdelta = 1./(1+dummy);
newC = oneminusdelta.*oldC;
if nargout > 1,
newm = oneminusdelta.*(oldm + h.*oldC);
end
%%%%%%%%%%%
%
% general procedure for a weighted combi of the fields of two structures
function terms = combine_terms(terms1,terms2,stepsize)
names1 = fieldnames(terms1);
names2 = fieldnames(terms2);
names = intersect(names1,names2);
terms = struct;
for i=1:length(names)
terms.(names{i}) = stepsize*terms1.(names{i}) + (1-stepsize)*terms2.(names{i});
end
%%%%%%%%%%%
%
% updates the Gaussian representation with new term proxies
function Gauss = update_Gauss(Gauss,terms,const)
if nargin < 3,
const = 1;
end
Gauss.h = Gauss.h + const*terms.h;
Gauss.diagK = Gauss.diagK + const*terms.diagK;
% get diagonal elements
diagidx = 1:(size(Gauss.auxK,1)+1):numel(Gauss.auxK);
Gauss.auxK(diagidx) = Gauss.auxK(diagidx) + const*terms.auxK';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.