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
icassoEst.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/icasso/icassoEst.m
8,817
utf_8
adb9102f63b02f7a42b3da5bdcf803ae
function sR=icassoEst(mode,X,M,varargin) %function sR=icassoEst(mode,X,M,['FastICAparamName1',value1,'FastICAparamName2',value2,...]) % %PURPOSE % %To compute randomized ICA estimates M times from data X. Output of %this function (sR) is called 'Icasso result structure' (see %icassoStruct). sR keeps the on all the methods, parameters, and %results in the Icasso procedure. % %EXAMPLES OF BASIC USAGE % % sR=icassoEst('randinit', X, 30); % %estimates ICA for 30 times on data matrix X using Icasso %default parameters for FastICA: symmetrical approach, kurtosis as %contrast function. In maximum 100 iterations are used for %estimating ICA in each round. Randomizes only initial conditions. % % sR=icassoEst('both', X, 30, 'g', 'tanh', 'approach', 'defl'); % %estimates ICA for 15 times on data matrix X using 'tanh' as the %contrast function and the deflatory approach in FastICA. Applies %both bootstrapping the data and randomizing initial conditions. % %INPUT % % mode (string) 'randinit' | 'bootstrap | 'both' % X (dxN matrix) data where d=dimension, N=number of vectors % M (scalar) number of randomizations (estimation cycles) % %Optional input arguments are given as argument identifier - value %pairs: 'identifier1', value1, 'identifier2', value2,... %(case insensitive) % %FastICA parameters apply here (see function fastica) %Default: 'approach', 'symm', 'g', 'pow3', 'maxNumIterations', 100 % %OUTPUTS % % sR (struct) Icasso result data structure % %DETAILS % %Meaning of different choices for input arg. 'mode' % 'randinit': different random initial condition each time. % 'bootstrap': the same initial cond. each time, but data is % bootstrapped. The initial condition can be explicitly % specified using FastICA parameter 'initGuess'. % 'both': use both data bootstrapping and randomization of % initial condition. % %FASTICA PARAMETERS See function 'fastica' in FastICA toolbox for %more information. Note that the following FastICA parameters %cannot be used: % % In all modes ('randinit','bootstrap','both'): % using 'interactivePCA','sampleSize', 'displayMode', 'displayInterval', % and 'only' are not allowed for obvious reasons. In addition, % in modes 'randinit' and 'both': % using 'initGuess' is not allowed since initial guess is % randomized, and % in modes 'bootstrap' and 'both': % using 'whiteMat', 'dewhiteMat', and 'whiteSig' are not allowed % since they need to be computed for each bootstrap sample % individually. % %ESTIMATE INDEXING CONVENTION: when function icassoEst is run %each estimate gets a unique, integer label in order of %appearance. The same order and indexing is used throughout the %Icasso software. In many functions, one can pick a subset of %estimates sR by giving vector whose elements refers to this unique %label. % %SEE ALSO % icasso % fastica % icassoStruct % icassoExp % icassoGet % icassoShow % icassoResult % %When icassoEst is accomplished, use icassoExp to obtain clustering %results and to store them in sR After this, the results can be %examined visually using icassoShow. Results and other information %an be finally retrieved also by functions icassoResult and icassoGet. %COPYRIGHT NOTICE %This function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %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 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. % ver 1.1 johan 210704 % Set the Icasso struct sR=icassoStruct(X); % Check compulsatory input arguments if nargin<3, error('At least three input args. required'); end %% Check mode. mode=lower(mode); switch mode case {'randinit','bootstrap','both'} ; otherwise error(['Randomization mode must be ''randinit'', ''bootstrap'' or' ... ' ''both''.']); end sR.mode=mode; %% Set some values num_of_args=length(varargin); whitening='not done'; %% Default values for some FastICA options fasticaoptions={'g','pow3','approach','symm',... 'maxNumIterations',100}; %% flag: initial conditions given (default: not given) isInitGuess=0; %% flag: elements for whitening given (default: not given) isWhitesig=0; isWhitemat=0; isDewhitemat=0; %% Check varargin & set defaults fasticaoptions=processvarargin(varargin,fasticaoptions); num_of_args=length(fasticaoptions); %% Check fasticaoptions: i=1; while i<num_of_args, switch fasticaoptions{i} case {'approach','firstEig','lastEig','numOfIC','finetune','mu','g','a1','a2',... 'stabilization','epsilon','maxNumIterations','maxFinetune','verbose',... 'pcaE','pcaD'} ; % these are ok %% Get explicit whitening if given & update flags; note that the %% arguments are dropped away from fasticaoptions to avoid %% duplicate storage in Icasso result struct & in FastICA input case 'whiteSig' w=fasticaoptions{i+1}; isWhitesig=1; fasticaoptions(i:i+1)=[]; i=i-2; num_of_args=num_of_args-2; case 'whiteMat' White=fasticaoptions{i+1}; isWhitemat=1; fasticaoptions(i:i+1)=[]; i=i-2; num_of_args=num_of_args-2; case 'dewhiteMat' deWhite=fasticaoptions{i+1}; isDewhitemat=1; fasticaoptions(i:i+1)=[]; i=i-2; num_of_args=num_of_args-2; case {'sampleSize','displayMode','displayInterval','only','interactivePCA'} error(['You are not allowed to set FastICA option ''' fasticaoptions{i} ''' in Icasso.']); % initGuess depends on mode case 'initGuess' switch mode case {'randinit','both'} error(['FastICA option ''initGuess'' cannot be used in sampling mode ''' ... mode '''.']); case 'bootstrap' isInitGuess=1; otherwise error('Internal error!?'); end otherwise error(['Doesn''t recognize FastICA option ''' fasticaoptions{i} '''.']); end % add counter i=i+2; end %% Whitening: %% Check if some of whitening arguments have been given: if (isWhitesig | isWhitemat | isDewhitemat), %% both/bootstrap use each time different whitening... better to %% give error if (strcmp(mode,'bootstrap') | strcmp(mode,'both')), error(['FastICA options ''whiteSig'',''whiteMat'',''dewhiteMat'' cannot be' ... ' used in modes ''bootstrap'' and ''both''.']); end %% FastICA expects that all of the three arguments are given (see %help fastica): if not, error if isWhitesig & isWhitemat & isDewhitemat, disp('Using user specified whitening.'); else error(['To prewhiten, each of ''whiteSig'',''whiteMat'',''dewhiteMat'' have to' ... ' be given (see help fastica)']); end else % compute whitening for original data [w,White,deWhite]=fastica(X,'only','white',fasticaoptions{:}); end % store whitening for original data: sR.whiteningMatrix=White; sR.dewhiteningMatrix=deWhite; % Icasso uses the same random initial condition for every sample in % 'bootstrap'. It has to be computed if not given!! if strcmp(mode,'bootstrap') & ~isInitGuess, warning(sprintf('\n\n%s\n\n',['Initial guess not given for mode ''bootstrap'': I will' ... ' set a (fixed) random initial condition'])); % Randomize init conditions and add to fastica options: this % keeps it fixed in every estimation round. fasticaoptions{end+1}='initGuess'; fasticaoptions{end+1}=rand(size(White'))-.5; end % store options (except whitening which is % stored separately) sR.fasticaoptions=fasticaoptions; %% Compute N times FastICA k=0; index=[]; for i=1:M, %clc; fprintf('\n\n%s\n\n',['Randomization using FastICA: Round ' num2str(i) '/' ... num2str(M)]); switch mode case 'randinit' % data is fixed; X_=X; case {'bootstrap','both'} % Bootstrap and compute whitening for _bootstrapped_ data X_=bootstrap(X); [w,White,deWhite]=fastica(X_,'only','white',fasticaoptions{:}); otherwise error('Internal error?!'); end % Estimate FastICA set displayMode off [dummy,A_,W_]=fastica(X_,fasticaoptions{:},... 'whiteMat',White,'dewhiteMat',deWhite,'whiteSig',w,... 'sampleSize',1,'displayMode','off'); % Store results if any n=size(A_,2); if n>0, k=k+1; sR.index(end+1:end+n,:)=[repmat(k,n,1), [1:n]']; sR.A{k}=A_; sR.W{k}=W_; end end function X=bootstrap(X) N=size(X,2); index=round(rand(N,1)*N+.5); X=X(:,index);
github
lcnhappe/happe-master
icassoStruct.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/icasso/icassoStruct.m
8,190
utf_8
d80e7670415d1867f114b16bebb620f6
function sR=icassoStruct(X) %function sR=icassoStruct([X]) % %PURPOSE % %To initiate an Icasso result data structure which is meant for %storing and keeping organized all data, parameters and results %when performing the Icasso procedure. % %EXAMPLE OF BASIC USAGE % % S=icassoStruct(X); % %creates an Icasso result structure in workspace variable S. Its %fields are initially empty except field .signal that contains %matrix X. % %INPUT % %[An argument in brackets is optional. If it isn't given or it's % an empty matrix/string, the function will use a default value.] % %[X] (dxN matrix) the original data (signals) consisting of N % d-dimensional vectors. Icasso centers the data (removes the % sample mean from it) and stores it in field .signal. % If the input argument is not given, or it is empty, % the field is left empty. % %OUTPUT % % sR (struct) Icasso result structure that contains fields % % .mode (string) % .signal (matrix) % .index (matrix) % .fasticaoptions (cell array) % .A (cell array) % .W (cell array) % .whiteningMatrix (matrix) % .dewhiteningMatrix (matrix) % .cluster (struct) % .projection (struct) % %DETAILS % %The following table presents the fields of Icasso result %structure. Icasso is a sequential procedure that is split into %several phases (functions). The table shows the order in which %the fields are computed, the function that is used to change the %parameters/results in the field, and lastly the phases that %the result depends on. % %P=parameter that may be a explicit user input or a default parameter %set by Icasso % %Phase Field Function depends on field(s) % %(1) .mode icassoEst P %(1) .signal icassoEst P %(1) .index icassoEst (ICA results) %(1) .fasticaoptions icassoEst P %(1) .A icassoEst (ICA results) %(1a) .W icassoEst (ICA results) %(1) .whiteningMatrix icassoEst (ICA results) %(1b) .dewhiteningMatrix icassoEst (ICA results) % %(2a) .cluster.simfcn icassoCluster P %(2b) .cluster.similarity icassoCluster 1a,1b,2a %(2c) .cluster.s2d icassoCluster P %(2d) .cluster.strategy icassoCluster P %(2e) .cluster.partition icassoCluster 2b-d %(2f) .cluster.dendrogram icassoCluster 2b-d %(2g) .cluster.index.R icassoCluster 2b,2c,2e % %(3a) .projection.method icassoProjection P %(3b) .projection.parameters icassoProjection P %(3c) .projection.coordinates icassoProjection 2b,3a-b % %icasso performs the whole process with default parameters %icassoEst performs phase 1 %icassoExp performs phases 2-3 with default parameters. % %(1) Data, ICA parameters, and estimation results % % .mode (string) % type of randomization ('bootstrap'|'randinit'|'both') % % .signal (dxN matrix) % the original data (signal) X (centered) where N is % the number of samples and d the dimension % % .index (Mx2 matrix) % the left column is the number of the estimation cycle, the % right one is the number of the estimate on that cycle. % See also function: icassoGet % %The following fields contain parameters and results of the ICA %estimation using FastICA toolbox. More information can be found, %e.g., from of function fastica in FastICA toolbox. % % .fasticaoptions (cell array) % contains the options that FastICA uses in estimation. % % .A (cell array of matrices) % contains mixing matrices from each estimation cycle % % .W (cell array of matrices) % contains demixing matrices from each estimation cycle % % .whiteningMatrix (matrix) % whitening matrix for original data (sR.signal) % % .dewhiteningMatrix (matrix) % dewhitening matrix for original data (sR.signal). % %(2) Mutual similarities and clustering % %Parameters and results of % -computing similarities S between the estimates, and % -clustering the estimates %are stored in field .cluster which has the following subfields: % % .cluster.simfcn (string) % a string option for function icassoCluster % (icassoSimilarity); it tells how the mutual similarities % between estimates are computed. % % .cluster.similarity (MxM matrix) % mutual similarities between estimates. % % .cluster.s2d (string) % before clustering and computing the clustering validity index % the similarity matrix S stored in .cluster.similarity is % transformed into a dissimilarity matrix. This string is the % name of the subfunction that makes the transformation: there % is a function call % D=feval(sR.cluster.s2d,sR.cluster.similarity); % inside icassoCluster. Note that the dissimilarity matrix % is not stored in the Icasso result data struct. % % .cluster.strategy (string) % strategy that was used for hierarchical clustering which is % done on dissimilarities D % .cluster.partition (MxM matrix) % stores the partitions resulting clustering. Each row % partition(i,:), represents a division of M objects into K(i) % clusters (classes). On each row, clusters must be labeled % with integers 1,2,...,K(i), where K(i) is the number of % clusters that may be different on each row Example: % partition=[[1 2 3 4];[1 1 1 1];[1 1 2 2]] gives three % different partitions where partition(1,:) means every object % being in its own clusters; partition(2,:) means all objects % being in a single cluster, and in partition(3,:) objects 1&2 % belong to cluster 1 and 3&4 to cluster 2. % % .cluster.dendrogram.Z and .cluster.dendrogram.order % stores information needed for drawing dendrogram and % similarity matrix visualizations. More details in function % som_linkage % %The following subfields of .cluster contain heuristic validity %scores for the partitions in .cluster.partition. If the score is %NaN it means that the validity has not been (or can't be) %computed. % % .cluster.index.R (Mx1 vector) % computed by subfunction rindex % %(3) Projection for visualization % %Parameters for performing the visualization projection are results %of the projection can be found in field .projection. % % .projection has the following subfields: % % .projection.method (string) % projection method used in icassoProjection % % .projection.parameters (cell array) % contains parameters used in icassoProjection % % .coordinates (Mx2 matrix) % contains the coordinates of the projected estimates % %COPYRIGHT NOTICE %This function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %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 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. % ver 1.2 johan 100105 if nargin<1|isempty(X), X=[]; else X=remmean(X); end sR.mode=[]; sR.signal=X; sR.index=[]; sR.fasticaoptions=[]; sR.A=[]; sR.W=[]; sR.whiteningMatrix=[]; sR.dewhiteningMatrix=[]; sR.cluster=initClusterStruct; sR.projection=initProjectionStruct; function cluster=initClusterStruct cluster.simfcn=[]; cluster.similarity=[]; cluster.s2d=[]; cluster.strategy=[]; cluster.partition=[]; cluster.dendrogram.Z=[]; cluster.dendrogram.order=[]; cluster.index.R=[]; function projection=initProjectionStruct projection.method=[]; projection.parameters=[]; projection.coordinates=[];
github
lcnhappe/happe-master
som_dendrogram.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/icasso/som_dendrogram.m
9,039
utf_8
43f32770e95d19d4a12855bd8bfb91f3
function [h,Coord,Color,height] = som_dendrogram(Z,varargin) %SOM_DENDROGRAM Visualize a dendrogram. % % [h,Coord,Color,height] = som_dendrogram(Z, [[argID,] value, ...]) % % Z = som_linkage(sM); % som_dendrogram(Z); % som_dendrogram(Z,sM); % som_dendrogram(Z,'coord',co); % % Input and output arguments ([]'s are optional): % h (vector) handle to the arc lines % Z (matrix) size n-1 x 1, the hierarchical cluster matrix % returned by functions like LINKAGE and SOM_LINKAGE % n is the number of original data samples. % [argID, (string) See below. The values which are unambiguous can % value] (varies) be given without the preceeding argID. % Coord (matrix) size 2*n-1 x {1,2}, the coordinates of the % original data samples and cluster nodes used % in the visualization % Color (matrix) size 2*n-1 x 3, the colors of ... % height (vector) size 2*n-1 x 1, the heights of ... % % Here are the valid argument IDs and corresponding values. The values % which are unambiguous (marked with '*') can be given without the % preceeding argID. % 'data' *(struct) map or data struct: many other optional % arguments require this % (matrix) data matrix % 'coord' (matrix) size n x 1 or n x 2, the coordinates of % the original data samples either in 1D or 2D % (matrix) size 2*n-1 x {1,2}, the coordinates of both % original data samples and each cluster % *(string) 'SOM', 'pca#', 'sammon#', or 'cca#': the coordinates % are calculated using the given data and the % required projection algorithm. The '#' at the % end of projection algorithms refers to the % desired output dimension and can be either 1 or 2 % (2 by default). In case of 'SOM', the unit % coordinates (given by SOM_VIS_COORDS) are used. % 'color' (matrix) size n x 3, the color of the original data samples % (matrix) size 2*n-1 x 3, the colors of both original % data samples and each cluster % (string) color specification, e.g. 'r.', used for each node % 'height' (vector) size n-1 x 1, the heights used for each cluster % (vector) size 2*n-1 x 1, the heights used for both original % data samples and each cluster % *(string) 'order', the order of combination determines height % 'depth', the depth at which the combination % happens determines height % 'linecolor' (string) color specification for the arc color, 'k' by default % (vector) size 1 x 3 % % See also SOM_LINKAGE, DENDROGRAM. % Copyright (c) 2000 by Juha Vesanto % Contributed to SOM Toolbox on June 16th, 2000 by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 160600 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% read the arguments % Z nd = size(Z,1)+1; nc = size(Z,1); % varargin Coordtype = 'natural'; Coord = []; codim = 1; Colortype = 'none'; Color = []; height = [zeros(nd,1); Z(:,3)]; M = []; linecol = 'k'; i=1; while i<=length(varargin), argok = 1; if ischar(varargin{i}), switch varargin{i}, case 'data', i = i + 1; M = varargin{i}; case 'coord', i=i+1; if isnumeric(varargin{i}), Coord = varargin{i}; Coordtype = 'given'; else if strcmp(varargin{i},'SOM'), Coordtype = 'SOM'; else Coordtype = 'projection'; Coord = varargin{i}; end end case 'color', i=i+1; if isempty(varargin{i}), Colortype = 'none'; elseif ischar(varargin{i}), Colortype = 'colorspec'; Color = varargin{i}; else Colortype = 'given'; Color = varargin{i}; end case 'height', i=i+1; height = varargin{i}; case 'linecolor', i=i+1; linecol = varargin{i}; case 'SOM', Coordtype = 'SOM'; case {'pca','pca1','pca2','sammon','sammon1','sammon2','cca','cca1','cca2'}, Coordtype = 'projection'; Coord = varargin{i}; case {'order','depth'}, height = varargin{i}; end elseif isstruct(varargin{i}), M = varargin{i}; else argok = 0; end if ~argok, disp(['(som_dendrogram) Ignoring invalid argument #' num2str(i+1)]); end i = i+1; end switch Coordtype, case 'SOM', if isempty(M) | ~any(strcmp(M.type,{'som_map','som_topol'})) , error('Cannot determine SOM coordinates without a SOM.'); end if strcmp(M.type,'som_map'), M = M.topol; end case 'projection', if isempty(M), error('Cannot do projection without the data.'); end if isstruct(M), if strcmp(M.type,'som_data'), M = M.data; elseif strcmp(M.type,'som_map'), M = M.codebook; end end if size(M,1) ~= nd, error('Given data must be equal in length to the number of original data samples.') end case 'given', if size(Coord,1) ~= nd & size(Coord,1) ~= nd+nc, error('Size of given coordinate matrix does not match the cluster hierarchy.'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% initialization % Coordinates switch Coordtype, case 'natural', o = leavesorder(Z)'; [dummy,Coord] = sort(o); codim = 1; case 'SOM', Coord = som_vis_coords(M.lattice,M.msize); codim = 2; case 'projection', switch Coord, case {'pca','pca2'}, Coord = pcaproj(M,2); codim = 2; case 'pca1', Coord = pcaproj(M,1); codim = 1; case {'cca','cca2'}, Coord = cca(M,2,20); codim = 2; case 'cca1', Coord = cca(M,1,20); codim = 1; case {'sammon','sammon2'}, Coord = sammon(M,2,50); codim = 2; case 'sammon1', Coord = sammon(M,1,50); codim = 1; end case 'given', codim = min(size(Coord,2),2); % nill end if size(Coord,1) == nd, Coord = [Coord; zeros(nc,size(Coord,2))]; for i=(nd+1):(nd+nc), leaves = leafnodes(Z,i,nd); if any(leaves), Coord(i,:) = mean(Coord(leaves,:),1); else Coord(i,:) = Inf; end end end % Colors switch Colortype, case 'colorspec', % nill case 'none', Color = ''; case 'given', if size(Color,1) == nd, Color = [Color; zeros(nc,3)]; for i=(nd+1):(nd+nc), leaves = leafnodes(Z,i,nd); if any(leaves), Color(i,:) = mean(Color(leaves,:),1); else Color(i,:) = 0.8; end end end end % height if ischar(height), switch height, case 'order', height = [zeros(nd,1); [1:nc]']; case 'depth', height = nodedepth(Z); height = max(height) - height; end else if length(height)==nc, height = [zeros(nd,1); height]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% draw % the arcs lfrom = []; lto = []; for i=1:nd+nc, if i<=nd, ch = []; elseif ~isfinite(Z(i-nd,3)), ch = []; else ch = Z(i-nd,1:2)'; end if any(ch), lfrom = [lfrom; i*ones(length(ch),1)]; lto = [lto; ch]; end end % the coordinates of the arcs if codim == 1, Lx = [Coord(lfrom), Coord(lto), Coord(lto)]; Ly = [height(lfrom), height(lfrom), height(lto)]; Lz = []; else Lx = [Coord(lfrom,1), Coord(lto,1), Coord(lto,1)]; Ly = [Coord(lfrom,2), Coord(lto,2), Coord(lto,2)]; Lz = [height(lfrom), height(lfrom), height(lto)]; end washold = ishold; if ~washold, cla; end % plot the lines if isempty(Lz), h = line(Lx',Ly','color',linecol); else h = line(Lx',Ly',Lz','color',linecol); if ~washold, view(3); end rotate3d on end % plot the nodes hold on switch Colortype, case 'none', % nill case 'colorspec', if codim == 1, plot(Coord,height,Color); else plot3(Coord(:,1), Coord(:,2), height, Color); end case 'given', som_grid('rect',[nd+nc 1],'line','none','Coord',[Coord, height],... 'Markersize',10,'Markercolor',Color); end if ~washold, hold off, end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions function depth = nodedepth(Z) nd = size(Z,1)+1; nc = size(Z,1); depth = zeros(nd+nc,1); ch = nc+nd-1; while any(ch), c = ch(1); ch = ch(2:end); if c>nd & isfinite(Z(c-nd,3)), chc = Z(c-nd,1:2); depth(chc) = depth(c) + 1; ch = [ch, chc]; end end return; function inds = leafnodes(Z,i,nd) inds = []; ch = i; while any(ch), c = ch(1); ch = ch(2:end); if c>nd & isfinite(Z(c-nd,3)), ch = [ch, Z(c-nd,1:2)]; end if c<=nd, inds(end+1) = c; end end return; function order = leavesorder(Z) nd = size(Z,1)+1; order = 2*nd-1; nonleaves = 1; while any(nonleaves), j = nonleaves(1); ch = Z(order(j)-nd,1:2); if j==1, oleft = []; else oleft = order(1:(j-1)); end if j==length(order), oright = []; else oright = order((j+1):length(order)); end order = [oleft, ch, oright]; nonleaves = find(order>nd); end return;
github
lcnhappe/happe-master
corrw.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/icasso/corrw.m
1,654
utf_8
b24c05ddd84adfca75a0870878a9c0f7
function R=corrw(W,D) %function R=corrw(W,D) % %PURPOSE % %To compute mutual linear correlation coefficients between M %independent component estimates using the demixing matrix W and %the dewhitening matrix D of the original data. % % R=W*D*D'*W'; % %INPUT % % W (field W in Icasso struct: demixing matrices) % D (field dewhiteningMatrix in Icasso struct) the dewhitening % matrix of the data % %OUTPUT % % R (MxM matrix) of correlation coefficients % %SEE ALSO % icassoSimilarity % The normalization (rownorm) is a security measure: in some % versions the FastICA has not normalized W properly if iteration % stops prematurely %COPYRIGHT NOTICE %This function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %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 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. % ver 1.2 100105 B=rownorm(W*D); R=B*B'; function X=rownorm(X) % normalize rows to unit length. s=abs(sqrt(sum(X.^2,2))); if any(s==0), warning('Contains zero vectors: can''t normalize them!'); end X=X./repmat(s,1,size(X,2));
github
lcnhappe/happe-master
reducesim.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/icasso/reducesim.m
3,056
utf_8
d2d2a37c6d316586dbfc3da7760af840
function S=reducesim(S,minLimit,partition,scatter,scatterLimit) %function S=reducesim(S,minLimit) % or %function S=reducesim(S,minLimit,partition,scatter,scatterLimit) % %PURPOSE % %To reduce the number of lines that are drawn when the similarity %matrix is visualized. That is, to set similarities below certain %threshold to zero, and optionally, also within-cluster %similarities above certain threshold to zero. % %INPUT % % Two input arguments: % % S (matrix) NxN similarity matrix % minLimit (scalar) all values below this threshold in S are set to % zero % % Five input arguments: % % S (matrix) NxN similarity matrix % minLimit (scalar) all values below this threshold in S are set to % zero % partition (vector) Nx1 partition vector into K clusters (see % explanation for 'partition vector' in function hcluster) % scatter (vector) Kx1 vector that contains within-scatter for % each cluster i=1,2,...,K implied by vector partition % scatterLimit (scalar) threshold for within-cluster scatter. % % %OUTPUT % % S (matrix) NxN similarity matrix with some entries cut to zero. % %SEE ALSO % clusterstat % icassoShow %COPYRIGHT NOTICE %This function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %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 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. % ver 1.2 100105 johan if nargin==2|nargin==5, ; else error('You must specify 2 or 5 input arguments!'); end %%% Maximum number of lines MAX_NLINES=5000; %%% Set within-cluster similarities above certain threshold to zero if nargin==5, Ncluster=max(partition); for i=1:Ncluster, index=partition==i; if scatter(i)>scatterLimit; S(index,index)=0; end end end %%% We assume symmetric matrix and don't care about %self-similarities upper diagonal is enough S=tril(S); S(eye(size(S))==1)=0; %% Number of lines to draw Nlines=sum(sum(S>minLimit)); %%% If too many lines, try to set better minLimit if Nlines>MAX_NLINES, warning('Creates overwhelming number of lines'); warning('Tries to change the limit...'); minLimit=reduce(S,MAX_NLINES); warning(['New limit =' num2str(minLimit)]); end %%% Set values below minLimit to zero S(S<minLimit)=0; function climit=reduce(c,N) c(c==0)=[]; c=c(:); if N==0, warning('N=0 not allowed; setting N=1'); end if N>length(c), N=length(c); end climit=sort(-c); climit=-climit; climit=climit(N);
github
lcnhappe/happe-master
clusterhull.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/icasso/clusterhull.m
5,149
utf_8
49c19208dafd1008be107e012aa6f36e
function [h_marker,txtcoord]=clusterhull(mode,coord,partition,color) %function [h_marker,txtcoord]=clusterhull(mode,coord,partition,[color]) % %PURPOSE % %To draw a cluster visualization where the objects (represented by %points) belonging to the same cluster are presented by "cluster hulls", %polygons where the edge of the polygon is the convex hull of the %points that belong to the same cluster. % %INPUT % %%[An argument in brackets is optional. If it isn't given or it's % an empty matrix/string, the function will use a default value.] % %mode (string) 'edge' | 'fill' %coord (Mx2 matrix) coordinates of points (objects) %partition (Mx1 vector) partition vector of objects (see % explanation for 'partition vector' in function hcluster) %[color] (Kx3 matrix) each line is a 1x3 RGB vector that defines % color for each cluster. Default color is red for all % clusters color(i,:)=[NaN NaN NaN] means that cluster(i) % is not drawn at all. % %OUTPUT % % h_marker (vector) graphic handles to all clusters. h_marker(i)=NaN if % color(i,:)=[NaN NaN NaN] % txtcoord (Kx2 matrix) suggested coordinates for text labels. % txtcoord(i,:)=[NaN NaN] if cluster i is not drawn. % Meaningful only in mode 'edge', returns always a % matrix of NaNs in mode 'fill'. % %DETAILS % %In mode 'edge' each cluster is represented by a convex hull if %there are more than two points in the cluster. A two point cluster is %represented by a line segment and a one point cluster by a small %cross. The face of the convex hull is invisible. % %In mode 'fill' the cluster hulls are filled with the specified %color. Clusters having less than three members are ignored. % %NOTE The function always adds to a plot (turns 'hold on' temporarily). % %USED IN % icassoGraph %COPYRIGHT NOTICE %This function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %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 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. % ver 1.2 100105 johan holdStat=ishold; hold on; Ncluster=max(partition); if nargin<4|isempty(color), color=repmat([1 0 0],Ncluster,1); end switch mode case 'edge' [h_marker,txtcoord]=clusteredge(coord,partition,color); case 'fill' h_marker=clusterfill(coord,partition,color); txtcoord=repmat(NaN,Ncluster,1); otherwise error('Unknown operation mode.'); end % Some graphic settings set(gca,'xtick',[],'ytick',[]); axis equal; if ~holdStat, hold off; end function [h_marker,txtcoord]=clusteredge(coord,partition,color); %% Number of clusters Ncluster=max(partition); %% Line width and +-sign size LINEWIDTH=2; MARKERSIZE=6; for cluster=1:Ncluster, hullCoord=[]; index=partition==cluster; Npoints=sum(index); coord_=coord(index,:); isVisible=all(isfinite(color(cluster,:))); if isVisible, if Npoints>=3, I=convhull(coord_(:,1),coord_(:,2)); hullCoord=enlargehull([coord_(I,1) coord_(I,2)]); h_marker(cluster,1)=patch(hullCoord(:,1),hullCoord(:,2),0); set(h_marker(cluster,1),'edgecolor',color(cluster,:),'facecolor','none', ... 'linewidth',LINEWIDTH); elseif size(coord_,1)==2, hullCoord(:,1)=[coord_(1,1) coord_(2,1)]'; hullCoord(:,2)=[coord_(1,2) coord_(2,2)]'; h_marker(cluster,1)=plot(hullCoord(:,1)',hullCoord(:,2)','-'); set(h_marker(cluster,1),'color',color(cluster,:),'linewidth',LINEWIDTH); else hullCoord(:,1)=coord_(1,1); hullCoord(:,2)=coord_(1,2); h_marker(cluster,1)=plot(coord_(1,1),coord_(1,2),'+'); set(h_marker(cluster),'color',color(cluster,:),'markersize',MARKERSIZE); end txtcoord(cluster,:)=gettextcoord(hullCoord); else txtcoord(cluster,1:2)=NaN; h_marker(cluster,1)=NaN; end end function h_marker=clusterfill(coord,partition,color) Ncluster=max(partition); k=0; for cluster=1:Ncluster, hullCoord=[]; index=cluster==partition; Npoints=sum(index); coord_=coord(index,:); isVisible=all(isfinite(color(cluster,:))); if Npoints>=3 & isVisible, I=convhull(coord_(:,1),coord_(:,2)); hullCoord=enlargehull([coord_(I,1) coord_(I,2)]); h_marker(cluster,1)=patch(hullCoord(:,1),hullCoord(:,2),0); set(h_marker(cluster),'edgecolor','none','facecolor',color(cluster,:)); else h_marker(cluster,1)=NaN; end end function c=gettextcoord(coord) [tmp,i]=min(coord(:,1)); c=coord(i,:); function coord=enlargehull(coord) S=1.1; m=repmat(mean(coord(1:end-1,:),1),size(coord,1),1); coord_=coord-m; coord_=coord_.*S; coord=coord_+m;
github
lcnhappe/happe-master
vis_valuetype.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/icasso/vis_valuetype.m
7,502
utf_8
cb7a373fcda9120d69231b2748371740
function flag=vis_valuetype(value, valid, str); % VIS_VALUETYPE Used for type checks in SOM Toolbox visualization routines % % flag = vis_valuetype(value, valid, str) % % Input and output arguments: % value (varies) variable to be checked % valid (cell array) size 1xN, cells are strings or vectors (see below) % str (string) 'all' or 'any' (default), determines whether % all or just any of the types listed in argument 'valid' % should be true for 'value' % % flag (scalar) 1 or 0 (true or false) % % This is an internal function of SOM Toolbox visualization. It makes % various type checks. For example: % % % Return 1 if X is a numeric scalar otherwise 0: % f=vis_valuetype(X,{'1x1'}); % % % Return 1 if X is a ColorSpec, that is, a 1x3 vector presenting an RGB % % value or any of strings 'red','blue','green','yellow','magenta','cyan', % % 'white' or 'black' or their shortenings 'r','g','b','y','m','c','w','k': % f=vis_valueype(X,{'1x3rgb','colorstyle'}) % % % Return 1 if X is _both_ 10x3 size numeric matrix and has RGB values as rows % f=vis_valuetype(X,{'nx3rgb',[10 3]},'all') % % Strings that may be used in argument valid: % id is true if value is % % [n1 n2 ... nn] any n1 x n2 x ... x nn sized numeric matrix % '1x1' scalar (numeric) % '1x2' 1x2 vector (numeric) % 'nx1' any nx1 numeric vector % 'nx2' nx2 % 'nx3' nx3 % 'nxn' any numeric square matrix % 'nxn[0,1]' numeric square matrix with values in interval [0,1] % 'nxm' any numeric matrix % '1xn' any 1xn numeric vector % '1x3rgb' 1x3 vector v for which all(v>=0 & v<=1), e.g., a RGB code % 'nx3rgb' nx3 numeric matrix that contains n RGB values as rows % 'nx3dimrgb' nx3xdim numeric matrix that contains RGB values % 'nxnx3rgb' nxnx3 numeric matrix of nxn RGB triples % 'none' string 'none' % 'xor' string 'xor' % 'indexed' string 'indexed' % 'colorstyle' strings 'red','blue','green','yellow','magenta','cyan','white' % or 'black', or 'r','g','b','y','m','c','w','k' % 'markerstyle' any of Matlab's marker chars '.','o','x','+','*','s','d','v', % '^','<','>','p'or 'h' % 'linestyle' any or Matlab's line style strings '-',':','--', or '-.' % 'cellcolumn' a nx1 cell array % 'topol_cell' {lattice, msize, shape} % 'topol_cell_no_shape' {lattice, msize} % 'string' any string (1xn array of char) % 'chararray' any MxN char array % Copyright (c) 1999-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta Johan 201099 juuso 280800 if nargin == 2 str='any'; end flag=0; sz=size(value); dims=ndims(value); % isnumeric numeric=isnumeric(value); character=ischar(value); % main loop: go through all types in arg. 'valid' for i=1:length(valid), if isnumeric(valid{i}), % numeric size for double matrix if numeric & length(valid{i}) == dims, flag(i)=all(sz == valid{i}); else flag(i)=0; % not numeric or wrong dimension end else msg=''; % for a error message inside try try switch valid{i} % scalar case '1x1' flag(i)=numeric & dims == 2 & sz(1)==1 & sz(2) ==1; % 1x2 numeric vector case '1x2' flag(i)=numeric & dims == 2 & sz(1)==1 & sz(2) == 2; % 1xn numeric vector case '1xn' flag(i)=numeric & dims == 2 & sz(1) == 1; % any numeric matrix case 'nxm' flag(i)=numeric & dims == 2; % nx3 numeric matrix case 'nx3' flag(i)=numeric & dims == 2 & sz(2) == 3; % nx2 numeric matrix case 'nx2' flag(i)=numeric & dims == 2 & sz(2) == 2; % nx1 numeric vector case 'nx1' flag(i)=numeric & dims == 2 & sz(2) == 1; % nx1xm numric matrix case 'nx1xm' flag(i)=numeric & dims == 3 & sz(2) == 1; % nx3 matrix of RGB triples case 'nx3rgb' flag(i)=numeric & dims == 2 & sz(2) == 3 & in0_1(value); % RGB triple (ColorSpec vector) case '1x3rgb' flag(i) = numeric & dims == 2 & sz(1)==1 & sz(2) == 3 & in0_1(value); % any square matrix case 'nxn' flag(i)=numeric & dims == 2 & sz(1) == sz(2); % nx3xdim array of nxdim RGB triples case 'nx3xdimrgb' flag(i)=numeric & dims == 3 & sz(2) == 3 & in0_1(value); % nxnx3 array of nxn RGB triples case 'nxnx3rgb' flag(i)= numeric & dims == 3 & sz(1) == sz(2) & sz(3) == 3 ... & in0_1(value); % nxn matrix of values between [0,1] case 'nxn[0,1]' flag(i)=numeric & dims == 2 & sz(1) == sz(2) & in0_1(value); % string 'indexed' case 'indexed' flag(i) = ischar(value) & strcmp(value,'indexed'); % string 'none' case 'none' flag(i) = character & strcmp(value,'none'); % string 'xor' case 'xor' flag(i) = character & strcmp(value,'xor'); % any string (1xn char array) case 'string' flag(i) = character & dims == 2 & sz(1)<=1; % any char array case 'chararray' flag(i) = character & dims == 2 & sz(1)>0; % ColorSpec string case 'colorstyle' flag(i)=(character & sz(1) == 1 & sz(2) == 1 & ... any(ismember('ymcrgbwk',value))) | ... (ischar(value) & any(strcmp(value,{'none','yellow','magenta',... 'cyan','red','green','blue','white','black'}))); % any valid Matlab's Marker case 'markerstyle' flag(i)=character & sz(1) == 1 & sz(2) == 1 & ... any(ismember('.ox+*sdv^<>ph',value)); % any valid Matlab's LineStyle case 'linestyle' str=strrep(strrep(strrep(value,'z','1'),'--','z'),'-.','z'); flag(i)=character & any(ismember(str,'z-:')) & sz(1)==1 & (sz(2)==1 | sz(2)==2); % any struct case 'struct' flag(i)=isstruct(value); % nx1 cell array of strings case 'cellcolumn_of_char' flag(i)=iscell(value) & dims == 2 & sz(2)==1; try, char(value); catch, flag(i)=0; end % mxn cell array of strings case '2Dcellarray_of_char' flag(i)=iscell(value) & dims == 2; try, char(cat(2,value{:})); catch, flag(i)=0; end % valid {lattice, msize} case 'topol_cell_no_shape' flag(i)=1; if ~iscell(value) | length(size(value)) ~= 2 | size(value,2)~=2 flag(i)=0; else if vis_valuetype(value{1},{'string'}), switch value{1} case { 'hexa','rect'} ; otherwise flag(i)=0; end end if ~vis_valuetype(value{2},{'1xn'}), flag(i)=0; end end % valid {lattice, msize, shape} case 'topol_cell' flag(i)=1; if ~iscell(value) | length(size(value)) ~= 2 | size(value,2) ~= 3, flag(i)=0; else if vis_valuetype(value{1},{'string'}), switch value{1} case { 'hexa','rect'} ; otherwise flag(i)=0; end end if ~vis_valuetype(value{2},{'1xn'}) flag(i)=0; end if ~vis_valuetype(value{3},{'string'}) flag(i)=0; else switch value{3} case { 'sheet','cyl', 'toroid'} ; otherwise flag(i)=0; end end end otherwise msg='Unknown valuetype!'; end catch % error during type check is due to wrong type of value: % lets set flag(i) to 0 flag(i)=0; end % Unknown indetifier? error(msg); end % set flag according to 3rd parameter (all ~ AND, any ~ OR) if strcmp(str,'all'); flag=all(flag); else flag=any(flag); end end function f=in0_1(value) f=all(value(:) >= 0 & value(:)<=1);
github
lcnhappe/happe-master
icassoGet.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/icasso/icassoGet.m
5,635
utf_8
9a56d24c879fa67d054651240e964543
function out=icassoGet(sR,field,index) %function out=icassoGet(sR,field,[index]) % %PURPOSE % %Auxiliary function for obtaining various information from the %Icasso result data structure. Using icassoGet, you can return %information related to original data, e.g.: data matrix, %(de)whitening matrix, total number of estimates, number of %estimates on each round. You can also return specified estimated %independent components (sources), and rows of demixing matrices %from. (However, it is easier to use function icassoResult to return %the final estimation results from the complete Icasso procedure.) % %EXAMPLES OF BASIC USAGE % % M=icassoGet(sR,'m'); % %returns total number of estimates. % % nic=icassoGet(sR,'numOfIC') % %returns number of estimated IC components on each round in an Nx1 %vector (The number may differ in deflatory estimation mode due to %convergence problems.) % % r=icassoGet(sR,'round',[25 17 126]); % %workspace variable r contains now a 3x2 matrix where the first %column shows the number of estimation cycle. The second column %is the order of appearance of the estimate within the cycle: %e.g. 2 5 : estimate 25 was 5th estimate in cycle 2 % 1 17 : 17 1st 1 % 7 6 : 126 6th 7 % % W=icassoGet(sR,'demixingmatrix',[25 17 126]); % %returns the demixing matrix rows for estimates 25, 17, and 126. % % s=icassoGet(sR,'source'); % %returns _all_ M estimated independent components (sources), i.e., %estimates from all resampling cycles. % %INPUT % %[An argument in brackets is optional. If it isn't given or it's % an empty matrix/string, the function will use a default value.] % % sR (struct) Icasso result data structure (from icassoEst). % field (string) (case insensitive) determines what is returned: % 'data' the original data centered % 'N' the number of estimation cycles % 'M' the total number of estimates available; % equal to sum(icassoGet(sR,'numofic')); % 'numofic' number of ICs extracted on each cycle (Nx1 % vector) % 'odim' original data dimension % 'rdim' reduced data dimension (after PCA) % 'round' output is an Mx2 matrix that identifies from % which estimation round each estimate % originates: % out(i,1) is the estimation round for % estimate i, % out(i,2) is the ordinal number of the % estimate within the round. % 'source' estimated source signals % 'dewhitemat' dewhitening matrix for the original data % 'whitemat' dewhitening matrix for the original data % 'demixingmatrix' demixing matrix rows ('W' works as well) % % [index] (vector of integers) specifies which estimates to return % Applies only for 'demixingmatrix', and 'source' % Default: leaving this argument out corresponds to % selecting all estimates, i.e., giving [1:M] as index % vector. % %OUTPUT % % out (type and meaning vary according to input argument 'field') % %SEE ALSO % icassoResult %COPYRIGHT NOTICE %This function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %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 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. % ver 1.2 100105 M=size(sR.index,1); if nargin<3, index=1:M; end switch lower(field) case 'm' out=size(sR.index,1); case 'n' out=length(sR.A); case 'odim' out=size(sR.whiteningMatrix,2); case 'rdim' out=size(sR.whiteningMatrix,1); case 'numofic' for i=1:length(sR.A), out(i,1)=size(sR.A{i},2); end case {'w','demixingmatrix'} out=getDeMixing(sR,index); case 'data' out=sR.signal; case {'dewhitemat'} out=sR.dewhiteningMatrix; case {'whitemat'} out=sR.whiteningMatrix; case 'source' out=getSource(sR,index); case 'round' out=sR.index(index,:) otherwise error('Unknown operation.'); end %function A=getMixing(sR,index); % %function A=getMixing(sR,index); % % reindex %index2=sR.index(index,:); %N=size(index2,1); A=[]; %for i=1:N, % A(:,i)=sR.A{index2(i,1)}(:,index2(i,2)); %end function W=getDeMixing(sR,index); % %function W=getDeMixing(sR,index); % % reindex index2=sR.index(index,:); N=size(index2,1); W=[]; for i=1:N, W(i,:)=sR.W{index2(i,1)}(index2(i,2),:); end function S=getSource(sR,index) %function S=getSource(sR,index) % X=sR.signal; W=getDeMixing(sR,index); S=W*X; %% Old stuff %function dWh=getDeWhitening(sR,index); % %function dWh=getDeWhitening(sR,index); % % %index=sR.index(index,:); %Nindex=size(index,1); W=[]; %for i=1:Nindex, % dWh(:,i)=sR.dewhiteningMatrix{1}(:,index(i,2)); %end %function W=getWhitening(sR,index); % %function W=getWhitening(sR,index); % % %index=sR.index(index,:); %Nindex=size(index,1); W=[]; %for i=1:Nindex, % W(:,i)=sR.whiteningMatrix{index(i,1)}(:,index(i,2)); %end
github
lcnhappe/happe-master
spm_input.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_input.m
89,257
utf_8
74a73562f0562998a037c0c5d7a512c7
function varargout = spm_input(varargin) % Comprehensive graphical and command line input function % FORMATs (given in Programmers Help) %_______________________________________________________________________ % % spm_input handles most forms of interactive user input for SPM. % (File selection is handled by spm_select.m) % % There are five types of input: String, Evaluated, Conditions, Buttons % and Menus: These prompt for string input; string input which is % evaluated to give a numerical result; selection of one item from a % set of buttons; selection of an item from a menu. % % - STRING, EVALUATED & CONDITION input - % For STRING, EVALUATED and CONDITION input types, a prompt is % displayed adjacent to an editable text entry widget (with a lilac % background!). Clicking in the entry widget allows editing, pressing % <RETURN> or <ENTER> enters the result. You must enter something, % empty answers are not accepted. A default response may be pre-specified % in the entry widget, which will then be outlined. Clicking the border % accepts the default value. % % Basic editing of the entry widget is supported *without* clicking in % the widget, provided no other graphics widget has the focus. (If a % widget has the focus, it is shown highlighted with a thin coloured % line. Clicking on the window background returns the focus to the % window, enabling keyboard accelerators.). This enables you to type % responses to a sequence of questions without having to repeatedly % click the mouse in the text widgets. Supported are BackSpace and % Delete, line kill (^U). Other standard ASCII characters are appended % to the text in the entry widget. Press <RETURN> or <ENTER> to submit % your response. % % A ContextMenu is provided (in the figure background) giving access to % relevant utilities including the facility to load input from a file % (see spm_load.m and examples given below): Click the right button on % the figure background. % % For EVALUATED input, the string submitted is evaluated in the base % MatLab workspace (see MatLab's `eval` command) to give a numerical % value. This permits the entry of numerics, matrices, expressions, % functions or workspace variables. I.e.: % i) - a number, vector or matrix e.g. "[1 2 3 4]" % "[1:4]" % "1:4" % ii) - an expression e.g. "pi^2" % "exp(-[1:36]/5.321)" % iii) - a function (that will be invoked) e.g. "spm_load('tmp.dat')" % (function must be on MATLABPATH) "input_cov(36,5.321)" % iv) - a variable from the base workspace % e.g. "tmp" % % The last three options provide a great deal of power: spm_load will % load a matrix from an ASCII data file and return the results. When % called without an argument, spm_load will pop up a file selection % dialog. Alternatively, this facility can be gained from the % ContextMenu. The second example assummes a custom funcion called % input_cov has been written which expects two arguments, for example % the following file saved as input_cov.m somewhere on the MATLABPATH % (~/matlab, the matlab subdirectory of your home area, and the current % directory, are on the MATLABPATH by default): % % function [x] = input_cov(n,decay) % % data input routine - mono-exponential covariate % % FORMAT [x] = input_cov(n,decay) % % n - number of time points % % decay - decay constant % x = exp(-[1:n]/decay); % % Although this example is trivial, specifying large vectors of % empirical data (e.g. reaction times for 72 scans) is efficient and % reliable using this device. In the last option, a variable called tmp % is picked up from the base workspace. To use this method, set the % variables in the MatLab base workspace before starting an SPM % procedure (but after starting the SPM interface). E.g. % >> tmp=exp(-[1:36]/5.321) % % Occasionally a vector of a specific length will be required: This % will be indicated in the prompt, which will start with "[#]", where % # is the length of vector(s) required. (If a matrix is entered then % at least one dimension should equal #.) % % Occasionally a specific type of number will be required. This should % be obvious from the context. If you enter a number of the wrong type, % you'll be alerted and asked to re-specify. The types are i) Real % numbers; ii) Integers; iii) Whole numbers [0,1,2,3,...] & iv) Natural % numbers [1,2,3,...] % % CONDITIONS type input is for getting indicator vectors. The features % of evaluated input described above are complimented as follows: % v) - a compressed list of digits 0-9 e.g. "12121212" % ii) - a list of indicator characters e.g. "abababab" % a-z mapped to 1-26 in alphabetical order, *except* r ("rest") % which is mapped to zero (case insensitive, [A:Z,a:z] only) % ...in addition the response is checked to ensure integer condition indices. % Occasionally a specific number of conditions will be required: This % will be indicated in the prompt, which will end with (#), where # is % the number of conditions required. % % CONTRAST type input is for getting contrast weight vectors. Enter % contrasts as row-vectors. Contrast weight vectors will be padded with % zeros to the correct length, and checked for validity. (Valid % contrasts are estimable, which are those whose weights vector is in % the row-space of the design matrix.) % % Errors in string evaluation for EVALUATED & CONDITION types are % handled gracefully, the user notified, and prompted to re-enter. % % - BUTTON input - % For Button input, the prompt is displayed adjacent to a small row of % buttons. Press the approprate button. The default button (if % available) has a dark outline. Keyboard accelerators are available % (provided no graphics widget has the focus): <RETURN> or <ENTER> % selects the default button (if available). Typing the first character % of the button label (case insensitive) "presses" that button. (If % these Keys are not unique, then the integer keys 1,2,... "press" the % appropriate button.) % % The CommandLine variant presents a simple menu of buttons and prompts % for a selection. Any default response is indicated, and accepted if % an empty line is input. % % % - MENU input - % For Menu input, the prompt is displayed in a pull down menu widget. % Using the mouse, a selection is made by pulling down the widget and % releasing the mouse on the appropriate response. The default response % (if set) is marked with an asterisk. Keyboard accelerators are % available (provided no graphic widget has the focus) as follows: 'f', % 'n' or 'd' move forward to next response down; 'b', 'p' or 'u' move % backwards to the previous response up the list; the number keys jump % to the appropriate response number; <RETURN> or <ENTER> slelects the % currently displayed response. If a default is available, then % pressing <RETURN> or <ENTER> when the prompt is displayed jumps to % the default response. % % The CommandLine variant presents a simple menu and prompts for a selection. % Any default response is indicated, and accepted if an empty line is % input. % % % - Combination BUTTON/EDIT input - % In this usage, you will be presented with a set of buttons and an % editable text widget. Click one of the buttons to choose that option, % or type your response in the edit widget. Any default response will % be shown in the edit widget. The edit widget behaves in the same way % as with the STRING/EVALUATED input, and expects a single number. % Keypresses edit the text widget (rather than "press" the buttons) % (provided no other graphics widget has the focus). A default response % can be selected with the mouse by clicking the thick border of the % edit widget. % % % - Comand line - % If YPos is 0 or global CMDLINE is true, then the command line is used. % Negative YPos overrides CMDLINE, ensuring the GUI is used, at % YPos=abs(YPos). Similarly relative YPos beginning with '!' % (E.g.YPos='!+1') ensures the GUI is used. % % spm_input uses the SPM 'Interactive' window, which is 'Tag'ged % 'Interactive'. If there is no such window, then the current figure is % used, or an 'Interactive' window created if no windows are open. % %----------------------------------------------------------------------- % Programers help is contained in the main body of spm_input.m %----------------------------------------------------------------------- % See : input.m (MatLab Reference Guide) % See also : spm_select.m (SPM file selector dialog) % : spm_input.m (Input wrapper function - handles batch mode) %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Andrew Holmes % $Id$ %======================================================================= % - FORMAT specifications for programers %======================================================================= % generic - [p,YPos] = spm_input(Prompt,YPos,Type,...) % string - [p,YPos] = spm_input(Prompt,YPos,'s',DefStr) % string+ - [p,YPos] = spm_input(Prompt,YPos,'s+',DefStr) % evaluated - [p,YPos] = spm_input(Prompt,YPos,'e',DefStr,n) % - natural - [p,YPos] = spm_input(Prompt,YPos,'n',DefStr,n,mx) % - whole - [p,YPos] = spm_input(Prompt,YPos,'w',DefStr,n,mx) % - integer - [p,YPos] = spm_input(Prompt,YPos,'i',DefStr,n) % - real - [p,YPos] = spm_input(Prompt,YPos,'r',DefStr,n,mm) % condition - [p,YPos] = spm_input(Prompt,YPos,'c',DefStr,n,m) % contrast - [p,YPos] = spm_input(Prompt,YPos,'x',DefStr,n,X) % permutation- [p,YPos] = spm_input(Prompt,YPos,'p',DefStr,P,n) % button - [p,YPos] = spm_input(Prompt,YPos,'b',Labels,Values,DefItem) % button/edit combo's (edit for string or typed scalar evaluated input) % [p,YPos] = spm_input(Prompt,YPos,'b?1',Labels,Values,DefStr,mx) % ...where ? in b?1 specifies edit widget type as with string & eval'd input % - [p,YPos] = spm_input(Prompt,YPos,'n1',DefStr,mx) % - [p,YPos] = spm_input(Prompt,YPos,'w1',DefStr,mx) % button dialog % - [p,YPos] = spm_input(Prompt,YPos,'bd',... % Labels,Values,DefItem,Title) % menu - [p,YPos] = spm_input(Prompt,YPos,'m',Labels,Values,DefItem) % display - spm_input(Message,YPos,'d',Label) % display - (GUI only) spm_input(Alert,YPos,'d!',Label) % % yes/no - [p,YPos] = spm_input(Prompt,YPos,'y/n',Values,DefItem) % buttons (shortcut) where Labels is a bar delimited string % - [p,YPos] = spm_input(Prompt,YPos,Labels,Values,DefItem) % % NB: Natural numbers are [1:Inf), Whole numbers are [0:Inf) % % -- Parameters (input) -- % % Prompt - prompt string % - Defaults (missing or empty) to 'Enter an expression' % % YPos - (numeric) vertical position {1 - 12} % - overriden by global CMDLINE % - 0 for command line % - negative to force GUI % - (string) relative vertical position E.g. '+1' % - relative to last position used % - overriden by global CMDLINE % - YPos(1)=='!' forces GUI E.g. '!+1' % - '_' is a shortcut for the lowest GUI position % - Defaults (missing or empty) to '+1' % % Type - type of interrogation % - 's'tring % - 's+' multi-line string % - p returned as cellstr (nx1 cell array of strings) % - DefStr can be a cellstr or string matrix % - 'e'valuated string % - 'n'atural numbers % - 'w'hole numbers % - 'i'ntegers % - 'r'eals % - 'c'ondition indicator vector % - 'x' - contrast entry % - If n(2) or design matrix X is specified, then % contrast matrices are padded with zeros to have % correct length. % - if design matrix X is specified, then contrasts are % checked for validity (i.e. in the row-space of X) % (checking handled by spm_SpUtil) % - 'b'uttons % - 'bd' - button dialog: Uses MatLab's questdlg % - For up to three buttons % - Prompt can be a cellstr with a long multiline message % - CmdLine support as with 'b' type % - button/edit combo's: 'be1','bn1','bw1','bi1','br1' % - second letter of b?1 specifies type for edit widget % - 'n1' - single natural number (buttons 1,2,... & edit) % - 'w1' - single whole number (buttons 0,1,... & edit) % - 'm'enu pulldown % - 'y/n' : Yes or No buttons % (See shortcuts below) % - bar delimited string : buttons with these labels % (See shortcuts below) % - Defaults (missing or empty) to 'e' % % DefStr - Default string to be placed in entry widget for string and % evaluated types % - Defaults to '' % % n ('e', 'c' & 'p' types) % - Size of matrix requred % - NaN for 'e' type implies no checking - returns input as evaluated % - length of n(:) specifies dimension - elements specify size % - Inf implies no restriction % - Scalar n expanded to [n,1] (i.e. a column vector) % (except 'x' contrast type when it's [n,np] for np % - E.g: [n,1] & [1,n] (scalar n) prompt for an n-vector, % returned as column or row vector respectively % [1,Inf] & [Inf,1] prompt for a single vector, % returned as column or row vector respectively % [n,Inf] & [Inf,n] prompts for any number of n-vectors, % returned with row/column dimension n respectively. % [a,b] prompts for an 2D matrix with row dimension a and % column dimension b % [a,Inf,b] prompt for a 3D matrix with row dimension a, % page dimension b, and any column dimension. % - 'c' type can only deal with single vectors % - NaN for 'c' type treated as Inf % - Defaults (missing or empty) to NaN % % n ('x'type) % - Number of contrasts required by 'x' type (n(1)) % ( n(2) can be used specify length of contrast vectors if ) % ( a design matrix isn't passed ) % - Defaults (missing or empty) to 1 - vector contrast % % mx ('n', 'w', 'n1', 'w1', 'bn1' & 'bw1' types) % - Maximum value (inclusive) % % mm ('r' type) % - Maximum and minimum values (inclusive) % % m - Number of unique conditions required by 'c' type % - Inf implies no restriction % - Defaults (missing or empty) to Inf - no restriction % % P - set (vector) of numbers of which a permutation is required % % X - Design matrix for contrast checking in 'x' type % - Can be either a straight matrix or a space structure (see spm_sp) % - Column dimension of design matrix specifies length of contrast % vectors (overriding n(2) is specified). % % Title - Title for questdlg in 'bd' type % % Labels - Labels for button and menu types. % - string matrix, one label per row % - bar delimited string % E.g. 'AnCova|Scaling|None' % % Values - Return values corresponding to Labels for button and menu types % - j-th row is returned if button / menu item j is selected % (row vectors are transposed) % - Defaults (missing or empty) to - (button) Labels % - ( menu ) menu item numbers % % DefItem - Default item number, for button and menu types. % % -- Parameters (output) -- % p - results % YPos - Optional second output argument returns GUI position just used % %----------------------------------------------------------------------- % WINDOWS: % % spm_input uses the SPM 'Interactive' 'Tag'ged window. If this isn't % available and no figures are open, an 'Interactive' SPM window is % created (`spm('CreateIntWin')`). If figures are available, then the % current figure is used *unless* it is 'Tag'ged. % %----------------------------------------------------------------------- % SHORTCUTS: % % Buttons SHORTCUT - If the Type parameter is a bar delimited string, then % the Type is taken as 'b' with the specified labels, and the next parameter % (if specified) is taken for the Values. % % Yes/No question shortcut - p = spm_input(Prompt,YPos,'y/n') expands % to p = spm_input(Prompt,YPos,'b','yes|no',...), enabling easy use of % spm_input for yes/no dialogue. Values defaults to 'yn', so 'y' or 'n' % is returned as appropriate. % %----------------------------------------------------------------------- % EXAMPLES: % ( Specified YPos is overriden if global CMDLINE is ) % ( true, when the command line versions are used. ) % % p = spm_input % Command line input of an evaluated string, default prompt. % p = spm_input('Enter a value',1) % Evaluated string input, prompted by 'Enter a value', in % position 1 of the dialog figure. % p = spm_input(str,'+1','e',0.001) % Evaluated string input, prompted by contents of string str, % in next position of the dialog figure. % Default value of 0.001 offered. % p = spm_input(str,2,'e',[],5) % Evaluated string input, prompted by contents of string str, % in second position of the dialog figure. % Vector of length 5 required - returned as column vector % p = spm_input(str,2,'e',[],[Inf,5]) % ...as above, but can enter multiple 5-vectors in a matrix, % returned with 5-vectors in rows % p = spm_input(str,0,'c','ababab') % Condition string input, prompted by contents of string str % Uses command line interface. % Default string of 'ababab' offered. % p = spm_input(str,0,'c','010101') % As above, but default string of '010101' offered. % [p,YPos] = spm_input(str,'0','s','Image') % String input, same position as last used, prompted by str, % default of 'Image' offered. YPos returns GUI position used. % p = spm_input(str,'-1','y/n') % Yes/No buttons for question with prompt str, in position one % before the last used Returns 'y' or 'n'. % p = spm_input(str,'-1','y/n',[1,0],2) % As above, but returns 1 for yes response, 0 for no, % with 'no' as the default response % p = spm_input(str,4,'AnCova|Scaling') % Presents two buttons labelled 'AnCova' & 'Scaling', with % prompt str, in position 4 of the dialog figure. Returns the % string on the depresed button, where buttons can be pressed % with the mouse or by the respective keyboard accelerators % 'a' & 's' (or 'A' & 'S'). % p = spm_input(str,-4,'b','AnCova|Scaling',[],2) % As above, but makes "Scaling" the default response, and % overrides global CMDLINE % p = spm_input(str,0,'b','AnCova|Scaling|None',[1,2,3]) % Prompts for [A]ncova / [S]caling / [N]one in MatLab command % window, returns 1, 2, or 3 according to the first character % of the entered string as one of 'a', 's', or 'n' (case % insensitive). % p = spm_input(str,1,'b','AnCova',1) % Since there's only one button, this just displays the response % in GUI position 1 (or on the command line if global CMDLINE % is true), and returns 1. % p = spm_input(str,'+0','br1','None|Mask',[-Inf,NaN],0.8) % Presents two buttons labelled "None" & "Mask" (which return % -Inf & NaN if clicked), together with an editable text widget % for entry of a single real number. The default of 0.8 is % initially presented in the edit window, and can be selected by % pressing return. % Uses the previous GUI position, unless global CMDLINE is true, % in which case a command-line equivalent is used. % p = spm_input(str,'+0','w1') % Prompts for a single whole number using a combination of % buttons and edit widget, using the previous GUI position, % or the command line if global CMDLINE is true. % p = spm_input(str,'!0','m','Single Subject|Multi Subject|Multi Study') % Prints the prompt str in a pull down menu containing items % 'Single Subject', 'Multi Subject' & 'Multi Study'. When OK is % clicked p is returned as the index of the choice, 1,2, or 3 % respectively. Uses last used position in GUI, irrespective of % global CMDLINE % p = spm_input(str,5,'m',... % 'Single Subject|Multi Subject|Multi Study',... % ['SS';'MS';'SP'],2) % As above, but returns strings 'SS', 'MS', or 'SP' according to % the respective choice, with 'MS; as the default response. % p = spm_input(str,0,'m',... % 'Single Subject|Multi Subject|Multi Study',... % ['SS';'MS';'SP'],2) % As above, but the menu is presented in the command window % as a numbered list. % spm_input('AnCova, GrandMean scaling',0,'d') % Displays message in a box in the MatLab command window % [null,YPos]=spm_input('Session 1','+1','d!','fMRI') % Displays 'fMRI: Session 1' in next GUI position of the % 'Interactive' window. If CMDLINE is 1, then nothing is done. % Position used is returned in YPos. % %----------------------------------------------------------------------- % FORMAT h = spm_input(Prompt,YPos,'m!',Labels,cb,UD,XCB); % GUI PullDown menu utility - creates a pulldown menu in the Interactive window % FORMAT H = spm_input(Prompt,YPos,'b!',Labels,cb,UD,XCB); % GUI Buttons utility - creates GUI buttons in the Interactive window % % Prompt, YPos, Labels - as with 'm'enu/'b'utton types % cb - CallBack string % UD - UserData % XCB - Extended CallBack handling - allows different CallBack for each item, % and use of UD in CallBack strings. [Defaults to 1 for PullDown type % when multiple CallBacks specified, 0 o/w.] % H - Handle of 'PullDown' uicontrol / 'Button's % % In "normal" mode (when XCB is false), this is essentially a utility % to create a PullDown menu widget or set of buttons in the SPM % 'Interactive' figure, using positioning and Label definition % conveniences of the spm_input 'm'enu & 'b'utton types. If Prompt is % not empty, then the PullDown/Buttons appears on the right, with the % Prompt on the left, otherwise the PullDown/Buttons use the whole % width of the Interactive figure. The PopUp's CallBack string is % specified in cb, and [optional] UserData may be passed as UD. % % For buttons, a separate callback can be specified for each button, by % passing the callbacks corresponding to the Labels as rows of a % cellstr or string matrix. % % This "different CallBacks" facility can also be extended to the % PullDown type, using the "extended callback" mode (when XCB is % true). % In addition, in "extended callback", you can use UD to % refer to the UserData argument in the CallBack strings. (What happens % is this: The cb & UD are stored as fields in the PopUp's UserData % structure, and the PopUp's callback is set to spm_input('!m_cb'), % which reads UD into the functions workspace and eval's the % appropriate CallBack string. Note that this means that base % workspace variables are inaccessible (put what you need in UD), and % that any return arguments from CallBack functions are not passed back % to the base workspace). % % %----------------------------------------------------------------------- % UTILITY FUNCTIONS: % % FORMAT colour = spm_input('!Colour') % Returns colour for input widgets, as specified in COLOUR parameter at % start of code. % colour - [r,g,b] colour triple % % FORMAT [iCond,msg] = spm_input('!iCond',str,n,m) % Parser for special 'c'ondition type: Handles digit strings and % strings of indicator chars. % str - input string % n - length of condition vector required [defaut Inf - no restriction] % m - number of conditions required [default Inf - no restrictions] % iCond - Integer condition indicator vector % msg - status message % % FORMAT hM = spm_input('!InptConMen',Finter,H) % Sets a basic Input ContextMenu for the figure % Finter - figure to set menu in % H - handles of objects to delete on "crash out" option % hM - handle of UIContextMenu % % FORMAT [CmdLine,YPos] = spm_input('!CmdLine',YPos) % Sorts out whether to use CmdLine or not & canonicalises YPos % CmdLine - Binary flag % YPos - Position index % % FORMAT Finter = spm_input('!GetWin',F) % Locates (or creates) figure to work in % F - Interactive Figure, defaults to 'Interactive' % Finter - Handle of figure to use % % FORMAT [PLoc,cF] = spm_input('!PointerJump',RRec,F,XDisp) % Raise window & jump pointer over question % RRec - Response rectangle of current question % F - Interactive Figure, Defaults to 'Interactive' % XDisp - X-displacement of cursor relative to RRec % PLoc - Pointer location before jumping % cF - Current figure before making F current. % % FORMAT [PLoc,cF] = spm_input('!PointerJumpBack',PLoc,cF) % Replace pointer and reset CurrentFigure back % PLoc - Pointer location before jumping % cF - Previous current figure % % FORMAT spm_input('!PrntPrmpt',Prompt,TipStr,Title) % Print prompt for CmdLine questioning % Prompt - prompt string, callstr, or string matrix % TipStr - tip string % Title - title string % % FORMAT [Frec,QRec,PRec,RRec] = spm_input('!InputRects',YPos,rec,F) % Returns rectangles (pixels) used in GUI % YPos - Position index % rec - Rectangle specifier: String, one of 'Frec','QRec','PRec','RRec' % Defaults to '', which returns them all. % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % FRec - Position of interactive window % QRec - Position of entire question % PRec - Position of prompt % RRec - Position of response % % FORMAT spm_input('!DeleteInputObj',F) % Deltes input objects (only) from figure F % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % % FORMAT [CPos,hCPos] = spm_input('!CurrentPos',F) % Returns currently used GUI question positions & their handles % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % CPos - Vector of position indices % hCPos - (n x CPos) matrix of object handles % % FORMAT h = spm_input('!FindInputObj',F) % Returns handles of input GUI objects in figure F % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % h - vector of object handles % % FORMAT [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine) % Returns next position index, specified by YPos % YPos - Absolute (integer) or relative (string) position index % Defaults to '+1' % F - Interactive Figure, defaults to spm_figure('FindWin','Interactive') % CmdLine - Command line? Defaults to spm_input('!CmdLine',YPos) % NPos - Next position index % CPos & hCPos - as for !CurrentPos % % FORMAT NPos = spm_input('!SetNextPos',YPos,F,CmdLine) % Sets up for input at next position index, specified by YPos. This utility % function can be used stand-alone to implicitly set the next position % by clearing positions NPos and greater. % YPos - Absolute (integer) or relative (string) position index % Defaults to '+1' % F - Interactive Figure, defaults to spm_figure('FindWin','Interactive') % CmdLine - Command line? Defaults to spm_input('!CmdLine',YPos) % NPos - Next position index % % FORMAT MPos = spm_input('!MaxPos',F,FRec3) % Returns maximum position index for figure F % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % Not required if FRec3 is specified % FRec3 - Length of interactive figure in pixels % % FORMAT spm_input('!EditableKeyPressFcn',h,ch) % KeyPress callback for GUI string / eval input % % FORMAT spm_input('!ButtonKeyPressFcn',h,Keys,DefItem,ch) % KeyPress callback for GUI buttons % % FORMAT spm_input('!PullDownKeyPressFcn',h,ch,DefItem) % KeyPress callback for GUI pulldown menus % % FORMAT spm_input('!m_cb') % Extended CallBack handler for 'p' PullDown utility type % % FORMAT spm_input('!dScroll',h,str) % Scroll text string in object h % h - handle of text object % Prompt - Text to scroll (Defaults to 'UserData' of h) % %----------------------------------------------------------------------- % SUBFUNCTIONS: % % FORMAT [Keys,Labs] = sf_labkeys(Labels) % Make unique character keys for the Labels, ignoring case. % Used with 'b'utton types. % % FORMAT [p,msg] = sf_eEval(str,Type,n,m) % Common code for evaluating various input types. % % FORMAT str = sf_SzStr(n,l) % Common code to construct prompt strings for pre-specified vector/matrix sizes % % FORMAT [p,msg] = sf_SzChk(p,n,msg) % Common code to check (& canonicalise) sizes of input vectors/matrices % %_______________________________________________________________________ % @(#)spm_input.m 2.8 Andrew Holmes 03/03/04 %-Parameters %======================================================================= PJump = 1; %-Jumping of pointer to question? TTips = 1; %-Use ToolTipStrings? (which can be annoying!) ConCrash = 1; %-Add "crash out" option to 'Interactive'fig.ContextMenu %-Condition arguments %======================================================================= if nargin<1|isempty(varargin{1}), Prompt=''; else, Prompt=varargin{1}; end if ~isempty(Prompt) & ischar(Prompt) & Prompt(1)=='!' %-Utility functions have Prompt string starting with '!' Type = Prompt; else %-Should be an input request: get Type & YPos if nargin<3|isempty(varargin{3}), Type='e'; else, Type=varargin{3}; end if any(Type=='|'), Type='b|'; end if nargin<2|isempty(varargin{2}), YPos='+1'; else, YPos=varargin{2}; end [CmdLine,YPos] = spm_input('!CmdLine',YPos); if ~CmdLine %-Setup for GUI use %-Locate (or create) figure to work in Finter = spm_input('!GetWin'); COLOUR = get(Finter,'Color'); %-Find out which Y-position to use, setup for use YPos = spm_input('!SetNextPos',YPos,Finter,CmdLine); %-Determine position of objects [FRec,QRec,PRec,RRec]=spm_input('!InputRects',YPos,'',Finter); end end switch lower(Type) case {'s','s+','e','n','w','i','r','c','x','p'} %-String and evaluated input %======================================================================= %-Condition arguments if nargin<6|isempty(varargin{6}), m=[]; else, m=varargin{6}; end if nargin<5|isempty(varargin{5}), n=[]; else, n=varargin{5}; end if nargin<4, DefStr=''; else, DefStr=varargin{4}; end if strcmp(lower(Type),'s+') %-DefStr should be a cellstr for 's+' type. if isempty(DefStr), DefStr = {}; else, DefStr = cellstr(DefStr); end DefStr = DefStr(:); else %-DefStr needs to be a string if ~ischar(DefStr), DefStr=num2str(DefStr); end DefStr = DefStr(:)'; end strM=''; switch lower(Type) %-Type specific defaults/setup case 's', TTstr='enter string'; case 's+',TTstr='enter string - multi-line'; case 'e', TTstr='enter expression to evaluate'; case 'n', TTstr='enter expression - natural number(s)'; if ~isempty(m), strM=sprintf(' (in [1,%d])',m); TTstr=[TTstr,strM]; end case 'w', TTstr='enter expression - whole number(s)'; if ~isempty(m), strM=sprintf(' (in [0,%d])',m); TTstr=[TTstr,strM]; end case 'i', TTstr='enter expression - integer(s)'; case 'r', TTstr='enter expression - real number(s)'; if ~isempty(m), TTstr=[TTstr,sprintf(' in [%g,%g]',min(m),max(m))]; end case 'c', TTstr='enter indicator vector e.g. 0101... or abab...'; if ~isempty(m) & isfinite(m), strM=sprintf(' (%d)',m); end case 'x', TTstr='enter contrast matrix'; case 'p', if isempty(n), error('permutation of what?'), else, P=n(:)'; end if isempty(m), n = [1,length(P)]; end m = P; if ~length(setxor(m,[1:max(m)])) TTstr=['enter permutation of [1:',num2str(max(m)),']']; else TTstr=['enter permutation of [',num2str(m),']']; end otherwise, TTstr='enter expression'; end strN = sf_SzStr(n); if CmdLine %-Use CmdLine to get answer %----------------------------------------------------------------------- spm_input('!PrntPrmpt',[Prompt,strN,strM],TTstr) %-Do Eval Types in Base workspace, catch errors switch lower(Type), case 's' if ~isempty(DefStr) Prompt=[Prompt,' (Default: ',DefStr,' )']; end str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end while isempty(str) spm('Beep') fprintf('! %s : enter something!\n',mfilename) str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end end p = str; msg = ''; case 's+' fprintf(['Multi-line input: Type ''.'' on a line',... ' of its own to terminate input.\n']) if ~isempty(DefStr) fprintf('Default : (press return to accept)\n') fprintf(' : %s\n',DefStr{:}) end fprintf('\n') str = input('l001 : ','s'); while (isempty(str) | strcmp(str,'.')) & isempty(DefStr) spm('Beep') fprintf('! %s : enter something!\n',mfilename) str = input('l001 : ','s'); end if isempty(str) %-Accept default p = DefStr; else %-Got some input, allow entry of additional lines p = {str}; str = input(sprintf('l%03u : ',length(p)+1),'s'); while ~strcmp(str,'.') p = [p;{str}]; str = input(sprintf('l%03u : ',length(p)+1),'s'); end end msg = ''; otherwise if ~isempty(DefStr) Prompt=[Prompt,' (Default: ',DefStr,' )']; end str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end [p,msg] = sf_eEval(str,Type,n,m); while ischar(p) spm('Beep'), fprintf('! %s : %s\n',mfilename,msg) str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end [p,msg] = sf_eEval(str,Type,n,m); end end if ~isempty(msg), fprintf('\t%s\n',msg), end else %-Use GUI to get answer %----------------------------------------------------------------------- %-Create text and edit control objects %--------------------------------------------------------------- hPrmpt = uicontrol(Finter,'Style','Text',... 'String',[strN,Prompt,strM],... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData','',... 'BackgroundColor',COLOUR,... 'HorizontalAlignment','Right',... 'Position',PRec); %-Default button surrounding edit widget (if a DefStr given) %-Callback sets hPrmpt UserData, and EditWidget string, to DefStr % (Buttons UserData holds handles [hPrmpt,hEditWidget], set later) cb = ['set(get(gcbo,''UserData'')*[1;0],''UserData'',',... 'get(gcbo,''String'')),',... 'set(get(gcbo,''UserData'')*[0;1],''String'',',... 'get(gcbo,''String''))']; if ~isempty(DefStr) if iscellstr(DefStr), str=[DefStr{1},'...']; else, str=DefStr; end hDef = uicontrol(Finter,'Style','PushButton',... 'String',DefStr,... 'ToolTipString',... ['Click on border to accept default: ' str],... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData',[],... 'BackgroundColor',COLOUR,... 'CallBack',cb,... 'Position',RRec+[-2,-2,+4,+4]); else hDef = []; end %-Edit widget: Callback puts string into hPrompts UserData cb = 'set(get(gcbo,''UserData''),''UserData'',get(gcbo,''String''))'; h = uicontrol(Finter,'Style','Edit',... 'String',DefStr,... 'Max',strcmp(lower(Type),'s+')+1,... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData',hPrmpt,... 'CallBack',cb,... 'Horizontalalignment','Left',... 'BackgroundColor','w',... 'Position',RRec); set(hDef,'UserData',[hPrmpt,h]) uifocus(h); if TTips, set(h,'ToolTipString',TTstr), end %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPrmpt,hDef,h]); cb = [ 'set(get(gcbo,''UserData''),''String'',',... '[''spm_load('''''',spm_select(1),'''''')'']), ',... 'set(get(get(gcbo,''UserData''),''UserData''),''UserData'',',... 'get(get(gcbo,''UserData''),''String''))']; uimenu(hM,'Label','load from text file','Separator','on',... 'CallBack',cb,'UserData',h) %-Bring window to fore & jump pointer to edit widget [PLoc,cF] = spm_input('!PointerJump',RRec,Finter); %-Setup FigureKeyPressFcn for editing of entry widget without clicking set(Finter,'KeyPressFcn',[... 'spm_input(''!EditableKeyPressFcn'',',... 'findobj(gcf,''Tag'',''GUIinput_',int2str(YPos),''',',... '''Style'',''edit''),',... 'get(gcbf,''CurrentCharacter''))']) %-Wait for edit, do eval Types in Base workspace, catch errors %--------------------------------------------------------------- waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input window cleared whilst waiting ',... 'for response: Bailing out!']), end str = get(hPrmpt,'UserData'); switch lower(Type), case 's' p = str; msg = ''; case 's+' p = cellstr(str); msg = ''; otherwise [p,msg] = sf_eEval(str,Type,n,m); while ischar(p) set(h,'Style','Text',... 'String',msg,'HorizontalAlignment','Center',... 'ForegroundColor','r') spm('Beep'), pause(2) set(h,'Style','Edit',... 'String',str,... 'HorizontalAlignment','Left',... 'ForegroundColor','k') %set(hPrmpt,'UserData',''); waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input window cleared ',... 'whilst waiting for response: Bailing out!']),end str = get(hPrmpt,'UserData'); [p,msg] = sf_eEval(str,Type,n,m); end end %-Fix edit window, clean up, reposition pointer, set CurrentFig back delete([hM,hDef]), set(Finter,'KeyPressFcn','') set(h,'Style','Text','HorizontalAlignment','Center',... 'ToolTipString',msg,... 'BackgroundColor',COLOUR) spm_input('!PointerJumpBack',PLoc,cF) drawnow end % (if CmdLine) %-Return response %----------------------------------------------------------------------- varargout = {p,YPos}; case {'b','bd','b|','y/n','be1','bn1','bw1','bi1','br1',... '-n1','n1','-w1','w1','m'} %-'b'utton & 'm'enu Types %======================================================================= %-Condition arguments switch lower(Type), case {'b','be1','bi1','br1','m'} m = []; Title = ''; if nargin<6, DefItem=[]; else, DefItem=varargin{6}; end if nargin<5, Values=[]; else, Values =varargin{5}; end if nargin<4, Labels=''; else, Labels =varargin{4}; end case 'bd' if nargin<7, Title=''; else, Title =varargin{7}; end if nargin<6, DefItem=[]; else, DefItem=varargin{6}; end if nargin<5, Values=[]; else, Values =varargin{5}; end if nargin<4, Labels=''; else, Labels =varargin{4}; end case 'y/n' Title = ''; if nargin<5, DefItem=[]; else, DefItem=varargin{5}; end if nargin<4, Values=[]; else, Values =varargin{4}; end if isempty(Values), Values='yn'; end Labels = {'yes','no'}; case 'b|' Title = ''; if nargin<5, DefItem=[]; else, DefItem=varargin{5}; end if nargin<4, Values=[]; else, Values =varargin{4}; end Labels = varargin{3}; case 'bn1' if nargin<7, m=[]; else, m=varargin{7}; end if nargin<6, DefItem=[]; else, DefItem=varargin{6}; end if nargin<5, Values=[]; else, Values =varargin{5}; end if nargin<4, Labels=[1:5]'; Values=[1:5]; Type='-n1'; else, Labels=varargin{4}; end case 'bw1' if nargin<7, m=[]; else, m=varargin{7}; end if nargin<6, DefItem=[]; else, DefItem=varargin{6}; end if nargin<5, Values=[]; else, Values =varargin{5}; end if nargin<4, Labels=[0:4]'; Values=[0:4]; Type='-w1'; else, Labels=varargin{4}; end case {'-n1','n1','-w1','w1'} if nargin<5, m=[]; else, m=varargin{5}; end if nargin<4, DefItem=[]; else, DefItem=varargin{4}; end switch lower(Type) case {'n1','-n1'}, Labels=[1:min([5,m])]'; Values=Labels'; Type='-n1'; case {'w1','-w1'}, Labels=[0:min([4,m])]'; Values=Labels'; Type='-w1'; end end %-Check some labels were specified if isempty(Labels), error('No Labels specified'), end if iscellstr(Labels), Labels=char(Labels); end %-Convert Labels "option" string to string matrix if required if ischar(Labels) & any(Labels=='|') OptStr=Labels; BarPos=find([OptStr=='|',1]); Labels=OptStr(1:BarPos(1)-1); for Bar = 2:sum(OptStr=='|')+1 Labels=strvcat(Labels,OptStr(BarPos(Bar-1)+1:BarPos(Bar)-1)); end end %-Set default Values for the Labels if isempty(Values) if strcmp(lower(Type),'m') Values=[1:size(Labels,1)]'; else Values=Labels; end else %-Make sure Values are in rows if size(Labels,1)>1 & size(Values,1)==1, Values = Values'; end %-Check numbers of Labels and Values match if (size(Labels,1)~=size(Values,1)) error('Labels & Values incompatible sizes'), end end %-Numeric Labels to strings if isnumeric(Labels) tmp = Labels; Labels = cell(size(tmp,1),1); for i=1:prod(size(tmp)), Labels{i}=num2str(tmp(i,:)); end Labels=char(Labels); end switch lower(Type), case {'b','bd','b|','y/n'} %-Process button types %======================================================================= %-Make unique character keys for the Labels, sort DefItem %--------------------------------------------------------------- nLabels = size(Labels,1); [Keys,Labs] = sf_labkeys(Labels); if ~isempty(DefItem) & any(DefItem==[1:nLabels]) DefKey = Keys(DefItem); else DefItem = 0; DefKey = ''; end if CmdLine %-Display question prompt spm_input('!PrntPrmpt',Prompt,'',Title) %-Build prompt %------------------------------------------------------- if ~isempty(Labs) Prmpt = ['[',Keys(1),']',deblank(Labs(1,:)),' ']; for i = 2:nLabels Prmpt=[Prmpt,'/ [',Keys(i),']',deblank(Labs(i,:)),' ']; end else Prmpt = ['[',Keys(1),'] ']; for i = 2:nLabels, Prmpt=[Prmpt,'/ [',Keys(i),'] ']; end end if DefItem Prmpt = [Prmpt,... ' (Default: ',deblank(Labels(DefItem,:)),')']; end %-Ask for user response %------------------------------------------------------- if nLabels==1 %-Only one choice - auto-pick & display k = 1; fprintf('%s: %s\t(only option)',Prmpt,Labels) else str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end while isempty(str) | ~any(lower(Keys)==lower(str(1))) if ~isempty(str),fprintf('%c\t!Out of range\n',7),end str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end end k = find(lower(Keys)==lower(str(1))); end fprintf('\n') p = Values(k,:); if ischar(p), p=deblank(p); end elseif strcmp(lower(Type),'bd') if nLabels>3, error('at most 3 labels for GUI ''db'' type'), end tmp = cellstr(Labels); if DefItem tmp = [tmp; tmp(DefItem)]; Prompt = cellstr(Prompt); Prompt=Prompt(:); Prompt = [Prompt;{' '};... {['[default: ',tmp{DefItem},']']}]; else tmp = [tmp; tmp(1)]; end k = min(find(strcmp(tmp,... questdlg(Prompt,sprintf('%s%s: %s...',spm('ver'),... spm('GetUser',' (%s)'),Title),tmp{:})))); p = Values(k,:); if ischar(p), p=deblank(p); end else Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets %-Create text and edit control objects %-'UserData' of prompt contains answer %------------------------------------------------------- hPrmpt = uicontrol(Finter,'Style','Text',... 'String',Prompt,... 'Tag',Tag,... 'UserData',[],... 'BackgroundColor',COLOUR,... 'HorizontalAlignment','Right',... 'Position',PRec); if nLabels==1 %-Only one choice - auto-pick k = 1; else %-Draw buttons and process response dX = RRec(3)/nLabels; if TTips, str = ['select with mouse or use kbd: ',... sprintf('%c/',Keys(1:end-1)),Keys(end)]; else, str=''; end %-Store button # in buttons 'UserData' property %-Store handle of prompt string in buttons 'Max' property %-Button callback sets UserData of prompt string to % number of pressed button cb = ['set(get(gcbo,''Max''),''UserData'',',... 'get(gcbo,''UserData''))']; H = []; XDisp = []; for i=1:nLabels if i==DefItem %-Default button, outline it h = uicontrol(Finter,'Style','Frame',... 'BackGroundColor','k',... 'ForeGroundColor','k',... 'Tag',Tag,... 'Position',... [RRec(1)+(i-1)*dX ... RRec(2)-1 dX RRec(4)+2]); XDisp = (i-1/3)*dX; H = [H,h]; end h = uicontrol(Finter,'Style','Pushbutton',... 'String',deblank(Labels(i,:)),... 'ToolTipString',str,... 'Tag',Tag,... 'Max',hPrmpt,... 'UserData',i,... 'BackgroundColor',COLOUR,... 'Callback',cb,... 'Position',[RRec(1)+(i-1)*dX+1 ... RRec(2) dX-2 RRec(4)]); if i == DefItem, uifocus(h); end H = [H,h]; end %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPrmpt,H]); %-Bring window to fore & jump pointer to default button [PLoc,cF]=spm_input('!PointerJump',RRec,Finter,XDisp); %-Callback for KeyPress, to store valid button # in % UserData of Prompt, DefItem if (DefItem~=0) % & return (ASCII-13) is pressed set(Finter,'KeyPressFcn',... ['spm_input(''!ButtonKeyPressFcn'',',... 'findobj(gcf,''Tag'',''',Tag,''',',... '''Style'',''text''),',... '''',lower(Keys),''',',num2str(DefItem),',',... 'get(gcbf,''CurrentCharacter''))']) %-Wait for button press, process results %----------------------------------------------- waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt) error(['Input objects cleared whilst ',... 'waiting for response: Bailing out!']) end k = get(hPrmpt,'UserData'); %-Clean up delete([H,hM]), set(Finter,'KeyPressFcn','') spm_input('!PointerJumpBack',PLoc,cF) end %-Display answer uicontrol(Finter,'Style','Text',... 'String',deblank(Labels(k,:)),... 'Tag',Tag,... 'Horizontalalignment','Center',... 'BackgroundColor',COLOUR,... 'Position',RRec); drawnow p = Values(k,:); if ischar(p), p=deblank(p); end end case {'be1','bn1','bw1','bi1','br1','-n1','-w1'} %-Process button/entry combo types %======================================================================= if ischar(DefItem), DefStr=DefItem; else, DefStr=num2str(DefItem); end if isempty(m), strM=''; else, strM=sprintf(' (<=%d)',m); end if CmdLine %-Process default item %--------------------------------------------------------------- if ~isempty(DefItem) [DefVal,msg] = sf_eEval(DefStr,Type(2),1); if ischar(DefVal), error(['Invalid DefItem: ',msg]), end Labels = strvcat(Labels,DefStr); Values = [Values;DefVal]; DefItem = size(Labels,1); end %-Add option to specify... Labels = strvcat(Labels,'specify...'); %-Process options nLabels = size(Labels,1); [Keys,Labs] = sf_labkeys(Labels); if ~isempty(DefItem), DefKey = Keys(DefItem); else, DefKey = ''; end %-Print banner prompt %--------------------------------------------------------------- spm_input('!PrntPrmpt',Prompt) %-Display question prompt if Type(1)=='-' %-No special buttons - go straight to input k = size(Labels,1); else %-Offer buttons, default or "specify..." %-Build prompt %------------------------------------------------------- if ~isempty(Labs) Prmpt = ['[',Keys(1),']',deblank(Labs(1,:)),' ']; for i = 2:nLabels Prmpt=[Prmpt,'/ [',Keys(i),']',deblank(Labs(i,:)),' ']; end else Prmpt = ['[',Keys(1),'] ']; for i = 2:nLabels, Prmpt=[Prmpt,'/ [',Keys(i),'] ']; end end if DefItem, Prmpt = [Prmpt,... ' (Default: ',deblank(Labels(DefItem,:)),')']; end %-Ask for user response %------------------------------------------------------- if nLabels==1 %-Only one choice - auto-pick & display k = 1; fprintf('%s: %s\t(only option)',Prmpt,Labels) else str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end while isempty(str) | ~any(lower(Keys)==lower(str(1))) if ~isempty(str),fprintf('%c\t!Invalid response\n',7),end str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end end k = find(lower(Keys)==lower(str(1))); end fprintf('\n') end %-Process response: prompt for value if "specify..." option chosen %=============================================================== if k<size(Labels,1) p = Values(k,:); if ischar(p), p=deblank(p); end else %-"specify option chosen: ask user to specify %------------------------------------------------------- switch lower(Type(2)) case 's', tstr=' string'; case 'e', tstr='n expression'; case 'n', tstr=' natural number';case 'w', tstr=' whole number'; case 'i', tstr='n integer'; case 'r', tstr=' real number'; otherwise, tstr=''; end Prompt = sprintf('%s (a%s%s)',Prompt,tstr,strM); if ~isempty(DefStr) Prompt=sprintf('%s\b, default %s)',Prompt,DefStr); end str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end %-Eval in Base workspace, catch errors [p,msg] = sf_eEval(str,Type(2),1,m); while ischar(p) spm('Beep'), fprintf('! %s : %s\n',mfilename,msg) str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end [p,msg] = sf_eEval(str,Type(2),1,m); end end else Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets nLabels = size(Labels,1); %-#buttons %-Create text and edit control objects %-'UserData' of prompt contains answer %--------------------------------------------------------------- hPrmpt = uicontrol(Finter,'Style','Text',... 'String',[Prompt,strM],... 'Tag',Tag,... 'UserData',[],... 'BackgroundColor',COLOUR,... 'HorizontalAlignment','Right',... 'Position',PRec); %-Draw buttons & entry widget, & process response dX = RRec(3)*(2/3)/nLabels; %-Store button # in buttons 'UserData' %-Store handle of prompt string in buttons 'Max' property %-Callback sets UserData of prompt string to button number. cb = ['set(get(gcbo,''Max''),''UserData'',get(gcbo,''UserData''))']; if TTips, str=sprintf('select by mouse or enter value in text widget'); else, str=''; end H = []; for i=1:nLabels h = uicontrol(Finter,'Style','Pushbutton',... 'String',deblank(Labels(i,:)),... 'Max',hPrmpt,... 'ToolTipString',str,... 'Tag',Tag,... 'UserData',i,... 'BackgroundColor',COLOUR,... 'Callback',cb,... 'Position',[RRec(1)+(i-1)*dX+1 RRec(2) dX-2 RRec(4)]); H = [H,h]; end %-Default button surrounding edit widget (if a DefStr given) %-Callback sets hPrmpt UserData, and EditWidget string, to DefStr % (Buttons UserData holds handles [hPrmpt,hEditWidget], set later) cb = ['set(get(gcbo,''UserData'')*[1;0],''UserData'',',... 'get(gcbo,''String'')),',... 'set(get(gcbo,''UserData'')*[0;1],''String'',',... 'get(gcbo,''String''))']; if ~isempty(DefStr) hDef = uicontrol(Finter,'Style','PushButton',... 'String',DefStr,... 'ToolTipString',['Click on border to accept ',... 'default: ' DefStr],... 'Tag',Tag,... 'UserData',[],... 'CallBack',cb,... 'BackgroundColor',COLOUR,... 'Position',... [RRec(1)+RRec(3)*(2/3) RRec(2)-2 RRec(3)/3+2 RRec(4)+4]); H = [H,hDef]; else hDef = []; end %-Edit widget: Callback puts string into hPrompts UserData cb = ['set(get(gcbo,''UserData''),''UserData'',get(gcbo,''String''))']; h = uicontrol(Finter,'Style','Edit',... 'String',DefStr,... 'ToolTipString',str,... 'Tag',Tag,... 'UserData',hPrmpt,... 'CallBack',cb,... 'Horizontalalignment','Center',... 'BackgroundColor','w',... 'Position',... [RRec(1)+RRec(3)*(2/3)+2 RRec(2) RRec(3)/3-2 RRec(4)]); set(hDef,'UserData',[hPrmpt,h]) uifocus(h); H = [H,h]; %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPrmpt,H]); %-Bring window to fore & jump pointer to default button [PLoc,cF] = spm_input('!PointerJump',RRec,Finter,RRec(3)*0.95); %-Setup FigureKeyPressFcn for editing of entry widget without clicking set(Finter,'KeyPressFcn',[... 'spm_input(''!EditableKeyPressFcn'',',... 'findobj(gcf,''Tag'',''GUIinput_',int2str(YPos),''',',... '''Style'',''edit''),',... 'get(gcbf,''CurrentCharacter''))']) %-Wait for button press, process results %--------------------------------------------------------------- waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input objects cleared whilst waiting ',... 'for response: Bailing out!']), end p = get(hPrmpt,'UserData'); if ~ischar(p) k = p; p = Values(k,:); if ischar(p), p=deblank(p); end else Labels = strvcat(Labels,'specify...'); k = size(Labels,1); [p,msg] = sf_eEval(p,Type(2),1,m); while ischar(p) set(H,'Visible','off') h = uicontrol('Style','Text','String',msg,... 'Horizontalalignment','Center',... 'ForegroundColor','r',... 'BackgroundColor',COLOUR,... 'Tag',Tag,'Position',RRec); spm('Beep') pause(2), delete(h), set(H,'Visible','on') set(hPrmpt,'UserData','') waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input objects cleared ',... 'whilst waiting for response: Bailing out!']),end p = get(hPrmpt,'UserData'); if ischar(p), [p,msg] = sf_eEval(p,Type(2),1,m); end end end %-Clean up delete([H,hM]), set(Finter,'KeyPressFcn','') spm_input('!PointerJumpBack',PLoc,cF) %-Display answer uicontrol(Finter,'Style','Text',... 'String',num2str(p),... 'Tag',Tag,... 'Horizontalalignment','Center',... 'BackgroundColor',COLOUR,... 'Position',RRec); drawnow end % (if CmdLine) case 'm' %-Process menu type %======================================================================= nLabels = size(Labels,1); if ~isempty(DefItem) & ~any(DefItem==[1:nLabels]), DefItem=[]; end %-Process pull down menu type if CmdLine spm_input('!PrntPrmpt',Prompt) nLabels = size(Labels,1); for i = 1:nLabels, fprintf('\t%2d : %s\n',i,Labels(i,:)), end Prmpt = ['Menu choice (1-',int2str(nLabels),')']; if DefItem Prmpt=[Prmpt,' (Default: ',num2str(DefItem),')']; end %-Ask for user response %------------------------------------------------------- if nLabels==1 %-Only one choice - auto-pick & display k = 1; fprintf('Menu choice: 1 - %s\t(only option)',Labels) else k = input([Prmpt,' ? ']); if DefItem & isempty(k), k=DefItem; end while isempty(k) | ~any([1:nLabels]==k) if ~isempty(k),fprintf('%c\t!Out of range\n',7),end k = input([Prmpt,' ? ']); if DefItem & isempty(k), k=DefItem; end end end fprintf('\n') else Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets if nLabels==1 %-Only one choice - auto-pick k = 1; else Labs=[repmat(' ',nLabels,2),Labels]; if DefItem Labs(DefItem,1)='*'; H = uicontrol(Finter,'Style','Frame',... 'BackGroundColor','k',... 'ForeGroundColor','k',... 'Position',QRec+[-1,-1,+2,+2]); else H = []; end cb = ['if (get(gcbo,''Value'')>1),',... 'set(gcbo,''UserData'',''Selected''), end']; hPopUp = uicontrol(Finter,'Style','PopUp',... 'HorizontalAlignment','Left',... 'ForegroundColor','k',... 'BackgroundColor',COLOUR,... 'String',strvcat([Prompt,'...'],Labs),... 'Tag',Tag,... 'UserData',DefItem,... 'CallBack',cb,... 'Position',QRec); if TTips, set(hPopUp,'ToolTipString',['select with ',... 'mouse or type option number (1-',... num2str(nLabels),') & press return']), end %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPopUp,H]); %-Bring window to fore & jump pointer to menu widget [PLoc,cF] = spm_input('!PointerJump',RRec,Finter); %-Callback for KeyPresses cb=['spm_input(''!PullDownKeyPressFcn'',',... 'findobj(gcf,''Tag'',''',Tag,'''),',... 'get(gcf,''CurrentCharacter''))']; set(Finter,'KeyPressFcn',cb) %-Wait for menu selection %----------------------------------------------- waitfor(hPopUp,'UserData') if ~ishandle(hPopUp), error(['Input object cleared ',... 'whilst waiting for response: Bailing out!']),end k = get(hPopUp,'Value')-1; %-Clean up delete([H,hM]), set(Finter,'KeyPressFcn','') set(hPopUp,'Style','Text',... 'Horizontalalignment','Center',... 'String',deblank(Labels(k,:)),... 'BackgroundColor',COLOUR) spm_input('!PointerJumpBack',PLoc,cF) end %-Display answer uicontrol(Finter,'Style','Text',... 'String',deblank(Labels(k,:)),... 'Tag',Tag,... 'Horizontalalignment','Center',... 'BackgroundColor',COLOUR,... 'Position',QRec); drawnow end p = Values(k,:); if ischar(p), p=deblank(p); end otherwise, error('unrecognised type') end % (switch lower(Type) within case {'b','b|','y/n'}) %-Return response %----------------------------------------------------------------------- varargout = {p,YPos}; case {'m!','b!'} %-GUI PullDown/Buttons utility %======================================================================= % H = spm_input(Prompt,YPos,'p',Labels,cb,UD,XCB) %-Condition arguments if nargin<7, XCB = 0; else, XCB = varargin{7}; end if nargin<6, UD = []; else, UD = varargin{6}; end if nargin<5, cb = ''; else, cb = varargin{5}; end if nargin<4, Labels = []; else, Labels = varargin{4}; end if CmdLine, error('Can''t do CmdLine GUI utilities!'), end if isempty(cb), cb = 'disp(''(CallBack not set)'')'; end if ischar(cb), cb = cellstr(cb); end if length(cb)>1 & strcmp(lower(Type),'m!'), XCB=1; end if iscellstr(Labels), Labels=char(Labels); end %-Convert Labels "option" string to string matrix if required if any(Labels=='|') OptStr=Labels; BarPos=find([OptStr=='|',1]); Labels=OptStr(1:BarPos(1)-1); for Bar = 2:sum(OptStr=='|')+1 Labels=strvcat(Labels,OptStr(BarPos(Bar-1)+1:BarPos(Bar)-1)); end end %-Check #CallBacks if ~( length(cb)==1 | (length(cb)==size(Labels,1)) ) error('Labels & Callbacks size mismatch'), end %-Draw Prompt %----------------------------------------------------------------------- Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets if ~isempty(Prompt) uicontrol(Finter,'Style','Text',... 'String',Prompt,... 'Tag',Tag,... 'HorizontalAlignment','Right',... 'BackgroundColor',COLOUR,... 'Position',PRec) Rec = RRec; else Rec = QRec; end %-Sort out UserData for extended callbacks (handled by spm_input('!m_cb') %----------------------------------------------------------------------- if XCB, if iscell(UD), UD={UD}; end, UD = struct('UD',UD,'cb',{cb}); end %-Draw PullDown or Buttons %----------------------------------------------------------------------- switch lower(Type), case 'm!' if XCB, UD.cb=cb; cb = {'spm_input(''!m_cb'')'}; end H = uicontrol(Finter,'Style','PopUp',... 'HorizontalAlignment','Left',... 'ForegroundColor','k',... 'BackgroundColor',COLOUR,... 'String',Labels,... 'Tag',Tag,... 'UserData',UD,... 'CallBack',char(cb),... 'Position',Rec); case 'b!' nLabels = size(Labels,1); dX = Rec(3)/nLabels; H = []; for i=1:nLabels if length(cb)>1, tcb=cb(i); else, tcb=cb; end if XCB, UD.cb=tcb; tcb = {'spm_input(''!m_cb'')'}; end h = uicontrol(Finter,'Style','Pushbutton',... 'String',deblank(Labels(i,:)),... 'ToolTipString','',... 'Tag',Tag,... 'UserData',UD,... 'BackgroundColor',COLOUR,... 'Callback',char(tcb),... 'Position',[Rec(1)+(i-1)*dX+1 ... Rec(2) dX-2 Rec(4)]); H = [H,h]; end end %-Bring window to fore & jump pointer to menu widget [PLoc,cF] = spm_input('!PointerJump',RRec,Finter); varargout = {H}; case {'d','d!'} %-Display message %======================================================================= %-Condition arguments if nargin<4, Label=''; else, Label=varargin{4}; end if CmdLine & strcmp(lower(Type),'d') fprintf('\n +-%s%s+',Label,repmat('-',1,57-length(Label))) Prompt = [Prompt,' ']; while length(Prompt)>0 tmp = length(Prompt); if tmp>56, tmp=min([max(find(Prompt(1:56)==' ')),56]); end fprintf('\n | %s%s |',Prompt(1:tmp),repmat(' ',1,56-tmp)) Prompt(1:tmp)=[]; end fprintf('\n +-%s+\n',repmat('-',1,57)) elseif ~CmdLine if ~isempty(Label), Prompt = [Label,': ',Prompt]; end figure(Finter) %-Create text axes and edit control objects %--------------------------------------------------------------- h = uicontrol(Finter,'Style','Text',... 'String',Prompt(1:min(length(Prompt),56)),... 'FontWeight','bold',... 'Tag',['GUIinput_',int2str(YPos)],... 'HorizontalAlignment','Left',... 'ForegroundColor','k',... 'BackgroundColor',COLOUR,... 'UserData',Prompt,... 'Position',QRec); if length(Prompt)>56 pause(1) set(h,'ToolTipString',Prompt) spm_input('!dScroll',h) uicontrol(Finter,'Style','PushButton','String','>',... 'ToolTipString','press to scroll message',... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData',h,... 'CallBack',[... 'set(gcbo,''Visible'',''off''),',... 'spm_input(''!dScroll'',get(gcbo,''UserData'')),',... 'set(gcbo,''Visible'',''on'')'],... 'BackgroundColor',COLOUR,... 'Position',[QRec(1)+QRec(3)-10,QRec(2),15,QRec(4)]); end end if nargout>0, varargout={[],YPos}; end %======================================================================= % U T I L I T Y F U N C T I O N S %======================================================================= case '!colour' %======================================================================= % colour = spm_input('!Colour') varargout = {COLOUR}; case '!icond' %======================================================================= % [iCond,msg] = spm_input('!iCond',str,n,m) % Parse condition indicator spec strings: % '2 3 2 3', '0 1 0 1', '2323', '0101', 'abab', 'R A R A' if nargin<4, m=Inf; else, m=varargin{4}; end if nargin<3, n=NaN; else, n=varargin{3}; end if any(isnan(n(:))) n=Inf; elseif (length(n(:))==2 & ~any(n==1)) | length(n(:))>2 error('condition input can only do vectors') end if nargin<2, i=''; else, i=varargin{2}; end if isempty(i), varargout={[],'empty input'}; return, end msg = ''; i=i(:)'; if ischar(i) if i(1)=='0' & all(ismember(unique(i(:)),char(abs('0'):abs('9')))) %-Leading zeros in a digit list msg = sprintf('%s expanded',i); z = min(find([diff(i=='0'),1])); i = [zeros(1,z), spm_input('!iCond',i(z+1:end))']; else %-Try an eval, for functions & string #s i = evalin('base',['[',i,']'],'i'); end end if ischar(i) %-Evaluation error from above: see if it's an 'abab' or 'a b a b' type: [c,null,i] = unique(lower(i(~isspace(i)))); if all(ismember(c,char(abs('a'):abs('z')))) %-Map characters a-z to 1-26, but let 'r' be zero (rest) tmp = c-'a'+1; tmp(tmp=='r'-'a'+1)=0; i = tmp(i); msg = [sprintf('[%s] mapped to [',c),... sprintf('%d,',tmp(1:end-1)),... sprintf('%d',tmp(end)),']']; else i = '!'; msg = 'evaluation error'; end elseif ~all(floor(i(:))==i(:)) i = '!'; msg = 'must be integers'; elseif length(i)==1 & prod(n)>1 msg = sprintf('%d expanded',i); i = floor(i./10.^[floor(log10(i)+eps):-1:0]); i = i-[0,10*i(1:end-1)]; end %-Check size of i & #conditions if ~ischar(i), [i,msg] = sf_SzChk(i,n,msg); end if ~ischar(i) & isfinite(m) & length(unique(i))~=m i = '!'; msg = sprintf('%d conditions required',m); end varargout = {i,msg}; case '!inptconmen' %======================================================================= % hM = spm_input('!InptConMen',Finter,H) if nargin<3, H=[]; else, H=varargin{3}; end if nargin<2, varargout={[]}; else, Finter=varargin{2}; end hM = uicontextmenu('Parent',Finter); uimenu(hM,'Label','help on spm_input',... 'CallBack','spm_help(''spm_input.m'')') if ConCrash uimenu(hM,'Label','crash out','Separator','on',... 'CallBack','delete(get(gcbo,''UserData''))',... 'UserData',[hM,H]) end set(Finter,'UIContextMenu',hM) varargout={hM}; case '!cmdline' %======================================================================= % [CmdLine,YPos] = spm_input('!CmdLine',YPos) %-Sorts out whether to use CmdLine or not & canonicalises YPos if nargin<2, YPos=''; else, YPos=varargin{2}; end if isempty(YPos), YPos='+1'; end CmdLine = []; %-Special YPos specifications if ischar(YPos) if(YPos(1)=='!'), CmdLine=0; YPos(1)=[]; end elseif YPos==0 CmdLine=1; elseif YPos<0 CmdLine=0; YPos=-YPos; end CmdLine = spm('CmdLine',CmdLine); if CmdLine, YPos=0; end varargout = {CmdLine,YPos}; case '!getwin' %======================================================================= % Finter = spm_input('!GetWin',F) %-Locate (or create) figure to work in (Don't use 'Tag'ged figs) if nargin<2, F='Interactive'; else, F=varargin{2}; end Finter = spm_figure('FindWin',F); if isempty(Finter) if any(get(0,'Children')) if isempty(get(gcf,'Tag')), Finter = gcf; else, Finter = spm('CreateIntWin'); end else, Finter = spm('CreateIntWin'); end end varargout = {Finter}; case '!pointerjump' %======================================================================= % [PLoc,cF] = spm_input('!PointerJump',RRec,F,XDisp) %-Raise window & jump pointer over question if nargin<4, XDisp=[]; else, XDisp=varargin{4}; end if nargin<3, F='Interactive'; else, F=varargin{3}; end if nargin<2, error('Insufficient arguments'), else, RRec=varargin{2}; end F = spm_figure('FindWin',F); PLoc = get(0,'PointerLocation'); cF = get(0,'CurrentFigure'); if ~isempty(F) figure(F) FRec = get(F,'Position'); if isempty(XDisp), XDisp=RRec(3)*4/5; end if PJump, set(0,'PointerLocation',... floor([(FRec(1)+RRec(1)+XDisp), (FRec(2)+RRec(2)+RRec(4)/3)])); end end varargout = {PLoc,cF}; case '!pointerjumpback' %======================================================================= % spm_input('!PointerJumpBack',PLoc,cF) %-Replace pointer and reset CurrentFigure back if nargin<4, cF=[]; else, F=varargin{3}; end if nargin<2, error('Insufficient arguments'), else, PLoc=varargin{2}; end if PJump, set(0,'PointerLocation',PLoc), end cF = spm_figure('FindWin',cF); if ~isempty(cF), set(0,'CurrentFigure',cF); end case '!prntprmpt' %======================================================================= % spm_input('!PrntPrmpt',Prompt,TipStr,Title) %-Print prompt for CmdLine questioning if nargin<4, Title = ''; else, Title = varargin{4}; end if nargin<3, TipStr = ''; else, TipStr = varargin{3}; end if nargin<2, Prompt = ''; else, Prompt = varargin{2}; end if isempty(Prompt), Prompt='Enter an expression'; end Prompt = cellstr(Prompt); if ~isempty(TipStr) tmp = 8 + length(Prompt{end}) + length(TipStr); if tmp < 62 TipStr = sprintf('%s(%s)',repmat(' ',1,70-tmp),TipStr); else TipStr = sprintf('\n%s(%s)',repmat(' ',1,max(0,70-length(TipStr))),TipStr); end end if isempty(Title) fprintf('\n%s\n',repmat('~',1,72)) else fprintf('\n= %s %s\n',Title,repmat('~',1,72-length(Title)-3)) end fprintf('\t%s',Prompt{1}) for i=2:prod(size(Prompt)), fprintf('\n\t%s',Prompt{i}), end fprintf('%s\n%s\n',TipStr,repmat('~',1,72)) case '!inputrects' %======================================================================= % [Frec,QRec,PRec,RRec,Sz,Se] = spm_input('!InputRects',YPos,rec,F) if nargin<4, F='Interactive'; else, F=varargin{4}; end if nargin<3, rec=''; else, rec=varargin{3}; end if nargin<2, YPos=1; else, YPos=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F), error('Figure not found'), end Units = get(F,'Units'); set(F,'Units','pixels') FRec = get(F,'Position'); set(F,'Units',Units); Xdim = FRec(3); Ydim = FRec(4); WS = spm('WinScale'); Sz = round(22*min(WS)); %-Height Pd = Sz/2; %-Pad Se = 2*round(25*min(WS)/2); %-Seperation Yo = round(2*min(WS)); %-Y offset for responses a = 5.5/10; y = Ydim - Se*YPos; QRec = [Pd y Xdim-2*Pd Sz]; %-Question PRec = [Pd y floor(a*Xdim)-2*Pd Sz]; %-Prompt RRec = [ceil(a*Xdim) y+Yo floor((1-a)*Xdim)-Pd Sz]; %-Response % MRec = [010 y Xdim-50 Sz]; %-Menu PullDown % BRec = MRec + [Xdim-50+1, 0+1, 50-Xdim+30, 0]; %-Menu PullDown OK butt if ~isempty(rec) varargout = {eval(rec)}; else varargout = {FRec,QRec,PRec,RRec,Sz,Se}; end case '!deleteinputobj' %======================================================================= % spm_input('!DeleteInputObj',F) if nargin<2, F='Interactive'; else, F=varargin{2}; end h = spm_input('!FindInputObj',F); delete(h(h>0)) case {'!currentpos','!findinputobj'} %======================================================================= % [CPos,hCPos] = spm_input('!CurrentPos',F) % h = spm_input('!FindInputObj',F) % hPos contains handles: Columns contain handles corresponding to Pos if nargin<2, F='Interactive'; else, F=varargin{2}; end F = spm_figure('FindWin',F); %-Find tags and YPos positions of 'GUIinput_' 'Tag'ged objects H = []; YPos = []; for h = get(F,'Children')' tmp = get(h,'Tag'); if ~isempty(tmp) if strcmp(tmp(1:min(length(tmp),9)),'GUIinput_') H = [H, h]; YPos = [YPos, eval(tmp(10:end))]; end end end switch lower(Type), case '!findinputobj' varargout = {H}; case '!currentpos' if nargout<2 varargout = {max(YPos),[]}; elseif isempty(H) varargout = {[],[]}; else %-Sort out tmp = sort(YPos); CPos = tmp(find([1,diff(tmp)])); nPos = length(CPos); nPerPos = diff(find([1,diff(tmp),1])); hCPos = zeros(max(nPerPos),nPos); for i = 1:nPos hCPos(1:nPerPos(i),i) = H(YPos==CPos(i))'; end varargout = {CPos,hCPos}; end end case '!nextpos' %======================================================================= % [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine) %-Return next position to use if nargin<3, F='Interactive'; else, F=varargin{3}; end if nargin<2, YPos='+1'; else, YPos=varargin{2}; end if nargin<4, [CmdLine,YPos]=spm_input('!CmdLine',YPos); else, CmdLine=varargin{4}; end F = spm_figure('FindWin',F); %-Get current positions if nargout<3 CPos = spm_input('!CurrentPos',F); hCPos = []; else [CPos,hCPos] = spm_input('!CurrentPos',F); end if CmdLine NPos = 0; else MPos = spm_input('!MaxPos',F); if ischar(YPos) %-Relative YPos %-Strip any '!' prefix from YPos if(YPos(1)=='!'), YPos(1)=[]; end if strncmp(YPos,'_',1) %-YPos='_' means bottom YPos=eval(['MPos+',YPos(2:end)],'MPos'); else YPos = max([0,CPos])+eval(YPos); end else %-Absolute YPos YPos=abs(YPos); end NPos = min(max(1,YPos),MPos); end varargout = {NPos,CPos,hCPos}; case '!setnextpos' %======================================================================= % NPos = spm_input('!SetNextPos',YPos,F,CmdLine) %-Set next position to use if nargin<3, F='Interactive'; else, F=varargin{3}; end if nargin<2, YPos='+1'; else, YPos=varargin{2}; end if nargin<4, [CmdLine,YPos]=spm_input('!CmdLine',YPos); else, CmdLine=varargin{4}; end %-Find out which Y-position to use [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine); %-Delete any previous inputs using positions NPos and after if any(CPos>=NPos), h=hCPos(:,CPos>=NPos); delete(h(h>0)), end varargout = {NPos}; case '!maxpos' %======================================================================= % MPos = spm_input('!MaxPos',F,FRec3) % if nargin<3 if nargin<2, F='Interactive'; else, F=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F) FRec3=spm('WinSize','Interactive')*[0;0;0;1]; else %-Get figure size Units = get(F,'Units'); set(F,'Units','pixels') FRec3 = get(F,'Position')*[0;0;0;1]; set(F,'Units',Units); end end Se = round(25*min(spm('WinScale'))); MPos = floor((FRec3-5)/Se); varargout = {MPos}; case '!editablekeypressfcn' %======================================================================= % spm_input('!EditableKeyPressFcn',h,ch,hPrmpt) if nargin<2, error('Insufficient arguments'), else, h=varargin{2}; end if isempty(h), set(gcbf,'KeyPressFcn','','UserData',[]), return, end if nargin<3, ch=get(get(h,'Parent'),'CurrentCharacter'); else, ch=varargin{3};end if nargin<4, hPrmpt=get(h,'UserData'); else, hPrmpt=varargin{4}; end tmp = get(h,'String'); if isempty(tmp), tmp=''; end if iscellstr(tmp) & length(tmp)==1; tmp=tmp{:}; end if isempty(ch) %- shift / control / &c. pressed return elseif any(abs(ch)==[32:126]) %-Character if iscellstr(tmp), return, end tmp = [tmp, ch]; elseif abs(ch)==21 %- ^U - kill tmp = ''; elseif any(abs(ch)==[8,127]) %-BackSpace or Delete if iscellstr(tmp), return, end if length(tmp), tmp(length(tmp))=''; end elseif abs(ch)==13 %-Return pressed if ~isempty(tmp) set(hPrmpt,'UserData',get(h,'String')) end return else %-Illegal character return end set(h,'String',tmp) case '!buttonkeypressfcn' %======================================================================= % spm_input('!ButtonKeyPressFcn',h,Keys,DefItem,ch) %-Callback for KeyPress, to store valid button # in UserData of Prompt, % DefItem if (DefItem~=0) & return (ASCII-13) is pressed %-Condition arguments if nargin<2, error('Insufficient arguments'), else, h=varargin{2}; end if isempty(h), set(gcf,'KeyPressFcn','','UserData',[]), return, end if nargin<3, error('Insufficient arguments'); else, Keys=varargin{3}; end if nargin<4, DefItem=0; else, DefItem=varargin{4}; end if nargin<5, ch=get(gcf,'CurrentCharacter'); else, ch=varargin{5}; end if isempty(ch) %- shift / control / &c. pressed return elseif (DefItem & ch==13) But = DefItem; else But = find(lower(ch)==lower(Keys)); end if ~isempty(But), set(h,'UserData',But), end case '!pulldownkeypressfcn' %======================================================================= % spm_input('!PullDownKeyPressFcn',h,ch,DefItem) if nargin<2, error('Insufficient arguments'), else, h=varargin{2}; end if isempty(h), set(gcf,'KeyPressFcn',''), return, end if nargin<3, ch=get(get(h,'Parent'),'CurrentCharacter'); else, ch=varargin{3};end if nargin<4, DefItem=get(h,'UserData'); else, ch=varargin{4}; end Pmax = get(h,'Max'); Pval = get(h,'Value'); if Pmax==1, return, end if isempty(ch) %- shift / control / &c. pressed return elseif abs(ch)==13 if Pval==1 if DefItem, set(h,'Value',max(2,min(DefItem+1,Pmax))), end else set(h,'UserData','Selected') end elseif any(ch=='bpu') %-Move "b"ack "u"p to "p"revious entry set(h,'Value',max(2,Pval-1)) elseif any(ch=='fnd') %-Move "f"orward "d"own to "n"ext entry set(h,'Value',min(Pval+1,Pmax)) elseif any(ch=='123456789') %-Move to entry n set(h,'Value',max(2,min(eval(ch)+1,Pmax))) else %-Illegal character end case '!m_cb' %-CallBack handler for extended CallBack 'p'ullDown type %======================================================================= % spm_input('!m_cb') %-Get PopUp handle and value h = gcbo; n = get(h,'Value'); %-Get PopUp's UserData, check cb and UD fields exist, extract cb & UD tmp = get(h,'UserData'); if ~(isfield(tmp,'cb') & isfield(tmp,'UD')) error('Invalid UserData structure for spm_input extended callback') end cb = tmp.cb; UD = tmp.UD; %-Evaluate appropriate CallBack string (ignoring any return arguments) % NB: Using varargout={eval(cb{n})}; gives an error if the CallBack % has no return arguments! if length(cb)==1, eval(char(cb)); else, eval(cb{n}); end case '!dscroll' %======================================================================= % spm_input('!dScroll',h,Prompt) %-Scroll text in object h if nargin<2, return, else, h=varargin{2}; end if nargin<3, Prompt = get(h,'UserData'); else, Prompt=varargin{3}; end tmp = Prompt; if length(Prompt)>56 while length(tmp)>56 tic, while(toc<0.1), pause(0.05), end tmp(1)=[]; set(h,'String',tmp(1:min(length(tmp),56))) end pause(1) set(h,'String',Prompt(1:min(length(Prompt),56))) end otherwise %======================================================================= error(['Invalid type/action: ',Type]) %======================================================================= end % (case lower(Type)) %======================================================================= %- S U B - F U N C T I O N S %======================================================================= function [Keys,Labs] = sf_labkeys(Labels) %======================================================================= %-Make unique character keys for the Labels, ignoring case if nargin<1, error('insufficient arguments'), end if iscellstr(Labels), Labels = char(Labels); end if isempty(Labels), Keys=''; Labs=''; return, end Keys=Labels(:,1)'; nLabels = size(Labels,1); if any(~diff(abs(sort(lower(Keys))))) if nLabels<10 Keys = sprintf('%d',[1:nLabels]); elseif nLabels<=26 Keys = sprintf('%c',abs('a')+[0:nLabels-1]); else error('Too many buttons!') end Labs = Labels; else Labs = Labels(:,2:end); end function [p,msg] = sf_eEval(str,Type,n,m) %======================================================================= %-Evaluation and error trapping of typed input if nargin<4, m=[]; end if nargin<3, n=[]; end if nargin<2, Type='e'; end if nargin<1, str=''; end if isempty(str), p='!'; msg='empty input'; return, end switch lower(Type) case 's' p = str; msg = ''; case 'e' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; else [p,msg] = sf_SzChk(p,n); end case 'n' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif any(floor(p(:))~=p(:)|p(:)<1)|~isreal(p) p='!'; msg='natural number(s) required'; elseif ~isempty(m) & any(p(:)>m) p='!'; msg=['max value is ',num2str(m)]; else [p,msg] = sf_SzChk(p,n); end case 'w' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif any(floor(p(:))~=p(:)|p(:)<0)|~isreal(p) p='!'; msg='whole number(s) required'; elseif ~isempty(m) & any(p(:)>m) p='!'; msg=['max value is ',num2str(m)]; else [p,msg] = sf_SzChk(p,n); end case 'i' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif any(floor(p(:))~=p(:))|~isreal(p) p='!'; msg='integer(s) required'; else [p,msg] = sf_SzChk(p,n); end case 'p' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif length(setxor(p(:)',m)) p='!'; msg='invalid permutation'; else [p,msg] = sf_SzChk(p,n); end case 'r' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif ~isreal(p) p='!'; msg='real number(s) required'; elseif ~isempty(m) & ( max(p)>max(m) | min(p)<min(m) ) p='!'; msg=sprintf('real(s) in [%g,%g] required',min(m),max(m)); else [p,msg] = sf_SzChk(p,n); end case 'c' if isempty(m), m=Inf; end [p,msg] = spm_input('!iCond',str,n,m); case 'x' X = m; %-Design matrix/space-structure if isempty(n), n=1; end %-Sort out contrast matrix dimensions (contrast vectors in rows) if length(n)==1, n=[n,Inf]; else, n=reshape(n(1:2),1,2); end if ~isempty(X) % - override n(2) w/ design column dimension n(2) = spm_SpUtil('size',X,2); end p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; else if isfinite(n(2)) & size(p,2)<n(2) tmp = n(2) -size(p,2); p = [p, zeros(size(p,1),tmp)]; if size(p,1)>1, str=' columns'; else, str='s'; end msg = sprintf('right padded with %d zero%s',tmp,str); else msg = ''; end if size(p,2)>n(2) p='!'; msg=sprintf('too long - only %d prams',n(2)); elseif isfinite(n(1)) & size(p,1)~=n(1) p='!'; if n(1)==1, msg='vector required'; else, msg=sprintf('%d contrasts required',n(1)); end elseif ~isempty(X) & ~spm_SpUtil('allCon',X,p') p='!'; msg='invalid contrast'; end end otherwise error('unrecognised type'); end function str = sf_SzStr(n,l) %======================================================================= %-Size info string constuction if nargin<2, l=0; else, l=1; end if nargin<1, error('insufficient arguments'), end if isempty(n), n=NaN; end n=n(:); if length(n)==1, n=[n,1]; end, dn=length(n); if any(isnan(n)) | (prod(n)==1 & dn<=2) | (dn==2 & min(n)==1 & isinf(max(n))) str = ''; lstr = ''; elseif dn==2 & min(n)==1 str = sprintf('[%d]',max(n)); lstr = [str,'-vector']; elseif dn==2 & sum(isinf(n))==1 str = sprintf('[%d]',min(n)); lstr = [str,'-vector(s)']; else str=''; for i = 1:dn if isfinite(n(i)), str = sprintf('%s,%d',str,n(i)); else, str = sprintf('%s,*',str); end end str = ['[',str(2:end),']']; lstr = [str,'-matrix']; end if l, str=sprintf('\t%s',lstr); else, str=[str,' ']; end function [p,msg] = sf_SzChk(p,n,msg) %======================================================================= %-Size checking if nargin<3, msg=''; end if nargin<2, n=[]; end, if isempty(n), n=NaN; else, n=n(:)'; end if nargin<1, error('insufficient arguments'), end if ischar(p) | any(isnan(n(:))), return, end if length(n)==1, n=[n,1]; end dn = length(n); sp = size(p); dp = ndims(p); if dn==2 & min(n)==1 %-[1,1], [1,n], [n,1], [1,Inf], [Inf,1] - vector - allow transpose %--------------------------------------------------------------- i = min(find(n==max(n))); if n(i)==1 & max(sp)>1 p='!'; msg='scalar required'; elseif ndims(p)~=2 | ~any(sp==1) | ( isfinite(n(i)) & max(sp)~=n(i) ) %-error: Not2D | not vector | not right length if isfinite(n(i)), str=sprintf('%d-',n(i)); else, str=''; end p='!'; msg=[str,'vector required']; elseif sp(i)==1 & n(i)~=1 p=p'; msg=[msg,' (input transposed)']; end elseif dn==2 & sum(isinf(n))==1 %-[n,Inf], [Inf,n] - n vector(s) required - allow transposing %--------------------------------------------------------------- i = find(isfinite(n)); if ndims(p)~=2 | ~any(sp==n(i)) p='!'; msg=sprintf('%d-vector(s) required',min(n)); elseif sp(i)~=n p=p'; msg=[msg,' (input transposed)']; end else %-multi-dimensional matrix required - check dimensions %--------------------------------------------------------------- if ndims(p)~=dn | ~all( size(p)==n | isinf(n) ) p = '!'; msg=''; for i = 1:dn if isfinite(n(i)), msg = sprintf('%s,%d',msg,n(i)); else, msg = sprintf('%s,*',msg); end end msg = ['[',msg(2:end),']-matrix required']; end end %========================================================================== function uifocus(h) try if strcmpi(get(h, 'Style'), 'PushButton') == 1 uicontrol(gcbo); else uicontrol(h); end end
github
lcnhappe/happe-master
spm_write_sn.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_write_sn.m
20,195
utf_8
5bb2c4d938b07e035b1552465111fcf7
function VO = spm_write_sn(V,prm,flags,extras) % Write Out Warped Images. % FORMAT VO = spm_write_sn(V,matname,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. % prefix - Prefix for normalised images. Defaults to 'w'. % 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,matname,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. % %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ 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) && strcmpi(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,... 'prefix','w'); if nargin < 3, flags = def_flags; else fnms = fieldnames(def_flags); for i=1:length(fnms), if ~isfield(flags,fnms{i}), flags.(fnms{i}) = def_flags.(fnms{i}); end; end; end; [x,y,z,mat] = get_xyzmat(prm,flags.bb,flags.vox); if nargin==4, if ischar(extras) && strcmpi(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',numel(V),'Resampling','volumes/slices completed'); for i=1:numel(V), VO = make_hdr_struct(V(i),x,y,z,mat, flags.prefix); if flags.preserve VO.fname = prepend(VO.fname,'m'); end detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat); if flags.preserve, VO.pinfo(1:2,:) = VO.pinfo(1:2,:)/detAff; end; %Dat= zeros(VO.dim(1:3)); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; 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(1).mat*prm.Affine); dat = spm_bsplins(C,X2,Y2,Z2,d); if flags.preserve, dat = dat*detAff; end; dat(msk{j}) = NaN; Dat(:,:,j) = single(dat); if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; if nargout~=0, VO.pinfo = [1 0]'; VO.dt = [spm_type('float32') spm_platform('bigend')]; VO.dat = Dat; else spm_write_vol(VO, 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',numel(V),'Resampling','volumes completed'); for i=1:numel(V), VO = make_hdr_struct(V(i),x,y,z,mat, flags.prefix); if flags.preserve VO.fname = prepend(VO.fname,'m'); end detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat); % Accumulate data %Dat= zeros(VO.dim(1:3)); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; 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(1).mat*prm.Affine); dat = spm_bsplins(C,X2,Y2,Z2,d); dat(msk{j}) = NaN; if ~flags.preserve, Dat(:,:,j) = single(dat); 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 numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; if nargout==0, if flags.preserve, VO = rmfield(VO,'pinfo'); end VO = spm_write_vol(VO,Dat); else VO.pinfo = [1 0]'; VO.dt = [spm_type('float32') spm_platform('bigend')]; VO.dat = Dat; end; spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = modulate(V,prm) spm_progress_bar('Init',numel(V),'Modulating','volumes completed'); for i=1:numel(V), VO = V(i); VO = rmfield(VO,'pinfo'); VO.fname = prepend(VO.fname,'m'); detAff = det(prm.VF(1).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; [x,y,z,mat] = get_xyzmat(prm,NaN,NaN,VO); 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 numel(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 numel(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.dt = [spm_type('float32') spm_platform('bigend')]; 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,prefix) VO = V; VO.fname = prepend(V.fname,prefix); VO.mat = mat; VO.dim(1:3) = [length(x) length(y) length(z)]; VO.pinfo = V.pinfo; 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] = spm_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 = true(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 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 numel(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:numel(V), [X2,Y2,Z2] = mmult(X,Y,z(j),V(i).mat\prm.VF(1).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:numel(V), [X2,Y2,Z2] = mmult(X1,Y1,Z1,V(i).mat\prm.VF(1).mat*prm.Affine); Count = Count + getmask(X2,Y2,Z2,V(i).dim(1:3),wrap); end; end; msk{j} = uint32(find(Count ~= numel(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,VG) % 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); if nargin<4, VG = prm.VG(1); if all(~isfinite(bb(:))) && all(~isfinite(vox(:))), x = 1:VG.dim(1); y = 1:VG.dim(2); z = 1:VG.dim(3); mat = VG.mat; return; end end [bb0,vox0] = bbvox_from_V(VG); if ~all(isfinite(vox(:))), vox = vox0; end; if ~all(isfinite(bb(:))), bb = bb0; end; msk = find(vox<0); bb = sort(bb); bb(:,msk) = flipud(bb(:,msk)); % Adjust bounding box slightly - so it rounds to closest voxel. % Comment out if not needed. %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; % Again, chose whether to round to closest voxel. %of = -vox.*(round(-bb(1,:)./vox)+1); of = bb(1,:)-vox; 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; LEFTHANDED = true; if (LEFTHANDED && det(mat(1:3,1:3))>0) || (~LEFTHANDED && 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; %_______________________________________________________________________ %_______________________________________________________________________ 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 VO = write_dets(P,bb,vox) if nargin==1, job = P; P = job.P; bb = job.bb; vox = job.vox; end; spm_progress_bar('Init',numel(P),'Writing','volumes completed'); for i=1:numel(V), prm = load(deblank(P{i})); [x,y,z,mat] = get_xyzmat(prm,bb,vox); 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); 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'); [pth,nam,ext,nm] = spm_fileparts(P{i}); VO = struct('fname',fullfile(pth,['jy_' nam ext nm]),... 'dim',[numel(x),numel(y),numel(z)],... 'dt',[spm_type('float32') spm_platform('bigend')],... 'pinfo',[1 0 0]',... 'mat',mat,... 'n',1,... 'descrip','Jacobian determinants'); VO = spm_create_vol(VO); detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; 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); %---------------------------------------------------------------------------- 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 = (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff; Dat(:,:,j) = single(dat); if numel(P)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; VO = spm_write_vol(VO,Dat); spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %_______________________________________________________________________
github
lcnhappe/happe-master
spm_imatrix.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_imatrix.m
1,499
utf_8
295b97abf7200bfd1af63c3e32aae6fd
function P = spm_imatrix(M) % returns the parameters for creating an affine transformation % FORMAT P = spm_imatrix(M) % M - Affine transformation matrix % P - Parameters (see spm_matrix for definitions) %___________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner & Stefan Kiebel % $Id$ % Translations and zooms %----------------------------------------------------------------------- R = M(1:3,1:3); C = chol(R'*R); P = [M(1:3,4)' 0 0 0 diag(C)' 0 0 0]; if det(R)<0, P(7)=-P(7);end % Fix for -ve determinants % Shears %----------------------------------------------------------------------- C = diag(diag(C))\C; P(10:12) = C([4 7 8]); R0 = spm_matrix([0 0 0 0 0 0 P(7:12)]); R0 = R0(1:3,1:3); R1 = R/R0; % This just leaves rotations in matrix R1 %----------------------------------------------------------------------- %[ c5*c6, c5*s6, s5] %[-s4*s5*c6-c4*s6, -s4*s5*s6+c4*c6, s4*c5] %[-c4*s5*c6+s4*s6, -c4*s5*s6-s4*c6, c4*c5] P(5) = asin(rang(R1(1,3))); if (abs(P(5))-pi/2)^2 < 1e-9, P(4) = 0; P(6) = atan2(-rang(R1(2,1)), rang(-R1(3,1)/R1(1,3))); else c = cos(P(5)); P(4) = atan2(rang(R1(2,3)/c), rang(R1(3,3)/c)); P(6) = atan2(rang(R1(1,2)/c), rang(R1(1,1)/c)); end; return; % There may be slight rounding errors making b>1 or b<-1. function a = rang(b) a = min(max(b, -1), 1); return;
github
lcnhappe/happe-master
spm_affreg.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_affreg.m
20,248
utf_8
431e3807877742bdec89d07ce61e87f8
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). % %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ 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.(fnms{i}) = 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).^2>1e-8)), 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).^2>1e-8)), 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; WG(~isfinite(WG)) = 1; 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; WF(~isfinite(WF)) = 1; 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; wt(~isfinite(wt)) = 1; 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; wt(~isfinite(wt)) = 1; 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) 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 + A1'*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.',... 'The Check Reg utility will show you the initial',... 'alignment between the images, which must be',... 'within about 4cm and about 15 degrees in order',... 'for SPM to find the optimal solution.'}; spm('alert*',str,mfilename,sqrt(-1)); error('insufficient image overlap') %_______________________________________________________________________ %_______________________________________________________________________ function piccies(VF,VG,M,scal) % 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/spm8/spm_vol.m
5,475
utf_8
41a73601c2e44259fb8f1f4f3e870558
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 % V.dt - A 1x2 array. First element is datatype (see spm_type). % The second is 1 or 0 depending on the endian-ness. % 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. % % Note that spm_vol can also be applied to the filename(s) of 4-dim % volumes. In that case, the elements of V will point to a series of 3-dim % images. %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ if nargin==0, V = struct('fname', {},... 'dim', {},... 'dt', {},... 'pinfo', {},... 'mat', {},... 'n', {},... 'descrip', {},... 'private',{}); return; end; % 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:numel(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 isempty(P), V = []; return; end; counter = 0; for i=1:size(P,1), v = subfunc(P(i,:)); [V(counter+1:counter+size(v, 2),1).fname] = deal(''); [V(counter+1:counter+size(v, 2),1).mat] = deal([0 0 0 0]); [V(counter+1:counter+size(v, 2),1).mat] = deal(eye(4)); [V(counter+1:counter+size(v, 2),1).mat] = deal([1 0 0]'); 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(counter+1:counter+size(v,2),1).' f{j} '] = deal(v.' f{j} ');']); end counter = counter + size(v,2); end return; %_______________________________________________________________________ %_______________________________________________________________________ function V = subfunc(p) [pth,nam,ext,n1] = spm_fileparts(deblank(p)); p = fullfile(pth,[nam ext]); n = str2num(n1); if ~spm_existfile(p), %existance_error_message(p); error('File "%s" does not exist.', p); end switch ext, case {'.nii','.NII'}, % Do nothing case {'.img','.IMG'}, if ~spm_existfile(fullfile(pth,[nam '.hdr'])) && ~spm_existfile(fullfile(pth,[nam '.HDR'])), %existance_error_message(fullfile(pth,[nam '.hdr'])), error('File "%s" does not exist.', fullfile(pth,[nam '.hdr'])); end case {'.hdr','.HDR'}, ext = '.img'; p = fullfile(pth,[nam ext]); if ~spm_existfile(p), %existance_error_message(p), error('File "%s" does not exist.', p); end otherwise, error('File "%s" is not of a recognised type.', p); end if isempty(n), V = spm_vol_nifti(p); else V = spm_vol_nifti(p,n); end; if isempty(n) && length(V.private.dat.dim) > 3 V0(1) = V; for i = 2:V.private.dat.dim(4) V0(i) = spm_vol_nifti(p, i); end V = V0; end if ~isempty(V), return; 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; %_______________________________________________________________________ %_______________________________________________________________________ function existance_error_message(q) str = {... 'Unable to find file:',... [' ',spm_str_manip(q,'k40d')],... ' ',... 'Please check that it exists.'}; spm('alert*',str,mfilename,sqrt(-1)); return;
github
lcnhappe/happe-master
spm_jobman.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_jobman.m
21,324
utf_8
970b3aa24a514dea929b79722697efdc
function varargout = spm_jobman(varargin) % Main interface for SPM Batch System % This function provides a compatibility layer between SPM and matlabbatch. % It translates spm_jobman callbacks into matlabbatch callbacks and allows % to edit and run SPM5 style batch jobs. % % FORMAT job_id = spm_jobman % job_id = spm_jobman('interactive') % job_id = spm_jobman('interactive',job) % job_id = spm_jobman('interactive',job,node) % job_id = spm_jobman('interactive','',node) % Runs the user interface in interactive mode. The job_id can be used to % manipulate this job in cfg_util. Note that changes to the job in cfg_util % will not show up in cfg_ui unless 'Update View' is called. % % FORMAT output_list = spm_jobman('serial') % output_list = spm_jobman('serial',job[,'', input1,...inputN]) % output_list = spm_jobman('serial',job ,node[,input1,...inputN]) % output_list = spm_jobman('serial','' ,node[,input1,...inputN]) % Runs the user interface in serial mode. I job is not empty, then node % is silently ignored. Inputs can be a list of arguments. These are % passed on to the open inputs of the specified job/node. Each input should % be suitable to be assigned to item.val{1}. For cfg_repeat/cfg_choice % items, input should be a cell list of indices input{1}...input{k} into % item.value. See cfg_util('filljob',...) for details. % % FORMAT output_list = spm_jobman('run',job) % output_list = spm_jobman('run_nogui',job) % Runs a job without X11 (as long as there is no graphics output from the % job itself). The matlabbatch system does not need graphics output to run % a job. % % node - indicates which part of the configuration is to be used. % For example, it could be 'jobs.spatial.coreg'. % % job - can be the name of a jobfile (as a .m, .mat or a .xml), a % cellstr of filenames, a 'jobs'/'matlabbatch' variable or a % cell of 'jobs'/'matlabbatch' variables loaded from a jobfile. % % Output_list is a cell array and contains the output arguments from each % module in the job. The format and contents of these outputs is defined in % the configuration of each module (.prog and .vout callbacks). % % FORMAT spm_jobman('initcfg') % Initialise cfg_util configuration and set path accordingly. % % FORMAT jobs = spm_jobman('spm5tospm8',jobs) % Takes a cell list of SPM5 job structures and returns SPM8 compatible versions. % % FORMAT job = spm_jobman('spm5tospm8bulk',jobfiles) % Takes a cell string with SPM5 job filenames and saves them in SPM8 % compatible format. The new job files will be MATLAB .m files. Their % filenames will be derived from the input filenames. To make sure they are % valid MATLAB script names they will be processed with % genvarname(filename) and have a '_spm8' string appended to their % filename. % % FORMAT spm_jobman('help',node) % spm_jobman('help',node,width) % Creates a cell array containing help information. This is justified % to be 'width' characters wide. e.g. % h = spm_jobman('help','jobs.spatial.coreg.estimate'); % for i=1:numel(h),fprintf('%s\n',h{i}); end; % % not implemented: FORMAT spm_jobman('defaults') % Runs the interactive defaults editor. % % FORMAT [tag, job] = spm_jobman('harvest', job_id|cfg_item|cfg_struct) % Take the job with id job_id in cfg_util and extract what is % needed to save it as a batch job (for experts only). If the argument is a % cfg_item or cfg_struct tree, it will be harvested outside cfg_util. % tag - tag of the root node of the current job/cfg_item tree % job - harvested data from the current job/cfg_item tree % % FORMAT spm_jobman('pulldown') % Creates a pulldown 'TASKS' menu in the Graphics window. % % not implemented: FORMAT spm_jobman('jobhelp') % Creates a cell array containing help information specific for a certain % job. Help is only printed for items where job specific help is % present. This can be used together with spm_jobman('help') to create a % job specific manual. This feature is available only on MATLAB R14SP2 % and higher. % % not implemented: FORMAT spm_jobman('chmod') % Changes the modality for the TASKS pulldown. % % This code is based on earlier versions by John Ashburner, Philippe % Ciuciu and Guillaume Flandin. %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Copyright (C) 2008 Freiburg Brain Imaging % Volkmar Glauche % $Id$ if nargin==0 h = cfg_ui; if nargout > 0, varargout = {h}; end else cmd = lower(varargin{1}); if any(strcmp(cmd, {'serial','interactive','run','run_nogui'})) if nargin > 1 % sort out job/node arguments for interactive, serial, run cmds if nargin>=2 && ~isempty(varargin{2}) % do not consider node if job is given if ischar(varargin{2}) || iscellstr(varargin{2}) jobs = load_jobs(varargin{2}); elseif iscell(varargin{2}) if iscell(varargin{2}{1}) % assume varargin{2} is a cell of jobs jobs = varargin{2}; else % assume varargin{2} is a single job jobs{1} = varargin{2}; end; end; [mljob comp] = canonicalise_job(jobs); elseif any(strcmp(cmd, {'interactive','serial'})) && nargin>=3 && isempty(varargin{2}) % Node spec only allowed for 'interactive', 'serial' arg3 = regexprep(varargin{3},'^spmjobs\.','spm.'); mod_cfg_id = cfg_util('tag2mod_cfg_id',arg3); else error('spm:spm_jobman:WrongUI', ... 'Don''t know how to handle this ''%s'' call.', lower(varargin{1})); end; end end; switch cmd case 'help' if (nargin < 2) || isempty(varargin{2}) node = 'spm'; else node = regexprep(varargin{2},'^spmjobs\.','spm.'); end; if nargin < 3 width = 60; else width = varargin{3}; end; varargout{1} = cfg_util('showdocwidth', width, node); case 'initcfg' if ~isdeployed addpath(fullfile(spm('Dir'),'matlabbatch')); addpath(fullfile(spm('Dir'),'config')); end cfg_get_defaults('cfg_util.genscript_run', @genscript_run); cfg_util('initcfg'); % This must be the first call to cfg_util if ~spm('cmdline') f = cfg_ui('Visible','off'); % Create invisible batch ui f0 = findobj(f, 'Tag','MenuFile'); % Add entries to file menu f2 = uimenu(f0,'Label','Load SPM5 job', 'Callback',@load_job, ... 'HandleVisibility','off', 'tag','jobs', ... 'Separator','on'); f3 = uimenu(f0,'Label','Bulk Convert SPM5 job(s)', ... 'Callback',@conv_jobs, ... 'HandleVisibility','off', 'tag','jobs'); end case 'interactive', if exist('mljob', 'var') cjob = cfg_util('initjob', mljob); elseif exist('mod_cfg_id', 'var') if isempty(mod_cfg_id) arg3 = regexprep(varargin{3},'^spmjobs\.','spm.'); warning('spm:spm_jobman:NodeNotFound', ... ['Can not find executable node ''%s'' - running '... 'matlabbatch without default node.'], arg3); cjob = cfg_util('initjob'); else cjob = cfg_util('initjob'); mod_job_id = cfg_util('addtojob', cjob, mod_cfg_id); cfg_util('harvest', cjob, mod_job_id); end; else cjob = cfg_util('initjob'); end; cfg_ui('local_showjob', findobj(0,'tag','cfg_ui'), cjob); if nargout > 0 varargout{1} = cjob; end; case 'serial', if exist('mljob', 'var') cjob = cfg_util('initjob', mljob); else cjob = cfg_util('initjob'); if nargin > 2 arg3 = regexprep(varargin{3},'^spmjobs\.','spm.'); [mod_cfg_id, item_mod_id] = cfg_util('tag2cfg_id', lower(arg3)); cfg_util('addtojob', cjob, mod_cfg_id); end; end; sts = cfg_util('filljobui', cjob, @serial_ui, varargin{4:end}); if sts cfg_util('run', cjob); if nargout > 0 varargout{1} = cfg_util('getalloutputs', cjob); end end; cfg_util('deljob', cjob); case {'run','run_nogui'} cjob = cfg_util('initjob', mljob); cfg_util('run', cjob); if nargout > 0 varargout{1} = cfg_util('getalloutputs', cjob); end cfg_util('deljob', cjob); case {'spm5tospm8'} varargout{1} = canonicalise_job(varargin{2}); case {'spm5tospm8bulk'} conv_jobs(varargin{2}); case {'defaults'}, warning('spm:spm_jobman:NotImplemented', 'Not yet implemented.'); case {'pulldown'} pulldown; case {'chmod'} warning('spm:spm_jobman:NotImplemented', 'Callback ''%s'' not implemented.', varargin{1}); case {'help'} warning('spm:spm_jobman:NotImplemented', 'Not yet implemented.'); case {'jobhelp'} warning('spm:spm_jobman:NotImplemented', 'Callback ''%s'' not implemented.', varargin{1}); case {'harvest'} if nargin == 1 error('spm:spm_jobman:CantHarvest', ... ['Can not harvest job without job_id. Please use ' ... 'spm_jobman(''harvest'', job_id).']); elseif cfg_util('isjob_id', varargin{2}) [tag job] = cfg_util('harvest', varargin{2}); elseif isa(varargin{2}, 'cfg_item') [tag job] = harvest(varargin{2}, varargin{2}, false, false); elseif isstruct(varargin{2}) % try to convert into class before harvesting c = cfg_struct2cfg(varargin{2}); [tag job] = harvest(c,c,false,false); else error('spm:spm_jobman:CantHarvestThis', ['Can not harvest ' ... 'this argument.']); end; varargout{1} = tag; varargout{2} = job; otherwise error(['"' varargin{1} '" - unknown option']); end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [mljob, comp] = canonicalise_job(job) % job: a cell list of job data structures. % Check whether job is a SPM5 or matlabbatch job. In the first case, all % items in job{:} should have a fieldname of either 'temporal', 'spatial', % 'stats', 'tools' or 'util'. If this is the case, then job will be % assigned to mljob{1}.spm, which is the tag of the SPM root % configuration item. comp = true(size(job)); mljob = cell(size(job)); for cj = 1:numel(job) for k = 1:numel(job{cj}) comp(cj) = comp(cj) && any(strcmp(fieldnames(job{cj}{k}), ... {'temporal', 'spatial', 'stats', 'tools', 'util'})); if ~comp(cj) break; end; end; if comp(cj) tmp = convert_jobs(job{cj}); for i=1:numel(tmp), mljob{cj}{i}.spm = tmp{i}; end else mljob{cj} = job{cj}; end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function conv_jobs(varargin) % Select a list of jobs, canonicalise each of it and save as a .m file % using gencode. spm('pointer','watch'); if nargin == 0 || ~iscellstr(varargin{1}) [fname sts] = spm_select([1 Inf], 'batch', 'Select job file(s)'); fname = cellstr(fname); if ~sts, return; end; else fname = varargin{1}; end; joblist = load_jobs(fname); for k = 1:numel(fname) if ~isempty(joblist{k}) [p n e v] = spm_fileparts(fname{k}); % Save new job as genvarname(*_spm8).m newfname = fullfile(p, sprintf('%s.m', ... genvarname(sprintf('%s_spm8', n)))); fprintf('SPM5 job: %s\nSPM8 job: %s\n', fname{k}, newfname); cjob = cfg_util('initjob', canonicalise_job(joblist(k))); cfg_util('savejob', cjob, newfname); cfg_util('deljob', cjob); end; end; spm('pointer','arrow'); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function load_job(varargin) % Select a single job file, canonicalise it and display it in GUI [fname sts] = spm_select([1 Inf], 'batch', 'Select job file'); if ~sts, return; end; spm('pointer','watch'); joblist = load_jobs(fname); if ~isempty(joblist{1}) spm_jobman('interactive',joblist{1}); end; spm('pointer','arrow'); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function newjobs = load_jobs(job) % Load a list of possible job files, return a cell list of jobs. Jobs can % be either SPM5 (i.e. containing a 'jobs' variable) or SPM8/matlabbatch % jobs. If a job file failed to load, an empty cell is returned in the % list. if ischar(job) filenames = cellstr(job); else filenames = job; end; newjobs = {}; for cf = 1:numel(filenames) [p,nam,ext] = fileparts(filenames{cf}); switch ext case '.xml', spm('Pointer','Watch'); try loadxml(filenames{cf},'jobs'); catch try loadxml(filenames{cf},'matlabbatch'); catch warning('spm:spm_jobman:LoadFailed','LoadXML failed: ''%s''',filenames{cf}); end; end; spm('Pointer'); case '.mat' try S=load(filenames{cf}); if isfield(S,'matlabbatch') matlabbatch = S.matlabbatch; elseif isfield(S,'jobs') jobs = S.jobs; else warning('spm:spm_jobman:JobNotFound','No SPM5/SPM8 job found in ''%s''', filenames{cf}); end catch warning('spm:spm_jobman:LoadFailed','Load failed: ''%s''',filenames{cf}); end; case '.m' try fid = fopen(filenames{cf},'rt'); str = fread(fid,'*char'); fclose(fid); eval(str); catch warning('spm:spm_jobman:LoadFailed','Load failed: ''%s''',filenames{cf}); end; if ~(exist('jobs','var') || exist('matlabbatch','var')) warning('spm:spm_jobman:JobNotFound','No SPM5/SPM8 job found in ''%s''', filenames{cf}); end; otherwise warning('Unknown extension: ''%s''', filenames{cf}); end; if exist('jobs','var') newjobs = [newjobs(:); {jobs}]; clear jobs; elseif exist('matlabbatch','var') newjobs = [newjobs(:); {matlabbatch}]; clear matlabbatch; end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function njobs = convert_jobs(jobs) decel = struct('spatial',struct('realign',[],'coreg',[],'normalise',[]),... 'temporal',[],... 'stats',[],... 'meeg',[],... 'util',[],... 'tools',struct('dartel',[])); njobs = {}; for i0 = 1:numel(jobs), tmp0 = fieldnames(jobs{i0}); tmp0 = tmp0{1}; if any(strcmp(tmp0,fieldnames(decel))), for i1=1:numel(jobs{i0}.(tmp0)), tmp1 = fieldnames(jobs{i0}.(tmp0){i1}); tmp1 = tmp1{1}; if ~isempty(decel.(tmp0)), if any(strcmp(tmp1,fieldnames(decel.(tmp0)))), for i2=1:numel(jobs{i0}.(tmp0){i1}.(tmp1)), njobs{end+1} = struct(tmp0,struct(tmp1,jobs{i0}.(tmp0){i1}.(tmp1){i2})); end else njobs{end+1} = struct(tmp0,jobs{i0}.(tmp0){i1}); end else njobs{end+1} = struct(tmp0,jobs{i0}.(tmp0){i1}); end end else njobs{end+1} = jobs{i0}; end end %------------------------------------------------------------------------ %------------------------------------------------------------------------ function pulldown fg = spm_figure('findwin','Graphics'); if isempty(fg), return; end; set(0,'ShowHiddenHandles','on'); delete(findobj(fg,'tag','jobs')); set(0,'ShowHiddenHandles','off'); f0 = uimenu(fg,'Label','TASKS', ... 'HandleVisibility','off', 'tag','jobs'); f1 = uimenu(f0,'Label','BATCH', 'Callback',@cfg_ui, ... 'HandleVisibility','off', 'tag','jobs'); f4 = uimenu(f0,'Label','SPM (interactive)', ... 'HandleVisibility','off', 'tag','jobs', 'Separator','on'); cfg_ui('local_setmenu', f4, cfg_util('tag2cfg_id', 'spm'), ... @local_init_interactive, false); f5 = uimenu(f0,'Label','SPM (serial)', ... 'HandleVisibility','off', 'tag','jobs'); cfg_ui('local_setmenu', f5, cfg_util('tag2cfg_id', 'spm'), ... @local_init_serial, false); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function local_init_interactive(varargin) cjob = cfg_util('initjob'); mod_cfg_id = get(gcbo,'userdata'); cfg_util('addtojob', cjob, mod_cfg_id); cfg_ui('local_showjob', findobj(0,'tag','cfg_ui'), cjob); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function local_init_serial(varargin) mod_cfg_id = get(gcbo,'userdata'); cjob = cfg_util('initjob'); cfg_util('addtojob', cjob, mod_cfg_id); sts = cfg_util('filljobui', cjob, @serial_ui); if sts cfg_util('run', cjob); end; cfg_util('deljob', cjob); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [val sts] = serial_ui(item) % wrapper function to translate cfg_util('filljobui'... input requests into % spm_input/cfg_select calls. sts = true; switch class(item), case 'cfg_choice', labels = cell(size(item.values)); values = cell(size(item.values)); for k = 1:numel(item.values) labels{k} = item.values{k}.name; values{k} = k; end; val = spm_input(item.name, 1, 'm', labels, values); case 'cfg_menu', val = spm_input(item.name, 1, 'm', item.labels, item.values); val = val{1}; case 'cfg_repeat', labels = cell(size(item.values)); values = cell(size(item.values)); for k = 1:numel(item.values) labels{k} = item.values{k}.name; values{k} = k; end; % enter at least item.num(1) values for k = 1:item.num(1) val(k) = spm_input(sprintf('%s(%d)', item.name, k), 1, 'm', ... labels, values); end; % enter more (up to varargin{3}(2) values labels = {labels{:} 'Done'}; % values is a cell list of natural numbers, use -1 for Done values = {values{:} -1}; while numel(val) < item.num(2) val1 = spm_input(sprintf('%s(%d)', item.name, numel(val)+1), 1, ... 'm', labels, values); if val1{1} == -1 break; else val(end+1) = val1; end; end; case 'cfg_entry', val = spm_input(item.name, 1, item.strtype, '', item.num, ... item.extras); case 'cfg_files', [t,sts] = cfg_getfile(item.num, item.filter, item.name, '', ... item.dir, item.ufilter); if sts val = cellstr(t); else val = {}; error('File selector was closed.'); end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [code cont] = genscript_run % Return code snippet to initialise SPM defaults and run a job generated by % cfg_util('genscript',...) through spm_jobman. modality = spm('CheckModality'); code{1} = sprintf('spm(''defaults'', ''%s'');', modality); code{2} = 'spm_jobman(''serial'', jobs, '''', inputs{:});'; cont = false;
github
lcnhappe/happe-master
spm_eeg_inv_vbecd_disp.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_eeg_inv_vbecd_disp.m
22,913
UNKNOWN
d298cddd05dcda0aab1c23b6a9f98906
function spm_eeg_inv_vbecd_disp(action,varargin) % Display the dipoles as obtained from VB-ECD % % FORMAT spm_eeg_inv_vbecd_disp('Init',D) % Display the latest VB-ECD solution saved in the .inv{} field of the % data structure D. % % FORMAT spm_eeg_inv_vbecd_disp('Init',D, ind) % Display the ind^th .inv{} cell element, if it is actually a VB-ECD % solution. %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Christophe Phillips % $Id$ % Note: % unfortunately I cannot see how to ensure that when zooming in the image % the dipole location stays in place... global st Fig = spm_figure('GetWin','Graphics'); colors = {'y','b','g','r','c','m'}; % 6 possible colors marker = {'o','x','+','*','s','d','v','p','h'}; % 9 possible markers Ncolors = length(colors); Nmarker = length(marker); if nargin == 0, action = 'Init'; end; switch lower(action), %========================================================================== case 'init' %========================================================================== % FORMAT spm_eeg_inv_vbecd_disp('init',D,ind) % Initialise the variables with GUI %-------------------------------------------------------------------------- if nargin<2 D = spm_eeg_load; else D = varargin{1}; end if nargin<3 % find the latest inverse produced with vbecd Ninv = length(D.inv); lind = []; for ii=1:Ninv if isfield(D.inv{ii},'method') && ... strcmp(D.inv{ii}.method,'vbecd') lind = [lind ii]; end end ind = max(lind); if ~ind, spm('alert*','No VB-ECD solution found with this data file!',... 'VB-ECD display') return end else ind = varargin{3}; end % Stash dipole(s) information in sdip structure sdip = D.inv{ind}.inverse; % if the exit flag is not in the structure, assume everything went ok. if ~isfield(sdip,'exitflag') sdip.exitflag = ones(1,sdip.n_seeds); end try Pimg = spm_vol(D.inv{ind}.mesh.sMRI); catch Pimg = spm_vol(fullfile(spm('dir'), 'canonical', 'single_subj_T1.nii')); end spm_orthviews('Reset'); spm_orthviews('Image', Pimg, [0.0 0.45 1 0.55]); spm_orthviews('MaxBB'); spm_orthviews('AddContext') st.callback = 'spm_image(''shopos'');'; % remove clicking in image for ii=1:3, set(st.vols{1}.ax{ii}.ax,'ButtonDownFcn',';'); end WS = spm('WinScale'); % Build GUI %========================================================================== % Location: %-------------------------------------------------------------------------- uicontrol(Fig,'Style','Frame','Position',[60 25 200 325].*WS, ... 'DeleteFcn','spm_image(''reset'');'); uicontrol(Fig,'Style','Frame','Position',[70 250 180 90].*WS); uicontrol(Fig,'Style','Text', 'Position',[75 320 170 016].*WS, ... 'String','Current Position'); uicontrol(Fig,'Style','Text', 'Position',[75 295 35 020].*WS,'String','mm:'); uicontrol(Fig,'Style','Text', 'Position',[75 275 35 020].*WS,'String','vx:'); uicontrol(Fig,'Style','Text', 'Position',[75 255 75 020].*WS,'String','Img Intens.:'); st.mp = uicontrol(Fig,'Style','Text', 'Position',[110 295 135 020].*WS,'String',''); st.vp = uicontrol(Fig,'Style','Text', 'Position',[110 275 135 020].*WS,'String',''); st.in = uicontrol(Fig,'Style','Text', 'Position',[150 255 85 020].*WS,'String',''); c = 'if get(gco,''Value'')==1, spm_orthviews(''Xhairs'',''off''), else, spm_orthviews(''Xhairs'',''on''); end;'; uicontrol(Fig,'Style','togglebutton','Position',[95 220 125 20].*WS,... 'String','Hide Crosshairs','Callback',c,'ToolTipString','show/hide crosshairs'); % Dipoles/seeds selection: %-------------------------------------------------------------------------- uicontrol(Fig,'Style','Frame','Position',[300 25 180 325].*WS); sdip.hdl.hcl = uicontrol(Fig,'Style','pushbutton','Position',[310 320 100 20].*WS, ... 'String','Clear all','CallBack','spm_eeg_inv_vbecd_disp(''ClearAll'')'); sdip.hdl.hseed=zeros(sdip.n_seeds,1); for ii=1:sdip.n_seeds if sdip.exitflag(ii)==1 sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','togglebutton','String',num2str(ii),... 'Position',[310+rem(ii-1,8)*20 295-fix((ii-1)/8)*20 20 20].*WS,... 'CallBack','spm_eeg_inv_vbecd_disp(''ChgSeed'')'); else sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','Text','String',num2str(ii), ... 'Position',[310+rem(ii-1,8)*20 293-fix((ii-1)/8)*20 20 20].*WS) ; end end uicontrol(Fig,'Style','text','String','Select dipole # :', ... 'Position',[310 255-fix((sdip.n_seeds-1)/8)*20 110 20].*WS); txt_box = cell(sdip.n_dip,1); for ii=1:sdip.n_dip, txt_box{ii} = num2str(ii); end txt_box{sdip.n_dip+1} = 'all'; sdip.hdl.hdip = uicontrol(Fig,'Style','popup','String',txt_box, ... 'Position',[420 258-fix((sdip.n_seeds-1)/8)*20 40 20].*WS, ... 'Callback','spm_eeg_inv_vbecd_disp(''ChgDip'')'); % Dipoles orientation and strength: %-------------------------------------------------------------------------- uicontrol(Fig,'Style','Frame','Position',[70 120 180 90].*WS); uicontrol(Fig,'Style','Text', 'Position',[75 190 170 016].*WS, ... 'String','Dipole orientation & strength'); uicontrol(Fig,'Style','Text', 'Position',[75 165 65 020].*WS, ... 'String','x-y-z or.:'); uicontrol(Fig,'Style','Text', 'Position',[75 145 75 020].*WS, ... 'String','theta-phi or.:'); uicontrol(Fig,'Style','Text', 'Position',[75 125 75 020].*WS, ... 'String','Dip. intens.:'); sdip.hdl.hor1 = uicontrol(Fig,'Style','Text', 'Position', ... [140 165 105 020].*WS,'String','a'); sdip.hdl.hor2 = uicontrol(Fig,'Style','Text', 'Position', ... [150 145 85 020].*WS,'String','b'); sdip.hdl.int = uicontrol(Fig,'Style','Text', 'Position', ... [150 125 85 020].*WS,'String','c'); st.vols{1}.sdip = sdip; % First plot = all the seeds that converged ! l_conv = find(sdip.exitflag==1); if isempty(l_conv) error('No seed converged towards a stable solution, nothing to be displayed !') else spm_eeg_inv_vbecd_disp('DrawDip',l_conv,1) set(sdip.hdl.hseed(l_conv),'Value',1); % toggle all buttons end %========================================================================== case 'drawdip' %========================================================================== % FORMAT spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip,sdip) % e.g. spm_eeg_inv_vbecd_disp('DrawDip',1,1,sdip) % e.g. spm_eeg_inv_vbecd_disp('DrawDip',[1:5],1,sdip) %-------------------------------------------------------------------------- if nargin < 2 i_seed = 1; else i_seed = varargin{1}; end if nargin<3 i_dip = 1; else i_dip = varargin{2}; end if nargin<4 if isfield(st.vols{1},'sdip') sdip = st.vols{1}.sdip; else error('I can''t find sdip structure'); end else sdip = varargin{3}; st.vols{1}.sdip = sdip; end if any(i_seed>sdip.n_seeds) || i_dip>(sdip.n_dip+1) error('Wrong i_seed or i_dip index in spm_eeg_inv_vbecd_disp'); end % Note if i_dip==(sdip.n_dip+1) all dipoles are displayed simultaneously, % The 3D cut will then be at the mean location of all sources !!! if i_dip == (sdip.n_dip+1) i_dip = 1:sdip.n_dip; end % if seed indexes passed is wrong (no convergence) remove the wrong ones i_seed(sdip.exitflag(i_seed)~=1) = []; if isempty(i_seed) error('You passed the wrong seed indexes...') end if size(i_seed,2)==1, i_seed=i_seed'; end % Display business %-------------------------------------------------------------------------- loc_mm = sdip.loc{i_seed(1)}(:,i_dip); if length(i_seed)>1 % unit = ones(1,sdip.n_dip); for ii = i_seed(2:end) loc_mm = loc_mm + sdip.loc{ii}(:,i_dip); end loc_mm = loc_mm/length(i_seed); end if length(i_dip)>1 loc_mm = mean(loc_mm,2); end % Place the underlying image at right cuts spm_orthviews('Reposition',loc_mm); if length(i_dip)>1 tabl_seed_dip = [kron(ones(length(i_dip),1),i_seed') ... kron(i_dip',ones(length(i_seed),1))]; else tabl_seed_dip = [i_seed' ones(length(i_seed),1)*i_dip]; end % Scaling, according to all dipoles in the selected seed sets. % The time displayed is the one corresponding to the maximum EEG power ! Mn_j = -1; l3 = -2:0; for ii = 1:length(i_seed) for jj = 1:sdip.n_dip Mn_j = max([Mn_j sqrt(sum(sdip.j{ii}(jj*3+l3,sdip.Mtb).^2))]); end end st.vols{1}.sdip.tabl_seed_dip = tabl_seed_dip; % Display all dipoles, the 1st one + the ones close enough. % Run through the 6 colors and 9 markers to differentiate the dipoles. % NOTA: 2 dipoles coming from the same set will have same colour/marker ind = 1 ; dip_h = zeros(9,size(tabl_seed_dip,1),1); % each dipole displayed has 9 handles: % 3 per view (2*3): for the line, for the circle & for the error js_m = zeros(3,1); % Deal with case of multiple i_seed and i_dip displayed. % make sure dipole from same i_seed have same colour but different marker. pi_dip = find(diff(tabl_seed_dip(:,2))); if isempty(pi_dip) % i.e. only one dip displayed per seed, use old fashion for ii=1:size(tabl_seed_dip,1) if ii>1 if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1) ind = ind+1; end end ic = mod(ind-1,Ncolors)+1; im = fix(ind/Ncolors)+1; loc_pl = sdip.loc{tabl_seed_dip(ii,1)}(:,tabl_seed_dip(ii,2)); js = sdip.j{tabl_seed_dip(ii,1)}(tabl_seed_dip(ii,2)*3+l3,sdip.Mtb); vloc = sdip.cov_loc{tabl_seed_dip(ii,1)}(tabl_seed_dip(ii,2)*3+l3,tabl_seed_dip(ii,2)*3+l3); dip_h(:,ii) = add1dip(loc_pl,js/Mn_j*20,vloc, ... marker{im},colors{ic},st.vols{1}.ax,Fig,st.bb); js_m = js_m+js; end else for ii=1:pi_dip(1) if ii>1 if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1) ind = ind+1; end end ic = mod(ind-1,Ncolors)+1; for jj=1:sdip.n_dip im = mod(jj-1,Nmarker)+1; loc_pl = sdip.loc{tabl_seed_dip(ii,1)}(:,jj); js = sdip.j{tabl_seed_dip(ii,1)}(jj*3+l3,sdip.Mtb); vloc = sdip.cov_loc{tabl_seed_dip(ii,1)}(jj*3+l3,jj*3+l3); js_m = js_m+js; dip_h(:,ii+(jj-1)*pi_dip(1)) = ... add1dip(loc_pl,js/Mn_j*20,vloc, ... marker{im},colors{ic},st.vols{1}.ax,Fig,st.bb); end end end st.vols{1}.sdip.ax = dip_h; % Display dipoles orientation and strength js_m = js_m/size(tabl_seed_dip,1); [th,phi,Ijs_m] = cart2sph(js_m(1),js_m(2),js_m(3)); Njs_m = round(js_m'/Ijs_m*100)/100; Angle = round([th phi]*1800/pi)/10; set(sdip.hdl.hor1,'String',[num2str(Njs_m(1)),' ',num2str(Njs_m(2)), ... ' ',num2str(Njs_m(3))]); set(sdip.hdl.hor2,'String',[num2str(Angle(1)),'� ',num2str(Angle(2)),'�']); set(sdip.hdl.int,'String',Ijs_m); % Change the colour of toggle button of dipoles actually displayed for ii=tabl_seed_dip(:,1) set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 1 .7]); end %========================================================================== case 'clearall' %========================================================================== % Clears all dipoles, and reset the toggle buttons %-------------------------------------------------------------------------- if isfield(st.vols{1},'sdip') sdip = st.vols{1}.sdip; else error('I can''t find sdip structure'); end disp('Clears all dipoles') spm_eeg_inv_vbecd_disp('ClearDip'); for ii=1:st.vols{1}.sdip.n_seeds if sdip.exitflag(ii)==1 set(st.vols{1}.sdip.hdl.hseed(ii),'Value',0); end end set(st.vols{1}.sdip.hdl.hdip,'Value',1); %========================================================================== case 'chgseed' %========================================================================== % Changes the seeds displayed %-------------------------------------------------------------------------- % disp('Change seed') sdip = st.vols{1}.sdip; if isfield(sdip,'tabl_seed_dip') prev_seeds = p_seed(sdip.tabl_seed_dip); else prev_seeds = []; end l_seed = zeros(sdip.n_seeds,1); for ii=1:sdip.n_seeds if sdip.exitflag(ii)==1 l_seed(ii) = get(sdip.hdl.hseed(ii),'Value'); end end l_seed = find(l_seed); % Modify the list of seeds displayed if isempty(l_seed) % Nothing left displayed i_seed=[]; elseif isempty(prev_seeds) % Just one dipole added, nothing before i_seed=l_seed; elseif length(prev_seeds)>length(l_seed) % One seed removed i_seed = prev_seeds; for ii=1:length(l_seed) p = find(prev_seeds==l_seed(ii)); if ~isempty(p) prev_seeds(p) = []; end % prev_seeds is left with the index of the one removed end i_seed(i_seed==prev_seeds) = []; % Remove the dipole & change the button colour spm_eeg_inv_vbecd_disp('ClearDip',prev_seeds); set(sdip.hdl.hseed(prev_seeds),'BackgroundColor',[.7 .7 .7]); else % One dipole added i_seed = prev_seeds; for ii=1:length(prev_seeds) p = find(prev_seeds(ii)==l_seed); if ~isempty(p) l_seed(p) = []; end % l_seed is left with the index of the one added end i_seed = [i_seed ; l_seed]; end i_dip = get(sdip.hdl.hdip,'Value'); spm_eeg_inv_vbecd_disp('ClearDip'); if ~isempty(i_seed) spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip); end %========================================================================== case 'chgdip' %========================================================================== % Changes the dipole index for the first seed displayed %-------------------------------------------------------------------------- disp('Change dipole') sdip = st.vols{1}.sdip; i_dip = get(sdip.hdl.hdip,'Value'); if isfield(sdip,'tabl_seed_dip') i_seed = p_seed(sdip.tabl_seed_dip); else i_seed = []; end if ~isempty(i_seed) spm_eeg_inv_vbecd_disp('ClearDip') spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip); end %========================================================================== case 'cleardip' %========================================================================== % FORMAT spm_eeg_inv_vbecd_disp('ClearDip',seed_i) % e.g. spm_eeg_inv_vbecd_disp('ClearDip') % clears all displayed dipoles % e.g. spm_eeg_inv_vbecd_disp('ClearDip',1) % clears the first dipole displayed %-------------------------------------------------------------------------- if nargin>2 seed_i = varargin{1}; else seed_i = 0; end if isfield(st.vols{1},'sdip') sdip = st.vols{1}.sdip; else return; % I don't do anything, as I can't find sdip strucure end if isfield(sdip,'ax') Nax = size(sdip.ax,2); else return; % I don't do anything, as I can't find axes info end if seed_i==0 % removes everything for ii=1:Nax for jj=1:9 delete(sdip.ax(jj,ii)); end end for ii=sdip.tabl_seed_dip(:,1) set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 .7 .7]); end sdip = rmfield(sdip,'tabl_seed_dip'); sdip = rmfield(sdip,'ax'); elseif seed_i<=Nax % remove one seed only l_seed = find(sdip.tabl_seed_dip(:,1)==seed_i); for ii=l_seed for jj=1:9 delete(sdip.ax(jj,ii)); end end sdip.ax(:,l_seed) = []; sdip.tabl_seed_dip(l_seed,:) = []; else error('Trying to clear unspecified dipole'); end st.vols{1}.sdip = sdip; %========================================================================== case 'redrawdip' %========================================================================== % spm_eeg_inv_vbecd_disp('RedrawDip') % redraw everything, useful when zooming into image %-------------------------------------------------------------------------- % spm_eeg_inv_vbecd_disp('ClearDip') % spm_eeg_inv_vbecd_disp('ChgDip') % disp('Change dipole') sdip = st.vols{1}.sdip; i_dip = get(sdip.hdl.hdip,'Value'); if isfield(sdip,'tabl_seed_dip') i_seed = p_seed(sdip.tabl_seed_dip); else i_seed = []; end if ~isempty(i_seed) spm_eeg_inv_vbecd_disp('ClearDip') spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip); end %========================================================================== otherwise %========================================================================== warning('Unknown action string'); end % warning(sw); return %========================================================================== % dh = add1dip(loc,js,vloc,mark,col,ax,Fig,bb) %========================================================================== function dh = add1dip(loc,js,vloc,mark,col,ax,Fig,bb) % Plots the dipoles on the 3 views, with an error ellipse for location % Then returns the handle to the plots global st is = inv(st.Space); loc = is(1:3,1:3)*loc(:) + is(1:3,4); % taking into account the zooming/scaling only for the location % NOT for the dipole's amplitude. % Amplitude plotting is quite arbitrary anyway and up to some scaling % defined for better viewing... loc(1,:) = loc(1,:) - bb(1,1)+1; loc(2,:) = loc(2,:) - bb(1,2)+1; loc(3,:) = loc(3,:) - bb(1,3)+1; % +1 added to be like John's orthview code % prepare error ellipse vloc = is(1:3,1:3)*vloc*is(1:3,1:3); [V,E] = eig(vloc); VE = V*diag(sqrt(diag(E))); % use std % VE = V*E; % or use variance ??? dh = zeros(9,1); figure(Fig) % Transverse slice, # 1 %---------------------- set(Fig,'CurrentAxes',ax{1}.ax) set(ax{1}.ax,'NextPlot','add') dh(1) = plot(loc(1),loc(2),[mark,col],'LineWidth',1); dh(2) = plot(loc(1)+[0 js(1)],loc(2)+[0 js(2)],col,'LineWidth',2); % add error ellipse [uu,ss,vv] = svd(VE([1 2],:)); [phi] = cart2pol(uu(1,1),uu(2,1)); e = diag(ss); t = (-1:.02:1)*pi; x = e(1)*cos(t)*cos(phi)-e(2)*sin(t)*sin(phi)+loc(1); y = e(2)*sin(t)*cos(phi)+e(1)*cos(t)*sin(phi)+loc(2); dh(3) = plot(x,y,[':',col],'LineWidth',.5); set(ax{1}.ax,'NextPlot','replace') % Coronal slice, # 2 %---------------------- set(Fig,'CurrentAxes',ax{2}.ax) set(ax{2}.ax,'NextPlot','add') dh(4) = plot(loc(1),loc(3),[mark,col],'LineWidth',1); dh(5) = plot(loc(1)+[0 js(1)],loc(3)+[0 js(3)],col,'LineWidth',2); % add error ellipse [uu,ss,vv] = svd(VE([1 3],:)); [phi] = cart2pol(uu(1,1),uu(2,1)); e = diag(ss); t = (-1:.02:1)*pi; x = e(1)*cos(t)*cos(phi)-e(2)*sin(t)*sin(phi)+loc(1); y = e(2)*sin(t)*cos(phi)+e(1)*cos(t)*sin(phi)+loc(3); dh(6) = plot(x,y,[':',col],'LineWidth',.5); set(ax{2}.ax,'NextPlot','replace') % Sagital slice, # 3 %---------------------- set(Fig,'CurrentAxes',ax{3}.ax) set(ax{3}.ax,'NextPlot','add') % dh(5) = plot(dim(2)-loc(2),loc(3),[mark,col],'LineWidth',2); % dh(6) = plot(dim(2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2); dh(7) = plot(bb(2,2)-bb(1,2)-loc(2),loc(3),[mark,col],'LineWidth',1); dh(8) = plot(bb(2,2)-bb(1,2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2); % add error ellipse [uu,ss,vv] = svd(VE([2 3],:)); [phi] = cart2pol(uu(1,1),uu(2,1)); e = diag(ss); t = (-1:.02:1)*pi; x = -(e(1)*cos(t)*cos(phi)-e(2)*sin(t)*sin(phi))+bb(2,2)-bb(1,2)-loc(2); y = e(2)*sin(t)*cos(phi)+e(1)*cos(t)*sin(phi)+loc(3); dh(9) = plot(x,y,[':',col],'LineWidth',.5); set(ax{3}.ax,'NextPlot','replace') return %========================================================================== % pr_seed = p_seed(tabl_seed_dip) %========================================================================== function pr_seed = p_seed(tabl_seed_dip) % Gets the list of seeds used in the previous display ls = sort(tabl_seed_dip(:,1)); if length(ls)==1 pr_seed = ls; else pr_seed = ls([find(diff(ls)) ; length(ls)]); end % % OLD STUFF %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Use it with arguments or not: % - spm_eeg_inv_vbecd_disp('Init') % The routine asks for the dipoles file and image to display % - spm_eeg_inv_vbecd_disp('Init',sdip) % The routine will use the avg152T1 canonical image % - spm_eeg_inv_vbecd_disp('Init',sdip,P) % The routines dispays the dipoles on image P. % % If multiple seeds have been used, you can select the seeds to display % by pressing their index. % Given that the sources could have different locations, the slices % displayed will be the 3D view at the *average* or *mean* locations of % selected sources. % If more than 1 dipole was fitted at a time, then selection of source 1 % to N is possible through the pull-down selector. % % The location of the source/cut is displayed in mm and voxel, as well as % the underlying image intensity at that location. % The cross hair position can be hidden by clicking on its button. % % Nota_1: If the cross hair is manually moved by clicking in the image or % changing its coordinates, the dipole displayed will NOT be at % the right displayed location. That's something that needs to be improved... % % Nota_2: Some seeds may have not converged within the limits fixed, % these dipoles are not displayed... % % Fields needed in sdip structure to plot on an image: % + n_seeds: nr of seeds set used, i.e. nr of solutions calculated % + n_dip: nr of fitted dipoles on the EEG time series % + loc: location of fitted dipoles, cell{1,n_seeds}(3 x n_dip) % remember that loc is fixed over the time window. % + j: sources amplitude over the time window, % cell{1,n_seeds}(3*n_dip x Ntimebins) % + Mtb: index of maximum power in EEG time series used % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % First point to consider % loc_mm = sdip.loc{i_seed(1)}(:,i_dip); % % % PLace the underlying image at right cuts % spm_orthviews('Reposition',loc_mm); % % spm_orthviews('Reposition',loc_vx); % % spm_orthviews('Xhairs','off') % % % if i_seed = set, Are there other dipoles close enough ? % tabl_seed_dip=[i_seed(1) i_dip]; % table summarising which set & dip to use. % if length(i_seed)>1 % unit = ones(1,sdip.n_dip); % for ii = i_seed(2:end)' % d2 = sqrt(sum((sdip.loc{ii}-loc_mm*unit).^2)); % l_cl = find(d2<=lim_cl); % if ~isempty(l_cl) % for jj=l_cl % tabl_seed_dip = [tabl_seed_dip ; [ii jj]]; % end % end % end % end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % get(sdip.hdl.hseed(1),'Value') % for ii=1:sdip.n_seeds, delete(hseed(ii)); end % h1 = uicontrol(Fig,'Style','togglebutton','Position',[600 25 10 10].*WS) % h2 = uicontrol(Fig,'Style','togglebutton','Position',[620 100 20 20].*WS,'String','1') % h2 = uicontrol(Fig,'Style','checkbox','Position',[600 100 10 10].*WS) % h3 = uicontrol(Fig,'Style','radiobutton','Position',[600 150 20 20].*WS) % h4 = uicontrol(Fig,'Style','radiobutton','Position',[700 150 20 20].*WS) % delete(h2),delete(h3),delete(h4), % delete(hdip)
github
lcnhappe/happe-master
spm_figure.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_figure.m
32,150
utf_8
8f4bd924a038c03f7d509cc9e37b8395
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: 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 % %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Andrew Holmes % $Id$ %======================================================================= % - 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 no such 'Tag'ged figure % is found and 'Tag' is recognized, 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 spm_figure('Print',F) % F - [Optional] Figure to print. ('Tag' or figure number) % Defaults to figure 'Tag'ed as 'Graphics'. % If none found, uses CurrentFigure if avaliable. % 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 number of pages. % % FORMAT n = spm_figure('CurrentPage'); % Return 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 shh = get(0,'showhiddenhandles'); set(0,'showhiddenhandles','on'); 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 set(0,'showhiddenhandles',shh); 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 'DEM' F = spm_figure('Create','DEM','Dynamic Expectation Maximisation'); case 'DFP' F = spm_figure('Create','DFP','Variational filtering'); case 'FMIN' F = spm_figure('Create','FMIN','Function minimisation'); case 'MFM' F = spm_figure('Create','MFM','Mean-field and neural mass models'); case 'MVB' F = spm_figure('Create','MVB','Multivariate Bayes'); case 'SI' F = spm_figure('Create','SI','System Identification'); case 'PPI' F = spm_figure('Create','PPI','Physio/Psycho-Physiologic Interaction'); case 'Interactive' F = spm('CreateIntWin'); otherwise F = spm_figure('Create',Tag,Tag); end end else set(0,'CurrentFigure',F); figure(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 zoom(F,'off'); rotate3d(F,'off'); 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') movegui(F); case 'print' %======================================================================= % spm_figure('Print',F,fname) %-Arguments & defaults if nargin<3, fname=''; else fname=varargin{3};end 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 if ~isempty(F), F = spm_figure('FindWin',F); end 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 %----------------------------------------------------------------------- %-Temporarily change all units to normalized prior to printing % (Fixes bizzarre problem with stuff jumping around!) %----------------------------------------------------------------------- H = findobj(get(F,'Children'),'flat','Type','axes'); if ~isempty(H), un = cellstr(get(H,'Units')); set(H,'Units','normalized') end; %-Print %----------------------------------------------------------------------- if ~iPaged spm_print(fname) 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'); spm_print(fname); set(hPg{p,1},'Visible','off') end set(hPg{Cpage,1},'Visible','on') set([hNextPage,hPrevPage,hPageNo],'Visible','on') end if ~isempty(H), set(H,{'Units'},un); end; set(0,'CurrentFigure',cF) case 'printto' %======================================================================= %spm_figure('PrintTo',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 [fn pn] = uiputfile('*.ps', 'Print to File'); if fn == 0 return; end; psname = fullfile(pn, fn); spm_figure('Print',F,psname); 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')); mHit = strcmp('on',get(h,'HitTest')); hPg = get(hNextPage,'UserData'); if isempty(hPg) hPg = {h(mVis), h(~mVis), h(mHit), h(~mHit)}; else hPg = [hPg; {h(mVis), h(~mVis), h(mHit), h(~mHit)}]; set(h(mVis),'Visible','off'); set(h(mHit),'HitTest','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{Cpage,3},'HitTest','off'); set(hPg{Npage,1},'Visible','on'); set(hPg{Npage,3},'HitTest','on'); set(hPageNo,'UserData',Npage,'String',sprintf('%d / %d',Npage,nPages)) for k = 1:length(hPg{Npage,1}) % VG if strcmp(get(hPg{Npage,1}(k),'Type'),'axes') axes(hPg{Npage,1}(k)); end; end; %-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 'currentpage' %======================================================================= % n = spm_figure('CurrentPage', F) if nargin<2, F='Graphics'; else F=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F), error('No Graphics window'), end hPageNo = findobj(F,'Tag','PageNo'); Cpage = get(hPageNo, 'UserData'); varargout = {Cpage}; 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'); %-Graphics window rectangle S0 = spm('WinSize','0',1); %-Screen size (of the current monitor) F = figure(... 'Tag',Tag,... 'Position',[S0(1) S0(2) 0 0] + 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',spm_get_defaults('renderer'),... 'Visible','off',... 'Toolbar','none'); 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'); uimenu(t0,'Position',1,... 'Label','SPM web',... 'CallBack','web(''http://www.fil.ion.ucl.ac.uk/spm/'');'); 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'); uimenu(t1,'Label','Gray', 'CallBack','spm_figure(''ColorMap'',''gray'')'); uimenu(t1,'Label','Hot', 'CallBack','spm_figure(''ColorMap'',''hot'')'); uimenu(t1,'Label','Pink', 'CallBack','spm_figure(''ColorMap'',''pink'')'); uimenu(t1,'Label','Jet','CallBack','spm_figure(''ColorMap'',''jet'')'); uimenu(t1,'Label','Gray-Hot', 'CallBack','spm_figure(''ColorMap'',''gray-hot'')'); uimenu(t1,'Label','Gray-Cool','CallBack','spm_figure(''ColorMap'',''gray-cool'')'); uimenu(t1,'Label','Gray-Pink','CallBack','spm_figure(''ColorMap'',''gray-pink'')'); uimenu(t1,'Label','Gray-Jet', 'CallBack','spm_figure(''ColorMap'',''gray-jet'')'); t1=uimenu(t0,'Label','Effects'); uimenu(t1,'Label','Invert','CallBack','spm_figure(''ColorMap'',''invert'')'); uimenu(t1,'Label','Brighten','CallBack','spm_figure(''ColorMap'',''brighten'')'); uimenu(t1,'Label','Darken','CallBack','spm_figure(''ColorMap'',''darken'')'); uimenu( F,'Label','Clear','HandleVisibility','off','CallBack','spm_figure(''Clear'',gcbf)'); t0=uimenu( F,'Label','SPM-Print','HandleVisibility','off'); %uimenu( F,'Label','SPM-Print','HandleVisibility','off','CallBack','spm_figure(''Print'',gcbf)'); t1=uimenu(t0,'Label','default print file','HandleVisibility','off','CallBack','spm_figure(''Print'',gcbf)'); t1=uimenu(t0,'Label','other print file','HandleVisibility','off','CallBack','spm_figure(''PrintTo'',spm_figure(''FindWin'',''Graphics''))'); % ### 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']; uimenu( F,'Label','Results-Fig','HandleVisibility','off','Callback',cb); % ### END NEW CODE ### set(0,'ShowHiddenHandles',cSHH) try spm_jobman('pulldown'); end %======================================================================= 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 'jet' colormap(jet(64)) case 'gray-hot' tmp = hot(64 + 16); tmp = tmp((1:64) + 16,:); colormap([gray(64); tmp]); case 'gray-cool' cool = [zeros(10,1) zeros(10,1) linspace(0.5,1,10)'; zeros(31,1) linspace(0,1,31)' ones(31,1); linspace(0,1,23)' ones(23,1) ones(23,1) ]; colormap([gray(64); cool]); case 'gray-pink' tmp = pink(64 + 16); tmp = tmp((1:64) + 16,:); colormap([gray(64); tmp]); case 'gray-jet' colormap([gray(64); jet(64)]); 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 isempty(handles), 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; %=======================================================================
github
lcnhappe/happe-master
spm_smooth.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_smooth.m
3,654
utf_8
0f00684dc1b7cb99c88cd50e6a64a20a
function spm_smooth(P,Q,s,dtype) % 3 dimensional convolution of an image % FORMAT spm_smooth(P,Q,S,dtype) % P - image to be smoothed % Q - filename for smoothed image % S - [sx sy sz] Gaussian filter width {FWHM} in mm % dtype - datatype [default: 0 == same datatype as P] %____________________________________________________________________________ % % spm_smooth is used to smooth or convolve images in a file (maybe). % % The sum of kernel coeficients are set to unity. Boundary % conditions assume data does not exist outside the image in z (i.e. % the kernel is truncated in z at the boundaries of the image space). S % can be a vector of 3 FWHM values that specifiy an anisotropic % smoothing. If S is a scalar isotropic smoothing is implemented. % % If Q is not a string, it is used as the destination of the smoothed % image. It must already be defined with the same number of elements % as the image. % %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner & Tom Nichols % $Id$ %----------------------------------------------------------------------- if length(s) == 1; s = [s s s]; end if nargin<4, dtype = 0; end; if ischar(P), P = spm_vol(P); end; if isstruct(P), for i=1:numel(P), smooth1(P(i),Q,s,dtype); end else smooth1(P,Q,s,dtype); end %_______________________________________________________________________ %_______________________________________________________________________ function smooth1(P,Q,s,dtype) if isstruct(P), VOX = sqrt(sum(P.mat(1:3,1:3).^2)); else VOX = [1 1 1]; end; if ischar(Q) && isstruct(P), [pth,nam,ext,num] = spm_fileparts(Q); q = fullfile(pth,[nam,ext]); Q = P; Q.fname = q; if ~isempty(num), Q.n = str2num(num); end; if ~isfield(Q,'descrip'), Q.descrip = sprintf('SPM compatible'); end; Q.descrip = sprintf('%s - conv(%g,%g,%g)',Q.descrip, s); if dtype~=0, % Need to figure out some rescaling. Q.dt(1) = dtype; if ~isfinite(spm_type(Q.dt(1),'maxval')), Q.pinfo = [1 0 0]'; % float or double, so scalefactor of 1 else % Need to determine the range of intensities if isfinite(spm_type(P.dt(1),'maxval')), % Integer types have a defined maximum value maxv = spm_type(P.dt(1),'maxval')*P.pinfo(1) + P.pinfo(2); else % Need to find the max and min values in original image mx = -Inf; mn = Inf; for pl=1:P.dim(3), tmp = spm_slice_vol(P,spm_matrix([0 0 pl]),P.dim(1:2),0); tmp = tmp(isfinite(tmp)); mx = max(max(tmp),mx); mn = min(min(tmp),mn); end maxv = max(mx,-mn); end sf = maxv/spm_type(Q.dt(1),'maxval'); Q.pinfo = [sf 0 0]'; end end end % compute parameters for spm_conv_vol %----------------------------------------------------------------------- s = s./VOX; % voxel anisotropy s1 = s/sqrt(8*log(2)); % FWHM -> Gaussian parameter x = round(6*s1(1)); x = -x:x; x = spm_smoothkern(s(1),x,1); x = x/sum(x); y = round(6*s1(2)); y = -y:y; y = spm_smoothkern(s(2),y,1); y = y/sum(y); z = round(6*s1(3)); z = -z:z; z = spm_smoothkern(s(3),z,1); z = z/sum(z); i = (length(x) - 1)/2; j = (length(y) - 1)/2; k = (length(z) - 1)/2; if isstruct(Q), Q = spm_create_vol(Q); end; spm_conv_vol(P,Q,x,y,z,-[i,j,k]);
github
lcnhappe/happe-master
spm_smoothto8bit.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_smoothto8bit.m
2,377
utf_8
89653bff7e0591df6fa676885a830a16
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. %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ 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.dt = [spm_type('uint8') spm_platform('bigend')]; 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/spm8/spm_platform.m
8,498
utf_8
9af699511e4e0bff6555d7a1e3fe0a23
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 % - 0 - is little endian % - 1 - is big endian % - 'filesys' - type of filesystem % - 'unx' - UNIX % - 'win' - DOS % - 'sepchar' - returns directory separator % - 'user' - returns username % - 'host' - returns system's host name % - 'tempdir' - returns name of temp directory % - 'drives' - returns string containing valid drive letters % % 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 definitions are contained in the data structures at % the beginning of the init_platform subfunction at the end of this % file. %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % 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}; 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 'host' %-Return hostname %========================================================================== varargout = {PLATFORM.host}; case 'drives' %-Return drives %========================================================================== varargout = {PLATFORM.drives}; 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;... 'PCWIN64', 'win', 0;... 'MAC', 'unx', 1;... 'MACI', 'unx', 0;... 'MACI64', 'unx', 0;... 'SOL2', 'unx', 1;... 'SOL64', 'unx', 1;... 'GLNX86', 'unx', 0;... 'GLNXA64', 'unx', 0}; PDefs = cell2struct(PDefs,{'computer','filesys','endian'},2); %-Which computer? %-------------------------------------------------------------------------- [issup, ci] = ismember(comp,{PDefs.computer}); if ~issup error([comp ' not supported architecture for ' spm('Ver')]); end %-Set byte ordering %-------------------------------------------------------------------------- PLATFORM.bigend = PDefs(ci).endian; %-Set filesystem type %-------------------------------------------------------------------------- PLATFORM.filesys = PDefs(ci).filesys; %-File separator character %-------------------------------------------------------------------------- PLATFORM.sepchar = filesep; %-Username %-------------------------------------------------------------------------- switch PLATFORM.filesys case 'unx' PLATFORM.user = getenv('USER'); case 'win' PLATFORM.user = getenv('USERNAME'); otherwise error(['Don''t know filesystem ',PLATFORM.filesys]) end if isempty(PLATFORM.user), PLATFORM.user = 'anonymous'; end %-Hostname %-------------------------------------------------------------------------- [sts, Host] = system('hostname'); if sts if strcmp(PLATFORM.filesys,'win') Host = getenv('COMPUTERNAME'); else Host = getenv('HOSTNAME'); end Host = regexp(Host,'(.*?)\.','tokens','once'); else Host = Host(1:end-1); end PLATFORM.host = Host; %-Drives %-------------------------------------------------------------------------- PLATFORM.drives = ''; if strcmp(PLATFORM.filesys,'win') driveLett = cellstr(char(('C':'Z')')); for i=1:numel(driveLett) if exist([driveLett{i} ':\'],'dir') PLATFORM.drives = [PLATFORM.drives driveLett{i}]; end end end %-Fonts %-------------------------------------------------------------------------- switch comp case {'MAC','MACI','MACI64'} PLATFORM.font.helvetica = 'TrebuchetMS'; PLATFORM.font.times = 'Times'; PLATFORM.font.courier = 'Courier'; PLATFORM.font.symbol = 'Symbol'; case {'SOL2','SOL64','GLNX86','GLNXA64'} PLATFORM.font.helvetica = 'Helvetica'; PLATFORM.font.times = 'Times'; PLATFORM.font.courier = 'Courier'; PLATFORM.font.symbol = 'Symbol'; case {'PCWIN','PCWIN64'} 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_preproc.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_preproc.m
20,519
utf_8
c08f55c5a2eaeb3e30508750d366f52f
function results = spm_preproc(varargin) % Combined Segmentation and Spatial Normalisation % % FORMAT results = spm_preproc(V,opts) % V - image to work with % opts - options % opts.tpm - n tissue probability images for each class % opts.ngaus - number of Gaussians per class (n+1 classes) % opts.warpreg - warping regularisation % opts.warpco - cutoff distance for DCT basis functions % opts.biasreg - regularisation for bias correction % opts.biasfwhm - FWHM of Gausian form for bias regularisation % opts.regtype - regularisation for affine part % opts.fudge - a fudge factor % opts.msk - unused % %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ [dir,nam,ext] = fileparts(which(mfilename)); opts0.tpm = char(... fullfile(dir,'tpm','grey.nii'),... fullfile(dir,'tpm','white.nii'),... fullfile(dir,'tpm','csf.nii')); opts0.ngaus = [2 2 2 4]; opts0.warpreg = 1; opts0.warpco = 25; opts0.biasreg = 0.0001; opts0.biasfwhm = 75; opts0.regtype = 'mni'; opts0.fudge = 5; opts0.samp = 3; opts0.msk = ''; if nargin==0 V = spm_select(1,'image'); else V = varargin{1}; end; if ischar(V), V = spm_vol(V); end; if nargin < 2 opts = opts0; else opts = varargin{2}; fnms = fieldnames(opts0); for i=1:length(fnms) if ~isfield(opts,fnms{i}), opts.(fnms{i}) = opts0.(fnms{i}); end; end; end; if length(opts.ngaus)~= size(opts.tpm,1)+1, error('Number of Gaussians per class is not compatible with number of classes'); end; K = sum(opts.ngaus); Kb = length(opts.ngaus); lkp = []; for k=1:Kb, lkp = [lkp ones(1,opts.ngaus(k))*k]; end; B = spm_vol(opts.tpm); b0 = spm_load_priors(B); d = V(1).dim(1:3); vx = sqrt(sum(V(1).mat(1:3,1:3).^2)); sk = max([1 1 1],round(opts.samp*[1 1 1]./vx)); [x0,y0,o] = ndgrid(1:sk(1):d(1),1:sk(2):d(2),1); z0 = 1:sk(3):d(3); tiny = eps; vx = sqrt(sum(V(1).mat(1:3,1:3).^2)); kron = inline('spm_krutil(a,b)','a','b'); % BENDING ENERGY REGULARIZATION for warping %----------------------------------------------------------------------- lam = 0.001; d2 = max(round((V(1).dim(1:3).*vx)/opts.warpco),[1 1 1]); kx = (pi*((1:d2(1))'-1)/d(1)/vx(1)).^2; ky = (pi*((1:d2(2))'-1)/d(2)/vx(2)).^2; kz = (pi*((1:d2(3))'-1)/d(3)/vx(3)).^2; Cwarp = (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)) ); Cwarp = Cwarp*opts.warpreg; Cwarp = [Cwarp*vx(1)^4 ; Cwarp*vx(2)^4 ; Cwarp*vx(3)^4]; Cwarp = sparse(1:length(Cwarp),1:length(Cwarp),Cwarp,length(Cwarp),length(Cwarp)); B3warp = spm_dctmtx(d(3),d2(3),z0); B2warp = spm_dctmtx(d(2),d2(2),y0(1,:)'); B1warp = spm_dctmtx(d(1),d2(1),x0(:,1)); lmR = speye(size(Cwarp)); Twarp = zeros([d2 3]); % GAUSSIAN REGULARISATION for bias correction %----------------------------------------------------------------------- fwhm = opts.biasfwhm; sd = vx(1)*V(1).dim(1)/fwhm; d3(1) = ceil(sd*2); krn_x = exp(-(0:(d3(1)-1)).^2/sd.^2)/sqrt(vx(1)); sd = vx(2)*V(1).dim(2)/fwhm; d3(2) = ceil(sd*2); krn_y = exp(-(0:(d3(2)-1)).^2/sd.^2)/sqrt(vx(2)); sd = vx(3)*V(1).dim(3)/fwhm; d3(3) = ceil(sd*2); krn_z = exp(-(0:(d3(3)-1)).^2/sd.^2)/sqrt(vx(3)); Cbias = kron(krn_z,kron(krn_y,krn_x)).^(-2)*opts.biasreg; Cbias = sparse(1:length(Cbias),1:length(Cbias),Cbias,length(Cbias),length(Cbias)); B3bias = spm_dctmtx(d(3),d3(3),z0); B2bias = spm_dctmtx(d(2),d3(2),y0(1,:)'); B1bias = spm_dctmtx(d(1),d3(1),x0(:,1)); lmRb = speye(size(Cbias)); Tbias = zeros(d3); % Fudge Factor - to (approximately) account for % non-independence of voxels ff = opts.fudge; ff = max(1,ff^3/prod(sk)/abs(det(V.mat(1:3,1:3)))); Cwarp = Cwarp*ff; Cbias = Cbias*ff; ll = -Inf; llr = 0; llrb = 0; tol1 = 1e-4; % Stopping criterion. For more accuracy, use a smaller value d = [size(x0) length(z0)]; f = zeros(d); for z=1:length(z0), f(:,:,z) = spm_sample_vol(V,x0,y0,o*z0(z),0); end; [thresh,mx] = spm_minmax(f); mn = zeros(K,1); rand('state',0); % give same results each time for k1=1:Kb, kk = sum(lkp==k1); mn(lkp==k1) = rand(kk,1)*mx; end; vr = ones(K,1)*mx^2; mg = ones(K,1)/K; if ~isempty(opts.msk), VM = spm_vol(opts.msk); if sum(sum((VM.mat-V(1).mat).^2)) > 1e-6 || any(VM.dim(1:3) ~= V(1).dim(1:3)), error('Mask must have the same dimensions and orientation as the image.'); end; end; Affine = eye(4); if ~isempty(opts.regtype), Affine = spm_maff(V,{x0,y0,z0},b0,B(1).mat,Affine,opts.regtype,ff*100); Affine = spm_maff(V,{x0,y0,z0},b0,B(1).mat,Affine,opts.regtype,ff); end; M = B(1).mat\Affine*V(1).mat; nm = 0; for z=1:length(z0), x1 = M(1,1)*x0 + M(1,2)*y0 + (M(1,3)*z0(z) + M(1,4)); y1 = M(2,1)*x0 + M(2,2)*y0 + (M(2,3)*z0(z) + M(2,4)); z1 = M(3,1)*x0 + M(3,2)*y0 + (M(3,3)*z0(z) + M(3,4)); buf(z).msk = spm_sample_priors(b0{end},x1,y1,z1,1)<(1-1/512); fz = f(:,:,z); %buf(z).msk = fz>thresh; buf(z).msk = buf(z).msk & isfinite(fz) & (fz~=0); if ~isempty(opts.msk), msk = spm_sample_vol(VM,x0,y0,o*z0(z),0); buf(z).msk = buf(z).msk & msk; end; buf(z).nm = sum(buf(z).msk(:)); buf(z).f = fz(buf(z).msk); nm = nm + buf(z).nm; buf(z).bf(1:buf(z).nm,1) = single(1); buf(z).dat = single(0); if buf(z).nm, buf(z).dat(buf(z).nm,Kb) = single(0); end; end; clear f finalit = 0; spm_chi2_plot('Init','Processing','Log-likelihood','Iteration'); for iter=1:100, if finalit, % THIS CODE MAY BE USED IN FUTURE % Reload the data for the final iteration. This iteration % does not do any registration, so there is no need to % mask out the background voxels. %------------------------------------------------------------ llrb = -0.5*Tbias(:)'*Cbias*Tbias(:); for z=1:length(z0), fz = spm_sample_vol(V,x0,y0,o*z0(z),0); buf(z).msk = fz~=0; if ~isempty(opts.msk), msk = spm_sample_vol(VM,x0,y0,o*z0(z),0); buf(z).msk = buf(z).msk & msk; end; buf(z).nm = sum(buf(z).msk(:)); buf(z).f = fz(buf(z).msk); nm = nm + buf(z).nm; buf(z).bf(1:buf(z).nm,1) = single(1); buf(z).dat = single(0); if buf(z).nm, buf(z).dat(buf(z).nm,Kb) = single(0); end; if buf(z).nm, bf = transf(B1bias,B2bias,B3bias(z,:),Tbias); tmp = bf(buf(z).msk); llrb = llrb + sum(tmp); buf(z).bf = single(exp(tmp)); end; end; % The background won't fit well any more, so increase the % variances of these Gaussians in order to give it a chance vr(lkp(K)) = vr(lkp(K))*8; spm_chi2_plot('Init','Processing','Log-likelihood','Iteration'); end; % Load the warped prior probability images into the buffer %------------------------------------------------------------ for z=1:length(z0), if ~buf(z).nm, continue; end; [x1,y1,z1] = defs(Twarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk); for k1=1:Kb, tmp = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb); buf(z).dat(:,k1) = single(tmp); end; end; for iter1=1:10, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Estimate cluster parameters %------------------------------------------------------------ for subit=1:40, oll = ll; mom0 = zeros(K,1)+tiny; mom1 = zeros(K,1); mom2 = zeros(K,1); mgm = zeros(Kb,1); ll = llr+llrb; for z=1:length(z0), if ~buf(z).nm, continue; end; bf = double(buf(z).bf); cr = double(buf(z).f).*bf; q = zeros(buf(z).nm,K); b = zeros(buf(z).nm,Kb); s = zeros(buf(z).nm,1)+tiny; for k1=1:Kb, pr = double(buf(z).dat(:,k1)); b(:,k1) = pr; s = s + pr*sum(mg(lkp==k1)); end; for k1=1:Kb, b(:,k1) = b(:,k1)./s; end; mgm = mgm + sum(b,1)'; for k=1:K, q(:,k) = mg(k)*b(:,lkp(k)) .* exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)); end; sq = sum(q,2)+tiny; ll = ll + sum(log(sq)); for k=1:K, % Moments p1 = q(:,k)./sq; mom0(k) = mom0(k) + sum(p1(:)); p1 = p1.*cr; mom1(k) = mom1(k) + sum(p1(:)); p1 = p1.*cr; mom2(k) = mom2(k) + sum(p1(:)); end; end; % Mixing proportions, Means and Variances for k=1:K, mg(k) = (mom0(k)+eps)/(mgm(lkp(k))+eps); mn(k) = mom1(k)/(mom0(k)+eps); vr(k) =(mom2(k)-mom1(k)*mom1(k)/mom0(k)+1e6*eps)/(mom0(k)+eps); vr(k) = max(vr(k),eps); end; if subit>1 || (iter>1 && ~finalit), spm_chi2_plot('Set',ll); end; if finalit, fprintf('Mix: %g\n',ll); end; if subit == 1, ooll = ll; elseif (ll-oll)<tol1*nm, % Improvement is small, so go to next step break; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Estimate bias %------------------------------------------------------------ if prod(d3)>0, for subit=1:40, % Compute objective function and its 1st and second derivatives Alpha = zeros(prod(d3),prod(d3)); % Second derivatives Beta = zeros(prod(d3),1); % First derivatives ollrb = llrb; oll = ll; ll = llr+llrb; for z=1:length(z0), if ~buf(z).nm, continue; end; bf = double(buf(z).bf); cr = double(buf(z).f).*bf; q = zeros(buf(z).nm,K); for k=1:K, q(:,k) = double(buf(z).dat(:,lkp(k)))*mg(k); end; s = sum(q,2)+tiny; for k=1:K, q(:,k) = q(:,k)./s .* exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)); end; sq = sum(q,2)+tiny; ll = ll + sum(log(sq)); w1 = zeros(buf(z).nm,1); w2 = zeros(buf(z).nm,1); for k=1:K, tmp = q(:,k)./sq/vr(k); w1 = w1 + tmp.*(mn(k) - cr); w2 = w2 + tmp; end; wt1 = zeros(d(1:2)); wt1(buf(z).msk) = 1 + cr.*w1; wt2 = zeros(d(1:2)); wt2(buf(z).msk) = cr.*(cr.*w2 - w1); b3 = B3bias(z,:)'; Beta = Beta + kron(b3,spm_krutil(wt1,B1bias,B2bias,0)); Alpha = Alpha + kron(b3*b3',spm_krutil(wt2,B1bias,B2bias,1)); clear w1 w2 wt1 wt2 b3 end; if finalit, fprintf('Bia: %g\n',ll); end; if subit > 1 && ~(ll>oll), % Hasn't improved, so go back to previous solution Tbias = oTbias; llrb = ollrb; for z=1:length(z0), if ~buf(z).nm, continue; end; bf = transf(B1bias,B2bias,B3bias(z,:),Tbias); buf(z).bf = single(exp(bf(buf(z).msk))); end; break; else % Accept new solution spm_chi2_plot('Set',ll); oTbias = Tbias; if subit > 1 && ~((ll-oll)>tol1*nm), % Improvement is only small, so go to next step break; else % Use new solution and continue the Levenberg-Marquardt iterations Tbias = reshape((Alpha + Cbias + lmRb)\((Alpha+lmRb)*Tbias(:) + Beta),d3); llrb = -0.5*Tbias(:)'*Cbias*Tbias(:); for z=1:length(z0), if ~buf(z).nm, continue; end; bf = transf(B1bias,B2bias,B3bias(z,:),Tbias); tmp = bf(buf(z).msk); llrb = llrb + sum(tmp); buf(z).bf = single(exp(tmp)); end; end; end; end; if ~((ll-ooll)>tol1*nm), break; end; end; end; if finalit, break; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Estimate deformations %------------------------------------------------------------ mg1 = full(sparse(lkp,1,mg)); ll = llr+llrb; for z=1:length(z0), if ~buf(z).nm, continue; end; bf = double(buf(z).bf); cr = double(buf(z).f).*bf; q = zeros(buf(z).nm,Kb); tmp = zeros(buf(z).nm,1)+tiny; s = zeros(buf(z).nm,1)+tiny; for k1=1:Kb, s = s + mg1(k1)*double(buf(z).dat(:,k1)); end; for k1=1:Kb, kk = find(lkp==k1); pp = zeros(buf(z).nm,1); for k=kk, pp = pp + exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k))*mg(k); end; q(:,k1) = pp; tmp = tmp+pp.*double(buf(z).dat(:,k1))./s; end; ll = ll + sum(log(tmp)); for k1=1:Kb, buf(z).dat(:,k1) = single(q(:,k1)); end; end; for subit=1:20, oll = ll; A = cell(3,3); A{1,1} = zeros(prod(d2)); A{1,2} = zeros(prod(d2)); A{1,3} = zeros(prod(d2)); A{2,2} = zeros(prod(d2)); A{2,3} = zeros(prod(d2)); A{3,3} = zeros(prod(d2)); Beta = zeros(prod(d2)*3,1); for z=1:length(z0), if ~buf(z).nm, continue; end; [x1,y1,z1] = defs(Twarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk); b = zeros(buf(z).nm,Kb); db1 = zeros(buf(z).nm,Kb); db2 = zeros(buf(z).nm,Kb); db3 = zeros(buf(z).nm,Kb); s = zeros(buf(z).nm,1)+tiny; ds1 = zeros(buf(z).nm,1); ds2 = zeros(buf(z).nm,1); ds3 = zeros(buf(z).nm,1); p = zeros(buf(z).nm,1)+tiny; dp1 = zeros(buf(z).nm,1); dp2 = zeros(buf(z).nm,1); dp3 = zeros(buf(z).nm,1); for k1=1:Kb, [b(:,k1),db1(:,k1),db2(:,k1),db3(:,k1)] = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb); s = s + mg1(k1)* b(:,k1); ds1 = ds1 + mg1(k1)*db1(:,k1); ds2 = ds2 + mg1(k1)*db2(:,k1); ds3 = ds3 + mg1(k1)*db3(:,k1); end; for k1=1:Kb, b(:,k1) = b(:,k1)./s; db1(:,k1) = (db1(:,k1)-b(:,k1).*ds1)./s; db2(:,k1) = (db2(:,k1)-b(:,k1).*ds2)./s; db3(:,k1) = (db3(:,k1)-b(:,k1).*ds3)./s; pp = double(buf(z).dat(:,k1)); p = p + pp.*b(:,k1); dp1 = dp1 + pp.*(M(1,1)*db1(:,k1) + M(2,1)*db2(:,k1) + M(3,1)*db3(:,k1)); dp2 = dp2 + pp.*(M(1,2)*db1(:,k1) + M(2,2)*db2(:,k1) + M(3,2)*db3(:,k1)); dp3 = dp3 + pp.*(M(1,3)*db1(:,k1) + M(2,3)*db2(:,k1) + M(3,3)*db3(:,k1)); end; clear x1 y1 z1 b db1 db2 db3 s ds1 ds2 ds3 tmp = zeros(d(1:2)); tmp(buf(z).msk) = dp1./p; dp1 = tmp; tmp(buf(z).msk) = dp2./p; dp2 = tmp; tmp(buf(z).msk) = dp3./p; dp3 = tmp; b3 = B3warp(z,:)'; Beta = Beta - [... kron(b3,spm_krutil(dp1,B1warp,B2warp,0)) kron(b3,spm_krutil(dp2,B1warp,B2warp,0)) kron(b3,spm_krutil(dp3,B1warp,B2warp,0))]; b3b3 = b3*b3'; A{1,1} = A{1,1} + kron(b3b3,spm_krutil(dp1.*dp1,B1warp,B2warp,1)); A{1,2} = A{1,2} + kron(b3b3,spm_krutil(dp1.*dp2,B1warp,B2warp,1)); A{1,3} = A{1,3} + kron(b3b3,spm_krutil(dp1.*dp3,B1warp,B2warp,1)); A{2,2} = A{2,2} + kron(b3b3,spm_krutil(dp2.*dp2,B1warp,B2warp,1)); A{2,3} = A{2,3} + kron(b3b3,spm_krutil(dp2.*dp3,B1warp,B2warp,1)); A{3,3} = A{3,3} + kron(b3b3,spm_krutil(dp3.*dp3,B1warp,B2warp,1)); clear b3 b3b3 tmp p dp1 dp2 dp3 end; Alpha = [A{1,1} A{1,2} A{1,3} ; A{1,2} A{2,2} A{2,3}; A{1,3} A{2,3} A{3,3}]; clear A for subit1 = 1:3, if iter==1, nTwarp = (Alpha+lmR*lam + 10*Cwarp)\((Alpha+lmR*lam)*Twarp(:) - Beta); else nTwarp = (Alpha+lmR*lam + Cwarp)\((Alpha+lmR*lam)*Twarp(:) - Beta); end; nTwarp = reshape(nTwarp,[d2 3]); nllr = -0.5*nTwarp(:)'*Cwarp*nTwarp(:); nll = nllr+llrb; for z=1:length(z0), if ~buf(z).nm, continue; end; [x1,y1,z1] = defs(nTwarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk); sq = zeros(buf(z).nm,1) + tiny; b = zeros(buf(z).nm,Kb); s = zeros(buf(z).nm,1)+tiny; for k1=1:Kb, b(:,k1) = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb); s = s + mg1(k1)*b(:,k1); end; for k1=1:Kb, sq = sq + double(buf(z).dat(:,k1)).*b(:,k1)./s; end; clear b nll = nll + sum(log(sq)); clear sq x1 y1 z1 end; if nll<ll, % Worse solution, so use old solution and increase regularisation lam = lam*10; else % Accept new solution ll = nll; llr = nllr; Twarp = nTwarp; lam = lam*0.5; break; end; end; spm_chi2_plot('Set',ll); if (ll-oll)<tol1*nm, break; end; end; if ~((ll-ooll)>tol1*nm), finalit = 1; break; % This can be commented out. end; end; spm_chi2_plot('Clear'); results = opts; results.image = V; results.tpm = B; results.Affine = Affine; results.Twarp = Twarp; results.Tbias = Tbias; results.mg = mg; results.mn = mn; results.vr = vr; results.thresh = 0; %thresh; results.ll = ll; return; %======================================================================= %======================================================================= function t = transf(B1,B2,B3,T) if ~isempty(T), d2 = [size(T) 1]; t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2)); t = B1*t1*B2'; else t = zeros(size(B1,1),size(B2,1)); end; return; %======================================================================= %======================================================================= function [x1,y1,z1] = defs(Twarp,z,B1,B2,B3,x0,y0,z0,M,msk) x1a = x0 + transf(B1,B2,B3(z,:),Twarp(:,:,:,1)); y1a = y0 + transf(B1,B2,B3(z,:),Twarp(:,:,:,2)); z1a = z0(z) + transf(B1,B2,B3(z,:),Twarp(:,:,:,3)); if nargin>=10, x1a = x1a(msk); y1a = y1a(msk); z1a = z1a(msk); end; x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4); y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4); z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4); return; %=======================================================================
github
lcnhappe/happe-master
spm_preproc_write.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_preproc_write.m
8,906
utf_8
9312486f72c3a8971ab0c9e847c3a465
function spm_preproc_write(p,opts) % Write out VBM preprocessed data % FORMAT spm_preproc_write(p,opts) % p - results from spm_prep2sn % opts - writing options. A struct containing these fields: % biascor - write bias corrected image % GM - flags for which images should be written % WM - similar to GM % CSF - similar to GM %____________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ if nargin==1, opts = struct('biascor',0,'GM',[0 0 1],'WM',[0 0 1],'CSF',[0 0 0],'cleanup',0); end; if numel(p)>0, b0 = spm_load_priors(p(1).VG); end; for i=1:numel(p), preproc_apply(p(i),opts,b0); end; return; %======================================================================= %======================================================================= function preproc_apply(p,opts,b0) %sopts = [opts.GM ; opts.WM ; opts.CSF]; nclasses = size(fieldnames(opts),1) - 2 ; switch nclasses case 3 sopts = [opts.GM ; opts.WM ; opts.CSF]; case 4 sopts = [opts.GM ; opts.WM ; opts.CSF ; opts.EXTRA1]; case 5 sopts = [opts.GM ; opts.WM ; opts.CSF ; opts.EXTRA1 ; opts.EXTRA2]; otherwise error('######## unsupported number of classes....!!!') end [pth,nam,ext]=fileparts(p.VF.fname); T = p.flags.Twarp; bsol = p.flags.Tbias; d2 = [size(T) 1]; d = p.VF.dim(1:3); [x1,x2,o] = ndgrid(1:d(1),1:d(2),1); x3 = 1:d(3); d3 = [size(bsol) 1]; B1 = spm_dctmtx(d(1),d2(1)); B2 = spm_dctmtx(d(2),d2(2)); B3 = spm_dctmtx(d(3),d2(3)); bB3 = spm_dctmtx(d(3),d3(3),x3); bB2 = spm_dctmtx(d(2),d3(2),x2(1,:)'); bB1 = spm_dctmtx(d(1),d3(1),x1(:,1)); mg = p.flags.mg; mn = p.flags.mn; vr = p.flags.vr; K = length(p.flags.mg); Kb = length(p.flags.ngaus); for k1=1:size(sopts,1), %dat{k1} = zeros(d(1:3),'uint8'); dat{k1} = uint8(0); dat{k1}(d(1),d(2),d(3)) = 0; if sopts(k1,3), Vt = struct('fname', fullfile(pth,['c', num2str(k1), nam, ext]),... 'dim', p.VF.dim,... 'dt', [spm_type('uint8') spm_platform('bigend')],... 'pinfo', [1/255 0 0]',... 'mat', p.VF.mat,... 'n', [1 1],... 'descrip', ['Tissue class ' num2str(k1)]); Vt = spm_create_vol(Vt); VO(k1) = Vt; end; end; if opts.biascor, VB = struct('fname', fullfile(pth,['m', nam, ext]),... 'dim', p.VF.dim(1:3),... 'dt', [spm_type('float32') spm_platform('bigend')],... 'pinfo', [1 0 0]',... 'mat', p.VF.mat,... 'n', [1 1],... 'descrip', 'Bias Corrected'); VB = spm_create_vol(VB); end; lkp = []; for k=1:Kb, lkp = [lkp ones(1,p.flags.ngaus(k))*k]; end; spm_progress_bar('init',length(x3),['Working on ' nam],'Planes completed'); M = p.VG(1).mat\p.flags.Affine*p.VF.mat; for z=1:length(x3), % Bias corrected image f = spm_sample_vol(p.VF,x1,x2,o*x3(z),0); cr = exp(transf(bB1,bB2,bB3(z,:),bsol)).*f; if opts.biascor, % Write a plane of bias corrected data VB = spm_write_plane(VB,cr,z); end; if any(sopts(:)), msk = (f==0) | ~isfinite(f); [t1,t2,t3] = defs(T,z,B1,B2,B3,x1,x2,x3,M); q = zeros([d(1:2) Kb]); bt = zeros([d(1:2) Kb]); for k1=1:Kb, bt(:,:,k1) = spm_sample_priors(b0{k1},t1,t2,t3,k1==Kb); end; b = zeros([d(1:2) K]); for k=1:K, b(:,:,k) = bt(:,:,lkp(k))*mg(k); end; s = sum(b,3); for k=1:K, p1 = exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)+eps); q(:,:,lkp(k)) = q(:,:,lkp(k)) + p1.*b(:,:,k)./s; end; sq = sum(q,3)+eps; sw = warning('off','MATLAB:divideByZero'); for k1=1:size(sopts,1), tmp = q(:,:,k1); tmp(msk) = 0; tmp = tmp./sq; dat{k1}(:,:,z) = uint8(round(255 * tmp)); end; warning(sw); end; spm_progress_bar('set',z); end; spm_progress_bar('clear'); if opts.cleanup > 0, [dat{1},dat{2},dat{3}] = clean_gwc(dat{1},dat{2},dat{3}, opts.cleanup); end; if any(sopts(:,3)), for z=1:length(x3), for k1=1:size(sopts,1), if sopts(k1,3), tmp = double(dat{k1}(:,:,z))/255; spm_write_plane(VO(k1),tmp,z); end; end; end; end; for k1=1:size(sopts,1), if any(sopts(k1,1:2)), so = struct('wrap',[0 0 0],'interp',1,'vox',[NaN NaN NaN],... 'bb',ones(2,3)*NaN,'preserve',0); ovx = abs(det(p.VG(1).mat(1:3,1:3)))^(1/3); fwhm = max(ovx./sqrt(sum(p.VF.mat(1:3,1:3).^2))-1,0.1); dat{k1} = decimate(dat{k1},fwhm); fn = fullfile(pth,['c', num2str(k1), nam, ext]); dim = [size(dat{k1}) 1]; VT = struct('fname',fn,'dim',dim(1:3),... 'dt', [spm_type('uint8') spm_platform('bigend')],... 'pinfo',[1/255 0]','mat',p.VF.mat,'dat',dat{k1}); if sopts(k1,2), spm_write_sn(VT,p,so); end; so.preserve = 1; if sopts(k1,1), VN = spm_write_sn(VT,p,so); VN.fname = fullfile(pth,['mwc', num2str(k1), nam, ext]); spm_write_vol(VN,VN.dat); end; end; end; return; %======================================================================= %======================================================================= function [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M) x1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1)); y1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2)); z1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3)); x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4); y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4); z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4); return; %======================================================================= %======================================================================= function t = transf(B1,B2,B3,T) if ~isempty(T) d2 = [size(T) 1]; t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2)); t = B1*t1*B2'; else t = zeros(size(B1,1),size(B2,1),size(B3,1)); end; return; %======================================================================= %======================================================================= function dat = decimate(dat,fwhm) % Convolve the volume in memory (fwhm in voxels). lim = ceil(2*fwhm); x = -lim(1):lim(1); x = spm_smoothkern(fwhm(1),x); x = x/sum(x); y = -lim(2):lim(2); y = spm_smoothkern(fwhm(2),y); y = y/sum(y); z = -lim(3):lim(3); z = spm_smoothkern(fwhm(3),z); z = z/sum(z); i = (length(x) - 1)/2; j = (length(y) - 1)/2; k = (length(z) - 1)/2; spm_conv_vol(dat,dat,x,y,z,-[i j k]); return; %======================================================================= %======================================================================= function [g,w,c] = clean_gwc(g,w,c, level) if nargin<4, level = 1; end; 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; th1 = 0.15; if level==2, th1 = 0.2; end; % Erosions and conditional dilations %----------------------------------------------------------------------- niter = 32; spm_progress_bar('Init',niter,'Extracting Brain','Iterations completed'); for j=1:niter, if j>2, th=th1; 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.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm.m
44,832
utf_8
d2d75e50e191a0c29cf483d58a754d7f
function varargout=spm(varargin) % SPM: Statistical Parametric Mapping (startup function) %_______________________________________________________________________ % ___ ____ __ __ % / __)( _ \( \/ ) % \__ \ )___/ ) ( Statistical Parametric Mapping % (___/(__) (_/\/\_) SPM - http://www.fil.ion.ucl.ac.uk/spm/ %_______________________________________________________________________ % % SPM (Statistical Parametric Mapping) is a package for the analysis % functional brain mapping experiments. It is the in-house package of % the Wellcome Trust Centre for Neuroimaging, and is available to the % scientific community as copyright freeware under the terms of the % GNU General Public Licence. % % Theoretical, computational and other details of the package are % available in SPM's "Help" facility. This can be launched from the % main SPM Menu window using the "Help" button, or directly from the % command line using the command `spm_help`. % % Details of this release are available via the "About SPM" help topic % (file spm.man), accessible from the SPM splash screen. (Or type % `spm_help spm.man` in the MATLAB command window) % % This spm function initialises the default parameters, and displays a % splash screen with buttons leading to the PET, fMRI and M/EEG % modalities. Alternatively, `spm('pet')`, `spm('fmri')`, `spm('eeg')` % (equivalently `spm pet`, `spm fmri` and `spm eeg`) lead directly to % the respective modality interfaces. % % Once the modality is chosen, (and it can be toggled mid-session) the % SPM user interface is displayed. This provides a constant visual % environment in which data analysis is implemented. The layout has % been designed to be simple and at the same time show all the % facilities that are available. The interface consists of three % windows: A menu window with pushbuttons for the SPM routines (each % button has a 'CallBack' string which launches the appropriate % function/script); A blank panel used for interaction with the user; % And a graphics figure with various editing and print facilities (see % spm_figure.m). (These windows are 'Tag'ged 'Menu', 'Interactive', and % 'Graphics' respectively, and should be referred to by their tags % rather than their figure numbers.) % % Further interaction with the user is (mainly) via questioning in the % 'Interactive' window (managed by spm_input), and file selection % (managed by spm_select). See the help on spm_input.m and spm_select.m for % details on using these functions. % % If a "message of the day" file named spm_motd.man exists in the SPM % directory (alongside spm.m) then it is displayed in the Graphics % window on startup. % % Arguments to this routine (spm.m) lead to various setup facilities, % mainly of use to SPM power users and programmers. See programmers % FORMAT & help in the main body of spm.m % %_______________________________________________________________________ % SPM is developed by members and collaborators of the % Wellcome Trust Centre for Neuroimaging %-SVN ID and authorship of this program... %----------------------------------------------------------------------- % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Andrew Holmes % $Id$ %======================================================================= % - 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 Welcome` is equivalent to ) %( `spm('Welcome')`. ) % % FORMAT spm % Defaults to spm('Welcome') % % FORMAT spm('Welcome') % Clears command window, deletes all figures, prints welcome banner and % splash screen, sets window defaults. % % FORMAT spm('AsciiWelcome') % Prints ASCII welcome banner in MATLAB command window. % % FORMAT spm('PET') spm('FMRI') spm('EEG') % Closes all windows and draws new Menu, Interactive, and Graphics % windows for an SPM session. The buttons in the Menu window launch the % main analysis routines. % % FORMAT spm('ChMod',Modality) % Changes modality of SPM: Currently SPM supports PET & MRI modalities, % each of which have a slightly different Menu window and different % defaults. This function switches to the specified modality, setting % defaults and displaying the relevant buttons. % % FORMAT spm('defaults',Modality) % Sets default global variables for the specified modality. % % FORMAT [Modality,ModNum]=spm('CheckModality',Modality) % Checks the specified modality against those supported, returns % upper(Modality) and the Modality number, it's position in the list of % supported Modalities. % % FORMAT Fmenu = spm('CreateMenuWin',Vis) % Creates SPM menu window, 'Tag'ged 'Menu' % F - handle of figure created % Vis - Visibility, 'on' or 'off' % % Finter = FORMAT spm('CreateIntWin',Vis) % Creates an SPM Interactive window, 'Tag'ged 'Interactive' % F - handle of figure created % Vis - Visibility, 'on' or 'off' % % FORMAT [Finter,Fgraph,CmdLine] = spm('FnUIsetup',Iname,bGX,CmdLine) % Robust UIsetup procedure for functions: % Returns handles of 'Interactive' and 'Graphics' figures. % Creates 'Interactive' figure if ~CmdLine, creates 'Graphics' figure if bGX. % Iname - Name for 'Interactive' window % bGX - Need a Graphics window? [default 1] % CmdLine - CommandLine usage? [default spm('CmdLine')] % Finter - handle of 'Interactive' figure % Fgraph - handle of 'Graphics' figure % CmdLine - CommandLine usage? % % FORMAT WS=spm('WinScale') % 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_figure.m, repeated to reduce inter-dependencies.) % % FORMAT [FS,sf] = spm('FontSize',FS) % FORMAT [FS,sf] = spm('FontSizes',FS) % Returns fontsizes FS scaled for the current display. % FORMAT sf = spm('FontScale') % Returns font scaling factor % FS - (vector of) Font sizes to scale [default [1:36]] % sf - font scaling factor (FS(out) = floor(FS(in)*sf) % % Rect = spm('WinSize',Win,raw) % Returns sizes and positions for SPM windows. % Win - 'Menu', 'Interactive', 'Graphics', or '0' % - Window whose position is required. Only first character is % examined. '0' returns size of root workspace. % raw - If specified, then positions are for a 1152 x 900 Sun display. % Otherwise the positions are scaled for the current display. % % FORMAT [c,cName] = spm('Colour') % Returns the RGB triple and a description for the current en-vogue SPM % colour, the background colour for the Menu and Help windows. % % FORMAT F = spm('FigName',Iname,F,CmdLine) % Set name of figure F to "SPMver (User): Iname" if ~CmdLine % Robust to absence of figure. % Iname - Name for figure % F (input) - Handle (or 'Tag') of figure to name [default 'Interactive'] % CmdLine - CommandLine usage? [default spm('CmdLine')] % F (output) - Handle of figure named % % FORMAT Fs = spm('Show') % Opens all SPM figure windows (with HandleVisibility) using `figure`. % Maintains current figure. % Fs - vector containing all HandleVisible figures (i.e. get(0,'Children')) % % FORMAT spm('Clear',Finter, Fgraph) % Clears and resets SPM-GUI, clears and timestamps MATLAB command window. % Finter - handle or 'Tag' of 'Interactive' figure [default 'Interactive'] % Fgraph - handle or 'Tag' of 'Graphics' figure [default 'Graphics'] % % FORMAT SPMid = spm('FnBanner', Fn,FnV) % Prints a function start banner, for version FnV of function Fn, & datestamps % FORMAT SPMid = spm('SFnBanner',Fn,FnV) % Prints a sub-function start banner % FORMAT SPMid = spm('SSFnBanner',Fn,FnV) % Prints a sub-sub-function start banner % Fn - Function name (string) % FnV - Function version (string) % SPMid - ID string: [SPMver: Fn (FnV)] % % FORMAT SPMdir = spm('Dir',Mfile) % Returns the directory containing the version of spm in use, % identified as the first in MATLABPATH containing the Mfile spm (this % file) (or Mfile if specified). % % FORMAT [v,r] = spm('Ver',Mfile,ReDo) % Returns the current version (v) and release (r) of file Mfile. This % corresponds to the Last changed Revision number extracted from the % Subversion Id tag. % If Mfile is absent or empty then it returns the current SPM version (v) % and release (r), extracted from the file Contents.m in the SPM directory % (these information are cached in a persistent variable to enable repeat % use without recomputation). % If Redo [default false] is true, then the cached current SPM information % are not used but recomputed (and recached). % % FORMAT v = spm('MLver') % Returns MATLAB version, truncated to major & minor revision numbers % % FORMAT xTB = spm('TBs') % Identifies installed SPM toolboxes: SPM toolboxes are defined as the % contents of sub-directories of fullfile(spm('Dir'),'toolbox') - the % SPM toolbox installation directory. For SPM to pick a toolbox up, % there must be a single mfile in the directory whose name ends with % the toolbox directory name. (I.e. A toolbox called "test" would be in % the "test" subdirectory of spm('Dir'), with a single file named % *test.m.) This M-file is regarded as the launch file for the % toolbox. % xTB - structure array containing toolbox definitions % xTB.name - name of toolbox (taken as toolbox directory name) % xTB.prog - launch program for toolbox % xTB.dir - toolbox directory % % FORMAT spm('TBlaunch',xTB,i) % Launch a toolbox, prepending TBdir to path if necessary % xTB - toolbox definition structure (i.e. from spm('TBs') % xTB.name - name of toolbox % xTB.prog - name of program to launch toolbox % xTB.dir - toolbox directory (prepended to path if not on path) % % FORMAT [v1,v2,...] = spm('GetGlobal',name1,name2,...) % Returns values of global variables (without declaring them global) % name1, name2,... - name strings of desired globals % a1, a2,... - corresponding values of global variables with given names % ([] is returned as value if global variable doesn't exist) % % FORMAT CmdLine = spm('CmdLine',CmdLine) % Command line SPM usage? % CmdLine (input) - CmdLine preference % [defaults (missing or empty) to global defaults.cmdline,] % [if it exists, or 0 (GUI) otherwise. ] % CmdLine (output) - true if global CmdLine if true, % or if on a terminal with no support for graphics windows. % % FORMAT spm('PopUpCB',h) % Callback handler for PopUp UI menus with multiple callbacks as cellstr UserData % % FORMAT str = spm('GetUser',fmt) % Returns current users login name, extracted from the hosting environment % fmt - format string: If USER is defined then sprintf(fmt,USER) is returned % % FORMAT spm('Beep') % Plays the keyboard beep! % % FORMAT spm('time') % Returns the current time and date as hh:mm dd/mm/yyyy % % FORMAT spm('Pointer',Pointer) % Changes pointer on all SPM (HandleVisible) windows to type Pointer % Pointer defaults to 'Arrow'. Robust to absence of windows % % FORMAT h = spm('alert',Message,Title,CmdLine,wait) % FORMAT h = spm('alert"',Message,Title,CmdLine,wait) % FORMAT h = spm('alert*',Message,Title,CmdLine,wait) % FORMAT h = spm('alert!',Message,Title,CmdLine,wait) % Displays an alert, either in a GUI msgbox, or as text in the command window. % ( 'alert"' uses the 'help' msgbox icon, 'alert*' the ) % ( 'error' icon, 'alert!' the 'warn' icon ) % Message - string (or cellstr) containing message to print % Title - title string for alert % CmdLine - CmdLine preference [default spm('CmdLine')] % - If CmdLine is complex, then a CmdLine alert is always used, % possibly in addition to a msgbox (the latter according % to spm('CmdLine').) % wait - if true, waits until user dismisses GUI / confirms text alert % [default 0] (if doing both GUI & text, waits on GUI alert) % h - handle of msgbox created, empty if CmdLine used % % FORMAT spm('GUI_FileDelete') % CallBack for GUI for file deletion, using spm_select and confirmation dialogs % % FORMAT spm('Clean') % Clear all variables, globals, functions, MEX links and class definitions. % % FORMAT spm('Help',varargin) % Merely a gateway to spm_help(varargin) - so you can type "spm help" % % FORMAT spm('Quit') % Quit SPM, delete all windows and clear the command window. % %_______________________________________________________________________ %-Parameters %----------------------------------------------------------------------- Modalities = {'PET','FMRI','EEG'}; %-Format arguments %----------------------------------------------------------------------- if nargin == 0, Action = 'Welcome'; else Action = varargin{1}; end %======================================================================= switch lower(Action), case 'welcome' %-Welcome splash screen %======================================================================= % spm('Welcome') spm_check_installation('basic'); defaults = spm('GetGlobal','defaults'); if isfield(defaults,'modality') spm(defaults.modality); return end %-Open startup window, set window defaults %----------------------------------------------------------------------- Fwelcome = openfig(fullfile(spm('Dir'),'spm_Welcome.fig'),'new','invisible'); set(Fwelcome,'name',sprintf('%s%s',spm('ver'),spm('GetUser',' (%s)'))); set(get(findobj(Fwelcome,'Type','axes'),'children'),'FontName',spm_platform('Font','Times')); set(findobj(Fwelcome,'Tag','SPM_VER'),'String',spm('Ver')); RectW = spm('WinSize','W',1); Rect0 = spm('WinSize','0',1); set(Fwelcome,'Units','pixels', 'Position',... [Rect0(1)+(Rect0(3)-RectW(3))/2, Rect0(2)+(Rect0(4)-RectW(4))/2, RectW(3), RectW(4)]); set(Fwelcome,'Visible','on'); %======================================================================= case 'asciiwelcome' %-ASCII SPM banner welcome %======================================================================= % spm('AsciiWelcome') disp( ' ___ ____ __ __ '); disp( '/ __)( _ \( \/ ) '); disp( '\__ \ )___/ ) ( Statistical Parametric Mapping '); disp(['(___/(__) (_/\/\_) ',spm('Ver'),' - http://www.fil.ion.ucl.ac.uk/spm/']); fprintf('\n'); %======================================================================= case lower(Modalities) %-Initialise SPM in PET, fMRI, EEG modality %======================================================================= % spm(Modality) spm_check_installation('basic'); try, feature('JavaFigures',0); end %-Initialisation and workspace canonicalisation %----------------------------------------------------------------------- local_clc; spm('AsciiWelcome'); fprintf('\n\nInitialising SPM'); Modality = upper(Action); fprintf('.'); delete(get(0,'Children')); fprintf('.'); %-Load startup global defaults %----------------------------------------------------------------------- spm_defaults; fprintf('.'); %-Setup for batch system %----------------------------------------------------------------------- spm_jobman('initcfg'); spm_select('prevdirs',[spm('Dir') filesep]); %-Draw SPM windows %----------------------------------------------------------------------- if ~spm('CmdLine') Fmenu = spm('CreateMenuWin','off'); fprintf('.'); Finter = spm('CreateIntWin','off'); fprintf('.'); else Fmenu = []; Finter = []; end Fgraph = spm_figure('Create','Graphics','Graphics','off'); fprintf('.'); spm_figure('WaterMark',Finter,spm('Ver'),'',45); fprintf('.'); Fmotd = fullfile(spm('Dir'),'spm_motd.man'); if exist(Fmotd,'file'), spm_help('!Disp',Fmotd,'',Fgraph,spm('Ver')); end fprintf('.'); %-Setup for current modality %----------------------------------------------------------------------- spm('ChMod',Modality); fprintf('.'); %-Reveal windows %----------------------------------------------------------------------- set([Fmenu,Finter,Fgraph],'Visible','on'); fprintf('done\n\n'); %-Print present working directory %----------------------------------------------------------------------- fprintf('SPM present working directory:\n\t%s\n',pwd) %======================================================================= case 'chmod' %-Change SPM modality PET<->fMRI<->EEG %======================================================================= % spm('ChMod',Modality) %----------------------------------------------------------------------- %-Sort out arguments %----------------------------------------------------------------------- if nargin<2, Modality = ''; else Modality = varargin{2}; end [Modality,ModNum] = spm('CheckModality',Modality); %-Sort out global defaults %----------------------------------------------------------------------- spm('defaults',Modality); %-Sort out visability of appropriate controls on Menu window %----------------------------------------------------------------------- Fmenu = spm_figure('FindWin','Menu'); if ~isempty(Fmenu) if strcmpi(Modality,'PET') set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'on' ); set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'on' ); elseif strcmpi(Modality,'FMRI') set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'on' ); set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'on' ); else set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'on' ); end set(findobj(Fmenu,'Tag','Modality'),'Value',ModNum,'UserData',ModNum); else warning('SPM Menu window not found'); end %======================================================================= case 'defaults' %-Set SPM defaults (as global variable) %======================================================================= % spm('defaults',Modality) %----------------------------------------------------------------------- if nargin<2, Modality=''; else Modality=varargin{2}; end Modality = spm('CheckModality',Modality); %-Re-initialise, load defaults (from spm_defaults.m) and store modality %----------------------------------------------------------------------- clear global defaults spm_get_defaults('modality',Modality); %-Addpath modality-specific toolboxes %----------------------------------------------------------------------- if strcmpi(Modality,'EEG') && ~isdeployed addpath(fullfile(spm('Dir'),'external','fieldtrip')); ft_defaults; addpath(fullfile(spm('Dir'),'external','bemcp')); addpath(fullfile(spm('Dir'),'external','ctf')); addpath(fullfile(spm('Dir'),'external','eeprobe')); addpath(fullfile(spm('Dir'),'toolbox', 'dcm_meeg')); addpath(fullfile(spm('Dir'),'toolbox', 'spectral')); addpath(fullfile(spm('Dir'),'toolbox', 'Neural_Models')); addpath(fullfile(spm('Dir'),'toolbox', 'Beamforming')); addpath(fullfile(spm('Dir'),'toolbox', 'MEEGtools')); end %-Return defaults variable if asked %----------------------------------------------------------------------- if nargout, varargout = {spm_get_defaults}; end %======================================================================= case 'checkmodality' %-Check & canonicalise modality string %======================================================================= % [Modality,ModNum] = spm('CheckModality',Modality) %----------------------------------------------------------------------- if nargin<2, Modality=''; else Modality=upper(varargin{2}); end if isempty(Modality) try Modality = spm_get_defaults('modality'); end end if ischar(Modality) ModNum = find(ismember(Modalities,Modality)); else if ~any(Modality == 1:length(Modalities)) Modality = 'ERROR'; ModNum = []; else ModNum = Modality; Modality = Modalities{ModNum}; end end if isempty(ModNum) if isempty(Modality) fprintf('Modality is not set: use spm(''defaults'',''MOD''); '); fprintf('where MOD is one of PET, FMRI, EEG.\n'); end error('Unknown Modality.'); end varargout = {upper(Modality),ModNum}; %======================================================================= case 'createmenuwin' %-Create SPM menu window %======================================================================= % Fmenu = spm('CreateMenuWin',Vis) %----------------------------------------------------------------------- if nargin<2, Vis='on'; else Vis=varargin{2}; end %-Close any existing 'Menu' 'Tag'ged windows %----------------------------------------------------------------------- delete(spm_figure('FindWin','Menu')) Fmenu = openfig(fullfile(spm('Dir'),'spm_Menu.fig'),'new','invisible'); set(Fmenu,'name',sprintf('%s%s: Menu',spm('ver'),spm('GetUser',' (%s)'))); S0 = spm('WinSize','0',1); SM = spm('WinSize','M'); set(Fmenu,'Units','pixels', 'Position',[S0(1) S0(2) 0 0] + SM); %-Set SPM colour %----------------------------------------------------------------------- set(findobj(Fmenu,'Tag', 'frame'),'backgroundColor',spm('colour')); try if ismac b = findobj(Fmenu,'Style','pushbutton'); set(b,'backgroundColor',get(b(1),'backgroundColor')+0.002); end end %-Set toolbox %----------------------------------------------------------------------- xTB = spm('tbs'); if ~isempty(xTB) set(findobj(Fmenu,'Tag', 'Toolbox'),'String',{'Toolbox:' xTB.name }); set(findobj(Fmenu,'Tag', 'Toolbox'),'UserData',xTB); else set(findobj(Fmenu,'Tag', 'Toolbox'),'Visible','off') end set(Fmenu,'Visible',Vis); varargout = {Fmenu}; %======================================================================= case 'createintwin' %-Create SPM interactive window %======================================================================= % Finter = spm('CreateIntWin',Vis) %----------------------------------------------------------------------- if nargin<2, Vis='on'; else Vis=varargin{2}; end %-Close any existing 'Interactive' 'Tag'ged windows %----------------------------------------------------------------------- delete(spm_figure('FindWin','Interactive')) Finter = openfig(fullfile(spm('Dir'),'spm_Interactive.fig'),'new','invisible'); set(Finter,'name',spm('Ver')); S0 = spm('WinSize','0',1); SI = spm('WinSize','I'); set(Finter,'Units','pixels', 'Position',[S0(1) S0(2) 0 0] + SI); set(Finter,'Visible',Vis); varargout = {Finter}; %======================================================================= case 'fnuisetup' %-Robust UI setup for main SPM functions %======================================================================= % [Finter,Fgraph,CmdLine] = spm('FnUIsetup',Iname,bGX,CmdLine) %----------------------------------------------------------------------- if nargin<4, CmdLine=spm('CmdLine'); else CmdLine=varargin{4}; end if nargin<3, bGX=1; else bGX=varargin{3}; end if nargin<2, Iname=''; else Iname=varargin{2}; end if CmdLine Finter = spm_figure('FindWin','Interactive'); if ~isempty(Finter), spm_figure('Clear',Finter), end %if ~isempty(Iname), fprintf('%s:\n',Iname), end else Finter = spm_figure('GetWin','Interactive'); spm_figure('Clear',Finter) if ~isempty(Iname) str = sprintf('%s (%s): %s',spm('ver'),spm('GetUser'),Iname); else str = ''; end set(Finter,'Name',str) end if bGX Fgraph = spm_figure('GetWin','Graphics'); spm_figure('Clear',Fgraph) else Fgraph = spm_figure('FindWin','Graphics'); end varargout = {Finter,Fgraph,CmdLine}; %======================================================================= case 'winscale' %-Window scale factors (to fit display) %======================================================================= % WS = spm('WinScale') %----------------------------------------------------------------------- S0 = spm('WinSize','0',1); if all(ismember(S0(:),[0 1])) varargout = {[1 1 1 1]}; return; end tmp = [S0(3)/1152 (S0(4)-50)/900]; varargout = {min(tmp)*[1 1 1 1]}; % Make sure that aspect ratio is about right - for funny shaped screens % varargout = {[S0(3)/1152 (S0(4)-50)/900 S0(3)/1152 (S0(4)-50)/900]}; %======================================================================= case {'fontsize','fontsizes','fontscale'} %-Font scaling %======================================================================= % [FS,sf] = spm('FontSize',FS) % [FS,sf] = spm('FontSizes',FS) % sf = spm('FontScale') %----------------------------------------------------------------------- if nargin<2, FS=1:36; else FS=varargin{2}; end offset = 1; %try, if ismac, offset = 1.4; end; end sf = offset + 0.85*(min(spm('WinScale'))-1); if strcmpi(Action,'fontscale') varargout = {sf}; else varargout = {ceil(FS*sf),sf}; end %======================================================================= case 'winsize' %-Standard SPM window locations and sizes %======================================================================= % Rect = spm('WinSize',Win,raw) %----------------------------------------------------------------------- if nargin<3, raw=0; else raw=1; end if nargin<2, Win=''; else Win=varargin{2}; end Rect = [[108 466 400 445];... [108 045 400 395];... [515 015 600 865];... [326 310 500 280]]; if isempty(Win) %-All windows elseif upper(Win(1))=='M' %-Menu window Rect = Rect(1,:); elseif upper(Win(1))=='I' %-Interactive window Rect = Rect(2,:); elseif upper(Win(1))=='G' %-Graphics window Rect = Rect(3,:); elseif upper(Win(1))=='W' %-Welcome window Rect = Rect(4,:); elseif Win(1)=='0' %-Root workspace Rect = get(0, 'MonitorPosition'); if all(ismember(Rect(:),[0 1])) warning('SPM:noDisplay','Unable to open display.'); end if size(Rect,1) > 1 % Multiple Monitors %-Use Monitor containing the Pointer pl = get(0,'PointerLocation'); Rect(:,[3 4]) = Rect(:,[3 4]) + Rect(:,[1 2]); w = find(pl(1)>=Rect(:,1) & pl(1)<=Rect(:,3) &... pl(2)>=Rect(:,2) & pl(2)<=Rect(:,4)); if numel(w)~=1, w = 1; end Rect = Rect(w,:); %-Make sure that the format is [x y width height] Rect(1,[3 4]) = Rect(1,[3 4]) - Rect(1,[1 2]) + 1; end else error('Unknown Win type'); end if ~raw WS = repmat(spm('WinScale'),size(Rect,1),1); Rect = Rect.*WS; end varargout = {Rect}; %======================================================================= case 'colour' %-SPM interface colour %======================================================================= % spm('Colour') %----------------------------------------------------------------------- %-Pre-developmental livery % varargout = {[1.0,0.2,0.3],'fightening red'}; %-Developmental livery % varargout = {[0.7,1.0,0.7],'flourescent green'}; %-Alpha release livery % varargout = {[0.9,0.9,0.5],'over-ripe banana'}; %-Beta release livery % varargout = {[0.9 0.8 0.9],'blackcurrant purple'}; %-Distribution livery varargout = {[0.8 0.8 1.0],'vile violet'}; try varargout = {spm_get_defaults('ui.colour'),'bluish'}; end %======================================================================= case 'figname' %-Robust SPM figure naming %======================================================================= % F = spm('FigName',Iname,F,CmdLine) %----------------------------------------------------------------------- if nargin<4, CmdLine=spm('CmdLine'); else CmdLine=varargin{4}; end if nargin<3, F='Interactive'; else F=varargin{3}; end if nargin<2, Iname=''; else Iname=varargin{2}; end %if ~isempty(Iname), fprintf('\t%s\n',Iname), end if CmdLine, varargout={[]}; return, end F = spm_figure('FindWin',F); if ~isempty(F) && ~isempty(Iname) set(F,'Name',sprintf('%s (%s): %s',spm('ver'),spm('GetUser'),Iname)) end varargout={F}; %======================================================================= case 'show' %-Bring visible MATLAB windows to the fore %======================================================================= % Fs = spm('Show') %----------------------------------------------------------------------- cF = get(0,'CurrentFigure'); Fs = get(0,'Children'); Fs = findobj(Fs,'flat','Visible','on'); for F=Fs', figure(F), end set(0,'CurrentFigure',cF) spm('FnBanner','GUI show'); varargout={Fs}; %======================================================================= case 'clear' %-Clear SPM GUI %======================================================================= % spm('Clear',Finter, Fgraph) %----------------------------------------------------------------------- if nargin<3, Fgraph='Graphics'; else Fgraph=varargin{3}; end if nargin<2, Finter='Interactive'; else Finter=varargin{2}; end spm_figure('Clear',Fgraph) spm_figure('Clear',Finter) spm('Pointer','Arrow') spm_conman('Initialise','reset'); local_clc; fprintf('\n'); %evalin('base','clear') %======================================================================= case {'fnbanner','sfnbanner','ssfnbanner'} %-Text banners for functions %======================================================================= % SPMid = spm('FnBanner', Fn,FnV) % SPMid = spm('SFnBanner',Fn,FnV) % SPMid = spm('SSFnBanner',Fn,FnV) %----------------------------------------------------------------------- time = spm('time'); str = spm('ver'); if nargin>=2, str = [str,': ',varargin{2}]; end if nargin>=3 v = regexp(varargin{3},'\$Rev: (\d*) \$','tokens','once'); if ~isempty(v) str = [str,' (v',v{1},')']; else str = [str,' (v',varargin{3},')']; end end switch lower(Action) case 'fnbanner' tab = ''; wid = 72; lch = '='; case 'sfnbanner' tab = sprintf('\t'); wid = 72-8; lch = '-'; case 'ssfnbanner' tab = sprintf('\t\t'); wid = 72-2*8; lch = '-'; end fprintf('\n%s%s',tab,str) fprintf('%c',repmat(' ',1,wid-length([str,time]))) fprintf('%s\n%s',time,tab) fprintf('%c',repmat(lch,1,wid)),fprintf('\n') varargout = {str}; %======================================================================= case 'dir' %-Identify specific (SPM) directory %======================================================================= % spm('Dir',Mfile) %----------------------------------------------------------------------- if nargin<2, Mfile='spm'; else Mfile=varargin{2}; end SPMdir = which(Mfile); if isempty(SPMdir) %-Not found or full pathname given if exist(Mfile,'file')==2 %-Full pathname SPMdir = Mfile; else error(['Can''t find ',Mfile,' on MATLABPATH']); end end SPMdir = fileparts(SPMdir); % if isdeployed % ind = findstr(SPMdir,'_mcr')-1; % if ~isempty(ind) % % MATLAB 2008a/2009a doesn't need this % SPMdir = fileparts(SPMdir(1:ind(1))); % end % end varargout = {SPMdir}; %======================================================================= case 'ver' %-SPM version %======================================================================= % [SPMver, SPMrel] = spm('Ver',Mfile,ReDo) %----------------------------------------------------------------------- if nargin > 3, warning('This usage of "spm ver" is now deprecated.'); end if nargin ~= 3, ReDo = false; else ReDo = logical(varargin{3}); end if nargin == 1 || (nargin > 1 && isempty(varargin{2})) Mfile = ''; else Mfile = which(varargin{2}); if isempty(Mfile) error('Can''t find %s on MATLABPATH.',varargin{2}); end end v = spm_version(ReDo); if isempty(Mfile) varargout = {v.Release v.Version}; else unknown = struct('file',Mfile,'id','???','date','','author',''); if ~isdeployed fp = fopen(Mfile,'rt'); if fp == -1, error('Can''t read %s.',Mfile); end str = fread(fp,Inf,'*uchar'); fclose(fp); str = char(str(:)'); r = regexp(str,['\$Id: (?<file>\S+) (?<id>[0-9]+) (?<date>\S+) ' ... '(\S+Z) (?<author>\S+) \$'],'names','once'); if isempty(r), r = unknown; end else r = unknown; end varargout = {r(1).id v.Release}; end %======================================================================= case 'mlver' %-MATLAB major & point version number %======================================================================= % v = spm('MLver') %----------------------------------------------------------------------- v = version; tmp = find(v=='.'); if length(tmp)>1, varargout={v(1:tmp(2)-1)}; end %======================================================================= case 'tbs' %-Identify installed toolboxes %======================================================================= % xTB = spm('TBs') %----------------------------------------------------------------------- % Toolbox directory %----------------------------------------------------------------------- Tdir = fullfile(spm('Dir'),'toolbox'); %-List of potential installed toolboxes directories %----------------------------------------------------------------------- if exist(Tdir,'dir') d = dir(Tdir); d = {d([d.isdir]).name}; d = {d{cellfun('isempty',regexp(d,'^\.'))}}; else d = {}; end %-Look for a "main" M-file in each potential directory %----------------------------------------------------------------------- xTB = []; for i = 1:length(d) tdir = fullfile(Tdir,d{i}); fn = cellstr(spm_select('List',tdir,['^.*' d{i} '\.m$'])); if ~isempty(fn{1}), xTB(end+1).name = strrep(d{i},'_',''); xTB(end).prog = spm_str_manip(fn{1},'r'); xTB(end).dir = tdir; end end varargout{1} = xTB; %======================================================================= case 'tblaunch' %-Launch an SPM toolbox %======================================================================= % xTB = spm('TBlaunch',xTB,i) %----------------------------------------------------------------------- if nargin < 3, i = 1; else i = varargin{3}; end if nargin < 2, xTB = spm('TBs'); else xTB = varargin{2}; end if i > 0 %-Addpath (& report) %------------------------------------------------------------------- if isempty(findstr(xTB(i).dir,path)) if ~isdeployed, addpath(xTB(i).dir,'-begin'); end spm('alert"',{'Toolbox directory prepended to Matlab path:',... xTB(i).dir},... [xTB(i).name,' toolbox'],1); end %-Launch %------------------------------------------------------------------- evalin('base',xTB(i).prog); end %======================================================================= case 'getglobal' %-Get global variable cleanly %======================================================================= % varargout = spm('GetGlobal',varargin) %----------------------------------------------------------------------- wg = who('global'); for i=1:nargin-1 if any(strcmp(wg,varargin{i+1})) eval(['global ',varargin{i+1},', tmp=',varargin{i+1},';']) varargout{i} = tmp; else varargout{i} = []; end end %======================================================================= case {'cmdline'} %-SPM command line mode? %======================================================================= % CmdLine = spm('CmdLine',CmdLine) %----------------------------------------------------------------------- if nargin<2, CmdLine=[]; else CmdLine=varargin{2}; end if isempty(CmdLine) defaults = spm('getglobal','defaults'); if isfield(defaults,'cmdline') CmdLine = defaults.cmdline; else CmdLine = 0; end end varargout = {CmdLine || (get(0,'ScreenDepth')==0)}; %======================================================================= case 'popupcb' %-Callback handling utility for PopUp menus %======================================================================= % spm('PopUpCB',h) %----------------------------------------------------------------------- if nargin<2, h=gcbo; else h=varargin{2}; end v = get(h,'Value'); if v==1, return, end set(h,'Value',1) CBs = get(h,'UserData'); evalin('base',CBs{v-1}) %======================================================================= case 'getuser' %-Get user name %======================================================================= % str = spm('GetUser',fmt) %----------------------------------------------------------------------- str = spm_platform('user'); if ~isempty(str) && nargin>1, str = sprintf(varargin{2},str); end varargout = {str}; %======================================================================= case 'beep' %-Produce beep sound %======================================================================= % spm('Beep') %----------------------------------------------------------------------- beep; %======================================================================= case 'time' %-Return formatted date/time string %======================================================================= % [timestr, date_vec] = spm('Time') %----------------------------------------------------------------------- tmp = clock; varargout = {sprintf('%02d:%02d:%02d - %02d/%02d/%4d',... tmp(4),tmp(5),floor(tmp(6)),tmp(3),tmp(2),tmp(1)), tmp}; %======================================================================= case 'memory' %======================================================================= % m = spm('Memory') %----------------------------------------------------------------------- maxmemdef = 200*1024*1024; m = maxmemdef; varargout = {m}; %======================================================================= case 'pointer' %-Set mouse pointer in all MATLAB windows %======================================================================= % spm('Pointer',Pointer) %----------------------------------------------------------------------- if nargin<2, Pointer='Arrow'; else Pointer=varargin{2}; end set(get(0,'Children'),'Pointer',Pointer) %======================================================================= case {'alert','alert"','alert*','alert!'} %-Alert dialogs %======================================================================= % h = spm('alert',Message,Title,CmdLine,wait) %----------------------------------------------------------------------- %- Globals %----------------------------------------------------------------------- if nargin<5, wait = 0; else wait = varargin{5}; end if nargin<4, CmdLine = []; else CmdLine = varargin{4}; end if nargin<3, Title = ''; else Title = varargin{3}; end if nargin<2, Message = ''; else Message = varargin{2}; end Message = cellstr(Message); if isreal(CmdLine) CmdLine = spm('CmdLine',CmdLine); CmdLine2 = 0; else CmdLine = spm('CmdLine'); CmdLine2 = 1; end timestr = spm('Time'); SPMv = spm('ver'); switch(lower(Action)) case 'alert', icon = 'none'; str = '--- '; case 'alert"', icon = 'help'; str = '~ - '; case 'alert*', icon = 'error'; str = '* - '; case 'alert!', icon = 'warn'; str = '! - '; end if CmdLine || CmdLine2 Message(strcmp(Message,'')) = {' '}; tmp = sprintf('%s: %s',SPMv,Title); fprintf('\n %s%s %s\n\n',str,tmp,repmat('-',1,62-length(tmp))) fprintf(' %s\n',Message{:}) fprintf('\n %s %s\n\n',repmat('-',1,62-length(timestr)),timestr) h = []; end if ~CmdLine tmp = max(size(char(Message),2),42) - length(SPMv) - length(timestr); str = sprintf('%s %s %s',SPMv,repmat(' ',1,tmp-4),timestr); h = msgbox([{''};Message(:);{''};{''};{str}],... sprintf('%s%s: %s',SPMv,spm('GetUser',' (%s)'),Title),... icon,'non-modal'); drawnow set(h,'windowstyle','modal'); end if wait if isempty(h) input(' press ENTER to continue...'); else uiwait(h) h = []; end end if nargout, varargout = {h}; end %======================================================================= case 'gui_filedelete' %-GUI file deletion %======================================================================= % spm('GUI_FileDelete') %----------------------------------------------------------------------- [P, sts] = spm_select(Inf,'.*','Select file(s) to delete'); if ~sts, return; end P = cellstr(P); n = numel(P); if n==0 || (n==1 && isempty(P{1})) spm('alert"','Nothing selected to delete!','file delete',0); return elseif n<4 str=[{' '};P]; elseif n<11 str=[{' '};P;{' ';sprintf('(%d files)',n)}]; else str=[{' '};P(1:min(n,10));{'...';' ';sprintf('(%d files)',n)}]; end if spm_input(str,-1,'bd','delete|cancel',[1,0],[],'confirm file delete') feval(@spm_unlink,P{:}); spm('alert"',P,'file delete',1); end %======================================================================= case 'clean' %-Clean MATLAB workspace %======================================================================= % spm('Clean') %----------------------------------------------------------------------- evalin('base','clear all'); evalc('clear classes'); %======================================================================= case 'help' %-Pass through for spm_help %======================================================================= % spm('Help',varargin) %----------------------------------------------------------------------- if nargin>1, spm_help(varargin{2:end}), else spm_help, end %======================================================================= case 'quit' %-Quit SPM and clean up %======================================================================= % spm('Quit') %----------------------------------------------------------------------- delete(get(0,'Children')); local_clc; fprintf('Bye for now...\n\n'); %======================================================================= otherwise %-Unknown action string %======================================================================= error('Unknown action string'); %======================================================================= end %======================================================================= function local_clc %-Clear command window %======================================================================= if ~isdeployed clc; end %======================================================================= function v = spm_version(ReDo) %-Retrieve SPM version %======================================================================= persistent SPM_VER; v = SPM_VER; if isempty(SPM_VER) || (nargin > 0 && ReDo) v = struct('Name','','Version','','Release','','Date',''); try fid = fopen(fullfile(spm('Dir'),'Contents.m'),'rt'); if fid == -1, error(str); end l1 = fgetl(fid); l2 = fgetl(fid); fclose(fid); l1 = strtrim(l1(2:end)); l2 = strtrim(l2(2:end)); t = textscan(l2,'%s','delimiter',' '); t = t{1}; v.Name = l1; v.Date = t{4}; v.Version = t{2}; v.Release = t{3}(2:end-1); catch if isdeployed % in deployed mode, M-files are encrypted % (but first two lines of Contents.m should be preserved) v.Name = 'Statistical Parametric Mapping'; v.Version = '8'; v.Release = 'SPM8'; v.Date = date; else error('Can''t obtain SPM Revision information.'); end end SPM_VER = v; end
github
lcnhappe/happe-master
spm_orthviews.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_orthviews.m
77,288
utf_8
8878b323c3d77a20da9a6c983c6cb96a
function varargout = spm_orthviews(action,varargin) % Display Orthogonal Views of a Normalized Image % FORMAT H = spm_orthviews('Image',filename[,position]) % filename - name of image to display % area - position of image % - area(1) - position x % - area(2) - position y % - area(3) - size x % - area(4) - size y % H - handle for ortho sections % FORMAT spm_orthviews('BB',bb) % bb - bounding box % [loX loY loZ % hiX hiY hiZ] % % FORMAT spm_orthviews('Redraw') % Redraws the images % % FORMAT spm_orthviews('Reposition',centre) % centre - X, Y & Z coordinates of centre voxel % % FORMAT spm_orthviews('Space'[,handle[,M,dim]]) % handle - the view to define the space by, optionally with extra % transformation matrix and dimensions (e.g. one of the blobs % of a view) % with no arguments - puts things into mm space % % FORMAT spm_orthviews('MaxBB') % sets the bounding box big enough display the whole of all images % % FORMAT spm_orthviews('Resolution',res) % res - resolution (mm) % % FORMAT spm_orthviews('Delete', handle) % handle - image number to delete % % FORMAT spm_orthviews('Reset') % clears the orthogonal views % % FORMAT spm_orthviews('Pos') % returns the co-ordinate of the crosshairs in millimetres in the % standard space. % % FORMAT spm_orthviews('Pos', i) % returns the voxel co-ordinate of the crosshairs in the image in the % ith orthogonal section. % % FORMAT spm_orthviews('Xhairs','off') OR spm_orthviews('Xhairs') % disables the cross-hairs on the display. % % FORMAT spm_orthviews('Xhairs','on') % enables the cross-hairs. % % FORMAT spm_orthviews('Interp',hld) % sets the hold value to hld (see spm_slice_vol). % % FORMAT spm_orthviews('AddBlobs',handle,XYZ,Z,mat) % Adds blobs from a pointlist to the image specified by the handle(s). % handle - image number to add blobs to % XYZ - blob voxel locations % Z - blob voxel intensities % mat - matrix from voxels to millimeters of blob. % name - a name for this blob % This method only adds one set of blobs, and displays them using a % split colour table. % % FORMAT spm_orthviews('AddColouredBlobs',handle,XYZ,Z,mat,colour,name) % Adds blobs from a pointlist to the image specified by the handle(s). % handle - image number to add blobs to % XYZ - blob voxel locations % Z - blob voxel intensities % mat - matrix from voxels to millimeters of blob. % colour - the 3 vector containing the colour that the blobs should be % name - a name for this blob % Several sets of blobs can be added in this way, and it uses full colour. % Although it may not be particularly attractive on the screen, the colour % blobs print well. % % FORMAT spm_orthviews('AddColourBar',handle,blobno) % Adds colourbar for a specified blob set % handle - image number % blobno - blob number % % FORMAT spm_orthviews('RemoveBlobs',handle) % Removes all blobs from the image specified by the handle(s). % % FORMAT spm_orthviews('Register',hReg) % hReg - Handle of HandleGraphics object to build registry in. % See spm_XYZreg for more information. % % spm_orthviews('AddContext',handle) % handle - image number to add context menu to % % spm_orthviews('RemoveContext',handle) % handle - image number to remove context menu from % % CONTEXT MENU % spm_orthviews offers many of its features in a context menu, which is % accessible via the right mouse button in each displayed image. % % PLUGINS % The display capabilities of spm_orthviews can be extended with % plugins. These are located in the spm_orthviews subdirectory of the SPM % distribution. Currently there are 3 plugins available: % quiver Add Quiver plots to a displayed image % quiver3d Add 3D Quiver plots to a displayed image % roi ROI creation and modification % The functionality of plugins can be accessed via calls to % spm_orthviews('plugin_name', plugin_arguments). For detailed descriptions % of each plugin see help spm_orthviews/spm_ov_'plugin_name'. % %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner, Matthew Brett, Tom Nichols and Volkmar Glauche % $Id$ % The basic fields of st are: % n - the number of images currently being displayed % vols - a cell array containing the data on each of the % displayed images. % Space - a mapping between the displayed images and the % mm space of each image. % bb - the bounding box of the displayed images. % centre - the current centre of the orthogonal views % callback - a callback to be evaluated on a button-click. % xhairs - crosshairs off/on % hld - the interpolation method % fig - the figure that everything is displayed in % mode - the position/orientation of the sagittal view. % - currently always 1 % % st.registry.hReg \_ See spm_XYZreg for documentation % st.registry.hMe / % % For each of the displayed images, there is a non-empty entry in the % vols cell array. Handles returned by "spm_orthviews('Image',.....)" % indicate the position in the cell array of the newly created ortho-view. % Operations on each ortho-view require the handle to be passed. % % When a new image is displayed, the cell entry contains the information % returned by spm_vol (type help spm_vol for more info). In addition, % there are a few other fields, some of which I will document here: % % premul - a matrix to premultiply the .mat field by. Useful % for re-orienting images. % window - either 'auto' or an intensity range to display the % image with. % mapping- Mapping of image intensities to grey values. Currently % one of 'linear', 'histeq', loghisteq', % 'quadhisteq'. Default is 'linear'. % Histogram equalisation depends on the image toolbox % and is only available if there is a license available % for it. % ax - a cell array containing an element for the three % views. The fields of each element are handles for % the axis, image and crosshairs. % % blobs - optional. Is there for using to superimpose blobs. % vol - 3D array of image data % mat - a mapping from vox-to-mm (see spm_vol, or % help on image formats). % max - maximum intensity for scaling to. If it % does not exist, then images are auto-scaled. % % There are two colouring modes: full colour, and split % colour. When using full colour, there should be a % 'colour' field for each cell element. When using % split colourscale, there is a handle for the colorbar % axis. % % colour - if it exists it contains the % red,green,blue that the blobs should be % displayed in. % cbar - handle for colorbar (for split colourscale). % % PLUGINS % The plugin concept has been developed to extend the display capabilities % of spm_orthviews without the need to rewrite parts of it. Interaction % between spm_orthviews and plugins takes place % a) at startup: The subfunction 'reset_st' looks for folders % 'spm_orthviews' in spm('Dir') and each toolbox % folder. Files with a name spm_ov_PLUGINNAME.m in any of % these folders will be treated as plugins. % For each such file, PLUGINNAME will be added to the list % st.plugins{:}. % The subfunction 'add_context' calls each plugin with % feval(['spm_ov_', st.plugins{k}], ... % 'context_menu', i, parent_menu) % Each plugin may add its own submenu to the context % menu. % b) at redraw: After images and blobs of st.vols{i} are drawn, the % struct st.vols{i} is checked for field names that occur in % the plugin list st.plugins{:}. For each matching entry, the % corresponding plugin is called with the command 'redraw': % feval(['spm_ov_', st.plugins{k}], ... % 'redraw', i, TM0, TD, CM0, CD, SM0, SD); % The values of TM0, TD, CM0, CD, SM0, SD are defined in the % same way as in the redraw subfunction of spm_orthviews. % It is up to the plugin to do all necessary redraw % operations for its display contents. Each displayed item % must have set its property 'HitTest' to 'off' to let events % go through to the underlying axis, which is responsible for % callback handling. The order in which plugins are called is % undefined. global st; if isempty(st), reset_st; end; spm('Pointer','watch'); if nargin == 0, action = ''; end; action = lower(action); switch lower(action), case 'image', H = specify_image(varargin{1}); if ~isempty(H) st.vols{H}.area = [0 0 1 1]; if numel(varargin)>=2, st.vols{H}.area = varargin{2}; end; if isempty(st.bb), st.bb = maxbb; end; bbox; cm_pos; end; varargout{1} = H; st.centre = mean(maxbb); redraw_all case 'bb', if ~isempty(varargin) && all(size(varargin{1})==[2 3]), st.bb = varargin{1}; end; bbox; redraw_all; case 'redraw', redraw_all; eval(st.callback); if isfield(st,'registry'), spm_XYZreg('SetCoords',st.centre,st.registry.hReg,st.registry.hMe); end; case 'reposition', if isempty(varargin), tmp = findcent; else tmp = varargin{1}; end; if numel(tmp) == 3 h = valid_handles(st.snap); if ~isempty(h) tmp = st.vols{h(1)}.mat * ... round(st.vols{h(1)}.mat\[tmp(:); 1]); end st.centre = tmp(1:3); end redraw_all; eval(st.callback); if isfield(st,'registry'), spm_XYZreg('SetCoords',st.centre,st.registry.hReg,st.registry.hMe); end cm_pos; case 'setcoords', st.centre = varargin{1}; st.centre = st.centre(:); redraw_all; eval(st.callback); cm_pos; case 'space', if numel(varargin)<1, st.Space = eye(4); st.bb = maxbb; bbox; redraw_all; else space(varargin{:}); bbox; redraw_all; end; case 'maxbb', st.bb = maxbb; bbox; redraw_all; case 'resolution', resolution(varargin{1}); bbox; redraw_all; case 'window', if numel(varargin)<2, win = 'auto'; elseif numel(varargin{2})==2, win = varargin{2}; end; for i=valid_handles(varargin{1}), st.vols{i}.window = win; end; redraw(varargin{1}); case 'delete', my_delete(varargin{1}); case 'move', move(varargin{1},varargin{2}); % redraw_all; case 'reset', my_reset; case 'pos', if isempty(varargin), H = st.centre(:); else H = pos(varargin{1}); end; varargout{1} = H; case 'interp', st.hld = varargin{1}; redraw_all; case 'xhairs', xhairs(varargin{1}); case 'register', register(varargin{1}); case 'addblobs', addblobs(varargin{:}); % redraw(varargin{1}); case 'addcolouredblobs', addcolouredblobs(varargin{:}); % redraw(varargin{1}); case 'addimage', addimage(varargin{1}, varargin{2}); % redraw(varargin{1}); case 'addcolouredimage', addcolouredimage(varargin{1}, varargin{2},varargin{3}); % redraw(varargin{1}); case 'addtruecolourimage', % spm_orthviews('Addtruecolourimage',handle,filename,colourmap,prop,mx,mn) % Adds blobs from an image in true colour % handle - image number to add blobs to [default 1] % filename of image containing blob data [default - request via GUI] % colourmap - colormap to display blobs in [GUI input] % prop - intensity proportion of activation cf grayscale [0.4] % mx - maximum intensity to scale to [maximum value in activation image] % mn - minimum intensity to scale to [minimum value in activation image] % if nargin < 2 varargin(1) = {1}; end if nargin < 3 varargin(2) = {spm_select(1, 'image', 'Image with activation signal')}; end if nargin < 4 actc = []; while isempty(actc) actc = getcmap(spm_input('Colourmap for activation image', '+1','s')); end varargin(3) = {actc}; end if nargin < 5 varargin(4) = {0.4}; end if nargin < 6 actv = spm_vol(varargin{2}); varargin(5) = {max([eps maxval(actv)])}; end if nargin < 7 varargin(6) = {min([0 minval(actv)])}; end addtruecolourimage(varargin{1}, varargin{2},varargin{3}, varargin{4}, ... varargin{5}, varargin{6}); % redraw(varargin{1}); case 'addcolourbar', addcolourbar(varargin{1}, varargin{2}); case 'rmblobs', rmblobs(varargin{1}); redraw(varargin{1}); case 'addcontext', if nargin == 1, handles = 1:24; else handles = varargin{1}; end; addcontexts(handles); case 'rmcontext', if nargin == 1, handles = 1:24; else handles = varargin{1}; end; rmcontexts(handles); case 'context_menu', c_menu(varargin{:}); case 'valid_handles', if nargin == 1 handles = 1:24; else handles = varargin{1}; end; varargout{1} = valid_handles(handles); otherwise, addonaction = strcmp(st.plugins,action); if any(addonaction) feval(['spm_ov_' st.plugins{addonaction}],varargin{:}); end; end; spm('Pointer'); return; %_______________________________________________________________________ %_______________________________________________________________________ function addblobs(handle, xyz, t, mat, name) global st if nargin < 5 name = ''; end; for i=valid_handles(handle), if ~isempty(xyz), rcp = round(xyz); dim = max(rcp,[],2)'; off = rcp(1,:) + dim(1)*(rcp(2,:)-1 + dim(2)*(rcp(3,:)-1)); vol = zeros(dim)+NaN; vol(off) = t; vol = reshape(vol,dim); st.vols{i}.blobs=cell(1,1); mx = max([eps max(t)]); mn = min([0 min(t)]); st.vols{i}.blobs{1} = struct('vol',vol,'mat',mat,'max',mx, 'min',mn,'name',name); addcolourbar(handle,1); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function addimage(handle, fname) global st for i=valid_handles(handle), if isstruct(fname), vol = fname(1); else vol = spm_vol(fname); end; mat = vol.mat; st.vols{i}.blobs=cell(1,1); mx = max([eps maxval(vol)]); mn = min([0 minval(vol)]); st.vols{i}.blobs{1} = struct('vol',vol,'mat',mat,'max',mx,'min',mn); addcolourbar(handle,1); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function addcolouredblobs(handle, xyz, t, mat, colour, name) if nargin < 6 name = ''; end; global st for i=valid_handles(handle), if ~isempty(xyz), rcp = round(xyz); dim = max(rcp,[],2)'; off = rcp(1,:) + dim(1)*(rcp(2,:)-1 + dim(2)*(rcp(3,:)-1)); vol = zeros(dim)+NaN; vol(off) = t; vol = reshape(vol,dim); if ~isfield(st.vols{i},'blobs'), st.vols{i}.blobs=cell(1,1); bset = 1; else bset = numel(st.vols{i}.blobs)+1; end; mx = max([eps maxval(vol)]); mn = min([0 minval(vol)]); st.vols{i}.blobs{bset} = struct('vol',vol, 'mat',mat, ... 'max',mx, 'min',mn, ... 'colour',colour, 'name',name); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function addcolouredimage(handle, fname,colour) global st for i=valid_handles(handle), if isstruct(fname), vol = fname(1); else vol = spm_vol(fname); end; mat = vol.mat; if ~isfield(st.vols{i},'blobs'), st.vols{i}.blobs=cell(1,1); bset = 1; else bset = numel(st.vols{i}.blobs)+1; end; mx = max([eps maxval(vol)]); mn = min([0 minval(vol)]); st.vols{i}.blobs{bset} = struct('vol',vol,'mat',mat,'max',mx,'min',mn,'colour',colour); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function addtruecolourimage(handle,fname,colourmap,prop,mx,mn) % adds true colour image to current displayed image global st for i=valid_handles(handle), if isstruct(fname), vol = fname(1); else vol = spm_vol(fname); end; mat = vol.mat; if ~isfield(st.vols{i},'blobs'), st.vols{i}.blobs=cell(1,1); bset = 1; else bset = numel(st.vols{i}.blobs)+1; end; c = struct('cmap', colourmap,'prop',prop); st.vols{i}.blobs{bset} = struct('vol',vol,'mat',mat,'max',mx, ... 'min',mn,'colour',c); addcolourbar(handle,bset); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function addcolourbar(vh,bh) global st if st.mode == 0, axpos = get(st.vols{vh}.ax{2}.ax,'Position'); else axpos = get(st.vols{vh}.ax{1}.ax,'Position'); end; st.vols{vh}.blobs{bh}.cbar = axes('Parent',st.fig,... 'Position',[(axpos(1)+axpos(3)+0.05+(bh-1)*.1) (axpos(2)+0.005) 0.05 (axpos(4)-0.01)],... 'Box','on', 'YDir','normal', 'XTickLabel',[], 'XTick',[]); if isfield(st.vols{vh}.blobs{bh},'name') ylabel(st.vols{vh}.blobs{bh}.name,'parent',st.vols{vh}.blobs{bh}.cbar); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function rmblobs(handle) global st for i=valid_handles(handle), if isfield(st.vols{i},'blobs'), for j=1:numel(st.vols{i}.blobs), if isfield(st.vols{i}.blobs{j},'cbar') && ishandle(st.vols{i}.blobs{j}.cbar), delete(st.vols{i}.blobs{j}.cbar); end; end; st.vols{i} = rmfield(st.vols{i},'blobs'); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function register(hreg) global st tmp = uicontrol('Position',[0 0 1 1],'Visible','off','Parent',st.fig); h = valid_handles(1:24); if ~isempty(h), tmp = st.vols{h(1)}.ax{1}.ax; st.registry = struct('hReg',hreg,'hMe', tmp); spm_XYZreg('Add2Reg',st.registry.hReg,st.registry.hMe, 'spm_orthviews'); else warning('Nothing to register with'); end; st.centre = spm_XYZreg('GetCoords',st.registry.hReg); st.centre = st.centre(:); return; %_______________________________________________________________________ %_______________________________________________________________________ function xhairs(arg1) global st st.xhairs = 0; opt = 'on'; if ~strcmp(arg1,'on'), opt = 'off'; else st.xhairs = 1; end; for i=valid_handles(1:24), for j=1:3, set(st.vols{i}.ax{j}.lx,'Visible',opt); set(st.vols{i}.ax{j}.ly,'Visible',opt); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function H = pos(arg1) global st H = []; for arg1=valid_handles(arg1), is = inv(st.vols{arg1}.premul*st.vols{arg1}.mat); H = is(1:3,1:3)*st.centre(:) + is(1:3,4); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function my_reset global st if ~isempty(st) && isfield(st,'registry') && ishandle(st.registry.hMe), delete(st.registry.hMe); st = rmfield(st,'registry'); end; my_delete(1:24); reset_st; return; %_______________________________________________________________________ %_______________________________________________________________________ function my_delete(arg1) global st % remove blobs (and colourbars, if any) rmblobs(arg1); % remove displayed axes for i=valid_handles(arg1), kids = get(st.fig,'Children'); for j=1:3, if any(kids == st.vols{i}.ax{j}.ax), set(get(st.vols{i}.ax{j}.ax,'Children'),'DeleteFcn',''); delete(st.vols{i}.ax{j}.ax); end; end; st.vols{i} = []; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function resolution(arg1) global st res = arg1/mean(svd(st.Space(1:3,1:3))); Mat = diag([res res res 1]); st.Space = st.Space*Mat; st.bb = st.bb/res; return; %_______________________________________________________________________ %_______________________________________________________________________ function move(handle,pos) global st for handle = valid_handles(handle), st.vols{handle}.area = pos; end; bbox; % redraw(valid_handles(handle)); return; %_______________________________________________________________________ %_______________________________________________________________________ function bb = maxbb global st mn = [Inf Inf Inf]; mx = -mn; for i=valid_handles(1:24), bb = [[1 1 1];st.vols{i}.dim(1:3)]; 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 = st.Space\(st.vols{i}.premul*st.vols{i}.mat)*c; tc = tc(1:3,:)'; mx = max([tc ; mx]); mn = min([tc ; mn]); end; bb = [mn ; mx]; return; %_______________________________________________________________________ %_______________________________________________________________________ function space(arg1,M,dim) global st if ~isempty(st.vols{arg1}) num = arg1; if nargin < 2 M = st.vols{num}.mat; dim = st.vols{num}.dim(1:3); end; Mat = st.vols{num}.premul(1:3,1:3)*M(1:3,1:3); vox = sqrt(sum(Mat.^2)); if det(Mat(1:3,1:3))<0, vox(1) = -vox(1); end; Mat = diag([vox 1]); Space = (M)/Mat; bb = [1 1 1; dim]; bb = [bb [1;1]]; bb=bb*Mat'; bb=bb(:,1:3); bb=sort(bb); st.Space = Space; st.bb = bb; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function H = specify_image(arg1) global st H=[]; if isstruct(arg1), V = arg1(1); else try V = spm_vol(arg1); catch fprintf('Can not use image "%s"\n', arg1); return; end; end; ii = 1; while ~isempty(st.vols{ii}), ii = ii + 1; end; DeleteFcn = ['spm_orthviews(''Delete'',' num2str(ii) ');']; V.ax = cell(3,1); for i=1:3, ax = axes('Visible','off','DrawMode','fast','Parent',st.fig,'DeleteFcn',DeleteFcn,... 'YDir','normal','ButtonDownFcn',@repos_start); d = image(0,'Tag','Transverse','Parent',ax,... 'DeleteFcn',DeleteFcn); set(ax,'Ydir','normal','ButtonDownFcn',@repos_start); lx = line(0,0,'Parent',ax,'DeleteFcn',DeleteFcn); ly = line(0,0,'Parent',ax,'DeleteFcn',DeleteFcn); if ~st.xhairs, set(lx,'Visible','off'); set(ly,'Visible','off'); end; V.ax{i} = struct('ax',ax,'d',d,'lx',lx,'ly',ly); end; V.premul = eye(4); V.window = 'auto'; V.mapping = 'linear'; st.vols{ii} = V; H = ii; return; %_______________________________________________________________________ %_______________________________________________________________________ function repos_start(varargin) % don't use right mouse button to start reposition if ~strcmpi(get(gcbf,'SelectionType'),'alt') set(gcbf,'windowbuttonmotionfcn',@repos_move, 'windowbuttonupfcn',@repos_end); spm_orthviews('reposition'); end %_______________________________________________________________________ %_______________________________________________________________________ function repos_move(varargin) spm_orthviews('reposition'); %_______________________________________________________________________ %_______________________________________________________________________ function repos_end(varargin) set(gcbf,'windowbuttonmotionfcn','', 'windowbuttonupfcn',''); %_______________________________________________________________________ %_______________________________________________________________________ function addcontexts(handles) for ii = valid_handles(handles), addcontext(ii); end; spm_orthviews('reposition',spm_orthviews('pos')); return; %_______________________________________________________________________ %_______________________________________________________________________ function rmcontexts(handles) global st for ii = valid_handles(handles), for i=1:3, set(st.vols{ii}.ax{i}.ax,'UIcontextmenu',[]); st.vols{ii}.ax{i} = rmfield(st.vols{ii}.ax{i},'cm'); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function bbox global st Dims = diff(st.bb)'+1; TD = Dims([1 2])'; CD = Dims([1 3])'; if st.mode == 0, SD = Dims([3 2])'; else SD = Dims([2 3])'; end; un = get(st.fig,'Units');set(st.fig,'Units','Pixels'); sz = get(st.fig,'Position');set(st.fig,'Units',un); sz = sz(3:4); sz(2) = sz(2)-40; for i=valid_handles(1:24), area = st.vols{i}.area(:); area = [area(1)*sz(1) area(2)*sz(2) area(3)*sz(1) area(4)*sz(2)]; if st.mode == 0, sx = area(3)/(Dims(1)+Dims(3))/1.02; else sx = area(3)/(Dims(1)+Dims(2))/1.02; end; sy = area(4)/(Dims(2)+Dims(3))/1.02; s = min([sx sy]); offy = (area(4)-(Dims(2)+Dims(3))*1.02*s)/2 + area(2); sky = s*(Dims(2)+Dims(3))*0.02; if st.mode == 0, offx = (area(3)-(Dims(1)+Dims(3))*1.02*s)/2 + area(1); skx = s*(Dims(1)+Dims(3))*0.02; else offx = (area(3)-(Dims(1)+Dims(2))*1.02*s)/2 + area(1); skx = s*(Dims(1)+Dims(2))*0.02; end; % Transverse set(st.vols{i}.ax{1}.ax,'Units','pixels', ... 'Position',[offx offy s*Dims(1) s*Dims(2)],... 'Units','normalized','Xlim',[0 TD(1)]+0.5,'Ylim',[0 TD(2)]+0.5,... 'Visible','on','XTick',[],'YTick',[]); % Coronal set(st.vols{i}.ax{2}.ax,'Units','Pixels',... 'Position',[offx offy+s*Dims(2)+sky s*Dims(1) s*Dims(3)],... 'Units','normalized','Xlim',[0 CD(1)]+0.5,'Ylim',[0 CD(2)]+0.5,... 'Visible','on','XTick',[],'YTick',[]); % Sagittal if st.mode == 0, set(st.vols{i}.ax{3}.ax,'Units','Pixels', 'Box','on',... 'Position',[offx+s*Dims(1)+skx offy s*Dims(3) s*Dims(2)],... 'Units','normalized','Xlim',[0 SD(1)]+0.5,'Ylim',[0 SD(2)]+0.5,... 'Visible','on','XTick',[],'YTick',[]); else set(st.vols{i}.ax{3}.ax,'Units','Pixels', 'Box','on',... 'Position',[offx+s*Dims(1)+skx offy+s*Dims(2)+sky s*Dims(2) s*Dims(3)],... 'Units','normalized','Xlim',[0 SD(1)]+0.5,'Ylim',[0 SD(2)]+0.5,... 'Visible','on','XTick',[],'YTick',[]); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function redraw_all redraw(1:24); return; %_______________________________________________________________________ function mx = maxval(vol) if isstruct(vol), mx = -Inf; for i=1:vol.dim(3), tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0); imx = max(tmp(isfinite(tmp))); if ~isempty(imx),mx = max(mx,imx);end end; else mx = max(vol(isfinite(vol))); end; %_______________________________________________________________________ function mn = minval(vol) if isstruct(vol), mn = Inf; for i=1:vol.dim(3), tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0); imn = min(tmp(isfinite(tmp))); if ~isempty(imn),mn = min(mn,imn);end end; else mn = min(vol(isfinite(vol))); end; %_______________________________________________________________________ %_______________________________________________________________________ function redraw(arg1) global st bb = st.bb; Dims = round(diff(bb)'+1); is = inv(st.Space); cent = is(1:3,1:3)*st.centre(:) + is(1:3,4); for i = valid_handles(arg1), M = st.vols{i}.premul*st.vols{i}.mat; TM0 = [ 1 0 0 -bb(1,1)+1 0 1 0 -bb(1,2)+1 0 0 1 -cent(3) 0 0 0 1]; TM = inv(TM0*(st.Space\M)); TD = Dims([1 2]); CM0 = [ 1 0 0 -bb(1,1)+1 0 0 1 -bb(1,3)+1 0 1 0 -cent(2) 0 0 0 1]; CM = inv(CM0*(st.Space\M)); CD = Dims([1 3]); if st.mode ==0, SM0 = [ 0 0 1 -bb(1,3)+1 0 1 0 -bb(1,2)+1 1 0 0 -cent(1) 0 0 0 1]; SM = inv(SM0*(st.Space\M)); SD = Dims([3 2]); else SM0 = [ 0 -1 0 +bb(2,2)+1 0 0 1 -bb(1,3)+1 1 0 0 -cent(1) 0 0 0 1]; SM = inv(SM0*(st.Space\M)); SD = Dims([2 3]); end; try imgt = spm_slice_vol(st.vols{i},TM,TD,st.hld)'; imgc = spm_slice_vol(st.vols{i},CM,CD,st.hld)'; imgs = spm_slice_vol(st.vols{i},SM,SD,st.hld)'; ok = true; catch fprintf('Image "%s" can not be resampled\n', st.vols{i}.fname); ok = false; end if ok, % get min/max threshold if strcmp(st.vols{i}.window,'auto') mn = -Inf; mx = Inf; else mn = min(st.vols{i}.window); mx = max(st.vols{i}.window); end; % threshold images imgt = max(imgt,mn); imgt = min(imgt,mx); imgc = max(imgc,mn); imgc = min(imgc,mx); imgs = max(imgs,mn); imgs = min(imgs,mx); % compute intensity mapping, if histeq is available if license('test','image_toolbox') == 0 st.vols{i}.mapping = 'linear'; end; switch st.vols{i}.mapping, case 'linear', case 'histeq', % scale images to a range between 0 and 1 imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps); imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps); imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps); img = histeq([imgt1(:); imgc1(:); imgs1(:)],1024); imgt = reshape(img(1:numel(imgt1)),size(imgt1)); imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1)); imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1)); mn = 0; mx = 1; case 'quadhisteq', % scale images to a range between 0 and 1 imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps); imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps); imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps); img = histeq([imgt1(:).^2; imgc1(:).^2; imgs1(:).^2],1024); imgt = reshape(img(1:numel(imgt1)),size(imgt1)); imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1)); imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1)); mn = 0; mx = 1; case 'loghisteq', sw = warning('off','MATLAB:log:logOfZero'); imgt = log(imgt-min(imgt(:))); imgc = log(imgc-min(imgc(:))); imgs = log(imgs-min(imgs(:))); warning(sw); imgt(~isfinite(imgt)) = 0; imgc(~isfinite(imgc)) = 0; imgs(~isfinite(imgs)) = 0; % scale log images to a range between 0 and 1 imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps); imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps); imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps); img = histeq([imgt1(:); imgc1(:); imgs1(:)],1024); imgt = reshape(img(1:numel(imgt1)),size(imgt1)); imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1)); imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1)); mn = 0; mx = 1; end; % recompute min/max for display if strcmp(st.vols{i}.window,'auto') mx = -inf; mn = inf; end; if ~isempty(imgt), tmp = imgt(isfinite(imgt)); mx = max([mx max(max(tmp))]); mn = min([mn min(min(tmp))]); end; if ~isempty(imgc), tmp = imgc(isfinite(imgc)); mx = max([mx max(max(tmp))]); mn = min([mn min(min(tmp))]); end; if ~isempty(imgs), tmp = imgs(isfinite(imgs)); mx = max([mx max(max(tmp))]); mn = min([mn min(min(tmp))]); end; if mx==mn, mx=mn+eps; end; if isfield(st.vols{i},'blobs'), if ~isfield(st.vols{i}.blobs{1},'colour'), % Add blobs for display using the split colourmap scal = 64/(mx-mn); dcoff = -mn*scal; imgt = imgt*scal+dcoff; imgc = imgc*scal+dcoff; imgs = imgs*scal+dcoff; if isfield(st.vols{i}.blobs{1},'max'), mx = st.vols{i}.blobs{1}.max; else mx = max([eps maxval(st.vols{i}.blobs{1}.vol)]); st.vols{i}.blobs{1}.max = mx; end; if isfield(st.vols{i}.blobs{1},'min'), mn = st.vols{i}.blobs{1}.min; else mn = min([0 minval(st.vols{i}.blobs{1}.vol)]); st.vols{i}.blobs{1}.min = mn; end; vol = st.vols{i}.blobs{1}.vol; M = st.vols{i}.premul*st.vols{i}.blobs{1}.mat; tmpt = spm_slice_vol(vol,inv(TM0*(st.Space\M)),TD,[0 NaN])'; tmpc = spm_slice_vol(vol,inv(CM0*(st.Space\M)),CD,[0 NaN])'; tmps = spm_slice_vol(vol,inv(SM0*(st.Space\M)),SD,[0 NaN])'; %tmpt_z = find(tmpt==0);tmpt(tmpt_z) = NaN; %tmpc_z = find(tmpc==0);tmpc(tmpc_z) = NaN; %tmps_z = find(tmps==0);tmps(tmps_z) = NaN; sc = 64/(mx-mn); off = 65.51-mn*sc; msk = find(isfinite(tmpt)); imgt(msk) = off+tmpt(msk)*sc; msk = find(isfinite(tmpc)); imgc(msk) = off+tmpc(msk)*sc; msk = find(isfinite(tmps)); imgs(msk) = off+tmps(msk)*sc; cmap = get(st.fig,'Colormap'); if size(cmap,1)~=128 figure(st.fig) spm_figure('Colormap','gray-hot') end; redraw_colourbar(i,1,[mn mx],(1:64)'+64); elseif isstruct(st.vols{i}.blobs{1}.colour), % Add blobs for display using a defined % colourmap % colourmaps gryc = (0:63)'*ones(1,3)/63; actc = ... st.vols{1}.blobs{1}.colour.cmap; actp = ... st.vols{1}.blobs{1}.colour.prop; % scale grayscale image, not isfinite -> black imgt = scaletocmap(imgt,mn,mx,gryc,65); imgc = scaletocmap(imgc,mn,mx,gryc,65); imgs = scaletocmap(imgs,mn,mx,gryc,65); gryc = [gryc; 0 0 0]; % get max for blob image if isfield(st.vols{i}.blobs{1},'max'), cmx = st.vols{i}.blobs{1}.max; else cmx = max([eps maxval(st.vols{i}.blobs{1}.vol)]); end; if isfield(st.vols{i}.blobs{1},'min'), cmn = st.vols{i}.blobs{1}.min; else cmn = -cmx; end; % get blob data vol = st.vols{i}.blobs{1}.vol; M = st.vols{i}.premul*st.vols{i}.blobs{1}.mat; tmpt = spm_slice_vol(vol,inv(TM0*(st.Space\M)),TD,[0 NaN])'; tmpc = spm_slice_vol(vol,inv(CM0*(st.Space\M)),CD,[0 NaN])'; tmps = spm_slice_vol(vol,inv(SM0*(st.Space\M)),SD,[0 NaN])'; % actimg scaled round 0, black NaNs topc = size(actc,1)+1; tmpt = scaletocmap(tmpt,cmn,cmx,actc,topc); tmpc = scaletocmap(tmpc,cmn,cmx,actc,topc); tmps = scaletocmap(tmps,cmn,cmx,actc,topc); actc = [actc; 0 0 0]; % combine gray and blob data to % truecolour imgt = reshape(actc(tmpt(:),:)*actp+ ... gryc(imgt(:),:)*(1-actp), ... [size(imgt) 3]); imgc = reshape(actc(tmpc(:),:)*actp+ ... gryc(imgc(:),:)*(1-actp), ... [size(imgc) 3]); imgs = reshape(actc(tmps(:),:)*actp+ ... gryc(imgs(:),:)*(1-actp), ... [size(imgs) 3]); csz = size(st.vols{i}.blobs{1}.colour.cmap); cdata = reshape(st.vols{i}.blobs{1}.colour.cmap, [csz(1) 1 csz(2)]); redraw_colourbar(i,1,[cmn cmx],cdata); else % Add full colour blobs - several sets at once scal = 1/(mx-mn); dcoff = -mn*scal; wt = zeros(size(imgt)); wc = zeros(size(imgc)); ws = zeros(size(imgs)); imgt = repmat(imgt*scal+dcoff,[1,1,3]); imgc = repmat(imgc*scal+dcoff,[1,1,3]); imgs = repmat(imgs*scal+dcoff,[1,1,3]); cimgt = zeros(size(imgt)); cimgc = zeros(size(imgc)); cimgs = zeros(size(imgs)); colour = zeros(numel(st.vols{i}.blobs),3); for j=1:numel(st.vols{i}.blobs) % get colours of all images first if isfield(st.vols{i}.blobs{j},'colour'), colour(j,:) = reshape(st.vols{i}.blobs{j}.colour, [1 3]); else colour(j,:) = [1 0 0]; end; end; %colour = colour/max(sum(colour)); for j=1:numel(st.vols{i}.blobs), if isfield(st.vols{i}.blobs{j},'max'), mx = st.vols{i}.blobs{j}.max; else mx = max([eps max(st.vols{i}.blobs{j}.vol(:))]); st.vols{i}.blobs{j}.max = mx; end; if isfield(st.vols{i}.blobs{j},'min'), mn = st.vols{i}.blobs{j}.min; else mn = min([0 min(st.vols{i}.blobs{j}.vol(:))]); st.vols{i}.blobs{j}.min = mn; end; vol = st.vols{i}.blobs{j}.vol; M = st.Space\st.vols{i}.premul*st.vols{i}.blobs{j}.mat; tmpt = spm_slice_vol(vol,inv(TM0*M),TD,[0 NaN])'; tmpc = spm_slice_vol(vol,inv(CM0*M),CD,[0 NaN])'; tmps = spm_slice_vol(vol,inv(SM0*M),SD,[0 NaN])'; % check min/max of sampled image % against mn/mx as given in st tmpt(tmpt(:)<mn) = mn; tmpc(tmpc(:)<mn) = mn; tmps(tmps(:)<mn) = mn; tmpt(tmpt(:)>mx) = mx; tmpc(tmpc(:)>mx) = mx; tmps(tmps(:)>mx) = mx; tmpt = (tmpt-mn)/(mx-mn); tmpc = (tmpc-mn)/(mx-mn); tmps = (tmps-mn)/(mx-mn); tmpt(~isfinite(tmpt)) = 0; tmpc(~isfinite(tmpc)) = 0; tmps(~isfinite(tmps)) = 0; cimgt = cimgt + cat(3,tmpt*colour(j,1),tmpt*colour(j,2),tmpt*colour(j,3)); cimgc = cimgc + cat(3,tmpc*colour(j,1),tmpc*colour(j,2),tmpc*colour(j,3)); cimgs = cimgs + cat(3,tmps*colour(j,1),tmps*colour(j,2),tmps*colour(j,3)); wt = wt + tmpt; wc = wc + tmpc; ws = ws + tmps; cdata=permute(shiftdim((1/64:1/64:1)'* ... colour(j,:),-1),[2 1 3]); redraw_colourbar(i,j,[mn mx],cdata); end; imgt = repmat(1-wt,[1 1 3]).*imgt+cimgt; imgc = repmat(1-wc,[1 1 3]).*imgc+cimgc; imgs = repmat(1-ws,[1 1 3]).*imgs+cimgs; imgt(imgt<0)=0; imgt(imgt>1)=1; imgc(imgc<0)=0; imgc(imgc>1)=1; imgs(imgs<0)=0; imgs(imgs>1)=1; end; else scal = 64/(mx-mn); dcoff = -mn*scal; imgt = imgt*scal+dcoff; imgc = imgc*scal+dcoff; imgs = imgs*scal+dcoff; end; set(st.vols{i}.ax{1}.d,'HitTest','off', 'Cdata',imgt); set(st.vols{i}.ax{1}.lx,'HitTest','off',... 'Xdata',[0 TD(1)]+0.5,'Ydata',[1 1]*(cent(2)-bb(1,2)+1)); set(st.vols{i}.ax{1}.ly,'HitTest','off',... 'Ydata',[0 TD(2)]+0.5,'Xdata',[1 1]*(cent(1)-bb(1,1)+1)); set(st.vols{i}.ax{2}.d,'HitTest','off', 'Cdata',imgc); set(st.vols{i}.ax{2}.lx,'HitTest','off',... 'Xdata',[0 CD(1)]+0.5,'Ydata',[1 1]*(cent(3)-bb(1,3)+1)); set(st.vols{i}.ax{2}.ly,'HitTest','off',... 'Ydata',[0 CD(2)]+0.5,'Xdata',[1 1]*(cent(1)-bb(1,1)+1)); set(st.vols{i}.ax{3}.d,'HitTest','off','Cdata',imgs); if st.mode ==0, set(st.vols{i}.ax{3}.lx,'HitTest','off',... 'Xdata',[0 SD(1)]+0.5,'Ydata',[1 1]*(cent(2)-bb(1,2)+1)); set(st.vols{i}.ax{3}.ly,'HitTest','off',... 'Ydata',[0 SD(2)]+0.5,'Xdata',[1 1]*(cent(3)-bb(1,3)+1)); else set(st.vols{i}.ax{3}.lx,'HitTest','off',... 'Xdata',[0 SD(1)]+0.5,'Ydata',[1 1]*(cent(3)-bb(1,3)+1)); set(st.vols{i}.ax{3}.ly,'HitTest','off',... 'Ydata',[0 SD(2)]+0.5,'Xdata',[1 1]*(bb(2,2)+1-cent(2))); end; if ~isempty(st.plugins) % process any addons for k = 1:numel(st.plugins), if isfield(st.vols{i},st.plugins{k}), feval(['spm_ov_', st.plugins{k}], ... 'redraw', i, TM0, TD, CM0, CD, SM0, SD); end; end; end; end; end; drawnow; return; %_______________________________________________________________________ %_______________________________________________________________________ function redraw_colourbar(vh,bh,interval,cdata) global st if isfield(st.vols{vh}.blobs{bh},'cbar') if st.mode == 0, axpos = get(st.vols{vh}.ax{2}.ax,'Position'); else axpos = get(st.vols{vh}.ax{1}.ax,'Position'); end; % only scale cdata if we have out-of-range truecolour values if ndims(cdata)==3 && max(cdata(:))>1 cdata=cdata./max(cdata(:)); end; image([0 1],interval,cdata,'Parent',st.vols{vh}.blobs{bh}.cbar); set(st.vols{vh}.blobs{bh}.cbar, ... 'Position',[(axpos(1)+axpos(3)+0.05+(bh-1)*.1)... (axpos(2)+0.005) 0.05 (axpos(4)-0.01)],... 'YDir','normal','XTickLabel',[],'XTick',[]); if isfield(st.vols{vh}.blobs{bh},'name') ylabel(st.vols{vh}.blobs{bh}.name,'parent',st.vols{vh}.blobs{bh}.cbar); end; end; %_______________________________________________________________________ %_______________________________________________________________________ function centre = findcent global st obj = get(st.fig,'CurrentObject'); centre = []; cent = []; cp = []; for i=valid_handles(1:24), for j=1:3, if ~isempty(obj), if (st.vols{i}.ax{j}.ax == obj), cp = get(obj,'CurrentPoint'); end; end; if ~isempty(cp), cp = cp(1,1:2); is = inv(st.Space); cent = is(1:3,1:3)*st.centre(:) + is(1:3,4); switch j, case 1, cent([1 2])=[cp(1)+st.bb(1,1)-1 cp(2)+st.bb(1,2)-1]; case 2, cent([1 3])=[cp(1)+st.bb(1,1)-1 cp(2)+st.bb(1,3)-1]; case 3, if st.mode ==0, cent([3 2])=[cp(1)+st.bb(1,3)-1 cp(2)+st.bb(1,2)-1]; else cent([2 3])=[st.bb(2,2)+1-cp(1) cp(2)+st.bb(1,3)-1]; end; end; break; end; end; if ~isempty(cent), break; end; end; if ~isempty(cent), centre = st.Space(1:3,1:3)*cent(:) + st.Space(1:3,4); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function handles = valid_handles(handles) global st; if isempty(st) || ~isfield(st,'vols') handles = []; else handles = handles(:)'; handles = handles(handles<=24 & handles>=1 & ~rem(handles,1)); for h=handles, if isempty(st.vols{h}), handles(handles==h)=[]; end; end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function reset_st global st fig = spm_figure('FindWin','Graphics'); bb = []; %[ [-78 78]' [-112 76]' [-50 85]' ]; st = struct('n', 0, 'vols',[], 'bb',bb,'Space',eye(4),'centre',[0 0 0],'callback',';','xhairs',1,'hld',1,'fig',fig,'mode',1,'plugins',{{}},'snap',[]); st.vols = cell(24,1); xTB = spm('TBs'); if ~isempty(xTB) pluginbase = {spm('Dir') xTB.dir}; else pluginbase = {spm('Dir')}; end for k = 1:numel(pluginbase) pluginpath = fullfile(pluginbase{k},'spm_orthviews'); if isdir(pluginpath) pluginfiles = dir(fullfile(pluginpath,'spm_ov_*.m')); if ~isempty(pluginfiles) if ~isdeployed, addpath(pluginpath); end % fprintf('spm_orthviews: Using Plugins in %s\n', pluginpath); for l = 1:numel(pluginfiles) [p, pluginname, e, v] = spm_fileparts(pluginfiles(l).name); st.plugins{end+1} = strrep(pluginname, 'spm_ov_',''); % fprintf('%s\n',st.plugins{k}); end; end; end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function img = scaletocmap(inpimg,mn,mx,cmap,miscol) if nargin < 5, miscol=1;end cml = size(cmap,1); scf = (cml-1)/(mx-mn); img = round((inpimg-mn)*scf)+1; img(img<1) = 1; img(img>cml) = cml; img(~isfinite(img)) = miscol; return; %_______________________________________________________________________ %_______________________________________________________________________ function cmap = getcmap(acmapname) % get colormap of name acmapname if ~isempty(acmapname), cmap = evalin('base',acmapname,'[]'); if isempty(cmap), % not a matrix, is .mat file? [p, f, e] = fileparts(acmapname); acmat = fullfile(p, [f '.mat']); if exist(acmat, 'file'), s = struct2cell(load(acmat)); cmap = s{1}; end; end; end; if size(cmap, 2)~=3, warning('Colormap was not an N by 3 matrix') cmap = []; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function item_parent = addcontext(volhandle) global st; %create context menu fg = spm_figure('Findwin','Graphics');set(0,'CurrentFigure',fg); %contextmenu item_parent = uicontextmenu; %contextsubmenu 0 item00 = uimenu(item_parent, 'Label','unknown image', 'Separator','on'); spm_orthviews('context_menu','image_info',item00,volhandle); item0a = uimenu(item_parent, 'UserData','pos_mm', 'Callback','spm_orthviews(''context_menu'',''repos_mm'');','Separator','on'); item0b = uimenu(item_parent, 'UserData','pos_vx', 'Callback','spm_orthviews(''context_menu'',''repos_vx'');'); item0c = uimenu(item_parent, 'UserData','v_value'); %contextsubmenu 1 item1 = uimenu(item_parent,'Label','Zoom'); item1_1 = uimenu(item1, 'Label','Full Volume', 'Callback','spm_orthviews(''context_menu'',''zoom'',6);', 'Checked','on'); item1_2 = uimenu(item1, 'Label','160x160x160mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',5);'); item1_3 = uimenu(item1, 'Label','80x80x80mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',4);'); item1_4 = uimenu(item1, 'Label','40x40x40mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',3);'); item1_5 = uimenu(item1, 'Label','20x20x20mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',2);'); item1_6 = uimenu(item1, 'Label','10x10x10mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',1);'); %contextsubmenu 2 checked={'off','off'}; checked{st.xhairs+1} = 'on'; item2 = uimenu(item_parent,'Label','Crosshairs'); item2_1 = uimenu(item2, 'Label','on', 'Callback','spm_orthviews(''context_menu'',''Xhair'',''on'');','Checked',checked{2}); item2_2 = uimenu(item2, 'Label','off', 'Callback','spm_orthviews(''context_menu'',''Xhair'',''off'');','Checked',checked{1}); %contextsubmenu 3 if st.Space == eye(4) checked = {'off', 'on'}; else checked = {'on', 'off'}; end; item3 = uimenu(item_parent,'Label','Orientation'); item3_1 = uimenu(item3, 'Label','World space', 'Callback','spm_orthviews(''context_menu'',''orientation'',3);','Checked',checked{2}); item3_2 = uimenu(item3, 'Label','Voxel space (1st image)', 'Callback','spm_orthviews(''context_menu'',''orientation'',2);','Checked',checked{1}); item3_3 = uimenu(item3, 'Label','Voxel space (this image)', 'Callback','spm_orthviews(''context_menu'',''orientation'',1);','Checked','off'); %contextsubmenu 3 if isempty(st.snap) checked = {'off', 'on'}; else checked = {'on', 'off'}; end; item3 = uimenu(item_parent,'Label','Snap to Grid'); item3_1 = uimenu(item3, 'Label','Don''t snap', 'Callback','spm_orthviews(''context_menu'',''snap'',3);','Checked',checked{2}); item3_2 = uimenu(item3, 'Label','Snap to 1st image', 'Callback','spm_orthviews(''context_menu'',''snap'',2);','Checked',checked{1}); item3_3 = uimenu(item3, 'Label','Snap to this image', 'Callback','spm_orthviews(''context_menu'',''snap'',1);','Checked','off'); %contextsubmenu 4 if st.hld == 0, checked = {'off', 'off', 'on'}; elseif st.hld > 0, checked = {'off', 'on', 'off'}; else checked = {'on', 'off', 'off'}; end; item4 = uimenu(item_parent,'Label','Interpolation'); item4_1 = uimenu(item4, 'Label','NN', 'Callback','spm_orthviews(''context_menu'',''interpolation'',3);', 'Checked',checked{3}); item4_2 = uimenu(item4, 'Label','Bilin', 'Callback','spm_orthviews(''context_menu'',''interpolation'',2);','Checked',checked{2}); item4_3 = uimenu(item4, 'Label','Sinc', 'Callback','spm_orthviews(''context_menu'',''interpolation'',1);','Checked',checked{1}); %contextsubmenu 5 % item5 = uimenu(item_parent,'Label','Position', 'Callback','spm_orthviews(''context_menu'',''position'');'); %contextsubmenu 6 item6 = uimenu(item_parent,'Label','Image','Separator','on'); item6_1 = uimenu(item6, 'Label','Window'); item6_1_1 = uimenu(item6_1, 'Label','local'); item6_1_1_1 = uimenu(item6_1_1, 'Label','auto', 'Callback','spm_orthviews(''context_menu'',''window'',2);'); item6_1_1_2 = uimenu(item6_1_1, 'Label','manual', 'Callback','spm_orthviews(''context_menu'',''window'',1);'); item6_1_2 = uimenu(item6_1, 'Label','global'); item6_1_2_1 = uimenu(item6_1_2, 'Label','auto', 'Callback','spm_orthviews(''context_menu'',''window_gl'',2);'); item6_1_2_2 = uimenu(item6_1_2, 'Label','manual', 'Callback','spm_orthviews(''context_menu'',''window_gl'',1);'); if license('test','image_toolbox') == 1 offon = {'off', 'on'}; checked = offon(strcmp(st.vols{volhandle}.mapping, ... {'linear', 'histeq', 'loghisteq', 'quadhisteq'})+1); item6_2 = uimenu(item6, 'Label','Intensity mapping'); item6_2_1 = uimenu(item6_2, 'Label','local'); item6_2_1_1 = uimenu(item6_2_1, 'Label','Linear', 'Checked',checked{1}, ... 'Callback','spm_orthviews(''context_menu'',''mapping'',''linear'');'); item6_2_1_2 = uimenu(item6_2_1, 'Label','Equalised histogram', 'Checked',checked{2}, ... 'Callback','spm_orthviews(''context_menu'',''mapping'',''histeq'');'); item6_2_1_3 = uimenu(item6_2_1, 'Label','Equalised log-histogram', 'Checked',checked{3}, ... 'Callback','spm_orthviews(''context_menu'',''mapping'',''loghisteq'');'); item6_2_1_4 = uimenu(item6_2_1, 'Label','Equalised squared-histogram', 'Checked',checked{4}, ... 'Callback','spm_orthviews(''context_menu'',''mapping'',''quadhisteq'');'); item6_2_2 = uimenu(item6_2, 'Label','global'); item6_2_2_1 = uimenu(item6_2_2, 'Label','Linear', 'Checked',checked{1}, ... 'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''linear'');'); item6_2_2_2 = uimenu(item6_2_2, 'Label','Equalised histogram', 'Checked',checked{2}, ... 'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''histeq'');'); item6_2_2_3 = uimenu(item6_2_2, 'Label','Equalised log-histogram', 'Checked',checked{3}, ... 'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''loghisteq'');'); item6_2_2_4 = uimenu(item6_2_2, 'Label','Equalised squared-histogram', 'Checked',checked{4}, ... 'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''quadhisteq'');'); end; %contextsubmenu 7 item7 = uimenu(item_parent,'Label','Blobs'); item7_1 = uimenu(item7, 'Label','Add blobs'); item7_1_1 = uimenu(item7_1, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_blobs'',2);'); item7_1_2 = uimenu(item7_1, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_blobs'',1);'); item7_2 = uimenu(item7, 'Label','Add image'); item7_2_1 = uimenu(item7_2, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_image'',2);'); item7_2_2 = uimenu(item7_2, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_image'',1);'); item7_3 = uimenu(item7, 'Label','Add colored blobs','Separator','on'); item7_3_1 = uimenu(item7_3, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_c_blobs'',2);'); item7_3_2 = uimenu(item7_3, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_c_blobs'',1);'); item7_4 = uimenu(item7, 'Label','Add colored image'); item7_4_1 = uimenu(item7_4, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_c_image'',2);'); item7_4_2 = uimenu(item7_4, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_c_image'',1);'); item7_5 = uimenu(item7, 'Label','Remove blobs', 'Visible','off','Separator','on'); item7_6 = uimenu(item7, 'Label','Remove colored blobs','Visible','off'); item7_6_1 = uimenu(item7_6, 'Label','local', 'Visible','on'); item7_6_2 = uimenu(item7_6, 'Label','global','Visible','on'); for i=1:3, set(st.vols{volhandle}.ax{i}.ax,'UIcontextmenu',item_parent); st.vols{volhandle}.ax{i}.cm = item_parent; end; if ~isempty(st.plugins) % process any plugins for k = 1:numel(st.plugins), feval(['spm_ov_', st.plugins{k}], ... 'context_menu', volhandle, item_parent); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function c_menu(varargin) global st switch lower(varargin{1}), case 'image_info', if nargin <3, current_handle = get_current_handle; else current_handle = varargin{3}; end; if isfield(st.vols{current_handle},'fname'), [p,n,e,v] = spm_fileparts(st.vols{current_handle}.fname); if isfield(st.vols{current_handle},'n') v = sprintf(',%d',st.vols{current_handle}.n); end; set(varargin{2}, 'Label',[n e v]); end; delete(get(varargin{2},'children')); if exist('p','var') item1 = uimenu(varargin{2}, 'Label', p); end; if isfield(st.vols{current_handle},'descrip'), item2 = uimenu(varargin{2}, 'Label',... st.vols{current_handle}.descrip); end; dt = st.vols{current_handle}.dt(1); item3 = uimenu(varargin{2}, 'Label', sprintf('Data type: %s', spm_type(dt))); str = 'Intensity: varied'; if size(st.vols{current_handle}.pinfo,2) == 1, if st.vols{current_handle}.pinfo(2), str = sprintf('Intensity: Y = %g X + %g',... st.vols{current_handle}.pinfo(1:2)'); else str = sprintf('Intensity: Y = %g X', st.vols{current_handle}.pinfo(1)'); end; end; item4 = uimenu(varargin{2}, 'Label',str); item5 = uimenu(varargin{2}, 'Label', 'Image dims', 'Separator','on'); item51 = uimenu(varargin{2}, 'Label',... sprintf('%dx%dx%d', st.vols{current_handle}.dim(1:3))); prms = spm_imatrix(st.vols{current_handle}.mat); item6 = uimenu(varargin{2}, 'Label','Voxel size', 'Separator','on'); item61 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', prms(7:9))); item7 = uimenu(varargin{2}, 'Label','Origin', 'Separator','on'); item71 = uimenu(varargin{2}, 'Label',... sprintf('%.2f %.2f %.2f', prms(1:3))); R = spm_matrix([0 0 0 prms(4:6)]); item8 = uimenu(varargin{2}, 'Label','Rotations', 'Separator','on'); item81 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(1,1:3))); item82 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(2,1:3))); item83 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(3,1:3))); item9 = uimenu(varargin{2},... 'Label','Specify other image...',... 'Callback','spm_orthviews(''context_menu'',''swap_img'');',... 'Separator','on'); case 'repos_mm', oldpos_mm = spm_orthviews('pos'); newpos_mm = spm_input('New Position (mm)','+1','r',sprintf('%.2f %.2f %.2f',oldpos_mm),3); spm_orthviews('reposition',newpos_mm); case 'repos_vx' current_handle = get_current_handle; oldpos_vx = spm_orthviews('pos', current_handle); newpos_vx = spm_input('New Position (voxels)','+1','r',sprintf('%.2f %.2f %.2f',oldpos_vx),3); newpos_mm = st.vols{current_handle}.mat*[newpos_vx;1]; spm_orthviews('reposition',newpos_mm(1:3)); case 'zoom' zoom_all(varargin{2}); bbox; redraw_all; case 'xhair', spm_orthviews('Xhairs',varargin{2}); cm_handles = get_cm_handles; for i = 1:numel(cm_handles), z_handle = get(findobj(cm_handles(i),'label','Crosshairs'),'Children'); set(z_handle,'Checked','off'); %reset check if strcmp(varargin{2},'off'), op = 1; else op = 2; end set(z_handle(op),'Checked','on'); end; case 'orientation', cm_handles = get_cm_handles; for i = 1:numel(cm_handles), z_handle = get(findobj(cm_handles(i),'label','Orientation'),'Children'); set(z_handle,'Checked','off'); end; if varargin{2} == 3, spm_orthviews('Space'); for i = 1:numel(cm_handles), z_handle = findobj(cm_handles(i),'label','World space'); set(z_handle,'Checked','on'); end; elseif varargin{2} == 2, spm_orthviews('Space',1); for i = 1:numel(cm_handles), z_handle = findobj(cm_handles(i),'label',... 'Voxel space (1st image)'); set(z_handle,'Checked','on'); end; else spm_orthviews('Space',get_current_handle); z_handle = findobj(st.vols{get_current_handle}.ax{1}.cm, ... 'label','Voxel space (this image)'); set(z_handle,'Checked','on'); return; end; case 'snap', cm_handles = get_cm_handles; for i = 1:numel(cm_handles), z_handle = get(findobj(cm_handles(i),'label','Snap to Grid'),'Children'); set(z_handle,'Checked','off'); end; if varargin{2} == 3, st.snap = []; elseif varargin{2} == 2, st.snap = 1; else st.snap = get_current_handle; z_handle = get(findobj(st.vols{get_current_handle}.ax{1}.cm,'label','Snap to Grid'),'Children'); set(z_handle(1),'Checked','on'); return; end; for i = 1:numel(cm_handles), z_handle = get(findobj(cm_handles(i),'label','Snap to Grid'),'Children'); set(z_handle(varargin{2}),'Checked','on'); end; case 'interpolation', tmp = [-4 1 0]; st.hld = tmp(varargin{2}); cm_handles = get_cm_handles; for i = 1:numel(cm_handles), z_handle = get(findobj(cm_handles(i),'label','Interpolation'),'Children'); set(z_handle,'Checked','off'); set(z_handle(varargin{2}),'Checked','on'); end; redraw_all; case 'window', current_handle = get_current_handle; if varargin{2} == 2, spm_orthviews('window',current_handle); else if isnumeric(st.vols{current_handle}.window) defstr = sprintf('%.2f %.2f', st.vols{current_handle}.window); else defstr = ''; end; [w yp] = spm_input('Range','+1','e',defstr,[1 inf]); while numel(w) < 1 || numel(w) > 2 uiwait(warndlg('Window must be one or two numbers','Wrong input size','modal')); [w yp] = spm_input('Range',yp,'e',defstr,[1 inf]); end if numel(w) == 1 w(2) = w(1)+eps; end spm_orthviews('window',current_handle,w); end; case 'window_gl', if varargin{2} == 2, for i = 1:numel(get_cm_handles), st.vols{i}.window = 'auto'; end; else current_handle = get_current_handle; if isnumeric(st.vols{current_handle}.window) defstr = sprintf('%d %d', st.vols{current_handle}.window); else defstr = ''; end; [w yp] = spm_input('Range','+1','e',defstr,[1 inf]); while numel(w) < 1 || numel(w) > 2 uiwait(warndlg('Window must be one or two numbers','Wrong input size','modal')); [w yp] = spm_input('Range',yp,'e',defstr,[1 inf]); end if numel(w) == 1 w(2) = w(1)+eps; end for i = 1:numel(get_cm_handles), st.vols{i}.window = w; end; end; redraw_all; case 'mapping', checked = strcmp(varargin{2}, ... {'linear', 'histeq', 'loghisteq', ... 'quadhisteq'}); checked = checked(end:-1:1); % Handles are stored in inverse order current_handle = get_current_handle; cm_handles = get_cm_handles; st.vols{current_handle}.mapping = varargin{2}; z_handle = get(findobj(cm_handles(current_handle), ... 'label','Intensity mapping'),'Children'); for k = 1:numel(z_handle) c_handle = get(z_handle(k), 'Children'); set(c_handle, 'checked', 'off'); set(c_handle(checked), 'checked', 'on'); end; redraw_all; case 'mapping_gl', checked = strcmp(varargin{2}, ... {'linear', 'histeq', 'loghisteq', 'quadhisteq'}); checked = checked(end:-1:1); % Handles are stored in inverse order cm_handles = get_cm_handles; for k = valid_handles(1:24), st.vols{k}.mapping = varargin{2}; z_handle = get(findobj(cm_handles(k), ... 'label','Intensity mapping'),'Children'); for l = 1:numel(z_handle) c_handle = get(z_handle(l), 'Children'); set(c_handle, 'checked', 'off'); set(c_handle(checked), 'checked', 'on'); end; end; redraw_all; case 'swap_img', current_handle = get_current_handle; newimg = spm_select(1,'image','select new image'); if ~isempty(newimg) new_info = spm_vol(newimg); fn = fieldnames(new_info); for k=1:numel(fn) st.vols{current_handle}.(fn{k}) = new_info.(fn{k}); end; spm_orthviews('context_menu','image_info',get(gcbo, 'parent')); redraw_all; end case 'add_blobs', % Add blobs to the image - in split colortable cm_handles = valid_handles(1:24); if varargin{2} == 2, cm_handles = get_current_handle; end; spm_figure('Clear','Interactive'); [SPM,VOL] = spm_getSPM; if ~isempty(SPM) for i = 1:numel(cm_handles), addblobs(cm_handles(i),VOL.XYZ,VOL.Z,VOL.M); c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs'); set(c_handle,'Visible','on'); delete(get(c_handle,'Children')); item7_3_1 = uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''remove_blobs'',2);'); if varargin{2} == 1, item7_3_2 = uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''remove_blobs'',1);'); end; end; redraw_all; end case 'remove_blobs', cm_handles = valid_handles(1:24); if varargin{2} == 2, cm_handles = get_current_handle; end; for i = 1:numel(cm_handles), rmblobs(cm_handles(i)); c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs'); delete(get(c_handle,'Children')); set(c_handle,'Visible','off'); end; redraw_all; case 'add_image', % Add blobs to the image - in split colortable cm_handles = valid_handles(1:24); if varargin{2} == 2, cm_handles = get_current_handle; end; spm_figure('Clear','Interactive'); fname = spm_select(1,'image','select image'); if ~isempty(fname) for i = 1:numel(cm_handles), addimage(cm_handles(i),fname); c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs'); set(c_handle,'Visible','on'); delete(get(c_handle,'Children')); item7_3_1 = uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''remove_blobs'',2);'); if varargin{2} == 1, item7_3_2 = uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''remove_blobs'',1);'); end; end; redraw_all; end case 'add_c_blobs', % Add blobs to the image - in full colour cm_handles = valid_handles(1:24); if varargin{2} == 2, cm_handles = get_current_handle; end; spm_figure('Clear','Interactive'); [SPM,VOL] = spm_getSPM; if ~isempty(SPM) c = spm_input('Colour','+1','m',... 'Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1); colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1]; c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'}; hlabel = sprintf('%s (%s)',VOL.title,c_names{c}); for i = 1:numel(cm_handles), addcolouredblobs(cm_handles(i),VOL.XYZ,VOL.Z,VOL.M,colours(c,:),VOL.title); addcolourbar(cm_handles(i),numel(st.vols{cm_handles(i)}.blobs)); c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove colored blobs'); ch_c_handle = get(c_handle,'Children'); set(c_handle,'Visible','on'); %set(ch_c_handle,'Visible',on'); item7_4_1 = uimenu(ch_c_handle(2),'Label',hlabel,'ForegroundColor',colours(c,:),... 'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',2,c);',... 'UserData',c); if varargin{2} == 1, item7_4_2 = uimenu(ch_c_handle(1),'Label',hlabel,'ForegroundColor',colours(c,:),... 'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',1,c);',... 'UserData',c); end; end; redraw_all; end case 'remove_c_blobs', cm_handles = valid_handles(1:24); if varargin{2} == 2, cm_handles = get_current_handle; end; colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1]; for i = 1:numel(cm_handles), if isfield(st.vols{cm_handles(i)},'blobs'), for j = 1:numel(st.vols{cm_handles(i)}.blobs), if all(st.vols{cm_handles(i)}.blobs{j}.colour == colours(varargin{3},:)); if isfield(st.vols{cm_handles(i)}.blobs{j},'cbar') delete(st.vols{cm_handles(i)}.blobs{j}.cbar); end st.vols{cm_handles(i)}.blobs(j) = []; break; end; end; rm_c_menu = findobj(st.vols{cm_handles(i)}.ax{1}.cm,'Label','Remove colored blobs'); delete(gcbo); if isempty(st.vols{cm_handles(i)}.blobs), st.vols{cm_handles(i)} = rmfield(st.vols{cm_handles(i)},'blobs'); set(rm_c_menu, 'Visible', 'off'); end; end; end; redraw_all; case 'add_c_image', % Add truecolored image cm_handles = valid_handles(1:24); if varargin{2} == 2, cm_handles = get_current_handle;end; spm_figure('Clear','Interactive'); fname = spm_select(1,'image','select image'); if ~isempty(fname) c = spm_input('Colour','+1','m','Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1); colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1]; c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'}; hlabel = sprintf('%s (%s)',fname,c_names{c}); for i = 1:numel(cm_handles), addcolouredimage(cm_handles(i),fname,colours(c,:)); addcolourbar(cm_handles(i),numel(st.vols{cm_handles(i)}.blobs)); c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove colored blobs'); ch_c_handle = get(c_handle,'Children'); set(c_handle,'Visible','on'); %set(ch_c_handle,'Visible',on'); item7_4_1 = uimenu(ch_c_handle(2),'Label',hlabel,'ForegroundColor',colours(c,:),... 'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',2,c);','UserData',c); if varargin{2} == 1 item7_4_2 = uimenu(ch_c_handle(1),'Label',hlabel,'ForegroundColor',colours(c,:),... 'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',1,c);',... 'UserData',c); end end redraw_all; end end; %_______________________________________________________________________ %_______________________________________________________________________ function current_handle = get_current_handle cm_handle = get(gca,'UIContextMenu'); cm_handles = get_cm_handles; current_handle = find(cm_handles==cm_handle); return; %_______________________________________________________________________ %_______________________________________________________________________ function cm_pos global st for i = 1:numel(valid_handles(1:24)), if isfield(st.vols{i}.ax{1},'cm') set(findobj(st.vols{i}.ax{1}.cm,'UserData','pos_mm'),... 'Label',sprintf('mm: %.1f %.1f %.1f',spm_orthviews('pos'))); pos = spm_orthviews('pos',i); set(findobj(st.vols{i}.ax{1}.cm,'UserData','pos_vx'),... 'Label',sprintf('vx: %.1f %.1f %.1f',pos)); set(findobj(st.vols{i}.ax{1}.cm,'UserData','v_value'),... 'Label',sprintf('Y = %g',spm_sample_vol(st.vols{i},pos(1),pos(2),pos(3),st.hld))); end end; return; %_______________________________________________________________________ %_______________________________________________________________________ function cm_handles = get_cm_handles global st cm_handles = []; for i=valid_handles(1:24), cm_handles = [cm_handles st.vols{i}.ax{1}.cm]; end return; %_______________________________________________________________________ %_______________________________________________________________________ function zoom_all(op) global st cm_handles = get_cm_handles; res = [.125 .125 .25 .5 1 1]; if op==6, st.bb = maxbb; else vx = sqrt(sum(st.Space(1:3,1:3).^2)); vx = vx.^(-1); pos = spm_orthviews('pos'); pos = st.Space\[pos ; 1]; pos = pos(1:3)'; if op == 5, st.bb = [pos-80*vx ; pos+80*vx] ; elseif op == 4, st.bb = [pos-40*vx ; pos+40*vx] ; elseif op == 3, st.bb = [pos-20*vx ; pos+20*vx] ; elseif op == 2, st.bb = [pos-10*vx ; pos+10*vx] ; elseif op == 1; st.bb = [pos- 5*vx ; pos+ 5*vx] ; else disp('no Zoom possible'); end; end resolution(res(op)); redraw_all; for i = 1:numel(cm_handles) z_handle = get(findobj(cm_handles(i),'label','Zoom'),'Children'); set(z_handle,'Checked','off'); set(z_handle(op),'Checked','on'); end if isfield(st.vols{1},'sdip') spm_eeg_inv_vbecd_disp('RedrawDip'); end return;
github
lcnhappe/happe-master
spm_maff.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_maff.m
11,287
utf_8
67d7a7a2de40e5f6a1c0c0e5e9f630f3
function [M,h] = spm_maff(varargin) % Affine registration to MNI space using mutual information % FORMAT M = spm_maff(P,samp,x,b0,MF,M,regtyp,ff) % P - filename or structure handle of image % x - cell array of {x1,x2,x3}, where x1 and x2 are % co-ordinates (from ndgrid), and x3 is a list of % slice numbers to use % b0 - a cell array of belonging probability images % (see spm_load_priors.m). % MF - voxel-to-world transform of belonging probability % images % M - starting estimates % regtype - regularisation type % 'mni' - registration of European brains with MNI space % 'eastern' - registration of East Asian brains with MNI space % 'rigid' - rigid(ish)-body registration % 'subj' - inter-subject registration % 'none' - no regularisation % ff - a fudge factor (derived from the one above) %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ [buf,MG] = loadbuf(varargin{1:2}); M = affreg(buf, MG, varargin{2:end}); return; %_______________________________________________________________________ %_______________________________________________________________________ function [buf,MG] = loadbuf(V,x) if ischar(V), V = spm_vol(V); end; x1 = x{1}; x2 = x{2}; x3 = x{3}; % Load the image V = spm_vol(V); d = V(1).dim(1:3); o = ones(size(x1)); d = [size(x1) length(x3)]; g = zeros(d); spm_progress_bar('Init',V.dim(3),'Loading volume','Planes loaded'); for i=1:d(3) g(:,:,i) = spm_sample_vol(V,x1,x2,o*x3(i),0); spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); % Convert the image to unsigned bytes [mn,mx] = spm_minmax(g); sw = warning('off','all'); for z=1:length(x3), gz = g(:,:,z); buf(z).msk = gz>mn & isfinite(gz); buf(z).nm = sum(buf(z).msk(:)); gz = double(gz(buf(z).msk)); buf(z).g = uint8(round(gz*(255/mx))); end; warning(sw); MG = V.mat; return; %_______________________________________________________________________ %_______________________________________________________________________ function [M,h0] = affreg(buf,MG,x,b0,MF,M,regtyp,ff) % Do the work x1 = x{1}; x2 = x{2}; x3 = x{3}; [mu,isig] = priors(regtyp); isig = isig*ff; Alpha0 = isig; Beta0 = -isig*mu; sol = M2P(M); sol1 = sol; ll = -Inf; nsmp = sum(cat(1,buf.nm)); pr = struct('b',[],'db1',[],'db2',[],'db3',[]); spm_chi2_plot('Init','Registering','Log-likelihood','Iteration'); for iter=1:200 penalty = (sol1-mu)'*isig*(sol1-mu); T = MF\P2M(sol1)*MG; R = derivs(MF,sol1,MG); y1a = T(1,1)*x1 + T(1,2)*x2 + T(1,4); y2a = T(2,1)*x1 + T(2,2)*x2 + T(2,4); y3a = T(3,1)*x1 + T(3,2)*x2 + T(3,4); h0 = zeros(256,length(b0)-1)+eps; for i=1:length(x3), if ~buf(i).nm, continue; end; y1 = y1a(buf(i).msk) + T(1,3)*x3(i); y2 = y2a(buf(i).msk) + T(2,3)*x3(i); y3 = y3a(buf(i).msk) + T(3,3)*x3(i); for k=1:size(h0,2), pr(k).b = spm_sample_priors(b0{k},y1,y2,y3,k==length(b0)); h0(:,k) = h0(:,k) + spm_hist(buf(i).g,pr(k).b); end; end; h1 = (h0+eps); ssh = sum(h1(:)); krn = spm_smoothkern(2,(-256:256)',0); h1 = conv2(h1,krn,'same'); h1 = h1/ssh; h2 = log2(h1./(sum(h1,2)*sum(h1,1))); ll1 = sum(sum(h0.*h2))/ssh - penalty/ssh; spm_chi2_plot('Set',ll1); if ll1-ll<1e-5, break; end; ll = ll1; sol = sol1; Alpha = zeros(12); Beta = zeros(12,1); for i=1:length(x3), nz = buf(i).nm; if ~nz, continue; end; msk = buf(i).msk; gi = double(buf(i).g)+1; y1 = y1a(msk) + T(1,3)*x3(i); y2 = y2a(msk) + T(2,3)*x3(i); y3 = y3a(msk) + T(3,3)*x3(i); dmi1 = zeros(nz,1); dmi2 = zeros(nz,1); dmi3 = zeros(nz,1); for k=1:size(h0,2), [pr(k).b, pr(k).db1, pr(k).db2, pr(k).db3] = spm_sample_priors(b0{k},y1,y2,y3,k==length(b0)); tmp = -h2(gi,k); dmi1 = dmi1 + tmp.*pr(k).db1; dmi2 = dmi2 + tmp.*pr(k).db2; dmi3 = dmi3 + tmp.*pr(k).db3; end; x1m = x1(msk); x2m = x2(msk); x3m = x3(i); A = [dmi1.*x1m dmi2.*x1m dmi3.*x1m... dmi1.*x2m dmi2.*x2m dmi3.*x2m... dmi1 *x3m dmi2 *x3m dmi3 *x3m... dmi1 dmi2 dmi3]; Alpha = Alpha + A'*A; Beta = Beta + sum(A,1)'; end; drawnow; Alpha = R'*Alpha*R; Beta = R'*Beta; % Gauss-Newton update sol1 = (Alpha+Alpha0)\(Alpha*sol - Beta - Beta0); end; spm_chi2_plot('Clear'); M = P2M(sol); return; %_______________________________________________________________________ %_______________________________________________________________________ function P = M2P(M) % Polar decomposition parameterisation of affine transform, % based on matrix logs J = M(1:3,1:3); V = sqrtm(J*J'); R = V\J; lV = logm(V); lR = -logm(R); if sum(sum(imag(lR).^2))>1e-6, error('Rotations by pi are still a problem.'); end; P = zeros(12,1); P(1:3) = M(1:3,4); P(4:6) = lR([2 3 6]); P(7:12) = lV([1 2 3 5 6 9]); return; %_______________________________________________________________________ %_______________________________________________________________________ function M = P2M(P) % Polar decomposition parameterisation of affine transform, % based on matrix logs % Translations D = P(1:3); D = D(:); % Rotation part ind = [2 3 6]; T = zeros(3); T(ind) = -P(4:6); R = expm(T-T'); % Symmetric part (zooms and shears) ind = [1 2 3 5 6 9]; T = zeros(3); T(ind) = P(7:12); V = expm(T+T'-diag(diag(T))); M = [V*R D ; 0 0 0 1]; return; %_______________________________________________________________________ %_______________________________________________________________________ function R = derivs(MF,P,MG) % Numerically compute derivatives of Affine transformation matrix w.r.t. % changes in the parameters. R = zeros(12,12); M0 = MF\P2M(P)*MG; M0 = M0(1:3,:); for i=1:12 dp = 0.000000001; P1 = P; P1(i) = P1(i) + dp; M1 = MF\P2M(P1)*MG; M1 = M1(1:3,:); R(:,i) = (M1(:)-M0(:))/dp; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function [mu,isig] = priors(typ) % The parameters for this distribution were derived empirically from 227 % scans, that were matched to the ICBM space. %% Values can be derived by... %sn = spm_select(Inf,'.*seg_inv_sn.mat$'); %X = zeros(size(sn,1),12); %for i=1:size(sn,1), % p = load(deblank(sn(i,:))); % M = p.VF(1).mat*p.Affine/p.VG(1).mat; % J = M(1:3,1:3); % V = sqrtm(J*J'); % R = V\J; % lV = logm(V); % lR = -logm(R); % P = zeros(12,1); % P(1:3) = M(1:3,4); % P(4:6) = lR([2 3 6]); % P(7:12) = lV([1 2 3 5 6 9]); % X(i,:) = P'; %end; %mu = mean(X(:,7:12)); %XR = X(:,7:12) - repmat(mu,[size(X,1),1]); %isig = inv(XR'*XR/(size(X,1)-1)) 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 'imni', % 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)*1e8; 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 'eastern', % For East Asian brains to MNI... mu = [0.0719 -0.0040 -0.0032 0.1416 0.0601 0.2578]'; isig = 1e4 * [ 0.0757 0.0220 -0.0224 -0.0049 0.0304 -0.0327 0.0220 0.3125 -0.1555 0.0280 -0.0012 -0.0284 -0.0224 -0.1555 1.9727 0.0196 -0.0019 0.0122 -0.0049 0.0280 0.0196 0.0576 -0.0282 -0.0200 0.0304 -0.0012 -0.0019 -0.0282 0.2128 -0.0275 -0.0327 -0.0284 0.0122 -0.0200 -0.0275 0.0511]; case 'none', % No regularisation... mu = zeros(6,1); isig = zeros(6); otherwise error(['"' typ '" not recognised as type of regularisation.']); end; mu = [zeros(6,1) ; mu]; isig = [zeros(6,12) ; zeros(6,6) isig]; return; %_______________________________________________________________________ %_______________________________________________________________________ function [h0,d1] = reg_unused(M) % Try to analytically compute the first and second derivatives of a % penalty function w.r.t. changes in parameters. It works for first % derivatives, but I couldn't make it work for the second derivs - so % I gave up and tried a new strategy. T = M(1:3,1:3); [U,S,V] = svd(T); s = diag(S); h0 = sum(log(s).^2); d1s = 2*log(s)./s; %d2s = 2./s.^2-2*log(s)./s.^2; d1 = zeros(12,1); for j=1:3 for i1=1:9 T1 = zeros(3,3); T1(i1) = 1; t1 = U(:,j)'*T1*V(:,j); d1(i1) = d1(i1) + d1s(j)*t1; end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function M = P2M_unused(P) % SVD parameterisation of affine transform, based on matrix-logs. % Translations D = P(1:3); D = D(:); % Rotation U ind = [2 3 6]; T = zeros(3); T(ind) = P(4:6); U = expm(T-T'); % Diagonal zooming matrix S = expm(diag(P(7:9))); % Rotation V' T(ind) = P(10:12); V = expm(T'-T); M = [U*S*V' D ; 0 0 0 1]; return; %_______________________________________________________________________ %_______________________________________________________________________
github
lcnhappe/happe-master
spm_normalise.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_normalise.m
13,235
utf_8
5dfafbc96b6282a48b19ee3433a77167
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) %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ 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] = spm_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:numel(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); aflags.sep = max(aflags.sep,max(sqrt(sum(VG(1).mat(1:3,1:3).^2)))); aflags.sep = max(aflags.sep,max(sqrt(sum(VF(1).mat(1:3,1:3).^2)))); 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 = aflags.sep/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<15*flags.smosrc/2 & VF1(1).dim(1:3)<15), 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.12 04/11/26'; 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'); if spm_matlab_version_chk('7') >= 0, save(matname,'-V6','Affine','Tr','VF','VG','flags'); else save(matname,'Affine','Tr','VF','VG','flags'); end; 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. % %______________________________________________________________________ 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 + numel(VG)*4; T = zeros(s2,1); T(s1+(1:4:numel(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_minmax.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_minmax.m
3,705
utf_8
58192721e506d5814be863bb8a7e2acf
function [mnv,mxv] = spm_minmax(g) % Compute a suitable range of intensities for VBM preprocessing stuff % FORMAT [mnv,mxv] = spm_minmax(g) % g - array of data % mnv - minimum value % mxv - maximum value % % A MOG with two Gaussians is fitted to the intensities. The lower % Gaussian is assumed to represent background. The lower value is % where there is a 50% probability of being above background. The % upper value is one that encompases 99.5% of the values. %____________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ d = [size(g) 1]; mxv = double(max(g(:))); mnv = double(min(g(:))); h = zeros(256,1); spm_progress_bar('Init',d(3),'Initial histogram','Planes loaded'); sw = warning('off','all'); for i=1:d(3) h = h + spm_hist(uint8(round(g(:,:,i)*(255/mxv))),ones(d(1)*d(2),1)); spm_progress_bar('Set',i); end; warning(sw); spm_progress_bar('Clear'); % Occasional problems with partially masked data because the first Gaussian % just fits the big peak at zero. This will fix that one, but cause problems % for skull-stripped data. h(1) = 0; h(end) = 0; % Very crude heuristic to find a suitable lower limit. The large amount % of background really messes up mutual information registration. % Begin by modelling the intensity histogram with two Gaussians. One % for background, and the other for tissue. [mn,v,mg] = fithisto((0:255)',h,1000,[1 128],[32 128].^2,[1 1]); pr = distribution(mn,v,mg,(0:255)'); %fg = spm_figure('FindWin','Interactive'); %if ~isempty(fg) % figure(fg); % plot((0:255)',h/sum(h),'b', (0:255)',pr,'r'); % drawnow; %end; % Find the lowest intensity above the mean of the first Gaussian % where there is more than 50% probability of not being background mnd = find((pr(:,1)./(sum(pr,2)+eps) < 0.5) & (0:255)' >mn(1)); if isempty(mnd) || mnd(1)==1 || mn(1)>mn(2), mnd = 1; else mnd = mnd(1)-1; end mnv = mnd*mxv/255; % Upper limit should get 99.5% of the intensities of the % non-background region ch = cumsum(h(mnd:end))/sum(h(mnd:end)); ch = find(ch>0.995)+mnd; mxv = ch(1)/255*mxv; return; %_______________________________________________________________________ %_______________________________________________________________________ function [mn,v,mg,ll]=fithisto(x,h,maxit,n,v,mg) % Fit a mixture of Gaussians to a histogram h = h(:); x = x(:); sml = mean(diff(x))/1000; if nargin==4 mg = sum(h); mn = sum(x.*h)/mg; v = (x - mn); v = sum(v.*v.*h)/mg*ones(1,n); mn = (1:n)'/n*(max(x)-min(x))+min(x); mg = mg*ones(1,n)/n; elseif nargin==6 mn = n; n = length(mn); else error('Incorrect usage'); end; ll = Inf; for it=1:maxit prb = distribution(mn,v,mg,x); scal = sum(prb,2)+eps; oll = ll; ll = -sum(h.*log(scal)); if it>2 && oll-ll < length(x)/n*1e-9 break; end; for j=1:n p = h.*prb(:,j)./scal; mg(j) = sum(p); mn(j) = sum(x.*p)/mg(j); vr = x-mn(j); v(j) = sum(vr.*vr.*p)/mg(j)+sml; end; mg = mg + 1e-3; mg = mg/sum(mg); end; %_______________________________________________________________________ %_______________________________________________________________________ function y=distribution(m,v,g,x) % Gaussian probability density if nargin ~= 4 error('not enough input arguments'); end; x = x(:); m = m(:); v = v(:); g = g(:); if ~all(size(m) == size(v) & size(m) == size(g)) error('incompatible dimensions'); end; for i=1:size(m,1) d = x-m(i); amp = g(i)/sqrt(2*pi*v(i)); y(:,i) = amp*exp(-0.5 * (d.*d)/v(i)); end; return;
github
lcnhappe/happe-master
spm_create_vol.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_create_vol.m
4,914
utf_8
3d1ffa54c52618a0923d6642b8f5e471
function V = spm_create_vol(V,varargin) % Create a volume % FORMAT V = spm_create_vol(V) % V - image volume information (see spm_vol.m) %____________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ for i=1:numel(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), V(i).(f{j}) = v.(f{j}); end; end; function V = create_vol(V,varargin) if ~isstruct(V), error('Not a structure.'); end; if ~isfield(V,'fname'), error('No "fname" field'); end; if ~isfield(V,'dim'), error('No "dim" field'); end; if ~all(size(V.dim)==[1 3]), error(['"dim" field is the wrong size (' num2str(size(V.dim)) ').']); end; if ~isfield(V,'n'), V.n = [1 1]; else V.n = [V.n(:)' 1 1]; V.n = V.n(1:2); end; if V.n(1)>1 && V.n(2)>1, error('Can only do up to 4D data (%s).',V.fname); end; if ~isfield(V,'dt'), V.dt = [spm_type('float64') spm_platform('bigend')]; end; dt{1} = spm_type(V.dt(1)); if strcmp(dt{1},'unknown'), error(['"' dt{1} '" is an unrecognised datatype (' num2str(V.dt(1)) ').']); end; if V.dt(2), dt{2} = 'BE'; else dt{2} = 'LE'; end; if ~isfield(V,'pinfo'), V.pinfo = [Inf Inf 0]'; end; if size(V.pinfo,1)==2, V.pinfo(3,:) = 0; end; V.fname = deblank(V.fname); [pth,nam,ext] = fileparts(V.fname); switch ext, case {'.img'} minoff = 0; case {'.nii'} minoff = 352; otherwise error(['"' ext '" is not a recognised extension.']); end; bits = spm_type(V.dt(1),'bits'); minoff = minoff + ceil(prod(V.dim(1:2))*bits/8)*V.dim(3)*(V.n(1)-1+V.n(2)-1); V.pinfo(3,1) = max(V.pinfo(3,:),minoff); if ~isfield(V,'descrip'), V.descrip = ''; end; if ~isfield(V,'private'), V.private = struct; end; dim = [V.dim(1:3) V.n]; dat = file_array(V.fname,dim,[dt{1} '-' dt{2}],0,V.pinfo(1),V.pinfo(2)); N = nifti; N.dat = dat; N.mat = V.mat; N.mat0 = V.mat; N.mat_intent = 'Aligned'; N.mat0_intent = 'Aligned'; N.descrip = V.descrip; try N0 = nifti(V.fname); % Just overwrite if both are single volume files. tmp = [N0.dat.dim ones(1,5)]; if prod(tmp(4:end))==1 && prod(dim(4:end))==1 N0 = []; end; catch N0 = []; end; if ~isempty(N0), % If the dimensions differ, then there is the potential for things to go badly wrong. tmp = [N0.dat.dim ones(1,5)]; if any(tmp(1:3) ~= dim(1:3)) warning(['Incompatible x,y,z dimensions in file "' V.fname '" [' num2str(tmp(1:3)) ']~=[' num2str(dim(1:3)) '].']); end; if dim(5) > tmp(5) && tmp(4) > 1, warning(['Incompatible 4th and 5th dimensions in file "' V.fname '" (' num2str([tmp(4:5) dim(4:5)]) ').']); end; N.dat.dim = [dim(1:3) max(dim(4:5),tmp(4:5))]; if ~strcmp(dat.dtype,N0.dat.dtype), warning(['Incompatible datatype in file "' V.fname '" ' N0.dat.dtype ' ~= ' dat.dtype '.']); end; if single(N.dat.scl_slope) ~= single(N0.dat.scl_slope) && (size(N0.dat,4)>1 || V.n(1)>1), warning(['Incompatible scalefactor in "' V.fname '" ' num2str(N0.dat.scl_slope) '~=' num2str(N.dat.scl_slope) '.']); end; if single(N.dat.scl_inter) ~= single(N0.dat.scl_inter), warning(['Incompatible intercept in "' V.fname '" ' num2str(N0.dat.scl_inter) '~=' num2str(N.dat.scl_inter) '.']); end; if single(N.dat.offset) ~= single(N0.dat.offset), warning(['Incompatible intercept in "' V.fname '" ' num2str(N0.dat.offset) '~=' num2str(N.dat.offset) '.']); end; if V.n(1)==1, % Ensure volumes 2..N have the original matrix nt = size(N.dat,4); if nt>1 && sum(sum((N0.mat-V.mat).^2))>1e-8, M0 = N0.mat; if ~isfield(N0.extras,'mat'), N0.extras.mat = zeros([4 4 nt]); else if size(N0.extras.mat,4)<nt, N0.extras.mat(:,:,nt) = zeros(4); end; end; for i=2:nt, if sum(sum(N0.extras.mat(:,:,i).^2))==0, N0.extras.mat(:,:,i) = M0; end; end; N.extras.mat = N0.extras.mat; end; N0.mat = V.mat; if strcmp(N0.mat0_intent,'Aligned'), N.mat0 = V.mat; end; if ~isempty(N.extras) && isstruct(N.extras) && isfield(N.extras,'mat') &&... size(N.extras.mat,3)>=1, N.extras.mat(:,:,V.n(1)) = V.mat; end; else N.extras.mat(:,:,V.n(1)) = V.mat; end; if ~isempty(N0.extras) && isstruct(N0.extras) && isfield(N0.extras,'mat'), N0.extras.mat(:,:,V.n(1)) = N.mat; N.extras = N0.extras; end; if sum((V.mat(:)-N0.mat(:)).^2) > 1e-4, N.extras.mat(:,:,V.n(1)) = V.mat; end; end; create(N); V.private = N;
github
lcnhappe/happe-master
spm_check_installation.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_check_installation.m
19,147
utf_8
5500b12cea8521a513b4ff3226dc8f4d
function spm_check_installation(action) % Check SPM installation % FORMAT spm_check_installation('basic') % Perform a superficial check of SPM installation [default]. % % FORMAT spm_check_installation('full') % Perform an in-depth diagnostic of SPM installation. % % FORMAT spm_check_installation('build') % Build signature of SPM distribution as used by previous option. % (for developers) %__________________________________________________________________________ % Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id$ if isdeployed, return; end %-Select action %-------------------------------------------------------------------------- if ~nargin, action = 'basic'; end switch action case 'basic' check_basic; case 'full' check_full; case 'build' build_signature; otherwise error('Unknown action to perform.'); end %========================================================================== % FUNCTION check_basic %========================================================================== function check_basic %-Minimal MATLAB version required %-------------------------------------------------------------------------- try v = spm_matlab_version_chk('7.1'); catch error('Where is spm_matlab_version_chk.m?'); end if v < 0 error([... 'SPM8 requires MATLAB 7.1 onwards in order to run.\n'... 'This MATLAB version is %s\n'], version); end %-Check installation %-------------------------------------------------------------------------- spm('Ver','',1); d = spm('Dir'); %-Check the search path %-------------------------------------------------------------------------- p = textscan(path,'%s','delimiter',pathsep); p = p{1}; if ~ismember(lower(d),lower(p)) error(sprintf([... 'You do not appear to have the MATLAB search path set up\n'... 'to include your SPM8 distribution. This means that you\n'... 'can start SPM in this directory, but if your change to\n'... 'another directory then MATLAB will be unable to find the\n'... 'SPM functions. You can use the editpath command in MATLAB\n'... 'to set it up.\n'... ' addpath %s\n'... 'For more information, try typing the following:\n'... ' help path\n help editpath'],d)); end %-Ensure that the original release - as well as the updates - was installed %-------------------------------------------------------------------------- if ~exist(fullfile(d,'spm_Npdf.m'),'file') % File that should not have changed if isunix error(sprintf([... 'There appears to be some problem with the installation.\n'... 'The original spm8.zip distribution should be installed\n'... 'and the updates installed on top of this. Unix commands\n'... 'to do this are:\n'... ' unzip spm8.zip\n'... ' unzip -o spm8_updates_r????.zip -d spm8\n'... 'You may need help from your local network administrator.'])); else error(sprintf([... 'There appears to be some problem with the installation.\n'... 'The original spm8.zip distribution should be installed\n'... 'and the updates installed on top of this. If in doubt,\n'... 'consult your local network administrator.'])); end end %-Ensure that the files were unpacked correctly %-------------------------------------------------------------------------- if ispc try t = load(fullfile(d,'Split.mat')); catch error(sprintf([... 'There appears to be some problem reading the MATLAB .mat\n'... 'files from the SPM distribution. This is probably\n'... 'something to do with the way that the distribution was\n'... 'unpacked. If you used WinZip, then ensure that\n'... 'TAR file smart CR/LF conversion is disabled\n'... '(under the Miscellaneous Configuration Options).'])); end if ~exist(fullfile(d,'toolbox','DARTEL','diffeo3d.c'),'file'), error(sprintf([... 'There appears to be some problem with the installation.\n'... 'This is probably something to do with the way that the\n'... 'distribution was unbundled from the original .zip files.\n'... 'Please ensure that the files are unpacked so that the\n'... 'directory structure is retained.'])); end end %-Check the MEX files %-------------------------------------------------------------------------- try feval(@spm_bsplinc,1,ones(1,6)); catch error([... 'SPM uses a number of MEX files, which are compiled functions.\n'... 'These need to be compiled for the various platforms on which SPM\n'... 'is run. At the FIL, where SPM is developed, the number of\n'... 'computer platforms is limited. It is therefore not possible to\n'... 'release a version of SPM that will run on all computers. See\n'... ' %s%csrc%cMakefile and\n'... ' http://en.wikibooks.org/wiki/SPM#Installation\n'... 'for information about how to compile mex files for %s\n'... 'in MATLAB %s.'],... d,filesep,filesep,computer,version); end %========================================================================== % FUNCTION check_full %========================================================================== function check_full %-Say Hello %-------------------------------------------------------------------------- disp( ' ___ ____ __ __ ' ); disp( '/ __)( _ \( \/ ) ' ); disp( '\__ \ )___/ ) ( Statistical Parametric Mapping ' ); disp(['(___/(__) (_/\/\_) SPM - http://www.fil.ion.ucl.ac.uk/spm/ ']); fprintf('\n'); %-Detect SPM directory %-------------------------------------------------------------------------- SPMdir = which('spm.m','-ALL'); if isempty(SPMdir) fprintf('SPM is not in your MATLAB path.\n'); return; elseif numel(SPMdir) > 1 fprintf('SPM seems to appear in several different folders:\n'); for i=1:numel(SPMdir) fprintf(' * %s\n',SPMdir{i}); end fprintf('Remove all but one with ''editpath'' or ''spm_rmpath''.\n'); return; else fprintf('SPM is installed in: %s\n',fileparts(SPMdir{1})); end SPMdir = fileparts(SPMdir{1}); %-Detect SPM version and revision number %-------------------------------------------------------------------------- v = struct('Name','','Version','','Release','','Date',''); try fid = fopen(fullfile(SPMdir,'Contents.m'),'rt'); if fid == -1 fprintf('Cannot open ''%s'' for reading.\n',fullfile(SPMdir,'Contents.m')); return; end l1 = fgetl(fid); l2 = fgetl(fid); fclose(fid); l1 = strtrim(l1(2:end)); l2 = strtrim(l2(2:end)); t = textscan(l2,'%s','delimiter',' '); t = t{1}; v.Name = l1; v.Date = t{4}; v.Version = t{2}; v.Release = t{3}(2:end-1); catch fprintf('Cannot obtain SPM version & revision number.\n'); return; end fprintf('SPM version is %s (%s, %s)\n', ... v.Release,v.Version,strrep(v.Date,'-',' ')); %-Detect SPM toolboxes %-------------------------------------------------------------------------- officials = {'Beamforming', 'DARTEL', 'dcm_meeg', 'DEM', 'FieldMap', ... 'HDW', 'MEEGtools', 'mixture', 'Neural_Models', 'Seg', 'spectral', ... 'SRender'}; dd = dir(fullfile(SPMdir,'toolbox')); dd = {dd([dd.isdir]).name}; dd(strmatch('.',dd)) = []; dd = setdiff(dd,officials); fprintf('SPM toolboxes:'); for i=1:length(dd) fprintf(' %s',dd{i}); end if isempty(dd), fprintf(' none'); end fprintf('\n'); %-Detect MATLAB & toolboxes %-------------------------------------------------------------------------- fprintf('MATLAB is installed in: %s\n',matlabroot); fprintf('MATLAB version is %s\n',version); fprintf('MATLAB toolboxes: '); hastbx = false; if license('test','signal_toolbox') && ~isempty(ver('signal')) vtbx = ver('signal'); hastbx = true; fprintf('signal (v%s) ',vtbx.Version); end if license('test','image_toolbox') && ~isempty(ver('images')) vtbx = ver('images'); hastbx = true; fprintf('images (v%s) ',vtbx.Version); end if license('test','statistics_toolbox') && ~isempty(ver('stats')) vtbx = ver('stats'); hastbx = true; fprintf('stats (v%s)',vtbx.Version); end if ~hastbx, fprintf('none.'); end fprintf('\n'); %-Detect Platform and Operating System %-------------------------------------------------------------------------- [C, maxsize] = computer; fprintf('Platform: %s (maxsize=%d)\n', C, maxsize); if ispc platform = [system_dependent('getos'),' ',system_dependent('getwinsys')]; elseif exist('ismac') && ismac [fail, input] = unix('sw_vers'); if ~fail platform = strrep(input, 'ProductName:', ''); platform = strrep(platform, sprintf('\t'), ''); platform = strrep(platform, sprintf('\n'), ' '); platform = strrep(platform, 'ProductVersion:', ' Version: '); platform = strrep(platform, 'BuildVersion:', 'Build: '); else platform = system_dependent('getos'); end else platform = system_dependent('getos'); end fprintf('OS: %s\n', platform); %-Detect Java %-------------------------------------------------------------------------- fprintf('%s\n', version('-java')); fprintf('Java support: '); level = {'jvm', 'awt', 'swing', 'desktop'}; for i=1:numel(level) if isempty(javachk(level{i})), fprintf('%s ',level{i}); end end fprintf('\n'); %-Detect Monitor(s) %-------------------------------------------------------------------------- M = get(0,'MonitorPositions'); fprintf('Monitor(s):'); for i=1:size(M,1) fprintf(' [%d %d %d %d]',M(i,:)); end fprintf(' (%dbit)\n', get(0,'ScreenDepth')); %-Detect OpenGL rendering %-------------------------------------------------------------------------- S = opengl('data'); fprintf('OpenGL version: %s',S.Version); if S.Software, fprintf('(Software)\n'); else fprintf('(Hardware)\n'); end fprintf('OpenGL renderer: %s (%s)\n',S.Vendor,S.Renderer); %-Detect MEX setup %-------------------------------------------------------------------------- fprintf('MEX extension: %s\n',mexext); try cc = mex.getCompilerConfigurations('C','Selected'); if ~isempty(cc) cc = cc(1); % can be C or C++ fprintf('C Compiler: %s (%s).\n', cc.Name, cc.Version); fprintf('C Compiler settings: %s (''%s'')\n', ... cc.Details.CompilerExecutable, cc.Details.OptimizationFlags); else fprintf('No C compiler is selected (see mex -setup)\n'); end end try [sts, m] = fileattrib(fullfile(SPMdir,'src')); m = [m.UserRead m.UserWrite m.UserExecute ... m.GroupRead m.GroupWrite m.GroupExecute ... m.OtherRead m.OtherWrite m.OtherExecute]; r = 'rwxrwxrwx'; r(~m) = '-'; fprintf('C Source code permissions: dir %s, ', r); [sts, m] = fileattrib(fullfile(SPMdir,'src','spm_resels_vol.c')); m = [m.UserRead m.UserWrite m.UserExecute ... m.GroupRead m.GroupWrite m.GroupExecute ... m.OtherRead m.OtherWrite m.OtherExecute]; r = 'rwxrwxrwx'; r(~m) = '-'; fprintf('file %s\n',r); end %-Get file details for local SPM installation %-------------------------------------------------------------------------- fprintf('%s\n',repmat('-',1,70)); l = generate_listing(SPMdir); fprintf('%s %40s\n','Parsing local installation...','...done'); %-Get file details for most recent public version %-------------------------------------------------------------------------- fprintf('Downloading SPM information...'); url = sprintf('http://www.fil.ion.ucl.ac.uk/spm/software/%s/%s.xml',... lower(v.Release),lower(v.Release)); try p = [tempname '.xml']; urlwrite(url,p); catch fprintf('\nCannot access URL %s\n',url); return; end fprintf('%40s\n','...done'); %-Parse it into a Matlab structure %-------------------------------------------------------------------------- fprintf('Parsing SPM information...'); tree = xmlread(p); delete(p); r = struct([]); ind = 1; if tree.hasChildNodes for i=0:tree.getChildNodes.getLength-1 m = tree.getChildNodes.item(i); if strcmp(m.getNodeName,'signature') m = m.getChildNodes; for j=0:m.getLength-1 if strcmp(m.item(j).getNodeName,'file') n = m.item(j).getChildNodes; for k=0:n.getLength-1 o = n.item(k); if ~strcmp(o.getNodeName,'#text') try s = char(o.getChildNodes.item(0).getData); catch s = ''; end switch char(o.getNodeName) case 'name' r(ind).file = s; case 'id' r(ind).id = str2num(s); otherwise r(ind).(char(o.getNodeName)) = s; end end end ind = ind + 1; end end end end end fprintf('%44s\n','...done'); %-Compare local and public versions %-------------------------------------------------------------------------- fprintf('%s\n',repmat('-',1,70)); compare_versions(l,r); fprintf('%s\n',repmat('-',1,70)); %========================================================================== % FUNCTION compare_versions %========================================================================== function compare_versions(l,r) %-Uniformise file names %-------------------------------------------------------------------------- a = {r.file}; a = strrep(a,'\','/'); [r.file] = a{:}; a = {l.file}; a = strrep(a,'\','/'); [l.file] = a{:}; %-Look for missing or unknown files %-------------------------------------------------------------------------- [x,ir,il] = setxor({r.file},{l.file}); if isempty([ir il]) fprintf('No missing or unknown files\n'); else if ~isempty(ir) fprintf('File(s) missing in your installation:\n'); end for i=1:length(ir) fprintf(' * %s\n', r(ir(i)).file); end if ~isempty(ir) && ~isempty(il), fprintf('%s\n',repmat('-',1,70)); end if ~isempty(il) fprintf('File(s) not part of the current version of SPM:\n'); end for i=1:length(il) fprintf(' * %s\n', l(il(i)).file); end end fprintf('%s\n',repmat('-',1,70)); %-Look for local changes or out-of-date files %-------------------------------------------------------------------------- [tf, ir] = ismember({r.file},{l.file}); dispc = true; for i=1:numel(r) if tf(i) if ~isempty(r(i).id) && (isempty(l(ir(i)).id) || (r(i).id ~= l(ir(i)).id)) dispc = false; fprintf('File %s is not up to date (r%d vs r%d)\n', ... r(i).file, r(i).id, l(ir(i)).id); end if ~isempty(r(i).md5) && ~isempty(l(ir(i)).md5) && ~strcmp(r(i).md5,l(ir(i)).md5) dispc = false; fprintf('File %s has been edited (checksum mismatch)\n', r(i).file); end end end if dispc fprintf('No local change or out-of-date files\n'); end %========================================================================== % FUNCTION build_signature %========================================================================== function build_signature [v,r] = spm('Ver','',1); d = spm('Dir'); l = generate_listing(d); fprintf('Saving %s signature in %s\n',... v, fullfile(pwd,sprintf('%s_signature.xml',v))); fid = fopen(fullfile(pwd,sprintf('%s_signature.xml',v)),'wt'); fprintf(fid,'<?xml version="1.0"?>\n'); fprintf(fid,'<!-- Signature for %s r%s -->\n',v,r); fprintf(fid,'<signature>\n'); for i=1:numel(l) fprintf(fid,' <file>\n'); fprintf(fid,' <name>%s</name>\n',l(i).file); fprintf(fid,' <id>%d</id>\n',l(i).id); fprintf(fid,' <date>%s</date>\n',l(i).date); fprintf(fid,' <md5>%s</md5>\n',l(i).md5); fprintf(fid,' </file>\n'); end fprintf(fid,'</signature>\n'); fclose(fid); %========================================================================== % FUNCTION generate_listing %========================================================================== function l = generate_listing(d,r,l) if nargin < 2 r = ''; end if nargin < 3 l = struct([]); end %-List content of folder %-------------------------------------------------------------------------- ccd = fullfile(d,r); fprintf('%-10s: %58s','Directory',ccd(max(1,length(ccd)-57):end)); dd = dir(ccd); f = {dd(~[dd.isdir]).name}; dispw = false; for i=1:length(f) [p,name,ext] = fileparts(f{i}); info = struct('file','', 'id',[], 'date','', 'md5',''); if ismember(ext,{'.m','.man','.txt','.xml','.c','.h',''}) info = extract_info(fullfile(ccd,f{i})); end info.file = fullfile(r,f{i}); try try info.md5 = md5sum(fullfile(ccd,f{i})); catch %[s, info.md5] = system(['md5sum "' fullfile(ccd,f{i}) '"']); %info.md5 = strtok(info.md5); end end if isempty(l), l = info; else l(end+1) = info; end if isempty(r) && strcmp(ext,'.m') w = which(f{i},'-ALL'); if numel(w) > 1 && ~strcmpi(f{i},'Contents.m') if ~dispw, fprintf('\n'); end dispw = true; fprintf('File %s appears %d times in your MATLAB path:\n',f{i},numel(w)); for j=1:numel(w) if j==1 && isempty(strmatch(d,w{1})) fprintf(' %s (SHADOWING)\n',w{1}); else fprintf(' %s\n',w{j}); end end end end end if ~dispw, fprintf('%s',repmat(sprintf('\b'),1,70)); end %-Recursively extract subdirectories %-------------------------------------------------------------------------- dd = {dd([dd.isdir]).name}; dd(strmatch('.',dd)) = []; for i=1:length(dd) l = generate_listing(d,fullfile(r,dd{i}),l); end %========================================================================== % FUNCTION extract_info %========================================================================== function svnprops = extract_info(f) %Extract Subversion properties ($Id$ tag) svnprops = struct('file',f, 'id',[], 'date','', 'md5',''); fp = fopen(f,'rt'); str = fread(fp,Inf,'*uchar'); fclose(fp); str = char(str(:)'); r = regexp(str,['\$Id: (?<file>\S+) (?<id>[0-9]+) (?<date>\S+) ' ... '(\S+Z) (?<author>\S+) \$'],'names'); if isempty(r) %fprintf('\n%s has no SVN Id.\n',f); else svnprops.file = r(1).file; svnprops.id = str2num(r(1).id); svnprops.date = r(1).date; [p,name,ext] = fileparts(f); if ~strmatch(svnprops.file,[name ext],'exact') warning('SVN Id for %s does not match filename.',f); end end if numel(r) > 1 %fprintf('\n%s has several SVN Ids.\n',f); end
github
lcnhappe/happe-master
spm_prep2sn.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/spm_prep2sn.m
7,345
utf_8
41b5744c0289cc48a8070de4648e82da
function [po,pin] = spm_prep2sn(p) % Convert the output from spm_preproc into an sn.mat % FORMAT [po,pin] = spm_prep2sn(p) % p - the results of spm_preproc % po - the output in a form that can be used by % spm_write_sn. % pin - the inverse transform in a form that can be % used by spm_write_sn. %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ if ischar(p), p = load(p); end; VG = p.tpm; VF = p.image; [Y1,Y2,Y3] = create_def(p.Twarp,VF,VG(1),p.Affine); [Y1,Y2,Y3] = spm_invdef(Y1,Y2,Y3,VG(1).dim(1:3),eye(4),eye(4)); MT = procrustes(Y1,Y2,Y3,VG(1),VF.mat); d = size(p.Twarp); [Affine,Tr] = reparameterise(Y1,Y2,Y3,VG(1),VF.mat,MT,max(d(1:3)+2,[8 8 8])); flags = struct(... 'ngaus', p.ngaus,... 'mg', p.mg,... 'mn', p.mn,... 'vr', p.vr,... 'warpreg', p.warpreg,... 'warpco', p.warpco,... 'biasreg', p.biasreg,... 'biasfwhm', p.biasfwhm,... 'regtype', p.regtype,... 'fudge', p.fudge,... 'samp', p.samp,... 'msk', p.msk,... 'Affine', p.Affine,... 'Twarp', p.Twarp,... 'Tbias', p.Tbias,... 'thresh', p.thresh); if nargout==0, [pth,nam,ext] = fileparts(VF.fname); fnam = fullfile(pth,[nam '_seg_sn.mat']); if spm_matlab_version_chk('7') >= 0, save(fnam,'-V6','VG','VF','Tr','Affine','flags'); else save(fnam,'VG','VF','Tr','Affine','flags'); end; else po = struct(... 'VG', VG,... 'VF', VF,... 'Tr', Tr,... 'Affine', Affine,... 'flags', flags); end; if nargout>=2, % Parameterisation for the inverse pin = struct(... 'VG', p.image,... 'VF', p.tpm(1),... 'Tr', p.Twarp,... 'Affine', p.tpm(1).mat\p.Affine*p.image.mat,... 'flags', flags); % VG = p.image; % VF = p.tpm(1); % Tr = p.Twarp; % Affine = p.tpm(1).mat\p.Affine*p.image.mat; % save('junk_sn.mat','VG','VF','Tr','Affine'); end; return; %======================================================================= %======================================================================= function [Affine,Tr] = reparameterise(Y1,Y2,Y3,B,M2,MT,d2) % Take a deformation field and reparameterise in the same form % as used by the spatial normalisation routines of SPM d = [size(Y1) 1]; [x1,x2,o] = ndgrid(1:d(1),1:d(2),1); x3 = 1:d(3); Affine = M2\MT*B(1).mat; A = inv(Affine); B1 = spm_dctmtx(d(1),d2(1)); B2 = spm_dctmtx(d(2),d2(2)); B3 = spm_dctmtx(d(3),d2(3)); pd = prod(d2(1:3)); AA = eye(pd)*0.01; Ab = zeros(pd,3); spm_progress_bar('init',length(x3),['Reparameterising'],'Planes completed'); mx = [0 0 0]; for z=1:length(x3), y1 = double(Y1(:,:,z)); y2 = double(Y2(:,:,z)); y3 = double(Y3(:,:,z)); msk = isfinite(y1); w = double(msk); y1(~msk) = 0; y2(~msk) = 0; y3(~msk) = 0; z1 = A(1,1)*y1+A(1,2)*y2+A(1,3)*y3 + w.*(A(1,4) - x1); z2 = A(2,1)*y1+A(2,2)*y2+A(2,3)*y3 + w.*(A(2,4) - x2); z3 = A(3,1)*y1+A(3,2)*y2+A(3,3)*y3 + w *(A(3,4) - z ); b3 = B3(z,:)'; Ab(:,1) = Ab(:,1) + kron(b3,spm_krutil(z1,B1,B2,0)); Ab(:,2) = Ab(:,2) + kron(b3,spm_krutil(z2,B1,B2,0)); Ab(:,3) = Ab(:,3) + kron(b3,spm_krutil(z3,B1,B2,0)); AA = AA + kron(b3*b3',spm_krutil(w, B1,B2,1)); spm_progress_bar('set',z); end; spm_progress_bar('clear'); Tr = reshape(AA\Ab,[d2(1:3) 3]); drawnow; return; %======================================================================= %======================================================================= function MT = procrustes(Y1,Y2,Y3,B,M2) % Take a deformation field and determine the closest rigid-body % transform to match it, with weighing. % % Example Reference: % F. L. Bookstein (1997). "Landmark Methods for Forms Without % Landmarks: Morphometrics of Group Differences in Outline Shape" % Medical Image Analysis 1(3):225-243 M1 = B.mat; d = B.dim(1:3); [x1,x2,o] = ndgrid(1:d(1),1:d(2),1); x3 = 1:d(3); c1 = [0 0 0]; c2 = [0 0 0]; sw = 0; spm_progress_bar('init',length(x3),['Procrustes (1)'],'Planes completed'); for z=1:length(x3), y1 = double(Y1(:,:,z)); y2 = double(Y2(:,:,z)); y3 = double(Y3(:,:,z)); msk = find(isfinite(y1)); w = spm_sample_vol(B(1),x1(msk),x2(msk),o(msk)*z,0); swz = sum(w(:)); sw = sw+swz; c1 = c1 + [w'*[x1(msk) x2(msk)] swz*z ]; c2 = c2 + w'*[y1(msk) y2(msk) y3(msk)]; spm_progress_bar('set',z); end; spm_progress_bar('clear'); c1 = c1/sw; c2 = c2/sw; T1 = [eye(4,3) M1*[c1 1]']; T2 = [eye(4,3) M2*[c2 1]']; C = zeros(3); spm_progress_bar('init',length(x3),['Procrustes (2)'],'Planes completed'); for z=1:length(x3), y1 = double(Y1(:,:,z)); y2 = double(Y2(:,:,z)); y3 = double(Y3(:,:,z)); msk = find(isfinite(y1)); w = spm_sample_vol(B(1),x1(msk),x2(msk),o(msk)*z,0); C = C + [(x1(msk)-c1(1)).*w (x2(msk)-c1(2)).*w ( z-c1(3))*w ]' * ... [(y1(msk)-c2(1)) (y2(msk)-c2(2)) (y3(msk)-c2(3)) ]; spm_progress_bar('set',z); end; spm_progress_bar('clear'); [u,s,v] = svd(M1(1:3,1:3)*C*M2(1:3,1:3)'); R = eye(4); R(1:3,1:3) = v*u'; MT = T2*R*inv(T1); return; %======================================================================= %======================================================================= function [Y1,Y2,Y3] = create_def(T,VG,VF,Affine) % Generate a deformation field from its parameterisation. d2 = size(T); d = VG.dim(1:3); M = VF.mat\Affine*VG.mat; [x1,x2,o] = ndgrid(1:d(1),1:d(2),1); x3 = 1:d(3); B1 = spm_dctmtx(d(1),d2(1)); B2 = spm_dctmtx(d(2),d2(2)); B3 = spm_dctmtx(d(3),d2(3)); [pth,nam,ext] = fileparts(VG.fname); spm_progress_bar('init',length(x3),['Creating Def: ' nam],'Planes completed'); for z=1:length(x3), [y1,y2,y3] = defs(T,z,B1,B2,B3,x1,x2,x3,M); Y1(:,:,z) = single(y1); Y2(:,:,z) = single(y2); Y3(:,:,z) = single(y3); spm_progress_bar('set',z); end; spm_progress_bar('clear'); return; %======================================================================= %======================================================================= function [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M) if ~isempty(sol), x1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1)); y1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2)); z1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3)); else x1a = x0; y1a = y0; z1a = z0; end; x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4); y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4); z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4); return; %======================================================================= %======================================================================= function t = transf(B1,B2,B3,T) d2 = [size(T) 1]; t1 = reshape(T, d2(1)*d2(2),d2(3)); drawnow; t1 = reshape(t1*B3', d2(1), d2(2)); drawnow; t = B1*t1*B2'; return; %=======================================================================
github
lcnhappe/happe-master
cfg_getfile.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/matlabbatch/cfg_getfile.m
46,070
utf_8
3e6a6877315f1b08af13c88de5044295
function [t,sts] = cfg_getfile(varargin) % File selector % FORMAT [t,sts] = cfg_getfile(n,typ,mesg,sel,wd,filt,frames) % n - Number of files % A single value or a range. e.g. % 1 - Select one file % Inf - Select any number of files % [1 Inf] - Select 1 to Inf files % [0 1] - select 0 or 1 files % [10 12] - select from 10 to 12 files % typ - file type % 'any' - all files % 'batch' - SPM batch files (.m, .mat and XML) % 'dir' - select a directory % 'image' - Image files (".img" and ".nii") % Note that it gives the option to select % individual volumes of the images. % 'mat' - Matlab .mat files or .txt files (assumed to contain % ASCII representation of a 2D-numeric array) % 'mesh' - Mesh files (".gii" and ".mat") % 'nifti' - NIfTI files without the option to select frames % 'xml' - XML files % Other strings act as a filter to regexp. This means % that e.g. DCM*.mat files should have a typ of '^DCM.*\.mat$' % mesg - a prompt (default 'Select files...') % sel - list of already selected files % wd - Directory to start off in % filt - value for user-editable filter (default '.*') % frames - Image frame numbers to include (default '1') % % t - selected files % sts - status (1 means OK, 0 means window quit) % % FORMAT [t,ind] = cfg_getfile('Filter',files,typ,filt,frames) % filter the list of files (cell array) in the same way as the % GUI would do. There is an additional typ 'extimage' which will match % images with frame specifications, too. The 'frames' argument % is currently ignored, i.e. image files will not be filtered out if % their frame numbers do not match. % When filtering directory names, the filt argument will be applied to the % last directory in a path only. % t returns the filtered list (cell array), ind an index array, such that % t = files(ind). % % FORMAT cpath = cfg_getfile('CPath',path,cwd) % function to canonicalise paths: Prepends cwd to relative paths, processes % '..' & '.' directories embedded in path. % path - string matrix containing path name % cwd - current working directory [default '.'] % cpath - conditioned paths, in same format as input path argument % % FORMAT [files,dirs]=cfg_getfile('List',direc,filt) % Returns files matching the filter (filt) and directories within dire % direc - directory to search % filt - filter to select files with (see regexp) e.g. '^w.*\.img$' % files - files matching 'filt' in directory 'direc' % dirs - subdirectories of 'direc' % FORMAT [files,dirs]=cfg_getfile('ExtList',direc,filt,frames) % As above, but for selecting frames of 4D NIfTI files % frames - vector of frames to select (defaults to 1, if not % specified). If the frame number is Inf, all frames for the % matching images are listed. % FORMAT [files,dirs]=cfg_getfile('FPList',direc,filt) % FORMAT [files,dirs]=cfg_getfile('ExtFPList',direc,filt,frames) % As above, but returns files with full paths (i.e. prefixes direc to each) % FORMAT [files,dirs]=cfg_getfile('FPListRec',direc,filt) % FORMAT [files,dirs]=cfg_getfile('ExtFPListRec',direc,filt,frames) % As above, but returns files with full paths (i.e. prefixes direc to % each) and searches through sub directories recursively. % % FORMAT cfg_getfile('prevdirs',dir) % Add directory dir to list of previous directories. % FORMAT dirs=cfg_getfile('prevdirs') % Retrieve list of previous directories. % % This code is based on the file selection dialog in SPM5, with virtual % file handling turned off. %____________________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % % This code is part of a batch job configuration system for MATLAB. See % help matlabbatch % for a general overview. %_______________________________________________________________________ % Copyright (C) 2007 Freiburg Brain Imaging % John Ashburner and Volkmar Glauche % $Id: cfg_getfile.m 6251 2014-10-30 13:58:44Z volkmar $ t = {}; sts = false; if nargin > 0 && ischar(varargin{1}) switch lower(varargin{1}) case {'addvfiles', 'clearvfiles', 'vfiles'} cfg_message('matlabbatch:deprecated:vfiles', ... 'Trying to use deprecated ''%s'' call.', ... lower(varargin{1})); case 'cpath' cfg_message(nargchk(2,Inf,nargin,'struct')); t = cpath(varargin{2:end}); sts = true; case 'filter' filt = mk_filter(varargin{3:end}); t = varargin{2}; if numel(t) == 1 && isempty(t{1}) sts = 1; return; end; t1 = cell(size(t)); if any(strcmpi(varargin{3},{'dir','extdir'})) % only filter last directory in path for k = 1:numel(t) t{k} = cpath(t{k}); if t{k}(end) == filesep [p n] = fileparts(t{k}(1:end-1)); else [p n] = fileparts(t{k}); end if strcmpi(varargin{3},'extdir') t1{k} = [n filesep]; else t1{k} = n; end end else % only filter filenames, not paths for k = 1:numel(t) [p n e] = fileparts(t{k}); t1{k} = [n e]; end end [t1,sts1] = do_filter(t1,filt.ext); [t1,sts2] = do_filter(t1,filt.filt); sts = sts1(sts2); t = t(sts); case {'list', 'fplist', 'extlist', 'extfplist'} if nargin > 3 frames = varargin{4}; else frames = 1; % (ignored in listfiles if typ==any) end; if regexpi(varargin{1}, 'ext') % use frames descriptor typ = 'extimage'; else typ = 'any'; end filt = mk_filter(typ, varargin{3}, frames); [t sts] = listfiles(varargin{2}, filt); % (sts is subdirs here) sts = sts(~(strcmp(sts,'.')|strcmp(sts,'..'))); % remove '.' and '..' entries if regexpi(varargin{1}, 'fplist') % return full pathnames direc = cfg_getfile('cpath', varargin{2}); % remove trailing path separator if present direc = regexprep(direc, [filesep '$'], ''); if ~isempty(t) t = strcat(direc, filesep, t); end if nargout > 1 % subdirs too sts = cellfun(@(sts1)cpath(sts1, direc), sts, 'UniformOutput',false); end end case {'fplistrec', 'extfplistrec'} % list directory [f1 d1] = cfg_getfile(varargin{1}(1:end-3),varargin{2:end}); f2 = cell(size(d1)); d2 = cell(size(d1)); for k = 1:numel(d1) % recurse into sub directories [f2{k} d2{k}] = cfg_getfile(varargin{1}, d1{k}, ... varargin{3:end}); end t = vertcat(f1, f2{:}); if nargout > 1 sts = vertcat(d1, d2{:}); end case 'prevdirs', if nargin > 1 prevdirs(varargin{2}); end; if nargout > 0 || nargin == 1 t = prevdirs; sts = true; end; otherwise cfg_message('matlabbatch:usage','Inappropriate usage.'); end else [t,sts] = selector(varargin{:}); end %======================================================================= %======================================================================= function [t,ok] = selector(n,typ,mesg,already,wd,filt,frames,varargin) if nargin<1 || ~isnumeric(n) || numel(n) > 2 n = [0 Inf]; else if numel(n)==1, n = [n n]; end; if n(1)>n(2), n = n([2 1]); end; if ~isfinite(n(1)), n(1) = 0; end; end if nargin<2 || ~ischar(typ), typ = 'any'; end; if nargin<3 || ~(ischar(mesg) || iscellstr(mesg)) mesg = 'Select files...'; elseif iscellstr(mesg) mesg = char(mesg); end if nargin<4 || isempty(already) || (iscell(already) && isempty(already{1})) already = {}; else % Add folders of already selected files to prevdirs list pd1 = cellfun(@(a1)strcat(fileparts(a1),filesep), already, ... 'UniformOutput',false); prevdirs(pd1); end if nargin<5 || isempty(wd) || ~ischar(wd) if isempty(already) wd = pwd; else wd = fileparts(already{1}); if isempty(wd) wd = pwd; end end; end if nargin<6 || ~ischar(filt), filt = '.*'; end; if nargin<7 || ~(isnumeric(frames) || ischar(frames)) frames = '1'; elseif isnumeric(frames) frames = char(gencode_rvalue(frames(:)')); elseif ischar(frames) try ev = eval(frames); if ~isnumeric(ev) frames = '1'; end catch frames = '1'; end end ok = 0; t = ''; sfilt = mk_filter(typ,filt,eval(frames)); [col1,col2,col3,lf,bf] = colours; % delete old selector, if any fg = findobj(0,'Tag',mfilename); if ~isempty(fg) delete(fg); end % create figure fg = figure('IntegerHandle','off',... 'Tag',mfilename,... 'Name',mesg,... 'NumberTitle','off',... 'Units','Pixels',... 'MenuBar','none',... 'DefaultTextInterpreter','none',... 'DefaultUicontrolInterruptible','on',... 'Visible','off'); cfg_onscreen(fg); set(fg,'Visible','on'); sellines = min([max([n(2) numel(already)]), 4]); [pselp pcntp pfdp pdirp] = panelpositions(fg, sellines+1); uicontrol(fg,... 'style','text',... 'units','normalized',... 'position',posinpanel([0 sellines/(sellines+1) 1 1/(sellines+1)],pselp),... lf,... 'BackgroundColor',get(fg,'Color'),... 'ForegroundColor',col3,... 'HorizontalAlignment','left',... 'string',mesg,... 'tag','msg'); % Selected Files sel = uicontrol(fg,... 'style','listbox',... 'units','normalized',... 'Position',posinpanel([0 0 1 sellines/(sellines+1)],pselp),... lf,... 'Callback',@unselect,... 'tag','selected',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'Max',10000,... 'Min',0,... 'String',already,... 'Value',1); c0 = uicontextmenu('Parent',fg); set(sel,'uicontextmenu',c0); uimenu('Label','Unselect All', 'Parent',c0,'Callback',@unselect_all); % get cwidth for buttons tmp=uicontrol('style','text','string',repmat('X',[1,50]),bf,... 'units','normalized','visible','off'); fnp = get(tmp,'extent'); delete(tmp); cw = 3*fnp(3)/50; if strcmpi(typ,'image'), uicontrol(fg,... 'style','edit',... 'units','normalized',... 'Position',posinpanel([0.61 0 0.37 .45],pcntp),... 'Callback',@update_frames,... 'tag','frame',... lf,... 'BackgroundColor',col1,... 'String',frames,'UserData',eval(frames)); % 'ForegroundGolor',col3,... end; % Help uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',posinpanel([0.02 .5 cw .45],pcntp),... bf,... 'Callback',@heelp,... 'tag','?',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','?',... 'ToolTipString','Show Help'); uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',posinpanel([0.03+cw .5 cw .45],pcntp),... bf,... 'Callback',@editwin,... 'tag','Ed',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','Ed',... 'ToolTipString','Edit Selected Files'); uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',posinpanel([0.04+2*cw .5 cw .45],pcntp),... bf,... 'Callback',@select_rec,... 'tag','Rec',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','Rec',... 'ToolTipString','Recursively Select Files with Current Filter'); % Done dne = uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',posinpanel([0.05+3*cw .5 0.45-3*cw .45],pcntp),... bf,... 'Callback',@(h,e)delete(h),... 'tag','D',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','Done',... 'Enable','off',... 'DeleteFcn',@null); if numel(already)>=n(1) && numel(already)<=n(2), set(dne,'Enable','on'); end; % Filter Button uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',posinpanel([0.51 .5 0.1 .45],pcntp),... bf,... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'Callback',@clearfilt,... 'String','Filt'); % Filter uicontrol(fg,... 'style','edit',... 'units','normalized',... 'Position',posinpanel([0.61 .5 0.37 .45],pcntp),... 'ForegroundColor',col3,... 'BackgroundColor',col1,... lf,... 'Callback',@(ob,ev)update(ob),... 'tag','regexp',... 'String',filt,... 'UserData',sfilt); % Directories db = uicontrol(fg,... 'style','listbox',... 'units','normalized',... 'Position',posinpanel([0.02 0 0.47 1],pfdp),... lf,... 'Callback',@click_dir_box,... 'tag','dirs',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'Max',1,... 'Min',0,... 'String','',... 'UserData',wd,... 'Value',1); % Files tmp = uicontrol(fg,... 'style','listbox',... 'units','normalized',... 'Position',posinpanel([0.51 0 0.47 1],pfdp),... lf,... 'Callback',@click_file_box,... 'tag','files',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'UserData',n,... 'Max',10240,... 'Min',0,... 'String','',... 'Value',1); c0 = uicontextmenu('Parent',fg); set(tmp,'uicontextmenu',c0); uimenu('Label','Select All', 'Parent',c0,'Callback',@select_all); % Drives if strcmpi(computer,'PCWIN') || strcmpi(computer,'PCWIN64'), % get fh for lists tmp=uicontrol('style','text','string','X',lf,... 'units','normalized','visible','off'); fnp = get(tmp,'extent'); delete(tmp); fh = 2*fnp(4); % Heuristics: why do we need 2* sz = get(db,'Position'); sz(4) = sz(4)-fh-2*0.01; set(db,'Position',sz); uicontrol(fg,... 'style','text',... 'units','normalized',... 'Position',posinpanel([0.02 1-fh-0.01 0.10 fh],pfdp),... 'HorizontalAlignment','left',... lf,... 'BackgroundColor',get(fg,'Color'),... 'ForegroundColor',col3,... 'String','Drive'); uicontrol(fg,... 'style','popupmenu',... 'units','normalized',... 'Position',posinpanel([0.12 1-fh-0.01 0.37 fh],pfdp),... lf,... 'Callback',@setdrive,... 'tag','drive',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'String',listdrives(false),... 'Value',1); end; [pd,vl] = prevdirs([wd filesep]); % Previous dirs uicontrol(fg,... 'style','popupmenu',... 'units','normalized',... 'Position',posinpanel([0.12 .05 0.86 .95*1/3],pdirp),... lf,... 'Callback',@click_dir_list,... 'tag','previous',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'String',pd,... 'Value',vl); uicontrol(fg,... 'style','text',... 'units','normalized',... 'Position',posinpanel([0.02 0 0.10 .95*1/3],pdirp),... 'HorizontalAlignment','left',... lf,... 'BackgroundColor',get(fg,'Color'),... 'ForegroundColor',col3,... 'String','Prev'); % Parent dirs uicontrol(fg,... 'style','popupmenu',... 'units','normalized',... 'Position',posinpanel([0.12 1/3+.05 0.86 .95*1/3],pdirp),... lf,... 'Callback',@click_dir_list,... 'tag','pardirs',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'String',pardirs(wd)); uicontrol(fg,... 'style','text',... 'units','normalized',... 'Position',posinpanel([0.02 1/3 0.10 .95*1/3],pdirp),... 'HorizontalAlignment','left',... lf,... 'BackgroundColor',get(fg,'Color'),... 'ForegroundColor',col3,... 'String','Up'); % Directory uicontrol(fg,... 'style','edit',... 'units','normalized',... 'Position',posinpanel([0.12 2/3 0.86 .95*1/3],pdirp),... lf,... 'Callback',@edit_dir,... 'tag','edit',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'String',''); uicontrol(fg,... 'style','text',... 'units','normalized',... 'Position',posinpanel([0.02 2/3 0.10 .95*1/3],pdirp),... 'HorizontalAlignment','left',... lf,... 'BackgroundColor',get(fg,'Color'),... 'ForegroundColor',col3,... 'String','Dir'); resize_fun(fg); set(fg, 'ResizeFcn',@resize_fun); update(sel,wd) set(fg,'windowstyle', 'modal'); waitfor(dne); drawnow; if ishandle(sel), t = get(sel,'String'); if isempty(t) t = {''}; elseif sfilt.code == -1 % canonicalise non-empty folder selection t = cellfun(@(t1)cpath(t1, pwd), t, 'UniformOutput',false); end; ok = 1; end; if ishandle(fg), delete(fg); end; drawnow; return; %======================================================================= %======================================================================= function apos = posinpanel(rpos,ppos) % Compute absolute positions based on panel position and relative % position apos = [ppos(1:2)+ppos(3:4).*rpos(1:2) ppos(3:4).*rpos(3:4)]; %======================================================================= %======================================================================= function [pselp, pcntp, pfdp, pdirp] = panelpositions(fg, sellines) if nargin == 1 na = numel(get(findobj(fg,'Tag','selected'),'String')); n = get(findobj(fg,'Tag','files'),'Userdata'); sellines = min([max([n(2) na]), 4]); end lf = cfg_get_defaults('cfg_ui.lfont'); bf = cfg_get_defaults('cfg_ui.bfont'); % Create dummy text to estimate character height t=uicontrol('style','text','string','Xg','units','normalized','visible','off',lf); lfh = 1.05*get(t,'extent'); delete(t) t=uicontrol('style','text','string','Xg','units','normalized','visible','off',bf); bfh = 1.05*get(t,'extent'); delete(t) % panel heights % 3 lines for directory, parent and prev directory list % variable height for dir/file navigation % 2 lines for buttons, filter etc % sellines plus scrollbar for selected files pselh = sellines*lfh(4) + 1.2*lfh(4); pselp = [0 0 1 pselh]; pcnth = 2*bfh(4); pcntp = [0 pselh 1 pcnth]; pdirh = 3*lfh(4); pdirp = [0 1-pdirh 1 pdirh]; pfdh = 1-(pselh+pcnth+pdirh); pfdp = [0 pselh+pcnth 1 pfdh]; %======================================================================= %======================================================================= function null(varargin) %======================================================================= %======================================================================= function omsg = msg(ob,str) ob = sib(ob,'msg'); omsg = get(ob,'String'); set(ob,'String',str); if nargin>=3, set(ob,'ForegroundColor',[1 0 0],'FontWeight','bold'); else set(ob,'ForegroundColor',[0 0 0],'FontWeight','normal'); end; drawnow; return; %======================================================================= %======================================================================= function setdrive(ob,varargin) st = get(ob,'String'); vl = get(ob,'Value'); update(ob,st{vl}); return; %======================================================================= %======================================================================= function resize_fun(fg,varargin) % do nothing return; [pselp pcntp pfdp pdirp] = panelpositions(fg); set(findobj(fg,'Tag','msg'), 'Position',pselp); set(findobj(fg,'Tag','pcnt'), 'Position',pcntp); set(findobj(fg,'Tag','pfd'), 'Position',pfdp); set(findobj(fg,'Tag','pdir'), 'Position',pdirp); return; %======================================================================= %======================================================================= function [d,mch] = prevdirs(d) persistent pd if ~iscell(pd), pd = {}; end; if nargin == 0 d = pd; else if ~iscell(d) d = cellstr(d); end d = unique(d(:)); mch = cellfun(@(d1)find(strcmp(d1,pd)), d, 'UniformOutput',false); sel = cellfun(@isempty, mch); npd = numel(pd); pd = [pd(:);d(sel)]; mch = [mch{~sel} npd+(1:nnz(sel))]; d = pd; end return; %======================================================================= %======================================================================= function pd = pardirs(wd) if ispc fs = '\\'; else fs = filesep; end pd1 = textscan(wd,'%s','delimiter',fs,'MultipleDelimsAsOne',1); if ispc pd = cell(size(pd1{1})); pd{end} = pd1{1}{1}; for k = 2:numel(pd1{1}) pd{end-k+1} = fullfile(pd1{1}{1:k},filesep); end else pd = cell(numel(pd1{1})+1,1); pd{end} = filesep; for k = 1:numel(pd1{1}) pd{end-k} = fullfile(filesep,pd1{1}{1:k},filesep); end end %======================================================================= %======================================================================= function clearfilt(ob,varargin) set(sib(ob,'regexp'),'String','.*'); update(ob); return; %======================================================================= %======================================================================= function click_dir_list(ob,varargin) vl = get(ob,'Value'); ls = get(ob,'String'); update(ob,deblank(ls{vl})); return; %======================================================================= %======================================================================= function edit_dir(ob,varargin) update(ob,get(ob,'String')); return; %======================================================================= %======================================================================= function c = get_current_char(lb) fg = sib(lb, mfilename); c = get(fg, 'CurrentCharacter'); if ~isempty(c) % reset CurrentCharacter set(fg, 'CurrentCharacter', char(13)); end %======================================================================= %======================================================================= function click_dir_box(lb,varargin) c = get_current_char(lb); if isempty(c) || isequal(c,char(13)) vl = get(lb,'Value'); str = get(lb,'String'); pd = get(sib(lb,'edit'),'String'); while ~isempty(pd) && strcmp(pd(end),filesep) pd=pd(1:end-1); % Remove any trailing fileseps end sel = str{vl}; if strcmp(sel,'..'), % Parent directory [dr odr] = fileparts(pd); elseif strcmp(sel,'.'), % Current directory dr = pd; odr = ''; else dr = fullfile(pd,sel); odr = ''; end; update(lb,dr); if ~isempty(odr) % If moving up one level, try to set focus on previously visited % directory cdrs = get(lb, 'String'); dind = find(strcmp(odr, cdrs)); if ~isempty(dind) set(lb, 'Value',dind(1)); end end end return; %======================================================================= %======================================================================= function re = getfilt(ob) ob = sib(ob,'regexp'); ud = get(ob,'UserData'); re = struct('code',ud.code,... 'frames',get(sib(ob,'frame'),'UserData'),... 'ext',{ud.ext},... 'filt',{{get(sib(ob,'regexp'),'String')}}); return; %======================================================================= %======================================================================= function update(lb,dr) lb = sib(lb,'dirs'); if nargin<2 || isempty(dr) || ~ischar(dr) dr = get(lb,'UserData'); end; if ~(strcmpi(computer,'PCWIN') || strcmpi(computer,'PCWIN64')) dr = [filesep dr filesep]; else dr = [dr filesep]; end; dr(strfind(dr,[filesep filesep])) = []; [f,d] = listfiles(dr,getfilt(lb)); if isempty(d), dr = get(lb,'UserData'); [f,d] = listfiles(dr,getfilt(lb)); else set(lb,'UserData',dr); end; set(lb,'Value',1,'String',d); set(sib(lb,'files'),'Value',1,'String',f); set(sib(lb,'pardirs'),'String',pardirs(dr),'Value',1); [ls,mch] = prevdirs(dr); set(sib(lb,'previous'),'String',ls,'Value',mch); set(sib(lb,'edit'),'String',dr); if numel(dr)>1 && dr(2)==':', str = char(get(sib(lb,'drive'),'String')); mch = find(lower(str(:,1))==lower(dr(1))); if ~isempty(mch), set(sib(lb,'drive'),'Value',mch); end; end; return; %======================================================================= %======================================================================= function update_frames(lb,varargin) str = get(lb,'String'); %r = get(lb,'UserData'); try r = eval(['[',str,']']); catch msg(lb,['Failed to evaluate "' str '".'],'r'); beep; return; end; if ~isnumeric(r), msg(lb,['Expression non-numeric "' str '".'],'r'); beep; else set(lb,'UserData',r); msg(lb,''); update(lb); end; %======================================================================= %======================================================================= function select_all(ob,varargin) lb = sib(ob,'files'); set(lb,'Value',1:numel(get(lb,'String'))); drawnow; click_file_box(lb); return; %======================================================================= %======================================================================= function click_file_box(lb,varargin) c = get_current_char(lb); if isempty(c) || isequal(c, char(13)) vlo = get(lb,'Value'); if isempty(vlo), msg(lb,'Nothing selected'); return; end; lim = get(lb,'UserData'); ob = sib(lb,'selected'); str3 = get(ob,'String'); str = get(lb,'String'); lim1 = min([max([lim(2)-numel(str3),0]),numel(vlo)]); if lim1==0, msg(lb,['Selected ' num2str(size(str3,1)) '/' num2str(lim(2)) ' already.']); beep; set(sib(lb,'D'),'Enable','on'); return; end; vl = vlo(1:lim1); msk = false(size(str,1),1); if vl>0, msk(vl) = true; else msk = []; end; str1 = str( msk); str2 = str(~msk); dr = get(sib(lb,'edit'), 'String'); str1 = strcat(dr, str1); set(lb,'Value',min([vl(1),numel(str2)]),'String',str2); r = (1:numel(str1))+numel(str3); str3 = [str3(:);str1(:)]; set(ob,'String',str3,'Value',r); if numel(vlo)>lim1, msg(lb,['Retained ' num2str(lim1) '/' num2str(numel(vlo))... ' of selection.']); beep; elseif isfinite(lim(2)) if lim(1)==lim(2), msg(lb,['Selected ' num2str(numel(str3)) '/' num2str(lim(2)) ' files.']); else msg(lb,['Selected ' num2str(numel(str3)) '/' num2str(lim(1)) '-' num2str(lim(2)) ' files.']); end; else if size(str3,1) == 1, ss = ''; else ss = 's'; end; msg(lb,['Selected ' num2str(numel(str3)) ' file' ss '.']); end; if ~isfinite(lim(1)) || numel(str3)>=lim(1), set(sib(lb,'D'),'Enable','on'); end; end return; %======================================================================= %======================================================================= function obj = sib(ob,tag) persistent fg; if isempty(fg) || ~ishandle(fg) fg = findobj(0,'Tag',mfilename); end obj = findobj(fg,'Tag',tag); return; %if isempty(obj), % cfg_message('matlabbatch:usage',['Can''t find object with tag "' tag '".']); %elseif length(obj)>1, % cfg_message('matlabbatch:usage',['Found ' num2str(length(obj)) ' objects with tag "' tag '".']); %end; %return; %======================================================================= %======================================================================= function unselect(lb,varargin) vl = get(lb,'Value'); if isempty(vl), return; end; str = get(lb,'String'); msk = true(numel(str),1); if vl~=0, msk(vl) = false; end; str2 = str(msk); set(lb,'Value',min(vl(1),numel(str2)),'String',str2); lim = get(sib(lb,'files'),'UserData'); if numel(str2)>= lim(1) && numel(str2)<= lim(2), set(sib(lb,'D'),'Enable','on'); else set(sib(lb,'D'),'Enable','off'); end; if numel(str2) == 1, ss1 = ''; else ss1 = 's'; end; %msg(lb,[num2str(size(str2,1)) ' file' ss ' remaining.']); if numel(vl) == 1, ss = ''; else ss = 's'; end; msg(lb,['Unselected ' num2str(numel(vl)) ' file' ss '. ' ... num2str(numel(str2)) ' file' ss1 ' remaining.']); return; %======================================================================= %======================================================================= function unselect_all(ob,varargin) lb = sib(ob,'selected'); set(lb,'Value',[],'String',{},'ListBoxTop',1); msg(lb,'Unselected all files.'); lim = get(sib(lb,'files'),'UserData'); if lim(1)>0, set(sib(lb,'D'),'Enable','off'); end; return; %======================================================================= %======================================================================= function [f,d] = listfiles(dr,filt) try ob = sib(gco,'msg'); domsg = ~isempty(ob); catch domsg = false; end if domsg omsg = msg(ob,'Listing directory...'); end if nargin<2, filt = ''; end; if nargin<1, dr = '.'; end; de = dir(dr); if ~isempty(de), d = {de([de.isdir]).name}; if ~any(strcmp(d, '.')) d = [{'.'}, d(:)']; end; if filt.code~=-1, f = {de(~[de.isdir]).name}; else % f = d(3:end); f = d; end; else d = {'.','..'}; f = {}; end; if domsg msg(ob,['Filtering ' num2str(numel(f)) ' files...']); end f = do_filter(f,filt.ext); f = do_filter(f,filt.filt); ii = cell(1,numel(f)); if filt.code==1 && (numel(filt.frames)~=1 || filt.frames(1)~=1), if domsg msg(ob,['Reading headers of ' num2str(numel(f)) ' images...']); end for i=1:numel(f), try ni = nifti(fullfile(dr,f{i})); dm = [ni.dat.dim 1 1 1 1 1]; d4 = (1:dm(4))'; catch d4 = 1; end; if all(isfinite(filt.frames)) msk = false(size(filt.frames)); for j=1:numel(msk), msk(j) = any(d4==filt.frames(j)); end; ii{i} = filt.frames(msk); else ii{i} = d4; end; end elseif filt.code==1 && (numel(filt.frames)==1 && filt.frames(1)==1), for i=1:numel(f), ii{i} = 1; end; end; if domsg msg(ob,['Listing ' num2str(numel(f)) ' files...']); end [f,ind] = sortrows(f(:)); ii = ii(ind); msk = true(1,numel(f)); for i=2:numel(f), if strcmp(f{i-1},f{i}), if filt.code==1, tmp = sort([ii{i}(:) ; ii{i-1}(:)]); tmp(~diff(tmp,1)) = []; ii{i} = tmp; end; msk(i-1) = false; end; end; f = f(msk); if filt.code==1, % Combine filename and frame number(s) ii = ii(msk); nii = cellfun(@numel, ii); c = cell(sum(nii),1); fi = cell(numel(f),1); for k = 1:numel(fi) fi{k} = k*ones(1,nii(k)); end ii = [ii{:}]; fi = [fi{:}]; for i=1:numel(c), c{i} = sprintf('%s,%d', f{fi(i)}, ii(i)); end; f = c; elseif filt.code==-1, fs = filesep; for i=1:numel(f), f{i} = [f{i} fs]; end; end; f = f(:); d = unique(d(:)); if domsg msg(ob,omsg); end return; %======================================================================= %======================================================================= function [f,ind] = do_filter(f,filt) t2 = false(numel(f),1); filt_or = sprintf('(%s)|',filt{:}); t1 = regexp(f,filt_or(1:end-1)); if numel(f)==1 && ~iscell(t1), t1 = {t1}; end; for i=1:numel(t1), t2(i) = ~isempty(t1{i}); end; ind = find(t2); f = f(t2); return; %======================================================================= %======================================================================= function heelp(ob,varargin) [col1,col2,col3,fn] = colours; fg = sib(ob,mfilename); t = uicontrol(fg,... 'style','listbox',... 'units','normalized',... 'Position',[0.01 0.01 0.98 0.98],... fn,... 'BackgroundColor',col2,... 'ForegroundColor',col3,... 'Max',0,... 'Min',0,... 'tag','HelpWin',... 'String',' '); c0 = uicontextmenu('Parent',fg); set(t,'uicontextmenu',c0); uimenu('Label','Done', 'Parent',c0,'Callback',@helpclear); str = cfg_justify(t, {[... 'File Selection help. You can return to selecting files via the right mouse button (the "Done" option). '],... '',[... 'The panel at the bottom shows files that are already selected. ',... 'Clicking a selected file will un-select it. To un-select several, you can ',... 'drag the cursor over the files, and they will be gone on release. ',... 'You can use the right mouse button to un-select everything.'],... '',[... 'Directories are navigated by editing the name of the current directory (where it says "Dir"), ',... 'by going to one of the previously entered directories ("Prev"), ',... 'by going to one of the parent directories ("Up") or by navigating around ',... 'the parent or subdirectories listed in the left side panel.'],... '',[... 'Files matching the filter ("Filt") are shown in the panel on the right. ',... 'These can be selected by clicking or dragging. Use the right mouse button if ',... 'you would like to select all files. Note that when selected, the files disappear ',... 'from this panel. They can be made to reappear by re-specifying the directory ',... 'or the filter. '],... '',[... 'Both directory and file lists can also be browsed by typing the leading ',... 'character(s) of a directory or file name.'],... '',[... 'Note that the syntax of the filter differs from that used by most other file selectors. ',... 'The filter works using so called ''regular expressions''. Details can be found in the ',... 'MATLAB help text on ''regexp''. ',... 'The following is a list of symbols with special meaning for filtering the filenames:'],... ' ^ start of string',... ' $ end of string',... ' . any character',... ' \ quote next character',... ' * match zero or more',... ' + match one or more',... ' ? match zero or one, or match minimally',... ' {} match a range of occurrances',... ' [] set of characters',... ' [^] exclude a set of characters',... ' () group subexpression',... ' \w match word [a-z_A-Z0-9]',... ' \W not a word [^a-z_A-Z0-9]',... ' \d match digit [0-9]',... ' \D not a digit [^0-9]',... ' \s match white space [ \t\r\n\f]',... ' \S not a white space [^ \t\r\n\f]',... ' \<WORD\> exact word match',... '',[... 'Individual time frames of image files can also be selected. The frame filter ',... 'allows specified frames to be shown, which is useful for image files that ',... 'contain multiple time points. If your images are only single time point, then ',... 'reading all the image headers can be avoided by specifying a frame filter of "1". ',... 'The filter should contain a list of integers indicating the frames to be used. ',... 'This can be generated by e.g. "1:100", or "1:2:100".'],... '',[... 'The recursive selection button (Rec) allows files matching the regular expression to ',... 'be recursively selected. If there are many directories to search, then this can take ',... 'a while to run.'],... '',[... 'There is also an edit button (Ed), which allows you to edit your selection of files. ',... 'When you are done, then use the menu-button of your mouse to either cancel or accept your changes.'],''}); set(t,'String',str); return; %======================================================================= %======================================================================= function helpclear(ob,varargin) ob = get(ob,'Parent'); ob = get(ob,'Parent'); ob = findobj(ob,'Tag','HelpWin'); delete(ob); %======================================================================= %======================================================================= function t = cpath(t,d) switch filesep, case '/', mch = '^/'; fs = '/'; fs1 = '/'; case '\', mch = '^.:\\'; fs = '\'; fs1 = '\\'; otherwise; cfg_message('matlabbatch:usage','What is this filesystem?'); end if isempty(regexp(t,mch,'once')), if (nargin<2)||isempty(d), d = pwd; end; t = [d fs t]; end; % Replace occurences of '/./' by '/' (problems with e.g. /././././././') re = [fs1 '\.' fs1]; while ~isempty(regexp(t,re, 'once' )), t = regexprep(t,re,fs); end; t = regexprep(t,[fs1 '\.' '$'], fs); % Replace occurences of '/abc/../' by '/' re = [fs1 '[^' fs1 ']+' fs1 '\.\.' fs1]; while ~isempty(regexp(t,re, 'once' )), t = regexprep(t,re,fs,'once'); end; t = regexprep(t,[fs1 '[^' fs1 ']+' fs1 '\.\.' '$'],fs,'once'); % Replace '//' t = regexprep(t,[fs1 '+'], fs); %======================================================================= %======================================================================= function editwin(ob,varargin) [col1,col2,col3,lf,bf] = colours; fg = gcbf; lb = sib(ob,'selected'); str = get(lb,'String'); ac = allchild(fg); acv = get(ac,'Visible'); h = uicontrol(fg,... 'Style','Edit',... 'units','normalized',... 'String',str,... lf,... 'Max',2,... 'Tag','EditWindow',... 'HorizontalAlignment','Left',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'Position',[0.01 0.08 0.98 0.9],... 'Userdata',struct('ac',{ac},'acv',{acv})); ea = uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',[.01 .01,.32,.07],... bf,... 'Callback',@editdone,... 'tag','EditWindowAccept',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','Accept'); ee = uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',[.34 .01,.32,.07],... bf,... 'Callback',@editeval,... 'tag','EditWindowEval',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','Eval'); ec = uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',[.67 .01,.32,.07],... bf,... 'Callback',@editclear,... 'tag','EditWindowCancel',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','Cancel'); set(ac,'visible','off'); %======================================================================= %======================================================================= function editeval(ob,varargin) ob = get(ob, 'Parent'); ob = sib(ob, 'EditWindow'); str = get(ob, 'String'); if ~isempty(str) [out,sts] = cfg_eval_valedit(char(str)); if sts && (iscellstr(out) || ischar(out)) set(ob, 'String', cellstr(out)); else fgc = get(ob, 'ForegroundColor'); set(ob, 'ForegroundColor', 'red'); pause(1); set(ob, 'ForegroundColor', fgc); end end %======================================================================= %======================================================================= function editdone(ob,varargin) ob = get(ob,'Parent'); ob = sib(ob,'EditWindow'); str = cellstr(get(ob,'String')); if isempty(str) || isempty(str{1}) str = {}; else dstr = deblank(str); if ~isequal(str, dstr) c = questdlg(['Some of the filenames contain trailing blanks. This may ' ... 'be due to copy/paste of strings between MATLAB and the ' ... 'edit window. Do you want to remove any trailing blanks?'], ... 'Trailing Blanks in Filenames', ... 'Remove', 'Keep', 'Remove'); switch lower(c) case 'remove' str = dstr; end end filt = getfilt(ob); if filt.code >= 0 % filter files, but not dirs [p,n,e] = cellfun(@fileparts, str, 'uniformoutput',false); fstr = strcat(n, e); [fstr1,fsel] = do_filter(fstr, filt.ext); str = str(fsel); end end lim = get(sib(ob,'files'),'UserData'); if numel(str)>lim(2), msg(ob,['Retained ' num2str(lim(2)) ' of the ' num2str(numel(str)) ' files.']); beep; str = str(1:lim(2)); elseif isfinite(lim(2)), if lim(1)==lim(2), msg(ob,['Selected ' num2str(numel(str)) '/' num2str(lim(2)) ' files.']); else msg(ob,['Selected ' num2str(numel(str)) '/' num2str(lim(1)) '-' num2str(lim(2)) ' files.']); end; else if numel(str) == 1, ss = ''; else ss = 's'; end; msg(ob,['Specified ' num2str(numel(str)) ' file' ss '.']); end; if ~isfinite(lim(1)) || numel(str)>=lim(1), set(sib(ob,'D'),'Enable','on'); else set(sib(ob,'D'),'Enable','off'); end; set(sib(ob,'selected'),'String',str,'Value',[]); acs = get(ob,'Userdata'); fg = gcbf; delete(findobj(fg,'-regexp','Tag','^EditWindow.*')); set(acs.ac,{'Visible'},acs.acv); %======================================================================= %======================================================================= function editclear(ob,varargin) fg = gcbf; acs = get(findobj(fg,'Tag','EditWindow'),'Userdata'); delete(findobj(fg,'-regexp','Tag','^EditWindow.*')); set(acs.ac,{'Visible'},acs.acv); %======================================================================= %======================================================================= function [c1,c2,c3,lf,bf] = colours c1 = [1 1 1]; c2 = [1 1 1]; c3 = [0 0 0]; lf = cfg_get_defaults('cfg_ui.lfont'); bf = cfg_get_defaults('cfg_ui.bfont'); if isempty(lf) lf = struct('FontName',get(0,'FixedWidthFontName'), ... 'FontWeight','normal', ... 'FontAngle','normal', ... 'FontSize',14, ... 'FontUnits','points'); end if isempty(bf) bf = struct('FontName',get(0,'FixedWidthFontName'), ... 'FontWeight','normal', ... 'FontAngle','normal', ... 'FontSize',14, ... 'FontUnits','points'); end %======================================================================= %======================================================================= function select_rec(ob, varargin) start = get(sib(ob,'edit'),'String'); filt = get(sib(ob,'regexp'),'Userdata'); filt.filt = {get(sib(ob,'regexp'), 'String')}; fob = sib(ob,'frame'); if ~isempty(fob) filt.frames = get(fob,'Userdata'); else filt.frames = []; end; ptr = get(gcbf,'Pointer'); try set(gcbf,'Pointer','watch'); sel = select_rec1(start,filt); catch set(gcbf,'Pointer',ptr); sel = {}; end; set(gcbf,'Pointer',ptr); already= get(sib(ob,'selected'),'String'); fb = sib(ob,'files'); lim = get(fb,'Userdata'); limsel = min(lim(2)-size(already,1),size(sel,1)); set(sib(ob,'selected'),'String',[already(:);sel(1:limsel)],'Value',[]); msg(ob,sprintf('Added %d/%d matching files to selection.', limsel, size(sel,1))); if ~isfinite(lim(1)) || size(sel,1)>=lim(1), set(sib(ob,'D'),'Enable','on'); else set(sib(ob,'D'),'Enable','off'); end; %======================================================================= %======================================================================= function sel=select_rec1(cdir,filt) sel={}; [t,d] = listfiles(cdir,filt); if ~isempty(t) sel = strcat([cdir,filesep],t); end; for k = 1:numel(d) if ~any(strcmp(d{k},{'.','..'})) sel1 = select_rec1(fullfile(cdir,d{k}),filt); sel = [sel(:); sel1(:)]; end; end; %======================================================================= %======================================================================= function sfilt=mk_filter(typ,filt,frames) if nargin<3, frames = 1; end; if nargin<2, filt = '.*'; end; if nargin<1, typ = 'any'; end; switch lower(typ), case {'any','*'}, code = 0; ext = {'.*'}; case {'image'}, code = 1; ext = {'.*\.nii(,\d+){0,2}$','.*\.img(,\d+){0,2}$','.*\.NII(,\d+){0,2}$','.*\.IMG(,\d+){0,2}$'}; case {'mesh'}, code = 0; ext = {'.*\.gii$','.*\.GII$','.*\.mat$','.*\.MAT$'}; case {'nifti'}, code = 0; ext = {'.*\.nii$','.*\.img$','.*\.NII$','.*\.IMG$'}; case {'gifti'}, code = 0; ext = {'.*\.gii$','.*\.GII$'}; case {'extimage'}, code = 1; ext = {'.*\.nii(,[0-9]*){0,2}$',... '.*\.img(,[0-9]*){0,2}$',... '.*\.NII(,[0-9]*){0,2}$',... '.*\.IMG(,[0-9]*){0,2}$'}; case {'xml'}, code = 0; ext = {'.*\.xml$','.*\.XML$'}; case {'mat'}, code = 0; ext = {'.*\.mat$','.*\.MAT$','.*\.txt','.*\.TXT'}; case {'batch'}, code = 0; ext = {'.*\.mat$','.*\.MAT$','.*\.m$','.*\.M$','.*\.xml$','.*\.XML$'}; case {'dir'}, code =-1; ext = {'.*'}; case {'extdir'}, code =-1; ext = {['.*' filesep '$']}; otherwise, code = 0; ext = {typ}; end; sfilt = struct('code',code,'frames',frames,'ext',{ext},... 'filt',{{filt}}); %======================================================================= %======================================================================= function drivestr = listdrives(reread) persistent mydrivestr; if isempty(mydrivestr) || reread driveLett = strcat(cellstr(char(('C':'Z')')), ':'); dsel = false(size(driveLett)); for i=1:numel(driveLett) dsel(i) = exist([driveLett{i} '\'],'dir')~=0; end mydrivestr = driveLett(dsel); end; drivestr = mydrivestr; %======================================================================= %=======================================================================
github
lcnhappe/happe-master
coor2D.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@meeg/coor2D.m
4,007
utf_8
f94070275bb14e35788e110abf929115
function [res, plotind] = coor2D(this, ind, val, mindist) % returns x and y coordinates of channels in 2D plane % FORMAT coor2D(this) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Vladimir Litvak, Laurence Hunt % $Id: coor2D.m 4372 2011-06-21 21:26:46Z vladimir $ megind = strmatch('MEG', chantype(this)); eegind = strmatch('EEG', chantype(this), 'exact'); otherind = setdiff(1:nchannels(this), [megind; eegind]); if nargin==1 || isempty(ind) if nargin<3 || (size(val, 2)<nchannels(this)) if ~isempty(megind) ind = megind; elseif ~isempty(eegind) ind = eegind; else ind = 1:nchannels(this); end else ind = 1:nchannels(this); end elseif ischar(ind) switch upper(ind) case 'MEG' ind = megind; case 'EEG' ind = eegind; otherwise ind = otherind; end end if nargin < 3 || isempty(val) if ~isempty(intersect(ind, megind)) if ~any(cellfun('isempty', {this.channels(megind).X_plot2D})) meg_xy = [this.channels(megind).X_plot2D; this.channels(megind).Y_plot2D]; elseif all(cellfun('isempty', {this.channels(megind).X_plot2D})) meg_xy = grid(length(megind)); else error('Either all or none of MEG channels should have 2D coordinates defined.'); end end if ~isempty(intersect(ind, eegind)) if ~any(cellfun('isempty', {this.channels(eegind).X_plot2D})) eeg_xy = [this.channels(eegind).X_plot2D; this.channels(eegind).Y_plot2D]; elseif all(cellfun('isempty', {this.channels(eegind).X_plot2D})) eeg_xy = grid(length(eegind)); else error('Either all or none of EEG channels should have 2D coordinates defined.'); end end if ~isempty(intersect(ind, otherind)) other_xy = grid(length(otherind)); end xy = zeros(2, length(ind)); plotind = zeros(1, length(ind)); for i = 1:length(ind) [found, loc] = ismember(ind(i), megind); if found xy(:, i) = meg_xy(:, loc); plotind(i) = 1; else [found, loc] = ismember(ind(i), eegind); if found xy(:, i) = eeg_xy(:, loc); plotind(i) = 2; else [found, loc] = ismember(ind(i), otherind); if found xy(:, i) = other_xy(:, loc); plotind(i) = 3; end end end end if nargin > 3 && ~isempty(mindist) xy = shiftxy(xy,mindist); end res = xy; else this = getset(this, 'channels', 'X_plot2D', ind, val(1, :)); this = getset(this, 'channels', 'Y_plot2D', ind, val(2, :)); res = this; end function xy = grid(n) ncol = ceil(sqrt(n)); x = 0:(1/(ncol+1)):1; x = 0.9*x+0.05; x = x(2:(end-1)); y = fliplr(x); [X, Y] = meshgrid(x, y); xy = [X(1:n); Y(1:n)]; function xy = shiftxy(xy,mindist) x = xy(1,:); y = xy(2,:); l=1; i=1; %filler mindist = mindist/0.999; % limits the number of loops while (~isempty(i) && l<50) xdiff = repmat(x,length(x),1) - repmat(x',1,length(x)); ydiff = repmat(y,length(y),1) - repmat(y',1,length(y)); xydist= sqrt(xdiff.^2 + ydiff.^2); %euclidean distance between all sensor pairs [i,j] = find(xydist<mindist*0.999); rm=(i<=j); i(rm)=[]; j(rm)=[]; %only look at i>j for m = 1:length(i); if (xydist(i(m),j(m)) == 0) diffvec = [mindist./sqrt(2) mindist./sqrt(2)]; else xydiff = [xdiff(i(m),j(m)) ydiff(i(m),j(m))]; diffvec = xydiff.*mindist./xydist(i(m),j(m)) - xydiff; end x(i(m)) = x(i(m)) - diffvec(1)/2; y(i(m)) = y(i(m)) - diffvec(2)/2; x(j(m)) = x(j(m)) + diffvec(1)/2; y(j(m)) = y(j(m)) + diffvec(2)/2; end l = l+1; end xy = [x; y];
github
lcnhappe/happe-master
cache.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@meeg/cache.m
754
utf_8
327310c88f9e84a225af302977c46fe6
function res = cache(this, stuff) % Method for retrieving/putting stuff from/into the temporary cache % FORMAT res = cache(obj, name) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: cache.m 1373 2008-04-11 14:24:03Z spm $ if ischar(stuff) % assume this is a retrieval res = getcache(this, stuff); else % assume this is a put name = inputname(2); res = setcache(this, name, stuff); end function res = getcache(this, stuff) if isfield(this.cache, stuff) eval(['res = this.cache.' stuff ';']); else res = []; end function this = setcache(this, name, stuff) eval(['this.cache(1).' name ' = stuff;']);
github
lcnhappe/happe-master
path.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@meeg/path.m
558
utf_8
7149045fd0a2ac178f0e2dcaf166b5e0
function res = path(this, name) % Method for getting/setting path % FORMAT res = path(this, name) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: path.m 1373 2008-04-11 14:24:03Z spm $ switch nargin case 1 res = getpath(this); case 2 res = setpath(this, name); otherwise end function res = getpath(this) try res = this.path; catch res = ''; end function this = setpath(this, name) this.path = name;
github
lcnhappe/happe-master
fname.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@meeg/fname.m
538
utf_8
00404808a43026efada0ed0cb853d259
function res = fname(this, name) % Method for getting/setting file name % FORMAT res = fname(this, name) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: fname.m 1373 2008-04-11 14:24:03Z spm $ switch nargin case 1 res = getfname(this); case 2 res = setfname(this, name); otherwise end function res = getfname(this) res = this.fname; function this = setfname(this, name) this.fname = name;
github
lcnhappe/happe-master
fnamedat.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@meeg/fnamedat.m
589
utf_8
39857f5d9ecf819f3bc1581bde7009cf
function res = fnamedat(this, name) % Method for getting/setting file name of data file % FORMAT res = fnamedat(this, name) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: fnamedat.m 1373 2008-04-11 14:24:03Z spm $ switch nargin case 1 res = getfnamedat(this); case 2 res = setfnamedat(this, name); otherwise end function res = getfnamedat(this) res = this.data.fnamedat; function this = setfnamedat(this, name) this.data.fnamedat = name;
github
lcnhappe/happe-master
privatepermission.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/privatepermission.m
827
utf_8
be8d85c3b8ab99ec9cf086139103335f
function varargout = permission(varargin) % Format % For getting the value % dat = permission(obj) % % For setting the value % obj = permission(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.permission; return; function obj = asgn(obj,dat) if ischar(dat) tmp = lower(deblank(dat(:)')); switch tmp, case 'ro', case 'rw', otherwise, error('Permission must be either "ro" or "rw"'); end obj.permission = tmp; else error('"permission" must be a character string.'); end; return;
github
lcnhappe/happe-master
privatescl_slope.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/privatescl_slope.m
680
utf_8
4f91ac10412885a1654d520cdaf4c008
function varargout = scl_slope(varargin) % Format % For getting the value % dat = scl_slope(obj) % % For setting the value % obj = scl_slope(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.scl_slope; return; function obj = asgn(obj,dat) if isnumeric(dat), % && numel(dat)<=1, obj.scl_slope = double(dat); else error('"scl_slope" must be numeric.'); end; return;
github
lcnhappe/happe-master
subsasgn.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/subsasgn.m
4,553
utf_8
8649bb5b2b003aef0a04f01504128d47
function obj = subsasgn(obj,subs,dat) % Overloaded subsasgn function for file_array objects. % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if isempty(subs) return; end; if ~strcmp(subs(1).type,'()'), if strcmp(subs(1).type,'.'), %error('Attempt to reference field of non-structure array.'); if numel(struct(obj))~=1, error('Can only change the fields of simple file_array objects.'); end; switch(subs(1).subs) case 'fname', obj = asgn(obj,@fname, subs(2:end),dat); %fname(obj,dat); case 'dtype', obj = asgn(obj,@dtype, subs(2:end),dat); %dtype(obj,dat); case 'offset', obj = asgn(obj,@offset, subs(2:end),dat); %offset(obj,dat); case 'dim', obj = asgn(obj,@dim, subs(2:end),dat); %obj = dim(obj,dat); case 'scl_slope', obj = asgn(obj,@scl_slope, subs(2:end),dat); %scl_slope(obj,dat); case 'scl_inter', obj = asgn(obj,@scl_inter, subs(2:end),dat); %scl_inter(obj,dat); case 'permission', obj = asgn(obj,@permission,subs(2:end),dat); %permission(obj,dat); otherwise, error(['Reference to non-existent field "' subs.subs '".']); end; return; end; if strcmp(subs(1).type,'{}'), error('Cell contents reference from a non-cell array object.'); end; end; if numel(subs)~=1, error('Expression too complicated');end; dm = size(obj); sobj = struct(obj); if length(subs.subs) < length(dm), l = length(subs.subs); dm = [dm(1:(l-1)) prod(dm(l:end))]; if numel(sobj) ~= 1, error('Can only reshape simple file_array objects.'); end; if numel(sobj.scl_slope)>1 || numel(sobj.scl_inter)>1, error('Can not reshape file_array objects with multiple slopes and intercepts.'); end; end; dm = [dm ones(1,16)]; do = ones(1,16); args = {}; for i=1:length(subs.subs), if ischar(subs.subs{i}), if ~strcmp(subs.subs{i},':'), error('This shouldn''t happen....'); end; args{i} = int32(1:dm(i)); else args{i} = int32(subs.subs{i}); end; do(i) = length(args{i}); end; for j=1:length(sobj), if strcmp(sobj(j).permission,'ro'), error('Array is read-only.'); end end if length(sobj)==1 sobj.dim = dm; if numel(dat)~=1, subfun(sobj,double(dat),args{:}); else dat1 = double(dat) + zeros(do); subfun(sobj,dat1,args{:}); end; else for j=1:length(sobj), ps = [sobj(j).pos ones(1,length(args))]; dm = [sobj(j).dim ones(1,length(args))]; siz = ones(1,16); for i=1:length(args), msk = args{i}>=ps(i) & args{i}<(ps(i)+dm(i)); args2{i} = find(msk); args3{i} = int32(double(args{i}(msk))-ps(i)+1); siz(i) = numel(args2{i}); end; if numel(dat)~=1, dat1 = double(subsref(dat,struct('type','()','subs',{args2}))); else dat1 = double(dat) + zeros(siz); end; subfun(sobj(j),dat1,args3{:}); end end return function sobj = subfun(sobj,dat,varargin) va = varargin; dt = datatypes; ind = find(cat(1,dt.code)==sobj.dtype); if isempty(ind), error('Unknown datatype'); end; if dt(ind).isint, dat(~isfinite(dat)) = 0; end; if ~isempty(sobj.scl_inter), inter = sobj.scl_inter; if numel(inter)>1, inter = resize_scales(inter,sobj.dim,varargin); end; dat = double(dat) - inter; end; if ~isempty(sobj.scl_slope), slope = sobj.scl_slope; if numel(slope)>1, slope = resize_scales(slope,sobj.dim,varargin); dat = double(dat)./slope; else dat = double(dat)/slope; end; end; if dt(ind).isint, dat = round(dat); end; % Avoid warning messages in R14 SP3 wrn = warning; warning('off'); dat = feval(dt(ind).conv,dat); warning(wrn); nelem = dt(ind).nelem; if nelem==1, mat2file(sobj,dat,va{:}); elseif nelem==2, sobj1 = sobj; sobj1.dim = [2 sobj.dim]; sobj1.dtype = dt(find(strcmp(dt(ind).prec,{dt.prec}) & (cat(2,dt.nelem)==1))).code; dat = reshape(dat,[1 size(dat)]); dat = [real(dat) ; imag(dat)]; mat2file(sobj1,dat,int32([1 2]),va{:}); else error('Inappropriate number of elements per voxel.'); end; return function obj = asgn(obj,fun,subs,dat) if ~isempty(subs), tmp = feval(fun,obj); tmp = subsasgn(tmp,subs,dat); obj = feval(fun,obj,tmp); else obj = feval(fun,obj,dat); end;
github
lcnhappe/happe-master
privatedim.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/privatedim.m
762
utf_8
0ad58f05456fccb279755b25289027c4
function varargout = dim(varargin) % Format % For getting the value % dat = dim(obj) % % For setting the value % obj = dim(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.dim; return; function obj = asgn(obj,dat) if isnumeric(dat) && all(dat>=0) && all(rem(dat,1)==0), dat = [double(dat(:)') 1 1]; lim = max([2 find(dat~=1)]); dat = dat(1:lim); obj.dim = dat; else error('"dim" must be a vector of positive integers.'); end; return;
github
lcnhappe/happe-master
privatescl_inter.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/privatescl_inter.m
681
utf_8
341f747372c0465de4be134d3595e133
function varargout = scl_inter(varargin) % Format % For getting the value % dat = scl_inter(obj) % % For setting the value % obj = scl_inter(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.scl_inter; return; function obj = asgn(obj,dat) if isnumeric(dat), % && numel(dat)<=1, obj.scl_inter = double(dat); else error('"scl_inter" must be numeric.'); end; return;
github
lcnhappe/happe-master
privatefname.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/privatefname.m
648
utf_8
87ba48423085238dda8deb873c3a5a24
function varargout = fname(varargin) % Format % For getting the value % dat = fname(obj) % % For setting the value % obj = fname(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.fname; return; function obj = asgn(obj,dat) if ischar(dat) obj.fname = deblank(dat(:)'); else error('"fname" must be a character string.'); end; return;
github
lcnhappe/happe-master
privateoffset.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/privateoffset.m
697
utf_8
5b5493cb277651ae207a6e094e50f16f
function varargout = offset(varargin) % Format % For getting the value % dat = offset(obj) % % For setting the value % obj = offset(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.offset; return; function obj = asgn(obj,dat) if isnumeric(dat) && numel(dat)==1 && dat>=0 && rem(dat,1)==0, obj.offset = double(dat); else error('"offset" must be a positive integer.'); end; return;
github
lcnhappe/happe-master
privatedtype.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/privatedtype.m
2,225
utf_8
4e4a2cfe6a4a9d295f1b9f3eb3fd3eb1
function varargout = dtype(varargin) % Format % For getting the value % dat = dtype(obj) % % For setting the value % obj = dtype(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wring number of arguments.'); end; return; function t = ref(obj) d = datatypes; mch = find(cat(1,d.code)==obj.dtype); if isempty(mch), t = 'UNKNOWN'; else t = d(mch).label; end; if obj.be, t = [t '-BE']; else t = [t '-LE']; end; return; function obj = asgn(obj,dat) d = datatypes; if isnumeric(dat) if numel(dat)>=1, mch = find(cat(1,d.code)==dat(1)); if isempty(mch) || mch==0, fprintf('Invalid datatype (%d).', dat(1)); disp('First part of datatype should be of one of the following'); disp(sortrows([num2str(cat(1,d.code)) ... repmat(' ',numel(d),2) strvcat(d.label)])); %error(['Invalid datatype (' num2str(dat(1)) ').']); return; end; obj.dtype = double(dat(1)); end; if numel(dat)>=2, obj.be = double(dat(2)~=0); end; if numel(dat)>2, error('Too many elements in numeric datatype.'); end; elseif ischar(dat), dat1 = lower(dat); sep = find(dat1=='-' | dat1=='/'); sep = sep(sep~=1); if ~isempty(sep), c1 = dat1(1:(sep(1)-1)); c2 = dat1((sep(1)+1):end); else c1 = dat1; c2 = ''; end; mch = find(strcmpi(c1,lower({d.label}))); if isempty(mch), disp('First part of datatype should be of one of the following'); disp(sortrows([num2str(cat(1,d.code)) ... repmat(' ',numel(d),2) strvcat(d.label)])); %error(['Invalid datatype (' c1 ').']); return; else obj.dtype = double(d(mch(1)).code); end; if any(c2=='b'), if any(c2=='l'), error('Cannot be both big and little endian.'); end; obj.be = 1; elseif any(c2=='l'), obj.be = 0; end; else error('Invalid datatype.'); end; return;
github
lcnhappe/happe-master
subsref.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/subsref.m
5,222
utf_8
80f9298dd645012f0fe42fcb32d6beef
function varargout=subsref(obj,subs) % SUBSREF Subscripted reference % An overloaded function... %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if isempty(subs), return; end switch subs(1).type case '{}' error('Cell contents reference from a non-cell array object.'); case '.' varargout = access_fields(obj,subs); return; end if numel(subs)~=1, error('Expression too complicated'); end; dim = [size(obj) ones(1,16)]; nd = find(dim>1,1,'last')-1; sobj = struct(obj); if ~numel(subs.subs) [subs.subs{1:nd+1}] = deal(':'); elseif length(subs.subs) < nd l = length(subs.subs); dim = [dim(1:(l-1)) prod(dim(l:end))]; if numel(sobj) ~= 1 error('Can only reshape simple file_array objects.'); else if numel(sobj.scl_slope)>1 || numel(sobj.scl_inter)>1 error('Can not reshape file_array objects with multiple slopes and intercepts.'); end sobj.dim = dim; end end do = ones(16,1); args = cell(1,length(subs.subs)); for i=1:length(subs.subs) if ischar(subs.subs{i}) if ~strcmp(subs.subs{i},':'), error('This shouldn''t happen....'); end if length(subs.subs) == 1 args{i} = 1:prod(dim); % possible overflow when int32() k = 0; for j=1:length(sobj) sobj(j).dim = [prod(sobj(j).dim) 1]; sobj(j).pos = [k+1 1]; k = k + sobj(j).dim(1); end else args{i} = 1:dim(i); end else args{i} = subs.subs{i}; end do(i) = length(args{i}); end if length(sobj)==1 t = subfun(sobj,args{:}); else dt = datatypes; dt = dt([dt.code]==sobj(1).dtype); % assuming identical datatypes t = zeros(do',func2str(dt.conv)); for j=1:length(sobj) ps = [sobj(j).pos ones(1,length(args))]; dm = [sobj(j).dim ones(1,length(args))]; for i=1:length(args) msk = find(args{i}>=ps(i) & args{i}<(ps(i)+dm(i))); args2{i} = msk; args3{i} = double(args{i}(msk))-ps(i)+1; end t = subsasgn(t,struct('type','()','subs',{args2}),subfun(sobj(j),args3{:})); end end varargout = {t}; %========================================================================== % function t = subfun(sobj,varargin) %========================================================================== function t = subfun(sobj,varargin) %sobj.dim = [sobj.dim ones(1,16)]; try args = cell(size(varargin)); for i=1:length(varargin) args{i} = int32(varargin{i}); end t = file2mat(sobj,args{:}); catch t = multifile2mat(sobj,varargin{:}); end if ~isempty(sobj.scl_slope) || ~isempty(sobj.scl_inter) slope = 1; inter = 0; if ~isempty(sobj.scl_slope), slope = sobj.scl_slope; end if ~isempty(sobj.scl_inter), inter = sobj.scl_inter; end if numel(slope)>1 slope = resize_scales(slope,sobj.dim,varargin); t = double(t).*slope; else t = double(t)*slope; end if numel(inter)>1 inter = resize_scales(inter,sobj.dim,varargin); end; t = t + inter; end %========================================================================== % function c = access_fields(obj,subs) %========================================================================== function c = access_fields(obj,subs) sobj = struct(obj); c = cell(1,numel(sobj)); for i=1:numel(sobj) %obj = class(sobj(i),'file_array'); obj = sobj(i); switch(subs(1).subs) case 'fname', t = fname(obj); case 'dtype', t = dtype(obj); case 'offset', t = offset(obj); case 'dim', t = dim(obj); case 'scl_slope', t = scl_slope(obj); case 'scl_inter', t = scl_inter(obj); case 'permission', t = permission(obj); otherwise error(['Reference to non-existent field "' subs(1).subs '".']); end if numel(subs)>1 t = subsref(t,subs(2:end)); end c{i} = t; end %========================================================================== % function val = multifile2mat(sobj,varargin) %========================================================================== function val = multifile2mat(sobj,varargin) % Convert subscripts into linear index [indx2{1:length(varargin)}] = ndgrid(varargin{:},1); ind = sub2ind(sobj.dim,indx2{:}); % Work out the partition dt = datatypes; dt = dt([dt.code]==sobj.dtype); sz = dt.size; mem = spm('memory'); % in bytes, has to be a multiple of 16 (max([dt.size])) s = ceil(prod(sobj.dim) * sz / mem); % Assign indices to partitions [x,y] = ind2sub([mem/sz s],ind(:)); c = histc(y,1:s); cc = [0 reshape(cumsum(c),1,[])]; % Read data in relevant partitions obj = sobj; val = zeros(length(x),1,func2str(dt.conv)); for i=reshape(find(c),1,[]) obj.offset = sobj.offset + mem*(i-1); obj.dim = [1 min(mem/sz, prod(sobj.dim)-(i-1)*mem/sz)]; val(cc(i)+1:cc(i+1)) = file2mat(obj,int32(1),int32(x(y==i))); end r = cellfun('length',varargin); if numel(r) == 1, r = [r 1]; end val = reshape(val,r);
github
lcnhappe/happe-master
disp.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/disp.m
887
utf_8
64720ef6ff6e10ebb67d01f5d3a04f7f
function disp(obj) % Display a file_array object % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if numel(struct(obj))>1, fprintf(' %s object: ', class(obj)); sz = size(obj); if length(sz)>4, fprintf('%d-D\n',length(sz)); else for i=1:(length(sz)-1), fprintf('%d-by-',sz(i)); end; fprintf('%d\n',sz(end)); end; else display(mystruct(obj)) end; return; %======================================================================= %======================================================================= function t = mystruct(obj) fn = fieldnames(obj); for i=1:length(fn) t.(fn{i}) = subsref(obj,struct('type','.','subs',fn{i})); end; return; %=======================================================================
github
lcnhappe/happe-master
offset.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/offset.m
697
utf_8
5b5493cb277651ae207a6e094e50f16f
function varargout = offset(varargin) % Format % For getting the value % dat = offset(obj) % % For setting the value % obj = offset(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.offset; return; function obj = asgn(obj,dat) if isnumeric(dat) && numel(dat)==1 && dat>=0 && rem(dat,1)==0, obj.offset = double(dat); else error('"offset" must be a positive integer.'); end; return;
github
lcnhappe/happe-master
scl_slope.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/scl_slope.m
680
utf_8
4f91ac10412885a1654d520cdaf4c008
function varargout = scl_slope(varargin) % Format % For getting the value % dat = scl_slope(obj) % % For setting the value % obj = scl_slope(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.scl_slope; return; function obj = asgn(obj,dat) if isnumeric(dat), % && numel(dat)<=1, obj.scl_slope = double(dat); else error('"scl_slope" must be numeric.'); end; return;
github
lcnhappe/happe-master
scl_inter.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/scl_inter.m
681
utf_8
341f747372c0465de4be134d3595e133
function varargout = scl_inter(varargin) % Format % For getting the value % dat = scl_inter(obj) % % For setting the value % obj = scl_inter(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.scl_inter; return; function obj = asgn(obj,dat) if isnumeric(dat), % && numel(dat)<=1, obj.scl_inter = double(dat); else error('"scl_inter" must be numeric.'); end; return;
github
lcnhappe/happe-master
fname.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/fname.m
648
utf_8
87ba48423085238dda8deb873c3a5a24
function varargout = fname(varargin) % Format % For getting the value % dat = fname(obj) % % For setting the value % obj = fname(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.fname; return; function obj = asgn(obj,dat) if ischar(dat) obj.fname = deblank(dat(:)'); else error('"fname" must be a character string.'); end; return;
github
lcnhappe/happe-master
dim.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/dim.m
762
utf_8
0ad58f05456fccb279755b25289027c4
function varargout = dim(varargin) % Format % For getting the value % dat = dim(obj) % % For setting the value % obj = dim(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.dim; return; function obj = asgn(obj,dat) if isnumeric(dat) && all(dat>=0) && all(rem(dat,1)==0), dat = [double(dat(:)') 1 1]; lim = max([2 find(dat~=1)]); dat = dat(1:lim); obj.dim = dat; else error('"dim" must be a vector of positive integers.'); end; return;
github
lcnhappe/happe-master
permission.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/permission.m
827
utf_8
be8d85c3b8ab99ec9cf086139103335f
function varargout = permission(varargin) % Format % For getting the value % dat = permission(obj) % % For setting the value % obj = permission(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.permission; return; function obj = asgn(obj,dat) if ischar(dat) tmp = lower(deblank(dat(:)')); switch tmp, case 'ro', case 'rw', otherwise, error('Permission must be either "ro" or "rw"'); end obj.permission = tmp; else error('"permission" must be a character string.'); end; return;
github
lcnhappe/happe-master
dtype.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/dtype.m
2,225
utf_8
4e4a2cfe6a4a9d295f1b9f3eb3fd3eb1
function varargout = dtype(varargin) % Format % For getting the value % dat = dtype(obj) % % For setting the value % obj = dtype(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wring number of arguments.'); end; return; function t = ref(obj) d = datatypes; mch = find(cat(1,d.code)==obj.dtype); if isempty(mch), t = 'UNKNOWN'; else t = d(mch).label; end; if obj.be, t = [t '-BE']; else t = [t '-LE']; end; return; function obj = asgn(obj,dat) d = datatypes; if isnumeric(dat) if numel(dat)>=1, mch = find(cat(1,d.code)==dat(1)); if isempty(mch) || mch==0, fprintf('Invalid datatype (%d).', dat(1)); disp('First part of datatype should be of one of the following'); disp(sortrows([num2str(cat(1,d.code)) ... repmat(' ',numel(d),2) strvcat(d.label)])); %error(['Invalid datatype (' num2str(dat(1)) ').']); return; end; obj.dtype = double(dat(1)); end; if numel(dat)>=2, obj.be = double(dat(2)~=0); end; if numel(dat)>2, error('Too many elements in numeric datatype.'); end; elseif ischar(dat), dat1 = lower(dat); sep = find(dat1=='-' | dat1=='/'); sep = sep(sep~=1); if ~isempty(sep), c1 = dat1(1:(sep(1)-1)); c2 = dat1((sep(1)+1):end); else c1 = dat1; c2 = ''; end; mch = find(strcmpi(c1,lower({d.label}))); if isempty(mch), disp('First part of datatype should be of one of the following'); disp(sortrows([num2str(cat(1,d.code)) ... repmat(' ',numel(d),2) strvcat(d.label)])); %error(['Invalid datatype (' c1 ').']); return; else obj.dtype = double(d(mch(1)).code); end; if any(c2=='b'), if any(c2=='l'), error('Cannot be both big and little endian.'); end; obj.be = 1; elseif any(c2=='l'), obj.be = 0; end; else error('Invalid datatype.'); end; return;
github
lcnhappe/happe-master
subsasgn.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@nifti/subsasgn.m
14,522
utf_8
86db451a023fd9a4a9252278adcab3ab
function obj = subsasgn(obj,subs,varargin) % Subscript assignment % See subsref for meaning of fields. % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ switch subs(1).type, case {'.'}, if numel(obj)~=nargin-2, error('The number of outputs should match the number of inputs.'); end; objs = struct(obj); for i=1:length(varargin), val = varargin{i}; obji = class(objs(i),'nifti'); obji = fun(obji,subs,val); objs(i) = struct(obji); end; obj = class(objs,'nifti'); case {'()'}, objs = struct(obj); if length(subs)>1, t = subsref(objs,subs(1)); % A lot of this stuff is a little flakey, and may cause Matlab to bomb. % %if numel(t) ~= nargin-2, % error('The number of outputs should match the number of inputs.'); %end; for i=1:numel(t), val = varargin{1}; obji = class(t(i),'nifti'); obji = subsasgn(obji,subs(2:end),val); t(i) = struct(obji); end; objs = subsasgn(objs,subs(1),t); else if numel(varargin)>1, error('Illegal right hand side in assignment. Too many elements.'); end; val = varargin{1}; if isa(val,'nifti'), objs = subsasgn(objs,subs,struct(val)); elseif isempty(val), objs = subsasgn(objs,subs,[]); else error('Assignment between unlike types is not allowed.'); end; end; obj = class(objs,'nifti'); otherwise error('Cell contents reference from a non-cell array object.'); end; return; %======================================================================= %======================================================================= function obj = fun(obj,subs,val) % Subscript referencing switch subs(1).type, case {'.'}, objs = struct(obj); for ii=1:numel(objs) obj = objs(ii); if any(strcmpi(subs(1).subs,{'dat'})), if length(subs)>1, val = subsasgn(obj.dat,subs(2:end),val); end; obj = assigndat(obj,val); objs(ii) = obj; continue; end; if isempty(obj.hdr), obj.hdr = empty_hdr; end; if ~isfield(obj.hdr,'magic'), error('Not a NIFTI-1 header'); end; if length(subs)>1, % && ~strcmpi(subs(1).subs,{'raw','dat'}), val0 = subsref(class(obj,'nifti'),subs(1)); val1 = subsasgn(val0,subs(2:end),val); else val1 = val; end; switch(subs(1).subs) case {'extras'} if length(subs)>1, obj.extras = subsasgn(obj.extras,subs(2:end),val); else obj.extras = val; end; case {'mat0'} if ~isnumeric(val1) || ndims(val1)~=2 || any(size(val1)~=[4 4]) || sum((val1(4,:)-[0 0 0 1]).^2)>1e-8, error('"mat0" should be a 4x4 matrix, with a last row of 0,0,0,1.'); end; if obj.hdr.qform_code==0, obj.hdr.qform_code=2; end; s = double(bitand(obj.hdr.xyzt_units,7)); if s d = findindict(s,'units'); val1 = diag([[1 1 1]/d.rescale 1])*val1; end; obj.hdr = encode_qform0(double(val1), obj.hdr); case {'mat0_intent'} if isempty(val1), obj.hdr.qform_code = 0; else if ~ischar(val1) && ~(isnumeric(val1) && numel(val1)==1), error('"mat0_intent" should be a string or a scalar.'); end; d = findindict(val1,'xform'); if ~isempty(d) obj.hdr.qform_code = d.code; end; end; case {'mat'} if ~isnumeric(val1) || ndims(val1)~=2 || any(size(val1)~=[4 4]) || sum((val1(4,:)-[0 0 0 1]).^2)>1e-8 error('"mat" should be a 4x4 matrix, with a last row of 0,0,0,1.'); end; if obj.hdr.sform_code==0, obj.hdr.sform_code=2; end; s = double(bitand(obj.hdr.xyzt_units,7)); if s d = findindict(s,'units'); val1 = diag([[1 1 1]/d.rescale 1])*val1; end; val1 = val1 * [eye(4,3) [1 1 1 1]']; obj.hdr.srow_x = val1(1,:); obj.hdr.srow_y = val1(2,:); obj.hdr.srow_z = val1(3,:); case {'mat_intent'} if isempty(val1), obj.hdr.sform_code = 0; else if ~ischar(val1) && ~(isnumeric(val1) && numel(val1)==1), error('"mat_intent" should be a string or a scalar.'); end; d = findindict(val1,'xform'); if ~isempty(d), obj.hdr.sform_code = d.code; end; end; case {'intent'} if ~valid_fields(val1,{'code','param','name'}) obj.hdr.intent_code = 0; obj.hdr.intent_p1 = 0; obj.hdr.intent_p2 = 0; obj.hdr.intent_p3 = 0; obj.hdr.intent_name = ''; else if ~isfield(val1,'code'), val1.code = obj.hdr.intent_code; end; d = findindict(val1.code,'intent'); if ~isempty(d), obj.hdr.intent_code = d.code; if isfield(val1,'param'), prm = [double(val1.param(:)) ; 0 ; 0; 0]; prm = [prm(1:length(d.param)) ; 0 ; 0; 0]; obj.hdr.intent_p1 = prm(1); obj.hdr.intent_p2 = prm(2); obj.hdr.intent_p3 = prm(3); end; if isfield(val1,'name'), obj.hdr.intent_name = val1.name; end; end; end; case {'diminfo'} if ~valid_fields(val1,{'frequency','phase','slice','slice_time'}) tmp = obj.hdr.dim_info; for bit=1:6, tmp = bitset(tmp,bit,0); end; obj.hdr.dim_info = tmp; obj.hdr.slice_start = 0; obj.hdr.slice_end = 0; obj.hdr.slice_duration = 0; obj.hdr.slice_code = 0; else if isfield(val1,'frequency'), tmp = val1.frequency; if ~isnumeric(tmp) || numel(tmp)~=1 || tmp<0 || tmp>3, error('Invalid frequency direction'); end; obj.hdr.dim_info = bitset(obj.hdr.dim_info,1,bitget(tmp,1)); obj.hdr.dim_info = bitset(obj.hdr.dim_info,2,bitget(tmp,2)); end; if isfield(val1,'phase'), tmp = val1.phase; if ~isnumeric(tmp) || numel(tmp)~=1 || tmp<0 || tmp>3, error('Invalid phase direction'); end; obj.hdr.dim_info = bitset(obj.hdr.dim_info,3,bitget(tmp,1)); obj.hdr.dim_info = bitset(obj.hdr.dim_info,4,bitget(tmp,2)); end; if isfield(val1,'slice'), tmp = val1.slice; if ~isnumeric(tmp) || numel(tmp)~=1 || tmp<0 || tmp>3, error('Invalid slice direction'); end; obj.hdr.dim_info = bitset(obj.hdr.dim_info,5,bitget(tmp,1)); obj.hdr.dim_info = bitset(obj.hdr.dim_info,6,bitget(tmp,2)); end; if isfield(val1,'slice_time') tim = val1.slice_time; if ~valid_fields(tim,{'start','end','duration','code'}), obj.hdr.slice_code = 0; obj.hdr.slice_start = 0; obj.hdr.end_slice = 0; obj.hdr.slice_duration = 0; else % sld = double(bitget(obj.hdr.dim_info,5)) + 2*double(bitget(obj.hdr.dim_info,6)); if isfield(tim,'start'), ss = double(tim.start); if isnumeric(ss) && numel(ss)==1 && ~rem(ss,1), % && ss>=1 && ss<=obj.hdr.dim(sld+1) obj.hdr.slice_start = ss-1; else error('Inappropriate "slice_time.start".'); end; end; if isfield(tim,'end'), ss = double(tim.end); if isnumeric(ss) && numel(ss)==1 && ~rem(ss,1), % && ss>=1 && ss<=obj.hdr.dim(sld+1) obj.hdr.slice_end = ss-1; else error('Inappropriate "slice_time.end".'); end; end; if isfield(tim,'duration') sd = double(tim.duration); if isnumeric(sd) && numel(sd)==1, s = double(bitand(obj.hdr.xyzt_units,24)); d = findindict(s,'units'); if ~isempty(d) && d.rescale, sd = sd/d.rescale; end; obj.hdr.slice_duration = sd; else error('Inappropriate "slice_time.duration".'); end; end; if isfield(tim,'code'), d = findindict(tim.code,'sliceorder'); if ~isempty(d), obj.hdr.slice_code = d.code; end; end; end; end; end; case {'timing'} if ~valid_fields(val1,{'toffset','tspace'}), obj.hdr.pixdim(5) = 0; obj.hdr.toffset = 0; else s = double(bitand(obj.hdr.xyzt_units,24)); d = findindict(s,'units'); if isfield(val1,'toffset'), if isnumeric(val1.toffset) && numel(val1.toffset)==1, if d.rescale, val1.toffset = val1.toffset/d.rescale; end; obj.hdr.toffset = val1.toffset; else error('"timing.toffset" needs to be numeric with 1 element'); end; end; if isfield(val1,'tspace'), if isnumeric(val1.tspace) && numel(val1.tspace)==1, if d.rescale, val1.tspace = val1.tspace/d.rescale; end; obj.hdr.pixdim(5) = val1.tspace; else error('"timing.tspace" needs to be numeric with 1 element'); end; end; end; case {'descrip'} if isempty(val1), val1 = char(val1); end; if ischar(val1), obj.hdr.descrip = val1; else error('"descrip" must be a string.'); end; case {'cal'} if isempty(val1), obj.hdr.cal_min = 0; obj.hdr.cal_max = 0; else if isnumeric(val1) && numel(val1)==2, obj.hdr.cal_min = val1(1); obj.hdr.cal_max = val1(2); else error('"cal" should contain two elements.'); end; end; case {'aux_file'} if isempty(val1), val1 = char(val1); end; if ischar(val1), obj.hdr.aux_file = val1; else error('"aux_file" must be a string.'); end; case {'hdr'} error('hdr is a read-only field.'); obj.hdr = val1; otherwise error(['Reference to non-existent field ''' subs(1).subs '''.']); end; objs(ii) = obj; end obj = class(objs,'nifti'); otherwise error('This should not happen.'); end; return; %======================================================================= %======================================================================= function obj = assigndat(obj,val) if isa(val,'file_array'), sz = size(val); if numel(sz)>8, error('Too many dimensions in data.'); end; sz = [sz 1 1 1 1 1 1 1 1]; sz = sz(1:8); sval = struct(val); d = findindict(sval.dtype,'dtype'); if isempty(d) error(['Unknown datatype (' num2str(double(sval.datatype)) ').']); end; [pth,nam,suf] = fileparts(sval.fname); if any(strcmp(suf,{'.img','.IMG'})) val.offset = max(sval.offset,0); obj.hdr.magic = 'ni1'; elseif any(strcmp(suf,{'.nii','.NII'})) val.offset = max(sval.offset,352); obj.hdr.magic = 'n+1'; else error(['Unknown filename extension (' suf ').']); end; val.offset = (ceil(val.offset/16))*16; obj.hdr.vox_offset = val.offset; obj.hdr.dim(2:(numel(sz)+1)) = sz; nd = max(find(obj.hdr.dim(2:end)>1)); if isempty(nd), nd = 3; end; obj.hdr.dim(1) = nd; obj.hdr.datatype = sval.dtype; obj.hdr.bitpix = d.size*8; if ~isempty(sval.scl_slope), obj.hdr.scl_slope = sval.scl_slope; end; if ~isempty(sval.scl_inter), obj.hdr.scl_inter = sval.scl_inter; end; obj.dat = val; else error('"raw" must be of class "file_array"'); end; return; function ok = valid_fields(val,allowed) if isempty(val), ok = false; return; end; if ~isstruct(val), error(['Expecting a structure, not a ' class(val) '.']); end; fn = fieldnames(val); for ii=1:length(fn), if ~any(strcmpi(fn{ii},allowed)), fprintf('Allowed fieldnames are:\n'); for i=1:length(allowed), fprintf(' %s\n', allowed{i}); end; error(['"' fn{ii} '" is not a valid fieldname.']); end end ok = true; return;
github
lcnhappe/happe-master
subsref.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@nifti/subsref.m
8,717
utf_8
3e5580b77072a8d2a98deb98231f6bab
function varargout = subsref(opt,subs) % Subscript referencing % % Fields are: % dat - a file-array representing the image data % mat0 - a 9-parameter affine transform (from qform0) % Note that the mapping is from voxels (where the first % is considered to be at [1,1,1], to millimetres. See % mat0_interp for the meaning of the transform. % mat - a 12-parameter affine transform (from sform0) % Note that the mapping is from voxels (where the first % is considered to be at [1,1,1], to millimetres. See % mat1_interp for the meaning of the transform. % mat_intent - intention of mat. This field may be missing/empty. % mat0_intent - intention of mat0. This field may be missing/empty. % intent - interpretation of image. When present, this structure % contains the fields % code - name of interpretation % params - parameters needed to interpret the image % diminfo - MR encoding of different dimensions. This structure may % contain some or all of the following fields % frequency - a value of 1-3 indicating frequency direction % phase - a value of 1-3 indicating phase direction % slice - a value of 1-3 indicating slice direction % slice_time - only present when "slice" field is present. % Contains the following fields % code - ascending/descending etc % start - starting slice number % end - ending slice number % duration - duration of each slice acquisition % Setting frequency, phase or slice to 0 will remove it. % timing - timing information. When present, contains the fields % toffset - acquisition time of first volume (seconds) % tspace - time between sucessive volumes (seconds) % descrip - a brief description of the image % cal - a two-element vector containing cal_min and cal_max % aux_file - name of an auxiliary file % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ varargout = rec(opt,subs); return; function c = rec(opt,subs) switch subs(1).type, case {'.'}, c = {}; opts = struct(opt); for ii=1:numel(opts) opt = class(opts(ii),'nifti'); %if ~isstruct(opt) % error('Attempt to reference field of non-structure array.'); %end; h = opt.hdr; if isempty(h), %error('No header.'); h = empty_hdr; end; % NIFTI-1 FORMAT switch(subs(1).subs) case 'extras', t = opt.extras; case 'raw', % A hidden field if isa(opt.dat,'file_array'), tmp = struct(opt.dat); tmp.scl_slope = []; tmp.scl_inter = []; t = file_array(tmp); else t = opt.dat; end; case 'dat', t = opt.dat; case 'mat0', t = decode_qform0(h); s = double(bitand(h.xyzt_units,7)); if s d = findindict(s,'units'); if ~isempty(d) t = diag([d.rescale*[1 1 1] 1])*t; end; end; case 'mat0_intent', d = findindict(h.qform_code,'xform'); if isempty(d) || d.code==0, t = ''; else t = d.label; end; case 'mat', if h.sform_code > 0 t = double([h.srow_x ; h.srow_y ; h.srow_z ; 0 0 0 1]); t = t * [eye(4,3) [-1 -1 -1 1]']; else t = decode_qform0(h); end s = double(bitand(h.xyzt_units,7)); if s d = findindict(s,'units'); t = diag([d.rescale*[1 1 1] 1])*t; end; case 'mat_intent', if h.sform_code>0, t = h.sform_code; else t = h.qform_code; end; d = findindict(t,'xform'); if isempty(d) || d.code==0, t = ''; else t = d.label; end; case 'intent', d = findindict(h.intent_code,'intent'); if isempty(d) || d.code == 0, %t = struct('code','UNKNOWN','param',[]); t = []; else t = struct('code',d.label,'param',... double([h.intent_p1 h.intent_p2 h.intent_p3]), 'name',deblank(h.intent_name)); t.param = t.param(1:length(d.param)); end case 'diminfo', t = []; tmp = bitand( h.dim_info ,3); if tmp, t.frequency = double(tmp); end; tmp = bitand(bitshift(h.dim_info,-2),3); if tmp, t.phase = double(tmp); end; tmp = bitand(bitshift(h.dim_info,-4),3); if tmp, t.slice = double(tmp); end; % t = struct('frequency',bitand( h.dim_info ,3),... % 'phase',bitand(bitshift(h.dim_info,-2),3),... % 'slice',bitand(bitshift(h.dim_info,-4),3)) if isfield(t,'slice') sc = double(h.slice_code); ss = double(h.slice_start)+1; se = double(h.slice_end)+1; ss = max(ss,1); se = min(se,double(h.dim(t.slice+1))); sd = double(h.slice_duration); s = double(bitand(h.xyzt_units,24)); d = findindict(s,'units'); if d.rescale, sd = sd*d.rescale; end; ns = (se-ss+1); d = findindict(sc,'sliceorder'); if isempty(d) label = 'UNKNOWN'; else label = d.label; end; t.slice_time = struct('code',label,'start',ss,'end',se,'duration',sd); if 0, % Never t.times = zeros(1,double(h.dim(t.slice+1)))+NaN; switch sc, case 0, % Unknown t.times(ss:se) = zeros(1,ns); case 1, % sequential increasing t.times(ss:se) = (0:(ns-1))*sd; case 2, % sequential decreasing t.times(ss:se) = ((ns-1):-1:0)*sd; case 3, % alternating increasing t.times(ss:2:se) = (0:floor((ns+1)/2-1))*sd; t.times((ss+1):2:se) = (floor((ns+1)/2):(ns-1))*sd; case 4, % alternating decreasing t.times(se:-2:ss) = (0:floor((ns+1)/2-1))*sd; t.times(se:-2:(ss+1)) = (floor((ns+1)/2):(ns-1))*sd; end; end; end; case 'timing', to = double(h.toffset); dt = double(h.pixdim(5)); if to==0 && dt==0, t = []; else s = double(bitand(h.xyzt_units,24)); d = findindict(s,'units'); if d.rescale, to = to*d.rescale; dt = dt*d.rescale; end; t = struct('toffset',to,'tspace',dt); end; case 'descrip', t = deblank(h.descrip); msk = find(t==0); if any(msk), t=t(1:(msk(1)-1)); end; case 'cal', t = [double(h.cal_min) double(h.cal_max)]; if all(t==0), t = []; end; case 'aux_file', t = deblank(h.aux_file); case 'hdr', % Hidden field t = h; otherwise error(['Reference to non-existent field ''' subs(1).subs '''.']); end; if numel(subs)>1, t = subsref(t,subs(2:end)); end; c{ii} = t; end; case {'{}'}, error('Cell contents reference from a non-cell array object.'); case {'()'}, opt = struct(opt); t = subsref(opt,subs(1)); if length(subs)>1 c = {}; for i=1:numel(t), ti = class(t(i),'nifti'); ti = rec(ti,subs(2:end)); c = {c{:}, ti{:}}; end; else c = {class(t,'nifti')}; end; otherwise error('This should not happen.'); end;
github
lcnhappe/happe-master
create.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@nifti/create.m
1,922
utf_8
3d0a267602ecbe433be656c175acb2a2
function create(obj,wrt) % Create a NIFTI-1 file % FORMAT create(obj) % This writes out the header information for the nifti object % % create(obj,wrt) % This also writes out an empty image volume if wrt==1 % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ for i=1:numel(obj) create_each(obj(i)); end; function create_each(obj) if ~isa(obj.dat,'file_array'), error('Data must be a file-array'); end; fname = obj.dat.fname; if isempty(fname), error('No filename to write to.'); end; dt = obj.dat.dtype; ok = write_hdr_raw(fname,obj.hdr,dt(end-1)=='B'); if ~ok, error(['Unable to write header for "' fname '".']); end; write_extras(fname,obj.extras); if nargin>2 && any(wrt==1), % Create an empty image file if necessary d = findindict(obj.hdr.datatype, 'dtype'); dim = double(obj.hdr.dim(2:end)); dim((double(obj.hdr.dim(1))+1):end) = 1; nbytes = ceil(d.size*d.nelem*prod(dim(1:2)))*prod(dim(3:end))+double(obj.hdr.vox_offset); [pth,nam,ext] = fileparts(obj.dat.fname); if any(strcmp(deblank(obj.hdr.magic),{'n+1','nx1'})), ext = '.nii'; else ext = '.img'; end; iname = fullfile(pth,[nam ext]); fp = fopen(iname,'a+'); if fp==-1, error(['Unable to create image for "' fname '".']); end; fseek(fp,0,'eof'); pos = ftell(fp); if pos<nbytes, bs = 2048; % Buffer-size nbytes = nbytes - pos; buf = uint8(0); buf(bs) = 0; while(nbytes>0) if nbytes<bs, buf = buf(1:nbytes); end; nw = fwrite(fp,buf,'uint8'); if nw<min(bs,nbytes), fclose(fp); error(['Problem while creating image for "' fname '".']); end; nbytes = nbytes - nw; end; end; fclose(fp); end; return;
github
lcnhappe/happe-master
getdict.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@nifti/private/getdict.m
5,184
utf_8
eebe7d552eb3613897e82d860005c90e
function d = getdict % Dictionary of NIFTI stuff % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ persistent dict; if ~isempty(dict), d = dict; return; end; % Datatype t = true; f = false; table = {... 0 ,'UNKNOWN' ,'uint8' ,@uint8 ,1,1 ,t,t,f 1 ,'BINARY' ,'uint1' ,@logical,1,1/8,t,t,f 256 ,'INT8' ,'int8' ,@int8 ,1,1 ,t,f,t 2 ,'UINT8' ,'uint8' ,@uint8 ,1,1 ,t,t,t 4 ,'INT16' ,'int16' ,@int16 ,1,2 ,t,f,t 512 ,'UINT16' ,'uint16' ,@uint16 ,1,2 ,t,t,t 8 ,'INT32' ,'int32' ,@int32 ,1,4 ,t,f,t 768 ,'UINT32' ,'uint32' ,@uint32 ,1,4 ,t,t,t 1024,'INT64' ,'int64' ,@int64 ,1,8 ,t,f,f 1280,'UINT64' ,'uint64' ,@uint64 ,1,8 ,t,t,f 16 ,'FLOAT32' ,'float32' ,@single ,1,4 ,f,f,t 64 ,'FLOAT64' ,'double' ,@double ,1,8 ,f,f,t 1536,'FLOAT128' ,'float128',@crash ,1,16 ,f,f,f 32 ,'COMPLEX64' ,'float32' ,@single ,2,4 ,f,f,f 1792,'COMPLEX128','double' ,@double ,2,8 ,f,f,f 2048,'COMPLEX256','float128',@crash ,2,16 ,f,f,f 128 ,'RGB24' ,'uint8' ,@uint8 ,3,1 ,t,t,f}; dtype = struct(... 'code' ,table(:,1),... 'label' ,table(:,2),... 'prec' ,table(:,3),... 'conv' ,table(:,4),... 'nelem' ,table(:,5),... 'size' ,table(:,6),... 'isint' ,table(:,7),... 'unsigned' ,table(:,8),... 'min',-Inf,'max',Inf',... 'supported',table(:,9)); for i=1:length(dtype), if dtype(i).isint if dtype(i).unsigned dtype(i).min = 0; dtype(i).max = 2^(8*dtype(i).size)-1; else dtype(i).min = -2^(8*dtype(i).size-1); dtype(i).max = 2^(8*dtype(i).size-1)-1; end; end; end; % Intent table = {... 0 ,'NONE' ,'None',{} 2 ,'CORREL' ,'Correlation statistic',{'DOF'} 3 ,'TTEST' ,'T-statistic',{'DOF'} 4 ,'FTEST' ,'F-statistic',{'numerator DOF','denominator DOF'} 5 ,'ZSCORE' ,'Z-score',{} 6 ,'CHISQ' ,'Chi-squared distribution',{'DOF'} 7 ,'BETA' ,'Beta distribution',{'a','b'} 8 ,'BINOM' ,'Binomial distribution',... {'number of trials','probability per trial'} 9 ,'GAMMA' ,'Gamma distribution',{'shape','scale'} 10 ,'POISSON' ,'Poisson distribution',{'mean'} 11 ,'NORMAL' ,'Normal distribution',{'mean','standard deviation'} 12 ,'FTEST_NONC' ,'F-statistic noncentral',... {'numerator DOF','denominator DOF','numerator noncentrality parameter'} 13 ,'CHISQ_NONC' ,'Chi-squared noncentral',{'DOF','noncentrality parameter'} 14 ,'LOGISTIC' ,'Logistic distribution',{'location','scale'} 15 ,'LAPLACE' ,'Laplace distribution',{'location','scale'} 16 ,'UNIFORM' ,'Uniform distribition',{'lower end','upper end'} 17 ,'TTEST_NONC' ,'T-statistic noncentral',{'DOF','noncentrality parameter'} 18 ,'WEIBULL' ,'Weibull distribution',{'location','scale','power'} 19 ,'CHI' ,'Chi distribution',{'DOF'} 20 ,'INVGAUSS' ,'Inverse Gaussian distribution',{'mu','lambda'} 21 ,'EXTVAL' ,'Extreme Value distribution',{'location','scale'} 22 ,'PVAL' ,'P-value',{} 23 ,'LOGPVAL' ,'Log P-value',{} 24 ,'LOG10PVAL' ,'Log_10 P-value',{} 1001,'ESTIMATE' ,'Estimate',{} 1002,'LABEL' ,'Label index',{} 1003,'NEURONAMES' ,'NeuroNames index',{} 1004,'MATRIX' ,'General matrix',{'M','N'} 1005,'MATRIX_SYM' ,'Symmetric matrix',{} 1006,'DISPLACEMENT' ,'Displacement vector',{} 1007,'VECTOR' ,'Vector',{} 1008,'POINTS' ,'Pointset',{} 1009,'TRIANGLE' ,'Triangle',{} 1010,'QUATERNION' ,'Quaternion',{} 1011,'DIMLESS' ,'Dimensionless',{} }; intent = struct('code',table(:,1),'label',table(:,2),... 'fullname',table(:,3),'param',table(:,4)); % Units table = {... 0, 1,'UNKNOWN' 1,1000,'m' 2, 1,'mm' 3,1e-3,'um' 8, 1,'s' 16,1e-3,'ms' 24,1e-6,'us' 32, 1,'Hz' 40, 1,'ppm' 48, 1,'rads'}; units = struct('code',table(:,1),'label',table(:,3),'rescale',table(:,2)); % Reference space % code = {0,1,2,3,4}; table = {... 0,'UNKNOWN' 1,'Scanner Anat' 2,'Aligned Anat' 3,'Talairach' 4,'MNI_152'}; anat = struct('code',table(:,1),'label',table(:,2)); % Slice Ordering table = {... 0,'UNKNOWN' 1,'sequential_increasing' 2,'sequential_decreasing' 3,'alternating_increasing' 4,'alternating_decreasing'}; sliceorder = struct('code',table(:,1),'label',table(:,2)); % Q/S Form Interpretation table = {... 0,'UNKNOWN' 1,'Scanner' 2,'Aligned' 3,'Talairach' 4,'MNI152'}; xform = struct('code',table(:,1),'label',table(:,2)); dict = struct('dtype',dtype,'intent',intent,'units',units,... 'space',anat,'sliceorder',sliceorder,'xform',xform); d = dict; return; function varargout = crash(varargin) error('There is a NIFTI-1 data format problem (an invalid datatype).');
github
lcnhappe/happe-master
write_extras.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/spm8/@nifti/private/write_extras.m
829
utf_8
598b84950ce613b42919ce1f50a59132
function extras = write_extras(fname,extras) % Write extra bits of information %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ [pth,nam,ext] = fileparts(fname); switch ext case {'.hdr','.img','.nii'} mname = fullfile(pth,[nam '.mat']); case {'.HDR','.IMG','.NII'} mname = fullfile(pth,[nam '.MAT']); otherwise mname = fullfile(pth,[nam '.mat']); end if isstruct(extras) && ~isempty(fieldnames(extras)), savefields(mname,extras); end; function savefields(fnam,p) if length(p)>1, error('Can''t save fields.'); end; fn = fieldnames(p); for i_=1:length(fn), eval([fn{i_} '= p.' fn{i_} ';']); end; if str2num(version('-release'))>=14, fn = {'-V6',fn{:}}; end; if numel(fn)>0, save(fnam,fn{:}); end; return;
github
lcnhappe/happe-master
delete.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/gifti/@xmltree/delete.m
1,189
utf_8
9ca7b2db1b9fc84848585e118ac9d026
function tree = delete(tree,uid) % XMLTREE/DELETE Delete (delete a subtree given its UID) % % tree - XMLTree object % uid - array of UID's of subtrees to be deleted %__________________________________________________________________________ % % Delete a subtree given its UID % The tree parameter must be in input AND in output %__________________________________________________________________________ % Copyright (C) 2002-2011 http://www.artefact.tk/ % Guillaume Flandin % $Id: delete.m 4460 2011-09-05 14:52:16Z guillaume $ %error(nargchk(2,2,nargin)); uid = uid(:); for i=1:length(uid) if uid(i)==1 warning('[XMLTree] Cannot delete root element.'); else p = tree.tree{uid(i)}.parent; tree = sub_delete(tree,uid(i)); tree.tree{p}.contents(find(tree.tree{p}.contents==uid(i))) = []; end end %========================================================================== function tree = sub_delete(tree,uid) if isfield(tree.tree{uid},'contents') for i=1:length(tree.tree{uid}.contents) tree = sub_delete(tree,tree.tree{uid}.contents(i)); end end tree.tree{uid} = struct('type','deleted');
github
lcnhappe/happe-master
save.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/gifti/@xmltree/save.m
5,114
utf_8
1c7adbb3f79946f51f25d9031fcb515c
function varargout = save(tree, filename) % XMLTREE/SAVE Save an XML tree in an XML file % FORMAT varargout = save(tree,filename) % % tree - XMLTree % filename - XML output filename % varargout - XML string %__________________________________________________________________________ % % Convert an XML tree into a well-formed XML string and write it into % a file or return it as a string if no filename is provided. %__________________________________________________________________________ % Copyright (C) 2002-2011 http://www.artefact.tk/ % Guillaume Flandin % $Id: save.m 4460 2011-09-05 14:52:16Z guillaume $ %error(nargchk(1,2,nargin)); prolog = '<?xml version="1.0" ?>\n'; %- Return the XML tree as a string if nargin == 1 varargout{1} = [sprintf(prolog) ... print_subtree(tree,'',root(tree))]; %- Output specified else %- Filename provided if ischar(filename) [fid, msg] = fopen(filename,'w'); if fid==-1, error(msg); end if isempty(tree.filename), tree.filename = filename; end %- File identifier provided elseif isnumeric(filename) && numel(filename) == 1 fid = filename; prolog = ''; %- With this option, do not write any prolog else error('[XMLTree] Invalid argument.'); end fprintf(fid,prolog); save_subtree(tree,fid,root(tree)); if ischar(filename), fclose(fid); end if nargout == 1 varargout{1} = print_subtree(tree,'',root(tree)); end end %========================================================================== function xmlstr = print_subtree(tree,xmlstr,uid,order) if nargin < 4, order = 0; end xmlstr = [xmlstr blanks(3*order)]; switch tree.tree{uid}.type case 'element' xmlstr = sprintf('%s<%s',xmlstr,tree.tree{uid}.name); for i=1:length(tree.tree{uid}.attributes) xmlstr = sprintf('%s %s="%s"', xmlstr, ... tree.tree{uid}.attributes{i}.key,... tree.tree{uid}.attributes{i}.val); end if isempty(tree.tree{uid}.contents) xmlstr = sprintf('%s/>\n',xmlstr); else xmlstr = sprintf('%s>\n',xmlstr); for i=1:length(tree.tree{uid}.contents) xmlstr = print_subtree(tree,xmlstr, ... tree.tree{uid}.contents(i),order+1); end xmlstr = [xmlstr blanks(3*order)]; xmlstr = sprintf('%s</%s>\n',xmlstr,... tree.tree{uid}.name); end case 'chardata' xmlstr = sprintf('%s%s\n',xmlstr, ... entity(tree.tree{uid}.value)); case 'cdata' xmlstr = sprintf('%s<![CDATA[%s]]>\n',xmlstr, ... tree.tree{uid}.value); case 'pi' xmlstr = sprintf('%s<?%s %s?>\n',xmlstr, ... tree.tree{uid}.target, tree.tree{uid}.value); case 'comment' xmlstr = sprintf('%s<!-- %s -->\n',xmlstr,... tree.tree{uid}.value); otherwise warning(sprintf('Type %s unknown: not saved', ... tree.tree{uid}.type)); end %========================================================================== function save_subtree(tree,fid,uid,order) if nargin < 4, order = 0; end fprintf(fid,blanks(3*order)); switch tree.tree{uid}.type case 'element' fprintf(fid,'<%s',tree.tree{uid}.name); for i=1:length(tree.tree{uid}.attributes) fprintf(fid,' %s="%s"',... tree.tree{uid}.attributes{i}.key, ... tree.tree{uid}.attributes{i}.val); end if isempty(tree.tree{uid}.contents) fprintf(fid,'/>\n'); else fprintf(fid,'>\n'); for i=1:length(tree.tree{uid}.contents) save_subtree(tree,fid,... tree.tree{uid}.contents(i),order+1) end fprintf(fid,blanks(3*order)); fprintf(fid,'</%s>\n',tree.tree{uid}.name); end case 'chardata' fprintf(fid,'%s\n',entity(tree.tree{uid}.value)); case 'cdata' fprintf(fid,'<![CDATA[%s]]>\n',tree.tree{uid}.value); case 'pi' fprintf(fid,'<?%s %s?>\n',tree.tree{uid}.target, ... tree.tree{uid}.value); case 'comment' fprintf(fid,'<!-- %s -->\n',tree.tree{uid}.value); otherwise warning(sprintf('[XMLTree] Type %s unknown: not saved', ... tree.tree{uid}.type)); end %========================================================================== function str = entity(str) % This has the side effect of strtrim'ming the char array. str = char(strrep(cellstr(str), '&', '&amp;' )); str = char(strrep(cellstr(str), '<', '&lt;' )); str = char(strrep(cellstr(str), '>', '&gt;' )); str = char(strrep(cellstr(str), '"', '&quot;')); str = char(strrep(cellstr(str), '''', '&apos;'));
github
lcnhappe/happe-master
branch.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/gifti/@xmltree/branch.m
1,750
utf_8
407ff520e9de6dc9150a5b4f44d75c90
function subtree = branch(tree,uid) % XMLTREE/BRANCH Branch Method % FORMAT uid = parent(tree,uid) % % tree - XMLTree object % uid - UID of the root element of the subtree % subtree - XMLTree object (a subtree from tree) %__________________________________________________________________________ % % Return a subtree from a tree. %__________________________________________________________________________ % Copyright (C) 2002-2011 http://www.artefact.tk/ % Guillaume Flandin % $Id: branch.m 4460 2011-09-05 14:52:16Z guillaume $ %error(nargchk(2,2,nargin)); if uid > length(tree) || ... numel(uid)~=1 || ... ~strcmp(tree.tree{uid}.type,'element') error('[XMLTree] Invalid UID.'); end subtree = xmltree; subtree = set(subtree,root(subtree),'name',tree.tree{uid}.name); %- fix by Piotr Dollar to copy attributes for the root node: subtree = set(subtree,root(subtree),'attributes',tree.tree{uid}.attributes); child = children(tree,uid); for i=1:length(child) l = length(subtree); subtree = sub_branch(tree,subtree,child(i),root(subtree)); subtree.tree{root(subtree)}.contents = [subtree.tree{root(subtree)}.contents l+1]; end %========================================================================== function tree = sub_branch(t,tree,uid,p) l = length(tree); tree.tree{l+1} = t.tree{uid}; tree.tree{l+1}.uid = l + 1; tree.tree{l+1}.parent = p; tree.tree{l+1}.contents = []; if isfield(t.tree{uid},'contents') contents = get(t,uid,'contents'); m = length(tree); for i=1:length(contents) tree.tree{l+1}.contents = [tree.tree{l+1}.contents m+1]; tree = sub_branch(t,tree,contents(i),l+1); m = length(tree); end end
github
lcnhappe/happe-master
flush.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/gifti/@xmltree/flush.m
1,413
utf_8
64502185e2efb9de8f36e36751a39517
function tree = flush(tree,uid) % XMLTREE/FLUSH Flush (Clear a subtree given its UID) % % tree - XMLTree object % uid - array of UID's of subtrees to be cleared % Default is root %__________________________________________________________________________ % % Clear a subtree given its UID (remove all the leaves of the tree) % The tree parameter must be in input AND in output %__________________________________________________________________________ % Copyright (C) 2002-2011 http://www.artefact.tk/ % Guillaume Flandin % $Id: flush.m 4460 2011-09-05 14:52:16Z guillaume $ %error(nargchk(1,2,nargin)); if nargin == 1, uid = root(tree); end uid = uid(:); for i=1:length(uid) tree = sub_flush(tree,uid(i)); end %========================================================================== function tree = sub_flush(tree,uid) if isfield(tree.tree{uid},'contents') % contents is parsed in reverse order because each child is % deleted and the contents vector is then eventually reduced for i=length(tree.tree{uid}.contents):-1:1 tree = sub_flush(tree,tree.tree{uid}.contents(i)); end end if strcmp(tree.tree{uid}.type,'chardata') ||... strcmp(tree.tree{uid}.type,'pi') ||... strcmp(tree.tree{uid}.type,'cdata') ||... strcmp(tree.tree{uid}.type,'comment') tree = delete(tree,uid); end
github
lcnhappe/happe-master
copy.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/gifti/@xmltree/copy.m
1,634
utf_8
e6df62a4f41243b78ed8c517b15e493b
function tree = copy(tree,subuid,uid) % XMLTREE/COPY Copy Method (copy a subtree in another branch) % FORMAT tree = copy(tree,subuid,uid) % % tree - XMLTree object % subuid - UID of the subtree to copy % uid - UID of the element where the subtree must be duplicated %__________________________________________________________________________ % % Copy a subtree to another branch. % The tree parameter must be in input AND in output. %__________________________________________________________________________ % Copyright (C) 2002-2015 http://www.artefact.tk/ % Guillaume Flandin % $Id: copy.m 6480 2015-06-13 01:08:30Z guillaume $ %error(nargchk(2,3,nargin)); if nargin == 2 uid = parent(tree,subuid); end l = length(tree); tree = sub_copy(tree,subuid,uid); tree.tree{uid}.contents = [tree.tree{uid}.contents l+1]; % to have the copy next to the original and not at the end? % contents = get(tree,parent,'contents'); % i = find(contents==uid); % tree = set(tree,parent,'contents',[contents(1:i) l+1 contents(i+1:end)]); %========================================================================== function tree = sub_copy(tree,uid,p) l = length(tree); tree.tree{l+1} = tree.tree{uid}; tree.tree{l+1}.uid = l+1; tree.tree{l+1}.parent = p; tree.tree{l+1}.contents = []; if isfield(tree.tree{uid},'contents') contents = get(tree,uid,'contents'); m = length(tree); for i=1:length(contents) tree.tree{l+1}.contents = [tree.tree{l+1}.contents m+1]; tree = sub_copy(tree,contents(i),l+1); m = length(tree); end end
github
lcnhappe/happe-master
convert.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/gifti/@xmltree/convert.m
5,573
utf_8
05b85174fb85e5d62de81654b76ef7ab
function s = convert(tree,uid) % XMLTREE/CONVERT Converter an XML tree in a structure % % tree - XMLTree object % uid - uid of the root of the subtree, if provided. % Default is root % s - converted structure %__________________________________________________________________________ % % Convert an XMLTree into a structure, when possible. % When several identical tags are present, a cell array is used. % The root tag is not saved in the structure. % If provided, only the structure corresponding to the subtree defined % by the uid UID is returned. %__________________________________________________________________________ % Copyright (C) 2002-2015 http://www.artefact.tk/ % Guillaume Flandin % $Id: convert.m 6480 2015-06-13 01:08:30Z guillaume $ % Exemple: % tree = '<a><b>field1</b><c>field2</c><b>field3</b></a>'; % toto = convert(xmltree(tree)); % <=> toto = struct('b',{{'field1', 'field3'}},'c','field2') %error(nargchk(1,2,nargin)); % Get the root uid of the output structure if nargin == 1 % Get the root uid of the XML tree root_uid = root(tree); else % Uid provided by user root_uid = uid; end % Initialize the output structure % struct([]) should be used but this only works with Matlab 6 % So we create a field that we delete at the end %s = struct(get(tree,root_uid,'name'),''); % struct([]) s = struct('deletedummy',''); %s = sub_convert(tree,s,root_uid,{get(tree,root_uid,'name')}); s = sub_convert(tree,s,root_uid,{}); s = rmfield(s,'deletedummy'); %========================================================================== function s = sub_convert(tree,s,uid,arg) type = get(tree,uid,'type'); switch type case 'element' child = children(tree,uid); l = {}; ll = {}; for i=1:length(child) if isfield(tree,child(i),'name') ll = { ll{:}, get(tree,child(i),'name') }; end end for i=1:length(child) if isfield(tree,child(i),'name') name = get(tree,child(i),'name'); nboccur = sum(ismember(l,name)); nboccur2 = sum(ismember(ll,name)); l = { l{:}, name }; if nboccur || (nboccur2>1) arg2 = { arg{:}, name, {nboccur+1} }; else arg2 = { arg{:}, name}; end else arg2 = arg; end s = sub_convert(tree,s,child(i),arg2); end if isempty(child) s = sub_setfield(s,arg{:},''); end %- saving attributes : does not work with <a t='q'>b</a> %- but ok with <a t='q'><c>b</c></a> % attrb = attributes(tree,'get',uid); %- % if ~isempty(attrb) %- % arg2 = {arg{:} 'attributes'}; %- % s = sub_setfield(s,arg2{:},attrb); %- % end %- case 'chardata' s = sub_setfield(s,arg{:},get(tree,uid,'value')); %- convert strings into their numerical equivalent when possible %- e.g. string '3.14159' becomes double scalar 3.14159 % v = get(tree,uid,'value'); %- % cv = str2num(v); %- % if isempty(cv) %- % s = sub_setfield(s,arg{:},v); %- % else %- % s = sub_setfield(s,arg{:},cv); %- % end %- case 'cdata' s = sub_setfield(s,arg{:},get(tree,uid,'value')); case 'pi' % Processing instructions are evaluated if possible app = get(tree,uid,'target'); switch app case {'matlab',''} s = sub_setfield(s,arg{:},eval(get(tree,uid,'value'))); case 'unix' s = sub_setfield(s,arg{:},unix(get(tree,uid,'value'))); case 'dos' s = sub_setfield(s,arg{:},dos(get(tree,uid,'value'))); case 'system' s = sub_setfield(s,arg{:},system(get(tree,uid,'value'))); otherwise try s = sub_setfield(s,arg{:},feval(app,get(tree,uid,'value'))); catch warning('[XMLTree] Unknown target application'); end end case 'comment' % Comments are forgotten otherwise warning(sprintf('Type %s unknown : not saved',get(tree,uid,'type'))); end %========================================================================== function s = sub_setfield(s,varargin) % Same as setfield but using '{}' rather than '()' %if (isempty(varargin) | length(varargin) < 2) % error('Not enough input arguments.'); %end subs = varargin(1:end-1); for i = 1:length(varargin)-1 if (isa(varargin{i}, 'cell')) types{i} = '{}'; elseif ischar(varargin{i}) types{i} = '.'; subs{i} = varargin{i}; %strrep(varargin{i},' ',''); % deblank field name else error('Inputs must be either cell arrays or strings.'); end end % Perform assignment try s = builtin('subsasgn', s, struct('type',types,'subs',subs), varargin{end}); catch error(lasterr) end
github
lcnhappe/happe-master
editor.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/gifti/@xmltree/editor.m
12,418
utf_8
80850644600bde45b47898d068ef0978
function editor(tree) %XMLTREE/EDITOR A Graphical User Interface for an XML tree % EDITOR(TREE) opens a new figure displaying the xmltree object TREE. % H = EDITOR(TREE) also returns the figure handle H. % % This is a beta version of <xmltree/view> successor % % See also XMLTREE %__________________________________________________________________________ % Copyright (C) 2002-2015 http://www.artefact.tk/ % Guillaume Flandin % $Id: editor.m 6480 2015-06-13 01:08:30Z guillaume $ %error(nargchk(1,1,nargin)); if ~isempty(getfilename(tree)) title = getfilename(tree); elseif ~isempty(inputname(1)) title = ['Variable ''' inputname(1) '''']; else title = 'Untitled'; end h = initWindow(title); setappdata(h,'handles',guihandles(h)); setappdata(h,'save',0); tree = set(tree,root(tree),'show',1); setappdata(h,'tree',tree); doUpdate([],[],h); set(h,'HandleVisibility','callback'); %========================================================================== function h = initWindow(title) wincolor = struct('bg', [0.8 0.8 0.8], ... 'fg', [1.0 1.0 1.0], ... 'title', [0.9 0.9 0.9]); title = [':: XMLTree Editor :: ' title]; h = figure('Name', title, ... 'Units', 'Points', ... 'NumberTitle', 'off', ... 'Resize', 'on', ... 'Color', wincolor.bg,... 'Position', [200 200 440 330], ... 'MenuBar', 'none', ... 'Tag', mfilename); set(h, 'CloseRequestFcn', {@doClose,h}); %- Left box uicontrol('Style', 'listbox', ... 'HorizontalAlignment','left', ... 'Units','Normalized', ... 'Visible','on',... 'BackgroundColor', wincolor.fg, ... 'Max', 1, ... 'Value', 1 , ... 'Enable', 'on', ... 'Position', [0.04 0.12 0.3 0.84], ... 'Callback', {@doList,h}, ... 'String', ' ', ... 'Tag', 'xmllistbox'); %- Right box uicontrol('Style', 'listbox', ... 'HorizontalAlignment','left', ... 'Units','Normalized', ... 'Visible','on',... 'BackgroundColor', wincolor.bg, ... 'Min', 0, ... 'Max', 2, ... 'Value', [], ... 'Enable', 'inactive', ... 'Position', [0.38 0.50 0.58 0.46], ... 'Callback', '', ... 'String', ' ', ... 'Tag', 'xmllist'); %- The Add button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.04 0.03 0.11 0.06], ... 'String', 'Add', ... 'Enable','on',... 'Tag', 'addbutton', ... 'Callback', {@doAdd,h}); %- The Modify button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.175 0.03 0.11 0.06], ... 'String', 'Modify', ... 'Enable','on',... 'Tag', 'modifybutton', ... 'Callback', {@doModify,h}); %- The Copy button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.310 0.03 0.11 0.06], ... 'String', 'Copy', ... 'Enable','on',... 'Tag', 'copybutton', ... 'Callback', {@doCopy,h}); %- The Delete button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.445 0.03 0.11 0.06], ... 'String', 'Delete', ... 'Enable','on',... 'Tag', 'delbutton', ... 'Callback', {@doDelete,h}); %- The Save button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.580 0.03 0.11 0.06], ... 'String', 'Save', ... 'Tag', 'savebutton', ... 'Callback', {@doSave,h}); %- The Run button %uicontrol('Style', 'pushbutton', ... % 'Units', 'Normalized', ... % 'Position', [0.715 0.03 0.11 0.06], ... % 'String', 'Run', ... % 'Enable', 'off', ... % 'Tag', 'runbutton', ... % 'Callback', {@doRun,h}); %- The Attributes button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.715 0.03 0.11 0.06], ... 'String', 'Attr.', ... 'Enable', 'on', ... 'Tag', 'runbutton', ... 'Callback', {@doAttributes,h}); %- The Close button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.850 0.03 0.11 0.06], ... 'String', 'Close', ... 'Tag', 'closebutton', ... 'Callback', {@doClose,h}); %========================================================================== function doClose(fig,evd,h) s = getappdata(h, 'save'); status = 1; if s button = questdlg(sprintf('Save changes to the XML tree?'),... 'XMLTree Editor','Yes','No','Cancel','Yes'); if strcmp(button,'Yes') status = doSave([],[],h); elseif strcmp(button,'Cancel') status = 0; end end if status delete(h); end function doAdd(fig,evd,h) tree = getappdata(h, 'tree'); uidList = getappdata(h, 'uidlist'); handles = getappdata(h, 'handles'); pos = get(handles.xmllistbox,'value'); uid = uidList(pos); answer = questdlg('Which kind of item to add?', ... 'XMLTree Editor :: Add','Node','Leaf','Node'); switch answer case 'Node' tree = add(tree,uid,'element','New_Node'); case 'Leaf' tree = add(tree,uid,'element','New_Leaf'); l = length(tree); tree = add(tree,l,'chardata','default'); end tree = set(tree,uid,'show',1); setappdata(h, 'tree', tree); setappdata(h, 'save', 1); doUpdate([],[],h); doList([],[],h); function doModify(fig,evd,h) tree = getappdata(h, 'tree'); uidList = getappdata(h, 'uidlist'); handles = getappdata(h, 'handles'); pos = get(handles.xmllistbox,'value'); uid = uidList(pos); contents = children(tree,uid); if length(contents) > 0 && ... strcmp(get(tree,contents(1),'type'),'chardata') str = get(tree,contents(1),'value'); prompt = {'Name :','New value:'}; def = {get(tree,uid,'name'),str}; title = sprintf('Modify %s',get(tree,uid,'name')); lineNo = 1; answer = inputdlg(prompt,title,lineNo,def); if ~isempty(answer) tree = set(tree,uid,'name',answer{1}); str = answer{2}; tree = set(tree,contents(1),'value',str); setappdata(h, 'tree', tree); setappdata(h, 'save', 1); end else str = ['Tag ' get(tree,uid,'name')]; prompt = {'Name :'}; def = {get(tree,uid,'name'),str}; title = sprintf('Modify %s tag',get(tree,uid,'name')); lineNo = 1; answer = inputdlg(prompt,title,lineNo,def); if ~isempty(answer) tree = set(tree,uid,'name',answer{1}); str = ['Tag ' get(tree,uid,'name')]; setappdata(h, 'tree', tree); setappdata(h, 'save', 1); end end %- Trying to keep the slider active set(handles.xmllist, 'Enable', 'on'); set(handles.xmllist, 'String', ' '); set(handles.xmllist, 'Enable', 'Inactive'); set(handles.xmllist, 'String', str); doUpdate([],[],h); doList([],[],h); function doCopy(fig,evd,h) tree = getappdata(h, 'tree'); uidList = getappdata(h, 'uidlist'); handles = getappdata(h, 'handles'); pos = get(handles.xmllistbox,'value'); uid = uidList(pos); if pos ~= 1 tree = copy(tree,uid); setappdata(h, 'tree', tree); setappdata(h, 'save', 1); doUpdate([],[],h); doList([],[],h); end function doDelete(fig,evd,h) tree = getappdata(h, 'tree'); uidList = getappdata(h, 'uidlist'); handles = getappdata(h, 'handles'); pos = get(handles.xmllistbox,'value'); uid = uidList(pos); if pos > 1 tree = delete(tree,uid); set(handles.xmllistbox,'value',pos-1); setappdata(h, 'save', 1); end setappdata(h, 'tree', tree); doUpdate([],[],h); doList([],[],h); function status = doSave(fig,evd,h) tree = getappdata(h, 'tree'); [filename, pathname] = uiputfile({'*.xml' 'XML file (*.xml)'}, ... 'Save XML file as'); status = ~(isequal(filename,0) | isequal(pathname,0)); if status save(tree,fullfile(pathname, filename)); set(h,'Name',[':: XMLTree Editor :: ' filename]); setappdata(h, 'save', 0); end function doRun(fig,evd,h) warndlg('Not implemented','XMLTree :: Run'); function doAttributes(fig,evd,h) tree = getappdata(h, 'tree'); uidList = getappdata(h, 'uidlist'); handles = getappdata(h, 'handles'); pos = get(handles.xmllistbox,'value'); uid = uidList(pos); attr = attributes(tree,'get',uid); if ~isempty(attr) fprintf('This element has %d attributes.\n',length(attr)); %%% %%% Do what you want with 'attr' %%% to modify them, use: %%% tree = attributes(tree,'set',uid,n,key,val) %%% to add one, use: %%% tree = attributes(tree,'add',uid,key,val) %%% to delete one, use: %%% tree = attributes(tree,'del',uid[,n]); %%% setappdata(h, 'tree', tree); setappdata(h, 'save', 1); %- only if attributes have been modified end %========================================================================== function doList(fig,evd,h) tree = getappdata(h, 'tree'); uidList = getappdata(h, 'uidlist'); handles = getappdata(h, 'handles'); uid = uidList(get(handles.xmllistbox, 'value')); %- Single mouse click if strcmp(get(h,'SelectionType'),'normal') contents = children(tree, uid); if length(contents) > 0 && ... strcmp(get(tree,contents(1),'type'),'chardata') str = get(tree,contents(1),'value'); set(handles.addbutton,'Enable','off'); elseif length(contents) == 0 str = ''; tree = add(tree,uid,'chardata',str); setappdata(h, 'tree', tree); set(handles.addbutton,'Enable','off'); else str = ['Tag ' get(tree,uid,'name')]; set(handles.addbutton,'Enable','on'); end if get(handles.xmllistbox,'value') == 1 set(handles.copybutton,'Enable','off'); set(handles.delbutton,'Enable','off'); else set(handles.copybutton,'Enable','on'); set(handles.delbutton,'Enable','on'); end %- Trying to keep the slider active set(handles.xmllist, 'Enable', 'on'); set(handles.xmllist, 'String', ' '); set(handles.xmllist, 'Enable', 'Inactive'); set(handles.xmllist, 'String', str); %- Double mouse click else tree = doFlip(tree, uid); setappdata(h, 'tree', tree); doUpdate([],[],h); end function doUpdate(fig,evd,h) tree = getappdata(h, 'tree'); handles = getappdata(h, 'handles'); [batchString, uidList] = doUpdateR(tree); set(handles.xmllistbox, 'String', batchString); setappdata(h, 'uidlist', uidList); %========================================================================== function [batchString, uidList] = doUpdateR(tree, uid, o) if nargin < 2, uid = root(tree); end if nargin < 3 || o == 0 o = 0; sep = ' '; else sep = blanks(4*o); end if attributes(tree,'length',uid) > 0 batchString = {[sep, get(tree, uid, 'name') ' *']}; else batchString = {[sep, get(tree, uid, 'name')]}; end uidList = [get(tree,uid,'uid')]; haselementchild = 0; contents = get(tree, uid, 'contents'); if isfield(tree, uid, 'show') && get(tree, uid, 'show') == 1 for i=1:length(contents) if strcmp(get(tree,contents(i),'type'),'element') [subbatchString, subuidList] = doUpdateR(tree,contents(i),o+1); batchString = {batchString{:} subbatchString{:}}; uidList = [uidList subuidList]; haselementchild = 1; end end if haselementchild == 1, batchString{1}(length(sep)) = '-'; end else for i=1:length(contents) if strcmp(get(tree,contents(i),'type'),'element') haselementchild = 1; end end if haselementchild == 1, batchString{1}(length(sep)) = '+'; end end function tree = doFlip(tree, uid) if isfield(tree,uid,'show') show = get(tree,uid,'show'); else show = 0; end tree = set(tree,uid,'show',~show);
github
lcnhappe/happe-master
find.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/gifti/@xmltree/find.m
5,901
utf_8
b241bfaac569f137b8b809b7b66765f3
function list = find(varargin) % XMLTREE/FIND Find elements in a tree with specified characteristics % FORMAT list = find(varargin) % % tree - XMLTree object % xpath - string path with specific grammar (XPath) % uid - lists of root uid's % parameter/value - pair of pattern % list - list of uid's of matched elements % % list = find(tree,xpath) % list = find(tree,parameter,value[,parameter,value]) % list = find(tree,uid,parameter,value[,parameter,value]) % % Grammar for addressing parts of an XML document: % XML Path Language XPath (http://www.w3.org/TR/xpath) % Example: /element1//element2[1]/element3[5]/element4 %__________________________________________________________________________ % % Find elements in an XML tree with specified characteristics or given % a path (using a subset of XPath language). %__________________________________________________________________________ % Copyright (C) 2002-2011 http://www.artefact.tk/ % Guillaume Flandin % $Id: find.m 4460 2011-09-05 14:52:16Z guillaume $ % TODO: % - clean up subroutines % - find should only be documented using XPath (other use is internal) % - handle '*', 'last()' in [] and '@' % - if a key is invalid, should rather return [] than error ? if nargin==0 error('[XMLTree] A tree must be provided'); elseif nargin==1 list = 1:length(tree.tree); return elseif mod(nargin,2) list = sub_find_subtree1(varargin{1}.tree,root(varargin{1}),varargin{2:end}); elseif isa(varargin{2},'double') && ... ndims(varargin{2}) == 2 && ... min(size(varargin{2})) == 1 list = unique(sub_find_subtree1(varargin{1}.tree,varargin{2:end})); elseif nargin==2 && ischar(varargin{2}) list = sub_pathfinder(varargin{:}); else error('[XMLTree] Arguments must be parameter/value pairs.'); end %========================================================================== function list = sub_find_subtree1(varargin) list = []; for i=1:length(varargin{2}) res = sub_find_subtree2(varargin{1},... varargin{2}(i),varargin{3:end}); list = [list res]; end %========================================================================== function list = sub_find_subtree2(varargin) uid = varargin{2}; list = []; if sub_comp_element(varargin{1}{uid},varargin{3:end}) list = [list varargin{1}{uid}.uid]; end if isfield(varargin{1}{uid},'contents') list = [list sub_find_subtree1(varargin{1},... varargin{1}{uid}.contents,varargin{3:end})]; end %========================================================================== function match = sub_comp_element(varargin) match = 0; try % v = getfield(varargin{1}, varargin{2}); % slow... for i=1:floor(nargin/2) v = subsref(varargin{1}, struct('type','.','subs',varargin{i+1})); if strcmp(v,varargin{i+2}) match = 1; end end catch end % More powerful but much slower %match = 0; %for i=1:length(floor(nargin/2)) % bug: remove length !!! % if isfield(varargin{1},varargin{i+1}) % if ischar(getfield(varargin{1},varargin{i+1})) & ischar(varargin{i+2}) % if strcmp(getfield(varargin{1},varargin{i+1}),char(varargin{i+2})) % match = 1; % end % elseif isa(getfield(varargin{1},varargin{i+1}),'double') & ... % isa(varargin{i+2},'double') % if getfield(varargin{1},varargin{i+1}) == varargin{i+2} % match = 1; % end % else % warning('Cannot compare different objects'); % end % end %end %========================================================================== function list = sub_pathfinder(tree,pth) %- Search for the delimiter '/' in the path i = strfind(pth,'/'); %- Begin search by root list = root(tree); %- Walk through the tree j = 1; while j <= length(i) %- Look for recursion '//' if j<length(i) && i(j+1)==i(j)+1 recursive = 1; j = j + 1; else recursive = 0; end %- Catch the current tag 'element[x]' if j ~= length(i) element = pth(i(j)+1:i(j+1)-1); else element = pth(i(j)+1:end); end %- Search for [] brackets k = xml_findstr(element,'[',1,1); %- If brackets are present in current element if ~isempty(k) l = xml_findstr(element,']',1,1); val = str2num(element(k+1:l-1)); element = element(1:k-1); end %- Use recursivity if recursive list = find(tree,list,'name',element); %- Just look at children else if i(j)==1 % if '/root/...' (list = root(tree) in that case) if sub_comp_element(tree.tree{list},'name',element) % list = 1; % list still contains root(tree) else list = []; return; end else list = sub_findchild(tree,list,element); end end % If an element is specified using a key if ~isempty(k) if val < 1 || val > length(list)+1 error('[XMLTree] Bad key in the path.'); elseif val == length(list)+1 list = []; return; end list = list(val); end if isempty(list), return; end j = j + 1; end %========================================================================== function list = sub_findchild(tree,listt,elmt) list = []; for a=1:length(listt) for b=1:length(tree.tree{listt(a)}.contents) if sub_comp_element(tree.tree{tree.tree{listt(a)}.contents(b)},'name',elmt) list = [list tree.tree{tree.tree{listt(a)}.contents(b)}.uid]; end end end
github
lcnhappe/happe-master
xml_parser.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/gifti/@xmltree/private/xml_parser.m
16,192
utf_8
7e44abd21a10863623b455d03e0651bb
function tree = xml_parser(xmlstr) % XML (eXtensible Markup Language) Processor % FORMAT tree = xml_parser(xmlstr) % % xmlstr - XML string to parse % tree - tree structure corresponding to the XML file %__________________________________________________________________________ % % xml_parser.m is an XML 1.0 (http://www.w3.org/TR/REC-xml) parser. % It aims to be fully conforming. It is currently not a validating % XML processor. % % A description of the tree structure provided in output is detailed in % the header of this m-file. %__________________________________________________________________________ % Copyright (C) 2002-2015 http://www.artefact.tk/ % Guillaume Flandin % $Id: xml_parser.m 6480 2015-06-13 01:08:30Z guillaume $ % XML Processor for GNU Octave and MATLAB (The Mathworks, Inc.) % Copyright (C) 2002-2015 Guillaume Flandin <[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 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 Pl. - Suite 330, Boston, MA 02111-1307, USA. %-------------------------------------------------------------------------- % Suggestions for improvement and fixes are always welcome, although no % guarantee is made whether and when they will be implemented. % Send requests to <[email protected]> % Check also the latest developments on the following webpage: % <http://www.artefact.tk/software/matlab/xml/> %-------------------------------------------------------------------------- % The implementation of this XML parser is much inspired from a % Javascript parser that used to be available at <http://www.jeremie.com/> % A C-MEX file xml_findstr.c is also required, to encompass some % limitations of the built-in FINDSTR function. % Compile it on your architecture using 'mex -O xml_findstr.c' command % if the compiled version for your system is not provided. % If this function does not behave as expected, comment the line % '#define __HACK_MXCHAR__' in xml_findstr.c and compile it again. %-------------------------------------------------------------------------- % Structure of the output tree: % There are 5 types of nodes in an XML file: element, chardata, cdata, % pi and comment. % Each of them contains an UID (Unique Identifier): an integer between % 1 and the number of nodes of the XML file. % % element (a tag <name key="value"> [contents] </name> % |_ type: 'element' % |_ name: string % |_ attributes: cell array of struct 'key' and 'value' or [] % |_ contents: double array of uid's or [] if empty % |_ parent: uid of the parent ([] if root) % |_ uid: double % % chardata (a character array) % |_ type: 'chardata' % |_ value: string % |_ parent: uid of the parent % |_ uid: double % % cdata (a litteral string <![CDATA[value]]>) % |_ type: 'cdata' % |_ value: string % |_ parent: uid of the parent % |_ uid: double % % pi (a processing instruction <?target value ?>) % |_ type: 'pi' % |_ target: string (may be empty) % |_ value: string % |_ parent: uid of the parent % |_ uid: double % % comment (a comment <!-- value -->) % |_ type: 'comment' % |_ value: string % |_ parent: uid of the parent % |_ uid: double % %-------------------------------------------------------------------------- % TODO/BUG/FEATURES: % - [compile] only a warning if TagStart is empty ? % - [attribution] should look for " and ' rather than only " % - [main] with normalize as a preprocessing, CDATA are modified % - [prolog] look for a DOCTYPE in the whole string even if it occurs % only in a far CDATA tag, bug even if the doctype is inside a comment % - [tag_element] erode should replace normalize here % - remove globals? uppercase globals rather persistent (clear mfile)? % - xml_findstr is indeed xml_strfind according to Mathworks vocabulary % - problem with entities: do we need to convert them here? (&eacute;) %-------------------------------------------------------------------------- %- XML string to parse and number of tags read global xmlstring Xparse_count xtree; %- Check input arguments %error(nargchk(1,1,nargin)); if isempty(xmlstr) error('[XML] Not enough parameters.') elseif ~ischar(xmlstr) || sum(size(xmlstr)>1)>1 error('[XML] Input must be a string.') end %- Initialize number of tags (<=> uid) Xparse_count = 0; %- Remove prolog and white space characters from the XML string xmlstring = normalize(prolog(xmlstr)); %- Initialize the XML tree xtree = {}; tree = fragment; tree.str = 1; tree.parent = 0; %- Parse the XML string tree = compile(tree); %- Return the XML tree tree = xtree; %- Remove global variables from the workspace clear global xmlstring Xparse_count xtree; %========================================================================== % SUBFUNCTIONS %-------------------------------------------------------------------------- function frag = compile(frag) global xmlstring xtree Xparse_count; while 1, if length(xmlstring)<=frag.str || ... (frag.str == length(xmlstring)-1 && strcmp(xmlstring(frag.str:end),' ')) return end TagStart = xml_findstr(xmlstring,'<',frag.str,1); if isempty(TagStart) %- Character data error('[XML] Unknown data at the end of the XML file.'); Xparse_count = Xparse_count + 1; xtree{Xparse_count} = chardata; xtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:end))); xtree{Xparse_count}.parent = frag.parent; xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count]; frag.str = ''; elseif TagStart > frag.str if strcmp(xmlstring(frag.str:TagStart-1),' ') %- A single white space before a tag (ignore) frag.str = TagStart; else %- Character data Xparse_count = Xparse_count + 1; xtree{Xparse_count} = chardata; xtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:TagStart-1))); xtree{Xparse_count}.parent = frag.parent; xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count]; frag.str = TagStart; end else if strcmp(xmlstring(frag.str+1),'?') %- Processing instruction frag = tag_pi(frag); else if length(xmlstring)-frag.str>4 && strcmp(xmlstring(frag.str+1:frag.str+3),'!--') %- Comment frag = tag_comment(frag); else if length(xmlstring)-frag.str>9 && strcmp(xmlstring(frag.str+1:frag.str+8),'![CDATA[') %- Litteral data frag = tag_cdata(frag); else %- A tag element (empty (<.../>) or not) if ~isempty(frag.end) endmk = ['/' frag.end '>']; else endmk = '/>'; end if strcmp(xmlstring(frag.str+1:frag.str+length(frag.end)+2),endmk) || ... strcmp(strip(xmlstring(frag.str+1:frag.str+length(frag.end)+2)),endmk) frag.str = frag.str + length(frag.end)+3; return else frag = tag_element(frag); end end end end end end %-------------------------------------------------------------------------- function frag = tag_element(frag) global xmlstring xtree Xparse_count; close = xml_findstr(xmlstring,'>',frag.str,1); if isempty(close) error('[XML] Tag < opened but not closed.'); else empty = strcmp(xmlstring(close-1:close),'/>'); if empty close = close - 1; end starttag = normalize(xmlstring(frag.str+1:close-1)); nextspace = xml_findstr(starttag,' ',1,1); attribs = ''; if isempty(nextspace) name = starttag; else name = starttag(1:nextspace-1); attribs = starttag(nextspace+1:end); end Xparse_count = Xparse_count + 1; xtree{Xparse_count} = element; xtree{Xparse_count}.name = strip(name); if frag.parent xtree{Xparse_count}.parent = frag.parent; xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count]; end if ~isempty(attribs) xtree{Xparse_count}.attributes = attribution(attribs); end if ~empty contents = fragment; contents.str = close+1; contents.end = name; contents.parent = Xparse_count; contents = compile(contents); frag.str = contents.str; else frag.str = close+2; end end %-------------------------------------------------------------------------- function frag = tag_pi(frag) global xmlstring xtree Xparse_count; close = xml_findstr(xmlstring,'?>',frag.str,1); if isempty(close) warning('[XML] Tag <? opened but not closed.') else nextspace = xml_findstr(xmlstring,' ',frag.str,1); Xparse_count = Xparse_count + 1; xtree{Xparse_count} = pri; if nextspace > close || nextspace == frag.str+2 xtree{Xparse_count}.value = erode(xmlstring(frag.str+2:close-1)); else xtree{Xparse_count}.value = erode(xmlstring(nextspace+1:close-1)); xtree{Xparse_count}.target = erode(xmlstring(frag.str+2:nextspace)); end if frag.parent xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count]; xtree{Xparse_count}.parent = frag.parent; end frag.str = close+2; end %-------------------------------------------------------------------------- function frag = tag_comment(frag) global xmlstring xtree Xparse_count; close = xml_findstr(xmlstring,'-->',frag.str,1); if isempty(close) warning('[XML] Tag <!-- opened but not closed.') else Xparse_count = Xparse_count + 1; xtree{Xparse_count} = comment; xtree{Xparse_count}.value = erode(xmlstring(frag.str+4:close-1)); if frag.parent xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count]; xtree{Xparse_count}.parent = frag.parent; end frag.str = close+3; end %-------------------------------------------------------------------------- function frag = tag_cdata(frag) global xmlstring xtree Xparse_count; close = xml_findstr(xmlstring,']]>',frag.str,1); if isempty(close) warning('[XML] Tag <![CDATA[ opened but not closed.') else Xparse_count = Xparse_count + 1; xtree{Xparse_count} = cdata; xtree{Xparse_count}.value = xmlstring(frag.str+9:close-1); if frag.parent xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count]; xtree{Xparse_count}.parent = frag.parent; end frag.str = close+3; end %-------------------------------------------------------------------------- function all = attribution(str) %- Initialize attributs nbattr = 0; all = cell(nbattr); %- Look for 'key="value"' substrings while 1, eq = xml_findstr(str,'=',1,1); if isempty(str) || isempty(eq), return; end id = sort([xml_findstr(str,'"',1,1),xml_findstr(str,'''',1,1)]); id=id(1); nextid = sort([xml_findstr(str,'"',id+1,1),xml_findstr(str,'''',id+1,1)]);nextid=nextid(1); nbattr = nbattr + 1; all{nbattr}.key = strip(str(1:(eq-1))); all{nbattr}.val = entity(str((id+1):(nextid-1))); str = str((nextid+1):end); end %-------------------------------------------------------------------------- function elm = element global Xparse_count; elm = struct('type','element','name','','attributes',[],'contents',[],'parent',[],'uid',Xparse_count); %-------------------------------------------------------------------------- function cdat = chardata global Xparse_count; cdat = struct('type','chardata','value','','parent',[],'uid',Xparse_count); %-------------------------------------------------------------------------- function cdat = cdata global Xparse_count; cdat = struct('type','cdata','value','','parent',[],'uid',Xparse_count); %-------------------------------------------------------------------------- function proce = pri global Xparse_count; proce = struct('type','pi','value','','target','','parent',[],'uid',Xparse_count); %-------------------------------------------------------------------------- function commt = comment global Xparse_count; commt = struct('type','comment','value','','parent',[],'uid',Xparse_count); %-------------------------------------------------------------------------- function frg = fragment frg = struct('str','','parent','','end',''); %-------------------------------------------------------------------------- function str = prolog(str) %- Initialize beginning index of elements tree b = 1; %- Initial tag start = xml_findstr(str,'<',1,1); if isempty(start) error('[XML] No tag found.') end %- Header (<?xml version="1.0" ... ?>) if strcmpi(str(start:start+2),'<?x') close = xml_findstr(str,'?>',1,1); if ~isempty(close) b = close + 2; else warning('[XML] Header tag incomplete.') end end %- Doctype (<!DOCTYPE type ... [ declarations ]>) start = xml_findstr(str,'<!DOCTYPE',b,1); % length('<!DOCTYPE') = 9 if ~isempty(start) close = xml_findstr(str,'>',start+9,1); if ~isempty(close) b = close + 1; dp = xml_findstr(str,'[',start+9,1); if (~isempty(dp) && dp < b) k = xml_findstr(str,']>',start+9,1); if ~isempty(k) b = k + 2; else warning('[XML] Tag [ in DOCTYPE opened but not closed.') end end else warning('[XML] Tag DOCTYPE opened but not closed.') end end %- Skip prolog from the xml string str = str(b:end); %-------------------------------------------------------------------------- function str = strip(str) str(isspace(str)) = ''; %-------------------------------------------------------------------------- function str = normalize(str) % Find white characters (space, newline, carriage return, tabs, ...) i = isspace(str); i = find(i == 1); str(i) = ' '; % replace several white characters by only one if ~isempty(i) j = i - [i(2:end) i(end)]; str(i(j == -1)) = []; end %-------------------------------------------------------------------------- function str = entity(str) str = strrep(str,'&lt;','<'); str = strrep(str,'&gt;','>'); str = strrep(str,'&quot;','"'); str = strrep(str,'&apos;',''''); str = strrep(str,'&amp;','&'); %-------------------------------------------------------------------------- function str = erode(str) if ~isempty(str) && str(1)==' ', str(1)=''; end; if ~isempty(str) && str(end)==' ', str(end)=''; end;
github
lcnhappe/happe-master
save.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/gifti/@gifti/save.m
21,043
utf_8
747d3d8c45fa4a27160c0c333450a4dc
function save(this,filename,encoding) % Save GIfTI object in a GIfTI format file % FORMAT save(this,filename) % this - GIfTI object % filename - name of GIfTI file to be created [Default: 'untitled.gii'] % encoding - optional argument to specify encoding format, among % ASCII, Base64Binary, GZipBase64Binary, ExternalFileBinary, % Collada (.dae), IDTF (.idtf). [Default: 'GZipBase64Binary'] %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id$ % Check filename and file format %-------------------------------------------------------------------------- ext = '.gii'; if nargin == 1 filename = 'untitled.gii'; else if nargin == 3 && strcmpi(encoding,'collada') ext = '.dae'; end if nargin == 3 && strcmpi(encoding,'idtf') ext = '.idtf'; end [p,f,e] = fileparts(filename); if ~ismember(lower(e),{ext}) e = ext; end filename = fullfile(p,[f e]); end % Open file for writing %-------------------------------------------------------------------------- fid = fopen(filename,'wt'); if fid == -1 error('Unable to write file %s: permission denied.',filename); end % Write file %-------------------------------------------------------------------------- switch ext case '.gii' if nargin < 3, encoding = 'GZipBase64Binary'; end fid = save_gii(fid,this,encoding); case '.dae' fid = save_dae(fid,this); case '.idtf' fid = save_idtf(fid,this); otherwise error('Unknown file format.'); end % Close file %-------------------------------------------------------------------------- fclose(fid); %========================================================================== % function fid = save_gii(fid,this,encoding) %========================================================================== function fid = save_gii(fid,this,encoding) % Defaults for DataArray's attributes %-------------------------------------------------------------------------- [unused,unused,mach] = fopen(fid); if strncmp('ieee-be',mach,7) def.Endian = 'BigEndian'; elseif strncmp('ieee-le',mach,7) def.Endian = 'LittleEndian'; else error('[GIFTI] Unknown byte order "%s".',mach); end def.Encoding = encoding; def.Intent = 'NIFTI_INTENT_NONE'; def.DataType = 'NIFTI_TYPE_FLOAT32'; def.ExternalFileName = ''; def.ExternalFileOffset = ''; def.offset = 0; if strcmp(def.Encoding,'GZipBase64Binary') && ~usejava('jvm') warning(['Cannot save GIfTI in ''GZipBase64Binary'' encoding. ' ... 'Revert to ''Base64Binary''.']); def.Encoding = 'Base64Binary'; end % Edit object DataArray attributes %-------------------------------------------------------------------------- for i=1:length(this.data) % Revert the dimension storage d = this.data{i}.attributes.Dim; this.data{i}.attributes = rmfield(this.data{i}.attributes,'Dim'); this.data{i}.attributes.Dimensionality = num2str(length(d)); for j=1:length(d) this.data{i}.attributes.(sprintf('Dim%d',j-1)) = num2str(d(j)); end % Enforce some conventions this.data{i}.attributes.ArrayIndexingOrder = 'ColumnMajorOrder'; if ~isfield(this.data{i}.attributes,'DataType') || ... isempty(this.data{i}.attributes.DataType) warning('DataType set to default: %s', def.DataType); this.data{i}.attributes.DataType = def.DataType; end if ~isfield(this.data{i}.attributes,'Intent') || ... isempty(this.data{i}.attributes.Intent) warning('Intent code set to default: %s', def.Intent); this.data{i}.attributes.Intent = def.Intent; end this.data{i}.attributes.Encoding = def.Encoding; this.data{i}.attributes.Endian = def.Endian; this.data{i}.attributes.ExternalFileName = def.ExternalFileName; this.data{i}.attributes.ExternalFileOffset = def.ExternalFileOffset; switch this.data{i}.attributes.Encoding case {'ASCII', 'Base64Binary','GZipBase64Binary' } case 'ExternalFileBinary' extfilename = this.data{i}.attributes.ExternalFileName; if isempty(extfilename) [p,f] = fileparts(fopen(fid)); extfilename = [f '.dat']; end [p,f,e] = fileparts(extfilename); this.data{i}.attributes.ExternalFileName = fullfile(fileparts(fopen(fid)),[f e]); this.data{i}.attributes.ExternalFileOffset = num2str(def.offset); otherwise error('[GIFTI] Unknown data encoding: %s.',this.data{i}.attributes.Encoding); end end % Prolog %-------------------------------------------------------------------------- fprintf(fid,'<?xml version="1.0" encoding="UTF-8"?>\n'); fprintf(fid,'<!DOCTYPE GIFTI SYSTEM "http://www.nitrc.org/frs/download.php/115/gifti.dtd">\n'); fprintf(fid,'<GIFTI Version="1.0" NumberOfDataArrays="%d">\n',numel(this.data)); o = @(x) blanks(x*3); % MetaData %-------------------------------------------------------------------------- fprintf(fid,'%s<MetaData',o(1)); if isempty(this.metadata) fprintf(fid,'/>\n'); else fprintf(fid,'>\n'); for i=1:length(this.metadata) fprintf(fid,'%s<MD>\n',o(2)); fprintf(fid,'%s<Name><![CDATA[%s]]></Name>\n',o(3),... this.metadata(i).name); fprintf(fid,'%s<Value><![CDATA[%s]]></Value>\n',o(3),... this.metadata(i).value); fprintf(fid,'%s</MD>\n',o(2)); end fprintf(fid,'%s</MetaData>\n',o(1)); end % LabelTable %-------------------------------------------------------------------------- fprintf(fid,'%s<LabelTable',o(1)); if isempty(this.label) fprintf(fid,'/>\n'); else fprintf(fid,'>\n'); for i=1:length(this.label.name) if ~all(isnan(this.label.rgba(i,:))) label_rgba = sprintf(' Red="%f" Green="%f" Blue="%f" Alpha="%f"',... this.label.rgba(i,:)); else label_rgba = ''; end fprintf(fid,'%s<Label Key="%d"%s><![CDATA[%s]]></Label>\n',o(2),... this.label.key(i), label_rgba, this.label.name{i}); end fprintf(fid,'%s</LabelTable>\n',o(1)); end % DataArray %-------------------------------------------------------------------------- for i=1:length(this.data) fprintf(fid,'%s<DataArray',o(1)); if def.offset this.data{i}.attributes.ExternalFileOffset = num2str(def.offset); end fn = sort(fieldnames(this.data{i}.attributes)); oo = repmat({o(5) '\n'},length(fn),1); oo{1} = ' '; oo{end} = ''; for j=1:length(fn) if strcmp(fn{j},'ExternalFileName') [p,f,e] = fileparts(this.data{i}.attributes.(fn{j})); attval = [f e]; else attval = this.data{i}.attributes.(fn{j}); end fprintf(fid,'%s%s="%s"%s',oo{j,1},... fn{j},attval,sprintf(oo{j,2})); end fprintf(fid,'>\n'); % MetaData %---------------------------------------------------------------------- fprintf(fid,'%s<MetaData>\n',o(2)); for j=1:length(this.data{i}.metadata) fprintf(fid,'%s<MD>\n',o(3)); fprintf(fid,'%s<Name><![CDATA[%s]]></Name>\n',o(4),... this.data{i}.metadata(j).name); fprintf(fid,'%s<Value><![CDATA[%s]]></Value>\n',o(4),... this.data{i}.metadata(j).value); fprintf(fid,'%s</MD>\n',o(3)); end fprintf(fid,'%s</MetaData>\n',o(2)); % CoordinateSystemTransformMatrix %---------------------------------------------------------------------- for j=1:length(this.data{i}.space) fprintf(fid,'%s<CoordinateSystemTransformMatrix>\n',o(2)); fprintf(fid,'%s<DataSpace><![CDATA[%s]]></DataSpace>\n',o(3),... this.data{i}.space(j).DataSpace); fprintf(fid,'%s<TransformedSpace><![CDATA[%s]]></TransformedSpace>\n',o(3),... this.data{i}.space(j).TransformedSpace); fprintf(fid,'%s<MatrixData>%s</MatrixData>\n',o(3),... sprintf('%f ',this.data{i}.space(j).MatrixData)); fprintf(fid,'%s</CoordinateSystemTransformMatrix>\n',o(2)); end % Data (saved using MATLAB's ColumnMajorOrder) %---------------------------------------------------------------------- fprintf(fid,'%s<Data>',o(2)); tp = getdict; try tp = tp.(this.data{i}.attributes.DataType); catch error('[GIFTI] Unknown DataType.'); end switch this.data{i}.attributes.Encoding case 'ASCII' fprintf(fid, [tp.format ' '], this.data{i}.data); case 'Base64Binary' fprintf(fid,base64encode(typecast(this.data{i}.data(:),'uint8'))); % uses native machine format case 'GZipBase64Binary' fprintf(fid,base64encode(dzip(typecast(this.data{i}.data(:),'uint8')))); % uses native machine format case 'ExternalFileBinary' extfilename = this.data{i}.attributes.ExternalFileName; dat = this.data{i}.data; if isa(dat,'file_array') dat = subsref(dat,substruct('()',repmat({':'},1,numel(dat.dim)))); end if ~def.offset fide = fopen(extfilename,'w'); % uses native machine format else fide = fopen(extfilename,'a'); % uses native machine format end if fide == -1 error('Unable to write file %s: permission denied.',extfilename); end fseek(fide,0,1); fwrite(fide,dat,tp.class); def.offset = ftell(fide); fclose(fide); otherwise error('[GIFTI] Unknown data encoding.'); end fprintf(fid,'</Data>\n'); fprintf(fid,'%s</DataArray>\n',o(1)); end fprintf(fid,'</GIFTI>\n'); %========================================================================== % function fid = save_dae(fid,this) %========================================================================== function fid = save_dae(fid,this) o = @(x) blanks(x*3); % Split the mesh into connected components %-------------------------------------------------------------------------- s = struct(this); try C = spm_mesh_label(s.faces); d = []; for i=1:numel(unique(C)) d(i).faces = s.faces(C==i,:); u = unique(d(i).faces); d(i).vertices = s.vertices(u,:); a = 1:max(d(i).faces(:)); a(u) = 1:size(d(i).vertices,1); %a = sparse(1,double(u),1:1:size(d(i).vertices,1)); d(i).faces = a(d(i).faces); end s = d; end % Prolog & root of the Collada XML file %-------------------------------------------------------------------------- fprintf(fid,'<?xml version="1.0"?>\n'); fprintf(fid,'<COLLADA xmlns="http://www.collada.org/2008/03/COLLADASchema" version="1.5.0">\n'); % Assets %-------------------------------------------------------------------------- fprintf(fid,'%s<asset>\n',o(1)); fprintf(fid,'%s<contributor>\n',o(2)); fprintf(fid,'%s<author_website>%s</author_website>\n',o(3),... 'http://www.fil.ion.ucl.ac.uk/spm/'); fprintf(fid,'%s<authoring_tool>%s</authoring_tool>\n',o(3),spm('Ver')); fprintf(fid,'%s</contributor>\n',o(2)); fprintf(fid,'%s<created>%s</created>\n',o(2),datestr(now,'yyyy-mm-ddTHH:MM:SSZ')); fprintf(fid,'%s<modified>%s</modified>\n',o(2),datestr(now,'yyyy-mm-ddTHH:MM:SSZ')); fprintf(fid,'%s<unit name="millimeter" meter="0.001"/>\n',o(2)); fprintf(fid,'%s<up_axis>Z_UP</up_axis>\n',o(2)); fprintf(fid,'%s</asset>\n',o(1)); % Image, Materials, Effects %-------------------------------------------------------------------------- %fprintf(fid,'%s<library_images/>\n',o(1)); fprintf(fid,'%s<library_materials>\n',o(1)); for i=1:numel(s) fprintf(fid,'%s<material id="material%d" name="material%d">\n',o(2),i,i); fprintf(fid,'%s<instance_effect url="#material%d-effect"/>\n',o(3),i); fprintf(fid,'%s</material>\n',o(2)); end fprintf(fid,'%s</library_materials>\n',o(1)); fprintf(fid,'%s<library_effects>\n',o(1)); for i=1:numel(s) fprintf(fid,'%s<effect id="material%d-effect" name="material%d-effect">\n',o(2),i,i); fprintf(fid,'%s<profile_COMMON>\n',o(3)); fprintf(fid,'%s<technique sid="COMMON">\n',o(4)); fprintf(fid,'%s<lambert>\n',o(5)); fprintf(fid,'%s<emission>\n',o(6)); fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0 0 0 1]); fprintf(fid,'%s</emission>\n',o(6)); fprintf(fid,'%s<ambient>\n',o(6)); fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0 0 0 1]); fprintf(fid,'%s</ambient>\n',o(6)); fprintf(fid,'%s<diffuse>\n',o(6)); fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0.5 0.5 0.5 1]); fprintf(fid,'%s</diffuse>\n',o(6)); fprintf(fid,'%s<transparent>\n',o(6)); fprintf(fid,'%s<color>%d %d %d %d</color>\n',o(7),[1 1 1 1]); fprintf(fid,'%s</transparent>\n',o(6)); fprintf(fid,'%s<transparency>\n',o(6)); fprintf(fid,'%s<float>%f</float>\n',o(7),0); fprintf(fid,'%s</transparency>\n',o(6)); fprintf(fid,'%s</lambert>\n',o(5)); fprintf(fid,'%s</technique>\n',o(4)); fprintf(fid,'%s</profile_COMMON>\n',o(3)); fprintf(fid,'%s</effect>\n',o(2)); end fprintf(fid,'%s</library_effects>\n',o(1)); % Geometry %-------------------------------------------------------------------------- fprintf(fid,'%s<library_geometries>\n',o(1)); for i=1:numel(s) fprintf(fid,'%s<geometry id="shape%d" name="shape%d">\n',o(2),i,i); fprintf(fid,'%s<mesh>\n',o(3)); fprintf(fid,'%s<source id="shape%d-positions">\n',o(4),i); fprintf(fid,'%s<float_array id="shape%d-positions-array" count="%d">',o(5),i,numel(s(i).vertices)); fprintf(fid,'%f ',repmat(s(i).vertices',1,[])); fprintf(fid,'</float_array>\n'); fprintf(fid,'%s<technique_common>\n',o(5)); fprintf(fid,'%s<accessor count="%d" offset="0" source="#shape%d-positions-array" stride="3">\n',o(6),size(s(i).vertices,1),i); fprintf(fid,'%s<param name="X" type="float" />\n',o(7)); fprintf(fid,'%s<param name="Y" type="float" />\n',o(7)); fprintf(fid,'%s<param name="Z" type="float" />\n',o(7)); fprintf(fid,'%s</accessor>\n',o(6)); fprintf(fid,'%s</technique_common>\n',o(5)); fprintf(fid,'%s</source>\n',o(4)); fprintf(fid,'%s<vertices id="shape%d-vertices">\n',o(4),i); fprintf(fid,'%s<input semantic="POSITION" source="#shape%d-positions"/>\n',o(5),i); fprintf(fid,'%s</vertices>\n',o(4)); fprintf(fid,'%s<triangles material="material%d" count="%d">\n',o(4),i,size(s(i).faces,1)); fprintf(fid,'%s<input semantic="VERTEX" source="#shape%d-vertices" offset="0"/>\n',o(5),i); fprintf(fid,'%s<p>',o(5)); fprintf(fid,'%d ',repmat(s(i).faces',1,[])-1); fprintf(fid,'</p>\n'); fprintf(fid,'%s</triangles>\n',o(4)); fprintf(fid,'%s</mesh>\n',o(3)); fprintf(fid,'%s</geometry>\n',o(2)); end fprintf(fid,'%s</library_geometries>\n',o(1)); % Scene %-------------------------------------------------------------------------- fprintf(fid,'%s<library_visual_scenes>\n',o(1)); fprintf(fid,'%s<visual_scene id="VisualSceneNode" name="SceneNode">\n',o(2)); for i=1:numel(s) fprintf(fid,'%s<node id="node%d">\n',o(3),i); fprintf(fid,'%s<instance_geometry url="#shape%d">\n',o(4),i); fprintf(fid,'%s<bind_material>\n',o(5)); fprintf(fid,'%s<technique_common>\n',o(6)); fprintf(fid,'%s<instance_material symbol="material%d" target="#material%d"/>\n',o(7),i,i); fprintf(fid,'%s</technique_common>\n',o(6)); fprintf(fid,'%s</bind_material>\n',o(5)); fprintf(fid,'%s</instance_geometry>\n',o(4)); fprintf(fid,'%s</node>\n',o(3)); end fprintf(fid,'%s</visual_scene>\n',o(2)); fprintf(fid,'%s</library_visual_scenes>\n',o(1)); fprintf(fid,'%s<scene>\n',o(1)); fprintf(fid,'%s<instance_visual_scene url="#VisualSceneNode" />\n',o(2)); fprintf(fid,'%s</scene>\n',o(1)); % End of XML %-------------------------------------------------------------------------- fprintf(fid,'</COLLADA>\n'); %========================================================================== % function fid = save_idtf(fid,this) %========================================================================== function fid = save_idtf(fid,this) o = inline('blanks(x*3)'); s = struct(this); % Compute normals %-------------------------------------------------------------------------- if ~isfield(s,'normals') try s.normals = spm_mesh_normals(... struct('vertices',s.vertices,'faces',s.faces),true); catch s.normals = []; end end % Split the mesh into connected components %-------------------------------------------------------------------------- try C = spm_mesh_label(s.faces); d = []; try if size(s.cdata,2) == 1 && (any(s.cdata>1) || any(s.cdata<0)) mi = min(s.cdata); ma = max(s.cdata); s.cdata = (s.cdata-mi)/ (ma-mi); else end end for i=1:numel(unique(C)) d(i).faces = s.faces(C==i,:); u = unique(d(i).faces); d(i).vertices = s.vertices(u,:); d(i).normals = s.normals(u,:); a = 1:max(d(i).faces(:)); a(u) = 1:size(d(i).vertices,1); %a = sparse(1,double(u),1:1:size(d(i).vertices,1)); d(i).faces = a(d(i).faces); d(i).mat = s.mat; try d(i).cdata = s.cdata(u,:); if size(d(i).cdata,2) == 1 d(i).cdata = repmat(d(i).cdata,1,3); end end end s = d; end % FILE_HEADER %-------------------------------------------------------------------------- fprintf(fid,'FILE_FORMAT "IDTF"\n'); fprintf(fid,'FORMAT_VERSION 100\n\n'); % NODES %-------------------------------------------------------------------------- for i=1:numel(s) fprintf(fid,'NODE "MODEL" {\n'); fprintf(fid,'%sNODE_NAME "%s"\n',o(1),sprintf('Mesh%04d',i)); fprintf(fid,'%sPARENT_LIST {\n',o(1)); fprintf(fid,'%sPARENT_COUNT %d\n',o(2),1); fprintf(fid,'%sPARENT %d {\n',o(2),0); fprintf(fid,'%sPARENT_NAME "%s"\n',o(3),'<NULL>'); fprintf(fid,'%sPARENT_TM {\n',o(3)); I = s(i).mat; % eye(4); for j=1:size(I,2) fprintf(fid,'%s',o(4)); fprintf(fid,'%f ',I(:,j)'); fprintf(fid,'\n'); end fprintf(fid,'%s}\n',o(3)); fprintf(fid,'%s}\n',o(2)); fprintf(fid,'%s}\n',o(1)); fprintf(fid,'%sRESOURCE_NAME "%s"\n',o(1),sprintf('Mesh%04d',i)); %fprintf(fid,'%sMODEL_VISIBILITY "BOTH"\n',o(1)); fprintf(fid,'}\n\n'); end % NODE_RESOURCES %-------------------------------------------------------------------------- for i=1:numel(s) fprintf(fid,'RESOURCE_LIST "MODEL" {\n'); fprintf(fid,'%sRESOURCE_COUNT %d\n',o(1),1); fprintf(fid,'%sRESOURCE %d {\n',o(1),0); fprintf(fid,'%sRESOURCE_NAME "%s"\n',o(2),sprintf('Mesh%04d',i)); fprintf(fid,'%sMODEL_TYPE "MESH"\n',o(2)); fprintf(fid,'%sMESH {\n',o(2)); fprintf(fid,'%sFACE_COUNT %d\n',o(3),size(s(i).faces,1)); fprintf(fid,'%sMODEL_POSITION_COUNT %d\n',o(3),size(s(i).vertices,1)); fprintf(fid,'%sMODEL_NORMAL_COUNT %d\n',o(3),size(s(i).normals,1)); if ~isfield(s(i),'cdata') || isempty(s(i).cdata) c = 0; else c = size(s(i).cdata,1); end fprintf(fid,'%sMODEL_DIFFUSE_COLOR_COUNT %d\n',o(3),c); fprintf(fid,'%sMODEL_SPECULAR_COLOR_COUNT %d\n',o(3),0); fprintf(fid,'%sMODEL_TEXTURE_COORD_COUNT %d\n',o(3),0); fprintf(fid,'%sMODEL_BONE_COUNT %d\n',o(3),0); fprintf(fid,'%sMODEL_SHADING_COUNT %d\n',o(3),1); fprintf(fid,'%sMODEL_SHADING_DESCRIPTION_LIST {\n',o(3)); fprintf(fid,'%sSHADING_DESCRIPTION %d {\n',o(4),0); fprintf(fid,'%sTEXTURE_LAYER_COUNT %d\n',o(5),0); fprintf(fid,'%sSHADER_ID %d\n',o(5),0); fprintf(fid,'%s}\n',o(4)); fprintf(fid,'%s}\n',o(3)); fprintf(fid,'%sMESH_FACE_POSITION_LIST {\n',o(3)); fprintf(fid,'%d %d %d\n',s(i).faces'-1); fprintf(fid,'%s}\n',o(3)); fprintf(fid,'%sMESH_FACE_NORMAL_LIST {\n',o(3)); fprintf(fid,'%d %d %d\n',s(i).faces'-1); fprintf(fid,'%s}\n',o(3)); fprintf(fid,'%sMESH_FACE_SHADING_LIST {\n',o(3)); fprintf(fid,'%d\n',zeros(size(s(i).faces,1),1)); fprintf(fid,'%s}\n',o(3)); if c fprintf(fid,'%sMESH_FACE_DIFFUSE_COLOR_LIST {\n',o(3)); fprintf(fid,'%d %d %d\n',s(i).faces'-1); fprintf(fid,'%s}\n',o(3)); end fprintf(fid,'%sMODEL_POSITION_LIST {\n',o(3)); fprintf(fid,'%f %f %f\n',s(i).vertices'); fprintf(fid,'%s}\n',o(3)); fprintf(fid,'%sMODEL_NORMAL_LIST {\n',o(3)); fprintf(fid,'%f %f %f\n',s(i).normals'); fprintf(fid,'%s}\n',o(3)); if c fprintf(fid,'%sMODEL_DIFFUSE_COLOR_LIST {\n',o(3)); fprintf(fid,'%f %f %f\n',s(i).cdata'); fprintf(fid,'%s}\n',o(3)); end fprintf(fid,'%s}\n',o(2)); fprintf(fid,'%s}\n',o(1)); fprintf(fid,'}\n'); end
github
lcnhappe/happe-master
gifti.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/gifti/@gifti/gifti.m
3,728
utf_8
37f5d9e67cb8f5e79f2ac46e1486ffd0
function this = gifti(varargin) % GIfTI Geometry file format class % Geometry format under the Neuroimaging Informatics Technology Initiative % (NIfTI): % http://www.nitrc.org/projects/gifti/ % http://nifti.nimh.nih.gov/ %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id$ switch nargin case 0 this = giftistruct; this = class(this,'gifti'); case 1 if isa(varargin{1},'gifti') this = varargin{1}; elseif isstruct(varargin{1}) f = {'faces', 'face', 'tri' 'vertices', 'vert', 'pnt', 'cdata'}; ff = {'faces', 'faces', 'faces', 'vertices', 'vertices', 'vertices', 'cdata'}; [c, ia] = intersect(f,fieldnames(varargin{1})); if ~isempty(c) this = gifti; for i=1:length(c) this = subsasgn(this,... struct('type','.','subs',ff{ia(i)}),... varargin{1}.(c{i})); end elseif isempty(setxor(fieldnames(varargin{1}),... {'metadata','label','data'})) this = class(varargin{1},'gifti'); else error('[GIFTI] Invalid structure.'); end elseif ishandle(varargin{1}) this = struct('vertices',get(varargin{1},'Vertices'), ... 'faces', get(varargin{1},'Faces')); if ~isempty(get(varargin{1},'FaceVertexCData')); this.cdata = get(varargin{1},'FaceVertexCData'); end this = gifti(this); elseif isnumeric(varargin{1}) this = gifti; this = subsasgn(this,... struct('type','.','subs','cdata'),... varargin{1}); elseif ischar(varargin{1}) if size(varargin{1},1)>1 this = gifti(cellstr(varargin{1})); return; end [p,n,e] = fileparts(varargin{1}); if strcmpi(e,'.mat') try this = gifti(load(varargin{1})); catch error('[GIFTI] Loading of file %s failed.', varargin{1}); end elseif strcmpi(e,'.asc') || strcmpi(e,'.srf') this = read_freesurfer_file(varargin{1}); this = gifti(this); else this = read_gifti_file(varargin{1},giftistruct); this = class(this,'gifti'); end elseif iscellstr(varargin{1}) fnames = varargin{1}; this(numel(fnames)) = giftistruct; this = class(this,'gifti'); for i=1:numel(fnames) this(i) = gifti(fnames{i}); end else error('[GIFTI] Invalid object construction.'); end otherwise error('[GIFTI] Invalid object construction.'); end %========================================================================== function s = giftistruct s = struct(... 'metadata', ... struct(... 'name', {}, ... 'value', {} ... ), ... 'label', ... struct(... 'name', {}, ... 'index', {} ... ), ... 'data', ... struct(... 'attributes', {}, ... 'metadata', struct('name',{}, 'value',{}), ... 'space', {}, ... 'data', {} ... ) ... );
github
lcnhappe/happe-master
read_gifti_file.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/gifti/@gifti/private/read_gifti_file.m
6,604
utf_8
3e691fdd0839d8cfad3929e4e181a5c1
function this = read_gifti_file(filename, this) % Low level reader of GIfTI 1.0 files % FORMAT this = read_gifti_file(filename, this) % filename - XML GIfTI filename % this - structure with fields 'metaData', 'label' and 'data'. %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id$ % Import XML-based GIfTI file %-------------------------------------------------------------------------- try t = xmltree(filename); catch error('[GIFTI] Loading of XML file %s failed.', filename); end % Root element of a GIFTI file %-------------------------------------------------------------------------- if ~strcmp(get(t,root(t),'name'),'GIFTI') error('[GIFTI] %s is not a GIFTI 1.0 file.', filename); end attr = cell2mat(attributes(t,'get',root(t))); attr = cell2struct({attr.val},strrep({attr.key},':','___'),2); if ~all(ismember({'Version','NumberOfDataArrays'},fieldnames(attr))) error('[GIFTI] Missing mandatory attributes for GIFTI root element.'); end if str2double(attr.Version) ~= 1 warning('[GIFTI] Unknown specification version of GIFTI file (%s).',attr.Version); end nbData = str2double(attr.NumberOfDataArrays); % Read children elements %-------------------------------------------------------------------------- uid = children(t,root(t)); for i=1:length(uid) switch get(t,uid(i),'name') case 'MetaData' this.metadata = gifti_MetaData(t,uid(i)); case 'LabelTable' this.label = gifti_LabelTable(t,uid(i)); case 'DataArray' this.data{end+1} = gifti_DataArray(t,uid(i),filename); otherwise warning('[GIFTI] Unknown element "%s": ignored.',get(t,uid(i),'name')); end end if nbData ~= length(this.data) warning('[GIFTI] Mismatch between expected and effective number of datasets.'); end %========================================================================== function s = gifti_MetaData(t,uid) s = struct('name',{}, 'value',{}); c = children(t,uid); for i=1:length(c) for j=children(t,c(i)) s(i).(lower(get(t,j,'name'))) = get(t,children(t,j),'value'); end end %========================================================================== function s = gifti_LabelTable(t,uid) s = struct('name',{}, 'key',[], 'rgba',[]); c = children(t,uid); for i=1:length(c) a = attributes(t,'get',c(i)); s(1).rgba(i,1:4) = NaN; for j=1:numel(a) switch lower(a{j}.key) case {'key','index'} s(1).key(i) = str2double(a{j}.val); case 'red' s(1).rgba(i,1) = str2double(a{j}.val); case 'green' s(1).rgba(i,2) = str2double(a{j}.val); case 'blue' s(1).rgba(i,3) = str2double(a{j}.val); case 'alpha' s(1).rgba(i,4) = str2double(a{j}.val); otherwise end end s(1).name{i} = get(t,children(t,c(i)),'value'); end %========================================================================== function s = gifti_DataArray(t,uid,filename) s = struct(... 'attributes', {}, ... 'data', {}, ... 'metadata', struct([]), ... 'space', {} ... ); attr = cell2mat(attributes(t,'get',uid)); s(1).attributes = cell2struct({attr.val},{attr.key},2); s(1).attributes.Dim = []; for i=1:str2double(s(1).attributes.Dimensionality) f = sprintf('Dim%d',i-1); s(1).attributes.Dim(i) = str2double(s(1).attributes.(f)); s(1).attributes = rmfield(s(1).attributes,f); end s(1).attributes = rmfield(s(1).attributes,'Dimensionality'); if isfield(s(1).attributes,'ExternalFileName') && ... ~isempty(s(1).attributes.ExternalFileName) s(1).attributes.ExternalFileName = fullfile(fileparts(filename),... s(1).attributes.ExternalFileName); end c = children(t,uid); for i=1:length(c) switch get(t,c(i),'name') case 'MetaData' s(1).metadata = gifti_MetaData(t,c(i)); case 'CoordinateSystemTransformMatrix' s(1).space(end+1) = gifti_Space(t,c(i)); case 'Data' s(1).data = gifti_Data(t,c(i),s(1).attributes); otherwise error('[GIFTI] Unknown DataArray element "%s".',get(t,c(i),'name')); end end %========================================================================== function s = gifti_Space(t,uid) s = struct('DataSpace','', 'TransformedSpace','', 'MatrixData',[]); for i=children(t,uid) s.(get(t,i,'name')) = get(t,children(t,i),'value'); end s.MatrixData = reshape(str2num(s.MatrixData),4,4)'; %========================================================================== function d = gifti_Data(t,uid,s) tp = getdict; try tp = tp.(s.DataType); catch error('[GIFTI] Unknown DataType.'); end [unused,unused,mach] = fopen(1); sb = @(x) x; try if (strcmp(s.Endian,'LittleEndian') && ~isempty(strmatch('ieee-be',mach))) ... || (strcmp(s.Endian,'BigEndian') && ~isempty(strmatch('ieee-le',mach))) sb = @swapbyte; end catch % Byte Order can be absent if encoding is ASCII, assume native otherwise end switch s.Encoding case 'ASCII' d = sscanf(get(t,children(t,uid),'value'),tp.format); case 'Base64Binary' d = typecast(sb(base64decode(get(t,children(t,uid),'value'))), tp.cast); case 'GZipBase64Binary' d = typecast(dunzip(sb(base64decode(get(t,children(t,uid),'value')))), tp.cast); case 'ExternalFileBinary' [p,f,e] = fileparts(s.ExternalFileName); if isempty(p) s.ExternalFileName = fullfile(pwd,[f e]); end if false fid = fopen(s.ExternalFileName,'r'); if fid == -1 error('[GIFTI] Unable to read binary file %s.',s.ExternalFileName); end fseek(fid,str2double(s.ExternalFileOffset),0); d = sb(fread(fid,prod(s.Dim),['*' tp.class])); fclose(fid); else d = file_array(s.ExternalFileName, s.Dim, tp.class, ... str2double(s.ExternalFileOffset),1,0,'rw'); end otherwise error('[GIFTI] Unknown data encoding: %s.',s.Encoding); end if length(s.Dim) == 1, s.Dim(end+1) = 1; end switch s.ArrayIndexingOrder case 'RowMajorOrder' d = permute(reshape(d,fliplr(s.Dim)),length(s.Dim):-1:1); case 'ColumnMajorOrder' d = reshape(d,s.Dim); otherwise error('[GIFTI] Unknown array indexing order.'); end
github
lcnhappe/happe-master
isintent.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/gifti/@gifti/private/isintent.m
2,477
utf_8
611bd4b3bf09d89f88da3652cc8e6320
function [a, b] = isintent(this,intent) % Correspondance between fieldnames and NIfTI intent codes % FORMAT ind = isintent(this,intent) % this - GIfTI object % intent - fieldnames % a - indices of found intent(s) % b - indices of dataarrays of found intent(s) %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id$ a = []; b = []; if ischar(intent), intent = cellstr(intent); end for i=1:length(this(1).data) switch this(1).data{i}.attributes.Intent(14:end) case 'POINTSET' [tf, loc] = ismember('vertices',intent); if tf a(end+1) = loc; b(end+1) = i; end [tf, loc] = ismember('mat',intent); if tf a(end+1) = loc; b(end+1) = i; end case 'TRIANGLE' [tf, loc] = ismember('faces',intent); if tf a(end+1) = loc; b(end+1) = i; end case 'VECTOR' [tf, loc] = ismember('normals',intent); if tf a(end+1) = loc; b(end+1) = i; end case cdata [tf, loc] = ismember('cdata',intent); if tf a(end+1) = loc; b(end+1) = i; end if strcmp(this(1).data{i}.attributes.Intent(14:end),'LABEL') [tf, loc] = ismember('labels',intent); if tf a(end+1) = loc; b(end+1) = i; end end otherwise fprintf('Intent %s is ignored.\n',this.data{i}.attributes.Intent); end end %[d,i] = unique(a); %if length(d) < length(a) % warning('Several fields match intent type. Using first.'); % a = a(i); % b = b(i); %end function c = cdata c = { 'NONE' 'CORREL' 'TTEST' 'FTEST' 'ZSCORE' 'CHISQ' 'BETA' 'BINOM' 'GAMMA' 'POISSON' 'NORMAL' 'FTEST_NONC' 'CHISQ_NONC' 'LOGISTIC' 'LAPLACE' 'UNIFORM' 'TTEST_NONC' 'WEIBULL' 'CHI' 'INVGAUSS' 'EXTVAL' 'PVAL' 'LOGPVAL' 'LOG10PVAL' 'ESTIMATE' 'LABEL' 'NEURONAMES' 'GENMATRIX' 'SYMMATRIX' 'DISPVECT' 'QUATERNION' 'DIMLESS' 'TIME_SERIES' 'RGB_VECTOR' 'RGBA_VECTOR' 'NODE_INDEX' 'SHAPE' 'CONNECTIVITY_DENSE' 'CONNECTIVITY_DENSE_TIME' 'CONNECTIVITY_PARCELLATED' 'CONNECTIVITY_PARCELLATED_TIME' 'CONNECTIVITY_CONNECTIVITY_TRAJECTORY' };
github
lcnhappe/happe-master
sb_rhs_venant.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/simbio/sb_rhs_venant.m
1,317
utf_8
2a6743d0e11f6cd5ca8bc3f2a5bab884
function rhs = sb_rhs_venant(pos,dir,vol); % SB_RHS_VENANT % % $Id$ %find node closest to source position next_nd = sb_get_next_nd(pos,vol.pos); %find nodes neighbouring closest node if isfield(vol,'tet') ven_nd = sb_get_ven_nd(next_nd,vol.tet); elseif isfield(vol,'hex') ven_nd = sb_get_ven_nd(next_nd,vol.hex); else error('No connectivity information given!'); end %calculate rhs matrix loads = sb_calc_ven_loads(pos,dir,ven_nd,vol.pos); %assign values in sparse matrix i = reshape(ven_nd',[],1); j = reshape(repmat([1:size(ven_nd,1)],size(ven_nd,2),1),[],1); loads = reshape(loads',[],1); j = j(i~=0); loads = loads(i~=0); i = i(i~=0); rhs = sparse(i,j,loads,size(vol.pos,1),size(pos,1)); end function next_nd = sb_get_next_nd(pos,node); next_nd = zeros(size(pos,1),1); for i=1:size(pos,1) [dist, next_nd(i)] = min(sum(bsxfun(@minus,node,pos(i,:)).^2,2)); end end function ven_nd = sb_get_ven_nd(next_nd,elem); ven_nd = zeros(size(next_nd,1),1); for i=1:size(next_nd,1) [tmp1,tmp2] = find(elem == next_nd(i)); tmp = unique(elem(tmp1,:)); %tmp = tmp(tmp~=next_nd(i)); seems like this is not done in the %original. if(length(tmp) > size(ven_nd,2)) ven_nd = [ven_nd, zeros(size(ven_nd,1),length(tmp)-size(ven_nd,2))]; end ven_nd(i,1:length(tmp)) = tmp; end end
github
lcnhappe/happe-master
netcdf.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/netcdf/netcdf.m
5,097
utf_8
3cc73e65d1ed73e0a6836af118228033
function S = netcdf(File,varargin) % Function to read NetCDF files % S = netcdf(File) % Input Arguments % File = NetCDF file to read % Optional Input Arguments: % 'Var',Var - Read data for VarArray(Var), default [1:length(S.VarArray)] % 'Rec',Rec - Read data for Record(Rec), default [1:S.NumRecs] % Output Arguments: % S = Structure of NetCDF data organised as per NetCDF definition % Notes: % Only version 1, classic 32bit, NetCDF files are supported. By default % data are extracted into the S.VarArray().Data field for all variables. % To read the header only call S = netcdf(File,'Var',[]); % % SEE ALSO % --------------------------------------------------------------------------- S = []; try if exist(File,'file') fp = fopen(File,'r','b'); else fp = []; error('File not found'); end if fp == -1 error('Unable to open file'); end % Read header Magic = fread(fp,4,'uint8=>char'); if strcmp(Magic(1:3),'CDF') error('Not a NetCDF file'); end if uint8(Magic(4))~=1 error('Version not supported'); end S.NumRecs = fread(fp,1,'uint32=>uint32'); S.DimArray = DimArray(fp); S.AttArray = AttArray(fp); S.VarArray = VarArray(fp); % Setup indexing to arrays and records Var = ones(1,length(S.VarArray)); Rec = ones(1,S.NumRecs); for i = 1:2:length(varargin) if strcmp(upper(varargin{i}),'VAR') Var=Var*0; Var(varargin{i+1})=1; elseif strcmp(upper(varargin{i}),'REC') Rec=Rec*0; Rec(varargin{i+1})=1; else error('Optional input argument not recognised'); end end if sum(Var)==0 fclose(fp); return; end % Read non-record variables Dim = double(cat(2,S.DimArray.Dim)); ID = double(cat(2,S.VarArray.Type)); for i = 1:length(S.VarArray) D = Dim(S.VarArray(i).DimID+1); N = prod(D); RecID{i}=find(D==0); if isempty(RecID{i}) if length(D)==0 D = [1,1]; N = 1; elseif length(D)==1 D=[D,1]; end if Var(i) S.VarArray(i).Data = ReOrder(fread(fp,N,[Type(ID(i)),'=>',Type(ID(i))]),D); fread(fp,(Pad(N,ID(i))-N)*Size(ID(i)),'uint8=>uint8'); else fseek(fp,Pad(N,ID(i))*Size(ID(i)),'cof'); end else S.VarArray(i).Data = []; end end % Read record variables for k = 1:S.NumRecs for i = 1:length(S.VarArray) if ~isempty(RecID{i}) D = Dim(S.VarArray(i).DimID+1); D(RecID{i}) = 1; N = prod(D); if length(D)==1 D=[D,1]; end if Var(i) & Rec(k) S.VarArray(i).Data = cat(RecID{i},S.VarArray(i).Data,... ReOrder(fread(fp,N,[Type(ID(i)),'=>',Type(ID(i))]),D)); if N > 1 fread(fp,(Pad(N,ID(i))-N)*Size(ID(i)),'uint8=>uint8'); end else fseek(fp,Pad(N,ID(i))*Size(ID(i)),'cof'); end end end end fclose(fp); catch Err = lasterror; fprintf('%s\n',Err.message); if ~isempty(fp) && fp ~= -1 fclose(fp); end end % --------------------------------------------------------------------------------------- % Utility functions function S = Size(ID) % Size of NetCDF data type, ID, in bytes S = subsref([1,1,2,4,4,8],struct('type','()','subs',{{ID}})); function T = Type(ID) % Matlab string for CDF data type, ID T = subsref({'int8','char','int16','int32','single','double'},... struct('type','{}','subs',{{ID}})); function N = Pad(Num,ID) % Number of elements to read after padding to 4 bytes for type ID N = (double(Num) + mod(4-double(Num)*Size(ID),4)/Size(ID)).*(Num~=0); function S = String(fp) % Read a CDF string; Size,[String,[Padding]] S = fread(fp,Pad(fread(fp,1,'uint32=>uint32'),1),'uint8=>char').'; function A = ReOrder(A,S) % Rearrange CDF array A to size S with matlab ordering A = permute(reshape(A,fliplr(S)),fliplr(1:length(S))); function S = DimArray(fp) % Read DimArray into structure if fread(fp,1,'uint32=>uint32') == 10 % NC_DIMENSION for i = 1:fread(fp,1,'uint32=>uint32') S(i).Str = String(fp); S(i).Dim = fread(fp,1,'uint32=>uint32'); end else fread(fp,1,'uint32=>uint32'); S = []; end function S = AttArray(fp) % Read AttArray into structure if fread(fp,1,'uint32=>uint32') == 12 % NC_ATTRIBUTE for i = 1:fread(fp,1,'uint32=>uint32') S(i).Str = String(fp); ID = fread(fp,1,'uint32=>uint32'); Num = fread(fp,1,'uint32=>uint32'); S(i).Val = fread(fp,Pad(Num,ID),[Type(ID),'=>',Type(ID)]).'; end else fread(fp,1,'uint32=>uint32'); S = []; end function S = VarArray(fp) % Read VarArray into structure if fread(fp,1,'uint32=>uint32') == 11 % NC_VARIABLE for i = 1:fread(fp,1,'uint32=>uint32') S(i).Str = String(fp); Num = double(fread(fp,1,'uint32=>uint32')); S(i).DimID = double(fread(fp,Num,'uint32=>uint32')); S(i).AttArray = AttArray(fp); S(i).Type = fread(fp,1,'uint32=>uint32'); S(i).VSize = fread(fp,1,'uint32=>uint32'); S(i).Begin = fread(fp,1,'uint32=>uint32'); % Classic 32 bit format only end else fread(fp,1,'uint32=>uint32'); S = []; end
github
lcnhappe/happe-master
writeCPersist.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/ctf/writeCPersist.m
5,086
utf_8
0c56dc571aa56100f050678e5fe815ff
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% Function writeCPersist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function writeCPersist(filename,Tag) % Version 1.2 24 April 2007. Removed terminating null characters from charatcer strings % types 10,11) % Version 1.1 13 April 2007 % Write a CTF CPersist file. See document CTF MEG File Format, PN900-0066 % Inputs : filename : Name of the output file name including path % Tag: Structure array containing all of the tags, types, and data. % 31 Aug 2006: Recognizes type=1,...,17. If other data types are specified, % writeCPersist will print an error message. % Delete existing file so the new file has the correct creation data/time. if nargin==0 fprintf(['writeCPersist: Version 1.2 24 April 2007 Writes a CTF CPersist file.\n'... '\twriteCPersist(filename,Tag) writes a CPersist file from the contents of\n',... '\tstructure array Tag. Tag is in the format prepared by readCPersist.\n\n']); Tag=[]; return end if exist(filename)==2 delete(filename); end startString='WS1_'; EOFstring='EndOfParameters'; startVal=256.^[3:-1:0]*double(startString)'; % Integer version of startString fid=fopen(filename,'w','ieee-be'); EOFcount=0; % Make sure that the startString's and EOFstring's balance count=0; while count<length(Tag) count=count+1; if strcmp(Tag(count).name,startString) % start of Cpersist object fwrite(fid,startVal,'int32'); EOFcount=EOFcount-1; continue end fwrite(fid,length(Tag(count).name),'int32'); % end of CPersist object fwrite(fid,Tag(count).name,'char'); if strcmp(Tag(count).name,EOFstring); EOFcount=EOFcount+1; continue; end fwrite(fid,Tag(count).type,'int32'); if Tag(count).type==1 fwrite(fid,Tag(count).data,'int32'); elseif Tag(count).type==2 % Start embedded CPersist object elseif Tag(count).type==3 % binary list fwrite(fid,2*length(Tag(count).data),'int32'); fwrite(fid,Tag(count).data,'int16'); elseif Tag(count).type==4 % double fwrite(fid,Tag(count).data,'float64'); elseif Tag(count).type==5 % integer fwrite(fid,Tag(count).data,'int32'); elseif Tag(count).type==6 % short integer fwrite(fid,Tag(count).data,'int16'); elseif Tag(count).type==7 % unsigned short integer fwrite(fid,Tag(count).data,'uint16'); elseif Tag(count).type==8 % Boolean byte fwrite(fid,Tag(count).data,'uint8'); elseif Tag(count).type==9; % CStr32 nChar=min(32,length(Tag(count).data)); fwrite(fid,[double(Tag(count).data(1:nChar)) zeros(1,32-nChar)],'uint8'); elseif Tag(count).type==10; % CString fwrite(fid,length(Tag(count).data),'int32'); fwrite(fid,double(Tag(count).data),'uint8'); elseif Tag(count).type==11; % Cstring list. nList=size(Tag(count).data,1); fwrite(fid,nList,'int32'); for k=1:nList % Do not force termination of strings with nulls (char(0)) Cstring=[deblank(Tag(count).data(k,:))]; fwrite(fid,length(Cstring),'int32'); fwrite(fid,double(Cstring),'uint8'); end clear k CString nList; elseif Tag(count).type==12; % CStr32 list. nList=size(Tag(count).data,1); %size(data)=[nList 32] fwrite(fid,nList,'int32'); % Do not force termination of strings with nulls (char(0)) for k=1:nList strng=deblank(Tag(count).data(k,:)); nChar=min(32,length(strng)); Tag(count).data(k,:)=[strng(1:nChar) char(zeros(1,32-nChar))]; end fwrite(fid,double(Tag(count).data)','uint8'); clear k strng nChar nList; elseif Tag(count).type==13; % SensorClass list. fwrite(fid,length(Tag(count).data),'int32'); fwrite(fid,Tag(count).data,'int32') elseif Tag(count).type==14 % long integer fwrite(fid,Tag(count).data,'int32'); elseif Tag(count).type==15 % unsigned longinteger fwrite(fid,Tag(count).data,'uint32'); elseif Tag(count).type==16 % unsigned integer fwrite(fid,Tag(count).data,'uint32'); elseif Tag(count).type==17 % Boolean if ~any(Tag(count).data==[0 1]) fprintf('writeCPersist: tagname=%s type=%d value=%d? (Must =0 or 1)\n',... tagname,type,Tag(count).data); Tag(count).data=(Tag(count).data~=0); fprintf(' Set value=%d.\n',Tag(count).data); end fwrite(fid,Tag(count).data,'int32'); else fprintf('writeCPersist: Tag(%d) name=%s type=%d\n',count,Tag(count).name,Tag(count).type); fprintf('\t\t UNRECOGNIZED type.\n'); fclose(fid); break; end end % Loop over tags fclose(fid); % EOF_count should be zero at the end of the file if EOFcount~=0; fprintf('write_CPerist: EOFcount=%d Stop strings do not balance start strings.\n',... EOFcount); fprintf(' Start string=%s Stop string=%s\n',startString,EOFstring); end return %%%%%%%% End of writeCPersist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
lcnhappe/happe-master
getCTFBalanceCoefs.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/ctf/getCTFBalanceCoefs.m
20,490
utf_8
2c434fcbdb53fbc50ee3fbda72e98883
function [alphaMEG,MEGindex,MEGbalanceindex,alphaGref,Grefindex,Gbalanceindex]=... getCTFBalanceCoefs(ds,balanceType,unit); % Reads balance coefficients for SQUID data in phi0's, and converts to coefficients % for data in physical units. % Input : ds : (1) ds structure from readCTFds % balanceType : 'NONE' : No balancing % 'G1BR' : 1st order balancing % 'G2BR' : 2nd order balancing % 'G3BR' : 3rd order balancing % 'G3AR' : 3rd order balancing + adaptive % If only MEG balance table is requested, size(balanceType)=[1 5] % If Gref balance table is requested also, size(balanceType)=[2 4] % unit: Type of units. Option: 'fT','T','phi0','int'. % If unit is not entered, of unit=[], the default is unit='fT'. % Outputs : % alphaMEG,MEGindex,MEGbalanceindex : MEG balancing coefficients for data in fT or T. % Suppose data array returned by getTrial2 has size(data)=[npt nchan]. % nMEG = number of MEG channels in the data set. % MEG channels have sensorTypeIndex==5. % % MEGindex = list of MEG channels referred to the channel numbering in % the complete dataset (i.e. it is not referred to only the list of % SQUID sensors). % by looking for sensors with ds.res4.senres.sensorTypeIndex==5 % size(MEGindex)=[1 nMEG] % MEG data = data(:,MEGindex) % MEGbalanceindex = list of reference channels for MEG balancing. % size(MEGbalanceindex)=[1 nRef] % Reference data for MEG balancing = data(:,MEGbalanceindex) % alphaMEG = balance coefficients. size(alphaMEG)=[nRef nMEG] % % Balancing MEG data : % - Start with data AFTER converting to physical units. % (I.e. SQUID data must be in fT or T.) % - balanced_data(:,MEGindex)=data(:,MEGindex)-data(:,MEGbalanceindex)*alphaMEG % If user specifies balanceType=[], ' ' or 'none', then getCTFBalanceCoefs returns % alphaMEG=zeros(0,nMEG), MEGindex=list of MEG sensor channels, % MEGbalanceindex=[], alphaGref=zeros(0,nGef), Grefindex=list of Gref channels % and Gbalanceindex=[]; % alphaGref,Grefindex,Gbalanceindex : Reference-gradiometer balancing coeficients. % These output arrays are optional. If the calling statement includes % them, then this program extracts a table of balance coefficients for % the reference gradiometers from the G1BR table in the coefficient files. % nGref = no. of reference gradiometers channels in the data set % (sensorTypeIndex=1) % Grefindex = list of reference channels. size(Grefindex)=[1 nGref] % Gradient reference data = data(:,Grefindex) % Gbalanceindex = list of channels for balancing reference % gradiometers. size(Gbalanceindex)=[1 nGbalcoef] % Balancing reference data = data(:,Gbalanceindex) % alphaGref = balance coefficients for ref. grads. % size(alphaGref)=[nGbalcoef nGref] % % Balancing ref. gradiometer data : % - Use data AFTER converting to physical units. (I.e. data in fT or T.) % balanced_data(:,Grefindex)=data(:,Grefindex)-data(:,Gbalanceindex)*alphaGref % Calls function getRawCTFBalanceCoefs (included in this listing). if nargout==0 & nargin==0 fprintf(['\ngetCTFBalanceCoefs: Version 1.1 17 April 2007 ',... 'Reads balance coefficients from ds.res4.scrr.\n\n',... '\tMEG balancing : [alphaMEG,MEGindex,MEGbalanceindex]=',... 'getCTFBalanceCoefs(ds,balanceType,unit);\n\n',... '\tMEG & Gref balancing : [alphaMEG,MEGindex,MEGbalanceindex,',... 'alphaGref,Grefindex,Gbalanceindex]=\n',... '\t ',... 'getCTFBalanceCoefs(ds,balanceType,unit);\n\n']); return end balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR', 'G3AR'); balanceOptionsEnds = [size(balanceOptions, 1), 2]; % Which options are available for MEGs and Grefs. physical_options=strvcat('fT','T'); raw_options=strvcat('phi0','int'); unit_options=strvcat(physical_options,raw_options); default_unit='fT'; % Specify outputs in case of an early return due to an error. MEGindex=[]; Grefindex=[]; alphaMEG=[]; MEGbalanceindex=[]; alphaGref=[]; Gbalanceindex=[]; % Check that the inputs are sensible. if nargin<2 fprintf(['\ngetCTFBalanceCoefs: Only %d input arguments? ',... 'Must specify at least ds and balanceType.\n\n'],nargin); return elseif ~isstruct(ds) | isempty(ds) | ~ischar(balanceType) | isempty(balanceType) fprintf('\ngetCTFBalanceCoefs: Wrong argument types or sizes.\n\n'); whos ds balanceType return elseif ~isfield(ds,'res4') fprintf('\ngetCTFBalanceCoefs: Field res4 is missing from structure ds.\n\n'); ds return elseif size(balanceType,1)>2 fprintf('\ngetCTFBalanceCoefs: size(balanceType)=[');fprintf(' %d',size(balanceType));... fprintf('] Must be[1 4] or [2 4].\n\n'); return end % Must have 3 or 6 output arguments. Set balanceType(2,:)='NONE' if necessary. if ~any(nargout==[3 6]); fprintf(['\ngetCTFBalanceCoefs: Called with %d output arguments. ',... 'Must be 3 or 6.\n\n'],nargout); return elseif (nargout==3 & size(balanceType,1)>1) | (nargout==6 & size(balanceType,1)==1) balanceType=strvcat(deblank(balanceType(1,:)),'NONE'); end % At this point, size(balanceType,1)=2. % Check that balanceType has allowed values for k=1:size(balanceType,1) % k=1:MEGs, k=2:Grefs if isempty(strmatch(balanceType(k,:),balanceOptions(1:balanceOptionsEnds(k),:))) fprintf('\ngetCTFBalanceCoefs: balanceType(%d,:)=%s Not an allowed option.\n\n',... k,balanceType(k,:)); return end end % Check the data units, convert to lower case and flag incorrect unit specification if ~exist('unit'); unit=default_unit; elseif isempty(unit); unit=default_unit; elseif ~ischar(unit) fprintf('\ngetCTFBalanceCoefs: Input unit has the wrong type: class(unit)=%s\n\n',... class(unit)); return end unit=lower(unit); if isempty(strmatch(unit,lower(strvcat(physical_options,raw_options)))) fprintf('\ngetCTFBalanceCoefs: unit=%s. Must be one of ',unit); for k=1:size(unit_options,1);fprintf(' %s,',deblank(unit_options(k,:)));end; fprintf('\n\n'); return end physical=~isempty(strmatch(unit,lower(physical_options))); balanceType=upper(deblank(balanceType)); [betaMEG,MEGindex,MEGbalanceindex,betaGref,Grefindex,Gbalanceindex]=... getRawCTFBalanceCoefs(ds,balanceType); % No balancing is requested, just return lists of MEGindex and Grefindex. if isempty(MEGbalanceindex) alphaMEG=zeros(0,length(MEGindex)); MEGbalanceindex=[]; % force size=[0 0] end if isempty(Gbalanceindex) alphaGref=zeros(0,length(Grefindex)); Gbalanceindex=[]; % force size=[0 0] end if isempty(MEGbalanceindex) & isempty(Gbalanceindex) return end % betaMEG and betaGref are the balance coefficients when signals are in phi0's. % Convert to balance coefficients when signals are in physical units (T or fT). % invproperGain is introduced to take care of situations where bad channels % are labelled by setting their gain to zero. if physical properGain=zeros(1,ds.res4.no_channels); invproperGain=zeros(1,ds.res4.no_channels); for k=1:ds.res4.no_channels if any(ds.res4.senres(k).sensorTypeIndex==[0 1 5:7]) % SQUIDs only properGain(k)=ds.res4.senres(k).properGain; % properGain = phi0/T if properGain(k)~=0 invproperGain(k)=1/properGain(k); end end end end if ~isempty(MEGbalanceindex) if physical alphaMEG=betaMEG.*(properGain(MEGbalanceindex)'*invproperGain(MEGindex)); else alphaMEG=betaMEG; end end if ~isempty(Gbalanceindex) if physical alphaGref=betaGref.*(properGain(Gbalanceindex)'*invproperGain(Grefindex)); else alphaGref=betaGref; end end return %%%%%%%%%%% End of getBalanceCoef %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%% Function getRawCTFBalanceCoefs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [betaMEG,MEGindex,Refindex,betaGref,Grefindex,Gbalanceindex]=... getRawCTFBalanceCoefs(ds,balanceType); % getRawCTFBalanceCoefs. Extracts raw-data (i.e. integer data) gradiometer balancing % coefficients from structure array ds.res4.scrr (ds is produced % by readCTFds). % Date : 24 OCt 2006 % Author : Harold Wilson % Inputs : ds : Structure returned by readCTFds. % balanceType : 'NONE' : No balancing % 'G1BR' : 1st order balancing % 'G2BR' : 2nd order balancing % 'G3BR' : 3rd order balancing % 'G3AR' : 3rd order balancing + adaptive % If only MEG balance table is requested, size(balanceType)=[1 4] % If Gref balance table is requested also, size(balanceType)=[2 4] % If balancing 'NONE' is specified, getRawCTFBalanceCoefs returns lists MEGindex and % Grefindex, and sets Refindex=[], Gbalanceindex=[]. % The reference gradiometers have only G1BR balancing coefficients. % Outputs : % betaMEG,MEGindex,Refindex : MEG balancing coefficients. % Suppose data array returned by getCTFdata has size(data)=[npt nchan]. % nMEG = number of MEG channels in the data set. % MEG channels have sensorTypeIndex==5. % % MEGindex = list of MEG channels in the data set. It is assembled % by looking for sensors with ds.res4.senres.sensorTypeIndex==5 % size(MEGindex)=[1 nMEG] % MEG data = data(:,MEGindex) % Refindex = list of reference channels for MEG balancing. % size(Refindex)=[1 nRef] % Reference data = data(:,Refindex) % betaMEG = balance coefficients. size(betaMEG)=[nRef nMEG] % % Balancing MEG data : % - Start with data BEFORE converting to physical units. % (I.e. SQUID data must be in phi0's or raw integers.) % - balanced_data(:,MEGindex)=data(:,MEGindex)-data(:,Refindex)*betaMEG % If user specifies balanceType=[] or ' ', then getRawCTFBalanceCoefs returns % betaMEG=zeros(1,nMEG),Refindex=3 and nRef=1; % betaGref,Grefindex,Gbalanceindex : Reference-gradiometer balancing coeficients. % These output arrays are optional. If the calling statement includes % them, then this program extracts a table of balance coefficients for % the reference gradiometers from the G1BR table in the coefficient files. % nGref = no. of reference gradiometers channels in the data set % (sensorTypeIndex=1) % Grefindex = list of reference channels. size(Grefindex)=[1 nGref] % Gradient reference data = data(:,Grefindex) % Gbalanceindex = list of channels for balancing reference % gradiometers. size(Gbalanceindex)=[1 nGbalcoef] % Balancing reference data = data(:,Gbalanceindex) % betaGref = balance coefficients for ref. grads. % size(betaGref)=[nGbalcoef nGref] % % Balancing ref. gradiometer data : % balanced_data(:,Grefindex)=data(:,Grefindex)-data(:,Gbalanceindex)*betaGref % No function calls. missingMEGMessage=0; missingGrefMessage=0; balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR', 'G3AR'); balanceOptionsEnds = [size(balanceOptions, 1), 2]; % Which options are available for MEGs and Grefs. common_mode_only=0; Brefindex=[]; % Index list of reference magnetometers in the data arrays Grefindex=[]; % Index list of reference gradiometers in the data arrays MEGindex=[]; % Index list of MEG sensors in the data arrays Gbalanceindex=[]; % Index list of sensors used as references to balance the reference % gradiometers Refindex=[]; % Index list of sensors used to balance the MEG sensors betaMEG=[]; betaGref=[]; % Check that the inputs are sensible. if nargin<2 fprintf(['\ngetRawCTFBalanceCoefs: Only %d input arguments? ',... 'Must specify at least ds and balance.\n\n'],nargin); return elseif ~isstruct(ds) | isempty(ds) | ~ischar(balanceType) | isempty(balanceType) fprintf('\ngetRawCTFBalanceCoefs: Wrong argument types or sizes.\n\n'); whos ds balanceType return elseif ~isfield(ds,'res4') fprintf('\ngetRawCTFBalanceCoefs: Field res4 is missing from structure ds.\n\n'); ds return end % Check that the output list is OK. if nargout~=3 & nargout~=6 fprintf('\ngetRawCTFBalanceCoefs : Call specifies %d output arguments.\n',nargout); fprintf('\t\tMust have 3 output arguments (MEG balance coefficients)\n'); fprintf('\t\tor 6 output arguments (reference gradiometer balancing also).\n\n'); return elseif nargout==3 if size(balanceType,1)>1;balanceType=balanceType(1,:);end else if size(balanceType,1)==1;balanceType=strvcat(balanceType,'NONE');end end % Check that balanceType has allowed values for k=1:size(balanceType,1) % k=1:MEGs, k=2:Grefs if isempty(strmatch(balanceType(k,:),balanceOptions(1:balanceOptionsEnds(k),:))) fprintf('\ngetRawCTFBalanceCoefs: balance(%d,:)=%s Not an allowed option.\n\n',... k,balanceType(k,:)); return end end % Make lists of reference magnetometers, reference gradiometers and MEG sensors. for q=1:length(ds.res4.senres) if ds.res4.senres(q).sensorTypeIndex==0 Brefindex=[Brefindex q]; elseif ds.res4.senres(q).sensorTypeIndex==1 Grefindex=[Grefindex q]; elseif ds.res4.senres(q).sensorTypeIndex==5 % Allow other MEG sensors? MEGindex=[MEGindex q]; end end nBref=length(Brefindex); % Don't currently use Brefindex or nBref nGref=length(Grefindex); nMEG=length(MEGindex); nGbalcoef=0; % Set to zero until we know the number by examining ds.res4.scrr if nargout==6 & strcmp(balanceType(2,:),'NONE') Gbalanceindex=[]; betaGref=zeros(0,nGref); elseif nargout==6 & ~strcmp(balanceType(2,:),'NONE') m1=1; % Get coefficients for balancing the reference gradiometers. mtot=size(ds.res4.scrr,2); for n=1:nGref Gname=strtok(ds.res4.chanNames(Grefindex(n),:),['- ',char(0)]); nGchar=length(Gname); for m=[m1:mtot 1:(m1-1)] if strncmp(Gname,char(ds.res4.scrr(m).sensorName),nGchar) & ... strcmp('G1BR',char(ds.res4.scrr(m).coefType)); if nGbalcoef<=0 % 1st match. Initialize table and get list of references nGbalcoef=ds.res4.scrr(m).numcoefs; betaGref=zeros(nGbalcoef,nGref); % Assemble index array for balancing the reference gradiometers for q=1:nGbalcoef Refname=strtok(char(ds.res4.scrr(m).sensor(:,q))',['- ',char(0)]); pRef=strmatch(Refname,ds.res4.chanNames); if isempty(pRef) fprintf(['getRawCTFBalanceCoefs : Sensor %s appears in ',... 'ds.res4.scrr, but not in ds.res4.chanNames\n'],Refname); return end Gbalanceindex=[Gbalanceindex pRef]; end end % end setup of balancing table for Ref. gradiometers if ds.res4.scrr(m).numcoefs~=nGbalcoef fprintf('\ngetRawCTFBalanceCoefs : %s has %d coefficients\n',... ds.res4.chanNames(Grefindex(1),1:nGchar),nGbalcoef); fprintf(' %s " %d " ????\n\n',... ds.res4.chanNames(Grefindex(n),1:nGchar),ds.res4.scrr(m).numcoefs); betaGref=[]; % Force useless output. return end betaGref(:,n)=reshape(ds.res4.scrr(m).coefs(1:nGbalcoef),nGbalcoef,1); m1=m+1; break; % Break out of m-loop. Go to nect n value. end if (m==m1-1 & m1>1) | (m==mtot & m1==1) if missingGrefMessage==0 if strncmp(balanceType(2,:), balanceOptions(5,:), 4) % Avoid warning for all sensors for adaptive coefficients. fprintf('\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients for reference sensors.\n',... balanceType(2,:)); else fprintf(['\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients',... ' for sensor(s)'],balanceType(2,:)); fprintf('\n\t\t\t\t'); end end missingGrefMessage=missingGrefMessage+1; if ~strncmp(balanceType(2,:), balanceOptions(5,:), 4) if missingGrefMessage==10*round(missingGrefMessage/10) fprintf('\n\t\t\t\t'); end fprintf(' %s',Gname); end betaGRef(:,n)=zeros(nGbalcoef,1); return end end % End loop over m (searching for scrr(m).sensorName) end % End loop over n (list of reference gradiometers) end % End of section getting coefficients to balance the reference gradiometers. if missingGrefMessage>0;fprintf('\n');end if strcmp(balanceType(1,:),'NONE') Refindex=[]; betaMEG=zeros(0,nMEG); return end % Get balance coefficients for the MEG sensors nRef=0; % Pointers for search through ds.res4.scrr structure array. m1=1; mtot=size(ds.res4.scrr,2); for n=1:nMEG MEGname=strtok(ds.res4.chanNames(MEGindex(n),:),['- ',char(0)]); nChar=length(MEGname); for m=[m1:mtot 1:(m1-1)] if strncmp(MEGname,char(ds.res4.scrr(m).sensorName),nChar) & ... strcmp(balanceType(1,:),char(ds.res4.scrr(m).coefType)); if nRef<=0 nRef=ds.res4.scrr(m).numcoefs; betaMEG=zeros(nRef,nMEG); for q=1:nRef % Assemble index array for balancing the MEG sensors Refname=strtok(char(ds.res4.scrr(m).sensor(:,q))',['- ',char(0)]); pRef=strmatch(Refname,ds.res4.chanNames); if isempty(pRef) fprintf(['\ngetRawCTFBalanceCoefs : Sensor %s appears in ',... 'ds.res4.scrr, but not in ds.res4.chanNames\n\n'],Refname); return end Refindex=[Refindex pRef]; end end % end setup of balancing table for MEG sensors if ds.res4.scrr(m).numcoefs~=nRef fprintf('\ngetRawCTFBalanceCoefs : %s - %s has %d coefficients\n',... ds.res4.chanNames(MEGindex(1),1:nChar),balanceType,nRef); fprintf(' %s - %s " %d " ????\n\n',... ds.res4.chanNames(MEGindex(n),1:nChar),balanceType,... ds.res4.scrr(m).numcoefs); betaMEG=[]; % An output that will force an error in the calling program. return end betaMEG(:,n)=reshape(ds.res4.scrr(m).coefs(1:nRef),nRef,1); m1=m+1; break; end if (m==m1-1 & m1>1) | (m==mtot & m1==1) if missingMEGMessage==0 if strncmp(balanceType(2,:), balanceOptions(5,:), 4) % Avoid warning for all sensors for adaptive coefficients. fprintf('\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients for sensors.\n',... balanceType(2,:)); else fprintf(['\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients',... ' for sensor(s)'],balanceType(1,:)); fprintf('\n\t\t\t\t'); end end missingMEGMessage=missingMEGMessage+1; if ~strncmp(balanceType(2,:), balanceOptions(5,:), 4) if missingMEGMessage==10*round(missingMEGMessage/10) fprintf('\n\t\t\t\t'); end fprintf(' %s',MEGname); end betaMEG(:,n)=zeros(nRef,1); end end % End of loop over m (ds.res4.scrr table) end % End of loop over MEG sensors if missingMEGMessage>0;fprintf('\n');end if common_mode_only if size(betaMEG,1)>3 & nMEG>0 betaMEG=betaMEG(1:3,:); Refindex=Refindex(1:3); end if size(betaGref,1)>3 & nGref>0 betaGref=betaGref(1:3,:); Gbalanceindex=Gbalanceindex(1:3); end end return
github
lcnhappe/happe-master
writeCTFds.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/ctf/writeCTFds.m
68,946
utf_8
96615f4833d69490d5b3e47f6f86c538
function ds=writeCTFds(datasetname,ds,data,unit); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % This program creates datasets that can be analyzed by CTF software. % % % % Datasets created by this program MUST NOT BE USED FOR CLINICAL APPLICATIONS. % % % % Please do not redistribute it without permission from VSM MedTech Ltd. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Author : Harold Wilson % Version 1.3 5 October 2007 Spelling errors in some variables corrected. % Version 1.2 24 April 2007 Modified to write both MEG and fMEG .hc files. % writeCTFds.m Version 1.1 Prepares a CTF-format data set. MATLAB to CTF conversion. % Adds record of filter changes to hist and newds files. % Adds no-clinical-use messages. % Creates multiple meg4 files when the total size of the data array % >536870910 elements. % Operation : % 1. User reads a data set using readCTFds and getTrial2. % size(data)= [SAMPLES, CHANNELS, TRIALS]. % 2. After working on data in MATLAB, user adjusts ds structure to reflect changes. % (writeCTFds will adjust the number of channels, channel names and trial structure.) % 3. This program then creates a new CTF data set. % datasetname must include the complete path description. % If a data set with name datasetname already exists, writeCTFds will issue an error message. % The new directory contains files for each field of structure ds. If the field is % missing no file is created. If the field is empty, an empty file is created. % Files default.* are not created by writeCTFds. % 4. The following fields of structure ds.res4 are modified based on the size of array data : % no_samples % no_channels % no_trials. % If size(ds.res4.chanNames,1)<no_channels, additional channel names are created % as required. The additional channels are called MXT%%%. It is assumed that % there will be <1000 new channels. % Inputs : datasetname : Output dataset including path. Extension '.ds' is optional. % ds : Structure produced by readCTFds. % data : MEG data array. size(data)=[no_samples no_channels no_trials] % Array data may be single or double. % unit : Determines the unit of the SQUID and EEG signals: % If unit is missing or unit==[], the unit is set to 'fT'. % 'ft' or 'fT' : Convert to fT (MEG), uV (EEG) % 't' or 'T' : Convert to T (MEG), V (EEG) % 'phi0' : Convert to phi0 (MEG), uV (EEG) % 'int': Read plain integers from *.meg4-file % Outputs : - ds : The ds structure of the output data set. % - datasetout : the name of the output data set. % - A data set. The .hz and .hz2 subdirectories are not included. % Function calls % Included in this listing: % - check_senres: Does simple checks on the fields of the senres table. % - writeHc: Creates the new .hc file % - checkMrk: Checks structure ds.mrk to see if it is valid marker set. % - writeEEG: Creates the new .EEG file. % - writeBadSegments: Creates the new bad.segments file. % - writeClassFile: Creates the new ClassFile.cls file. % - writeVirtualChannels: Creates the new VirtualChannels file. % - updateDescriptors: Adds non-clinical-use and creation software messages to % infods, res4, newds and hist fields of ds. % - updateHLC: Adds head-coil movement information to infods. % - updateDateTime : Resets dattime fields of res4 and infods. % - updateBandwidth: Resets bandwidth of newds and infods. Adds res4 filter % description to ds.hist. % - getArrayField : Extracts one field of a structure array to make it easier to % manipulate. % - writeMarkerFile: Creates the new MarkerFile.mrk file. % - writeCPersist: Creates the new .acq and .infods files. % Other calls: % - writeRes4: Writes the new .res4 file. % Output files are opened with 'w' permission and 'ieee-be' machine format in order % to be compatible with the Linux acquisition and analysis software. Do not open files % with 'wt' permission because this will add an extra char(13) byte at the end of each % line of text. persistent printWarning bandwidthMessage delim=filesep; if nargin==0 & nargout==0 % Print a version number fprintf(['\twriteCTFds: Version 1.3 5 October 2007 ',... 'Creates v4.1 and v4.2 CTF data sets.\n',... '\tCall: ds=writeCTFds(datasetname,ds,data,unit);\n',... '\t\tdatasetname = Name of the new dataset including the path.\n',... '\t\tds = Structure describing the new dataset (ds.hc must be v1.2 format).\n',... '\t\tdata = data that will be written to the new dataset .meg4 file.\n',... '\t\tunit = physical units of the data.\n\n']); return end % Allowed 8-byte headers for res4 and meg4 files. res4_headers=strvcat(['MEG41RS',char(0)],['MEG42RS',char(0)]); meg4_headers=strvcat(['MEG41CP',char(0)],['MEG42CP',char(0)]); maxMEG4Size=2^31; % Maximum MEG$ file in bytes. (Limit set by Linux software) MAX_COILS=8; % Parameter that determines the size of the ds.res.senres structure. lenSensorName=32; % Channel names must be 32 characters printDefaultBandwidthMessage=0; % Print a message about default bandwidth? default_flp=0.25; % Default is flp=0.25*ds.res4.sample_rate clinicalUseMessage='NOT FOR CLINICAL USE'; creatorSoftware='writeCTFds'; % Added to .infods file meg4ChunkSize=2^20; % Write new .meg4 file in chunks of 4*meg4ChunkSize bytes. DATASET_HZ_UNKNOWN=round(2^31-1); % Peculiar requirement of DataEditor as of 23 Oct. 2006 if ~exist('clinicalUseMessage'); clinicalUseMessage=char([]); end % Check inputs if nargin<3 fprintf(['\nwriteCTFds: Must supply inputs datasetname,ds,data. ',... 'Only %d input arguments are present.\n\n'],nargin); ds=-1; % Force an error in the calling program. return end % Check input argument unit. Convert unit to lower case. if exist('unit')~=1 unit='ft'; % default elseif isempty(unit) unit='ft'; % default elseif ischar(unit) unit=lower(unit); if ~strcmp(unit,'int') & ~strcmp(unit,'ft') & ~strcmp(unit,'t') & ~strcmp(unit,'phi0') fprintf(['\nwriteCTFds : unit=%s Not a valid option. Must be ',... '''fT'', ''T'', ''phi0'' or ''int''\n\n'],unit); ds=-1; % Force an error in the calling program. return end end % Check argument type if ~isstruct(ds) | ~isnumeric(data) | ~ischar(unit) | ~ischar(datasetname) fprintf('\nwriteCTFds: Some of the inputs are the wrong type.\n'); whos datasetname ds data unit; ds=-1; return elseif ~isfield(ds,'res4') | ~isfield(ds,'meg4') fprintf('\nwriteCTFds: Fields res4 and meg4 must be present in structure ds.\n\n'); ds % List the fields of structure ds. ds=-1; % Force an error in the calling program. return end % Refuse to write a data set with balanced reference gradiometers. balancedGref=0; for k=1:ds.res4.no_channels balancedGref=(ds.res4.senres(k).sensorTypeIndex==1 & ds.res4.senres(k).grad_order_no~=0); end if balancedGref fprintf('\nwriteCTFds: ds.res4.senres indicates balanced reference gradiometers.\n\n'); ds=-1; % Force an error in the calling program. return end clear k balancedGref; % Separate datasetname into a path and the baseName datasetname=deblank(datasetname); ksep=max([0 findstr(datasetname,delim)]); baseName=datasetname((ksep+1):length(datasetname)); path=datasetname(1:ksep); % String path is terminated by the file delimiter (or path=[]). % Remove the last .ds from baseName. kdot=max(findstr(baseName,'.ds')); if kdot==(length(baseName)-2) baseName=baseName(1:(max(kdot)-1)); else datasetname=[datasetname,'.ds']; end clear ksep kdot; % Save the name already in structure ds, and change to the new datset name. if isfield(ds,'baseName') olddatasetname=[ds.baseName,'.ds']; if isfield(ds, 'path') olddatasetname=[ds.path,olddatasetname]; end else olddatasetname=' None '; end ds.path=path; ds.baseName=baseName; % Does the dataset already exist? if exist(datasetname)==7 fprintf('\nwriteCTFds: Dataset %s already exists. Use a different name.\n\n',... datasetname); ds=-1; % Force an error in the calling program. return end if size(ds.res4.chanNames,2)~=lenSensorName fprintf(['\nwriteCTFds : size(ds.res4.chanNames)=[%d %d] ? Must ',... 'have %d-character channel names.\n\n'],size(ds.res4.chanNames),lenSensorName); ds=-1; return end % Check that the channel names have a sensor-file identification extensions. % If it is missing, print a warning message. % Sensor type indices : SQUIDs (0:7), ADCs (10), DACs(14), Clock (17), HLC (13,28,29) % See Document CTF MEG File Formats (PN 900-0088), RES4 File Format/ for index=[0:7 10 13 14 17 28 29] for k=find([ds.res4.senres.sensorTypeIndex]==index); if isempty(strfind(ds.res4.chanNames(k,:),'-')) fprintf(['writeCTFds: Channel %3d %s No sensor-file identification.',... ' (''-xxxx'' appended to channel name).\n',... '\t\tSome CTF software may not work with these channel names.\n'],... k,deblank(ds.res4.chanNames(k,:))); break; end end if isempty(strfind(ds.res4.chanNames(k,:),'-'));break;end end clear index k chanName; % Update the data description in the ds.res4 structure. [nSample, nChan, trials]=size(data); % Update ds.res4 fields to match the size of array data. ds.res4.no_trials=trials; ds.res4.no_channels=nChan; ds.res4.no_samples=nSample; ds.res4.epoch_time=nSample*trials/ds.res4.sample_rate; % Check if channels have been added or removed from array data. [no_chanNames len_chanNames]=size(ds.res4.chanNames); if no_chanNames<nChan % Assume that new channel are at the end of the data set. Add a fake extension. for kx=1:(nChan-no_chanNames) ds.res4.chanNames=... strvcat(ds.res4.chanNames,['MXT' num2str(kx,'%3.3d') '-0001' char(0)]); end fprintf('\tAdded %d SQUID channels to the end of ds.res4.chanNames table.\n',... nChan-no_chanNames); elseif no_chanNames>nChan fprintf(['\nlength(chanNames)=%d, but only %d channels of data. ',... 'writeCTFds cannot tell which channel names to remove.\n\n'],no_chanNames,nChan); ds=-1; return end clear no_chanNames len_chanNames; % The senres table may have been changed, especially if channels are added or removed. % Check structure senres, print error messages, and possibly fix the errors. [ds.res4.senres,status]=check_senres(ds.res4.senres,ds.res4.no_channels); if status<0;ds=-1;return;end clear status; % Check that ds.res4.numcoef is the size of structure array ds.res4.scrr. if isfield(ds.res4,'scrr') if ~isequal(size(ds.res4.scrr,2),ds.res4.numcoef) fprintf('Error in ds.res4: ds.res4.numcoef=%d, but size(ds.res4.scrr)=[',... ds.res4.numcoef); fprintf(' %d',size(ds.res4.scrr));fprintf('] ?\n'); return end elseif ds.res4.numcoef~=0 fprintf(['Error in ds.res4: ds.res4.numcoef=%d,',... ' but scrr is not a field of ds.res4\n'],ds.res4.numcoef); return end % Before converting data to integers, save HLC channels for motion analysis in function % make_new_infods. Pass HLCdata to function make_new_infods if isempty(strmatch('HLC',ds.res4.chanNames)) HLCdata=[]; else % Make a list of head-coil channels coil=0; HLClist=[]; while ~isempty(strmatch(['HLC00',int2str(coil+1)],ds.res4.chanNames)) coil=coil+1; for k=1:3 HLClist=[HLClist strmatch(['HLC00',int2str(coil),int2str(k)],ds.res4.chanNames)]; end end HLCdata=reshape(double(data(:,HLClist,:)),ds.res4.no_samples,3,coil,ds.res4.no_trials); clear coil k HLClist; end % Convert data to integers because CTF data sets are stored as raw numbers and % not as physical qunatities. The res4 file contains the calibrations for % converting back to physical units. Array data may be single precision, so % convert to double before doing any adjustments to the data. % Already checked that unit is valid. if strcmp(unit,'int') data=reshape(data,nSample,nChan*trials); for k=1:nChan*trials if strcmp(class(data),'single') data(:,k)=single(round(double(data(:,k)))); else data(:,k)=round(double(data(:,k))); end end data=reshape(data,nSample,nChan,trials); clear k; else for chan=1:nChan % Convert EEGs from uV to V, SQUIDs from fT to T SQUIDtype=any(ds.res4.senres(chan).sensorTypeIndex==[0:7]); EEGtype=any(ds.res4.senres(chan).sensorTypeIndex==[8 9]); if EEGtype & (strcmp(unit,'ft') | strtcmp(unit,'phi0')) alphaG=1e-6; elseif SQUIDtype & strcmp(unit,'ft') alphaG=1e-15; elseif SQUIDtype & strcmp(unit,'phi0') alphaG=1./(ds.res4.senres(chan).properGain*ds.res4.senres(chan).ioGain); else alphaG=1; end % Convert from physical units to integers using the gains in the senres table. for kt=1:trials buff=round(double(data(:,chan,kt))*(alphaG*... (ds.res4.senres(chan).properGain*ds.res4.senres(chan).qGain*ds.res4.senres(chan).ioGain))); if strcmp(class(data),'single') data(:,chan,kt)=single(buff); else data(:,chan,kt)=buff; end end end clear chan alphaG SQUIDtype EEGtype buff kt; end % Create the output dataset [status,msg]=mkdir(path,[baseName '.ds']); if status==0 | ~isempty(msg) fprintf('\nwriteCTFds: Failed to create directory.\n'); fprintf(' [status,msg]=mkdir(%s)\n',datasetname); fprintf(' returns status=%d, msg=%s',status,msg);fprintf('\n\n'); ds=-1; return end clear msg status; % Write the data file (meg4 file). Check ds.meg4.header and make sure that % the output .meg4 file has an acceptable header. headerMessage=1; if ~isfield(ds.meg4,'header'); % If ds.meg4.header is missing, add it. nChar=length(deblank(meg4_headers(1,:))); ds.meg4.header=[meg4_headers(1,1:min(7,nChar)) char(zeros(1,7-nChar))]; elseif isempty(strmatch(ds.meg4.header(1:7),meg4_headers(:,1:7),'exact')) ds.meg4.header=meg4_headers(1,1:7); else headerMessage=0; end if headerMessage; fprintf('writeCTFds: Set ds.meg4.header=%s\n',ds.meg4.header); end clear headerMessage; if isempty(printWarning) fprintf(['\nwriteCTFds: The data you are writing have been processed by software not\n',... '\tmanufactured by VSM MedTech Ltd. and that has not received marketing clearance\n',... '\tfor clinical applications. These data should not be later employed for clinical\n',... '\tand/or diagnostic purposes.\n\n']); printWarning=1; end % Write the meg4 file(s). If there are more than maxMEG4Size-8 bytes, then additional meg4 % files will be created. % Convert data to a 1-D array ndata=prod(size(data)); data=reshape(data,ndata,1); ptsPerTrial=nSample*nChan; maxPtsPerFile=ptsPerTrial*floor((maxMEG4Size-8)/(4*ptsPerTrial)); pt=0; % Last point written to the output file(s). while pt<ndata endPt=pt+min(ndata-pt,maxPtsPerFile); if pt==0 meg4Ext='.meg4'; else meg4Ext=['.',int2str(floor(pt/maxPtsPerFile)),'_meg4']; end fidMeg4=fopen([path,baseName,'.ds',delim,baseName,meg4Ext],'w','ieee-be'); fwrite(fidMeg4,[ds.meg4.header(1:7),char(0)],'uint8'); while pt<endPt pt1=min(pt+meg4ChunkSize,endPt); % Convert to double in case data is fwrite(fidMeg4,double(data((pt+1):pt1)),'int32'); % is single and write in short pt=pt1; % pieces. end fclose(fidMeg4); end % Update the .meg4 part of structure ds. ds.meg4.fileSize=4*ndata+8*(1+floor(ndata/maxPtsPerFile)); clear data pt pt1 ndata fidMeg4 ptsPerTrial maxPtsPerFile meg4Ext; % Add dataset names to .hist if ~isfield(ds,'hist');ds.hist=char([]);end ds.hist=[ds.hist char(10) char(10) datestr(now) ' :' char(10) ... ' Read into MATLAB as data set ' olddatasetname char(10) ... ' Rewritten by writeCTFds as data set ' datasetname char(10)]; % If infods doesn't exist or is empty create it. if ~isfield(ds,'infods');ds.infods=[];end if isempty(ds.infods) ds.infods=make_dummy_infods(isfield(ds,'hc'),~isempty(HLCdata),ds.res4.sample_rate); end % Update text fields of res4,infods, newds and hist. ds=updateDescriptors(ds,clinicalUseMessage,creatorSoftware); % Add HLC data to infods ds.infods=updateHLC(ds.infods,HLCdata); % Analyze structure array ds.res4.filters to make text info for .hist file and % bandwidth parameters for .newds file. fhp=0; % High-pass cutoff assuming no filters flp=default_flp*ds.res4.sample_rate; % Assumed lowpass cutoff. SHOULD THIS BE CHANGED? if isempty(bandwidthMessage) & printDefaultBandwidthMessage fprintf('writeCTFds: Lowpass filter set to flp=%0.2f*sample_rate\n',default_flp); bandwidthMessage=1; end ds=updateBandwidth(ds,fhp,flp); % Update date/time fields of infods and res4 ds=updateDateTime(ds); % Create the .res4 file in the output dataset. ds.res4=writeRes4([path,baseName,'.ds',delim,baseName,'.res4'],ds.res4,MAX_COILS); if ds.res4.numcoef<0 fprintf('\nwriteCTFds: writeRes4 returned ds.res4.numcoef=%d (<0??)\n\n',... ds.res4.numcoef); % Kill the output dataset. rmdir([path,baseName,'.ds'],'s'); ds=-1; return end % Create .hist file histfile=[path,baseName,'.ds',delim,baseName,'.hist']; fid=fopen(histfile,'w'); fwrite(fid,ds.hist,'uint8'); fclose(fid); % New .newds file if isfield(ds,'newds') fid=fopen([path,baseName,'.ds',delim,baseName,'.newds'],'w'); fwrite(fid,ds.newds,'uint8'); fclose(fid); end % New infods file. if isfield(ds,'infods') writeCPersist([path,baseName,'.ds',delim,baseName,'.infods'],ds.infods); end % new hc file if isfield(ds,'hc') ds.hc=writeHc([path,baseName,'.ds',delim,baseName,'.hc'],ds.hc,HLCdata(:,:,1)); end clear HLCdata; % MarkerFile.mrk if checkMrk(ds) writeMarkerFile([path,baseName,'.ds',delim,'MarkerFile.mrk'],ds.mrk); end % .EEG if isfield(ds,'EEG') writeEEG([path,baseName,'.ds',delim,baseName,'.EEG'],ds.EEG); end % .acq if isfield(ds,'acq'); % Check that ds.acq has the correct fields if isfield(ds.acq,'name') & isfield(ds.acq,'type') & isfield(ds.acq,'data') acqFilename=[path,baseName,'.ds',delim,baseName,'.acq']; writeCPersist(acqFilename,ds.acq); end end % bad.segments file if isfield(ds,'badSegments') writeBadSegments([path,baseName,'.ds',delim,'bad.segments'],ds.badSegments,... ds.res4.no_trials,ds.res4.no_samples/ds.res4.sample_rate); end % BadChannels if isfield(ds,'BadChannels'); if ischar(ds.BadChannels) & ~isempty(ds.BadChannels) fid=fopen([path,baseName,'.ds',delim,'BadChannels'],'w','ieee-be'); for k=1:size(ds.BadChannels,1) fprintf(fid,'%s\n',deblank(ds.BadChannels(k,:))); end fclose(fid); end end % ClassFile if check_cls(ds) writeClassFile([path,baseName,'.ds',delim,'ClassFile.cls'],ds.TrialClass); end % VirtualChannels if isfield(ds,'Virtual') writeVirtualChannels([path,baseName,'.ds',delim,'VirtualChannels'],ds.Virtual); end % processing.cfg if isfield(ds,'processing'); if ischar(ds.processing) fid=fopen([datasetname,delim,'processing.cfg'],'w','ieee-be'); fwrite(fid,ds.processing,'uint8'); fclose(fid); end end % Update the data set path and name ds.path=path; ds.baseName=baseName; return % *************** End of function writeCTFds ******************************************** % ************************************************************************************** % ************************************************************************************** % *************** Function check_senres ************************** function [senres,status]=check_senres(senres,numChan); % A user may have augmented the senres table, so check that all the fields have the % correct size. This will cause errors in programs that try to compute % sensor response using the geometry in the senres table. % Does "sanity" checks on the senres table. If there are obviously incorrect entries, it % tries to fix them, and prints a message. If the senres table does not specify coil % positions, orientations or areas, set them to zero, but give them the correct array % size. newChannelType=4; % Create the fake sensors as MEG magnetometers. This way offsets can be removed. status=-1; % Does the senres table have the correct no. of channels? no_senres=length(senres); if no_senres<numChan % Add channels. Assume that they are gradiometers. ioGain=1; qGain=2^20; gain=0.3; properGain=1e15/(qGain*ioGain*gain); % sensor gain in phi0/fT for kx=(no_senres+1):numChan senres(kx)=struct(... 'sensorTypeIndex',newChannelType,'originalRunNum',0,'coilShape',0,... 'properGain',properGain,'qGain',qGain,'ioGain',ioGain,... 'ioOffset',0,'numCoils',1,... 'grad_order_no',0,... 'gain',gain,... 'pos0',zeros(3,1),'ori0',zeros(3,1),... 'area',0.1,'numturns',1,... 'pos',[0 0 21]','ori',zeros(3,1)); end fprintf(['\tAdded %d SQUID channels to senres table. Nominal gain of each = ',... '%8.4f fT/step\n'],numChan-no_senres,gain); clear kx gain qGain ioGain properGain; elseif no_senres>numChan % Channels have been removed from the data set, but can't tell which elements of the % senres table to remove. fprintf(['length(senres)=%d, but only %d channels of data. writeCTFds can''t',... ' tell which channels to remove from senres table.\n'],no_senres,numChan); return end no_senres=length(senres); % Previous version of check_senres ensures that several fields had size [1 1]. % Seems unnecessary, so removed it. for k=1:no_senres % Check the fields that define pickup loops. Force the field defining the pickup % loops to have the correct size. It is not clear why the EEG channels and % the type=13,28,29 HLC channels need numCoils=1, and area>0. if any(senres(k).sensorTypeIndex==[0:7]) % SQUID channels correct_numCoils=rem(senres(k).sensorTypeIndex,4)+1; elseif any(senres(k).sensorTypeIndex==[13 28 29]) % HLC channels correct_numCoils=1; elseif any(senres(k).sensorTypeIndex==[8 9]) % EEG channels correct_numCoils=1; else correct_numCoils=0; end if senres(k).numCoils~=correct_numCoils & any(senres(k).sensorTypeIndex==[0:7]) fprintf('writeCTFds_test: senres(%d).sensorTypeIndex=%d but numCoils=%d??\n',... k,senres(k).sensorTypeIndex,senres(k).numCoils); fprintf(' Set numCoils=%d\n',correct_numCoils); senres(k).numCoils=correct_numCoils; end numCoils=senres(k).numCoils; if size(senres(k).pos0)~=[3 numCoils];pos0=zeros(3,numCoils);end if size(senres(k).ori0)~=[3 numCoils];ori0=zeros(3,numCoils);end if size(senres(k).pos)~=[3 numCoils];pos=zeros(3,numCoils);end if size(senres(k).ori)~=[3 numCoils];ori=zeros(3,numCoils);end if size(senres(k).numturns)~=[1 numCoils];numturns=zeros(1,numCoils);end if size(senres(k).area)~=[1 numCoils];area=zeros(3,numCoils);end end status=1; return % ************* End of function check_senres********************************************* % ************************************************************************************** % ************************************************************************************** % ************* function make_dummy_infods********************************************* function Tag=make_dummy_infods(exist_hc,exist_HLC,sample_rate); % If the user does not supply ds.infos, this code makes a dummy version. It has all of % the tags that Acq created in file Richard_SEF_20060606_04.infods. % *********************************************************************************** % *********************************************************************************** DATASET_HZ_UNKNOWN=round(2^31-1); % Peculiar requirement of DataEditor as of 23 Oct. 2006 fprintf('writeCTDds (make_dummy_infods): Creating a dummy infods file with all the tags.\n'); Tag(1)=struct('name','WS1_','type',0,'data',[]); Tag(length(Tag)+1)=struct('name','_PATIENT_INFO','type',2,'data',[]); Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]); Tag(length(Tag)+1)=struct('name','_PATIENT_UID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011'); Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_FIRST','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_MIDDLE','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_LAST','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_ID','type',10,'data','x'); Tag(length(Tag)+1)=struct('name','_PATIENT_BIRTHDATE','type',10,'data','19500101000000'); Tag(length(Tag)+1)=struct('name','_PATIENT_SEX','type',5,'data',2); Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_NAME','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_UID','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_INSTITUTE','type',10,'data',''); Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]); Tag(length(Tag)+1)=struct('name','_PROCEDURE_INFO','type',2,'data',[]); Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]); Tag(length(Tag)+1)=struct('name','_PROCEDURE_VERSION','type',5,'data',1); Tag(length(Tag)+1)=struct('name','_PROCEDURE_UID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_ACCESSIONNUMBER','type',10,'data','0'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_TITLE','type',10,'data','0'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_SITE','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PROCEDURE_STATUS','type',5,'data',1); Tag(length(Tag)+1)=struct('name','_PROCEDURE_TYPE','type',5,'data',2); % Research type Tag(length(Tag)+1)=struct('name','_PROCEDURE_STARTEDDATETIME','type',10,... 'data','20060606164306'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_CLOSEDDATETIME','type',10,... 'data','19000100000000'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_COMMENTS','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PROCEDURE_LOCATION','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PROCEDURE_ISINDB','type',5,'data',0); Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]); Tag(length(Tag)+1)=struct('name','_DATASET_INFO','type',2,'data',[]); Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]); Tag(length(Tag)+1)=struct('name','_DATASET_VERSION','type',5,'data',2); Tag(length(Tag)+1)=struct('name','_DATASET_UID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0042'); Tag(length(Tag)+1)=struct('name','_DATASET_PATIENTUID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011'); Tag(length(Tag)+1)=struct('name','_DATASET_PROCEDUREUID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041'); Tag(length(Tag)+1)=struct('name','_DATASET_STATUS','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_RPFILE','type',10,'data','default.rp'); Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPTITLE','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPPROTOCOL','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPDESCRIPTION','type',10,... 'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONDATETIME','type',10,... 'data','Unknown'); Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONSOFTWARE','type',10,... 'data','Acq '); Tag(length(Tag)+1)=struct('name','_DATASET_CREATORDATETIME','type',10,... 'data',sprintf('%d',floor(clock))); Tag(length(Tag)+1)=struct('name','_DATASET_CREATORSOFTWARE','type',10,... 'data','Acq '); Tag(length(Tag)+1)=struct('name','_DATASET_KEYWORDS','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_COMMENTS','type',10,... 'data','Dummy infods.'); Tag(length(Tag)+1)=struct('name','_DATASET_OPERATORNAME','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_LASTMODIFIEDDATETIME','type',10,... 'data',sprintf('%d',floor(clock))); if exist_hc nominalPositions=0; % Measured else nominalPositions=1; % Nominal end Tag(length(Tag)+1)=struct('name','_DATASET_NOMINALHCPOSITIONS','type',5,... 'data',nominalPositions); Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,... 'data','ds.res4.scrr'); Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,... 'data','ds.res4.senres'); %Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,... % 'data','/opt/ctf-5.1/hardware/M015/M015_1609.coef'); %Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,... % 'data','/opt/ctf-5.1/hardware/M015/M015_1609.sens'); Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEM','type',10,'data','DSQ-2010'); Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEMTYPE','type',10,'data','Untitled'); Tag(length(Tag)+1)=struct('name','_DATASET_LOWERBANDWIDTH','type',4,'data',0); Tag(length(Tag)+1)=struct('name','_DATASET_UPPERBANDWIDTH','type',4,'data',... round(0.25*sample_rate)); Tag(length(Tag)+1)=struct('name','_DATASET_ISINDB','type',5,'data',0); if exist_HLC HZ_MODE=5; elseif exist_hc HZ_MODE=1; else HZ_MODE=DATASET_HZ_UNKNOWN; end Tag(length(Tag)+1)=struct('name','_DATASET_HZ_MODE','type',5,'data',HZ_MODE); Tag(length(Tag)+1)=struct('name','_DATASET_MOTIONTOLERANCE','type',4,'data',0.005); Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTION','type',4,'data',0.005); Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONTRIAL','type',7,'data',0); Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONCOIL','type',10,'data','1'); Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]); Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]); return % ************* End of function make_dummy_infods********************************************* % ************************************************************************************** % ************************************************************************************** % ************* Function writeHc********************************************* function hc=writeHc(hcFileName,hc,HLCdata); % Modified for v1.2 ds.hc structures. ds.hc.names has the exact, complete names of the % head coils. The coordinates relative to the subject may be ds.hc.head(MEG) OR % ds.hc.abdomen (fMEG). % Creates a .hc file in a CTF dataset % Inputs: hcFileName : Complete name of .hc file including path, basename and .hc ext. % hc : structure with nasion, left, right head coil positions in dewar and % CTF head coordinates. % HLCdata : head coil locations at the start of 1st trial. unit=m % coordinates=dewar. Used only if structure hc is empty and it is MEG % data (not fMEG data). % Output : hc : hc structure. hc=struct([]) on failure. hc is set to the coil positions % in array HLCdata if hc=[] on entry. % Check inputs if exist('hc')~=1 hc=struct([]); elseif ~isstruct(hc) hc=struct([]); end hcfields=fieldnames(hc); if exist('HLCdata')~=1 HLCdata=[]; elseif ~isnumeric(HLCdata) | size(HLCdata,1)~=3 | size(HLCdata,2)<3 HLCdata=[]; end % Check hc Filename if exist('hcFileName')~=1;hcFileName=char([]);end if ~ischar(hcFileName) | isempty(hcFileName) fprintf('writeCTFds (writeHc): Called writeHc with bad file name.\n'); hcFileName return end % Both hc and HLCdata bad? if length(hcfields)~=4 & isempty(HLCdata) fprintf('writeCTFds (writeHc): Called writeHc with bad hc and bad HLCdata.\n'); hc=struct([]) return elseif length(hcfields)~=4 rstandard=8/sqrt(2)*[1 1 0;-1 1 0;1 -1 0]'; rstandard(3,:)=-27; rdewar=100*HLCdata(:,1:3); % Convert from dewar coordinates to CTF head coordinates. originCTF=0.5*(hc.dewar(:,2)+hc.dewar(:,3)); % Unit vectors for the CTF coordinates uCTF(:,1)=hc.dewar(:,1)-originCTF; uCTF(:,3)=cross(uxCTF,hc.dewar(:,2)-hc.dewar(:,3)); uCTF(:,2)=cross(uCTF(:,3),uCTF(:,1)); uCTF=uCTF./(ones(3,1)*sqrt(sum(uCTF.^2,1))); rCTF=uCTF'*(rdewar-originCTF*ones(1,3)) hc=struct('names',strvcat('nasion','left ear','right ear'),... 'standard',rstandard,'dewar',rdewar,'head',rCTF); clear originCTF uCTF rstandard rdewar rCTF; end % Character strings for generating the .hc text file % Should never have both 'head' and 'abdomen' fields. labelword=strvcat('standard','measured','measured'); printField=[strmatch('standard',hcfields) strmatch('dewar',hcfields) ... strmatch('head',hcfields) strmatch('abdomen',hcfields)]; if ~strmatch('names',hcfields) | length(printField)~=3 fprintf(['writeCTFds (writeHc): Structure hc does not have all of the required fields.\n',... ' No .hc file will appear in the output dataset.\n']); hc; hc=struct([]); return end relative=strvcat('dewar','dewar',hcfields{printField(3)}); coilcoord=strvcat('standard','dewar',hcfields{printField(3)}); comp='xyz'; coilname=hc.names; fid=fopen(hcFileName,'w','ieee-be'); for k=1:size(coilcoord,1) rcoil=getfield(hc,coilcoord(k,:)); for coil=1:size(hc.names,1) clName=deblank(hc.names(coil,:)); fwrite(fid,[labelword(k,:) ' ' clName ' coil position relative to ',... deblank(relative(k,:)) ' (cm):' char(10)],'uint8'); for m=1:3 fwrite(fid,[char(9) comp(m) ' = ' num2str(rcoil(m,coil),'%7.5f') char(10)],'uint8'); end end end fclose(fid); status=0; return % ************* End of function writeHc********************************************* % ************************************************************************************** %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%Function checkMrk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function MarkerFileOK=checkMrk(ds); % Examines structure ds to see if a sensible MarkerFile can be created from ds.mrk. % Output: MarkerFileOK=1 : ds.mrk looks OK % MarkerFileOK=0 : ds.mrk cannot be a set of valid markers for these data. MarkerFileOK=isfield(ds,'mrk'); if MarkerFileOK MarkerFileOK=~isempty(ds.mrk); end if MarkerFileOK % Are the markers appropriate? minMarkerTrial=[]; minMarkerTime=[]; maxMarkerTrial=[]; maxMarkerTime=[]; for k=1:length(ds.mrk) maxMarkerTrial=max([maxMarkerTrial max(ds.mrk(k).trial)]); maxMarkerTime=max([maxMarkerTime max(ds.mrk(k).time)]); minMarkerTrial=min([minMarkerTrial min(ds.mrk(k).trial)]); minMarkerTime=min([minMarkerTime min(ds.mrk(k).time)]); end if isempty(maxMarkerTrial) | isempty(maxMarkerTime) MarkerFileOK=0; % Do not create MarkerFile.mrk if all of the marker classes are empty. else MarkerFileOK=(maxMarkerTrial<=ds.res4.no_trials & minMarkerTrial>=1 & ... maxMarkerTime<=(ds.res4.no_samples/ds.res4.sample_rate) & ... minMarkerTime>=(-ds.res4.preTrigPts/ds.res4.sample_rate)); if ~MarkerFileOK fprintf(['\nwriteCTFds (checkMrk): ds.mrk cannot possibly be a set of markers ',... 'for array(data).\n']); fprintf([' minMarkerTrial=%d (must be >=1) ',... 'maxMarkerTrial=%d (must be <=%d)\n'],... minMarkerTrial,maxMarkerTrial,ds.res4.no_trials); fprintf([' minMarkerTime=%7.4f (must be >=%7.4f) ',... 'maxMarkerTrial=%7.4f (must be <=%7.4f )\n'],... minMarkerTime,-ds.res4.preTrigPts/ds.res4.sample_rate,... maxMarkerTime,ds.res4.no_samples/ds.res4.sample_rate); fprintf(' MarkerFile.mrk will not be created.\n\n'); end end end return %%%%%%%%%%%%%% end of checkMrk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Function writeEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function writeEEG(eegFileName,EEG); % Reads the EEG file of a dtaset and stores the infoemation in strucure array EEG. % EEG(k).chanName = channel name in the dataset (EEGmmm where mmm=channel number) % EEG(k).name = channel name given by the user (e.g. Fp4) % EEG(k).pos = electrode position in cm in CTF head coordinates % Check inputs if exist('eegFileName')~=1;eegFileName=char([]);end if ~ischar(eegFileName) | isempty(eegFileName) fprintf('writeCTFds (writeEEG): Called writeEEG with bad file name.\n'); eegFileName EEG=struct([]); end if exist('EEG')~=1 EEG=struct([]); elseif ~isstruct(EEG) EEG=struct([]); end if isempty(EEG);return;end fid=fopen(eegFileName,'w','ieee-be'); if fid<0 fprintf('writeCTFds (writeEEG): Could not open file %s\n',eegFileName); return end nEEG=length(EEG); for k=1:nEEG fprintf(fid,'%d\t%s\t%7.5f\t%7.5f\t%7.5f\n',EEG(k).chanNum,EEG(k).name,EEG(k).pos); end fclose(fid); return %%%%%%%%% End of writeEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Function writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function writeBadSegments(badSegmentsFile,badSegments,nTrial,tTrial); % Creates a bad.segements file in a CTF data set from the information in structure % badSegments which is created by read_badSegments, or by the user. % If structure badSegments is empty, then the file is not created. % badSegments structure: % badSegments.trial = List of trial numbers % badSegments.StartTime = List of bad segment start times (relative to trial). % badSegments.EndTime = List of bad segment end times. % Check badSegmentsFile if exist('badSegmentsFile')~=1;badSegmentsFile=char([]);end if isempty(badSegmentsFile) | ~ischar(badSegmentsFile) fprintf('writeCTFds(writeBadSegments): Bad file name.\n'); badSegmentsFile return end % Check that structure badSegments is defined correctly if exist('badSegments')~=1 | exist('nTrial')~=1 return elseif ~isstruct(badSegments) | isempty(badSegments) return elseif ~isfield(badSegments,'trial') | ~isfield(badSegments,'StartTime') | ... ~isfield(badSegments,'EndTime') return elseif isempty(badSegments.trial) | isempty(badSegments.StartTime) | ... isempty(badSegments.EndTime) return elseif ~isequal(size(badSegments.trial),size(badSegments.StartTime),... size(badSegments.EndTime)) fprintf(['\nwriteCTFds (writeBadSegments): ',... 'The fields of structure badSegments do not all have the same size.\n']); return elseif any(badSegments.trial>nTrial) | any(badSegments.trial<1) | ... any(badSegments.EndTime>tTrial) fprintf(['\nwriteCTFds (writeBadSegments): ds.badSegments cannot possibly describe ',... 'bad segments for these data.\n',... '\tmin(badSegments.trial)=%d max(badSegments.trial)=%d ',... 'max(badSegments.EndTime)=%0.4f s\n\t\tDataset: nTrial=%d tTrial=%0.4f s\n'],... min(badSegments.trial),max(badSegments.trial),max(badSegments.EndTime),... nTrial,tTrial); fprintf('\t\tbad.segments file will not be created.\n\n'); return end % Convert all fields to simple vectors nSeg=prod(size(badSegments.trial)); trial=reshape(badSegments.trial,1,nSeg); StartTime=reshape(badSegments.StartTime,1,nSeg); EndTime=reshape(badSegments.EndTime,1,nSeg); fid=fopen(badSegmentsFile,'w','ieee-be'); if fid<0 fprintf('writeCTFds (writeBadSegments): Could not open file %s\n',badSegmentsFile); return end % Extra tabs are inserted to reproduce the format of bad.segments files produced by % DataEditor (5.3.0-experimental-linux-20060918). fprintf(fid,'%0.6g\t\t%0.6g\t\t%0.6g\t\t\n',[trial;StartTime;EndTime]); fclose(fid); return %%%%%%%%% End of writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%Function check_cls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ClassFileOK=check_cls(ds); % Examines structure ds to see if a sensible ClassFile can be created from ds.TrialClass. ClassFileOK=isfield(ds,'TrialClass'); if ClassFileOK ClassFileOK=~isempty(ds.TrialClass); end if ClassFileOK % Are the class trials appropriate? minClassTrial=[]; maxClassTrial=[]; for k=1:length(ds.TrialClass) maxClassTrial=max([maxClassTrial max(ds.TrialClass(k).trial)]); minClassTrial=min([minClassTrial min(ds.TrialClass(k).trial)]); end % Create ClassFile.cls even when the trail classes are empty. if ~isempty(maxClassTrial) ClassFileOK=(maxClassTrial<=ds.res4.no_trials & minClassTrial>=1); if ~ClassFileOK fprintf(['\nwriteCTFds (check_cls): ds.TrialClass cannot possibly be a set of ',... 'trial classes for array(data).\n minClassTrial=%d (must be >=1) ',... 'maxClassTrial=%d (must be <=%d)\n'],... minClassTrial,maxClassTrial,ds.res4.no_trials); fprintf(' ClassFile.cls will not be created.\n'); end end end return %%%%%%%%%%%%%% end of check_cls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% Function writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function writeClassFile(ClassFile,TrialClass); % Write the ClassFile of a CTF data set. % The CLassFile allows a user to store a list of trial classifications in a data set. % The ClassFile format is defined in document CTF MEG File Formats, PN900-0088. % This format is rigid. % Inputs : % ClassFile : marker file including the full path and extension .mrk. % TrialClass : Structure creted by read_ClassFile. % Output : ClassFile.cls. % Check input TrialClass. if exist('TrialClass')~=1;TrialClass=[];end if isempty(TrialClass) | ~isstruct(TrialClass) fprintf('writeCTFds (writeClassFile): TrialClass is empty or is not a structure.\n'); TrialClass return end % Check ClassFile if exist('ClassFile')~=1;ClassFile=char([]);end if isempty(ClassFile) | ~ischar(ClassFile) fprintf('writeCTFds (writeClassFile): Bad file name.\n'); ClassFile end fid=fopen(ClassFile,'w','ieee-be'); if fid<0 fprintf('writeCTFds (writeClassFile): Could not open file %s\n',ClassFile); return end nClass=length(TrialClass); % Generate datasetname from ClassFIle. ksep=max([0 strfind(ClassFile,filesep)]); datasetname=ClassFile(1:ksep-1); if isempty(datasetname);datasetname=cd;end fprintf(fid,'PATH OF DATASET:\n%s\n\n\n',datasetname); fprintf(fid,'NUMBER OF CLASSES:\n%d\n\n\n',nClass); for k=1:nClass if k==1 % Add sign character to make output match the output of Acq. sgn=char([]); % There should be no real significance to this. else % Why does DataEditor places the + sign only on ClassID 2,3,...? sgn='+'; end No_of_Trials=prod(size(TrialClass(k).trial)); fprintf(fid,'CLASSGROUPID:\n%s%d\nNAME:\n%s\nCOMMENT:\n%s\n',... sgn,TrialClass(k).ClassGroupId,TrialClass(k).Name,TrialClass(k).Comment); fprintf(fid,'COLOR:\n%s\nEDITABLE:\n%s\nCLASSID:\n%s%d\nNUMBER OF TRIALS:\n%d\n',... TrialClass(k).Color,TrialClass(k).Editable,sgn,TrialClass(k).ClassId,No_of_Trials); fprintf(fid,'LIST OF TRIALS:\nTRIAL NUMBER\n'); % Subtract one so trial numbering starts at 0 in ClassFile.cls fprintf(fid,'%20d\n',reshape(TrialClass(k).trial,1,No_of_Trials)-1); fprintf(fid,'\n\n'); end fclose(fid); return %%%%%%%%%%%%%% end of writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% Function writeVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function writeVirtualChannels(VirtualChannelsFile,Virtual); % Writes a VirtualChannels file using the information in structure Virtual. % S\tructure Virtual is prepared by read_VirtualChannels % Check VirtualChannelsFile if exist('VirtualChannelsFile')~=1;VirtualChannelsFile=char([]);end if isempty(VirtualChannelsFile) | ~ischar(VirtualChannelsFile) fprintf('write_VirtualChannelsFile: Bad file name.\n'); VirtualChannelsFile return end % Check structure array Virtual if exist('Virtual')~=1 fprintf('writeVirtualChannels: Must specify structure Virtual.\n'); return elseif isempty(Virtual) | ~isstruct(Virtual) return elseif ~isfield(Virtual,'Name') | ~isfield(Virtual,'wt'); return elseif isempty(Virtual(1).Name) return end fid=fopen(VirtualChannelsFile,'w','ieee-be'); if fid<0 fprintf('writeCTFds (writeVirtualChannels): Could not open file %s\n',VirtualChannelsFile); return end fprintf(fid,'//Virtual channel configuration\n\n'); for k=1:length(Virtual) fprintf(fid,'VirtualChannel\n{\n\tName:\t%s\n\tUnit:\t%s\n',... Virtual(k).Name,Virtual(k).Unit); for q=1:size(Virtual(k).wt) % Floating format chosen to match VirtualChanels file creatd by % DataEditor (5.3.0-experimental-linux-20060918). fprintf(fid,'\tRef:\t%s,%0.6g\n',deblank(Virtual(k).chan(q,:)),Virtual(k).wt(q)); end fprintf(fid,'}\n\n'); end fclose(fid); return %%%%%%%%%%%%%% end of writeVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% Function updateDescriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ds=updateDescriptors(ds,comment,creatorSoftware,HLCcntrl); % Makes sure that certain tags are in structure infods, and makes sure that information % is transfered to infods and newds from res4. Updates several fields of res4 with % clinical use message (=comment) and name of creator program. % Inputs: ds : ds structure produced by readCTFds. % comment : Character string that is added to infods tags listed in addCommentTag % and res4 fields listed in addCommentField % creatorSoftware : Character string indicating that the data set was % created by writeCTFds. Added to infods tags listed in addCreatorTag and % appName field of res4. % HLCcntrl: If ds.infods is missing or empty, HLCcntrl determines the % _DATA_HZ_MODE tage of infods. if noit present or empty, HLCcntrl=0. % Creates a dummy infods structure if necessary using function make_dummy_infods. % Changes infods and newds to match information in % ds.res4.nf_run_title % ds.res4.collect_descriptor % ds.res4.nf_subject_id % ds.res4.nf_operator % Adds comment (clinical use message) and creator software name to infods, newds and hist files. if ~isfield(ds,'infods');ds.infods=[];end % infods tags that will display the comment. addCommentTag=strvcat('_PATIENT_ID','_PATIENT_INSTITUTE','_PROCEDURE_COMMENTS',... '_DATASET_COMMENTS','_DATASET_STATUS','_DATASET_PROCSTEPTITLE'); % res4 text fields that will display the comment addCommentField=strvcat('appName','dataOrigin','dataDescription',... 'nf_run_title','nf_subject_id','run_description'); % res4 text string lengths (from document "CTF MEG File Formats", PN900-0088) addCommentLength=[256 256 256 256 32 -1]'; % -1 indicates variable length % infods tags that will display the creator software. addCreatorTag=strvcat('_PROCEDURE_COMMENTS','_DATASET_STATUS',... '_DATASET_COLLECTIONSOFTWARE','_DATASET_CREATORSOFTWARE'); % res4 text fields that will display the creator software. addCreatorField=strvcat('appName','run_description'); addCreatorLength=[256 -1]'; % List of infods tags that will be set to ds.res4.fields (not necessarily fields listed in % addCommentField or addCreatorField addRes4Tag=strvcat('_PATIENT_ID','_DATASET_PROCSTEPTITLE',... '_DATASET_PROCSTEPDESCRIPTION','_DATASET_OPERATORNAME'); % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Add the Tags to infods. In most cases they will already be there, but just to be sure. addTag=strvcat(addRes4Tag,addCommentTag,addCreatorTag); tagClass=strvcat('_PATIENT','_PROCEDURE','_DATASET'); % List of all the tag names as a character array tagName=getArrayField(ds.infods,'name')'; if length(ds.infods)==1;tagName=tagName';end tagType=getArrayField(ds.infods,'type'); tagPtr=1; % If a class is missing, inject the class starting at tagPtr+1. for k=1:size(tagClass,1) addIndex=strmatch(deblank(tagClass(k,:)),addTag)'; % Are there any tags to be added in this class? if isempty(addIndex);continue;end % List of infods tags in the tagClass, but excluding the CPerist type (which marks the % start of a class. infodsIndex=strmatch(deblank(tagClass(k,:)),tagName); if isempty(infodsIndex) % Create a new class of tags. if strcmp(deblank(tagName(tagPtr+1,:)),'EndOfParameters') & k>1; tagPtr=tagPtr+1; end nTag=length(ds.infods); tagName((tagPtr+4):(nTag+3),:)=tagName((tagPtr+1):nTag,:); ds.infods((tagPtr+4):(nTag+3))=ds.infods((tagPtr+1):nTag); ds.infods(tagPtr+1)=struct('name',[deblank(tagClass(k,:)),'_INFO'],'type',2,'data',[]); ds.infods(tagPtr+2)=struct('name','WS1_','type',0,'data',[]); ds.infods(tagPtr+3)=struct('name','EndOfParameters','type',-1,'data',[]); tagName=strvcat(tagName(1:tagPtr,:),... strvcat([deblank(tagClass(k,:)),'_INFO'],'WS1_','EndOfParameters'),... tagName(tagPtr+1:nTag,:)); nTag=nTag+3; tagPtr=tagPtr+2; else if ds.infods(max(infodsIndex)).type==2 tagPtr=max(infodsIndex)+1; % Class consists of no tags beyond the CPersist definition else tagPtr=max(infodsIndex); % Class contains at least one real tag. end clear infodsIndex; end for q=addIndex if isempty(strmatch(deblank(addTag(q,:)),tagName)) tagName=strvcat(tagName(1:tagPtr,:),deblank(addTag(q,:)),tagName(tagPtr+1:nTag,:)); ds.infods((tagPtr+2):(nTag+1))=ds.infods((tagPtr+1):nTag); ds.infods(tagPtr+1)=struct('name',deblank(addTag(q,:)),'type',10,'data',char([])); tagPtr=tagPtr+1; nTag=nTag+1; end end end clear k q nTag tagPtr infodsIndex addIndex; % All of the tags in addTag have been added to ds.infods. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if exist('creatorSoftware')~=1; creatorSoftware=char([]); elseif ~ischar(creatorSoftware) creatorSoftware=char([]); else creatorSoftware=deblank(creatorSoftware); end if exist('comment')~=1; comment=char([]); elseif ~ischar(comment) comment=char([]); else comment=deblank(comment); end tagName=getArrayField(ds.infods,'name')'; % Update the res4 fields : add creator message. % Don't check field length, but truncate later. for q=1:size(addCreatorField,1); strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:)))); if isempty(strfind(strng,creatorSoftware)) newStrng=creatorSoftware; if ~isempty(strng);newStrng=[strng ' ' newStrng];end ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),newStrng); end end clear q strng nChar strng0 ns; % Update the res4 fields : add comment (= clinical use message) % Don't check field length, but truncate later. for q=1:size(addCommentField,1); strng=deblank(getfield(ds.res4,deblank(addCommentField(q,:)))); if isempty(strfind(strng,comment)) newStrng=comment; if ~isempty(strng);newStrng=[strng ' ' newStrng];end ds.res4=setfield(ds.res4,deblank(addCommentField(q,:)),newStrng); end end clear strng newStrng q; % Update res4.run_description ds.res4.run_description=[ds.res4.run_description,char(0)]; ds.res4.rdlen=length(ds.res4.run_description); % Update infods entries from .res4 fields ds.infods(strmatch('_PATIENT_ID',tagName)).data=deblank(ds.res4.nf_subject_id); ds.infods(strmatch('_DATASET_PROCSTEPTITLE',tagName)).data=deblank(ds.res4.nf_run_title); ds.infods(strmatch('_DATASET_PROCSTEPDESCRIPTION',tagName)).data=... deblank(ds.res4.nf_collect_descriptor); ds.infods(strmatch('_DATASET_OPERATORNAME',tagName)).data=deblank(ds.res4.nf_operator); % Truncate the .res4. fields. Leave room for a final char(0). for q=1:size(addCreatorField,1); strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:)))); if length(strng)>addCreatorLength(q)-1 & addCreatorLength(q)>0 ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),... strng(length(strng)+[-addCreatorLength(q)+2:0])); end end for q=1:size(addCommentField,1); strng=deblank(getfield(ds.res4,deblank(addCommentField(q,:)))); if length(strng)>addCommentLength(q)-1 & addCommentLength(q)>0 ds.res4=setfield(ds.res4,deblank(addCommentField(q,:)),... strng(length(strng)+[-addCommentLength(q)+2:0])); end end clear q strng; % Add creator software to infods tags. Have already cheked that the tags are there. for q=1:size(addCreatorTag,1) if isempty(strmatch(deblank(addCreatorTag(q,:)),addRes4Tag)) k=strmatch(deblank(addCreatorTag(q,:)),tagName); if length(k)==1 if isempty(strfind(ds.infods(k).data,creatorSoftware)) newStrng=creatorSoftware; if ~isempty(deblank(ds.infods(k).data)); newStrng=[deblank(ds.infods(k).data) ' ' newStrng]; end ds.infods(k).data=newStrng; end else fprintf('writeCTFds: Tag %s appears %d times in ds.infods ??\n',... deblank(addCreatorTag(q,:)),length(k)); end end end clear q k; % Add comment (clinical use statement) to ds.infods for q=1:size(addCommentTag,1) if isempty(strmatch(deblank(addCommentTag(q,:)),addRes4Tag)) k=strmatch(deblank(addCommentTag(q,:)),tagName); if length(k)==1 if isempty(strfind(ds.infods(k).data,comment)) newStrng=comment; if ~isempty(deblank(ds.infods(k).data)); newStrng=[deblank(ds.infods(k).data) ' ' newStrng]; end ds.infods(k).data=newStrng; end else fprintf(['writeCTFds (updateDescriptors): Tag %s appears %d times in ',... 'ds.infods ??\n'],deblank(addCommentTag(q,:)),length(k)); end end end clear q k; % Add the creator and comment information to the newds file if isfield(ds,'newds'); nChar=length(ds.newds); % Keyword positions aNpos=max(strfind(ds.newds,[char(9) 'appName:' char(9)])); if isempty(aNpos) fprintf(['writeCTFds (update_decsriptors): Keyword ''appName'' ',... 'does not appear in ds.newds.\n',... ' set ds.newds=[].\n']); ds.newds=char([]); else eol=max([11 min(strfind(ds.newds(aNpos+1:length(ds.newds)),char(10)))]); ds.newds=[ds.newds(1:(aNpos+eol-1)) ' ' creatorSoftware ' ' comment ... ds.newds((aNpos+eol):length(ds.newds))]; end clear nChar aNpos eol; end % Add clinical use message to hist file. if isfield(ds,'hist') & ~isempty(comment) ds.hist=[ds.hist char(10) comment char(10)]; end return %%%%%%%%%%%%%% End of updateDescriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% Function updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [infods,status]=updateHLC(infods,HLCdata); % Adds notes and continuous-head-localization tags to .infods file % Inputs : infods : Structure of tags to be written to output infods file. % HLCdata : 0 or [] or not defined - There are no HLC channels % (head-coil position) in the data. Just pass the existing tags to % the output dataset. % HLCdata : real array : size(HLCdata)=[samplesPerTrial 3 Ncoil nTrial] % Calculate the head motion tags. % Outputs : status : 0: Everything looks OK % 1: Couldn't find _DATASET tags. % <0: There is a problem with the new infods file. % Calls: % - getArrayField: Extracts field names from structure array S. % Defaults for the head localization tags. % Might do this better with a structure. HZ_MODE_UNKNOWN=2^31-1; % Bug in DataEditor and acquisition software, Oct. 2006 % Should be -1. % New dataset tags for HLC specification. addTag=strvcat('_DATASET_HZ_MODE',... '_DATASET_MOTIONTOLERANCE',... '_DATASET_MAXHEADMOTION',... '_DATASET_MAXHEADMOTIONTRIAL',... '_DATASET_MAXHEADMOTIONCOIL'); addTagType=[5 4 4 7 10]'; % Check HLCdata array. HLCdata=[] indicates no continuous head localization. if ~exist('HLCdata')==1 HLCdata=[]; elseif ~isempty(HLCdata) [samplesPerTrial nDim Ncoil nTrial]=size(HLCdata); if nDim~=3; fprintf('writeCTFds (updateHLC): size(HLCdata)=[');fprintf(' %d',size(HLCdata)); fprintf(']\n'); fprintf(' nDim=%d?? Setting HLCdata=[].\n',nDim); HLCdata=[]; end end % Assume that all the tag names are different. There is no checking when a tag listed in % addTag matches more than one entry in array name. name=getArrayField(infods,'name')'; %size(name)=[nTag lengthTag] DATASET_tags=strmatch('_DATASET',name)'; % size(DATASET_tags)=[1 nTag] if isempty(DATASET_tags) status=1; % No _DATASET tags. Don't add anything. else status=0; if isempty(HLCdata) TagValue(1)=HZ_MODE_UNKNOWN; TextTagValue=char(0); addTag=addTag(1,:); % Remove the other HLC tags addTagType=addTagType(1); else % ~isempty(HLCdata) % Remove HLC offsets. HLCoffset=squeeze(HLCdata(1,:,:,1)); for q=1:Ncoil for k=1:3 HLCdata(:,k,q,:)=HLCdata(:,k,q,:)-HLCoffset(k,q); end end % Calculate motions as displacement from the start of the dataset. absMotion=squeeze(sqrt(sum(HLCdata.^2,2))); %size(absMotion)=[samplesPerTrial Ncoil nTrial] maxCoilMotion=squeeze(max(absMotion,[],1)); % size(maxCoilMovement)=[Ncoil nTrial] maxHeadMotion=max(max(maxCoilMotion)); [mx maxHeadMotionCoil]=max(max(maxCoilMotion,[],2)); [mx maxHeadMotionTrial]=max(max(maxCoilMotion,[],1)); % Create a list of head motion tag values TagValue(1)=5; % Indicates continuous head localization TagValue(2)=max(2*maxHeadMotion,0.02); % _DATASET_MOTIONTOLERANCE TagValue(3)=maxHeadMotion; % _DATASET_MAXHEADMOTION % Subtract 1 from the trial so trial numbering starts at 0. TagValue(4)=maxHeadMotionTrial-1; % _DATASET_MAXHEADMOTIONTRIAL TextTagValue=char(zeros(4,1)); % Placeholder since tags1:4 are numerical % _MAXHEADMOTIONCOIL value TextTagValue=strvcat(TextTagValue,sprintf('%d',maxHeadMotionCoil)); TagValue=[TagValue 0]; % Placeholder only since the 5th tag is a text string. end % Add or insert tags. for q=1:size(addTag,1) nTag=length(infods); tagName=deblank(addTag(q,:)); TagNo=strmatch(tagName,name,'exact')'; if isempty(TagNo) % Insert a tag at the end of the _DATASET tags. TagNo=max(DATASET_tags)+1; infods((TagNo+1):(nTag+1))=infods(TagNo:nTag); name=strvcat(name(1:TagNo-1,:),tagName,name(TagNo:nTag,:)); DATASET_tags=[DATASET_tags TagNo]; end if addTagType(q)~=10 infods(TagNo)=struct('name',tagName,'type',addTagType(q),'data',TagValue(q)); else infods(TagNo)=struct('name',tagName,'type',addTagType(q),... 'data',deblank(TextTagValue(q,:))); end end % End loop over head position and head motion tags. clear q TagNo TextTagValue TagValue; end % End section add _DATASET tags return %%%%%%%%%%%%%% End of updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% Function updateBandwidth %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ds=updateBandwidth(ds,fhp,flp); % Updates the bandwidth fields of infods and newds. % 3 possible dources of bandwidth: % 1. fhp,flp inputs (default) % 2. newds fiels % 3. res4.filter % 4. infods field % Almost always, fhp,flp will have the default values, but it could be defined in the % fields of ds, so check. Result: lots of code to achieve a simple result. % read fhp,flp from newds (if it exists) if isfield(ds,'newds') BWpos=max(strfind(ds.newds,[char(9) 'bandwidth:' char(9)])); % Keyword position if isempty(BWpos) fprintf(['writeCTFds (updateBandwidth): Keyword ''bandwidth:''',... 'does not appear in ds.newds.\n',... ' Field newds removed from structure ds.\n']); ds=rmfield(ds,'newds'); else % Get the bandwidth parameters from ds.newds. eol=max([13 min(strfind(ds.newds(BWpos+1:length(ds.newds)),char(10)))]); buff=sscanf(ds.newds((BWpos+13):(BWpos+eol)),'%f%c%f'); fhp=max(fhp,buff(1)); flp=min(flp,buff(3)); end clear eol buff BWpos; end % Get fhp, flp from res4. if ~isempty(ds.res4.filters) for kq=1:ds.res4.num_filters freq=ds.res4.filters(kq).freq; if ds.res4.filters(kq).fType==1; flp=min(flp,freq); elseif ds.res4.filters(kq).fType==2; fhp=max(fhp,freq); end end clear kq freq; end % Get fhp, flp from ds.infods if isfield(ds,'infods') name=getArrayField(ds.infods,'name')'; TagNo=strmatch('_DATASET_LOWERBANDWIDTH',name,'exact'); if ~isempty(TagNo);fhp=max(fhp,ds.infods(TagNo).data);end TagNo=strmatch('_DATASET_UPPERBANDWIDTH',name,'exact'); if ~isempty(TagNo);flp=min(flp,ds.infods(TagNo).data);end end % Now have fhp,flp. Update hist. Add all the res4 filters. if ~isempty(ds.res4.filters) if ~isfield(ds,'hist');hist=char([]);end ds.hist=[ds.hist 'Filters specified in res4 file :' char(10)]; for kq=1:ds.res4.num_filters freq=ds.res4.filters(kq).freq; if ds.res4.filters(kq).fType==1; ds.hist=[ds.hist ... num2str(kq,'%8d') ' Lowpass ' num2str(freq,'%6.2f') ' Hz' char(10)]; elseif ds.res4.filters(kq).fType==2; ds.hist=[ds.hist ... num2str(kq,'%8d') ' Highpass ' num2str(freq,'%6.2f') ' Hz' char(10)]; elseif ds.res4.filters(kq).fType==3; ds.hist=[ds.hist num2str(kq,'%8d') ' Notch ' num2str(freq,'%6.2f') ... ' Hz width=' num2str(ds.res4.filters(kq).Param,'%6.2f') ' Hz' char(10)]; else ds.hist=[ds.hist ' fType=',num2str(ds.res4.filters(kq).fType,'%d') char(10)]; end end ds.hist=[ds.hist ,... 'Bandwidth: ',num2str(fhp,'%0.3g'),' - ',num2str(flp,'%0.3g'),' Hz',char(10)]; clear kq freq; end % Update newds bandwidth if isfield(ds,'newds') BWpos=max(strfind(ds.newds,[char(9) 'bandwidth:' char(9)])); eol=max([12 min(strfind(ds.newds(BWpos+1:length(ds.newds)),char(10)))]); ds.newds=[ds.newds(1:BWpos+11) num2str(fhp,'%0.6f') ', ' num2str(flp,'%0.6f') ... ds.newds((BWpos+eol):length(ds.newds))]; clear BWpos eol; end % Update infods bandwidth tags. Lots of coding becasue it's possible that infods does % not already have bandwidth tags. name=getArrayField(ds.infods,'name')'; DATASET_tags=strmatch('_DATASET_',name); if ~isempty(DATASET_tags) addTag=strvcat('_DATASET_LOWERBANDWIDTH','_DATASET_UPPERBANDWIDTH'); TagValue=[fhp flp]; % Add or update tags. for q=1:size(addTag,1) nTag=length(ds.infods); TagNo=strmatch(deblank(addTag(q,:)),name,'exact')'; if isempty(TagNo) % Insert a tag at the end of the _DATASET tags. TagNo=max(DATASET_tags)+1; ds.infods((TagNo+1):(nTag+1))=ds.infods(TagNo:nTag); ds.infods(TagNo)=struct('name',deblank(addTag(q,:)),'type',4,'data',TagValue(q)); name=strvcat(name(1:TagNo-1,:),deblank(addTag(q,:)),name(TagNo:nTag,:)); DATASET_tags=[DATASET_tags TagNo]; else ds.infods(TagNo).data=TagValue(q); % Tag exists. Just update the value. end end % End loop over head position and head motion tags. clear q nTag DATASET_tags; else fprintf(['writeCTFds (updateBandwidth): Found no _DATASET tags in infods.\n'... '\t\t\tDid not add bandwidth tags.\n']); end return %%%%%%%%%%%%%% End of updateBandwidth %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% Function updateDateTime %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ds=updateDateTime(ds); % Update the dat/time fields of res4 and and infods datetime=floor(clock); if isfield(ds,'infods'); name=getArrayField(ds.infods,'name')'; DATASET_tags=strmatch('_DATASET_',name); if ~isempty(DATASET_tags) addTag=strvcat('_DATASET_CREATORDATETIME','_DATASET_LASTMODIFIEDDATETIME'); tagData=sprintf('%d%2.2d%2.2d%2.2d%2.2d%2.2d',datetime); tagType=10; for q=1:size(addTag,1) nTag=length(ds.infods); TagNo=strmatch(deblank(addTag(q,:)),name,'exact')'; if isempty(TagNo) % Insert a tag at the end of the _DATASET tags. TagNo=max(DATASET_tags)+1; ds.infods((TagNo+1):(nTag+1))=ds.infods(TagNo:nTag); name=strvcat(name(1:TagNo-1,:),deblank(addTag(q,:)),name(TagNo:nTag,:)); DATASET_tags=[DATASET_tags TagNo]; end ds.infods(TagNo)=struct('name',deblank(addTag(q,:)),'type',tagType,'data',tagData); end clear nTag TagNo name DATASET_tags addTag tagData tagType; else fprintf('writeCTFds (updateDateTime): Cannot find any _DATASET tags in ds.infods.\n'); end % End loop over head position and head motion tags. else fprintf('writeCTFds (updateDateTime): Cannot find ds.infods.\n'); end ds.res4.data_date=sprintf('%4d/%2.2d/%2.2d',datetime(1:3)); ds.res4.data_time=sprintf('%2.2d:%2.2d:%2.2d',datetime(4:6)); return %%%%%%%%%%%%%% End of updateDateTime %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% Function getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x=getArrayField(S,yfield) % Extracts one field of a structure array. % Inputs: S : structure array. % yfield: name of field of S (string) % Output: x. x(:,n)=S(n).yfield; size(x)=[size(yfield) length(S)] % Field sizes: Two options: % 1. size(S(n).yfield) is the same for all n. Any size allowed. % 2. S(n).yfield is a 2-D array for all structure elements S(n). % Then yfield of different array elements S(n) can have different sizes. % The array returned will be large enough to accomodate all of the data. sizeS=size(S); nS=prod(sizeS); S=reshape(S,1,nS); % Determine which array-size option to use. sizey=size(getfield(S,{1},yfield)); option1=1; option2=(length(sizey)==2); for n=2:nS sizeyn=size(getfield(S,{n},yfield)); option1=option1 & isequal(sizey,sizeyn); option2=option2 & length(sizeyn)==2; if option2 sizey=max([sizey;sizeyn],[],1); end end if option1 % All fields have the same size nY=prod(sizey); if isnumeric(getfield(S,{1},yfield)) x=zeros(nY,nS); elseif ischar(getfield(S,{1},yfield)) x=char(zeros(nY,nS)); end for n=1:nS x(:,n)=reshape(getfield(S,{n},yfield),nY,1); end x=reshape(x,[sizey nS]); elseif option2 % All fields have only two dimensions if isnumeric(getfield(S,{1},yfield)) x=zeros([sizey nS]); elseif ischar(getfield(S,{1},yfield)) x=char(zeros([sizey nS])); end for n=1:nS y=getfield(S,{n},yfield); sizeyn=size(y); x(1:sizeyn(1),1:sizeyn(2),n)=y; end else fprintf(['getArrayField: Field %s of the structure array has >2 dimensions ',... 'and not all field have the same size.\n'],yfield); x=[]; end x=squeeze(x); return %%%%%%%% End of getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
lcnhappe/happe-master
writeRes4.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/ctf/writeRes4.m
8,560
utf_8
416bc2b62624835c63140e54415d2f49
function res4=writeRes4(res4File,res4,MAX_COILS); % Write the new .res4 file. Use ieee-be (big endian) format % Character-string output is done using function writeCTFstring which % checks that strings are the correct length for the .res4 file format. % Function calls: - writeCTFstring (included in this listing). fid_res4=fopen(res4File,'w','ieee-be'); if fid_res4<0 fprintf('writeCTFds (writeRes4): Could not open file %s\n',res4File); return end fwrite(fid_res4,[res4.header(1:7),char(0)],'uint8'); % 8-byte header % meg41GeneralResRec res4.appName=writeCTFstring(res4.appName,-256,fid_res4); res4.dataOrigin=writeCTFstring(res4.dataOrigin,-256,fid_res4); res4.dataDescription=writeCTFstring(res4.dataDescription,-256,fid_res4); fwrite(fid_res4,res4.no_trials_avgd,'int16'); res4.data_time=writeCTFstring(res4.data_time,255,fid_res4); res4.data_date=writeCTFstring(res4.data_date,255,fid_res4); % new_general_setup_rec_ext part of meg41GeneralResRec fwrite(fid_res4,res4.no_samples,'int32'); % 4 fwrite(fid_res4,[res4.no_channels 0],'int16'); % 2*2 fwrite(fid_res4,res4.sample_rate,'double'); % 8 fwrite(fid_res4,res4.epoch_time,'double'); % 8 fwrite(fid_res4,[res4.no_trials 0],'int16'); % 2*2 fwrite(fid_res4,res4.preTrigPts,'int32'); % 4 fwrite(fid_res4,res4.no_trials_done,'int16'); % 2 fwrite(fid_res4,res4.no_trials_display,'int16'); % 2 fwrite(fid_res4,res4.save_trials,'int32'); % 4 CTFBoolean % meg41TriggerData part of new_general_setup_rec_ext 10 bytes total fwrite(fid_res4,res4.primaryTrigger,'int32'); % 4 fwrite(fid_res4,res4.triggerPolarityMask,'int32'); % 4 fwrite(fid_res4,[0 0],'uint8'); % 2 bytes % end of meg41TriggerData part of new_general_setup_rec_ext fwrite(fid_res4,[0 0],'uint8'); % 2 bytes padding fwrite(fid_res4,[res4.trigger_mode 0],'int16'); % 2*2 fwrite(fid_res4,res4.accept_reject_Flag,'int32'); % 4 CTFBoolean fwrite(fid_res4,[res4.run_time_display 0],'int16');% 2*2 fwrite(fid_res4,res4.zero_Head_Flag,'int32'); % 4 CTFBoolean fwrite(fid_res4,res4.artifact_mode,'int32'); % 4 CTFBoolean % end of new_general_setup_rec_ext part of meg41GeneralResRec % meg4FileSetup part of meg41GeneralResRec res4.nf_run_name=writeCTFstring(res4.nf_run_name,32,fid_res4); res4.nf_run_title=writeCTFstring(res4.nf_run_title,-256,fid_res4); res4.nf_instruments=writeCTFstring(res4.nf_instruments,32,fid_res4); res4.nf_collect_descriptor=writeCTFstring(res4.nf_collect_descriptor,32,fid_res4); res4.nf_subject_id=writeCTFstring(res4.nf_subject_id,-32,fid_res4); res4.nf_operator=writeCTFstring(res4.nf_operator,32,fid_res4); res4.nf_sensorFileName=writeCTFstring(res4.nf_sensorFileName,56,fid_res4); res4.rdlen=length(res4.run_description); % Run_description may have been changed. fwrite(fid_res4,[0 res4.rdlen 0],'int32'); % 12-byte structure of the .res4 file. res4.run_description=writeCTFstring(res4.run_description,res4.rdlen,fid_res4); % end of meg4FileSetup part of meg41GeneralResRec % filter descriptions fwrite(fid_res4,res4.num_filters,'int16'); for kfilt=1:res4.num_filters fwrite(fid_res4,res4.filters(kfilt).freq,'double'); fwrite(fid_res4,res4.filters(kfilt).fClass,'int32'); fwrite(fid_res4,res4.filters(kfilt).fType,'int32'); fwrite(fid_res4,res4.filters(kfilt).numParam,'int16'); for kparm=1:res4.filters(kfilt).numParam fwrite(fid_res4,res4.filters(kfilt).Param(kparm),'double'); end end % Write channel names. Must have size(res4.chanNames)=[nChan 32] [no_chanNames len_chanNames]=size(res4.chanNames); for kchan=1:res4.no_channels res4.chanNames(kchan,:)=writeCTFstring(res4.chanNames(kchan,:),len_chanNames,fid_res4); end % Write sensor resource table for kchan=1:res4.no_channels fwrite(fid_res4,res4.senres(kchan).sensorTypeIndex,'int16'); fwrite(fid_res4,res4.senres(kchan).originalRunNum,'int16'); fwrite(fid_res4,res4.senres(kchan).coilShape,'int32'); fwrite(fid_res4,res4.senres(kchan).properGain,'double'); fwrite(fid_res4,res4.senres(kchan).qGain,'double'); fwrite(fid_res4,res4.senres(kchan).ioGain,'double'); fwrite(fid_res4,res4.senres(kchan).ioOffset,'double'); fwrite(fid_res4,res4.senres(kchan).numCoils,'int16'); numCoils=res4.senres(kchan).numCoils; fwrite(fid_res4,res4.senres(kchan).grad_order_no,'int16'); fwrite(fid_res4,0,'int32'); % Padding to 8-byte boundary % coilTbl for qx=1:numCoils fwrite(fid_res4,[res4.senres(kchan).pos0(:,qx)' 0],'double'); fwrite(fid_res4,[res4.senres(kchan).ori0(:,qx)' 0],'double'); fwrite(fid_res4,[res4.senres(kchan).numturns(qx) 0 0 0],'int16'); fwrite(fid_res4,res4.senres(kchan).area(qx),'double'); end if numCoils<MAX_COILS fwrite(fid_res4,zeros(10*(MAX_COILS-numCoils),1),'double'); end %HdcoilTbl for qx=1:numCoils fwrite(fid_res4,[res4.senres(kchan).pos(:,qx)' 0],'double'); fwrite(fid_res4,[res4.senres(kchan).ori(:,qx)' 0],'double'); fwrite(fid_res4,[res4.senres(kchan).numturns(qx) 0 0 0],'int16'); fwrite(fid_res4,res4.senres(kchan).area(qx),'double'); end if numCoils<MAX_COILS fwrite(fid_res4,zeros(10*(MAX_COILS-numCoils),1),'double'); end end % End writing sensor resource table % Write the table of balance coefficients. if res4.numcoef<=0 fwrite(fid_res4,res4.numcoef,'int16'); % Number of coefficient records elseif res4.numcoef>0 scrx_out=[]; for kx=1:res4.numcoef sName=strtok(char(res4.scrr(kx).sensorName),['- ',char(0)]); if ~isempty(strmatch(sName,res4.chanNames)) scrx_out=[scrx_out kx]; end end % Remove the extra coefficient records res4.scrr=res4.scrr(scrx_out); res4.numcoef=size(res4.scrr,2); fwrite(fid_res4,res4.numcoef,'int16'); % Number of coefficient records % Convert res4.scrr to double before writing to output file. In MATLAB 5.3.1, % when the 'ieee-be' option is applied, fwrite cannot write anything except % doubles and character strings, even if fwrite does allow you to specify short % integer formats in the output file. for nx=1:res4.numcoef fwrite(fid_res4,double(res4.scrr(nx).sensorName),'uint8'); fwrite(fid_res4,[double(res4.scrr(nx).coefType) 0 0 0 0],'uint8'); fwrite(fid_res4,double(res4.scrr(nx).numcoefs),'int16'); fwrite(fid_res4,double(res4.scrr(nx).sensor),'uint8'); fwrite(fid_res4,res4.scrr(nx).coefs,'double'); end end fclose(fid_res4); return % ************************************************************************************* %*************** Function writeCTFstring ************************************************ function strng=writeCTFstring(instrng,strlen,fid) % Writes a character string to output unit fid. Append nulls to get the correct length. % instrng : Character string. size(instrng)=[nLine nPerLine]. strng is reformulated as a % long string of size [1 nChar]. Multiple lines are allowed so the user can % easily append text. If necessary, characters are removed from % instrng(1:nLine-1,:) so all of strng(nLine,:) can be accomodated. % strlen: Number of characters to write. strlen<0 means remove leading characters. % If abs(strlen)>length(strng) pad with nulls (char(0)) % If 0<strlen<length(strng), truncate strng and terminate with a null. % If -length(string)<strlen<0, remove leading characters and terminate with a null. % Form a single long string nLine=size(instrng,1); strng=deblank(instrng(1,:)); if nLine>1 % Concatenate lines 1:nLine-1 for k=2:nLine-1 if length(strng)>0 if ~strcmp(strng(length(strng)),'.') & ~strcmp(strng(length(strng)),',') strng=[strng '.']; % Force a period at the end of the string. end end strng=[strng ' ' deblank(instrng(k,:))]; end if length(strng)>0 if ~strcmp(strng(length(strng)),'.') % Force a period at the end of the string. strng=[strng '.']; end end % Add all of the last line. nChar=length(strng); nLast=length(deblank(instrng(nLine,:))); strng=[strng(1:min(nChar,abs(strlen)-nLast-4)) ' ' deblank(instrng(nLine,:))]; end if length(strng)<abs(strlen) strng=[strng char(zeros(1,abs(strlen)-length(strng)))]; elseif length(strng)>=strlen & strlen>0 strng=[strng(1:strlen-1) char(0)]; else strng=[strng(nLast+[strlen+2:0]) char(0)]; end fwrite(fid,strng,'char'); return % ************* End of function writeCTFstring *************************************** % ************************************************************************************
github
lcnhappe/happe-master
addCTFtrial.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/ctf/addCTFtrial.m
51,483
utf_8
b59730fdb231f07741e7e87dea9e6c1c
function cntrl=addCTFtrial(datasetname,data,unit,mrk,cls,badSegments); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % This program creates datasets that can be analyzed by CTF software. % % % % Datasets created by this program MUST NOT BE USED FOR CLINICAL APPLICATIONS. % % % % Please do not redistribute it without permission from VSM MedTech Ltd. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % addCTFtrial.m Version 1.1 Adds trial(s) to a a CTF-format data set previously % created from MATLAB by writeCTFds.m. The purpose of addCTFtrial is to allow % users to write CTF data sets that are too large for the computer's memory. % Date : 18 April 2007 % Author : Harold Wilson % Operation : % 1. Use writeCTFds to create a dataset (name = DATASET) consisting of one or % more trials. size(data)= [SAMPLES, CHANNELS, TRIALS]. % 2. Later, a trial is to be added to DATASET. This program adds the new information % to the .res4, .mrk, .cls and badSegements files and appends the new data to the % existing .meg4 file. % Inputs : datasetname : Dataset including path. Extension '.ds' is optional. % data : MEG data array. size(data)=[no_samples no_channels no_trials_added] % Array data may be single or double. % unit : Determines the unit of the SQUID and EEG signals: % If unit is missing or unit==[], the unit is set to 'fT'. % 'ft' or 'fT' : Convert to fT (MEG), uV (EEG) % 't' or 'T' : Convert to T (MEG), V (EEG) % 'phi0' : Convert to phi0 (MEG), uV (EEG) % 'int': Read plain integers from *.meg4-file % mrk,cls,badSegments : Structures describing the markers, trial classes and bad % segments of the new trials. Trial numbering refers to the new trials % being added to the dataset, starting at trial=1. Markers are updated % only when there is already as .mrk file in the dataset. % Outputs : - Dataset with trial(s) added. % - cntrl : 0 - failure. The dataset is not modified. % 1 - success. The new data is added to the dataset % Function calls % Included in this listing: % - combineMarkers: Combines marker specifications in structures ds.mrk and mrk. % - combineClasses: Combines trial class specifications in structures % ds.TrialClass and cls. % - writeBadSegments: Creates the new bad.segments file. % - writeClassFile: Creates the new ClassFile.cls file. % - updateCreatorSoftware: Adds non-clinical-use and creation software messages to % infods, res4, newds and hist fields of ds. % - updateHLC: Adds head-coil movement information from the trials being added to an % existing ds.infods. % - getArrayField : Extracts one field of a structure array to make it easier to % manipulate. % Not included in this listing: % - writeRes4: Writes the new .res4 file. % - writeMarkerFile: Creates the new MarkerFile.mrk file. % - writeCPersist: Creates the new .acq and .infods files. % Output files are opened with 'w' permission and 'ieee-be' machine format in order % to be compatible with the Linux acquisition and analysis software. Do not open files % with 'wt' permission because this will add an extra byte (char(13)) at the end of each % line of text. %persistent printWarning % No clinical-use warning with addCTFtrial. %printWarning=1; delim=filesep; if nargin==0 & nargout==0 % Print a version number fprintf(['\taddCTFtrial: Version 1.1 18 April 2007 ',... 'Adds trials to v4.1 and v4.2 CTF data sets.\n',... '\tCall: cntrl=addCTFtrial(datasetname,data,unit,mrk,cls,badSegments);\n',... '\t\tdatasetname = Name of existing dataset including the path.\n',... '\t\tdata = Data that will be written to the new dataset .meg4 file.\n',... '\t\tunit = Physical units of the data.\n',... '\t\tmrk,cls,badSegments = descriptions of markers, trial classes and',... ' bad segments of data.\n\n']); return end % Indicate failure on an early return. cntrl=0; % Allowed 8-byte headers for res4 and meg4 files. res4_headers=strvcat(['MEG41RS',char(0)],['MEG42RS',char(0)]); meg4_headers=strvcat(['MEG41CP',char(0)],['MEG42CP',char(0)]); MAX_COILS=8; % Parameter that determines the size of the ds.res4.senres structure. maxMEG4Size=2^31; % Maximum MEG$ file in bytes. (Limit set by Linux software) % addCTFds will add trials to datasets only if they were created by writeCTFds. originalCreatorSoftware='writeCTFds'; creatorSoftware='addCTFtrial'; % Added to .infods file meg4ChunkSize=2^20; % Write new .meg4 file in chunks of 4*meg4ChunkSize bytes. clinical_use_message='NOT FOR CLINICAL USE'; if ~exist('clinical_use_message'); clinical_use_message=char([]); end % Check number of inputs if nargin<2 fprintf(['addCTFtrial: Must supply inputs datasetname,data. ',... 'Only %d input arguments are present.\n'],nargin); return end % Check input argument unit. Convert unit to lower case. if exist('unit')~=1 unit='ft'; % default elseif isempty(unit) unit='ft'; % default elseif ischar(unit) unit=lower(unit); if ~strcmp(unit,'int') & ~strcmp(unit,'ft') & ~strcmp(unit,'t') & ~strcmp(unit,'phi0') fprintf(['addCTFtrial : unit=%s Not a valid option. Must be ',... '''fT'', ''T'', ''phi0'' or ''int''\n'],unit); ds=-1; % Force an error in the calling program. return end end % Check argument type if ~isnumeric(data) fprintf('\naddCTFtrial: Input data is not numeric.\n'); return elseif ~ischar(unit) fprintf('\naddCTFtrial: Input unit is not char.\n'); return elseif~ischar(datasetname) fprintf('\naddCTFtrial: Input datasetname is not char.\n'); return end if exist('mrk')==1 if ~isstruct(mrk) fprintf('\naddCTFtrial: Input mrk is not a structure.\n\n'); return end else mrk=struct([]); end if exist('cls')==1 if ~isstruct(cls) fprintf('\naddCTFtrial: Input cls is not a structure.\n\n'); return end else cls=struct([]); end if exist('badSegments')==1 if ~isstruct(badSegments) fprintf('\naddCTFtrial: Input badSegments is not a structure.\n\n'); return end else badSegments=struct([]); end % Does the dataset exist? if exist(datasetname)~=7 fprintf('addCTFtrial: Dataset %s does not exist.\n',datasetname); return end % Separate datasetname into a path and the baseName datasetname=deblank(datasetname); ksep=max([0 findstr(datasetname,delim)]); baseName=datasetname((ksep+1):length(datasetname)); path=datasetname(1:ksep); % String path is terminated by the file delimiter (or path=[]). % Remove the last .ds from baseName. kdot=max(findstr(baseName,'.ds')); if kdot==(length(baseName)-2) baseName=baseName(1:(max(kdot)-1)); else datasetname=[datasetname,'.ds']; end clear ksep kdot; % Get the ds structure of the dataset ds=readCTFds(datasetname); % Update text fields of res4,infods, newds. ds=updateCreatorSoftware(ds,creatorSoftware,originalCreatorSoftware); if isempty(ds);return;end nSample=ds.res4.no_samples; fSample=ds.res4.sample_rate; nChan=ds.res4.no_channels; % Check that the new data and the existing data have the same number of channels % and points per trial. if size(data,1)~=nSample | size(data,2)~=nChan | size(data,3)==0 fprintf(['addCTFtrial: size(data)=[%d %d %d], but existing data has no_samples=%d,',... ' no_channels=%d\n'],[size(data,1) size(data,2) size(data,3)],... nSample,nChan); return end % Update ds.res4 fields to match the size of array data. nTrialNew=size(data,3); nTrialOld=ds.res4.no_trials; ds.res4.no_trials=nTrialOld+nTrialNew; ds.res4.epoch_time=nSample*ds.res4.no_trials/fSample; % Before converting data to integers, save the HLC channels for motion analysis in function % function updateHLC. if isempty(strmatch('HLC',ds.res4.chanNames)) HLCdata=[]; else % Make a list of head-coil channels coil=0; HLClist=[]; while ~isempty(strmatch(['HLC00',int2str(coil+1)],ds.res4.chanNames)) coil=coil+1; for k=1:3 HLClist=[HLClist strmatch(['HLC00',int2str(coil),int2str(k)],ds.res4.chanNames)]; end end HLCdata=reshape(double(data(:,HLClist,:)),nSample,3,coil,nTrialNew); clear coil k HLClist; end % Convert data to integers because CTF data sets are stored as raw numbers and % not as physical qunatities. The res4 file contains the calibrations for % converting back to physical units. Array data may be single precision, so % convert to double before doing any adjustments to the data. % Already checked that unit is valid. if strcmp(unit,'int') data=reshape(data,nSample,nChan*nTrialNew); for k=1:nChan*nTrialNew if strcmp(class(data),'single') data(:,k)=single(round(double(data(:,k)))); else data(:,k)=round(double(data(:,k))); end end data=reshape(data,nSample,nChan,nTrialNew); clear k; else for chan=1:nChan % Convert EEGs from uV to V, SQUIDs from fT to T SQUIDtype=any(ds.res4.senres(chan).sensorTypeIndex==[0:7]); EEGtype=any(ds.res4.senres(chan).sensorTypeIndex==[8 9]); if EEGtype & (strcmp(unit,'ft') | strtcmp(unit,'phi0')) alphaG=1e-6; elseif SQUIDtype & strcmp(unit,'ft') alphaG=1e-15; elseif SQUIDtype & strcmp(unit,'phi0') alphaG=1./(ds.res4.senres(chan).properGain*ds.res4.senres(chan).ioGain); else alphaG=1; end % Convert from physical units to integers using the gains in the senres table. for kt=1:nTrialNew buff=round(double(data(:,chan,kt))*(alphaG*... (ds.res4.senres(chan).properGain*ds.res4.senres(chan).qGain*ds.res4.senres(chan).ioGain))); if strcmp(class(data),'single') data(:,chan,kt)=single(buff); else data(:,chan,kt)=buff; end end end clear chan alphaG SQUIDtype EEGtype buff kt; end % Check the meg4 file header. fidMeg4=fopen([path,baseName,'.ds\',baseName,'.meg4'],'r','ieee-be'); fileHeader=fread(fidMeg4,8,'char')'; fclose(fidMeg4); if isempty(strmatch(fileHeader(1:7),meg4_headers(:,1:7),'exact')) ds.meg4.header=meg4_headers(1,1:7); fprintf('addCTFtrial: meg4 header=%s ?\n',fileHeader); return end % Create the .res4 file in the output dataset. ds.res4=writeRes4([path,baseName,'.ds\',baseName,'.res4'],ds.res4,MAX_COILS); if ds.res4.numcoef<0 fprintf('addCTFtrial: writeRes4 returned ds.res4.numcoef=%d (<0??)\n',ds.res4.numcoef); fprintf(' Deleting dataset %s\n',baseName); rmdir([path,baseName,'.ds'],'s'); return end % Add trial(s) to the existing meg4 file. Complicated coding in case the use requests % writing several trials, which fill up one meg4 file and start the next one. ptsPerTrial=nSample*nChan; data=reshape(data,ptsPerTrial,nTrialNew); maxTrialPerFile=floor((maxMEG4Size-8)/(4*ptsPerTrial)); maxPtsPerFile=ptsPerTrial*maxTrialPerFile; nExt=-1; trial=0; pt=0; while trial<nTrialNew nExt=nExt+1; if nExt==0 meg4Ext='.meg4'; else meg4Ext=['.',int2str(nExt),'_meg4']; end meg4File=[path,baseName,'.ds\',baseName,meg4Ext]; D=dir(meg4File); if isempty(D) % Create the next meg4 file and write the header. fidMeg4=fopen(meg4File,'w','ieee-be'); fwrite(fidMeg4,[ds.meg4.header(1:7),char(0)],'uint8'); fclose(fidMeg4); D=struct('bytes',8); end nWrite=min(nTrialNew-trial,floor((maxMEG4Size-D.bytes)/(4*ptsPerTrial))); %fprintf('nExt=%d meg4File=%s\n\t\tsize=%d bytes nWrite=%d\n',nExt,meg4File,D.bytes,nWrite); if nWrite>0 fidMeg4=fopen(meg4File,'a','ieee-be'); endPt=pt+nWrite*ptsPerTrial; while pt<endPt pt1=min(pt+meg4ChunkSize,endPt); % Convert to double in case data is fwrite(fidMeg4,double(data(pt+1:pt1)),'int32'); % single. This may cause memory pt=pt1; % problems so write in short pieces. end fclose(fidMeg4); trial=trial+nWrite; end end clear trial pt meg4Ext meg4File D fidMeg4 nWrite endPt pt1; % Set variable cntrl to indicate that the meg4 and res4 files have been updated. cntrl=1; % Update the .meg4 part of structure ds. ds.meg4.fileSize=8*(nExt+1); clear data pt pt1 ndata fidMeg4; % Add dataset names to .hist, and write new .hist file. if ~isfield(ds,'hist'); ds.hist=char([]); else q0=max(strfind(ds.hist,originalCreatorSoftware)); if ~isempty(q0) & isempty(strfind(ds.hist(q0:length(ds.hist)),creatorSoftware)) ds.hist=[ds.hist(1:q0+length(originalCreatorSoftware)-1) ', ' creatorSoftware ... ds.hist(q0+length(originalCreatorSoftware):length(ds.hist))]; end % Create .hist file histfile=[path,baseName,'.ds\',baseName,'.hist']; fid=fopen(histfile,'w'); fwrite(fid,ds.hist,'char'); fclose(fid); end % Add HLC data and write new infods file. if isfield(ds,'infods') ds.infods=updateHLC(ds.infods,HLCdata); writeCPersist([path,baseName,'.ds',delim,baseName,'.infods'],ds.infods); end clear HLCdata; % New .newds file. if isfield(ds,'newds') fid=fopen([path,baseName,'.ds\',baseName,'.newds'],'w'); fwrite(fid,ds.newds,'char'); fclose(fid); end % Add markers, and create new MarkerFile.mrk if isfield(ds,'mrk') mrk=combineMarkers(ds.mrk,nTrialOld,mrk,nTrialNew,ds.res4); if ~isempty(mrk) writeMarkerFile([path,baseName,'.ds',delim,'MarkerFile.mrk'],mrk); end elseif ~isempty(mrk) fprintf(['addCTFtrial: Existing dataset has no MarkerFile, but structure mrk is',... ' specified in call to addCTFtrial.\n',... ' MarkerFile.mrk not created.\n']); end % bad.segments file if isfield(ds,'badSegments') & ~isempty(badSegments) ds.badSegments.trial=[ds.badSegments.trial badSegments.trial+nTrialOld]; ds.badSegments.StartTime=[ds.badSegments.StartTime badSegments.StartTime]; ds.badSegments.EndTime=[ds.badSegments.EndTime badSegments.EndTime]; writeBadSegments([path,baseName,'.ds',delim,'bad.segments'],ds.badSegments,... ds.res4.no_trials,nSample/fSample); end % ClassFile. Add trial classes, and create new ClassFile.cls if ~isempty(cls) if isfield(ds,'TrialClass') cls=combineClasses(ds.TrialClass,nTrialOld,cls,nTrialNew); if ~isempty(cls) writeClassFile([path,baseName,'.ds',delim,'ClassFile.cls'],cls); end else fprintf(['addCTFtrial: Existing dataset has no ClassFile, but structure cls is',... ' specified in call to addCTFtrial.\n',... ' ClassFile.cls not created.\n']); end end return % *************** End of function addCTFtrial ******************************************** % ************************************************************************************** % ************************************************************************************** % ************* function make_dummy_infods********************************************* function Tag=make_dummy_infods(exist_hc,exist_HLC,sample_rate); % If the user does not supply ds.infos, this code makes a dummy version. It has all of % the tags that Acq created in file Richard_SEF_20060606_04.infods. % *********************************************************************************** % *********************************************************************************** DATASET_HZ_UNKNOWN=round(2^31-1); % Peculiar requirement of DataEditor as of 23 Oct. 2006 fprintf('writeCTDds (make_dummy_infods): Creating a dummy infods file with all the tags.\n'); Tag(1)=struct('name','WS1_','type',0,'data',[]); Tag(length(Tag)+1)=struct('name','_PATIENT_INFO','type',2,'data',[]); Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]); Tag(length(Tag)+1)=struct('name','_PATIENT_UID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011'); Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_FIRST','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_MIDDLE','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_LAST','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_ID','type',10,'data','x'); Tag(length(Tag)+1)=struct('name','_PATIENT_BIRTHDATE','type',10,'data','19500101000000'); Tag(length(Tag)+1)=struct('name','_PATIENT_SEX','type',5,'data',2); Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_NAME','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_UID','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_INSTITUTE','type',10,'data',''); Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]); Tag(length(Tag)+1)=struct('name','_PROCEDURE_INFO','type',2,'data',[]); Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]); Tag(length(Tag)+1)=struct('name','_PROCEDURE_VERSION','type',5,'data',1); Tag(length(Tag)+1)=struct('name','_PROCEDURE_UID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_ACCESSIONNUMBER','type',10,'data','0'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_TITLE','type',10,'data','0'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_SITE','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PROCEDURE_STATUS','type',5,'data',1); Tag(length(Tag)+1)=struct('name','_PROCEDURE_TYPE','type',5,'data',2); % Research type Tag(length(Tag)+1)=struct('name','_PROCEDURE_STARTEDDATETIME','type',10,... 'data','20060606164306'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_CLOSEDDATETIME','type',10,... 'data','19000100000000'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_COMMENTS','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PROCEDURE_LOCATION','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PROCEDURE_ISINDB','type',5,'data',0); Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]); Tag(length(Tag)+1)=struct('name','_DATASET_INFO','type',2,'data',[]); Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]); Tag(length(Tag)+1)=struct('name','_DATASET_VERSION','type',5,'data',2); Tag(length(Tag)+1)=struct('name','_DATASET_UID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0042'); Tag(length(Tag)+1)=struct('name','_DATASET_PATIENTUID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011'); Tag(length(Tag)+1)=struct('name','_DATASET_PROCEDUREUID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041'); Tag(length(Tag)+1)=struct('name','_DATASET_STATUS','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_RPFILE','type',10,'data','default.rp'); Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPTITLE','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPPROTOCOL','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPDESCRIPTION','type',10,... 'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONDATETIME','type',10,... 'data','Unknown'); Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONSOFTWARE','type',10,... 'data','Acq '); Tag(length(Tag)+1)=struct('name','_DATASET_CREATORDATETIME','type',10,... 'data',sprintf('%d',floor(clock))); Tag(length(Tag)+1)=struct('name','_DATASET_CREATORSOFTWARE','type',10,... 'data','Acq '); Tag(length(Tag)+1)=struct('name','_DATASET_KEYWORDS','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_COMMENTS','type',10,... 'data','Dummy infods.'); Tag(length(Tag)+1)=struct('name','_DATASET_OPERATORNAME','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_LASTMODIFIEDDATETIME','type',10,... 'data',sprintf('%d',floor(clock))); if exist_hc nominalPositions=0; % Measured else nominalPositions=1; % Nominal end Tag(length(Tag)+1)=struct('name','_DATASET_NOMINALHCPOSITIONS','type',5,... 'data',nominalPositions); Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,... 'data','ds.res4.scrr'); Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,... 'data','ds.res4.senres'); %Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,... % 'data','/opt/ctf-5.1/hardware/M015/M015_1609.coef'); %Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,... % 'data','/opt/ctf-5.1/hardware/M015/M015_1609.sens'); Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEM','type',10,'data','DSQ-2010'); Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEMTYPE','type',10,'data','Untitled'); Tag(length(Tag)+1)=struct('name','_DATASET_LOWERBANDWIDTH','type',4,'data',0); Tag(length(Tag)+1)=struct('name','_DATASET_UPPERBANDWIDTH','type',4,'data',... round(0.25*sample_rate)); Tag(length(Tag)+1)=struct('name','_DATASET_ISINDB','type',5,'data',0); if exist_HLC HZ_MODE=5; elseif exist_hc HZ_MODE=1; else HZ_MODE=DATASET_HZ_UNKNOWN; end Tag(length(Tag)+1)=struct('name','_DATASET_HZ_MODE','type',5,'data',HZ_MODE); Tag(length(Tag)+1)=struct('name','_DATASET_MOTIONTOLERANCE','type',4,'data',0.005); Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTION','type',4,'data',0.005); Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONTRIAL','type',7,'data',0); Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONCOIL','type',10,'data','1'); Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]); Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]); return % ************* End of function make_dummy_infods********************************************* % ************************************************************************************** %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%Function combineMarkers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function mrkNew=combineMarkers(mrkOld,nTrialOld,mrk,nTrialNew,res4); % Combines existing marker information with markers for new trial(s) being added to the % dataset ny addCTFtral. % Start by examining the new markers defined in structure mrk. % Examines structure ds to see if a sensible MarkerFile can be created from ds.mrk. % Output: mrkNew : New marker structure. If the new markers are invlaid, or empty, then % mrkNew=struct([]) is returned. MarkerFileOK=~isempty(mrk); if MarkerFileOK if isempty([mrk.trial]) | isempty([mrk.time]) MarkerFileOK=0; % Do not create MarkerFile.mrk if all of the marker classes are empty. else % Are the markers appropriate? minMarkerTrial=min(min([mrk.trial])); maxMarkerTrial=max(max([mrk.trial])); minMarkerTime=min(min([mrk.time])); maxMarkerTime=max(max([mrk.time])); MarkerFileOK=(maxMarkerTrial<=nTrialNew & minMarkerTrial>=1 & ... maxMarkerTime<=(res4.no_samples/res4.sample_rate) & ... minMarkerTime>=(-res4.preTrigPts/res4.sample_rate)); if ~MarkerFileOK fprintf(['addCTFtrial: Structure mrk cannot possibly be a set of markers ',... 'for %d trial(s) in array(data).\n'],nTrialNew); fprintf([' minMarkerTrial=%d (must be >=1) ',... 'maxMarkerTrial=%d (must be <=%d)\n'],... minMarkerTrial,maxMarkerTrial,ds.res4.no_trials); fprintf([' minMarkerTime=%7.4f (must be >=%7.4f) ',... 'maxMarkerTrial=%7.4f (must be <=%7.4f )\n'],... minMarkerTime,-res4.preTrigPts/res4.sample_rate,... maxMarkerTime,res4.no_samples/res4.sample_rate); fprintf(' MarkerFile.mrk will not be updated.\n'); end end end if MarkerFileOK==0 mrkNew=struct([]); % return an empty marker structure % Check mrkOld to see if each existing trial had at least one marker. if isequal(unique([mrkOld.trial]),[1:nTrialOld]) fprintf(['addCTFtrial: All of the trials in the existing data have at least one\n',... ' marked point,but the new trials have no marker points?\n']); end return end % There are valid new markers. Add the new markers to the existing marker structure, % and extend the marker definition if new markers have been defined. % Check the Name mrkNew=mrkOld; maxClassId=max([mrkNew.ClassId]); for k=1:length(mrk) addq=1; % Check if the marker is already defined. for q=1:length(mrkOld) if strcmp(mrkOld(q).Name,mrk(k).Name) mrkNew(q).trial=[mrkNew(q).trial mrk(k).trial+nTrialOld]; mrkNew(q).time=[mrkNew(q).time mrk(k).time]; addq=0; break; end end if addq % Create a new marker class newClassId=~isfield(mrk(k),'ClassId'); if ~newClassId newClassId=any(mrk(k).ClassId==[mrkNew.ClassId]); end if newClassId mrk(k).ClassId=max([mrkNew.ClassId])+1; end if ~isfield(mrk(k),'Color');mrk(k).Color='Red';end if ~isfield(mrk(k),'Comment');mrk(k).Comment=char([]);end if ~isfield(mrk(k),'ClassGroupId');mrk(k).ClassGroupId=3;end if mrk(k).ClassGroupId==0 if ~isfield(mrk(k),'BitNumber') | ~isfield(mrk(k),'Polarity') | ... ~isfield(mrk(k),'Source') | ~isfield(mrk(k),'Threshold') fprintf(['addCTFtrial: Structure mrk defines ClassGroupId=0 marker %s, ',... 'but not fields BitNumber, Polarity, Source or Threshold.\n'],mrk(k).Name); fprintf(' Marker set %s will be defined with ClassGroupId=3.\n',... mrk(k).Name); mrk(k).ClassGroupId=3; end end % ClassGroupId : make 4 fields empty. if mrk(k).ClassGroupId==3 mrk(k).BitNumber=[]; mrk(k).Polarity=[]; mrk(k).Source=[]; mrk(k).Threshold=[]; end q0=length(mrkNew)+1; mrkNew(q0)=mrk(k); mrkNew(q0).trial=mrk(k).trial+nTrialOld; mrkNew(q0).time=mrk(k).time; end clear addq; end return %%%%%%%%%%%%%% end of combineMarkers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Function writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function writeBadSegments(badSegmentsFile,badSegments,nTrial,tTrial); % Creates a bad.segments file in a CTF data set from the information in structure % badSegments which is created by read_badSegments, or by the user. % If structure badSegments is empty, then the file is not created. % badSegments structure: % badSegments.trial = List of trial numbers % badSegments.StartTime = List of bad segment start times (relative to trial). % badSegments.EndTime = List of bad segment end times. % Check badSegmentsFile if exist('badSegmentsFile')~=1;badSegmentsFile=char([]);end if isempty(badSegmentsFile) | ~ischar(badSegmentsFile) fprintf('addCTFtrial(writeBadSegments): Bad file name.\n'); badSegmentsFile return end % Check that structure badSegments is defined correctly if exist('badSegments')~=1 | exist('nTrial')~=1 return elseif ~isstruct(badSegments) | isempty(badSegments) return elseif ~isfield(badSegments,'trial') | ~isfield(badSegments,'StartTime') | ... ~isfield(badSegments,'EndTime') return elseif isempty(badSegments.trial) | isempty(badSegments.StartTime) | ... isempty(badSegments.EndTime) return elseif ~isequal(size(badSegments.trial),size(badSegments.StartTime),... size(badSegments.EndTime)) fprintf(['\naddCTFtrial (writeBadSegments): ',... 'The fields of structure badSegments do not all have the same size.\n']); return elseif any(badSegments.trial>nTrial) | any(badSegments.trial<1) | ... any(badSegments.StartTime<0) | any(badSegments.EndTime>tTrial) fprintf(['\naddCTFtrial (writeBadSegments): badSegments cannot possibly describe ',... 'bad segments for these data.\n',... '\tmin(badSegments.trial)=%d max(badSegments.trial)=%d ',... 'min(badSegments.StartTime)=%0.4f max(badSegments.EndTime)=%0.4f s\n\t\tDataset:',... ' nTrial=%d tTrial=%0.4f s\n'],... min(badSegments.trial),max(badSegments.trial),min(badSegments.StartTime),... max(badSegments.EndTime),nTrial,tTrial); fprintf('\t\tNew bad.segments file will not be created.\n\n'); return end % Convert all fields to simple vectors nSeg=prod(size(badSegments.trial)); trial=reshape(badSegments.trial,1,nSeg); StartTime=reshape(badSegments.StartTime,1,nSeg); EndTime=reshape(badSegments.EndTime,1,nSeg); fid=fopen(badSegmentsFile,'w','ieee-be'); if fid<0 fprintf('writeCTFds (writeBadSegments): Could not open file %s\n',badSegmentsFile); return end % Extra tabs are inserted to reproduce the format of bad.segments files produced by % DataEditor (5.3.0-experimental-linux-20060918). fprintf(fid,'%0.6g\t\t%0.6g\t\t%0.6g\t\t\n',[trial;StartTime;EndTime]); fclose(fid); return %%%%%%%%% End of writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%Function checkCls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ClassFileOK=checkCls(ds); % Examines structure ds to see if a sensible ClassFile can be created from ds.TrialClass. ClassFileOK=isfield(ds,'TrialClass'); if ClassFileOK ClassFileOK=~isempty(ds.TrialClass); end if ClassFileOK % Are the class trials appropriate? minClassTrial=[]; maxClassTrial=[]; for k=1:length(ds.TrialClass) maxClassTrial=max([maxClassTrial max(ds.TrialClass(k).trial)]); minClassTrial=min([minClassTrial min(ds.TrialClass(k).trial)]); end % Create ClassFile.cls even when the trail classes are empty. if ~isempty(maxClassTrial) ClassFileOK=(maxClassTrial<=ds.res4.no_trials & minClassTrial>=1); if ~ClassFileOK fprintf(['\nwriteCTFds (checkCls): ds.TrialClass cannot possibly be a set of ',... 'trial classes for array(data).\n minClassTrial=%d (must be >=1) ',... 'maxClassTrial=%d (must be <=%d)\n'],... minClassTrial,maxClassTrial,ds.res4.no_trials); fprintf(' ClassFile.cls will not be created.\n'); end end end return %%%%%%%%%%%%%% end of checkCls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%Function combineClasses %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function clsNew=combineClasses(clsOld,nTrialOld,cls,nTrialNew); % Combines existing trial class information with classes for new trial(s) that are % being added to the dataset by addCTFtral. % Start by examining the new markers defined in structure mrk. % Examines structure ds to see if a sensible CLassFile can be created from clsOld and cls. % Output: clsNew : New class structure. If the new classes are invalid, or empty, then % clsNew=struct([]) is returned. ClassFileOK=~isempty(cls); if ClassFileOK if isempty([cls.trial]) ClassFileOK=0; % Do not create ClassFile.cls if all of the trial classes are empty. else % Are the markers appropriate? minClassTrial=min(min([cls.trial])); maxClassTrial=max(max([cls.trial])); ClassFileOK=(maxClassTrial<=nTrialNew & minClassTrial>=1); if ~ClassFileOK fprintf(['addCTFtrial: Structure cls cannot possibly be a set of classes ',... 'for %d trial(s) in array data .\n'],nTrialNew); fprintf([' minClassTrial=%d (must be >=1) ',... 'maxClassTrial=%d (must be <=%d)\n'],... minClassTrial,maxClassTrial,nTrialNew); fprintf(' ClassFile.cls will not be updated.\n'); end end end if ClassFileOK==0 clsNew=struct([]); % return an empty class structure % Check clsOld to see if each existing trial had at least one class. if isequal(unique([clsOld.trial]),[1:nTrialOld]) fprintf(['addCTFtrial: All of the trials in the existing data are assigned to at ',... 'least one class\n',... ' but the new trials have no classes?\n']); end return end % There are valid new classes. Add the new classes to the existing class structure, % and extend the class definition if new classes have been defined. clsNew=clsOld; maxClassId=max([clsNew.ClassId]); for k=1:length(cls) addq=1; % Check if the class is already defined. for q=1:length(clsOld) if strcmp(clsOld(q).Name,cls(k).Name) clsNew(q).trial=[clsNew(q).trial cls(k).trial+nTrialOld]; addq=0; break; end end if addq % Create a new trial class newClassId=~isfield(cls(k),'ClassId'); if ~newClassId % Check if cls(k).ClassId is already in use. newClassId=any(cls(k).ClassId==[clsNew.ClassId]); end if newClassId cls(k).ClassId=max([clsNew.ClassId])+1; end if ~isfield(cls(k),'Color');cls(k).Color='Red';end if ~isfield(cls(k),'Comment');cls(k).Comment=char([]);end if ~isfield(cls(k),'ClassGroupId');cls(k).ClassGroupId=3;end q0=length(clsNew)+1; clsNew(q0)=cls(k); clsNew(q0).trial=cls(k).trial+nTrialOld; end clear addq; end return %%%%%%%%%%%%%% end of combineClasses %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% Function writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function writeClassFile(ClassFile,TrialClass); % Write the ClassFile of a CTF data set. % The CLassFile allows a user to store a list of trial classifications in a data set. % The ClassFile format is defined in document CTF MEG File Formats, PN900-0088. % This format is rigid. % Inputs : % ClassFile : marker file including the full path and extension .mrk. % TrialClass : Structure creted by read_ClassFile. % Output : ClassFile.cls. % Check input TrialClass. if exist('TrialClass')~=1;TrialClass=[];end if isempty(TrialClass) | ~isstruct(TrialClass) fprintf('writeCTFds (writeClassFile): TrialClass is empty or is not a structure.\n'); TrialClass return end % Check ClassFile if exist('ClassFile')~=1;ClassFile=char([]);end if isempty(ClassFile) | ~ischar(ClassFile) fprintf('writeCTFds (writeClassFile): Bad file name.\n'); ClassFile end fid=fopen(ClassFile,'w','ieee-be'); if fid<0 fprintf('writeCTFds (writeClassFile): Could not open file %s\n',ClassFile); return end nClass=length(TrialClass); % Generate datasetname from ClassFIle. ksep=max([0 strfind(ClassFile,filesep)]); datasetname=ClassFile(1:ksep-1); if isempty(datasetname);datasetname=cd;end fprintf(fid,'PATH OF DATASET:\n%s\n\n\n',datasetname); fprintf(fid,'NUMBER OF CLASSES:\n%d\n\n\n',nClass); for k=1:nClass if k==1 % Add sign character to make output match the output of Acq. sgn=char([]); % There should be no real significance to this. else % Why does DataEditor places the + sign only on ClassID 2,3,...? sgn='+'; end No_of_Trials=prod(size(TrialClass(k).trial)); fprintf(fid,'CLASSGROUPID:\n%s%d\nNAME:\n%s\nCOMMENT:\n%s\n',... sgn,TrialClass(k).ClassGroupId,TrialClass(k).Name,TrialClass(k).Comment); fprintf(fid,'COLOR:\n%s\nEDITABLE:\n%s\nCLASSID:\n%s%d\nNUMBER OF TRIALS:\n%d\n',... TrialClass(k).Color,TrialClass(k).Editable,sgn,TrialClass(k).ClassId,No_of_Trials); fprintf(fid,'LIST OF TRIALS:\nTRIAL NUMBER\n'); % Subtract one so trial numbering starts at 0 in ClassFile.cls fprintf(fid,'%20d\n',reshape(TrialClass(k).trial,1,No_of_Trials)-1); fprintf(fid,'\n\n'); end fclose(fid); return %%%%%%%%%%%%%% end of writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% Function updateCreatorSoftware %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ds=updateCreatorSoftware(ds,creatorSoftware,originalCreatorSoftware); % Changes the creator software fields of the ds structure, and returns ds=struct([]) if % field infods is missing from structure ds, or if it thinks that the dataset was not % created by the MATLAB code specified by originalCreatorSoftware (i.e. writeCTFds). % Makes sure that creatorSoftware info is changed in structure infods, newds and res4. % Inputs: ds : ds structure produced by readCTFds. % creatorSoftware : Character string indicating that the data set was % modified by addCTFtrial. Added to infods tags listed in addCreatorTag and % appName field of res4. % originalCreatorSoftware : Character string indicating that the data set was % created by writeCTFds. Added to infods tags listed in addCreatorTag and % appName field of res4. % Output: ds : ds structure with changes to ds.infids, ds.res4, ds.newds. % If the input ds structure does not indicate that iot was created by % writeCTFds (originalCreatorSoftware), ds=struct([]) is returned. % Adds comment (clinical use message) and creator software name to infods, newds and hist files. if ~isfield(ds,'infods'); fprintf(['addCTFtrial (updateCreatorSoftware): Structure ds does not include',... ' field infods.\n']); whos ds ds=struct([]); % Force an error in the calling program return end % The infods tags and red4 fields that display creator software must also indicate that % the dataset was created by originalCreatorSoftware. % infods tags that will display the creator software. addCreatorTag=strvcat('_PROCEDURE_COMMENTS','_DATASET_STATUS',... '_DATASET_COLLECTIONSOFTWARE','_DATASET_CREATORSOFTWARE'); % res4 text fields that will display the creator software. addCreatorField=strvcat('appName','run_description'); addCreatorLength=[256 -1]'; % -1 indicates variable length if exist('creatorSoftware')~=1; creatorSoftware=char([]); elseif ~ischar(creatorSoftware) creatorSoftware=char([]); else creatorSoftware=deblank(creatorSoftware); end if exist('originalCreatorSoftware')~=1; originalCreatorSoftware=char([]); elseif ~ischar(originalCreatorSoftware) originalCreatorSoftware=char([]); else originalCreatorSoftware=deblank(originalCreatorSoftware); end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Check that the string originalCreatorSoftware appears in the infods and res4 files. tagName=getArrayField(ds.infods,'name')'; if length(ds.infods)==1;tagName=tagName';end % Update the infods fields. for k=1:size(addCreatorTag,1) q=strmatch(deblank(addCreatorTag(k,:)),tagName); if isempty(q); fprintf('addCTFtrial (updateCreatorSoftware): Tag %s is missing from ds.infods.\n',... deblank(addCreatorTag(k,:))); ds=struct([]); return elseif length(q)>1 fprintf(['addCTFtrial (updateCreatorSoftware): Tag %s appears %d times in ',... 'ds.infods.\n'],deblank(addCreatorTag(k,:)),length(q)); ds=struct([]); return else strng=ds.infods(q).data; % Strng must contain originalCreatorSoftware nChar=length(strng); if length(originalCreatorSoftware)>0 qpos=strfind(strng,originalCreatorSoftware); if isempty(qpos) fprintf(['addCTFtrial (updateCreatorSoftware): String %s does not appear in',... ' ds.infods tag %s\n'],originalCreatorSoftware,addCreatorTag(k,:)); fprintf([' This dataset was not created ',... 'by CTF MATLAB Export software.\n']); ds=struct([]); return end qpos=qpos+length(originalCreatorSoftware)-1; else qpos=length(strng); end % Add creatorSoftware string if it is not already present. if isempty(strfind(strng,creatorSoftware)) ds.infods(q).data=[strng(1:qpos) ' ' creatorSoftware ' ' strng(qpos+1:nChar)]; end end end % Update the res4 fields: add creatorSoftware message. % Don't check field length. Truncate later. for q=1:size(addCreatorField,1); strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:)))); nChar=length(strng); if length(originalCreatorSoftware)>0 qpos=strfind(strng,originalCreatorSoftware); if isempty(qpos) fprintf(['addCTFtrial (updateCreatorSoftware): String %s does not appear in',... ' ds.res4.%s\n'],originalCreatorSoftware,deblank(addCreatorField(q,:))); fprintf([' This dataset was not created ',... 'by CTF MATLAB Export software.\n']); ds=struct([]); return end qpos=qpos+length(originalCreatorSoftware); else qpos=nChar; end % Add creatorSoftware string if it is not already present. if isempty(strfind(strng,creatorSoftware)) newStrng=[strng(1:qpos) ' ' creatorSoftware ' ' strng(qpos+1:nChar)]; ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),newStrng); end end clear q strng nChar strng0 ns newStrng; % Update res4.run_description ds.res4.run_description=[deblank(ds.res4.run_description),char(0)]; ds.res4.rdlen=length(ds.res4.run_description); % Truncate the .res4. fields. Leave room for a final char(0). for q=1:size(addCreatorField,1); strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:)))); if length(strng)>addCreatorLength(q)-1 & addCreatorLength(q)>0 ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),... strng(length(strng)+[-addCreatorLength(q)+2:0])); end end clear q strng; % Add the creator and comment information to the newds file if isfield(ds,'newds'); nChar=length(ds.newds); % Keyword positions aNpos=max(strfind(ds.newds,[char(9) 'appName:' char(9)])); if isempty(aNpos) fprintf(['addCTFtrial (updateCreatorSoftware): Keyword ''appName'' ',... 'does not appear in ds.newds.\n',... ' set ds.newds=[].\n']); ds.newds=char([]); else eol=max([11 min(strfind(ds.newds(aNpos+1:length(ds.newds)),char(10)))]); wPos=min(strfind(ds.newds(aNpos+[1:eol]),originalCreatorSoftware)); addPos=min(strfind(ds.newds(aNpos+[1:eol]),creatorSoftware)); if isempty(addPos) if isempty(wPos) ds.newds=[ds.newds(1:(aNpos+eol-1)) ' ' creatorSoftware ... ds.newds((aNpos+eol):length(ds.newds))]; else ds.newds=[ds.newds(1:(aNpos+wPos+length(originalCreatorSoftware)-1)) ', ' ... creatorSoftware ... ds.newds((aNpos+wPos+length(originalCreatorSoftware)):length(ds.newds))]; end end clear eol wPos addPos; end clear nChar aNpos; end return %%%%%%%%%%%%%% End of update_creatorSoftware %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% Function updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [infods,status]=updateHLC(infods,HLCdata,HLC0,nTrial0); % Adds notes and continuous-head-localization tags to .infods file. % Updates MAXHEADMOTION tags when called from addCTFtrial % Inputs : infods : Structure of tags to be written to output infods file. % HLCdata : 0 or [] or not defined - There are no HLC channels % (head-coil position) in the data. Just pass the existing tags to % the output dataset. % HLCdata : real array : size(HLCdata)=[samplesPerTrial 3 Ncoil nTrial] % Calculate the head motion tags. % HLC0 : Head coil positions (m) in dewar coordinates at the start of the run. % size(HLC0)=[3 Ncoil] % nTrial0=No. of trials of data already written to the dataset. % Outputs : status : 0: Everything looks OK % 1: Couldn't find _DATASET tags. % <0: There is a problem with the new infods file. % Calls: % - getArrayField: Extracts field names from structure array S. % Defaults for the head localization tags. % Might do this better with a structure. HZ_MODE_UNKNOWN=2^31-1; % Bug in DataEditor and acquisition software, Oct. 2006 % Should be -1. % New dataset tags for HLC specification. addTag=strvcat('_DATASET_HZ_MODE',... '_DATASET_MOTIONTOLERANCE',... '_DATASET_MAXHEADMOTION',... '_DATASET_MAXHEADMOTIONTRIAL',... '_DATASET_MAXHEADMOTIONCOIL'); addTagType=[5 4 4 7 10]'; if exist('nTrial0')~=1 nTrial0=0; elseif isempty(nTrial0) nTrial0=0; elseif min(nTrial0)<0 nTrial0=0; end % Check HLCdata array. HLCdata=[] indicates no continuous head localization. if exist('HLCdata')~=1 HLCdata=[]; elseif ~isempty(HLCdata) [samplesPerTrial nDim Ncoil nTrial]=size(HLCdata); if nDim~=3; fprintf('addCTFtrial (updateHLC): size(HLCdata)=[');fprintf(' %d',size(HLCdata)); fprintf(']\n'); fprintf(' nDim=%d?? Setting HLCdata=[].\n',nDim); HLCdata=[]; end end if exist('HLC0')~=1 HLC0=[]; elseif ~isequal(size(HLC0),[3 size(HLCdata,3)]) HLC0=[]; end if isempty(HLC0) & ~isempty(HLCdata) HLC0=squeeze(HLCdata(1,:,:,1)); end % Assume that all the tag names are different. There is no checking when a tag listed in % addTag matches more than one entry in array name. name=getArrayField(infods,'name')'; %size(name)=[nTag lengthTag] DATASET_tags=strmatch('_DATASET',name)'; % size(DATASET_tags)=[1 nTag] if isempty(DATASET_tags) status=1; % No _DATASET tags. Don't add anything. else status=0; if isempty(HLCdata) TagValue(1)=HZ_MODE_UNKNOWN; TextTagValue=char(0); addTag=addTag(1,:); % Remove the other HLC tags addTagType=addTagType(1); else % ~isempty(HLCdata) % Remove HLC offsets. for q=1:Ncoil for k=1:3 HLCdata(:,k,q,:)=HLCdata(:,k,q,:)-HLC0(k,q); end end % Calculate motions as displacement from the start of the dataset. absMotion=squeeze(sqrt(sum(HLCdata.^2,2))); %size(absMotion)=[samplesPerTrial Ncoil nTrial] maxCoilMotion=squeeze(max(absMotion,[],1)); % size(maxCoilMovement)=[Ncoil nTrial] maxHeadMotion=max(max(maxCoilMotion)); [mx maxHeadMotionCoil]=max(max(maxCoilMotion,[],2)); [mx maxHeadMotionTrial]=max(max(maxCoilMotion,[],1)); % Create a list of head motion tag values TagValue(1)=5; % Indicates continuous head localization TagValue(2)=max(2*maxHeadMotion,0.02); % _DATASET_MOTIONTOLERANCE TagValue(3)=maxHeadMotion; TagValue(4)=maxHeadMotionTrial-1+nTrial0; % _DATASET_MAXHEADMOTIONTRIAL TextTagValue=strvcat(char(zeros(4,1)),sprintf('%d',maxHeadMotionCoil)); % Does the existing infods have the head-motion tags? TagNo2=strmatch(deblank(addTag(2,:)),name,'exact'); TagNo3=strmatch(deblank(addTag(3,:)),name,'exact'); TagNo4=strmatch(deblank(addTag(4,:)),name,'exact'); TagNo5=strmatch(deblank(addTag(5,:)),name,'exact'); if ~isempty(TagNo2) & ~isempty(TagNo3) & ~isempty(TagNo4) & ... ~isempty(TagNo5) & nTrial0>0 % Structure infods already has the head-motions tags from previous data. TagValue(2)=max(TagValue(2),infods(TagNo2).data); if TagValue(3)<=infods(TagNo3).data TagValue(3)=infods(TagNo3).data; TagValue(4)=infods(TagNo4).data; TextTagValue=strvcat(char(zeros(4,1)),infods(TagNo5).data); end elseif (~isempty(TagNo2) | ~isempty(TagNo3) | ~isempty(TagNo4) | ... ~isempty(TagNo5)) & nTrial0>0 fprintf(['addCTFtrial (updateHLC): Some, but not all, of the ds.infods CHL ',... 'tags are defined.\n',... ' Infods will be defines with information from the %d new ',... 'trial(s) being added.\n'],size(HLCdata,4)); end TagValue=[TagValue 0]; % Placeholder only since the 5th tag is a text string. end % Add or insert tags. for q=1:size(addTag,1) nTag=length(infods); tagName=deblank(addTag(q,:)); TagNo=strmatch(tagName,name,'exact')'; if isempty(TagNo) % Insert a tag at the end of the _DATASET tags. TagNo=max(DATASET_tags)+1; infods((TagNo+1):(nTag+1))=infods(TagNo:nTag); name=strvcat(name(1:TagNo-1,:),tagName,name(TagNo:nTag,:)); DATASET_tags=[DATASET_tags TagNo]; end if addTagType(q)~=10 infods(TagNo)=struct('name',tagName,'type',addTagType(q),'data',TagValue(q)); else infods(TagNo)=struct('name',tagName,'type',addTagType(q),... 'data',deblank(TextTagValue(q,:))); end end % End loop over head position and head motion tags. clear q TagNo TextTagValue TagValue; end % End section add _DATASET tags return %%%%%%%%%%%%%% End of updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% Function getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x=getArrayField(S,yfield) % Extracts one field of a structure array. % Inputs: S : structure array. % yfield: name of field of S (string) % Output: x. x(:,n)=S(n).yfield; size(x)=[size(yfield) length(S)] % Field sizes: Two options: % 1. size(S(n).yfield) is the same for all n. Any size allowed. % 2. S(n).yfield is a 2-D array for all structure elements S(n). % Then yfield of different array elements S(n) can have different sizes. % The array returned will be large enough to accomodate all of the data. sizeS=size(S); nS=prod(sizeS); S=reshape(S,1,nS); % Determine which array-size option to use. sizey=size(getfield(S,{1},yfield)); option1=1; option2=(length(sizey)==2); for n=2:nS sizeyn=size(getfield(S,{n},yfield)); option1=option1 & isequal(sizey,sizeyn); option2=option2 & length(sizeyn)==2; if option2 sizey=max([sizey;sizeyn],[],1); end end if option1 % All fields have the same size nY=prod(sizey); if isnumeric(getfield(S,{1},yfield)) x=zeros(nY,nS); elseif ischar(getfield(S,{1},yfield)) x=char(zeros(nY,nS)); end for n=1:nS x(:,n)=reshape(getfield(S,{n},yfield),nY,1); end x=reshape(x,[sizey nS]); elseif option2 % All fields have only two dimensions if isnumeric(getfield(S,{1},yfield)) x=zeros([sizey nS]); elseif ischar(getfield(S,{1},yfield)) x=char(zeros([sizey nS])); end for n=1:nS y=getfield(S,{n},yfield); sizeyn=size(y); x(1:sizeyn(1),1:sizeyn(2),n)=y; end else fprintf(['getArrayField: Field %s of the structure array has >2 dimensions ',... 'and not all field have the same size.\n'],yfield); x=[]; end x=squeeze(x); return %%%%%%%% End of getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
lcnhappe/happe-master
setCTFDataBalance.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/ctf/setCTFDataBalance.m
32,056
utf_8
894c3744554abe635876ce6944dca0cd
function [data,ds]=setCTFDataBalance(data,ds,balance1,unit,chanList,messages); % Version 1.1 13 April 2007 Mod to chanList: If chanList is omitted and % size(data,2)<ds.res4.no_channels, then setCTFDataBalance % sets chanList=1:size(data,2) and prints a warning the first % time it happens. % 7 Dec. 2006. Fixed a bug. Changed calls to getCTFBalanceCoefs so % setCTFDataBalance would balance and unbalance reference gradiometers. % Version 1.0 27 October 2006 % Adjusts the gradient order balance from balance0 to balance1. % Inputs : % data : Array of data to be balanced. precision= single or double. % size(data)=[Npt Nchan Ntrial]. If chanList is not supplied, it is assumed that % array data has dataset channels 1:Nchan (i.e. data is not just SQUID sensors % although only SQUID channels are affected by setCTFDataBalance.) % ds : Structure produced by readCTFds that describes the dataset. % balance1 : Character array defining balance of the output data. % Parameter balance1 must be specified, even if it is only balance1=[]; % balance1=[],' ' or 'NONE' : Output is unbalanced. % size(balance,1)=1 : MEG balancing. Assume no reference balancing. % size(balance,1)=2 : MEG balance = balance(1,:). % Gref balance = balance(2,:) % unit : Options : [],' ', 'fT', or 'T' : Physical unit % 'int' or 'phi0' : Raw units. % If the unit argument is not included, unit is set to 'fT'. % chanList : Optional list of dataset channels included in array data. % Channel numbering is referred to structure ds (the output of readCTFds). % If length(chanList)=Nchan. % data(:,k,q)=trial q of channel chanList(k) of the dataset. % If chanList=[],<0 or not defined : Array data has dataset channels 1:Nchan. % Otherwise, length(chanList)=Nchan=size(data,2). % If length(chanList)~=size(data,2) : Error. % messages=0: Don't print tracing message % =1: Print a message when there is a change in requested balance. % =2: Always print a message % Outputs: data: Data with balanced SQUID signals. Set data=[] on failure. % ds: ds structure for balanced data. Set ds=-1 on failure. % In any event, print error messages.if exist('messages')~=1;messages=1;end % The balance and unbalance is made complicated because this code allows for situations % where the reference gradiometers are also balanced (although this option seems never % to be used). % Function calls: Most functions are called only once, and are intended to be % called only by setCTFDataBalance or its subprograms. % - getCTFBalanceCoefs. Called by balance_data and unbalance_data. Gets the balance % tables from structure ds. % Included in this listing: % - getDsBalance: Gets the current balance state of the data and checks for error in % the grad_order_no field of ds.rs4.senres. % - check_balance : Makes balance1 into [2 4] character arrays. % - unbalance_data : Converts data from balance0 to unbalanced. % - balance_data: Converts data from unbalanced to balance1. % - reindex : Called by functions unbalance_data and balance_data to re-order indices % when chanList does not include all the channels, or the channels have % been reordered in array data. % If virtual memory is a problem, consider bringing functions balance_data and % unbalance_data into the code. In the present configuration, a copy of array data is % made when these functions are called. % In the event of an error, returns data=[], ds1=-1 This should force an error in the % calling program. persistent chanListWarning if nargout==0 & nargin==0 fprintf(['\nsetCTFDataBalance: Version 1.1 13 April 2007 ',... 'Balances MEG data.\n',... '\t\tCall : ',... '[data1,ds1]=setCTFDataBalance(data0,ds0,balance1,unit,chanList,messages);\n\n']); return end buffsize=6e6; % process blocks of buffsize words (=8*buffsize bytes) at a time balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR'); unit_options=strvcat('fT','T','phi0','int'); default_unit='fT'; % Check that the inputs are sensible. if nargin<3 fprintf(['\nsetCTFDataBalance: Only %d input arguments? ',... 'Must specify at least data, ds and balance.\n\n'],nargin); data=[];ds=-1; return elseif ~any(strmatch(class(data),strvcat('single','double'))) | isempty(data) | ... ~isstruct(ds) | isempty(ds) | isempty(balance1) |~ischar(balance1) fprintf('\nsetCTFDataBalance: Wrong argument types or sizes.\n\n'); whos data ds balance1 data=[];ds=-1; return elseif ~isfield(ds,'res4') fprintf('\nsetCTFDataBalance: Field res4 is missing from structure ds.\n\n'); ds data=[];ds=-1; return end if nargout~=2 fprintf(['\nsetCTFDataBalance: %d output arguments specified. ',... 'Must have 2 outputs (data,ds).\n\n'],nargout); data=[];ds=-1; return end % Single or double precision data. prec=class(data); % Force upper-case characters balance1=upper(balance1); % Check that arrays data and chanList are consistent and sensible if size(data,2)>ds.res4.no_channels fprintf('\nsetCTFDataBalance: ds.res4.no_channels=%d, but size data=[',... ds.res4.no_channels); fprintf(' %d',size(data));fprintf(']\n\n'); data=[];ds=-1; return end if exist('chanList')~=1;chanList=[];end if ~isempty(chanList) % chanList~=[]. Check chanList if ~isnumeric(chanList) fprintf('\nsetCTFDataBalance: chanList has the wrong type.\n\n'); whos data ds balance1 chanList data=[];ds=-1; return else % chanList is numeric and non-empty % Check that chanList is a vector if sum(size(chanList)>1)>1 fprintf('\nsetCTFDataBalance: size(chanList)=[');fprintf(' %d',size(chanList)); fprintf('] Not a vector.\n\n'); data=[];ds=-1; % Force an error in the calling program return else chanList=reshape(chanList,1,length(chanList)); % chanList is a row vector. if any(chanList<=0) | any(chanList>ds.res4.no_channels) | ... length(chanList)~=size(data,2) fprintf('setCTFDataBalance: Error in input chanList:\n'); fprintf(' min(chanList)=%d max(chanList)=%d Dataset has %d channels.\n',... min(chanList),max(chanList),ds.res4.no_channels); fprintf('length(chanList)=%d size(data)=[',length(chanList)); fprintf(' %d',size(data)); fprintf('] Must have length(chanList)=size(data,2)\n'); data=[];ds=-1; % Force an error in the calling program return end end end else % chanList=[]. Array data must include all of the channels. if size(data,2)<ds.res4.no_channels if isempty(chanListWarning) fprintf('setCTFDataBalance: No chanList supplied and size(data)=['); fprintf(' %d',size(data));fprintf(']\n'); fprintf(' Set chanList=1:%d\n',size(data,2)); fprintf(' No. of channels=ds.res4.no_channels=%d\n',... ds.res4.no_channels); chanListWarning=1; end chanList=1:size(data,2); end end % Check the data units, convert to lower case and flag incorrect unit specification if ~exist('unit'); unit=default_unit; elseif isempty(unit); unit=default_unit; elseif ~ischar(unit) fprintf('\nsetCTFDataBalance: Input unit has the wrong type: class(unit)=%s\n\n',... class(unit)); data=[];ds=-1; return end unit=lower(unit); if isempty(strmatch(unit,lower(unit_options))) fprintf('\nsetCTFDataBalance: unit=%s. Must be one of',unit); for k=1:size(unit_options,1);fprintf(' %s',unit_options(k,:));end;fprintf('\n'); data=[];ds=-1; % Force an error in the calling program return end % Make sure message request is sensible. This is important only as a way of checking % that the input list is sensible. The value of messages does not affect the output of % setCTFDataBalance. if exist('messages')~=1;messages=1;end if ~isnumeric(messages) fprintf(['\nsetCTFDataBalance: Input messages has the wrong type: ',... 'class(messages)=%s\n\n'],class(messages)); data=[];ds=-1; return elseif isempty(messages); messages=1; elseif ~isequal(size(messages),[1 1]) fprintf('\nsetCTFDataBalance: Input messages doesn''t make sense. size(messages)=['); fprintf(' %d',size(messages));fprintf('] (Must be [1 1])\n\n'); data=[];ds=-1; return elseif messages<0 | messages>2 fprintf('\nsetCTFDataBalance: Input messages=%d. Must be [], 0, 1 or 2.\n\n',messages); data=[];ds=-1; return end % Process data in blocks of nChBlock channels to reduce virtual memory demand. nChBlock=max(1,floor(buffsize/size(data,1))); % badGref = list of bad reference gradiometers referred to dataset channel numbering. % badGMEG = list of bad MEG gradiometers referred to dataset channel numbering. % These gradiometers are considered bad because their grad_order_no is wrong, not % because thay are listed in ds.BadChannels [balance0,badGref,badGMEG,Greflist,GMEGlist]=getDsBalance(ds); if strmatch('BAD',balance0) fprintf(['\nsetCTFDataBalance: The balance order of the Grefs and/or the MEG ',... 'channels cannot be determined.\n',... ' Check ds.res4.senres().grad_order_no.\n\n']); data=[];ds=-1; % Force an error in the calling program return end % Check balance1 and put in a standard form. balance1=check_balance(balance1); if isempty(balance1) | isempty(balance0) fprintf(['\nsetCTFDataBalance: size(ds balance) =[%d %d] (after call to ',... 'getDsBalance.)\n',... ' size(new balance)=[%d %d] (after call to check_balance.)\n\n'],... size(balance0),size(balance1)); data=[];ds=-1; % Force an error in the calling program return end % Print a message? chanset=strvcat('MEGs','Grefs'); for k=1:2 if messages==2 | (messages==1 & ~strcmp(balance0(k,:),balance1(k,:))) fprintf('setCTFDataBalance: Adjusting %s from balance=%s to balance=%s.\n',... chanset(k,:),balance0(k,:),balance1(k,:)); end end clear k chanset; if isequal(balance0,balance1) return end % Convert from balance0 to unbalanced. if ~isequal(balance0,strvcat('NONE','NONE')); data=unbalance_data(data,ds,balance0,unit,nChBlock,chanList,badGref); % unbalance_data returns data=[] when list badGref includes a Gref that is required for % balancing. if isempty(data);ds=-1;return;end end % Convert from unbalanced to balance1. if ~isequal(balance1,strvcat('NONE','NONE')); % balance_data returns data=[] when badGref includes a Gref that is required for % balancing. data=balance_data(data,ds,balance1,unit,nChBlock,chanList,badGref,messages); if isempty(data);ds=-1;return;end end % Mark the balance order in structure ds. % Make sure that the bad channels are marked with a different order. This will force % errors if these data are used later. Set the data in the bad channels to zero, and add % the bad channels to ds.BadChannels. Gorder=strmatch(balance1(2,:),balanceOptions)-1; MEGorder=strmatch(balance1(1,:),balanceOptions)-1; for k=setdiff(Greflist,badGref) ds.res4.senres(k).grad_order_no=Gorder; end for k=setdiff(GMEGlist,badGMEG) ds.res4.senres(k).grad_order_no=MEGorder; end for k=badGref ds.res4.senres(k).grad_order_no=0; end for k=badGMEG ds.res4.senres(k).grad_order_no=round(3-MEGorder); end % Set channels with bad balance order parameter to zero. kBad=[badGref badGMEG]; if ~isempty(chanList) kBad=reindex(chanList,intersect(chanList,kBad)); end for k=kBad if strcmp(prec,'single') data(:,k,:)=single(zeros(size(data,1),1,size(data,3))); else data(:,k,:)=zeros(size(data,1),1,size(data,3)); end end clear k Gorder MEGorder; if isempty([badGref badGMEG]);return;end % Add bad channels to ds.BadChannels if ~isfield(ds,'BadChannels');ds.BadChannels=char([]);end BadList=union(badGref,badGMEG); if ~isempty(ds.BadChannels) for k=1:size(ds.BadChannels,1) BadList=[BadList strmatch(deblank(ds.BadChannels(k,:)),ds.res4.chanNames)]; end ds.BadChannels=char([]); end for k=sort(BadList) ds.BadChannels=strvcat(ds.BadChannels,strtok(ds.res4.chanNames(k,:),'- ')); end return % ************** End of function setCTFDataBalance ********************************** % ********************************************************************************** % ******************************************************************************** % ******************* function getDsBalance ************************************** function [dsbalance,badGref,badGMEG,Greflist,GMEGlist]=getDsBalance(ds); % Get the current balance state from structure ds. Check for channels that are marked % as bad by having a different grad_order_no. % Check whether things make sense. % Return the balance and lists of bad gradiometers. % Also return the complete list of reference gradiometers and MEG gradiometers since % setCTFDataBalance uses them. % In normal operation, getDsBalance will return badGref=[], badGMEG=[]; balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR'); Greflist=[]; % List of reference gradiometers (sensorTypeIndex=1) Greforder=[]; GMEGlist=[]; % List of MEG gradiometers (sensorTypeIndex=5) GMEGorder=[]; % Make lists of sensors and gradient balancing. for k=1:ds.res4.no_channels if ds.res4.senres(k).sensorTypeIndex==1 Greflist=[Greflist k]; Greforder=[Greforder ds.res4.senres(k).grad_order_no]; elseif ds.res4.senres(k).sensorTypeIndex==5 GMEGlist=[GMEGlist k]; GMEGorder=[GMEGorder ds.res4.senres(k).grad_order_no]; end end % Reference balance OK? dsbalance=char(zeros(2,4)); if any(Greforder<0) | any(Greforder>1) fprintf(['\nsetCTFDataBalance: The reference gradiometer balance orders make no ',... 'sense.\n %2d Gref channels. %2d have grad_order_no=0\n'],... length(Greflist),sum(Greforder==0)); fprintf(' %2d have grad_order_no=1\n',sum(Greforder==1)); fprintf(' %2d have grad_order_no<0 or >1\n',... sum(Greforder>1)+sum(Greforder<0)); dsbalance=strvcat(dsbalance(1,:),'BAD'); badGref=Greflist; % Mark everything bad elseif sum(Greforder==0)>sum(Greforder==1) dsbalance=strvcat(dsbalance(1,:),balanceOptions(1,:)); badGref=Greflist(find(Greforder~=0)); else dsbalance=strvcat(dsbalance(1,:),balanceOptions(2,:)); badGref=Greflist(find(Greforder~=1)); end % Sort MEG gradiometer balance. In correct operation, all MEG channels should have the % same balance (0,1,2 or 3). for bal=0:3 nMEGbal(bal+1)=sum(GMEGorder==bal); end [maxbal MEGorder]=max(nMEGbal); MEGorder=MEGorder-1; if maxbal>ceil(0.5*length(GMEGlist)) & all(GMEGorder>=0) & all(GMEGorder<=3) dsbalance(1,:)=balanceOptions(MEGorder+1,:); badGMEG=GMEGlist(GMEGorder~=MEGorder); else fprintf('\nsetCTFDataBalance: The MEG-sensor balance orders make no sense.\n'); fprintf(' %3d MEG gradiometer channels.\n',length(GMEGlist)); fprintf(' %3d have grad_order_no=%d\n',[nMEGbal;0:3]); if sum(nMEGbal)<length(GMEGlist) fprintf(' %3d have grad_order_no<0 or >3\n\n',... length(GMEGlist)-sum(nMEGbal)); end dsbalance=strvcat('BAD',dsbalance(2,:)); badGMEG=GMEGlist; % Mark everything bad` end return % ************** End of function getDsBalance ********************************** % ********************************************************************************** % ******************************************************************************** % ******************* function check_balance ************************************** function balance=check_balance(balance); % make sure that character array balance has the correct format. balance_options=strvcat('NONE','G1BR','G2BR','G3BR'); % Make balance into a [4 2] character array if ~ischar(balance) & ~isempty(balance) fprintf('setCTFDataBalance (check_balance): balance is not a character array.\n'); balance=char([]); % Force an error. return; elseif isempty(deblank(balance)) balance=strvcat('NONE','NONE'); return elseif size(balance,1)==1 balance=strvcat(balance,'NONE'); % No Gref balancing elseif size(balance,1)>2 fprintf('setCTFDataBalance (check_balance): size(balance)=[%d %d]?\n',size(balance)); balance=char([]); % Force an error. return end balance=upper(balance); if size(balance,2)>4;balance=balance(:,1:4);end for k=1:2 % k=1:MEGs, k=2:Grefs if isempty(deblank(balance(k,:))); balance(k,:)='NONE'; elseif isempty(strmatch(balance(k,:),balance_options(1:(6-2*k),:))) fprintf('check_balance: balance(%d,:)=%s Not an allowed option.\n',k,balance(k,:)); balance=char([]); % Force an error? return end end return % ************** End of function check_balance ********************************** % ********************************************************************************** % ************************************************************************ % ****** Convert from balanced to unbalanced data ********************** function data=unbalance_data(data,ds,balance0,unit,nChBlock,chanList,badGref); % Inputs: data: Data array. size(data)=[Npt Nchan Ntrial] % ds: ds strtcuture for the data. % balance0: balance0(1,:) = MEG balance before unbalancing % balance0(2,:) = Gref balance before unbalancing % unit : 'ft','t' (physical units) % 'int', 'phi0' % chanList: List if channels included in array data (referred to the channel % numbering in structure ds) % badGref: A list of gRef channels markes as bad because they seen to have the % wrong grad_order_no. if ~exist('chanList');chanList=[];end prec=class(data); % Read the balance tables for both MEG and reference gradiometers. % Usually balance0(2,:)='NONE', and it returns alphaGref=[]. [alphaMEG,MEGindex,MEGbalanceindex,alphaGref,Grefindex,Gbalanceindex]=... getCTFBalanceCoefs(ds,balance0,unit); % Unbalance the Grefs first. In almost all cases, balance0(2,:)='NONE', % so the program will skip this section. if ~strcmp(upper(balance0(2,:)),'NONE') % The index lists give channel numbers referred to data set channel numbering if isempty(Grefindex) | isempty(Gbalanceindex) fprintf('setCTFDataBalance (unbalance_data): balance=%s\n',... '\t\tsize(Grefindex)=[%d %d] size(Gbalanceindex)=[%d %d] ??\n',balance0(2,:),... size(Grefindex),size(Gbalanceindex)); data=[]; % Force an error in the calling program return end % Are there any badGref in the Gbalanceindex list? if ~isempty(intersect(Gbalanceindex,badGref)) fprintf(['setCTFDataBalance (unbalance_data): A reference gradiometer marked bad ',... 'because of its grad_order_no\n',... ' appears in the list of reference sensors required for ',... '%s Gref balancing.\n'],balance0(2,:)); fprintf(' Gbalanceindex=');fprintf(' %d',Gbalanceindex);fprintf('\n'); fprintf(' badGref=');fprintf(' %d',badGref);fprintf('\n'); data=[]; % Force an error in the calling program return end if isequal(chanList,1:max(max(Gbalanceindex),max(Grefindex)));chanList=[];end if ~isempty(chanList) if ~isempty(setdiff(Gbalanceindex,chanList)) fprintf(['setCTFDataBalance (unbalance_data): List chanList does not include ',... 'all of the reference sensors in the %s table for reference gradiometers.\n'],... balance0(2,:)); data=[]; return end [Gbalanceindex,Grefindex,alphaGref]=... reindex(chanList,Gbalanceindex,Grefindex,alphaGref); end % Balancing reference gradiometers: % balanced_data(:,Grefindex) % =raw_data(:,Grefindex)-raw_data(:,Gbalanceindex)*alphaGref % size(alphaGref)=[length(Gbalanceindex) length(Grefindex)] % Note : not all of the sensors in list Gbalanceindex are gradiometers. % Rewrite as a matrix equation: % balanced_data(:,Gindex)=raw_data(:,Gindex)*Gbalmat % Gindex=list of all the sensors involved in balancing the reference % gradiometers. % size(Gbalmat)=[length(Gindex) length(Gindex)] [Gindex]=union(Gbalanceindex,Grefindex); [Cx,Fbal]=intersect(Gindex,Gbalanceindex); % Gindex(Fbal)=Gbalanceindex [Cx,Fref]=intersect(Gindex,Grefindex); % Gindex(Fref)=Grefindex Gbalmat=eye(length(Gindex)); Gbalmat(Fbal,Fref)=Gbalmat(Fbal,Fref)-alphaGref; clear Fbal Fref Cx Grefindex Gbalanceindex alphaGref; % Convert to unbalanced reference gradiometers for pt=1:size(data,3) if strcmp(prec,'single') data(:,Gindex,pt)=single(double(data(:,Gindex,pt))/Gbalmat); else data(:,Gindex,pt)=data(:,Gindex,pt)/Gbalmat; end end clear Gbalmat pt; end % Finished unbalancing the reference gradiometers if strcmp(upper(balance0(1,:)),'NONE'); return; % No unbalancing required for MEG gradiometers end % Are there any badGref in the MEGbalanceindex list? if ~isempty(intersect(MEGbalanceindex,badGref)) fprintf(['setCTFDataBalance (unbalance_data): A reference gradiometer marked bad ',... 'because of its grad_order_no\n',... ' appears in the list of reference sensors required for ',... '%s MEG balancing.\n'],balance0(1,:)); fprintf(' MEGbalanceindex=');fprintf(' %d',MEGbalanceindex);fprintf('\n'); fprintf(' badGref=');fprintf(' %d',badGref);fprintf('\n'); data=[]; % Force an error in the calling program return end % Don't bother with chanList if it obviously includes all the SQUID channels and in % the dataset ordering. if isequal(chanList,1:max(max(MEGindex),max(MEGbalanceindex)));chanList=[];end if isempty(alphaMEG) | isempty(MEGindex) | isempty(MEGbalanceindex) return; elseif ~isequal(size(alphaMEG),[length(MEGbalanceindex) length(MEGindex)]) fprintf(['setCTFDataBalance (unbalance_data): size(alphaMEG)=[%d %d] ',... 'length(MEGbalanceindex)=%d length(MEGindex)=%d\n'],... size(alphaMEG),length(MEGbalanceindex),length(MEGindex)); data=[]; return elseif all(reshape(alphaMEG,1,length(MEGbalanceindex)*length(MEGindex))==0) return end % Make the index lists refer to the entries in chanList. if ~isempty(chanList) if ~isempty(setdiff(MEGbalanceindex,chanList)) fprintf(['setCTFDataBalance (unbalance_data): List chanList does not include ',... 'all of the reference sensors in the %s table for MEG gradiometers.\n'],... balance0(1,:)); data=[]; return end [MEGbalanceindex,MEGindex,alphaMEG]=... reindex(chanList,MEGbalanceindex,MEGindex,alphaMEG); end % Reverse the balance applied to the MEG channels. Needs unbalanced reference data. if ~isempty(alphaMEG) & ... ~isequal(alphaMEG,zeros(length(MEGbalanceindex),length(MEGindex))) % Unbalance MEG data trial-by-trial and in blocks of nChBlock channels for pt=1:size(data,3) for m=1:nChBlock:length(MEGindex) mptr=m:min(m+nChBlock-1,length(MEGindex)); MEGblock=MEGindex(mptr); if strcmp(prec,'single'); data(:,MEGblock,pt)=single(double(data(:,MEGblock,pt))+... double(data(:,MEGbalanceindex,pt))*alphaMEG(:,mptr)); else data(:,MEGblock,pt)=data(:,MEGblock,pt)+... data(:,MEGbalanceindex,pt)*alphaMEG(:,mptr); end end end clear pt m mptr MEGblock; end return % ******************* End of function unbalance_data **************************** % *********************************************************************************** % *********************************************************************************** % *************** Convert from unbalanced data to balanced data ******************* function data=balance_data(data,ds,balance,unit,nChBlock,chanList,badGref,messages); % Extracts the balance table from structure ds and balances data as specified in balance. % If the balancing requires a reference gradiometer marked in the badGref list, an error % message is printed and the data array is set to []. % If a MEG channel is missing from the balance table, then the channel is set to zero. % Inputs: data: The aray of data to be balanced. % ds: The ds structure read by readCTFds that contains the balance table. % balance: The desired output balance state. % balance(1,:) = MEG balance % balance(2,:) = Gref balance % unit : Data units ('fT','T','phio','int') % nChBlock : rad the data in blocks of nChBlock to reduce memory requirements. % chanList: List of the channels that actual;ly appear in data. referred to the % dataset channel numbering (not to te list of SQUID channels) % badGref: List of reference gradiometer channels that cannot be used for % balancing. if ~exist('chanList');chanList=[];end prec=class(data); [alphaMEG,MEGindex,MEGbalanceindex,alphaGref,Grefindex,Gbalanceindex]=... getCTFBalanceCoefs(ds,balance,unit); if ~strcmp(lower(balance(1,:)),'NONE'); % Are there any MEG channels missing from list MEGindex (i.e. missing from the balance table)? % Make a list of MEG channels referred to dataset channel numbering. MEGlist=[]; for k=1:ds.res4.no_channels if ds.res4.senres(k).sensorTypeIndex==5;MEGlist=[MEGlist k];end end missingMEG=setdiff(MEGlist,MEGindex); if ~isempty(missingMEG) & messages~=0 & ... (isempty(chanList) | intersect(missingMEG,chanList)) fprintf('setCTFDataBalance (balance_data): Channel(s) missing from the balance table:\n'); for k=missingMEG fprintf('\t%3d: %s\n',k,strtok(ds.res4.chanNames(k,:),'- ')); end end clear MEGlist k; % Are there any badGref in the MEGbalanceindex list? if ~isempty(intersect(MEGbalanceindex,badGref)) fprintf(['setCTFDataBalance (unbalance_data): A reference gradiometer marked bad ',... 'because of its grad_order_no\n',... ' appears in the list of reference sensors required for ',... '%s MEG balancing.\n'],balance(1,:)); fprintf(' MEGbalanceindex=');fprintf(' %d',MEGbalanceindex);fprintf('\n'); fprintf(' badGref=');fprintf(' %d',badGref);fprintf('\n'); data=[]; % Force an error in the calling program return end if isequal(chanList,1:max(max(MEGindex),max(MEGbalanceindex))); chanList=[]; end % Check if alphaMEG is all zeros or is improperly defined. do_balance=~isempty(alphaMEG) & ~isempty(MEGindex) & ~isempty(MEGbalanceindex); if do_balance if ~isequal(size(alphaMEG),[length(MEGbalanceindex) length(MEGindex)]); fprintf(['setCTFDataBalance (balance_data): size(alphaMEG)=[%d %d] ',... 'length(MEGbalanceindex)=%d length(MEGindex)=%d\n'],... size(alphaMEG),length(MEGbalanceindex),length(MEGindex)); data=[]; return elseif isempty(chanList) & size(data,2)<max(MEGindex) fprintf(['setCTFDataBalance (balance_data): chanList=[], but size(data,2)=%d ',... 'max(MEGindex)=%d ?\n'],size(data,2),max(MEGindex)); data=[]; return end do_balance=~all(reshape(alphaMEG,1,length(MEGbalanceindex)*length(MEGindex))==0); end if do_balance if ~isempty(chanList) % Re-sort the reference sensor indices and make them refer to chanList [MEGbalanceindex,MEGindex,alphaMEG]=... reindex(chanList,MEGbalanceindex,MEGindex,alphaMEG); % Refer the missing MEG channels to chanList if ~isempty(missingMEG);missingMEG=reindex(chanList,missingMEG);end end % Balance MEGs data trial-by-trial and in blocks of nChBlock channels for pt=1:size(data,3) for m=1:nChBlock:length(MEGindex) mptr=m:min(m+nChBlock-1,length(MEGindex)); MEGblock=MEGindex(mptr); if strcmp(prec,'single') data(:,MEGblock,pt)=single(double(data(:,MEGblock,pt))-... double(data(:,MEGbalanceindex,pt))*alphaMEG(:,mptr)); else data(:,MEGblock,pt)=data(:,MEGblock,pt)-... data(:,MEGbalanceindex,pt)*alphaMEG(:,mptr); end end % Zero the channel with missing coefficients. They cannot possibly be correct. for m=missingMEG if strcmp(prec,'single') data(:,m,pt)=single(zeros(size(data,1),1,1)); else data(:,m,pt)=zeros(size(data,1),1,1); end end end end clear alphaMEG MEGindex MEGbalanceindex Ix pt m mptr MEGblock do_balance missingMEG; end % Finished balancing the MEG data % Is Gref balancing requested? In most cases, balance(2,:)='NONE' if size(balance,1)==1;return;end if strcmp(balance(2,:),'NONE');return;end % Are there any bad Gref sensors in the Gbalanceindex list? if ~isempty(intersect(Gbalanceindex,badGref)) fprintf(['setCTFDataBalance (balance_data): A reference gradiometer marked bad ',... 'because of its grad_order_no\n',... ' appears in the list of reference sensors required for ',... '%s Gref balancing.\n'],balance(2,:)); fprintf(' Gbalanceindex=');fprintf(' %d',Gbalanceindex);fprintf('\n'); fprintf(' badGref=');fprintf(' %d',badGref);fprintf('\n'); data=[]; % Force an error in the calling program return end % Make the index lists refer to the entries in chanList. if ~isempty(chanList) [Gbalanceindex,Grefindex,alphaGref]=... reindex(chanList,Gbalanceindex,Grefindex,alphaGref); end % Balance the reference channels for pt=1:size(data,3) for m=1:nChBlock:length(Grefindex) mptr=m:min(m+nChBlock-1,length(Grefindex)); Grefblock=Grefindex(mptr); if strcmp(prec,'single'); data(:,Grefblock,pt)=single(double(data(:,Grefblock,pt))-... double(data(:,Gbalanceindex,pt))*alphaGref(:,mptr)); else data(:,Grefblock,pt)=data(:,Grefblock,pt)-... data(:,Gbalanceindex,pt)*alphaGref(:,mptr); end end end clear pt m mptr Grefblock Grefindex Gbalanceindex; return % ******************** End of function balance_data **************************** % *********************************************************************************** % *********************************************************************************** % ************** Reassign indices in sensor and reference lists. ****************** function [refindex,sensorindex,alfa2]=reindex(chanlist,reflist,sensorlist,alfa); % Reindex lists reflist and sensor list, and reorders 2nd index of matrix alfa. % Inputs : Lists of sensor and references for balancing and matrix of balance % coefficients. % Outputs : index lists: chanlist(refindex)=reflist % chanlist(sensorindex)=sensorlist % alfa2=The part of alfa that refers to the part of sensorlist % that appears in chanlist. refindex=[];sensorindex=[];alfa2=[]; % Force an error on an early return. % Sensible argument lists? if nargout>nargin-1 | nargout==0 fprintf('reindex: %d outputs, but only %d inputs.\n',nargout,nargin); return end [X c1 c2]=intersect(chanlist,reflist); [Y ylist]=sort(c2); refindex=c1(ylist); if length(refindex)~=length(reflist) fprintf('setCTFDataBalance (reindex): length(refindex)=%d length(reflist)=%d\n',... length(refindex),length(reflist)); fprintf(' Some references are not included in chanlist.\n'); return end if nargin>=3 & nargout>=2 [X c1 c2]=intersect(chanlist,sensorlist); [Y ylist]=sort(c2); sensorindex=c1(ylist); end if nargin>=4 & nargout>=3 alfa2=alfa(:,Y); end return % ***********************************************************************************
github
lcnhappe/happe-master
writeCTFMRI.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/ctf/writeCTFMRI.m
8,517
utf_8
c6bdbc15d67e3621b8109f6b399f5eae
function writeCTFMRI(fileName,MRItags,MRIdata); % Version 1.2 25 April 2007 Module writeCPersist changed, and removed from this text % file. % Version 1.1 19 April 2007 : No changes from v1.0 % Version 1.0 27 Oct. 2006 % Write a CTF MRI in v4 format. % For file format and a defineition fo CPersist objects, see document % "CTF MEG FIle Formats", PN900-0088 % Input: fileName : Name of MRI file including path and extension. % Outputs: MRItags : CPersist tags describing the MRI in the format of the structure array % produced by readMRI. There must be no start and stop tags. % Clnical use messages are added to _PATIENT_ID, _PATIENT_NAME, % _STUDY_COMMENTS, _CTFMRI_COMMENTS. % I.e name='WS1_', type=0, data=[] and % name='EndOfParameters', type -1, data=[] % MRIdata: 256x256x256 array. No value may exceed 2^15-1 since the data are % converted to int16. % MRIdata(j,k,n) = pixel(j,k) of slice n. % j = coronal slice. j=1:anterior, j=256:posterior % k = axial slice. k=1:superior, k=256:inferior % n = sagittal slice. j=1:left, j=256:right % Calls: writeCPersist (not included in this listing) % update_MRI_descriptors (included in this listing) persistent printWarning clinical_use_message='NOT FOR CLINICAL USE'; creatorSoftware='writeCTFMRI.m'; % Added to .infods file NpxNot256Warning=1; % Print a warning if the no. of slices is not 256 if nargin==0 & nargout==0 fprintf(['writeCTFMRI: Version 1.2 25 April 2007 Creates MRIs in CTFMRI v4 format.\n',... '\twriteCTFMRI(MRIfilename,MRItags,MRIdata);\n',... '\t\tMRIfilename = complete name including path and extension .mri\n',... '\t\tMRItags= structure array listing descriptors in the format produced',... 'by function readMRI.\n',... '\t\tMRIdata = MRI data array.\n\n',... '\tSee document "CTF MEG FIle Formats", PN900-0088\n']); return end if nargin~=3 fprintf(['writeCTFMRI: Found %d input arguments. ',... 'Must have 3 inputs (filename,MRItags,MRIdata).\n'],nargin); return elseif ~ischar(fileName) | isempty(fileName) | ~isstruct(MRItags) | isempty(MRItags) |... ~isnumeric(MRIdata) | isempty(MRIdata) fprintf('writeCTFMRI : Wrong argument type, or argument(s) empty.\n'); whos fileName MRItags MRIdata; return elseif ~isfield(MRItags,'name') | ~isfield(MRItags,'type') | ~isfield(MRItags,'data') fprintf('writeCTFMRI: MRItags does not have the correct fields (name, type,data).\n'); MRItags return elseif ndims(MRIdata)~=3 | ~all(size(MRIdata)==size(MRIdata,1)) fprintf('writeCTFMRI: size(MRIdata)=[');fprintf(' %d',size(MRIdata));... fprintf('] Must be Npx*[1 1 1] in CTF MRI format.\n'); return elseif exist(fileName)==2 fprintf('writeCTFMRI: File %s already exists.\n',fileName); return end % Verify that this really is a CTF MRI. name=char([]); for k=1:length(MRItags); name=strvcat(name,MRItags(k).name); end isCTFMRI=(~isempty(strmatch('_CTFMRI_',name))); MRIsize=size(MRIdata,1); % assume square slices nSlice=size(MRIdata,3); if NpxNot256Warning & MRIsize~=256 fprintf(['\nwriteCTFMRI: size(MRIdata)=%d*[1 1 1]. CTF MRI format standard is ',... '256*[1 1 1].\n\t\t\tThis file may not work with MRIViewer.\n\n'],MRIsize); end if isCTFMRI sizeTag=strmatch('_CTFMRI_SIZE',name,'exact'); if length(sizeTag)~=1 isCTFMRI=0; else MRItags(sizeTag).data=MRIsize; end clear sizeTag; end if ~isCTFMRI fprintf(['writeCTFMRI: Structure array MRItags does not contain the tags ',... 'for a CTF MRI file (v4 format).\n'],fileName); return end clear isCTFMRI % Add clinical use and creator software messgaes MRItags=update_MRI_descriptors(MRItags,clinical_use_message,creatorSoftware); % Add MRIdata to MRItags, and add start and end tags nTag=length(MRItags); MRItags(2:nTag+1)=MRItags(1:nTag); MRItags(1)=struct('name','WS1_','type',0,'data',[]); % Start tag nTag=nTag+1; for k=1:nSlice MRItags(nTag+k)=struct('name',['_CTFMRI_SLICE_DATA#',num2str(k,'%5.5d')],'type',3,... 'data',int16(reshape(MRIdata(:,:,k),MRIsize^2,1))); end nTag=nTag+nSlice; MRItags(nTag+1)=struct('name','EndOfParameters','type',-1,'data',[]); % End tag clear MRIdata k nSlice MRIsize nTag; if isempty(printWarning) fprintf(['\nwriteCTFMRI: The MRI you are creating has been processed by software not\n',... '\tmanufactured by VSM MedTech Ltd. and that has not received marketing clearance\n',... '\tfor clinical applications. This MRI should not be later employed for clinical\n',... '\tand/or diagnostic purposes.\n']); printWarning=1; end % Create the MRI file. writeCPersist(fileName,MRItags); return %%%%%%%%%%%%%% end of readMRI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% Function update_MRI_descriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function MRItags=update_MRI_descriptors(MRItags,comment,creatorSoftware); % Makes sure that certain tags are in structure MRItags. % Inputs: MRItags : Structure array produced by readCTFMRI. % comment : Character string that is added to infods tags listed in addCommentTag. % creatorSoftware : Character string indicating that the MRI set was % created by writeCTFMRI. Added to the tags listed in addCreatorTag. % Adds comment (clinical use message) and creator software name to % MRI tags that will display the comment. addCommentTag=strvcat('_PATIENT_ID','_PATIENT_NAME',... '_STUDY_COMMENTS','_CTFMRI_COMMENT'); % MRI tags that will display the creator software. addCreatorTag=strvcat('_CTFMRI_COMMENT'); % Check that the comment and creator tags are in structure MRItags. If not, issue an % error message and set MRItags to []. addTag=strvcat(addCommentTag,addCreatorTag); addIndex=zeros(1,size(addTag,1)); k=0; for k=1:length(MRItags) tagIndex=strmatch(MRItags(k).name,addTag,'exact'); addIndex(tagIndex)=k; if all(addIndex)~=0;break;end end % addTag(j) is MRItags(addIndex(j)) if any(addIndex==0) % At least one of the addTags is missing. Print an error message and return. fprintf(['writeCTFMRI (update_MRI_descriptors): At least one tag is missing from ',... 'structure array MRItags.\n']); for k=1:size(addTag,1) if isempty(strmatch(addTag(k,:),addTag(1:k-1,:),'exact')) fprintf('\t\t\t%s\n',deblank(addTag(k,:))); end end MRItags=struct([]); % Force an error in the calling program. return end % Check that all of the addTags are text strings type=[MRItags.type]; if any(type(addIndex)~=9 & type(addIndex)~=10) fprintf('writeCTFMRI (update_MRI_descriptors): At least one of the new tags is not a character string.\n'); for k=1:length(addTag) if isempty(strmatch(addTag(k,:),addTag(1:k-1,:),'exact')) fprintf('\t\t\t%s type=%d\n',deblank(addTag(k,:)),type(addIndex(k))); end end MRItags=struct([]); % Force an error in the calling program. return end addCommentIndex=addIndex(1:size(addCommentTag,1)); addCreatorIndex=addIndex(size(addCommentTag,1)+[1:size(addCreatorTag,1)]); if exist('creatorSoftware')~=1; creatorSoftware=char([]); elseif ~ischar(creatorSoftware) creatorSoftware=char([]); else creatorSoftware=deblank(creatorSoftware); end if exist('comment')~=1; comment=char([]); elseif ~ischar(comment) comment=char([]); else comment=deblank(comment); end for k=addCreatorIndex if isempty(MRItags(k).data) MRItags(k).data=creatorSoftware; else MRItags(k).data=[creatorSoftware ' ' MRItags(k).data]; end end for k=addCommentIndex if isempty(MRItags(k).data) MRItags(k).data=comment; else MRItags(k).data=[comment ' ' MRItags(k).data]; end end % Shorten type 9 (CStr32) strings to 31 characters plus a terminating null. for k=addIndex if MRItags(k).type==9 & length(MRItags(k).data)>31; MRItags(k).data=[MRItags(k).data(1:31) char(0)]; end end return %%%%%%%%%%%%%% End of update_MRI_descriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
lcnhappe/happe-master
readCTFds.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/ctf/readCTFds.m
36,570
utf_8
e228d972ce0710af61be4d1d0c89f3fe
function ds=readCTFds(datasetname) % ************************************************************************ % % This program is provided to users of CTF MEG systems as a courtesy only. % It's operation has not been verified for clinical use. % Please do not redistribute it without permission from CTF Systems Inc. % % ************************************************************************ % readCTFds opens a CTF data set and creates a MATLAB structure with the information % in the .res4, .infods, .newds, .acq, .hc, .hist, .EEG, bad.segments, BadChannels, % ClassFile.cls andMarkerFile.mrk files. It confirms the existence of a .meg4 file % with the correct size. % See document CTF MEG File Formats, PN900-0088 for a description of the formats of % dataset files. % Author : Harold Wilson % ***************** Revisions and bug fixes ************************************** % Version 1.3 4 October 2007 % 1. readCTFds v1.2 failed when run in MATLAB 7.2, but ran correctly in % MATLAB 6.5 and 7.3. The failure occurred when calls to fscanf with a % final '\n' in the format string were followed by fgetl. In MATLAB 6.5 and 7.3, % this returns the next line of a text file, but in MATLAB 7.2, this % returns an empty charatcer string. % Changes were made to subprograms % - readHc, % - readClassFile % - readMarkerFile. % 2. In v1.1 and 1.2, if any of the head coil positions exceeded 100 cm, readHc % reported an error and returned hc=struct([]). In v1.3, is reports the error, % and returns the erroneaous values. % Version 1.2: 24 April 2007 % - readHc modified to read fMEG .hc files. % - readCPersist modified to handle extra bytes that appear in some .acq files. % Version 1.1: 13 April 2007 % readCTFds is modified to handle cases where the data files exceed a total of 2^31-8 % bytes. In these cases files .1_meg4,.2_meg4,... appear in the dataset. % *********************************************************************************** % Inputs : datasetname : Complete name of the data set directory. Includes the complete % path and the .ds extension. % Output: ds : A structure that gives data set parameters. % Function calls included in this listing: % - readRes4 % - readHc % - readEEG % - readMarkerFile % - readClassFile % - readBadSegments % - readVirtualChannels % External functions: - readCPersist Reads infods and acq files. % - The data directory is datasetname. % - path is the complete path to the directory including the last file delimiter. % - baseName is the directory name, less the last file extension. % - datasetname=[path,baseName,'.ds']; persistent printWarning multipleMeg4Files if nargin==0 & nargout==0 % Print a version number fprintf(['\treadCTFds: Version 1.3 4 October 2007 ',... 'Reads v4.1 and v4.2 CTF data sets including fMEG .hc files.\n',... '\tCall: ds=readCTFds(datasetname)\n',... '\t\tdatasetname = Name of the dataset including the path.\n',... '\t\tds = Structure containing all dataset information except for data in ',... 'the .meg4 file.\n\n']); return end MAX_COILS=8; MAX_BALANCING=50; % max. no. of balancing coefficients SENSOR_LABEL=31; % No. of characters in sensor labels in the balancing % coefficient tables len_sensor_name=32; % length of sensor coefficient records in bytes. See listing for MEGDefs.h %senres_lenrec=len_sensor_name+8+2+MAX_BALANCING*SENSOR_LABEL+8*MAX_BALANCING; % Allowed 8-byte headers for res4 and meg4 files. res4Headers=strvcat(['MEG41RS',char(0)],['MEG42RS',char(0)]); meg4Headers=strvcat(['MEG41CP',char(0)],['MEG42CP',char(0)]); delim=filesep; ds=struct([]); % Check that the data set exists. if exist('datasetname')~=1 fprintf('\nreadCTFds: No input datasetname specified.\n\n'); return elseif ~ischar(datasetname) | isempty(datasetname) | size(datasetname,1)~=1 fprintf('\nreadCTFds: Dataset name is not a string, or is empty, or is an array.\n\n'); whos datasetname return else % Separate datasetname into a path and the baseName and add extension .ds. datasetname=deblank(datasetname); ksep=max([0 findstr(datasetname,delim)]); baseName=datasetname((ksep+1):length(datasetname)); path=datasetname(1:ksep); % String path is terminated by the file delimiter (or path=[]). % Remove the last .ds from baseName. kdot=max(findstr(baseName,'.ds')); if kdot==(length(baseName)-2) baseName=baseName(1:(max(kdot)-1)); else datasetname=[datasetname,'.ds']; end clear ksep kdot; if exist(datasetname)~=7 fprintf('\nreadCTFds: Cannot find dataset %s.\n\n',datasetname); return end end % Check that the res4 and meg4 files exist. res4File=[datasetname,delim,baseName,'.res4']; meg4File=[datasetname,delim,baseName,'.meg4']; if exist(res4File)~=2 | exist(meg4File)~=2 fprintf('readCTFds: In directory %s, cannot find .res4 and/or .meg4 files.\n',... datasetname); return end % Check the headers on .meg4, .1_meg4, ... qFile=0; meg4Ext='.meg4'; meg4Size=[]; while 1 if qFile>0; meg4Ext=['.',int2str(qFile),'_meg4']; meg4File=[datasetname,delim,baseName,meg4Ext]; end if qFile>1 & isempty(multipleMeg4Files) fprintf('readCTFds: This dataset has multiple meg4 files.\n'); multipleMeg4Files=1; end fid=fopen(meg4File,'r','ieee-be'); if fid<=0;break;end D=dir([datasetname,delim,baseName,meg4Ext]); meg4Size=[meg4Size D.bytes]; meg4Header=char(fread(fid,8,'uint8')'); fclose(fid); if isempty(strmatch(meg4Header,meg4Headers,'exact')) fprintf('\nreadCTFds: %s file header=%s Valid header options:',meg4Ext,meg4Header); for k=1:size(meg4Headers,1);fprintf(' %s',meg4Headers(k,:));end fprintf('\n\n'); ds=struct([]); return end qFile=qFile+1; end Nmeg4=length(meg4Size); clear D fid qFile; % Add baseName and path to structure ds. ds=struct('baseName',baseName,'path',path); % Read the res4 file ds.res4=readRes4(res4File,res4Headers,... MAX_COILS,MAX_BALANCING,SENSOR_LABEL,len_sensor_name); if isempty(ds.res4);ds=struct([]);return;end dataBytes=4*ds.res4.no_trials*ds.res4.no_channels*ds.res4.no_samples; % Assemble ds.meg4. ds.meg4.fileSize=sum(meg4Size); ds.meg4.header=meg4Header; clear meg4Header meg4Size; % Does the size of the .meg4 file match the size specified by the .res4 file? if ds.meg4.fileSize~=8*Nmeg4+dataBytes fprintf(['\nreadCTFds: Data set error : size of meg4 file(s)\n\t\t',... '%10d bytes (from dir command)\n'],ds.meg4.fileSize); fprintf('\t\t%10d bytes (from res4 file)\n\n',8*Nmeg4+dataBytes); return end if isempty(printWarning) fprintf(['\nreadCTFds: You are reading CTF data for use with a software-application tool\n',... '\tthat is not manufactured by VSM MedTech Ltd. and has not received marketing\n',... '\tclearance for clinical applications. If CTF MEG data are processed by this tool,\n',... '\tthey should not be later employed for clinical and/or diagnostic purposes.\n\n']); printWarning=1; end % .infods file if exist([datasetname,delim,baseName,'.infods'])==2 ds.infods=readCPersist([datasetname,delim,baseName,'.infods']); end % .newds file if exist([datasetname,delim,baseName,'.newds'])==2 fid=fopen([datasetname,delim,baseName,'.newds'],'r','ieee-be'); ds.newds=char(fread(fid,'uint8'))'; fclose(fid); clear fid; end % .acq file if exist([datasetname,delim,baseName,'.acq'])==2 ds.acq=readCPersist([datasetname,delim,baseName,'.acq']); end % .hist file if exist([datasetname,delim,baseName,'.hist'])==2 fid=fopen([datasetname,delim,baseName,'.hist'],'r','ieee-be'); ds.hist=char(fread(fid,'uint8'))'; fclose(fid); end % .hc file if exist([datasetname,delim,baseName,'.hc'])==2 ds.hc=readHc([datasetname,delim,baseName,'.hc']); end % .eeg file if exist([datasetname,delim,baseName,'.eeg'])==2 ds.eeg=readEEG([datasetname,delim,baseName,'.eeg']); if isempty(ds.eeg);ds=rmfield(ds,'eeg');end end % marker file if exist([datasetname,delim,'MarkerFile.mrk'])==2 ds.mrk=readMarkerFile([datasetname,delim,'MarkerFile.mrk']); end % ClassFile if exist([datasetname,delim,'ClassFile.cls'])==2 ds.TrialClass=readClassFile([datasetname,delim,'ClassFile.cls']); end % bad.segments if exist([datasetname,delim,'bad.segments'])==2 ds.badSegments=readBadSegments([datasetname,delim,'bad.segments']); end % BadChannels if exist([datasetname,delim,'BadChannels'])==2 fid=fopen([datasetname,delim,'BadChannels'],'r','ieee-be'); ds.BadChannels=char([]); while 1 strng=fscanf(fid,'%s\n',1); if isempty(strng);break;end ds.BadChannels=strvcat(ds.BadChannels,strng); end fclose(fid); clear fid; end % VirtualChannels Assume this is the name of the file. Modify to accept *.vc? if exist([datasetname,delim,'VirtualChannels'])==2 ds.Virtual=readVirtualChannels([datasetname,delim,'VirtualChannels']); end % processing.cfg if exist([datasetname,delim,'processing.cfg'])==2 fid=fopen([datasetname,delim,'processing.cfg']); ds.processing=char(fread(fid,'uint8'))'; fclose(fid); clear fid; end return %%%%%%%%%%%%%%%%% End of readCTFds %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Function readRes4 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res4=readRes4(res4File,res4Headers,... MAX_COILS,MAX_BALANCING,SENSOR_LABEL,len_sensor_name); % Open the res4 file fid=fopen(res4File,'r','ieee-be'); % Check header. res4.header=char(fread(fid,8,'uint8')'); if isempty(strmatch(res4.header,res4Headers,'exact')) fprintf(['\nreadCTFds (readRes4):res4 file header = %s. ',... 'Valid header options:'],res4.header); for k=1:size(res4Headers,1);fprintf(' %s',res4Headers(k,:));end;fprintf('\n\n'); res4=struct([]); fclose(fid); return end % Remove trailing blanks, but include a final null (char(0)). res4.appName=[deblank(char(fread(fid,256,'uint8')')) char(0)]; res4.dataOrigin=[deblank(char(fread(fid,256,'uint8')')) char(0)]; res4.dataDescription=[deblank(char(fread(fid,256,'uint8')')) char(0)]; res4.no_trials_avgd=fread(fid,1,'int16'); res4.data_time=[deblank(char(fread(fid,255,'uint8')')) char(0)]; res4.data_date=[deblank(char(fread(fid,255,'uint8')')) char(0)]; % new_general_setup_rec_ext part of meg41GeneralResRec res4.no_samples=fread(fid,1,'int32'); temp=fread(fid,2,'int16'); res4.no_channels=temp(1); res4.sample_rate=fread(fid,1,'float64'); res4.epoch_time=fread(fid,1,'float64'); temp=fread(fid,2,'int16'); res4.no_trials=temp(1); res4.preTrigPts=fread(fid,1,'int32'); res4.no_trials_done=fread(fid,1,'int16'); res4.no_trials_display=fread(fid,1,'int16'); res4.save_trials=fread(fid,1,'int32'); % meg41TriggerData part of new_general_setup_rec_ext 10 bytes total res4.primaryTrigger=fread(fid,1,'int32'); res4.triggerPolarityMask=fread(fid,1,'int32'); temp=fread(fid,1,'int16'); %Skip 2 bytes of padding % end of meg41TriggerData part of new_general_setup_rec_ext temp=fread(fid,3,'int16'); %Skip 2 bytes of padding res4.trigger_mode=temp(2); res4.accept_reject_Flag=fread(fid,1,'int32'); temp=fread(fid,2,'int16'); %Skip 2 bytes of padding res4.run_time_display=temp(1); res4.zero_Head_Flag=fread(fid,1,'int32'); res4.artifact_mode=fread(fid,1,'int32'); % end of new_general_setup_rec_ext part of meg41GeneralResRec % meg4FileSetup part of meg41GeneralResRec % Remove trailing blanks, but include a final null (char(0)) res4.nf_run_name=[deblank(char(fread(fid,32,'uint8')')) char(0)]; res4.nf_run_title=[deblank(char(fread(fid,256,'uint8')')) char(0)]; res4.nf_instruments=[deblank(char(fread(fid,32,'uint8')')) char(0)]; res4.nf_collect_descriptor=[deblank(char(fread(fid,32,'uint8')')) char(0)]; res4.nf_subject_id=[deblank(char(fread(fid,32,'uint8')')) char(0)]; res4.nf_operator=[deblank(char(fread(fid,32,'uint8')')) char(0)]; res4.nf_sensorFileName=[deblank(char(fread(fid,56,'uint8')')) char(0)]; temp=fread(fid,3,'int32'); res4.rdlen=temp(2); res4.run_description=[deblank(char(fread(fid,res4.rdlen,'uint8')')) char(0)]; % end of meg4FileSetup part of meg41GeneralResRec % Filter descriptions. Set field res4.filters=[] if no filters are % defined. res4.num_filters=fread(fid,1,'int16'); if res4.num_filters==0 res4.filters=[]; else for kfilt=1:res4.num_filters res4.filters(kfilt).freq=fread(fid,1,'float64'); res4.filters(kfilt).fClass=fread(fid,1,'int32'); res4.filters(kfilt).fType=fread(fid,1,'int32'); res4.filters(kfilt).numParam=fread(fid,1,'int16'); for kparm=1:res4.filters(kfilt).numParam res4.filters(kfilt).Param(kparm)=fread(fid,1,'float64'); end end clear kfilt kparm; end % Read channel names. Must have size(res4.chanNames)=[channels 32] % Clean up the channel names. The MEG system software leaves junk % bytes in the channel name following the first zero. res4.chanNames=char(zeros(res4.no_channels,32)); for kchan=1:res4.no_channels xname=strtok(char(fread(fid,32,'uint8')'),char(0)); res4.chanNames(kchan,1:length(xname))=xname; end clear kchan xname; % Read sensor resource table. Floating point values are 'double' % but the code could be changed to convert to 'single' to save memory. for kchan=1:res4.no_channels res4.senres(kchan).sensorTypeIndex=fread(fid,1,'int16'); res4.senres(kchan).originalRunNum=fread(fid,1,'int16'); res4.senres(kchan).coilShape=fread(fid,1,'int32'); res4.senres(kchan).properGain=fread(fid,1,'double'); res4.senres(kchan).qGain=fread(fid,1,'double'); res4.senres(kchan).ioGain=fread(fid,1,'double'); res4.senres(kchan).ioOffset=fread(fid,1,'double'); res4.senres(kchan).numCoils=fread(fid,1,'int16'); numCoils=res4.senres(kchan).numCoils; temp=fread(fid,3,'int16'); res4.senres(kchan).grad_order_no=temp(1); % Special code to take care of situations where someone wants to label bad channels % by setting their gain to zero. invgain=(res4.senres(kchan).ioGain*... res4.senres(kchan).properGain*res4.senres(kchan).qGain); if abs(invgain)>1e-50 res4.senres(kchan).gain=1/invgain; else res4.senres(kchan).gain=sign(invgain)*1e50; end if res4.senres(kchan).sensorTypeIndex>=0 & res4.senres(kchan).sensorTypeIndex<=7 % Nominal gain (fT/integer step) res4.senres(kchan).gain=1e15*res4.senres(kchan).gain; end % Data that was included in res4.senres(kchan).coilTbl in earlier versions of readCTFds res4.senres(kchan).pos0=zeros(3,res4.senres(kchan).numCoils); res4.senres(kchan).ori0=zeros(3,res4.senres(kchan).numCoils); res4.senres(kchan).area=zeros(1,res4.senres(kchan).numCoils); res4.senres(kchan).numturns=zeros(1,res4.senres(kchan).numCoils); for qx=1:numCoils buff=fread(fid,8,'double'); res4.senres(kchan).pos0(:,qx)=buff(1:3); res4.senres(kchan).ori0(:,qx)=buff(5:7); temp=fread(fid,4,'int16'); res4.senres(kchan).numturns(qx)=temp(1); res4.senres(kchan).area(qx)=fread(fid,1,'double'); end if numCoils<MAX_COILS % Skip the rest of the coilTbl buff=fread(fid,10*(MAX_COILS-numCoils),'double'); end % Data that was included in res4.senres(kchan).HdcoilTbl in earlier versions of readCTFds res4.senres(kchan).pos=zeros(3,res4.senres(kchan).numCoils); res4.senres(kchan).ori=zeros(3,res4.senres(kchan).numCoils); for qx=1:numCoils buff=fread(fid,8,'double'); res4.senres(kchan).pos(:,qx)=buff(1:3); res4.senres(kchan).ori(:,qx)=buff(5:7); temp=fread(fid,2,'double'); % Don't bother with area and numturns. Already read. end if numCoils<MAX_COILS % Skip the rest of the HdcoilTbl buff=fread(fid,10*(MAX_COILS-numCoils),'double'); end end clear kchan buff numCoils temp qx; % End reading sensor resource table res4.numcoef=fread(fid,1,'int16'); % Number of coefficient records % Create structure array res4.scrr which holds the balancing tables. for nx=1:res4.numcoef res4.scrr(nx).sensorName=uint8(fread(fid,len_sensor_name,'uint8'))'; buff=fread(fid,8,'uint8'); res4.scrr(nx).coefType=uint8(buff(1:4))'; % discard bytes 5-8 res4.scrr(nx).numcoefs=double(fread(fid,1,'int16')); numcoef=res4.scrr(nx).numcoefs; buff=fread(fid,SENSOR_LABEL*MAX_BALANCING,'uint8'); buff=reshape(buff,SENSOR_LABEL,MAX_BALANCING); res4.scrr(nx).sensor=[uint8(buff(:,1:numcoef)) ... uint8(zeros(SENSOR_LABEL,MAX_BALANCING-numcoef))]; buff=fread(fid,MAX_BALANCING,'double'); res4.scrr(nx).coefs=[buff(1:numcoef);zeros(MAX_BALANCING-numcoef,1)]; end fclose(fid); % Close the res4 file return %%%%%%%%%% End of readRes4 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Function readHc %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hc=readHc(hcFile); % Reads the .hc file and returns a structure with head-coil posiiotns. % The hc file format is given in document CTF MEG File Formats (PN900-0088). % .hc file format: Coils and positions are specified by 4 lines of text: % Line 1: A B coil position relative to C (cm): % " 2: [tag]x = F % " 3: [tag]y = F % " 4: [tag]z = F % A = 'standard' or 'stadard' or 'measured'. 'stadard' is a typographical error that % appeared in v4 of the CTF Acq. The first set of coil positions is 'standard' or % 'stanard'. The next two sets are 'measured'. % B = coil label. For MEG systems, the first three coils must have the names 'nasion', % 'left ear', 'right ear'. They may be followed by other coil names. % For fMEG systems, there is no fixed standard for coil names.b readHc will % accept any coil names. Typically the coils are 'back','left hip','right hip', % 'sternum', 'belly'. In some UAMS data the names are 'nasion',... % The string 'coil position relative to' appears in all valid .hc files. It marks % the end of the coil label and the start ot the coordinate-system. % C = coordinate system = 'dewar' and 'head'(MEG) or 'abdomen' (fMEG). No variations % are permitted. The first two sets of coil positions are in dewar coordinates. % The last set is in 'head' or 'abdomen' coordinates. % Units : For .hc to be a valid coil position file, the coordinates must be in cm. % The program searches for the string '(cm):'. % F = coordinate (numeric) % There are exactly 3 sets of coil positions in the file appearing in the order % (1) A='standard', C='dewar' % (2) A='measured', C='dewar' % (3) A='measured', C='head' or 'abdomen' % The coils must appear in the same order in each set. % Input : Name of hc file (including complete path and .hc extension) % Output : Structure hc containing standard, dewar and CTF coordinates of the % nasion,left,right coils. % hc.name= names of the coils size(hc.name)=[nCoil x] % MEG: hc.standard, hc.dewar, hc.head : size=[3 nCoil] : coil positions in cm % fMEG: hc.standard, hc.dewar, hc.abdomen : size=[3 nCoil] : coil positions in cm if nargin==0 & nargout==0 fprintf(['readHc: Version 1.3 4 Oct. 2007\n',... '\thc=readHc(hcFile) reads head-coil file hcFile and returns the head coil',... '\t positions in structure hc\n\n',... '\tThe file format is defined in document CTF MEG File Formats, PN900-0088.\n\n']); return end basicString='coil position relative to'; % In MEG systems, the first three coil names are fixed. MEGCoilLabel=strvcat('nasion','left ear','right ear'); C3options=strvcat('head','abdomen'); unitString='(cm):'; maxRCoil=200; % Report an error if any coil position is > maxRCoil cm. printWarning=1; hc=struct([]); % Return in event of an error. if exist(hcFile)~=2 return end prec=1e-6; % Round positions. % Decide if this is a MEG or an fMEG system. Find the first line that contains the % string 'coil position relative to'. % MEG system: This line contains 'nasion'. % fMEG system: This line does not contains 'nasion'. fhc=fopen(hcFile,'rt','ieee-be'); % Decide system type and generate arrays for strings A and C. % Search for first line. Allow for the posibility that extra text lines migt be added at % the start of the file. strngA=char([]); while 1 textline=fgetl(fhc); if isequal(textline,-1) break elseif strfind(textline,'coil position relative to'); stringA=strtok(textline); % Fix typographic error in some releases of Acq, not in all coils. if strcmp(stringA,'stadard') stringA = 'standard'; end if ~strcmp(stringA,'standard') break end stringA=strvcat(stringA,'measured','measured'); break; end end if isequal(textline,-1) | size(stringA,1)<3 fprintf('readHc: File %s does not have the head position file format.\n',hcFile); fclose(fhc); return end % Set stringC(3,:)='head' or 'abdomen' later. stringC=strvcat('dewar','dewar'); % textline is the first useful line of the head coil file. coilLabel=char([]); % Names given to the coils rhc=zeros(3,0); % Coil positions (cm) coil=0; nCoil=0; lastPositionSet=1; while ~isequal(textline,-1) % Parse the line [A,R]=strtok(textline); % Fix typographic error in some releases of Acq, not in all coils. if strcmp(A,'stadard') A = 'standard'; end kpos=strfind(R,basicString); coilName=deblank(R(2:kpos-1)); [C,R]=strtok(R(kpos+length(basicString):length(R))); if strmatch(C,C3options) stringC=strvcat(stringC,C); end [unit,R]=strtok(R); if isempty(A) & isempty(C) % This can happen on empty line after reading all the information, and would cause positionSet to be [1; 2; 3], problematic for loop below. break; end positionSet=intersect(strmatch(A,stringA),strmatch(C,stringC)); % strmatch matches empty strings to everything. if isempty(positionSet) | ~strcmp(unit,unitString) | ~isempty(R) break; end if positionSet==lastPositionSet coil=coil+1; else coil=1; end if positionSet==1 % Assemble list of coil names coilLabel=strvcat(coilLabel,coilName); nCoil=coil; elseif ~strcmp(coilName,deblank(coilLabel(coil,:))); break; end % The line describing the coil and coordinate frame is OK. % Get the coordinates by reading 3 lines. buff=fscanf(fhc,'%s%s%f',9); if ~isequal(size(buff),[9 1]) break end rhc=[rhc prec*round(buff(3:3:9)/prec)]; fgetl(fhc); % Skip to the start of the next line. textline=fgetl(fhc); lastPositionSet=positionSet; end fclose(fhc); clear lastPositionSet coil textline fhc; clear stringA A C R kpos coilName unit buff; if size(rhc,2)~=positionSet*nCoil fprintf('readHc: File %s does not have %d complete sets of %d coils.\n',... hcFile,positionSet,nCoil); return end if max(max(abs(rhc)))>maxRCoil & printWarning fprintf('readHc: Head Coil file %s\n max(coil position)>%d.\n',... hcFile,round(maxRCoil)); end % Assemble structure hc. hc=struct('names',coilLabel); coilCoords=deblank(strvcat('standard','dewar',stringC(3,:))); for q=1:positionSet hc=setfield(hc,deblank(coilCoords(q,:)),rhc(:,nCoil*(q-1)+[1:nCoil])); end return %%%%%%%%% End of readHc %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Function readEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function EEG=readEEG(EEGfile); % Reads the EEG file of a dataset and stores the infoemation in strucure array EEG. % EEG(k).chanName = channel name in the dataset (EEGmmm where mmm=channel number) % EEG(k).name = channel name given by the user (e.g. Fp4) % EEG(k).pos = electrode position in cm in CTF head coordinates if exist(EEGfile)~=2 EEG=struct([]); return end fid=fopen(EEGfile,'r'); EEG=struct('chanNum',[],'name',char([]),'pos',[]); nEEG=0; while 1 chanNum=fscanf(fid,'%d',1); name=fscanf(fid,'%s',1); pos=fscanf(fid,'%f',3); if isempty(pos);break;end nEEG=nEEG+1; EEG(nEEG)=struct('chanNum',chanNum,'name',name,'pos',pos); end fclose(fid); return %%%%%%%%% End of readEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Function readClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function TrialClass=readClassFile(ClassFileName); % Reads a CTF ClassFile and stores information in a structure. % The class file allows a user to store a list of classsified trials in a data set. % The ClassFile format is defined in document CTF MEG File Formats, PN900-0088. % This format is rigid and readClassFile assumes that the ClassFile has the format % current in October 2006. % Inputs : % ClassFileName : marker file including the full path and extension .mrk. % trialList : List of trials to read. Trial numbering : 1,2,... % If omitted or empty, read all markers. % Output : Structure array marker. Output trial numbering starts at 1. % See CTF MEG File Formats, (PN900-0088) for the meaning of the structure % fields. A trial mat=y start before the t=0 point, so it is possible to have % markers with time<0 (see ds.res4.preTrigPts). TrialClass=struct([]); if exist(ClassFileName)~=2 return % File doesn't exist. end fid=fopen(ClassFileName,'r','ieee-be'); for k=1:5;fgetl(fid);end % Skip 5 lines (including path info) nClass=sscanf(fgetl(fid),'%d',1); %Read value and skip to the start of the next non-blank line. if nClass<=0 fprintf('readClassFile: File %s has %d classes.\n',nClass); return end TrialClass=struct('ClassGroupId',[],'Name',char([]),... 'Comment',char([]),'Color',char([]),'Editable',char([]),'ClassId',[],'trial',[]); for k=1:nClass % Find the start of the next class identification % There is no need to check for end of file because the loop ends before an attempt % is made to read class nClass+1. while ~strcmp('CLASSGROUPID:',fgetl(fid));end ClassGroupId=sscanf(fgetl(fid),'%d',1); fgetl(fid); Name=deblank(fgetl(fid)); fgetl(fid); Comment=deblank(fgetl(fid)); fgetl(fid); Color=deblank(fgetl(fid)); fgetl(fid); Editable=deblank(fgetl(fid)); fgetl(fid); ClassId=sscanf(fgetl(fid),'%d',1); fgetl(fid); No_of_Trials=sscanf(fgetl(fid),'%d',1); fgetl(fid);fgetl(fid); if No_of_Trials>0 trial=reshape(fscanf(fid,'%d',No_of_Trials),1,No_of_Trials); else trial=[]; end % Adjust trial numbering so it starts at 1. TrialClass(k)=struct('ClassGroupId',ClassGroupId,'Name',Name,... 'Comment',Comment,'Color',Color,'Editable',Editable,'ClassId',ClassId,... 'trial',trial+1); end fclose(fid); return %%%%%%%%% End of readClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Function readBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function badSegments=readBadSegments(badSegmentsFile); % Reads the bad.segements file of a CTF data set and stores the information in structure % bad_segments. % badSegments.trial = List of trial numbers % badSegments.StartTime = List of bad segment start times (relative to trial). % badSegments.EndTime = List of bad segment end times. % Reads the file one line at a time. Each line has three numbers. % 1st: Trial number=integer. Trial numbering for bad.segments starts at 1. % 2nd,3rd : Start, End times (s). if exist(badSegmentsFile)~=2 badSegments=struct([]); return end fid=fopen(badSegmentsFile,'r','ieee-be'); badSegments=struct('chanName',char([]),'name',char([]),'pos',[]); nLine=0; data=zeros(3,0); while 1 txt=fgetl(fid); if isequal(txt,-1);break;end nLine=nLine+1; [buff,count]=sscanf(txt,'%f'); % Are the data good? badline=(count~=3); if ~badline;badline=(abs((buff(1)-round(buff(1)))>0.0001) | buff(3)<buff(2));end if badline fprintf('readCTFds (readBadSegments): Format error in file bad.segments.\n'); fprintf('\tLine %d has %d numbers: ',nLine,count);fprintf('\t %g',buff);fprintf('\n'); fprintf('\tMust have 3 numbers on each line: #1=integer, #2,#3=float, #3>=#2.\n'); badSegments=struct([]); return end data=[data buff]; end fclose(fid); badSegments=struct('trial',data(1,:),'StartTime',data(2,:),'EndTime',data(3,:)); return %%%%%%%%% End of readBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Function readVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function Virtual=readVirtualChannels(VirtualChannelsName); % Reads the Virtual channels file associated with a data set Virtual=struct([]); % Check VirtualChannelsName if exist('VirtualChannelsName')~=1;VirtualChannelsName=char([]);end if isempty(VirtualChannelsName) fprintf('readVirtualChannels: Must specify a VirtualChannels file.\n'); return elseif ~ischar(VirtualChannelsName) fprintf('readVirtualChannels: VirtualChannelsName must be a character string.\n'); return elseif exist(VirtualChannelsName)~=2 fprintf('readVirtualChannels: Cannot find file %s\n',VirtualChannelsName); return end fid=fopen(VirtualChannelsName,'r'); count=0; Virtual=struct('Name',char([]),'Unit',char([]),'chan',char([]),'wt',[]); strng=textread(VirtualChannelsName,'%s','delimiter',',\t'); k=0; while k<length(strng) k=k+1; if strmatch('VirtualChannel',strng{k}); Refcount=0; chan=char([]); wt=[]; elseif strmatch('Name:',strng{k}); k=k+1; Name=strng{k}; if isempty(Name);break;end elseif strmatch('Unit:',strng{k}); k=k+1; Unit=strng{k}; elseif strmatch('Ref:',strng{k}); chan=strvcat(chan,strng{k+1}); wt=[wt;str2num(strng{k+2})]; k=k+2; elseif strmatch('}',strng{k}); count=count+1; Virtual(count)=struct('Name',Name,'Unit',Unit,'chan',chan,'wt',wt); clear Name Unit chan wt Refcount; end end fclose(fid); if isempty(Virtual(1).Name) Virtual=struct([]); end return %%%%%%%%% End of readVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Function readMarkerFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function marker=readMarkerFile(MarkerFileName,trialList); % Version 1.3 4 Oct. 2007 % Reads specified trials of a CTF MarkerFile. % The MarkerFile format is defined in document CTF MEG File Formats, PN900-0088. % This format is rigid and readMarkerFile assumes that the MarkerFile has the format % current in October 2006. The document lists 4 Class Groups, but only CLASSGROUPID=0 % (triggers) and CLASSGROUPID=3 (Manual) are actually used. read_MArkerFile reads only % these two groups, but it prints a message if the other groups are encountered. % Trigger markers (CLASSGROUPID=0) have an additional 4 pieces of information supplied: % BITNUMBER(int), POLARITY(+ or 1),SOURCE(text) and THRESHOLD (float). FOr % CLASSGROUPID=3, these fields are left empty. % Inputs : % MarkerFileName : marker file including the full path and extension .mrk. % trialList : List of trials to read. Trial numbering : 1,2,... % If omitted or empty, read all markers. % Output : marker: Structure array. Output trial numbering starts at 1. % See CTF MEG File Formats, (PN900-0088) for the meaning of the structure % fields. A trial may start before the t=0 point, so it is possible to have % markers with time<0 (see ds.res4.preTrigPts). % Fields: ClassGroupId, Name,Comment,Color,Editable,ClassId,trial,time; % Other fields that appear with ClassGroupId=0 are not included. if nargin==0 & nargout==0 fprintf(['readMarkerFile: Version 1.3 4 Oct. 2007\n',... '\tReads a CTF dataset MarkerFile and returns a structure array.\n',... '\tmarker=readMarkerFile(FileName) reads ',... 'a marker file and returns the trials and times.\n',... '\tmarker=readMarkerFile(FileName,trialList) reads a marker file and returns only\n',... '\t\t\tthe markers for trials listed in vector trialList.\n\n',... '\treadMarkerFile increments trial numbers by 1 so first trial in a dataset has trial=1.\n\n',... '\tThe MarkerFile format is defined in document CTF MEG File Formats, PN900-0088.\n\n']); return end marker=struct([]); % Check MarkerFileName if exist('MarkerFileName')~=1;MarkerFileName=char([]);end if exist(MarkerFileName)~=2 % No MarkerFile present fprintf('readMarkerFile: Could not find MarkerFile.\n'); MarkerFileName return end % Check input trialList if exist('trialList')~=1 trialList=[]; else trialList=reshape(trialList,1,length(trialList)); if any((trialList-round(trialList))>0.1) | any(round(trialList)<=0) fprintf('readMarkerFile: trialList must have only positive integers.\n'); return end end fid=fopen(MarkerFileName,'r','ieee-be'); for k=1:5;fgetl(fid);end % Skip 5 lines (including path info) nMarker=sscanf(fgetl(fid),'%d',1); %Read value and skip to the start of the next non-blank line. if nMarker<=0 fprintf('readMarkerFile: File %s has %d markers.\n',nMarker); fclose(fid); return end marker=struct('ClassGroupId',[],'Name',char([]),... 'Comment',char([]),'Color',char([]),'Editable',char([]),'ClassId',[],... 'BitNumber',[],'Polarity',char([]),'Source',char([]),'Threshold',[],... 'trial',[],'time',[]); for k=1:nMarker % Find the start of the next marker identification % There is no need to check for end of file because the loop ends before an attempt % is made to read marker class nClass+1. while ~strcmp('CLASSGROUPID:',fgetl(fid));end ClassGroupId=sscanf(fgetl(fid),'%d',1); if ~any(ClassGroupId==[0 3]) fprintf('read_MarkerFile: Skipping a marker with CLASSGROUPID=%d\n',ClassGroupId); continue; end fgetl(fid); Name=deblank(fgetl(fid)); fgetl(fid); Comment=deblank(fgetl(fid)); fgetl(fid); Color=deblank(fgetl(fid)); fgetl(fid); Editable=deblank(fgetl(fid)); fgetl(fid); ClassId=sscanf(fgetl(fid),'%d',1); if ClassGroupId==0 fgetl(fid); BitNumber=sscanf(fgetl(fid),'%d',1); fgetl(fid); Polarity=deblank(fgetl(fid)); fgetl(fid); Source=deblank(fgetl(fid)); fgetl(fid); Threshold=sscanf(fgetl(fid),'%f',1); else BitNumber=[]; Polarity=char([]); Source=char([]); Threshold=[]; end fgetl(fid); No_of_Samples=sscanf(fgetl(fid),'%d',1); fgetl(fid);fgetl(fid); trial=zeros(1,No_of_Samples); time=zeros(1,No_of_Samples); if No_of_Samples>0 buff=fscanf(fid,'%d %f\n',2*No_of_Samples); trial=reshape(buff(1:2:2*No_of_Samples-1),1,No_of_Samples)+1; % Trial numbering starts at 1. time=reshape(buff(2:2:2*No_of_Samples),1,No_of_Samples); clear buff; end % Keep only the specified trials. if ~isempty(trialList) index=[]; for q=trialList; index=[index find(trial==q)]; end trial=trial(index); time=time(index); No_of_Samples=length(index); clear q index; end marker(k)=struct('ClassGroupId',ClassGroupId,'Name',Name,... 'Comment',Comment,'Color',Color,'Editable',Editable,'ClassId',ClassId,... 'BitNumber',BitNumber,'Polarity',Polarity,'Source',Source,'Threshold',Threshold,... 'trial',trial,'time',time); end fclose(fid); %clear k ClassGroupId Name Comment Color Editable ClassID No_of_Samples trial time; return %%%%%%%%%%%% End of readMarkerFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
lcnhappe/happe-master
sqddemo.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/sqdproject/sqddemo.m
13,633
utf_8
3e91690d3d302c08b018202387b55f3c
function sqddemo(action) % SQDDEMO; Provides a interactive demo explaining the use of sqdread and % sqdwrite functions persistent Newline; persistent Running; persistent Decoration; if ~nargin action = 'start'; end; switch lower(action) case 'init' Newline = sprintf('\n'); Running = uicontinue('Starting Demo -->'); Decoration(1:80) = '-'; Decoration = [Decoration, Newline]; case 'start' sqddemo('init'); if Running clc; txt = ['Hello', Newline,... 'Welcome to this SQD-demonstration',Newline,... 'This demo hopes to explain the use of matlab functions',Newline,... 'SQDREAD and SQDWRITE which will let you interface ',Newline,... 'MATLAB data structures with MEG160 sqd-files.',Newline,Newline,... Decoration,Newline... 'If you have any questions/suggestions, please email to:',Newline,... ' [email protected] - Shantanu Ray',Newline,Decoration,Newline]; disp(txt); end; Running = uicontinue('Next - Sqdread -->'); sqddemo('read'); Running = uicontinue('Next - Sqdwrite -->'); sqddemo('write'); disp(['End of the demo',Newline,Decoration]); case 'read' if Running clc; txt = ['Lets begin with SQDREAD',Newline,Decoration,Newline,... 'Usage :',Newline,Newline,... 'DATA = sqdread(FILENAME,''CHANNELS'',[C1 C2 C3,...],...',Newline,... ' ''SAMPLES'',[S1 SN],''FORMAT'',''double'');',Newline,... Newline,... 'SQDREAD opens the sqd-file FILENAME, reads the data for Channels ',Newline,... '[C1,C2,C3,...], Samples from S1 to SN and returns to you a matrix',Newline,... 'DATA. The format of DATA is as follows :',Newline,... 'DATA = [Chan(0)Sample(1), Chan(1)Sample(1), ... Chan(end-1)Sample(1) ;...',Newline,... ' Chan(0)Sample(2), Chan(1)Sample(2), ... . ;...',Newline,... ' . . . ;...',Newline,... ' . . . ;...',Newline,... ' Chan(0)Sample(end), Chan(1)Sample(end),... Chan(end-1)Sample(end)]',Newline,Newline,... 'SQDREAD can also return the information (INFO) regarding the Data Acquisition',Newline,... 'as a MATLAB object belonging to the class SQDHANDLE',Newline,... 'To return only the INFO: ',Newline,... ' INFO = sqdread(FILENAME,''Info'');',Newline,Newline,... 'For a quick intro into SQDHANDLE, try sqddemo(''sqdhandle'') or help sqdhandle.',Newline,Decoration,Newline ]; disp(txt); Running = uicontinue('Next - Other ways of using sqdread -->'); sqddemo('read1'); end; case 'read1' if Running clc; txt = ['Other ways of using SQDREAD are as follows: ',Newline,Decoration,Newline,... 'In the call for getting data, specification of channels, samples,',Newline,... 'format is completely optional. Hence,...',Newline,... ' DATA = sqdread(FILENAME); Returns all the data in the file',Newline,... ' DATA = sqdread(FILENAME,''Channels'',[0:9]); Returns all the data',Newline,... ' for channels from 0 to 9.',Newline,... ' DATA = sqdread(FILENAME,''Samples'',[1001 2000]); Returns data for',Newline,... ' for all channels but samples 1001 to 2000',Newline,Newline,... 'SQDREAD can be used to return DATA and INFO simultaneously',Newline,... 'ie. all of the above commands could have been called as follows:',Newline,... ' [DATA,INFO] = sqdread(FILENAME,...);',Newline,Decoration,Newline]; disp(txt); end; case 'write' if Running, clc; txt = ['Before we continue on to SQDWRITE,',Newline,... 'let us briefly look at the structure of the',Newline,... 'sqd-files.',Newline,Decoration,Newline,... 'The sqd-files generated from MEG160 contain not',Newline,... 'only the data collected but also information',Newline,... 'regarding the condition under which the',Newline,... 'experiment was conducted.',Newline,Newline,... 'Unfortunately, only part of the details of',Newline,... 'the way in which information is written to',Newline,... 'the sqd-files is known.',Newline,Newline,... 'Hence in order for MEG160 to open any ',Newline,... 'file that we create, we must insert',Newline,... 'information regarding data acquisition',Newline,... 'from an already existing sqd-file. Hence,',Newline,... 'an assumption is made that the user starts',Newline,... 'with a sqd-file from MEG160, reads the data',Newline,... 'using SQDREAD, and then having processed',Newline,... 'the data, uses SQDWRITE to write to a new',Newline,... 'file. The original sqd-file will be used as',Newline,... 'a template for the new file. SQDWRITE can',Newline,... 'also be used to directly modify the original',Newline,... 'sqd-file.',Newline,Decoration,Newline]; disp(txt); Running = uicontinue('Next - Using sqdwrite to create a new file -->'); sqddemo('write1'); Running = uicontinue('Next - sqdwrite in APPEND mode -->'); sqddemo('write2'); Running = uicontinue('Next - sqdwrite in OVERWRITE mode -->'); sqddemo('write3'); end; case 'write1' if Running, clc; txt = ['Now on to SQDWRITE: ',Newline,Decoration,Newline,... 'Usage:',Newline,Newline,... '1. To create a new sqd-file:',Newline,Decoration,Newline,... '[ERR,INFO] = sqdwrite(SOURCE,...',Newline,... ' DESTINATION,...',Newline,... ' DATA);',Newline,Newline,... ' where,',Newline,... ' SOURCE - Source sqd-file name (for template)',Newline,... ' DESTINATION - Destination sqd-file name',Newline,... ' DATA - The data to be written the destination',Newline,... ' file. Data should be arranged in matrix',Newline,... ' in the same format as the output of SQDREAD',Newline,... ' i.e. DATA = ',Newline,... ' [Chan(0)Sample(1), Chan(1)Sample(1), ... Chan(end-1)Sample(1) ;...',Newline,... ' Chan(0)Sample(2), Chan(1)Sample(2), ... . ;...',Newline,... ' . . . ;...',Newline,... ' . . . ;...',Newline,... ' Chan(0)Sample(end), Chan(1)Sample(end), ... Chan(end-1)Sample(end)]',Newline,... ' SQDWRITE gets information about number of samples',Newline,... ' from the size of DATA. Number of channels in the',Newline,... ' DATA should be equal to the Source sqd-file.',Newline,... ' ERR - Error/Confirmation count. If SQDWRITE',Newline,... ' is successful, ERR = number of bytes written',Newline,... ' to new file. If SQDWRITE is unsuccessful',Newline,... ' ERR = -1.',Newline,... ' INFO - SQDHANDLE to the new sqd-file',Newline,Decoration,Newline]; disp(txt); end; case 'write2' if Running, clc, txt = ['2. To append data:',Newline,Decoration,Newline,... '[ERR,INFO] = sqdwrite(SOURCE,DESTINATION,...',Newline,... ' ''ACTION'',''APPEND'',...',Newline,... ' ''DATA'',APPEND-DATA);',Newline,Newline,... 'In APPEND mode, SQDWRITE assumes that APPEND-DATA',Newline,... 'has data for all channels of the SOURCE FILE and ',Newline,... 'merely appens to already existing data',Newline,... 'SOURCE and DESTINTION can be the same.',Newline,... 'ERR will return the number of bytes successfully',Newline,... 'appended, whereas, INFO will have an updated',Newline,... 'number of Samples',Newline,Decoration,Newline]; disp(txt); end; case 'write3' if Running, clc txt = ['3. To overwrite data:',Newline,Decoration,Newline,... '[ERR,INFO] = sqdwrite(SOURCE,DESTINATION,...',Newline,... ' ''ACTION'',''OVERWRITE'',...',Newline,... ' ''CHANNELS'',[CH1 CH2 .. CHn],...',Newline,... ' ''SAMPLES'',[SAMP1 SAMPN],...',Newline,... ' ''DATA'',OVERWRITE-DATA);',Newline,Newline,... ' where,',Newline,... ' CHANNELS - Channel number which should be overwritten',Newline,... ' SAMPLES - Sample number which shoul be overwritten.',Newline,Newline,... 'In OVERWRITE mode, SQDWRITE writes over the data at',Newline,... 'the location specified by Channelnumber and sample ',Newline,... 'number. It returns an error if there is no data at ',Newline,... 'the specified location. If Channel number and/or Sample number',Newline,... 'are not provided, SQDWRITE assumes default values, ie',Newline,... 'ALL channels and ALL samples respectively',Newline,Decoration,Newline,... 'Still to come in SQDWRITE:',Newline,... '1. Deleting data',Newline,... '2. Deleting entire channels',Newline,... '3. Writing a file from SQDHANDLE and DATA (without template)',Newline,... Decoration,Newline]; disp(txt); end; case 'sqdhandle' if isempty(Running),sqddemo('init');end; if Running clc txt = [Decoration,'SQDHANDLE is a MATLAB class. It is used to hold',Newline,... 'various information regarding the Data Acquisition',Newline,... 'parameters used in the MEG experiment.',Newline,... 'Examples: Version and system info, amplifier gain, sensitivity',Newline,... ' Sampling Rate, data duration, channel count',Newline,... 'The different properties of sqdhandle can be viewed in the',Newline,... 'help for sqdhandle.',Newline,Newline... 'The values of these properties can be viewed by using any of the',Newline,... 'following methods :',Newline,... 'To view a PROPERTY of object A:',Newline',... ' val = A.PROPERTY; Ex. A.Version, A.version (case insensitive)',Newline,... ' val = get(A,''PROPERTY'') Ex. get(A,''Version''), get(A,''version'')',Newline,... 'To see all the properties: ',Newline,... ' get(A),disp(A),display(A) ',Newline,Newline,... 'Similarly, to set the value of any of the properties of SQDHANDLE',Newline,... ' A.PROPERTY = val; Ex. A.Version = 1;',Newline,... ' A = set(A,''PROPERTY'',val); Ex. A = set(A,''version'',1);',Newline,Newline,... ' set(A,''PROPERTY'') shows you which values the PROPERTY can take',Newline,Newline,... 'SQDHANDLE inherits from ACQPARAM and hence the properties of ',Newline,... 'ACQPARAM are also encapsulated in SQDHANDLE',Newline,Decoration]; disp(txt); end; end; function running = uicontinue(key) newline = sprintf('\n'); valid = 0; if ~nargin,key = '';end; while ~valid, disp([key,newline]); w = input('Press Enter to continue or Q to quit ','s'); if isempty(w) valid = 1; running = 1; elseif strncmpi(w,'q',1) valid = 1; running = 0; end; end;
github
lcnhappe/happe-master
get.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/sqdproject/@chanhandle/get.m
6,405
utf_8
72519eea5ca24f660f7729d2725a9efb
function out = get(t,varargin) % GET Get object properties. % out = GET(t,'PropertyName') returns the value of the specified % property for the object t. If t is a vector of handles, then % get will return an M-by-1 cell array of values where M is equal % to length(t). If 'PropertyName' is replaced by a 1-by-N or N-by-1 % cell array of strings containing property names, then GET will % return an M-by-N cell array of values. % % GET(t) displays all property names and values if nargin<1, error('first argument must be acqparam object') end; if isa(t,'chanhandle') fields = fieldnames(t.handle(1)); % get list of fields switch nargin case 1 % display of all properties of object for i = 1:length(t.handle) disp([ '%%% Properties of chanhandle #' num2str(i)]); for j = 1:length(fields) dispfield(t.handle(i),fields{j}); end; end; case 2 % Return the value of only the specified property if isnumeric(varargin{1}) % Ex. get(t(channel_nums)) % argin = channel number if min(varargin{1})>0 & ... % check if channel number is valid max(varargin{1})<=length(t.handle) &... (round(varargin{1})==varargin{1}) chlist = varargin{1}; out = chanhandle(t.handle(chlist(1))); for chi = 2:length(chlist) out = [out;chanhandle(t.handle(chlist(chi)))]; end else error('Channel number out of bounds'); end; elseif ischar(varargin{1}) % Ex. get(t,'field') % argin = 'field' prop = varargin{1}; if strcmpi(prop,'NumChannels') % If Prop = NumChannels out = length(t.handle); return; end; if ischar(prop), % Check to see if the Property is valid testval = getsfield(t.handle(1),prop); if isnumeric(testval) % If O/p value is numeric then simple array for i = 1:length(t.handle) out(i,:) = getsfield(t.handle(i),prop); end; elseif ischar(testval) % Elseif O/p value is string than cell array for i = 1:length(t.handle) out{i} = getsfield(t.handle(i),prop); end; end; end; end; case 3 %Ex. get(t,channel_nums,field) if min(varargin{1})>0 & ... max(varargin{1})<=length(t.handle) &... (round(varargin{1})==varargin{1}) chnum = varargin{1}; else error('Channel number out of bounds'); end; prop = varargin{2}; if ischar(prop), testval = getsfield(t.handle(chnum(1)),prop); if isnumeric(testval) for i = 1:length(chnum) out(i,:) = getsfield(t.handle(chnum(i)),prop); end; elseif ischar(testval) for i = 1:length(chnum) out{i} = getsfield(t.handle(chnum(i)),prop); end; end; end; end; end; function stdout = dispfield(t,prop) % DISPFIELD gets field value depending on field. Takes care of special % situtations like for private fields, sensitivity and amplifier settings % and acquisition parameters % val = dispfield(t,prop) if strcmpi(prop,'Sensitivity') % Sensitivity field is not transparent ot user. The properties % of Sensitivity are displayed as Senstivity.field stdout = sprintf('%s : %3.3f\n%s : %3.3f',... 'Sensitivity.Gains',t.Sensitivity.Gains,... 'Sensitivity.Offsets',t.Sensitivity.Offsets); elseif strcmpi(prop,'SensorInfo') % SensorInfo field is not transparent ot user. The properties % of SensorInfo are displayed as SensorInfo.field if max(strcmpi({'trigger','EEG','ECG','etc','NULL'},t.SensorInfo.type)) stdout = sprintf('%s : %s\n%s : %s\n%s : %d',... 'SensorInfo.Type',t.SensorInfo.type,... 'SensorInfo.ChanName',t.SensorInfo.channame,... 'SensorInfo.IdentNum',t.SensorInfo.identnum); else taglist = fieldnames(t.SensorInfo); stdout = sprintf('%s : %s\n','SensorInfo.Type',t.SensorInfo.type); taglist(find(strcmpi(taglist(:),'type'))) = []; for i = 1:length(taglist) stdout = [stdout,sprintf('%s : %3.3f\n',['SensorInfo.' taglist{i}],... eval(['t.SensorInfo.' taglist{i}]))]; end; end; elseif strcmpi(prop,'Private') % If private, display nothing return; else % For all other properties val = getsfield(t,prop); val = val'; if ischar(val), stdout = sprintf('%s : %s',prop,val); elseif max(val-floor(val))>0 stdout = sprintf('%s : %s',prop,sprintf('%10.3f',val(:))); else stdout = sprintf('%s : %s',prop,sprintf('%d',val(:))); end; end; disp(stdout); function out = getsfield(t,prop) % GETSFIELD gets field value depending on field. Takes care of special % situtations like for Sensitivity and SensorInfo % val = getfield(t.handle,prop) out = []; % init out fields = fieldnames(t); % Fields of substructure "handle" subsindx = findstr(prop,'.'); if ~isempty(subsindx) % if subfield of Sensitivity/SensorInfo subtag = prop(1:subsindx-1); % Get main field (Sensitivity/SensorInfo) subsubs = prop(subsindx+1:end); % Get subfield ntag = find(strcmpi(fields(:),subtag)); if ~isempty(ntag), % If valid mainfield subtagstruct = getfield(t,fields{ntag}); % get structure of mainfield substags = fieldnames(subtagstruct); nsubs = find(strcmpi(substags(:),subsubs)); if ~isempty(nsubs), % If valid subfield out = getfield(subtagstruct,substags{nsubs}); end; end; else % If main field n = find(strcmpi(fields(:),prop)); if ~isempty(n), out = getfield(t,fields{n}); end; end; if isempty(out) error('sorry - couldnt obtain channel info - please check input parameters'); end;
github
lcnhappe/happe-master
chanhandle.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/sqdproject/@chanhandle/chanhandle.m
3,739
utf_8
d43b79acd008d1094f4aabd77746e71b
function t = chanhandle(varargin) % T = CHANHANDLE; Constructor for class CHANHANDLE % Chanhandle class contains channel-specific information only. % An object belonging to chanhandle has the following properties: % ChannelNumber % Sensitivity % SensorInfo % Usage: % t = chanhandle; Default values % t = chanhandle(t1); where t1 is a chanhandle % t = chanhandle(fname,channelnum); where fname is name of the sqd file % See also, % @chanhandle/get.m,set.m,writechanloc.m % Note: % Object structure: % Chanhandle can be a handle to only one channel, or several channels. % To accomodate an object array, the object is structured as follows: % Chanhandle_obj has only one field - "handle". Subfields of "handle" are % the above named properties. ie % ChanHandle_Obj -> % handle -> % ChannelNumber % Sensitivity % SensorInfo % When the ChanHandle_obj contains several channels, "handle" is an array of % structures. % % Also, note that: % The ChannelNumber subfield indicates the hardware channel number. Whereas, the % index of handle is software index to it. The index of handle is monotonically % increasing from 1. So Chanhandle_obj contains HwChannels = 0,1,3 % then handle(1) -> HwChannel = 0 % handle(2) -> HwChannel = 1 % handle(3) -> HwChannel = 3 % ChanHandle_obj is be indexed as the "handle" substructure. % % For internal use only, an additional way of initialising object: % t = chanhandle(handle); where "handle" is a structure with the channel's info % Fields for "handle": ChannelNumber,Sensitivity,SensorInfo % initialize the fields of the object to default values t.handle.ChannelNumber = 0; % hardware channel number (0-191) t.handle.Sensitivity = [];% Sensitivity Gain/Offset t.handle.SensorInfo = [];% type,position,size,etc. of sensor % Define class definition t = class(t,'chanhandle'); switch nargin case 0 % Default object, return case 1 if isa(varargin{1},'chanhandle'), % if argin = chanhandle_obj t = varargin{1}; elseif ischar(varargin{1}) % if argin = sqd-filename fname = varargin{1}; t.handle = readsqdinfo(t.handle,varargin{1}); elseif isstruct(varargin{1}) % if argin = "handle" substructure t.handle = varargin{1}; else error('Incorrect input to chanhandle.m'); end; case 2 % if argin = sqd-filename,channelnumber if ischar(varargin{1})&isnumeric(varargin{2}) for i = 1:length(varargin{2}) t.handle(i).ChannelNumber = varargin{2}(i); if ~isempty(varargin{1}) % In case no file name is passed - default values t.handle(i) = readsqdinfo(t.handle(i),varargin{1}); end; end; else error('Incorrect inputs to chanhandle.m'); end; otherwise error('Incorrect inputs to chanhandle.m'); end; function t = readsqdinfo(t,fname) % T = READSQDINFO(T,FNAME); Update values of CHANHANDLE object 'T' % to those given in sqd-file FNAME seekset=-1; % Start point for fseek: -1 => beginning of the file if nargin<2|~ischar(fname),error('Incorrect arguments');end; % open file as binary and little endian fid = fopen(fname,'rb','l'); if fid==-1, disp('File not found'); [f,p] = uigetfile('*.sqd','MEG160 files'); if ((~isstr(f)) | ~min(size(f))), t = []; return; end; fname = [p f]; t.FileName = [p f]; fid = fopen(fname,'rb','l'); end; %Read in info regarding sensitivity of sensors t.Sensitivity = sensitivityinfo(fid,seekset,t.ChannelNumber); % Read in sensor location t.SensorInfo = sensorinfo(fid,seekset,t.ChannelNumber); % Close file fclose(fid);
github
lcnhappe/happe-master
get.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/sqdproject/@sqdhandle/get.m
3,777
utf_8
ee256890517a8c295444d2cc58ed54cd
function out = get(t,prop) % GET Get object properties. % out = GET(t,'PropertyName') returns the value of the specified % property for the object t. If t is a vector of handles, then % get will return an M-by-1 cell array of values where M is equal % to length(t). If 'PropertyName' is replaced by a 1-by-N or N-by-1 % cell array of strings containing property names, then GET will % return an M-by-N cell array of values. % % GET(t) displays all property names and values if nargin<1, error('first argument must be acqparam object') end; if isa(t,'sqdhandle') fields = fieldnames(t); % get fields of object switch nargin case 1 % Display all properties for j = 1:length(fields) dispfield(t,fields{j}); end; case 2 % return specified property out = []; if ischar(prop), out = getsfield(t,prop); elseif iscell(prop) for j = 1:length(prop) out{j} = getsfield(t,prop{j}); end; end; end; end; function stdout = dispfield(t,prop) % DISPFIELD gets field value depending on field. Takes care of special % situtations like for private fields, sensitivity and amplifier settings % and acquisition parameters % val = dispfield(t,prop) if strcmpi(prop,'acqparam') get(t.acqparam); stdout = ''; elseif strcmpi(prop,'Channels') % For Channels, just display [1xChannelNumer] array of chanhandle objects stdout = sprintf('%s : %s','Channels',... ['[1x' num2str(get(t,'ChannelCount')) '] Channel array']); elseif strcmpi(prop,'PatientInfo') % For patient info, just display Name of the patient person stdout = sprintf('%s : %s','PatientInfo',... t.PatientInfo.name); elseif strcmpi(prop,'Amplifier') % The field Amplifier is transparent ot the user. Directly display % the inputgain and output gain stdout = sprintf('%s : %d\n%s : %d',... 'InputGain',t.Amplifier.InputGain,... 'OutputGain',t.Amplifier.OutputGain); elseif strcmpi(prop,'FileName') % Display filename without path [pathstr,fname] = fileparts(t.FileName); stdout = sprintf('%s : %s','FileName',fname); elseif strcmpi(prop,'Private') % if private return; % show nothing else % For all otherproperties val = getsfield(t,prop); val = val'; if ischar(val), stdout = sprintf('%s : %s',prop,val); elseif max(val-floor(val))>0 stdout = sprintf('%s : %s',prop,sprintf('%10.3f',val(:))); else stdout = sprintf('%s : %s',prop,sprintf('%d',val(:))); end; end; disp(stdout); function out = getsfield(t,prop) % GETSFIELD gets field value depending on field. Takes care of special % situtations like for patientinfo,amplifier settings, % and acquisition parameters % val = getfield(t,prop) out = []; taglist = fieldnames(struct(t)); % List of fields if strcmpi(prop,'InputGain') % if Amplifier.InputGain out = t.Amplifier.InputGain; elseif strcmpi(prop,'OutputGain') % if Amplifier.OutputGain out = t.Amplifier.OutputGain; elseif strcmpi(prop,'SensitivityGain') sensinfo = sensitivityinfo(t.FileName); out = sensinfo.Gains; else % for others n = find(strcmpi(taglist(:),prop)); if ~isempty(n), % If main field out = getfield(struct(t),taglist{n}); else % if patient info patinfolist = fieldnames(t.PatientInfo); subindx = find(strcmpi(patinfolist(:),prop)); if ~subindx out = getfield(t.PatientInfo,patinfolist{subindx}); else % if property of acqparam out = get(t.acqparam,prop); end; end; end;
github
lcnhappe/happe-master
putdata.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/sqdproject/@sqdhandle/putdata.m
10,726
utf_8
59ea137b693298211a264bf05305767f
function err = putdata(t,filename,varargin) % ERR = PUTDATA(SQDHANDLE,FILENAME,'DATA',channeldata); % Writes new Channel Data to .sqd file given by 'filename'. The template % (Acquisition and Setup Information) is chosen from SQDHANDLE. It assumes % that the channeldata is in a format (shown below) and appropriately modifies % the information regarding the data written to the sqd-file. It returns ERR % which is the number of values successfully written. It returns -1 if % there hs been a complete failure. INFO is the sqdhandle to the new % sqd-file. % Assumption: Data is given for all 192 channels. % % Usage: % err = putdata(t,filename,'Data',data); % Write new data to sqd-file. Data should be arranged as following: % |Chan(0)Sample(1) Chan(1)Sample(1) ... Chan(end)Sample(1) | % |Chan(0)Sample(2) Chan(1)Sample(2) ... . | % | . . . | % | . . . | % |Chan(0)Sample(end) Chan(1)Sample(end) ... Chan(end)Sample(end)| % PUTDATA will take the channel and sample assignments from the data % entered. % % err = putdata(t,filename,... % 'ACTION',<'Append','Overwrite'>,... % 'CHANNELS',[CH1 CH2 .. CHn],... % 'SAMPLES',[SAMP1 SAMPN],... % 'DATA',data); % Write data to an already existing sqd-file. You may specify the Action % to be 'Append' or 'Overwrite'. % APPEND merely appends to an existing file. It assumes the data is in the above % format (Samplenum,Channelnum).The input arguments - 'CHANNELS' and % 'SAMPLES' will be ignored. % OVERWRITE requires destination file to already exist. It writes the raw data % writes over the data at the location specified by Channelnumber and % sample number. It returns an error if there is no data at the specified % location. If neither Channelnumber nor Samplesnumber is specified, it % is assumed that overwrite will take place for entire existing data. % Similar logic applies if only ChannelNumber or only Samplenumber is % specified. % % See also, % sqdhandle/getdata,sqdhandle,get,set % To be included in the coming versions: % #Action - INSERT allows you to insert data into an already existing sqdfile. You % must specify the location of insertion by specifying 'Samples' % #Variable numebr of channels instead of assuming all 192 channels. if nargin<4 error('Atleast 4 arguments required'); end; if ~isa(t,'sqdhandle') error('First argument must belong to class - sqdhandle'); end; if rem(nargin-2,2) error('Property and range must come in pairs'); end; err = 0; rawoffset = get(t,'RawOffset'); % Initialize default values for actions: action = 'append'; format = get(t,'Datatype'); switch lower(format) case 'int16' numbytes = 16/8; case 'double' numbytes = 64/8; end; if ~rem(nargin-2,2)&fix((nargin-2)/2) inargs = varargin; while length(inargs)>=2 prop = inargs{1}; range = inargs{2}; inargs = inargs(3:end); switch lower(prop) case 'channels' channels = sort(range); case 'samples' samples = sort(range); if length(samples)>2 error('Sorry - Please input only start and stop of the range') end; if (samples<=0) error('Value of Sample-Range must be >0'); end; case 'data' data = range; case 'action' action = lower(range); otherwise error('Sorry - Incorrect Property used'); end; end; end; if ~exist(filename,'file') fid = fopen(get(t,'FileName'),'rb','l');% Open sqd-read-file to obtain template if (fid==-1) disp('Error opening files'); err = -1; return; end; template = fread(fid,rawoffset,'uchar'); % Read in template as bytes fclose(fid); fid = fopen(filename,'w','l'); err = fwrite(fid,template,'uchar'); % Write template to file fclose(fid); fid = fopen(filename,'r+','l'); updateinfo(t,fid,0); fclose(fid); end; % Switch on action: switch action case 'append' rawdata = convert2raw(t,data,format); fid = fopen(filename,'a+','l'); [samplenum,channum] = size(data); % Get number of chanels to be added err = err+fwrite(fid,rawdata,format); % Write data and update output err fclose(fid); fid = fopen(filename,'r+','l'); updateinfo(t,fid,samplenum); % update info in file fclose(fid); case 'insert' disp('sorry cant do it yet'); return; case 'overwrite' fid = fopen(filename,'r','l'); % fid = fopen(filename,'r'); % Do checks so that size of data in the file, size of input data and % value of input arguments are in agreement % 1. Check for data present in file fseek(fid,0,1); % Go to end of the file if ftell(fid)<rawoffset % If new sqd-file error('No data exists in sqd-file - cannot overwrite'); end; fclose(fid); [numsamples,numchannels] = size(data); numsamplesold = get(t,'SamplesAvailable'); channelcount = get(t,'ChannelCount'); if ~exist('samples','var') samples = [1,numsamplesold]; % Default for number of samples end; if ~exist('channels','var') channels = 0:channelcount-1; % Default for number of channels end; numsamples1 = samples(2)-samples(1)+1; numchannels1 = length(channels); % 2. Check for input arguments agreeing with each other if (numsamples~=numsamples1)|(numchannels~=numchannels1), disp('Error: Number of channels and number of samples given in rawdata'); disp(' doesnot match those given as input arguments.'); disp(' Check if input data has been given in the right format'); error('quiting'); end; % 3. Check if overwrite is legal ie there is enough data in file to % overwrite. if (numsamples>numsamplesold)|(numchannels>channelcount), error('Not enough data in file to overwrite'); end; % End of checks % Convert to raw rawdata = convert2raw(t,data,format,channels); % Open file in overwrite mode [fid,message] = fopen(filename,'r+','l'); % [fid,message] = fopen(filename,'r+'); % Begin writing data if (numsamples == numsamplesold) & (numchannels == channelcount) fseek(fid,rawoffset,-1); err = err+fwrite(fid,rawdata,format); % changing conditions here 11/20/08 dbhertz jzsimon % If all channels elseif (length(channels)==channelcount) offset = channelcount*(samples(1)-1)*numbytes; fseek(fid, rawoffset+offset,-1); err = err+fwrite(fid,... % File ID rawdata,... % DATA [num2str(numchannels) '*' format]); % PRECISION elseif (channels(2:end)-channels(1:end-1))==ones(1,numchannels-1) % If contiguous channels offset = (channels(1)+channelcount*(samples(1)-1))*numbytes-... (channelcount - channels(end))*numbytes; fseek(fid,rawoffset+offset,-1); err = err+fwrite(fid,... % File ID rawdata,... % DATA [num2str(numchannels) '*' format],... % PRECISION (channelcount - channels(end)+channels(1)-1)*numbytes); % SKIP else % If non-contiguous channels disp('Error: Channels must be contiguous'); disp(' Please try again.'); error('quiting'); % for i = 1:length(channels) % chan_offset = channels(i); % sample_offset = channelcount*(samples(1)-1); % fseek(fid,rawoffset+(sample_offset+chan_offset)*numbytes-(channelcount-1)*numbytes,-1); % err = err + fwrite(fid,... % FILE ID % rawdata(:,i),... % DATA % format,... % PRECISION % (channelcount-1)*numbytes); % SKIP % end; end; fclose(fid); end; % fclose('all'); return; function rawdata = convert2raw(t,data,format,channels) % % Converts data from 'double' to format % switch format % case 'double' % gain = get(t,'SensitivityGains'); % if nargin<4, % channels = 1:get(t,'ChannelCount'); % end; % gain = gain(channels)'; % inversegain = (ones(size(gain))./gain); % convfactor = ones(size(data,1),1)*inversegain*(2^12)/50; % rawdata = data'; % rawdata = rawdata'; % rawdata = rawdata(:); % case {'int16','short'} persistent FileName; persistent Gain; if nargin<4, channels = [1:get(t,'ChannelCount')]-1; end; % %gain = get(t.Channels,channels+1,'Sensitivity.Gain'); %gain = gain'; % if isempty(FileName) FileName = 'new'; end; if isempty(Gain)|(~strcmp(FileName,t.FileName)) Gain = get(t,'SensitivityGain'); end; chgain = Gain(channels+1); % ampgain = get(t,'OutputGain')/get(t,'InputGain'); % inversegain = (ones(size(chgain))./chgain); % convfactor = ones(size(data,1),1)*inversegain*(2^12)/ampgain; ampgain = get(t,'OutputGain')*get(t,'InputGain'); inversegain = (ones(size(chgain))./chgain); % see comments in getdata.m for what these different factors mean: convfactor = ones(size(data,1),1)*ampgain*inversegain*(2^12)/10; % convfactor = ones(size(data,1),1)*10/(2^12)*gain/ampgain; rawdata = convfactor.*data; rawdata = rawdata'; rawdata = rawdata(:); function [err,t] = updateinfo(t,fid,samplenum) % Updates information regarding sample number % fseek to appropriate location SEEK_SET = -1; fseek( fid, 128, SEEK_SET ); acq_offset = fread(fid,1,'long'); fseek( fid, acq_offset+(32+64)/8, SEEK_SET ); switch get(t,'AcquisitionType') case 1 % Read acquisition parameters fseek(fid,(32/8),0); if ~samplenum err = fwrite(fid,round(samplenum),'long'); else samplenum = samplenum + fread(fid,1,'long'); fseek(fid,-(32/8),0); err = fwrite(fid,round(samplenum),'long'); end; t = set(t,'ActSamplesAcquired',round(samplenum)); t = set(t,'SamplesAcquired',round(samplenum)); case {2,3} % Read acquisition parameters if ~samplenum err = fwrite(fid,round(samplenum),'long'); else samplenum = samplenum + fread(fid,1,'long'); fseek(fid,-(32/8),0); err = fwrite(fid,round(samplenum),'long'); end; t = set(t,'FrameLength',round(samplenum)); end; return;
github
lcnhappe/happe-master
get.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/sqdproject/@acqparam/get.m
3,525
utf_8
c36be430c00919d46ee5184a3794613e
function out = get(t,prop) % GET(T,PROP) Get object properties. % out = GET(t,'PropertyName') returns the value of the specified % property for the object t. If t is a vector of handles, then % get will return an M-by-1 cell array of values where M is equal % to length(t). If 'PropertyName' is replaced by a 1-by-N or N-by-1 % cell array of strings containing property names, then GET will % return an M-by-N cell array of values. % % GET(t) displays all property names and values if nargin<1, error('first argument must be acqparam object'); end; if ~isa(t,'acqparam') error('first argument must be acqparam object'); else taglist = fieldnames(struct(t)); % Get list of fields of object switch nargin case 1 % If just asking for a regular display of all properties for j = 1:length(taglist) dispfield(t,taglist{j}); end; case 2 % If asking to return value of specific properties if ischar(prop), out = getsfield(t,prop); elseif iscell(prop) for j = 1:length(prop) out{j} = getsfield(t,prop{j}); end; end; end; end; function stdout = dispfield(t,prop) % DISPFIELD gets field value depending on field. Takes care of special % situtations like for private fields, sensitivity and amplifier settings % and acquisition parameters % val = dispfield(t,prop) % To Display SampleInfo: % The field SampleInfo is transparent to the user % The user is shown directly the contents of SampleInfo sampinfotaglist = fieldnames(t.SampleInfo); % get list of fields of SampleINfo if strcmpi(prop,'SampleInfo') % To display whole of SampleInfo stdout = ''; % Init output for i = 1:length(sampinfotaglist) stdout = [stdout,... % show fields of SampleInfo sprintf('%s : %d\n',sampinfotaglist{i},... getfield(t.SampleInfo,sampinfotaglist{i}))]; end; elseif find(strcmpi(sampinfotaglist(:),prop))% To display specific property % of SampleInfo indx = find(strcmpi(sampinfotaglist(:),prop)); stdout = sprintf('%s : %d\n',sampinfotaglist{indx},... getfield(t.SampleInfo,sampinfotaglist{indx})); elseif strcmpi(prop,'Private') % If private property stdout = ''; % show nothing else % For all other properties val = getsfield(t,prop); val = val'; if ischar(val), stdout = sprintf('%s : %s',prop,val); elseif max(val-floor(val))>0 stdout = sprintf('%s : %s',prop,sprintf('%10.3f',val(:))); else stdout = sprintf('%s : %s',prop,sprintf('%d',val(:))); end; end; disp(stdout); function out = getsfield(t,prop) % GETSFIELD gets field value depending on field. Takes care of special % situtations like for SampleInfo % val = getsfield(t,prop) taglist = fieldnames(struct(t)); % Get regular fields of object sampinfotaglist = fieldnames(t.SampleInfo); % Get fields of SampleInfo if find(strcmpi(taglist(:),prop)) % If regular field indx = find(strcmpi(taglist(:),prop)); out = getfield(struct(t),taglist{indx});% see builtin getfield for structure elseif find(strcmpi(sampinfotaglist(:),prop))% Is SampleInfo field indx = find(strcmpi(sampinfotaglist(:),prop)); out = getfield(t.SampleInfo,sampinfotaglist{indx}); end;
github
lcnhappe/happe-master
nansum.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/src/nansum.m
194
utf_8
d26aaa8d5695a2cd15c51e72c3d4a186
% NANSUM provides a replacement for MATLAB's nanmean. % % For usage see SUM. function y = nansum(x, dim) x(isnan(x)) = 0; if nargin==1 y = sum(x); else y = sum(x,dim); end end % function
github
lcnhappe/happe-master
nanstd.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/src/nanstd.m
248
utf_8
fa0dc38960ab4c502a685ee11ebb3328
% NANSTD provides a replacement for MATLAB's nanstd that is almost % compatible. % % For usage see STD. Note that the three-argument call with FLAG is not % supported. function Y = nanstd(varargin) Y = sqrt(nanvar(varargin{:})); end % function
github
lcnhappe/happe-master
nanmean.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/src/nanmean.m
245
utf_8
8ab56ab826c1e69fd89a8937baae4bf0
% NANMEAN provides a replacement for MATLAB's nanmean. % % For usage see MEAN. function y = nanmean(x, dim) if nargin<2 N = sum(~isnan(x)); y = nansum(x) ./ N; else N = sum(~isnan(x), dim); y = nansum(x, dim) ./ N; end end % function
github
lcnhappe/happe-master
ft_connectivity_corr.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/connectivity/ft_connectivity_corr.m
8,589
utf_8
65aed98bf500c7a9cfb427092834352e
function [c, v, outcnt] = ft_connectivity_corr(input, varargin) % FT_CONNECTIVITY_CORR computes correlation, coherence or a related % quantity from a data-matrix containing a covariance or cross-spectral % density. % % Use as % [c, v, n] = ft_connectivity_corr(input, varargin) % % The input data input should be an array organized as: % Repetitions x Channel x Channel (x Frequency) (x Time) % or % Repetitions x Channelcombination (x Frequency) (x Time) % % If the input already contains an average, the first dimension should be % singleton. Furthermore, the input data can be complex-valued cross % spectral densities, or real-valued covariance estimates. If the former is % the case, the output will be coherence (or a derived metric), if the % latter is the case, the output will be the correlation coefficient. % % Additional input arguments come as key-value pairs: % % hasjack = 0 or 1 specifying whether the Repetitions represent % leave-one-out samples % complex = 'abs', 'angle', 'real', 'imag', 'complex', 'logabs' for % post-processing of coherency % feedback = 'none', 'text', 'textbar' type of feedback showing progress of % computation % dimord = specifying how the input matrix should be interpreted % powindx = required if the input data contain linearly indexed % channel pairs. should be an Nx2 matrix indexing on each % row for the respective channel pair the indices of the % corresponding auto-spectra % pownorm = flag that specifies whether normalisation with the % product of the power should be performed (thus should % be true when correlation/coherence is requested, and % false when covariance or cross-spectral density is % requested). % % Partialisation can be performed when the input data is (chan x chan). The % following options need to be specified: % % pchanindx = index-vector to the channels that need to be % partialised % allchanindx = index-vector to all channels that are used % (including the "to-be-partialised" ones). % % The output c contains the correlation/coherence, v is a variance estimate % which only can be computed if the data contains leave-one-out samples, % and n is the number of repetitions in the input data. % % It implements the methods as described in the following papers: % % Coherence: Rosenberg et al, The Fourier approach to the identification of % functional coupling between neuronal spike trains. Prog Biophys Molec % Biol 1989; 53; 1-31 % % Partial coherence: Rosenberg et al, Identification of patterns of % neuronal connectivity - partial spectra, partial coherence, and neuronal % interactions. J. Neurosci. Methods, 1998; 83; 57-72 % % Phase locking value: Lachaux et al, Measuring phase sychrony in brain % signals. Human Brain Mapping, 1999; 8; 194-208. % % Imaginary part of coherency: Nolte et al, Identifying true brain % interaction from EEG data using the imaginary part of coherence. Clinical % Neurophysiology, 2004; 115; 2292-2307 % % See also FT_CONNECTIVITYANALYSIS % Copyright (C) 2009-2010 Donders Institute, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % 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$ % FiXME: If output is angle, then jack-knifing should be done % differently since it is a circular variable hasjack = ft_getopt(varargin, 'hasjack', 0); cmplx = ft_getopt(varargin, 'complex', 'abs'); feedback = ft_getopt(varargin, 'feedback', 'none'); dimord = ft_getopt(varargin, 'dimord'); powindx = ft_getopt(varargin, 'powindx'); pownorm = ft_getopt(varargin, 'pownorm', 0); pchanindx = ft_getopt(varargin, 'pchanindx'); allchanindx = ft_getopt(varargin, 'allchanindx'); if isempty(dimord) error('input parameters should contain a dimord'); end siz = [size(input) 1]; % do partialisation if necessary if ~isempty(pchanindx), % partial spectra are computed as in Rosenberg JR et al (1998) J.Neuroscience Methods, equation 38 chan = allchanindx; nchan = numel(chan); pchan = pchanindx; npchan = numel(pchan); newsiz = siz; newsiz(2:3) = numel(chan); % size of partialised csd A = zeros(newsiz); % FIXME this only works for data without time dimension if numel(siz)==5 && siz(5)>1, error('this only works for data without time'); end for j = 1:siz(1) %rpt loop AA = reshape(input(j, chan, chan, : ), [nchan nchan siz(4:end)]); AB = reshape(input(j, chan, pchan,: ), [nchan npchan siz(4:end)]); BA = reshape(input(j, pchan, chan, : ), [npchan nchan siz(4:end)]); BB = reshape(input(j, pchan, pchan, :), [npchan npchan siz(4:end)]); for k = 1:siz(4) %freq loop %A(j,:,:,k) = AA(:,:,k) - AB(:,:,k)*pinv(BB(:,:,k))*BA(:,:,k); A(j,:,:,k) = AA(:,:,k) - AB(:,:,k)/(BB(:,:,k))*BA(:,:,k); end end input = A; siz = size(input); else % do nothing end % compute the metric if (length(strfind(dimord, 'chan'))~=2 || ~isempty(strfind(dimord, 'pos'))) && ~isempty(powindx), % crossterms are not described with chan_chan_therest, but are linearly indexed outsum = zeros(siz(2:end)); outssq = zeros(siz(2:end)); outcnt = zeros(siz(2:end)); ft_progress('init', feedback, 'computing metric...'); for j = 1:siz(1) ft_progress(j/siz(1), 'computing metric for replicate %d from %d\n', j, siz(1)); if pownorm p1 = reshape(input(j,powindx(:,1),:,:,:), siz(2:end)); p2 = reshape(input(j,powindx(:,2),:,:,:), siz(2:end)); denom = sqrt(p1.*p2); clear p1 p2 else denom = 1; end tmp = complexeval(reshape(input(j,:,:,:,:), siz(2:end))./denom, cmplx); outsum = outsum + tmp; outssq = outssq + tmp.^2; outcnt = outcnt + double(~isnan(tmp)); end ft_progress('close'); elseif length(strfind(dimord, 'chan'))==2 || length(strfind(dimord, 'pos'))==2, % crossterms are described by chan_chan_therest outsum = zeros(siz(2:end)); outssq = zeros(siz(2:end)); outcnt = zeros(siz(2:end)); ft_progress('init', feedback, 'computing metric...'); for j = 1:siz(1) ft_progress(j/siz(1), 'computing metric for replicate %d from %d\n', j, siz(1)); if pownorm p1 = zeros([siz(2) 1 siz(4:end)]); p2 = zeros([1 siz(3) siz(4:end)]); for k = 1:siz(2) p1(k,1,:,:,:,:) = input(j,k,k,:,:,:,:); p2(1,k,:,:,:,:) = input(j,k,k,:,:,:,:); end p1 = p1(:,ones(1,siz(3)),:,:,:,:); p2 = p2(ones(1,siz(2)),:,:,:,:,:); denom = sqrt(p1.*p2); clear p1 p2; else denom = 1; end tmp = complexeval(reshape(input(j,:,:,:,:,:,:), siz(2:end))./denom, cmplx); % added this for nan support marvin %tmp(isnan(tmp)) = 0; % added for nan support outsum = outsum + tmp; outssq = outssq + tmp.^2; outcnt = outcnt + double(~isnan(tmp)); end ft_progress('close'); end n = siz(1); if all(outcnt(:)==n) outcnt = n; end %n1 = shiftdim(sum(~isnan(input),1),1); %c = outsum./n1; % added this for nan support marvin c = outsum./outcnt; % correct the variance estimate for the under-estimation introduced by the jackknifing if n>1, if hasjack %bias = (n1-1).^2; % added this for nan support marvin bias = (outcnt-1).^2; else bias = 1; end %v = bias.*(outssq - (outsum.^2)./n1)./(n1 - 1); % added this for nan support marvin v = bias.*(outssq - (outsum.^2)./outcnt)./(outcnt-1); else v = []; end function [c] = complexeval(c, str) switch str case 'complex' %do nothing case 'abs' c = abs(c); case 'angle' c = angle(c); % negative angle means first row leads second row case 'imag' c = imag(c); case 'absimag' c = abs(imag(c)); case 'real' c = real(c); case '-logabs' c = -log(1 - abs(c).^2); otherwise error('complex = ''%s'' not supported', str); end
github
lcnhappe/happe-master
ft_connectivity_psi.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/connectivity/ft_connectivity_psi.m
5,649
utf_8
db9ca445aeb3e9dc93fc82e65fdc4335
function [c, v, n] = ft_connectivity_psi(input, varargin) % FT_CONNECTIVITY_PSI computes the phase slope index from a data-matrix % containing the cross-spectral density. It implements the method described % in: Nolte et al., Robustly estimating the flow direction of information % in complex physical systems. Physical Review Letters, 2008; 100; 234101. % % Use as % [c, v, n] = ft_connectivity_psi(input, varargin) % % The input data input should be organized as: % % Repetitions x Channel x Channel (x Frequency) (x Time) % % or % % Repetitions x Channelcombination (x Frequency) (x Time) % % The first dimension should be singleton if the input already contains an % average % % Additional input arguments come as key-value pairs: % % nbin = scalar, half-bandwidth parameter: the number of frequency bins % across which to integrate % hasjack = 0 or 1, specifying whether the repetitions represent % leave-one-out samples (allowing for a variance estimate) % feedback = 'none', 'text', 'textbar' type of feedback showing progress of % computation % dimord = string, specifying how the input matrix should be interpreted % powindx % normalize % % The output p contains the phase slope index, v is a variance estimate % which only can be computed if the data contains leave-one-out samples, % and n is the number of repetitions in the input data. If the phase slope % index is positive, then the first chan (1st dim) becomes more lagged (or % less leading) with higher frequency, indicating that it is causally % driven by the second channel (2nd dim) % % See also FT_CONNECTIVITYANALYSIS % Copyright (C) 2009-2010 Donders Institute, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % 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$ % FIXME: interpretation of the slope hasjack = ft_getopt(varargin, 'hasjack', 0); feedback = ft_getopt(varargin, 'feedback', 'none'); dimord = ft_getopt(varargin, 'dimord'); powindx = ft_getopt(varargin, 'powindx'); normalize = ft_getopt(varargin, 'normalize', 'no'); nbin = ft_getopt(varargin, 'nbin'); if isempty(dimord) error('input parameters should contain a dimord'); end if (length(strfind(dimord, 'chan'))~=2 || ~isempty(strfind(dimord, 'pos'))>0) && ~isempty(powindx), %crossterms are not described with chan_chan_therest, but are linearly indexed siz = size(input); outsum = zeros(siz(2:end)); outssq = zeros(siz(2:end)); pvec = [2 setdiff(1:numel(siz),2)]; ft_progress('init', feedback, 'computing metric...'); %first compute coherency and then phaseslopeindex for j = 1:siz(1) ft_progress(j/siz(1), 'computing metric for replicate %d from %d\n', j, siz(1)); c = reshape(input(j,:,:,:,:), siz(2:end)); p1 = abs(reshape(input(j,powindx(:,1),:,:,:), siz(2:end))); p2 = abs(reshape(input(j,powindx(:,2),:,:,:), siz(2:end))); p = ipermute(phaseslope(permute(c./sqrt(p1.*p2), pvec), nbin, normalize), pvec); outsum = outsum + p; outssq = outssq + p.^2; end ft_progress('close'); elseif length(strfind(dimord, 'chan'))==2 || length(strfind(dimord, 'pos'))==2, %crossterms are described by chan_chan_therest siz = size(input); outsum = zeros(siz(2:end)); outssq = zeros(siz(2:end)); pvec = [3 setdiff(1:numel(siz),3)]; ft_progress('init', feedback, 'computing metric...'); for j = 1:siz(1) ft_progress(j/siz(1), 'computing metric for replicate %d from %d\n', j, siz(1)); p1 = zeros([siz(2) 1 siz(4:end)]); p2 = zeros([1 siz(3) siz(4:end)]); for k = 1:siz(2) p1(k,1,:,:,:,:) = input(j,k,k,:,:,:,:); p2(1,k,:,:,:,:) = input(j,k,k,:,:,:,:); end c = reshape(input(j,:,:,:,:,:,:), siz(2:end)); p1 = p1(:,ones(1,siz(3)),:,:,:,:); p2 = p2(ones(1,siz(2)),:,:,:,:,:); p = ipermute(phaseslope(permute(c./sqrt(p1.*p2), pvec), nbin, normalize), pvec); p(isnan(p)) = 0; outsum = outsum + p; outssq = outssq + p.^2; end ft_progress('close'); end n = siz(1); c = outsum./n; if n>1, n = shiftdim(sum(~isnan(input),1),1); if hasjack bias = (n-1).^2; else bias = 1; end v = bias.*(outssq - (outsum.^2)./n)./(n - 1); else v = []; end %--------------------------------------- function [y] = phaseslope(x, n, norm) m = size(x, 1); %total number of frequency bins y = zeros(size(x)); x(1:end-1,:,:,:,:) = conj(x(1:end-1,:,:,:,:)).*x(2:end,:,:,:,:); if strcmp(norm, 'yes') coh = zeros(size(x)); coh(1:end-1,:,:,:,:) = (abs(x(1:end-1,:,:,:,:)) .* abs(x(2:end,:,:,:,:))) + 1; %FIXME why the +1? get the coherence for k = 1:m begindx = max(1,k-n); endindx = min(m,k+n); y(k,:,:,:,:) = imag(nansum(x(begindx:endindx,:,:,:,:)./coh(begindx:endindx,:,:,:,:),1)); end else for k = 1:m begindx = max(1,k-n); endindx = min(m,k+n); y(k,:,:,:,:) = imag(nansum(x(begindx:endindx,:,:,:,:),1)); end end
github
lcnhappe/happe-master
sfactorization_wilson2x2.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/connectivity/private/sfactorization_wilson2x2.m
8,406
utf_8
73bfa40093aff0fb82e9ca232813340b
function [H, Z, S, psi] = sfactorization_wilson2x2(S,freq,Niterations,tol,cmbindx,fb,init,checkflag) % SFACTORIZATION_WILSON2X2 performs pairwise non-parametric spectral factorization on % cross-spectra, based on Wilson's algorithm. % % Usage : [H, Z, psi] = sfactorization_wilson(S,freq); % % Inputs : S (1-sided, 3D-spectral matrix in the form of Channel x Channel x frequency) % : freq (a vector of frequencies) at which S is given. % % Outputs: H (transfer function) % : Z (noise covariance) % : S (cross-spectral density 1-sided) % : psi (left spectral factor) % % This function is an implemention of Wilson's algorithm (Eq. 3.1) % for spectral matrix factorization. % % Ref: G.T. Wilson,"The Factorization of Matricial Spectral Densities," % SIAM J. Appl. Math.23,420-426(1972). % Written by M. Dhamala & G. Rangarajan, UF, Aug 3-4, 2006. % Email addresses: [email protected], [email protected] % Copyright (C) 2009-2013, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % 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<8, checkflag = true; end if nargin<7, init = 'chol'; end if nargin<6, fb = 'none'; end if nargin<5, error('FieldTrip:connectivity:sfactorization_wilson2x2', 'when requesting multiple pairwise spectral decomposition, ''cmbindx'' needs to be specified'); end if nargin<4, tol = 1e-8; end if nargin<3, Niterations = 1000; end; dfreq = round(diff(freq)*1e5)./1e5; % allow for some numeric issues if ~all(dfreq==dfreq(1)) error('FieldTrip:connectivity:sfactorization_wilson2x2', 'frequency axis is not evenly spaced'); end if freq(1)~=0 ft_warning('FieldTrip:connectivity:sfactorization_wilson2x2', 'when performing non-parametric spectral factorization, the frequency axis should ideally start at 0, zero padding the spectral density'); dfreq = mean(dfreq); npad = freq(1)./dfreq; % update the freq axis and keep track of the frequency bins that are % expected in the output selfreq = (1:numel(freq)) + npad; freq = [(0:(npad-1))./dfreq freq]; S = cat(3, zeros(size(S,1), size(S,1), npad), S); else selfreq = 1:numel(freq); end % ensure input S is double (mex-files don't work with single) S = double(S); % check whether the last frequency bin is strictly real-valued. % if that's the case, then it is assumed to be the Nyquist frequency % and the two-sided spectral density will have an even number of % frequency bins. if not, in order to preserve hermitian symmetry, % the number of frequency bins needs to be odd. Send = S(:,:,end); N = numel(freq); m = size(cmbindx,1); if all(imag(Send(:))<abs(trace(Send)./size(Send,1)*1e-9)) hasnyq = true; N2 = 2*(N-1); else hasnyq = false; N2 = 2*(N-1)+1; end % preallocate memory for the identity matrix I = repmat(eye(2),[1 1 m N2]); % Defining 2 x 2 identity matrix % %Step 1: Forming 2-sided spectral densities for ifft routine in matlab % Sarr = zeros(2,2,m,N2) + 1i.*zeros(2,2,m,N2); % for c = 1:m % Stmp = S(cmbindx(c,:),cmbindx(c,:),:); % % % the input cross-spectral density is assumed to be weighted with a % % factor of 2 in all non-DC and Nyquist bins, therefore weight the % % DC-bin with a factor of 2 to get a correct two-sided representation % Sarr(:,:,c,1) = Stmp(:,:,1).*2; % % for f_ind = 2:N % Sarr(:,:,c, f_ind) = Stmp(:,:,f_ind); % Sarr(:,:,c,(N2+2)-f_ind) = Stmp(:,:,f_ind).'; % end % end % Sarr2 = Sarr; % preallocate memory for the 2-sided spectral density Sarr = zeros(2,2,N2,m) + 1i.*zeros(2,2,N2,m); for c = 1:m Sarr(:,:,1:N,c) = S(cmbindx(c,:),cmbindx(c,:),:); end if hasnyq, N1 = N; else N1 = N + 1; % the highest frequency needs to be represented twice, for symmetry purposes end Sarr(:,:,N1:N2,:) = flipdim(Sarr(:,:,2:N,:),3); Sarr(2,1,N1:N2,:) = conj(Sarr(2,1,N1:N2,:)); Sarr(1,2,N1:N2,:) = conj(Sarr(1,2,N1:N2,:)); Sarr = permute(Sarr, [1 2 4 3]); Sarr(:,:,:,1) = Sarr(:,:,:,1).*2; % weight the DC-bin % the input cross-spectral density is assumed to be weighted with a % factor of 2 in all non-DC and Nyquist bins, therefore weight the % Nyquist bin with a factor of 2 to get a correct two-sided representation if hasnyq Sarr(:,:,:,N) = Sarr(:,:,:,N).*2; end %Step 2: Computing covariance matrices gam = real(reshape(ifft(reshape(Sarr, [4*m N2]), [], 2),[2 2 m N2])); %Step 3: Initializing for iterations gam0 = gam(:,:,:,1); h = complex(zeros(size(gam0))); for k = 1:m switch init case 'chol' [tmp, dum] = chol(gam0(:,:,k)); if dum warning('initialization with ''chol'' for iterations did not work well, using arbitrary starting condition'); tmp = rand(2,2); %arbitrary initial condition tmp = triu(tmp); end case 'rand' tmp = rand(2,2); %arbitrary initial condition tmp = triu(tmp); otherwise error('initialization method should be eithe ''chol'' or ''rand'''); end h(:,:,k) = tmp; %h(:,:,k) = chol(gam0(:,:,k)); end psi = repmat(h, [1 1 1 N2]); %Step 4: Iterating to get spectral factors ft_progress('init', fb, 'computing spectral factorization'); for iter = 1:Niterations ft_progress(iter./Niterations, 'computing iteration %d/%d\n', iter, Niterations); invpsi = inv2x2(psi); g = sandwich2x2(invpsi, Sarr) + I; gp = PlusOperator2x2(g,m,N); %gp constitutes positive and half of zero lags psi_old = psi; psi = mtimes2x2(psi, gp); if checkflag, psierr = abs(psi-psi_old)./abs(psi); psierrf = mean(psierr(:)); if(psierrf<tol), fprintf('reaching convergence at iteration %d\n',iter); break; end % checking convergence end end ft_progress('close'); %Step 5: Getting covariance matrix from spectral factors gamtmp = reshape(real(ifft(transpose(reshape(psi, [4*m N2]))))', [2 2 m N2]); %Step 6: Getting noise covariance & transfer function (see Example pp. 424) A0 = gamtmp(:,:,:,1); A0inv = inv2x2(A0); Z = zeros(2,2,m); for k = 1:m %Z = A0*A0.'*fs; %Noise covariance matrix Z(:,:,k) = A0(:,:,k)*A0(:,:,k).'; %Noise covariance matrix not multiplied by sampling frequency %FIXME check this; at least not multiplying it removes the need to correct later on %this also makes it more equivalent to the noisecov estimated by biosig's mvar-function end H = complex(zeros(2,2,m,N)); S = complex(zeros(2,2,m,N)); for k = 1:N for kk = 1:m H(:,:,kk,k) = psi(:,:,kk,k)*A0inv(:,:,kk); % Transfer function S(:,:,kk,k) = psi(:,:,kk,k)*psi(:,:,kk,k)'; % Cross-spectral density end end siz = [size(H) 1 1]; H = reshape(H, [4*siz(3) siz(4:end)]); siz = [size(S) 1 1]; S = reshape(S, [4*siz(3) siz(4:end)]); siz = [size(Z) 1 1]; Z = reshape(Z, [4*siz(3) siz(4:end)]); siz = [size(psi) 1 1]; psi = reshape(psi, [4*siz(3) siz(4:end)]); if numel(selfreq)~=numel(freq) % return only the frequency bins that were in the input H = H(:,selfreq,:,:); S = S(:,selfreq,:,:); psi = psi(:,selfreq,:,:); end %--------------------------------------------------------------------- function gp = PlusOperator2x2(g,ncmb,nfreq) % This function is for [ ]+operation: % to take the positive lags & half of the zero lag and reconstitute % M. Dhamala, UF, August 2006 g = transpose(reshape(g, 4*ncmb, [])); gam = ifft(g); % taking only the positive lags and half of the zero lag gamp = gam; beta0 = 0.5*gam(1,:); %for k = 1:ncmb % gamp(1,(k-1)*4+1:k*4) = reshape(triu(reshape(beta0(1,(k-1)*4+1:k*4),[2 2])),[1 4]); %end beta0(2:4:4*ncmb) = 0; gamp(1,:) = beta0; gamp(nfreq+1:end,:) = 0; % reconstituting gp = fft(gamp); gp = reshape(transpose(gp), [2 2 ncmb numel(gp)/(4*ncmb)]);
github
lcnhappe/happe-master
ft_warning.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/connectivity/private/ft_warning.m
7,789
utf_8
d832a7ad5e2f9bb42995e6e5d4caa198
function [ws, warned] = ft_warning(varargin) % FT_WARNING will throw a warning for every unique point in the % stacktrace only, e.g. in a for-loop a warning is thrown only once. % % Use as one of the following % ft_warning(string) % ft_warning(id, string) % Alternatively, you can use ft_warning using a timeout % ft_warning(string, timeout) % ft_warning(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. % % Use as ft_warning('-clear') to clear old warnings from the current % stack % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = ft_warning(...) % or as % ft_warning(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, ft_warning accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = ft_warning(...) % where w is a boolean that indicates whether a warning as been thrown or not. % % Please note that you can NOT use it like this % ft_warning('the value is %d', 10) % instead you should do % ft_warning(sprintf('the value is %d', 10)) % Copyright (C) 2012-2016, Robert Oostenveld, J?rn M. Horschig % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % 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$ global ft_default warned = false; ws = []; stack = dbstack; if any(strcmp({stack(2:end).file}, 'ft_warning.m')) % don't call FT_WARNING recursively, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3068 return; end if nargin < 1 error('You need to specify at least a warning message'); end if isstruct(varargin{1}) warning(varargin{1}); return; end if ~isfield(ft_default, 'warning') ft_default.warning = []; end if ~isfield(ft_default.warning, 'stopwatch') ft_default.warning.stopwatch = []; end if ~isfield(ft_default.warning, 'identifier') ft_default.warning.identifier = []; end if ~isfield(ft_default.warning, 'ignore') ft_default.warning.ignore = {}; end % put the arguments we will pass to warning() in this cell array warningArgs = {}; if nargin==3 % calling syntax (id, msg, timeout) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); msg = warningArgs{1}; timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && isequal(varargin{1}, 'off') ft_default.warning.ignore = union(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && isequal(varargin{1}, 'on') ft_default.warning.ignore = setdiff(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = inf; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); msg = warningArgs{1}; timeout = inf; % default timeout in seconds fname = [warningArgs{1}]; end if ismember(msg, ft_default.warning.ignore) % do not show this warning return; end if isempty(timeout) error('Timeout ill-specified'); end if timeout ~= inf fname = fixname(fname); % make a nice string that is allowed as fieldname in a structures line = []; else % here, we create the fieldname functionA.functionB.functionC... [tmpfname, ft_default.warning.identifier, line] = fieldnameFromStack(ft_default.warning.identifier); if ~isempty(tmpfname), fname = tmpfname; clear tmpfname; end end if nargin==1 && ischar(varargin{1}) && strcmp('-clear', varargin{1}) if strcmp(fname, '-clear') % reset all fields if called outside a function ft_default.warning.identifier = []; ft_default.warning.stopwatch = []; else if issubfield(ft_default.warning.identifier, fname) ft_default.warning.identifier = rmsubfield(ft_default.warning.identifier, fname); end end return; end % and add the line number to make this unique for the last function fname = horzcat(fname, line); if ~issubfield('ft_default.warning.stopwatch', fname) ft_default.warning.stopwatch = setsubfield(ft_default.warning.stopwatch, fname, tic); end now = toc(getsubfield(ft_default.warning.stopwatch, fname)); % measure time since first function call if ~issubfield(ft_default.warning.identifier, fname) || ... (issubfield(ft_default.warning.identifier, fname) && now>getsubfield(ft_default.warning.identifier, [fname '.timeout'])) % create or reset field ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, fname, []); % warning never given before or timed out ws = warning(warningArgs{:}); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.timeout'], now+timeout); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.ws'], msg); warned = true; else % the warning has been issued before, but has not timed out yet ws = getsubfield(ft_default.warning.identifier, [fname '.ws']); end end % function ft_warning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fname, ft_previous_warnings, line] = fieldnameFromStack(ft_previous_warnings) % stack(1) is this function, stack(2) is ft_warning stack = dbstack('-completenames'); if size(stack) < 3 fname = []; line = []; return; end i0 = 3; % ignore ft_preamble while strfind(stack(i0).name, 'ft_preamble') i0=i0+1; end fname = horzcat(fixname(stack(end).name)); if ~issubfield(ft_previous_warnings, fixname(stack(end).name)) ft_previous_warnings.(fixname(stack(end).name)) = []; % iteratively build up structure fields end for i=numel(stack)-1:-1:(i0) % skip postamble scripts if strncmp(stack(i).name, 'ft_postamble', 12) break; end fname = horzcat(fname, '.', horzcat(fixname(stack(i).name))); % , stack(i).file if ~issubfield(ft_previous_warnings, fname) % iteratively build up structure fields setsubfield(ft_previous_warnings, fname, []); end end % line of last function call line = ['.line', int2str(stack(i0).line)]; end % function outcome = issubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % outcome = eval(['isfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % outcome = isfield(strct, fname); % end % end % function strct = rmsubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % strct = eval(['rmfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % strct = rmfield(strct, fname); % end % end
github
lcnhappe/happe-master
sfactorization_wilson.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/connectivity/private/sfactorization_wilson.m
7,826
utf_8
42fad4dc181f918d0eae9b4b4158dec0
function [H, Z, S, psi] = sfactorization_wilson(S,freq,Niterations,tol,fb,init,checkflag) % SFACTORIZATION_WILSON performs multivariate non-parametric spectral factorization on % cross-spectra, based on Wilson's algorithm. % % Usage : [H, Z, S, psi] = sfactorization_wilson(S,freq); % % Inputs : S (1-sided, 3D-spectral matrix in the form of Channel x Channel x frequency) % : freq (a vector of frequencies) at which S is given. % % Outputs: H (transfer function) % : Z (noise covariance) % : psi (left spectral factor) % % This function is an implemention of Wilson's algorithm (Eq. 3.1) % for spectral matrix factorization % % Ref: G.T. Wilson,"The Factorization of Matricial Spectral Densities," % SIAM J. Appl. Math.23,420-426(1972). % Written by M. Dhamala & G. Rangarajan, UF, Aug 3-4, 2006. % Email addresses: [email protected], [email protected] % Copyright (C) 2009-2013, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % 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<7, checkflag = true; end if nargin<6, init = 'chol'; end if nargin<5, fb = 'none'; end if nargin<4, tol = 1e-8; end if nargin<3, Niterations = 1000; end dfreq = round(diff(freq)*1e5)./1e5; % allow for some numeric issues if ~all(dfreq==dfreq(1)) error('FieldTrip:connectivity:sfactorization_wilson', 'frequency axis is not evenly spaced'); end if freq(1)~=0 ft_warning('FieldTrip:connectivity:sfactorization_wilson', 'when performing non-parametric spectral factorization, the frequency axis should ideally start at 0, zero padding the spectral density'); dfreq = mean(dfreq); npad = freq(1)./dfreq; % update the freq axis and keep track of the frequency bins that are % expected in the output selfreq = (1:numel(freq)) + npad; freq = [(0:(npad-1))./dfreq freq]; S = cat(3, zeros(size(S,1), size(S,1), npad), S); else selfreq = 1:numel(freq); end % check whether the last frequency bin is strictly real-valued. % if that's the case, then it is assumed to be the Nyquist frequency % and the two-sided spectral density will have an even number of % frequency bins. if not, in order to preserve hermitian symmetry, % the number of frequency bins needs to be odd. Send = S(:,:,end); N = numel(freq); m = size(S,1); if all(imag(Send(:))<abs(trace(Send)./size(Send,1)*1e-9)) N2 = 2*(N-1); else N2 = 2*(N-1)+1; end % preallocate memory for efficiency Sarr = zeros(m,m,N2) + 1i.*zeros(m,m,N2); gam = zeros(m,m,N2); gamtmp = zeros(m,m,N2); psi = zeros(m,m,N2); I = eye(m); % Defining m x m identity matrix %Step 1: Forming 2-sided spectral densities for ifft routine in matlab % the input cross-spectral density is assumed to be weighted with a % factor of 2 in all non-DC and Nyquist bins, therefore weight the % DC-bin with a factor of 2 to get a correct two-sided representation Sarr(:,:,1) = S(:,:,1).*2; for f_ind = 2:N Sarr(:,:, f_ind) = S(:,:,f_ind); Sarr(:,:,(N2+2)-f_ind) = S(:,:,f_ind).'; end % the input cross-spectral density is assumed to be weighted with a % factor of 2 in all non-DC and Nyquist bins, therefore weight the % Nyquist bin with a factor of 2 to get a correct two-sided representation if mod(size(Sarr,3),2)==0 Sarr(:,:,N) = Sarr(:,:,N).*2; end %Step 2: Computing covariance matrices for k1 = 1:m for k2 = 1:m %gam(k1,k2,:) = real(ifft(squeeze(Sarr(k1,k2,:)))*fs); %FIXME think about this gam(k1,k2,:) = real(ifft(squeeze(Sarr(k1,k2,:)))); end end %Step 3: Initializing for iterations gam0 = gam(:,:,1); switch init case 'chol' [tmp, dum] = chol(gam0); if dum warning('initialization with ''chol'' for iterations did not work well, using arbitrary starting condition'); tmp = randn(m,1000); %arbitrary initial condition tmp = (tmp*tmp')./1000; %tmp = triu(tmp); [tmp, dum] = chol(tmp); end case 'rand' %tmp = randn(m,m); %arbitrary initial condition %tmp = triu(tmp); tmp = randn(m,1000); %arbitrary initial condition tmp = (tmp*tmp')./1000; %tmp = triu(tmp); [tmp, dum] = chol(tmp); otherwise error('initialization method should be eithe ''chol'' or ''rand'''); end h = tmp; for ind = 1:N2 psi(:,:,ind) = h; end %Step 4: Iterating to get spectral factors g = zeros(size(psi)); ft_progress('init', fb, 'computing spectral factorization'); for iter = 1:Niterations ft_progress(iter./Niterations, 'computing iteration %d/%d\n', iter, Niterations); for ind = 1:N2 %invpsi = inv(psi(:,:,ind)); g(:,:,ind) = psi(:,:,ind)\Sarr(:,:,ind)/psi(:,:,ind)'+I;%Eq 3.1 end gp = PlusOperator(g,m,N); %gp constitutes positive and half of zero lags psi_old = psi; for k = 1:N2 psi(:,:,k) = psi(:,:,k)*gp(:,:,k); psierr(k) = norm(psi(:,:,k)-psi_old(:,:,k),1); end if checkflag, psierrf = mean(psierr); if(psierrf<tol), fprintf('reaching convergence at iteration %d\n',iter); break; end % checking convergence end end ft_progress('close'); %Step 5: Getting covariance matrix from spectral factors for k1 = 1:m for k2 = 1:m gamtmp(k1,k2,:) = real(ifft(squeeze(psi(k1,k2,:)))); end end %Step 6: Getting noise covariance & transfer function (see Example pp. 424) A0 = gamtmp(:,:,1); A0inv = inv(A0); %Z = A0*A0.'*fs; %Noise covariance matrix Z = A0*A0.'; %Noise covariance matrix not multiplied by sampling frequency %FIXME check this; at least not multiplying it removes the need to correct later on %this also makes it more equivalent to the noisecov estimated by biosig's mvar-function H = zeros(m,m,N) + 1i*zeros(m,m,N); for k = 1:N H(:,:,k) = psi(:,:,k)*A0inv; %Transfer function S(:,:,k) = psi(:,:,k)*psi(:,:,k)'; %Updated cross-spectral density end if numel(selfreq)~=numel(freq) % return only the frequency bins that were in the input H = H(:,:,selfreq); S = S(:,:,selfreq); psi = psi(:,:,selfreq); end %--------------------------------------------------------------------- function gp = PlusOperator(g,nchan,nfreq) % This function is for [ ]+operation: % to take the positive lags & half of the zero lag and reconstitute % M. Dhamala, UF, August 2006 g = transpose(reshape(g, nchan^2, [])); gam = ifft(g); % taking only the positive lags and half of the zero lag gamp = gam; beta0 = 0.5*gam(1,:); gamp(1, :) = reshape(triu(reshape(beta0, [nchan nchan])),[1 nchan^2]); gamp(nfreq+1:end,:) = 0; % reconstituting gp = fft(gamp); gp = reshape(transpose(gp), [nchan nchan numel(gp)/(nchan^2)]); %------------------------------------------------------ %this is the original code; above is vectorized version %which is assumed to be faster with many channels present %for k1 = 1:nchan % for k2 = 1:nchan % gam(k1,k2,:) = ifft(squeeze(g(k1,k2,:))); % end %end % %% taking only the positive lags and half of the zero lag %gamp = gam; %beta0 = 0.5*gam(:,:,1); %gamp(:,:,1) = triu(beta0); %this is Stau %gamp(:,:,nfreq+1:end) = 0; % %% reconstituting %for k1 = 1:nchan % for k2 = 1:nchan % gp(k1,k2,:) = fft(squeeze(gamp(k1,k2,:))); % end %end
github
lcnhappe/happe-master
test_corrupt_matfiles.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_corrupt_matfiles.m
977
utf_8
5ab1651a584ef5f3c5112d046bde5d58
function test_corrupt_matfiles % MEM 8gb % WALLTIME 10:00:00 files = findfiles('/home/common/matlab/fieldtrip/data/test'); status = true(size(files)); for i=1:length(files) try tmp = load(files{i}); clear tmp fprintf('passed reading %s\n', files{i}); catch status(i) = false; warning('failed reading %s\n', files{i}); end end if any(status==false) error('not all files could be read into MATLAB'); end function files = findfiles(p) d = dir(p); d = d([d.bytes]<4*1e9); % skip files that are too large files = {d(~[d.isdir]).name}'; files = files(~cellfun(@isempty, regexp(files, '\.mat$'))); % only select the mat files files = files( cellfun(@isempty, regexp(files, '^\._'))); % exclude the OS X resource forks for i=1:length(files) files{i} = fullfile(p, files{i}); end dirs = {d( [d.isdir]).name}'; dirs = dirs(3:end); % the first two are . and .. for i=1:length(dirs) files = cat(1, files, findfiles(fullfile(p, dirs{i}))); end
github
lcnhappe/happe-master
test_tutorial_eventrelatedstatistics.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_tutorial_eventrelatedstatistics.m
9,523
utf_8
2cf8fa1f8ee413ae513bff8697d5f5e7
function test_tutorial_eventrelatedstatistics(datadir) % MEM 2500mb % WALLTIME 00:20:00 % TEST test_tutorial_eventrelatedstatistics % TEST ft_timelockanalysis ft_multiplotER ft_singleplotER ft_timelockstatistics % TEST ft_topoplotER ft_clusterplot global ft_default; ft_default.feedback = 'no'; if nargin==0 if ispc datadir = 'H:'; else datadir = '/home'; end load(fullfile(datadir, 'common', 'matlab', 'fieldtrip', 'data', 'ftp', 'tutorial', 'eventrelatedstatistics', 'ERF_orig.mat')); else load(fullfile(datadir, 'ERF_orig.mat')); end % Tutorial update on 3 Feb: no longer give grandaverage inarg to % ft_XX_statistics, instead introduce cell-array inarg. %% calculating the grand-average % calculate grand average for each condition cfg = []; cfg.channel = 'all'; cfg.latency = 'all'; cfg.parameter = 'avg'; GA_FC = ft_timelockgrandaverage(cfg,allsubjFC{:}); GA_FIC = ft_timelockgrandaverage(cfg,allsubjFIC{:}); %% plotting the grand-average cfg = []; cfg.showlabels = 'yes'; cfg.layout = 'CTF151.lay'; figure; ft_multiplotER(cfg,GA_FC, GA_FIC) cfg = []; cfg.channel = 'MLT12'; figure; ft_singleplotER(cfg,GA_FC, GA_FIC) time = [0.3 0.7]; % Scaling of the vertical axis for the plots below ymax = 1.9e-13; figure; for iSub = 1:10 subplot(3,4,iSub) plot(allsubjFC{iSub}.time,allsubjFC{iSub}.avg(52,:)); hold on % use the rectangle to indicate the time range used later rectangle('Position',[time(1) 0 (time(2)-time(1)) ymax],'FaceColor',[0.7 0.7 0.7]); % repeat the plotting to get the line in front of the rectangle plot(allsubjFIC{iSub}.time,allsubjFIC{iSub}.avg(52,:),'r'); title(strcat('subject ',num2str(iSub))) ylim([0 1.9e-13]) xlim([-1 2]) end subplot(3,4,11); text(0.5,0.5,'FC','color','b') ;text(0.5,0.3,'FIC','color','r') axis off %% plotting single subject averages chan = 52; time = [0.3 0.7]; % find the time points for the effect of interest in the grand average data timesel_FIC = find(GA_FIC.time >= time(1) & GA_FIC.time <= time(2)); timesel_FC = find(GA_FC.time >= time(1) & GA_FC.time <= time(2)); % select the individual subject data from the time points and calculate the mean for isub = 1:10 values_FIC(isub) = mean(allsubjFIC{isub}.avg(chan,timesel_FIC)); values_FC(isub) = mean(allsubjFC{isub}.avg(chan,timesel_FC)); end % plot to see the effect in each subject M = [values_FC',values_FIC']; figure; plot(M','o-'); xlim([0.5 2.5]) legend({'subj1', 'subj2', 'subj3', 'subj4', 'subj5', 'subj6', ... 'subj7', 'subj8', 'subj9', 'subj10'}, 'location','EastOutside'); %% T-test with MATLAB function % dependent samples ttest FCminFIC = values_FC - values_FIC; [h,p,ci,stats] = ttest_wrapper(FCminFIC, 0, 0.05) % H0: mean = 0, alpha 0.05 %% T-test with FieldTrip function cfg = []; cfg.channel = 'MLT12'; cfg.latency = [0.3 0.7]; cfg.avgovertime = 'yes'; cfg.parameter = 'avg'; cfg.method = 'analytic'; cfg.statistic = 'ft_statfun_depsamplesT'; cfg.alpha = 0.05; cfg.correctm = 'no'; Nsub = 10; cfg.design(1,1:2*Nsub) = [ones(1,Nsub) 2*ones(1,Nsub)]; cfg.design(2,1:2*Nsub) = [1:Nsub 1:Nsub]; cfg.ivar = 1; % the 1st row in cfg.design contains the independent variable cfg.uvar = 2; % the 2nd row in cfg.design contains the subject number stat = ft_timelockstatistics(cfg,allsubjFC{:},allsubjFIC{:}); %% Multiple comparisons %loop over channels time = [0.3 0.7]; timesel_FIC = find(GA_FIC.time >= time(1) & GA_FIC.time <= time(2)); timesel_FC = find(GA_FC.time >= time(1) & GA_FC.time <= time(2)); clear h p FICminFC = zeros(1,10); for iChan = 1:151 for isub = 1:10 FICminFC(isub) = mean(allsubjFIC{isub}.avg(iChan,timesel_FIC)) - mean(allsubjFC{isub}.avg(iChan,timesel_FC)); [h(iChan), p(iChan)] = ttest_wrapper(FICminFC, 0, 0.05 ); % test each channel separately end end % plot uncorrected "significant" channels cfg = []; cfg.style = 'blank'; cfg.layout = 'CTF151.lay'; cfg.highlight = 'on'; cfg.highlightchannel = find(h); cfg.comment = 'no'; figure; ft_topoplotER(cfg, GA_FC) title('significant without multiple comparison correction') %% with Bonferoni correction for multiple comparisons FICminFC = zeros(1,10); for iChan = 1:151 for isub = 1:10 FICminFC(isub) = mean(allsubjFIC{isub}.avg(iChan,timesel_FIC)) - mean(allsubjFC{isub}.avg(iChan,timesel_FC)); [h(iChan), p(iChan)] = ttest_wrapper(FICminFC, 0, 0.05/151); % test each channel separately end end %% Bonferoni correction with FieldTrip function cfg = []; cfg.channel = 'MEG'; %now all channels cfg.latency = [0.3 0.7]; cfg.avgovertime = 'yes'; cfg.parameter = 'avg'; cfg.method = 'analytic'; cfg.statistic = 'ft_statfun_depsamplesT'; cfg.alpha = 0.05; cfg.correctm = 'bonferoni'; Nsub = 10; cfg.design(1,1:2*Nsub) = [ones(1,Nsub) 2*ones(1,Nsub)]; cfg.design(2,1:2*Nsub) = [1:Nsub 1:Nsub]; cfg.ivar = 1; % the 1st row in cfg.design contains the independent variable cfg.uvar = 2; % the 2nd row in cfg.design contains the subject number stat = ft_timelockstatistics(cfg,allsubjFC{:},allsubjFIC{:}); %% NON-PARAMETRIC Permutation test based on t statistics cfg = []; cfg.channel = 'MEG'; cfg.latency = [0.3 0.7]; cfg.avgovertime = 'yes'; cfg.parameter = 'avg'; cfg.method = 'montecarlo'; cfg.statistic = 'ft_statfun_depsamplesT'; cfg.alpha = 0.05; cfg.correctm = 'no'; cfg.correcttail = 'prob'; cfg.numrandomization = 1000; Nsub = 10; cfg.design(1,1:2*Nsub) = [ones(1,Nsub) 2*ones(1,Nsub)]; cfg.design(2,1:2*Nsub) = [1:Nsub 1:Nsub]; cfg.ivar = 1; % the 1st row in cfg.design contains the independent variable cfg.uvar = 2; % the 2nd row in cfg.design contains the subject number stat = ft_timelockstatistics(cfg,allsubjFIC{:},allsubjFC{:}); % make the plot cfg = []; cfg.style = 'blank'; cfg.layout = 'CTF151.lay'; cfg.highlight = 'on'; cfg.highlightchannel = find(stat.mask); cfg.comment = 'no'; figure; ft_topoplotER(cfg, GA_FC) title('Nonparametric: significant without multiple comparison correction') %% NON-PARAMETRIC: Permutation test based on cluster statistics cfg = []; cfg.method = 'template'; % try 'distance' as well cfg.template = 'ctf151_neighb.mat'; % specify type of template cfg.layout = 'CTF151.lay'; % specify layout of sensors* cfg.feedback = 'yes'; % show a neighbour plot neighbours = ft_prepare_neighbours(cfg, GA_FC); % define neighbouring channels cfg = []; cfg.neighbours = neighbours; % define neighbouring channels cfg.channel = 'MEG'; cfg.latency = [0.3 0.7]; cfg.avgovertime = 'yes'; cfg.parameter = 'avg'; cfg.method = 'montecarlo'; cfg.statistic = 'ft_statfun_depsamplesT'; cfg.alpha = 0.05; cfg.correctm = 'cluster'; cfg.correcttail = 'prob'; cfg.numrandomization = 1000; Nsub = 10; cfg.design(1,1:2*Nsub) = [ones(1,Nsub) 2*ones(1,Nsub)]; cfg.design(2,1:2*Nsub) = [1:Nsub 1:Nsub]; cfg.ivar = 1; % the 1st row in cfg.design contains the independent variable cfg.uvar = 2; % the 2nd row in cfg.design contains the subject number stat = ft_timelockstatistics(cfg,allsubjFIC{:},allsubjFC{:}); % make a plot cfg = []; cfg.style = 'blank'; cfg.layout = 'CTF151.lay'; cfg.highlight = 'on'; cfg.highlightchannel = find(stat.mask); cfg.comment = 'no'; figure; ft_topoplotER(cfg, GA_FC) title('Nonparametric: significant with cluster multiple comparison correction') %% longer time window for NON-PARAMETRIC: permutation test based on cluster statistics cfg = []; cfg.channel = 'MEG'; cfg.neighbours = neighbours; % defined as above cfg.latency = [0.1 0.5]; cfg.avgovertime = 'no'; cfg.parameter = 'avg'; cfg.method = 'montecarlo'; cfg.statistic = 'ft_statfun_depsamplesT'; cfg.alpha = 0.05; cfg.correctm = 'cluster'; cfg.correcttail = 'prob'; %cfg.tail = 1; % options are -1, 1 and 0 (default = 0, for 2-tailed) cfg.numrandomization = 1000; cfg.minnbchan = 2; % minimal neighbouring channels Nsub = 10; cfg.design(1,1:2*Nsub) = [ones(1,Nsub) 2*ones(1,Nsub)]; cfg.design(2,1:2*Nsub) = [1:Nsub 1:Nsub]; cfg.ivar = 1; % the 1st row in cfg.design contains the independent variable cfg.uvar = 2; % the 2nd row in cfg.design contains the subject number stat = ft_timelockstatistics(cfg,allsubjFIC{:},allsubjFC{:}); failed = true; for i=1:1000 % this can fail sometime, like every second iteration or so, 100 is a *really* conservative number here stat = ft_timelockstatistics(cfg,allsubjFIC{:},allsubjFC{:}); % make a plot pcfg = []; pcfg.highlightsymbolseries = ['*','*','.','.','.']; pcfg.layout = 'CTF151.lay'; pcfg.contournum = 0; pcfg.markersymbol = '.'; pcfg.parameter = 'stat'; pcfg.alpha = 0.05; pcfg.zlim = [-5 5]; try ft_clusterplot(pcfg,stat); failed = false; break; end end if failed error('ft_clusterplot fails cause p was too high'); end function [h,p,ci,stats]=ttest_wrapper(x,y,alpha) % helper functions for ttest % - old Matlab, with syntax: ttest(x,y,alpha,tail,dim) % - new Matlab and GNU Octave, with syntax: ttest(x,y,'alpha',alpha,...) if nargin('ttest')>0 [h,p,ci,stats]=ttest(x,y,alpha); else [h,p,ci,stats]=ttest(x,y,'alpha',alpha); end
github
lcnhappe/happe-master
test_old_ft_freqanalysis.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_old_ft_freqanalysis.m
4,746
utf_8
6af1e431442a1ca536fdb9f401782c5c
function test_old_ft_freqanalysis % MEM 1gb % WALLTIME 00:10:00 % TEST test_old_ft_freqanalysis function test_ft_freqanalysis % TEST_FT_FREQANALYSIS % This script tests the ft_freqanalysis functions using simulated data % A. Stolk and J.M. Schoffelen % simulate one second of data, samplefreq = 1200 hz t = (1:1200)/1200; a = cos(2*pi*10*t); b = sin(2*pi*25*t); c = a + b; % simulate preprocessed data %cfg = []; %cfg.layout = 'CTF275.lay'; %cfg.layout = prepare_layout(cfg); %data.label = cfg.layout.label(1:273,1); % data.grad.pnt = zeros(595,3); % data.grad.ori = zeros(595,3); % data.grad.tra = zeros(302,595); data.fsample = 1200; data.label = {'chan01';'cos10';'sin25'}; %for j = 1:273 for j = 1 %data.trial{1,1}(j,:) = c; data.trial{1,1} = [c;a;b]; data.time{1,1}(j,:) = t; end % ft_freqnalysis_mtmfft cfg = []; cfg.output = 'pow'; %cfg.channel = 'MEG'; cfg.channel = 'all'; cfg.method = 'mtmfft'; cfg.taper = 'hanning'; cfg.foilim = [1 40]; cfg.keeptrials = 'no'; cfg.keeptapers = 'no'; mtmfft = ft_freqanalysis(cfg, data); % check whether the powerpeaks are at the given frequencies if mtmfft.powspctrm(1,9) < mtmfft.powspctrm(1,10) > mtmfft.powspctrm(1,11) && ... mtmfft.powspctrm(1,24) < mtmfft.powspctrm(1,25) > mtmfft.powspctrm(1,26); else error('test_ft_freqanalysis:notEqual', 'Incorrect output for ft_freqanalysis_mtmfft.'); end % ft_freqnalysis_mtmconvol cfg = []; cfg.output = 'pow'; %cfg.channel = 'MEG'; cfg.channel = 'all'; cfg.method = 'mtmconvol'; cfg.taper = 'hanning'; cfg.keeptrials = 'no'; cfg.keeptapers = 'no'; cfg.foi = 1:1:40; cfg.t_ftimwin = 0.5 * ones(1,length(cfg.foi)); % 500 ms cfg.toi = 0.3:0.05:0.75; % center 1/2 second mtmconvol = ft_freqanalysis(cfg, data); % check whether the powerpeaks are at the given frequencies if mtmconvol.powspctrm(1,9,1) < mtmconvol.powspctrm(1,10,1) > mtmconvol.powspctrm(1,11,1) && ... mtmconvol.powspctrm(1,24,1) < mtmconvol.powspctrm(1,25,1) > mtmconvol.powspctrm(1,26,1); else error('test_ft_freqanalysis:notEqual', 'Incorrect output for ft_freqanalysis_convol.'); end % test new implementation specest % ft_freqnalysis_mtmfft cfg = []; cfg.output = 'fourier'; cfg.channel = 'all'; cfg.method = 'mtmfft'; cfg.taper = 'hanning'; cfg.foilim = [1 40]; cfg.keeptrials = 'yes'; cfg.keeptapers = 'yes'; mtmfft1 = ft_freqanalysis(cfg, data); mtmfft2 = ft_freqanalysis(cfg, data, 1); x = [mtmfft1.fourierspctrm(:,1,10) mtmfft2.fourierspctrm(:,1,10)]; y = [mtmfft1.fourierspctrm(:,1,25) mtmfft2.fourierspctrm(:,1,25)]; % x(2) should only have real component (angle = 0) % y(2) should only have imag component (negative value, angle = -pi/2) % abs(x(1))==abs(x(2)) % abs(y(1))==abs(y(2)) % ft_freqnalysis_mtmconvol cfg = []; cfg.output = 'fourier'; cfg.channel = 'all'; cfg.method = 'mtmconvol'; cfg.taper = 'hanning'; cfg.keeptrials = 'no'; cfg.keeptapers = 'no'; cfg.foi = 1:1:40; cfg.t_ftimwin = 0.5 * ones(1,length(cfg.foi)); % 500 ms cfg.toi = 0.25:1./1200:0.75; % center 1/2 second mtmconvol1 = ft_freqanalysis(cfg, data); mtmconvol2 = ft_freqanalysis(cfg, data, 1); x = [squeeze(mtmconvol1.fourierspctrm(:,2,10,:)) ... squeeze(mtmconvol2.fourierspctrm(:,2,10,:))]; y = [squeeze(mtmconvol1.fourierspctrm(:,3,25,:)) ... squeeze(mtmconvol2.fourierspctrm(:,3,25,:))]; % observations: % Old implementation has 1 Nan at the beginning % New implementation has 1 Nan at the end % expectations: % angle(x(1,2)) = -pi, (phase of cosine @10Hz @0.25 s: this is approximately true, but not exact % angle(y(1,2)) = 0 (phase of sine @25Hz @0.25 s = 6.25 cycle: this is approximately true, but not exact % FIXME should we look into this? % issues are probably related to even numbered t_ftimwins... % ft_freqnalysis_mtmconvol cfg = []; cfg.output = 'fourier'; cfg.channel = 'all'; cfg.method = 'mtmconvol'; cfg.taper = 'dpss'; cfg.keeptrials = 'no'; cfg.keeptapers = 'no'; cfg.foi = 1:1:40; cfg.t_ftimwin = 0.5 * ones(1,length(cfg.foi)); % 500 ms cfg.toi = 0.25:1./1200:0.75; % center 1/2 second cfg.tapsmofrq = ones(1,numel(cfg.foi)).*4; mtmconvol1 = ft_freqanalysis(cfg, data); mtmconvol2 = ft_freqanalysis(cfg, data, 1); x = [squeeze(mtmconvol1.fourierspctrm(:,2,10,:)); ... squeeze(mtmconvol2.fourierspctrm(:,2,10,:))]; y = [squeeze(mtmconvol1.fourierspctrm(:,3,25,:)); ... squeeze(mtmconvol2.fourierspctrm(:,3,25,:))];
github
lcnhappe/happe-master
test_bug1306.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_bug1306.m
3,242
utf_8
6eafe5e96456aef8810d60524f895038
function test_bug1306b % MEM 1500mb % WALLTIME 00:10:00 % Use function signature below for testing --- note that xUnit does not seem to support it. %function datanew = test_ft_preprocessing(datainfo, writeflag, version) % TEST test_ft_preprocessing % TEST ft_preprocessing ref_datasets % writeflag determines whether the output should be saved to disk % version determines the output directory if nargin<1 datainfo = ref_datasets; end if nargin<2 writeflag = 0; end if nargin<3 version = 'latest'; end for k = 1:numel(datainfo) disp(['preprocessing dataset ' datainfo(k).filename]); datanew = preprocessing10trials(datainfo(k), writeflag, version); datanew = ft_timelockanalysis([],datanew); % fname = fullfile(datainfo(k).origdir,version,'raw',datainfo(k).type,['preproc_',datainfo(k).datatype]); % load(fname); % % these are per construction different if writeflag = 0; % datanew = rmfield(datanew, 'cfg'); % data = rmfield(data, 'cfg'); % % these can have subtle differences eg. in hdr.orig.FID % data.hdr = []; % datanew2 = datanew; % datanew2.hdr = []; % % % do the comparison with the header removed, the output argument still % % contains the header % assert(isequaln(data, datanew2)); end %---------------------------------------------------------- % subfunction to read in 10 trials of data %---------------------------------------------------------- function [data] = preprocessing10trials(dataset, writeflag, version) % --- HISTORICAL --- attempt forward compatibility with function handles if ~exist('ft_preprocessing') && exist('preprocessing') eval('ft_preprocessing = @preprocessing;'); end if ~exist('ft_read_header') && exist('read_header') eval('ft_read_header = @read_header;'); elseif ~exist('ft_read_header') && exist('read_fcdc_header') eval('ft_read_header = @read_fcdc_header;'); end if ~exist('ft_read_event') && exist('read_event') eval('ft_read_event = @read_event;'); elseif ~exist('ft_read_event') && exist('read_fcdc_event') eval('ft_read_event = @read_fcdc_event;'); end cfg = []; cfg.dataset = fullfile(dataset.origdir,'original',dataset.type,dataset.datatype,'/',dataset.filename); if writeflag, cfg.outputfile = fullfile(dataset.origdir,version,'raw',dataset.type,['preproc_',dataset.datatype '.mat']); end % get header and event information if ~isempty(dataset.dataformat) hdr = ft_read_header(cfg.dataset, 'headerformat', dataset.dataformat); event = ft_read_event(cfg.dataset, 'eventformat', dataset.dataformat); cfg.dataformat = dataset.dataformat; cfg.headerformat = dataset.dataformat; else hdr = ft_read_header(cfg.dataset); event = ft_read_event(cfg.dataset); end % create 10 1-second trials to be used as test-case begsample = ((1:10)-1)*round(hdr.Fs) + 1; endsample = ((1:10) )*round(hdr.Fs); offset = zeros(1,10); cfg.trl = [begsample(:) endsample(:) offset(:)]; sel = cfg.trl(:,2)<=hdr.nSamples*hdr.nTrials; cfg.trl = cfg.trl(sel,:); cfg.continuous = 'yes'; data = ft_preprocessing(cfg); if ~strcmp(version, 'latest') && str2num(version)<20100000 % -- HISTORICAL --- older FieldTrip versions don't support outputfile save(cfg.outputfile, 'data'); end
github
lcnhappe/happe-master
test_bug1988.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_bug1988.m
3,484
utf_8
843427441883f86575969f343d6b7737
function test_bug1988 % MEM 3gb % WALLTIME 00:45:00 % TEST test_bug1988 ft_volumesegment ft_prepare_headmodel %% segmentedmri.mat % from current version may not match what is on the ftp for tutorials % as it's called in the BF tutorial mri = ft_read_mri('/home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer/Subject01.mri'); mri.coordsys = 'ctf'; % this can also be determined with ft_determine_coordsys cfg = []; % cfg.coordsys = 'ctf'; % not supported any more, should be specified in the input data segmentedmri_bf = ft_volumesegment(cfg, mri); load /home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer/segmentedmri.mat reference_bf = segmentedmri;clear segmentedmri % Note to developer: if these assertss fail, is current code wrong, or should % tutorial be updated? assert(isequaln(segmentedmri_bf.gray,reference_bf.gray)) assert(isequaln(rmfield(segmentedmri_bf, 'cfg'),rmfield(reference_bf, 'cfg'))) % headmodel_meg, as it's called in the headmodel_meg tutorial mri = ft_read_mri('/home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer/Subject01.mri'); mri.coordsys = 'ctf'; % this can also be determined with ft_determine_coordsys cfg = []; % cfg.coordsys = 'ctf'; % not supported any more, should be specified in the input data cfg.output = 'brain'; segmentedmri_hm = ft_volumesegment(cfg, mri); load /home/common/matlab/fieldtrip/data/ftp/tutorial/headmodel_meg/segmentedmri.mat reference_hm = segmentedmri;clear segmentedmri reference_hm = tryrmfield(reference_hm, 'cfg'); segmentedmri_hm = tryrmfield(segmentedmri_hm, 'cfg'); assert(isequaln(segmentedmri_hm.brain,reference_hm.brain)) assert(isequaln(segmentedmri_hm,reference_hm)) % headmodel_eeg load /home/common/matlab/fieldtrip/data/ftp/tutorial/headmodel_eeg/segmentedmri.mat reference_he = segmentedmri;clear segmentedmri mri = ft_read_mri('/home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer/Subject01.mri'); mri.coordsys = 'ctf'; % this can also be determined with ft_determine_coordsys cfg = []; % cfg.coordsys = 'ctf'; % not supported any more, should be specified in the input data cfg.output = {'brain' 'skull' 'scalp'}; segmentedmri_he = ft_volumesegment(cfg, mri); reference_he = tryrmfield(reference_he, 'cfg'); segmentedmri_he = tryrmfield(segmentedmri_he, 'cfg'); assert(isequaln(segmentedmri_he.brain,reference_he.brain)) assert(isequaln(segmentedmri_he,reference_he)) %% vol.mat % from current version may not match what is on the ftp for tutorials load /home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer/vol.mat % has a vol of type 'nolte' in 'cm' and as an example pnt: volbf = vol; clear vol cfg = []; cfg.method = 'singleshell'; volbf_new = ft_prepare_headmodel(cfg,segmentedmri_bf); volbf = tryrmfield(volbf, 'cfg'); volbf_new = tryrmfield(volbf_new,'cfg'); assert(isequaln(volbf_new,volbf)) load /home/common/matlab/fieldtrip/data/ftp/tutorial/headmodel_meg/vol.mat % has a vol of type 'singleshell' in 'cm' and as an example pnt: volhm = vol; clear vol cfg = []; cfg.method = 'singleshell'; volhm_new = ft_prepare_headmodel(cfg,segmentedmri_hm); volhm_new = rmfield(volhm_new,'cfg'); volhm = rmfield(volhm,'cfg'); volhm_new = rmfield(volhm_new,'cfg'); assert(isequaln(volhm_new,volhm)) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function s = tryrmfield(s, f) if isfield(s, f) s = rmfield(s, f); end
github
lcnhappe/happe-master
test_ft_sourceanalysis.m
.m
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_ft_sourceanalysis.m
84,994
utf_8
8dd6e4bc89de5f6d19e62984a36b9342
function [varargout] = test_ft_sourceanalysis(datainfo, writeflag, version, diagnosticsflag) % MEM 4gb % WALLTIME 04:30:00 % TEST test_ft_sourceanalysis % TEST ft_sourceanalysis ref_datasets % writeflag determines whether the output should be saved to disk % version determines the output directory % diagnosticsflag determines whether some output will be generated for % diagnostics, rather than exiting on error if nargin<1 || isempty(datainfo) datainfo = ref_datasets; end if nargin<2 writeflag = 0; end if nargin<3 || isempty(version) version = 'latest'; end if nargin<4 diagnosticsflag = 0; end diagnostics = {}; % make headmodel headmodel= []; headmodel.o = [0 0 4]; headmodel.r = 12; headmodel.unit = 'cm'; headmodel.type = 'singlesphere'; % 3D folded cortical sheet load(dccnpath('/home/common/matlab/fieldtrip/data/test/corticalsheet.mat')); sourcemodel_sheet = []; sourcemodel_sheet.pos = corticalsheet.pnt(1:100,:); % FIXME reduce the size of the mesh sourcemodel_sheet.inside = 1:size(sourcemodel_sheet.pos,1); % FIXME this should not be needed sourcemodel_sheet.unit = 'cm'; % 3D regular grid sourcemodel_grid = []; sourcemodel_grid.resolution = 2.5; sourcemodel_grid.xgrid = 'auto'; sourcemodel_grid.ygrid = 'auto'; sourcemodel_grid.zgrid = 'auto'; % small number of dipoles, i.e. regions of interest sourcemodel_roi = []; sourcemodel_roi.pos = [0 0 5; 1 0 5; -1 0 5; 0 1 5]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The following section can be used to generate all combinations % for the test computations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if false set1 = { 'sheet' 'grid' 'roi' }; set2 = { 'freq_mtmfft_fourier_trl' 'freq_mtmconvol_fourier_trl' 'freq_mtmfft_trl' 'freq_mtmfft' 'freq_mtmconvol_trl' 'freq_mtmconvol' 'timelock' 'timelock_trl' 'timelock_cov' 'timelock_cov_trl' }; set3 = { 'DICS_keepall' 'DICS_keepall_rawtrial' 'DICS_keepnothing' 'DICS_keepnothing_rawtrial' 'DICS_refdip' 'DICS_refchan' 'DICS_realfilter' 'DICS_fixedori' 'MNE_keepall' 'MNE_keepnothing' 'MNE_keepall_rawtrial' 'MNE_keepnothing_rawtrial' 'LCMV_keepall' 'LCMV_keepnothing' 'LCMV_keepall_rawtrial' 'LCMV_keepnothing_rawtrial' 'DICS_keepall' 'DICS_keepall_rawtrial' 'DICS_keepnothing' 'DICS_keepnothing_rawtrial' 'DICS_refdip' 'DICS_refchan' 'DICS_realfilter' 'DICS_fixedori' 'PCC_keepall' 'PCC_keepall_rawtrial' 'PCC_keepnothing' 'PCC_keepnothing_rawtrial' 'PCC_refdip' }; i = 1; n = length(set1)*length(set2)*length(set3) for i1=1:length(set1) for i2=1:length(set2) for i3=1:length(set3) combination{i,1} = set1{i1}; combination{i,2} = set2{i2}; combination{i,3} = set3{i3}; i = i + 1; end end end % it requires manual intervention to update the list below keyboard end % constructing all combinations % this script (in test/private) generates the list of allowed combinations combination = test_ft_sourceanalysis_combinations_allowed; % TODO: there's an equivalent list of forbidden combinations that should be % tested to generate an explicit error -> using freq data for time domain % methods, or using tlck data for freq domain methods. type = {datainfo.type}' sel = strcmp(type, 'meg'); datainfo = datainfo(sel); for k = 1:numel(datainfo) %%%%%%FIXME added by JM for the time being, neuromag306 with both a %%%%%%grad and an elec fails if strcmp(datainfo(k).datatype, 'neuromag306') removeelec = true; else removeelec = false; end % tmp = randperm(size(combination,1)); % combination = combination(tmp,:); %sel = find(strncmp(combination(:,2),'freq',4)&strncmp(combination(:,3),'MNE',3)); %for j = sel(:)'%1:size(combination,1) for j = 1:size(combination,1) clear timelock freq data sourcemodel = combination{j,1}; datarepresentation = combination{j,2}; algorithm = combination{j,3}; switch sourcemodel case 'sheet' grid = sourcemodel_sheet; case 'grid' grid = sourcemodel_grid; case 'roi' grid = sourcemodel_roi; end switch datarepresentation(1) % this starts with timelock or freq case 'f' inputfile = fullfile(datainfo(k).origdir,version,'freq', datainfo(k).type,[datarepresentation '_' datainfo(k).datatype '.mat']); load(inputfile); data = freq; sourcerepresentation = ['source_' sourcemodel '_' datarepresentation(6:end)]; % drop the 'freq' from the name case 't' inputfile = fullfile(datainfo(k).origdir,version,'timelock',datainfo(k).type,[datarepresentation '_' datainfo(k).datatype '.mat']); load(inputfile); data = timelock; sourcerepresentation = ['source_' sourcemodel '_' datarepresentation]; end if removeelec && isfield(data, 'elec') data = rmfield(data, 'elec'); end testfunction = str2func(sprintf('sourceanalysis_%s', algorithm)); outputfile = fullfile(datainfo(k).origdir,version,'source',datainfo(k).type,[sourcerepresentation '_' algorithm '_' datainfo(k).datatype '.mat']); %try fprintf('----------------------------------------------------------------------------------------------------------\n'); fprintf('----------------------------------------------------------------------------------------------------------\n'); fprintf('inputfile = %s\n', inputfile); fprintf('outputfile = %s\n', outputfile); fprintf('----------------------------------------------------------------------------------------------------------\n'); fprintf('----------------------------------------------------------------------------------------------------------\n'); % execute the actual function that performs the computation %try source = testfunction(data, grid, headmodel); %catch me % if strcmp(me.message, 'method ''mne'' is unsupported for source reconstruction in the frequency domain'); % % continue, and ensure 'source' to exist % source = []; % load(outputfile); % REMOVE THIS ONCE THE FUNCTION RUNS THROUGH AGAIN % elseif strcmp(me.message, 'rawtrial in combination with pcc has been temporarily disabled'); % if exist('outputfile', 'file'), % load(outputfile); % else % source = []; % end % else % keyboard; % end %end if writeflag save(outputfile, 'source'); else sourcenew = source; clear source if exist(outputfile, 'file') load(outputfile); % this contains the previous "source" else warning('file %s does not exist', outputfile); source = []; source.cfg = []; end if isfield(sourcenew, 'cfg'), sourcenew = rmfield(sourcenew, 'cfg'); end% these are different, a.o. due to the callinfo source = rmfield(source, 'cfg'); if ~diagnosticsflag, assert(isequalwithequalnans(source, sourcenew), sprintf('assertion failed: the computed data are different from the data in file %s',outputfile)); else diagnostics{k,j,1} = combination(j,:); if isfield(source, 'avg') && isfield(sourcenew, 'avg') if issubfield(source, 'avg.pow') diagnostics{k,j,2} = 'pow'; diagnostics{k,j,3} = max(source.avg.pow-sourcenew.avg.pow)./max(source.avg.pow); elseif isfield(source.avg, 'mom') diagnostics{k,j,2} = 'mom'; diagnostics{k,j,3} = max(source.avg.mom{1}-sourcenew.avg.mom{1})./max(source.avg.mom{1}); elseif isfield(source.avg, 'csd') diagnostics{k,j,2} = 'csd'; diagnostics{k,j,3} = max(source.avg.csd{1}-sourcenew.avg.csd{1})./max(source.avg.csd{1}); end elseif isfield(source, 'trial') && isfield(sourcenew, 'trial') if isfield(source.trial(1), 'pow') diagnostics{k,j,2} = 'pow'; diagnostics{k,j,3} = max(source.trial(1).pow-sourcenew.trial(1).pow)./max(source.trial(1).pow); elseif isfield(source.trial(1), 'mom') diagnostics{k,j,2} = 'mom'; diagnostics{k,j,3} = max(source.trial(1).mom{1}-sourcenew.trial(1).mom{1})./max(source.trial(1).mom{1}); elseif isfield(source.trial(1), 'csd') diagnostics{k,j,2} = 'csd'; diagnostics{k,j,3} = max(source.trial(1).csd{1}-sourcenew.trial(1).csd{1})./max(source.trial(1).csd{1}); end end end end % catch me % % if strcmp(me.message, sprintf('assertion failed: the computed data are different from the data in file %s',outputfile)) % error('assertion failed: the computed data are different from the data in file %s',outputfile); % elseif strcmp(me.message, 'method ''mne'' is unsupported for source reconstruction in the frequency domain') % warning(me.message); % elseif strcmp(me.message, 'rawtrial in combination with pcc has been temporarily disabled') % warning(me.message); % else % % not all combinations are going to work, give a warning if it fails % %warning('failed on %s', outputfile); % error(me.message); % end % end end % combination end % datainfo if nargout varargout{1} = diagnostics; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % MNE subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function source = sourceanalysis_MNE_keepall(data, grid, headmodel) cfg = []; cfg.channel = 'MEG'; cfg.method = 'mne'; cfg.mne.keepleadfield = 'yes'; cfg.mne.keepfilter = 'yes'; cfg.mne.lambda = 1e4; cfg.headmodel = headmodel; cfg.grid = grid; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_MNE_keepnothing(data, grid, headmodel) cfg = []; cfg.channel = 'MEG'; cfg.method = 'mne'; cfg.mne.keepleadfield = 'no'; cfg.mne.keepfilter = 'no'; cfg.mne.lambda = 1e4; cfg.headmodel = headmodel; cfg.grid = grid; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_MNE_keepall_rawtrial(data, grid, headmodel) % construct the average spatial filter source = sourceanalysis_MNE_keepall(data, grid, headmodel); % project all trials through the average spatial filter cfg = []; cfg.channel = 'MEG'; cfg.method = 'mne'; cfg.mne.lambda = 1e4; cfg.mne.keepleadfield = 'yes'; cfg.mne.keepfilter = 'yes'; cfg.headmodel = headmodel; cfg.grid = grid; cfg.rawtrial = 'yes'; cfg.grid.filter = source.avg.filter; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_MNE_keepnothing_rawtrial(data, grid, headmodel) % construct the average spatial filter source = sourceanalysis_MNE_keepall(data, grid, headmodel); % project all trials through the average spatial filter cfg = []; cfg.method = 'mne'; cfg.channel = 'MEG'; cfg.mne.lambda = 1e4; cfg.mne.keepleadfield = 'no'; cfg.mne.keepfilter = 'no'; cfg.headmodel = headmodel; cfg.grid = grid; cfg.rawtrial = 'yes'; cfg.grid.filter = source.avg.filter; source = ft_sourceanalysis(cfg, data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % LCMV subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function source = sourceanalysis_LCMV_keepall(data, grid, headmodel) cfg = []; cfg.channel = 'MEG'; cfg.method = 'lcmv'; cfg.lcmv.keepleadfield = 'yes'; cfg.lcmv.keepfilter = 'yes'; cfg.lcmv.keepcov = 'yes'; cfg.lcmv.lambda = '5%'; cfg.headmodel = headmodel; cfg.grid = grid; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_LCMV_keepnothing(data, grid, headmodel) cfg = []; cfg.channel = 'MEG'; cfg.method = 'lcmv'; cfg.lcmv.keepleadfield = 'no'; cfg.lcmv.keepfilter = 'no'; cfg.lcmv.keepcov = 'no'; cfg.lcmv.lambda = '5%'; cfg.headmodel = headmodel; cfg.grid = grid; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_LCMV_keepall_rawtrial(data, grid, headmodel) % construct the average spatial filter source = sourceanalysis_LCMV_keepall(data, grid, headmodel); % project all trials through the average spatial filter cfg = []; cfg.channel = 'MEG'; cfg.method = 'lcmv'; cfg.lcmv.keepleadfield = 'yes'; cfg.lcmv.keepfilter = 'yes'; cfg.lcmv.keepcov = 'yes'; cfg.lcmv.lambda = '5%'; cfg.headmodel = headmodel; cfg.grid = grid; cfg.rawtrial = 'yes'; cfg.grid.filter = source.avg.filter; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_LCMV_keepnothing_rawtrial(data, grid, headmodel) % construct the average spatial filter source = sourceanalysis_LCMV_keepall(data, grid, headmodel); % project all trials through the average spatial filter cfg = []; cfg.channel = 'MEG'; cfg.method = 'lcmv'; cfg.lcmv.keepleadfield = 'no'; cfg.lcmv.keepfilter = 'no'; cfg.lcmv.keepcov = 'no'; cfg.lcmv.lambda = '5%'; cfg.headmodel = headmodel; cfg.grid = grid; cfg.rawtrial = 'yes'; cfg.grid.filter = source.avg.filter; source = ft_sourceanalysis(cfg, data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % DICS subfunctions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function source = sourceanalysis_DICS_keepall(data, grid, headmodel) cfg = []; cfg.method = 'dics'; cfg.headmodel = headmodel; cfg.channel = 'MEG'; cfg.grid = grid; cfg.frequency = 10; cfg.latency = 0.5; cfg.keeptrials = 'yes'; cfg.dics.projectnoise = 'yes'; cfg.dics.feedback = 'none'; % dics options cfg.dics.keepfilter = 'yes'; cfg.dics.keepleadfield = 'yes'; cfg.dics.keepcsd = 'yes'; cfg.dics.keepmom = 'yes'; cfg.dics.lambda = '5%'; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_DICS_keepall_rawtrial(data, grid, headmodel) cfg = []; cfg.method = 'dics'; cfg.headmodel = headmodel; cfg.channel = 'MEG'; cfg.grid = grid; cfg.frequency = 10; cfg.latency = 0.5; cfg.keeptrials = 'yes'; cfg.dics.projectnoise = 'yes'; cfg.dics.feedback = 'none'; % dics options cfg.dics.keepfilter = 'yes'; cfg.dics.keepleadfield = 'yes'; cfg.dics.keepcsd = 'yes'; cfg.dics.keepmom = 'yes'; cfg.dics.lambda = '5%'; % get filter tmp = sourceanalysis_DICS_keepall(data, grid, headmodel); cfg.rawtrial = 'yes'; cfg.grid.filter = tmp.avg.filter; cfg.feedback = 'none'; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_DICS_keepnothing(data, grid, headmodel) cfg = []; cfg.method = 'dics'; cfg.headmodel = headmodel; cfg.channel = 'MEG'; cfg.grid = grid; cfg.frequency = 10; cfg.latency = 0.5; cfg.keeptrials = 'no'; cfg.dics.projectnoise = 'no'; cfg.dics.feedback = 'none'; % dics options cfg.dics.keepfilter = 'no'; cfg.dics.keepleadfield = 'no'; cfg.dics.keepcsd = 'no'; cfg.dics.lambda = '5%'; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_DICS_keepnothing_rawtrial(data, grid, headmodel) cfg = []; cfg.method = 'dics'; cfg.headmodel = headmodel; cfg.channel = 'MEG'; cfg.grid = grid; cfg.frequency = 10; cfg.latency = 0.5; cfg.keeptrials = 'no'; cfg.dics.projectnoise = 'no'; cfg.dics.feedback = 'none'; % dics options cfg.dics.keepfilter = 'no'; cfg.dics.keepleadfield = 'no'; cfg.dics.keepcsd = 'no'; cfg.dics.lambda = '5%'; % get filter tmp = sourceanalysis_DICS_keepall(data, grid, headmodel); cfg.rawtrial = 'yes'; cfg.grid.filter = tmp.avg.filter; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_DICS_refdip(data, grid, headmodel) cfg = []; cfg.method = 'dics'; cfg.headmodel = headmodel; cfg.channel = 'MEG'; cfg.grid = grid; cfg.frequency = 10; cfg.latency = 0.5; cfg.dics.refdip = [2 5 9]; cfg.dics.keepcsd = 'yes'; cfg.dics.feedback = 'none'; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_DICS_refchan(data, grid, headmodel) cfg = []; cfg.method = 'dics'; cfg.headmodel = headmodel; cfg.channel = 'MEG'; cfg.grid = grid; cfg.frequency = 10; cfg.latency = 0.5; if numel(data.label)<40 cfg.refchan = data.label{5}; else cfg.refchan = data.label{40}; end cfg.dics.keepcsd = 'yes'; cfg.dics.feedback = 'none'; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_DICS_realfilter(data, grid, headmodel) cfg = []; cfg.method = 'dics'; cfg.headmodel = headmodel; cfg.channel = 'MEG'; cfg.grid = grid; cfg.frequency = 10; cfg.latency = 0.5; cfg.dics.realfilter = 'yes'; cfg.dics.keepfilter = 'yes'; cfg.dics.feedback = 'none'; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_DICS_fixedori(data, grid, headmodel) cfg = []; cfg.method = 'dics'; cfg.headmodel = headmodel; cfg.channel = 'MEG'; cfg.grid = grid; cfg.frequency = 10; cfg.latency = 0.5; cfg.dics.fixedori = 'yes'; cfg.dics.feedback = 'none'; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_PCC_keepall(data, grid, headmodel) % do PCC cfg = []; cfg.method = 'pcc'; cfg.pcc.keepfilter = 'yes'; cfg.pcc.keepleadfield = 'yes'; cfg.pcc.keepcsd = 'yes'; cfg.pcc.keepmom = 'yes'; cfg.pcc.lambda = '5%'; cfg.channel = 'MEG'; cfg.frequency = 10; cfg.latency = 0.5; cfg.headmodel = headmodel; cfg.grid = grid; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_PCC_keepall_rawtrial(data, grid, headmodel) % do PCC cfg = []; cfg.method = 'pcc'; cfg.pcc.keepfilter = 'yes'; cfg.pcc.keepleadfield = 'yes'; cfg.pcc.keepcsd = 'yes'; cfg.pcc.keepmom = 'yes'; cfg.pcc.lambda = '5%'; cfg.channel = 'MEG'; cfg.frequency = 10; cfg.latency = 0.5; cfg.headmodel = headmodel; cfg.grid = grid; tmp = ft_sourceanalysis(cfg, data); % get filter tmp = sourceanalysis_PCC_keepall(data, grid, headmodel); cfg.rawtrial = 'yes'; cfg.grid.filter = tmp.avg.filter; cfg.pcc.feedback = 'none'; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_PCC_keepnothing(data, grid, headmodel) % do PCC cfg = []; cfg.method = 'pcc'; cfg.pcc.keepfilter = 'no'; cfg.pcc.keepleadfield = 'no'; cfg.pcc.keepcsd = 'no'; cfg.pcc.keepmom = 'no'; cfg.pcc.lambda = '5%'; cfg.channel = 'MEG'; cfg.frequency = 10; cfg.latency = 0.5; cfg.headmodel = headmodel; cfg.grid = grid; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_PCC_keepnothing_rawtrial(data, grid, headmodel) % do PCC cfg = []; cfg.method = 'pcc'; cfg.pcc.keepfilter = 'no'; cfg.pcc.keepleadfield = 'no'; cfg.pcc.keepcsd = 'no'; cfg.pcc.keepmom = 'no'; cfg.pcc.lambda = '5%'; cfg.channel = 'MEG'; cfg.frequency = 10; cfg.latency = 0.5; cfg.headmodel = headmodel; cfg.grid = grid; tmp = ft_sourceanalysis(cfg, data); % get filter tmp = sourceanalysis_PCC_keepall(data, grid, headmodel); cfg.rawtrial = 'yes'; cfg.grid.filter = tmp.avg.filter; cfg.pcc.feedback = 'none'; source = ft_sourceanalysis(cfg, data); function source = sourceanalysis_PCC_refdip(data, grid, headmodel) % do PCC cfg = []; cfg.method = 'pcc'; cfg.channel = 'MEG'; cfg.frequency = 10; cfg.latency = 0.5; cfg.headmodel = headmodel; cfg.grid = grid; cfg.refdip = [2 5 9]; %cfg.keepcsd = 'yes'; % keepcsd is ALWAYS ON with PCC source = ft_sourceanalysis(cfg, data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % subfunction that define the permissive combinations of options function combination = test_ft_sourceanalysis_combinations_allowed combination = { 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_keepall' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_keepall_rawtrial' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_keepnothing' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_keepnothing_rawtrial' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_refdip' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_refchan' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_realfilter' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_fixedori' 'sheet' 'freq_mtmfft_fourier_trl' 'MNE_keepall' 'sheet' 'freq_mtmfft_fourier_trl' 'MNE_keepnothing' 'sheet' 'freq_mtmfft_fourier_trl' 'MNE_keepall_rawtrial' 'sheet' 'freq_mtmfft_fourier_trl' 'MNE_keepnothing_rawtrial' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_keepall' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_keepall_rawtrial' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_keepnothing' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_keepnothing_rawtrial' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_refdip' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_refchan' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_realfilter' 'sheet' 'freq_mtmfft_fourier_trl' 'DICS_fixedori' 'sheet' 'freq_mtmfft_fourier_trl' 'PCC_keepall' %'sheet' 'freq_mtmfft_fourier_trl' 'PCC_keepall_rawtrial' 'sheet' 'freq_mtmfft_fourier_trl' 'PCC_keepnothing' %'sheet' 'freq_mtmfft_fourier_trl' 'PCC_keepnothing_rawtrial' 'sheet' 'freq_mtmfft_fourier_trl' 'PCC_refdip' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_keepall' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_keepall_rawtrial' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_keepnothing' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_keepnothing_rawtrial' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_refdip' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_refchan' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_realfilter' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_fixedori' 'sheet' 'freq_mtmconvol_fourier_trl' 'MNE_keepall' 'sheet' 'freq_mtmconvol_fourier_trl' 'MNE_keepnothing' 'sheet' 'freq_mtmconvol_fourier_trl' 'MNE_keepall_rawtrial' 'sheet' 'freq_mtmconvol_fourier_trl' 'MNE_keepnothing_rawtrial' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_keepall' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_keepall_rawtrial' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_keepnothing' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_keepnothing_rawtrial' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_refdip' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_refchan' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_realfilter' 'sheet' 'freq_mtmconvol_fourier_trl' 'DICS_fixedori' 'sheet' 'freq_mtmconvol_fourier_trl' 'PCC_keepall' %'sheet' 'freq_mtmconvol_fourier_trl' 'PCC_keepall_rawtrial' 'sheet' 'freq_mtmconvol_fourier_trl' 'PCC_keepnothing' %'sheet' 'freq_mtmconvol_fourier_trl' 'PCC_keepnothing_rawtrial' 'sheet' 'freq_mtmconvol_fourier_trl' 'PCC_refdip' % 'sheet' 'freq_mtmfft_trl' 'DICS_keepall' % 'sheet' 'freq_mtmfft_trl' 'DICS_keepall_rawtrial' % 'sheet' 'freq_mtmfft_trl' 'DICS_keepnothing' % 'sheet' 'freq_mtmfft_trl' 'DICS_keepnothing_rawtrial' % 'sheet' 'freq_mtmfft_trl' 'DICS_refdip' % 'sheet' 'freq_mtmfft_trl' 'DICS_refchan' % 'sheet' 'freq_mtmfft_trl' 'DICS_realfilter' % 'sheet' 'freq_mtmfft_trl' 'DICS_fixedori' % 'sheet' 'freq_mtmfft_trl' 'MNE_keepall' % 'sheet' 'freq_mtmfft_trl' 'MNE_keepnothing' % 'sheet' 'freq_mtmfft_trl' 'MNE_keepall_rawtrial' % 'sheet' 'freq_mtmfft_trl' 'MNE_keepnothing_rawtrial' % 'sheet' 'freq_mtmfft_trl' 'DICS_keepall' % 'sheet' 'freq_mtmfft_trl' 'DICS_keepall_rawtrial' % 'sheet' 'freq_mtmfft_trl' 'DICS_keepnothing' % 'sheet' 'freq_mtmfft_trl' 'DICS_keepnothing_rawtrial' % 'sheet' 'freq_mtmfft_trl' 'DICS_refdip' % 'sheet' 'freq_mtmfft_trl' 'DICS_refchan' % 'sheet' 'freq_mtmfft_trl' 'DICS_realfilter' % 'sheet' 'freq_mtmfft_trl' 'DICS_fixedori' % 'sheet' 'freq_mtmfft_trl' 'PCC_keepall' % 'sheet' 'freq_mtmfft_trl' 'PCC_keepall_rawtrial' % 'sheet' 'freq_mtmfft_trl' 'PCC_keepnothing' % 'sheet' 'freq_mtmfft_trl' 'PCC_keepnothing_rawtrial' % 'sheet' 'freq_mtmfft_trl' 'PCC_refdip' % 'sheet' 'freq_mtmfft' 'DICS_keepall' % 'sheet' 'freq_mtmfft' 'DICS_keepall_rawtrial' % 'sheet' 'freq_mtmfft' 'DICS_keepnothing' % 'sheet' 'freq_mtmfft' 'DICS_keepnothing_rawtrial' % 'sheet' 'freq_mtmfft' 'DICS_refdip' % 'sheet' 'freq_mtmfft' 'DICS_refchan' % 'sheet' 'freq_mtmfft' 'DICS_realfilter' % 'sheet' 'freq_mtmfft' 'DICS_fixedori' % 'sheet' 'freq_mtmfft' 'MNE_keepall' % 'sheet' 'freq_mtmfft' 'MNE_keepnothing' % 'sheet' 'freq_mtmfft' 'MNE_keepall_rawtrial' % 'sheet' 'freq_mtmfft' 'MNE_keepnothing_rawtrial' % 'sheet' 'freq_mtmfft' 'DICS_keepall' % 'sheet' 'freq_mtmfft' 'DICS_keepall_rawtrial' % 'sheet' 'freq_mtmfft' 'DICS_keepnothing' % 'sheet' 'freq_mtmfft' 'DICS_keepnothing_rawtrial' % 'sheet' 'freq_mtmfft' 'DICS_refdip' % 'sheet' 'freq_mtmfft' 'DICS_refchan' % 'sheet' 'freq_mtmfft' 'DICS_realfilter' % 'sheet' 'freq_mtmfft' 'DICS_fixedori' % 'sheet' 'freq_mtmfft' 'PCC_keepall' % 'sheet' 'freq_mtmfft' 'PCC_keepall_rawtrial' % 'sheet' 'freq_mtmfft' 'PCC_keepnothing' % 'sheet' 'freq_mtmfft' 'PCC_keepnothing_rawtrial' % 'sheet' 'freq_mtmfft' 'PCC_refdip' % 'sheet' 'freq_mtmconvol_trl' 'DICS_keepall' % 'sheet' 'freq_mtmconvol_trl' 'DICS_keepall_rawtrial' % 'sheet' 'freq_mtmconvol_trl' 'DICS_keepnothing' % 'sheet' 'freq_mtmconvol_trl' 'DICS_keepnothing_rawtrial' % 'sheet' 'freq_mtmconvol_trl' 'DICS_refdip' % 'sheet' 'freq_mtmconvol_trl' 'DICS_refchan' % 'sheet' 'freq_mtmconvol_trl' 'DICS_realfilter' % 'sheet' 'freq_mtmconvol_trl' 'DICS_fixedori' % 'sheet' 'freq_mtmconvol_trl' 'MNE_keepall' % 'sheet' 'freq_mtmconvol_trl' 'MNE_keepnothing' % 'sheet' 'freq_mtmconvol_trl' 'MNE_keepall_rawtrial' % 'sheet' 'freq_mtmconvol_trl' 'MNE_keepnothing_rawtrial' % 'sheet' 'freq_mtmconvol_trl' 'DICS_keepall' % 'sheet' 'freq_mtmconvol_trl' 'DICS_keepall_rawtrial' % 'sheet' 'freq_mtmconvol_trl' 'DICS_keepnothing' % 'sheet' 'freq_mtmconvol_trl' 'DICS_keepnothing_rawtrial' % 'sheet' 'freq_mtmconvol_trl' 'DICS_refdip' % 'sheet' 'freq_mtmconvol_trl' 'DICS_refchan' % 'sheet' 'freq_mtmconvol_trl' 'DICS_realfilter' % 'sheet' 'freq_mtmconvol_trl' 'DICS_fixedori' % 'sheet' 'freq_mtmconvol_trl' 'PCC_keepall' % 'sheet' 'freq_mtmconvol_trl' 'PCC_keepall_rawtrial' % 'sheet' 'freq_mtmconvol_trl' 'PCC_keepnothing' % 'sheet' 'freq_mtmconvol_trl' 'PCC_keepnothing_rawtrial' % 'sheet' 'freq_mtmconvol_trl' 'PCC_refdip' % 'sheet' 'freq_mtmconvol' 'DICS_keepall' % 'sheet' 'freq_mtmconvol' 'DICS_keepall_rawtrial' % 'sheet' 'freq_mtmconvol' 'DICS_keepnothing' % 'sheet' 'freq_mtmconvol' 'DICS_keepnothing_rawtrial' % 'sheet' 'freq_mtmconvol' 'DICS_refdip' % 'sheet' 'freq_mtmconvol' 'DICS_refchan' % 'sheet' 'freq_mtmconvol' 'DICS_realfilter' % 'sheet' 'freq_mtmconvol' 'DICS_fixedori' % 'sheet' 'freq_mtmconvol' 'MNE_keepall' % 'sheet' 'freq_mtmconvol' 'MNE_keepnothing' % 'sheet' 'freq_mtmconvol' 'MNE_keepall_rawtrial' % 'sheet' 'freq_mtmconvol' 'MNE_keepnothing_rawtrial' % 'sheet' 'freq_mtmconvol' 'DICS_keepall' % 'sheet' 'freq_mtmconvol' 'DICS_keepall_rawtrial' % 'sheet' 'freq_mtmconvol' 'DICS_keepnothing' % 'sheet' 'freq_mtmconvol' 'DICS_keepnothing_rawtrial' % 'sheet' 'freq_mtmconvol' 'DICS_refdip' % 'sheet' 'freq_mtmconvol' 'DICS_refchan' % 'sheet' 'freq_mtmconvol' 'DICS_realfilter' % 'sheet' 'freq_mtmconvol' 'DICS_fixedori' % 'sheet' 'freq_mtmconvol' 'PCC_keepall' % 'sheet' 'freq_mtmconvol' 'PCC_keepall_rawtrial' % 'sheet' 'freq_mtmconvol' 'PCC_keepnothing' % 'sheet' 'freq_mtmconvol' 'PCC_keepnothing_rawtrial' % 'sheet' 'freq_mtmconvol' 'PCC_refdip' 'sheet' 'timelock' 'MNE_keepall' 'sheet' 'timelock' 'MNE_keepnothing' % 'sheet' 'timelock' 'MNE_keepall_rawtrial' % 'sheet' 'timelock' 'MNE_keepnothing_rawtrial' 'sheet' 'timelock' 'LCMV_keepall' 'sheet' 'timelock' 'LCMV_keepnothing' % 'sheet' 'timelock' 'LCMV_keepall_rawtrial' % 'sheet' 'timelock' 'LCMV_keepnothing_rawtrial' 'sheet' 'timelock_trl' 'MNE_keepall' 'sheet' 'timelock_trl' 'MNE_keepnothing' 'sheet' 'timelock_trl' 'MNE_keepall_rawtrial' 'sheet' 'timelock_trl' 'MNE_keepnothing_rawtrial' 'sheet' 'timelock_trl' 'LCMV_keepall' 'sheet' 'timelock_trl' 'LCMV_keepnothing' 'sheet' 'timelock_trl' 'LCMV_keepall_rawtrial' 'sheet' 'timelock_trl' 'LCMV_keepnothing_rawtrial' 'sheet' 'timelock_cov' 'MNE_keepall' 'sheet' 'timelock_cov' 'MNE_keepnothing' % 'sheet' 'timelock_cov' 'MNE_keepall_rawtrial' % 'sheet' 'timelock_cov' 'MNE_keepnothing_rawtrial' 'sheet' 'timelock_cov' 'LCMV_keepall' 'sheet' 'timelock_cov' 'LCMV_keepnothing' % 'sheet' 'timelock_cov' 'LCMV_keepall_rawtrial' % 'sheet' 'timelock_cov' 'LCMV_keepnothing_rawtrial' 'sheet' 'timelock_cov_trl' 'MNE_keepall' 'sheet' 'timelock_cov_trl' 'MNE_keepnothing' 'sheet' 'timelock_cov_trl' 'MNE_keepall_rawtrial' 'sheet' 'timelock_cov_trl' 'MNE_keepnothing_rawtrial' 'sheet' 'timelock_cov_trl' 'LCMV_keepall' 'sheet' 'timelock_cov_trl' 'LCMV_keepnothing' 'sheet' 'timelock_cov_trl' 'LCMV_keepall_rawtrial' 'sheet' 'timelock_cov_trl' 'LCMV_keepnothing_rawtrial' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_keepall' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_keepall_rawtrial' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_keepnothing' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_keepnothing_rawtrial' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_refdip' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_refchan' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_realfilter' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_fixedori' 'grid' 'freq_mtmfft_fourier_trl' 'MNE_keepall' 'grid' 'freq_mtmfft_fourier_trl' 'MNE_keepnothing' 'grid' 'freq_mtmfft_fourier_trl' 'MNE_keepall_rawtrial' 'grid' 'freq_mtmfft_fourier_trl' 'MNE_keepnothing_rawtrial' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_keepall' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_keepall_rawtrial' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_keepnothing' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_keepnothing_rawtrial' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_refdip' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_refchan' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_realfilter' 'grid' 'freq_mtmfft_fourier_trl' 'DICS_fixedori' 'grid' 'freq_mtmfft_fourier_trl' 'PCC_keepall' %'grid' 'freq_mtmfft_fourier_trl' 'PCC_keepall_rawtrial' 'grid' 'freq_mtmfft_fourier_trl' 'PCC_keepnothing' %'grid' 'freq_mtmfft_fourier_trl' 'PCC_keepnothing_rawtrial' 'grid' 'freq_mtmfft_fourier_trl' 'PCC_refdip' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_keepall' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_keepall_rawtrial' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_keepnothing' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_keepnothing_rawtrial' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_refdip' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_refchan' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_realfilter' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_fixedori' 'grid' 'freq_mtmconvol_fourier_trl' 'MNE_keepall' 'grid' 'freq_mtmconvol_fourier_trl' 'MNE_keepnothing' 'grid' 'freq_mtmconvol_fourier_trl' 'MNE_keepall_rawtrial' 'grid' 'freq_mtmconvol_fourier_trl' 'MNE_keepnothing_rawtrial' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_keepall' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_keepall_rawtrial' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_keepnothing' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_keepnothing_rawtrial' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_refdip' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_refchan' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_realfilter' 'grid' 'freq_mtmconvol_fourier_trl' 'DICS_fixedori' 'grid' 'freq_mtmconvol_fourier_trl' 'PCC_keepall' %'grid' 'freq_mtmconvol_fourier_trl' 'PCC_keepall_rawtrial' 'grid' 'freq_mtmconvol_fourier_trl' 'PCC_keepnothing' %'grid' 'freq_mtmconvol_fourier_trl' 'PCC_keepnothing_rawtrial' 'grid' 'freq_mtmconvol_fourier_trl' 'PCC_refdip' % 'grid' 'freq_mtmfft_trl' 'DICS_keepall' % 'grid' 'freq_mtmfft_trl' 'DICS_keepall_rawtrial' % 'grid' 'freq_mtmfft_trl' 'DICS_keepnothing' % 'grid' 'freq_mtmfft_trl' 'DICS_keepnothing_rawtrial' % 'grid' 'freq_mtmfft_trl' 'DICS_refdip' % 'grid' 'freq_mtmfft_trl' 'DICS_refchan' % 'grid' 'freq_mtmfft_trl' 'DICS_realfilter' % 'grid' 'freq_mtmfft_trl' 'DICS_fixedori' % 'grid' 'freq_mtmfft_trl' 'MNE_keepall' % 'grid' 'freq_mtmfft_trl' 'MNE_keepnothing' % 'grid' 'freq_mtmfft_trl' 'MNE_keepall_rawtrial' % 'grid' 'freq_mtmfft_trl' 'MNE_keepnothing_rawtrial' % 'grid' 'freq_mtmfft_trl' 'DICS_keepall' % 'grid' 'freq_mtmfft_trl' 'DICS_keepall_rawtrial' % 'grid' 'freq_mtmfft_trl' 'DICS_keepnothing' % 'grid' 'freq_mtmfft_trl' 'DICS_keepnothing_rawtrial' % 'grid' 'freq_mtmfft_trl' 'DICS_refdip' % 'grid' 'freq_mtmfft_trl' 'DICS_refchan' % 'grid' 'freq_mtmfft_trl' 'DICS_realfilter' % 'grid' 'freq_mtmfft_trl' 'DICS_fixedori' % 'grid' 'freq_mtmfft_trl' 'PCC_keepall' % 'grid' 'freq_mtmfft_trl' 'PCC_keepall_rawtrial' % 'grid' 'freq_mtmfft_trl' 'PCC_keepnothing' % 'grid' 'freq_mtmfft_trl' 'PCC_keepnothing_rawtrial' % 'grid' 'freq_mtmfft_trl' 'PCC_refdip' % 'grid' 'freq_mtmfft' 'DICS_keepall' % 'grid' 'freq_mtmfft' 'DICS_keepall_rawtrial' % 'grid' 'freq_mtmfft' 'DICS_keepnothing' % 'grid' 'freq_mtmfft' 'DICS_keepnothing_rawtrial' % 'grid' 'freq_mtmfft' 'DICS_refdip' % 'grid' 'freq_mtmfft' 'DICS_refchan' % 'grid' 'freq_mtmfft' 'DICS_realfilter' % 'grid' 'freq_mtmfft' 'DICS_fixedori' % 'grid' 'freq_mtmfft' 'MNE_keepall' % 'grid' 'freq_mtmfft' 'MNE_keepnothing' % 'grid' 'freq_mtmfft' 'MNE_keepall_rawtrial' % 'grid' 'freq_mtmfft' 'MNE_keepnothing_rawtrial' % 'grid' 'freq_mtmfft' 'DICS_keepall' % 'grid' 'freq_mtmfft' 'DICS_keepall_rawtrial' % 'grid' 'freq_mtmfft' 'DICS_keepnothing' % 'grid' 'freq_mtmfft' 'DICS_keepnothing_rawtrial' % 'grid' 'freq_mtmfft' 'DICS_refdip' % 'grid' 'freq_mtmfft' 'DICS_refchan' % 'grid' 'freq_mtmfft' 'DICS_realfilter' % 'grid' 'freq_mtmfft' 'DICS_fixedori' % 'grid' 'freq_mtmfft' 'PCC_keepall' % 'grid' 'freq_mtmfft' 'PCC_keepall_rawtrial' % 'grid' 'freq_mtmfft' 'PCC_keepnothing' % 'grid' 'freq_mtmfft' 'PCC_keepnothing_rawtrial' % 'grid' 'freq_mtmfft' 'PCC_refdip' % 'grid' 'freq_mtmconvol_trl' 'DICS_keepall' % 'grid' 'freq_mtmconvol_trl' 'DICS_keepall_rawtrial' % 'grid' 'freq_mtmconvol_trl' 'DICS_keepnothing' % 'grid' 'freq_mtmconvol_trl' 'DICS_keepnothing_rawtrial' % 'grid' 'freq_mtmconvol_trl' 'DICS_refdip' % 'grid' 'freq_mtmconvol_trl' 'DICS_refchan' % 'grid' 'freq_mtmconvol_trl' 'DICS_realfilter' % 'grid' 'freq_mtmconvol_trl' 'DICS_fixedori' % 'grid' 'freq_mtmconvol_trl' 'MNE_keepall' % 'grid' 'freq_mtmconvol_trl' 'MNE_keepnothing' % 'grid' 'freq_mtmconvol_trl' 'MNE_keepall_rawtrial' % 'grid' 'freq_mtmconvol_trl' 'MNE_keepnothing_rawtrial' % 'grid' 'freq_mtmconvol_trl' 'DICS_keepall' % 'grid' 'freq_mtmconvol_trl' 'DICS_keepall_rawtrial' % 'grid' 'freq_mtmconvol_trl' 'DICS_keepnothing' % 'grid' 'freq_mtmconvol_trl' 'DICS_keepnothing_rawtrial' % 'grid' 'freq_mtmconvol_trl' 'DICS_refdip' % 'grid' 'freq_mtmconvol_trl' 'DICS_refchan' % 'grid' 'freq_mtmconvol_trl' 'DICS_realfilter' % 'grid' 'freq_mtmconvol_trl' 'DICS_fixedori' % 'grid' 'freq_mtmconvol_trl' 'PCC_keepall' % 'grid' 'freq_mtmconvol_trl' 'PCC_keepall_rawtrial' % 'grid' 'freq_mtmconvol_trl' 'PCC_keepnothing' % 'grid' 'freq_mtmconvol_trl' 'PCC_keepnothing_rawtrial' % 'grid' 'freq_mtmconvol_trl' 'PCC_refdip' % 'grid' 'freq_mtmconvol' 'DICS_keepall' % 'grid' 'freq_mtmconvol' 'DICS_keepall_rawtrial' % 'grid' 'freq_mtmconvol' 'DICS_keepnothing' % 'grid' 'freq_mtmconvol' 'DICS_keepnothing_rawtrial' % 'grid' 'freq_mtmconvol' 'DICS_refdip' % 'grid' 'freq_mtmconvol' 'DICS_refchan' % 'grid' 'freq_mtmconvol' 'DICS_realfilter' % 'grid' 'freq_mtmconvol' 'DICS_fixedori' % 'grid' 'freq_mtmconvol' 'MNE_keepall' % 'grid' 'freq_mtmconvol' 'MNE_keepnothing' % 'grid' 'freq_mtmconvol' 'MNE_keepall_rawtrial' % 'grid' 'freq_mtmconvol' 'MNE_keepnothing_rawtrial' % 'grid' 'freq_mtmconvol' 'DICS_keepall' % 'grid' 'freq_mtmconvol' 'DICS_keepall_rawtrial' % 'grid' 'freq_mtmconvol' 'DICS_keepnothing' % 'grid' 'freq_mtmconvol' 'DICS_keepnothing_rawtrial' % 'grid' 'freq_mtmconvol' 'DICS_refdip' % 'grid' 'freq_mtmconvol' 'DICS_refchan' % 'grid' 'freq_mtmconvol' 'DICS_realfilter' % 'grid' 'freq_mtmconvol' 'DICS_fixedori' % 'grid' 'freq_mtmconvol' 'PCC_keepall' % 'grid' 'freq_mtmconvol' 'PCC_keepall_rawtrial' % 'grid' 'freq_mtmconvol' 'PCC_keepnothing' % 'grid' 'freq_mtmconvol' 'PCC_keepnothing_rawtrial' % 'grid' 'freq_mtmconvol' 'PCC_refdip' 'grid' 'timelock' 'MNE_keepall' 'grid' 'timelock' 'MNE_keepnothing' % 'grid' 'timelock' 'MNE_keepall_rawtrial' % 'grid' 'timelock' 'MNE_keepnothing_rawtrial' 'grid' 'timelock' 'LCMV_keepall' 'grid' 'timelock' 'LCMV_keepnothing' % 'grid' 'timelock' 'LCMV_keepall_rawtrial' % 'grid' 'timelock' 'LCMV_keepnothing_rawtrial' 'grid' 'timelock_trl' 'MNE_keepall' 'grid' 'timelock_trl' 'MNE_keepnothing' 'grid' 'timelock_trl' 'MNE_keepall_rawtrial' 'grid' 'timelock_trl' 'MNE_keepnothing_rawtrial' 'grid' 'timelock_trl' 'LCMV_keepall' 'grid' 'timelock_trl' 'LCMV_keepnothing' 'grid' 'timelock_trl' 'LCMV_keepall_rawtrial' 'grid' 'timelock_trl' 'LCMV_keepnothing_rawtrial' 'grid' 'timelock_cov' 'MNE_keepall' 'grid' 'timelock_cov' 'MNE_keepnothing' % 'grid' 'timelock_cov' 'MNE_keepall_rawtrial' % 'grid' 'timelock_cov' 'MNE_keepnothing_rawtrial' 'grid' 'timelock_cov' 'LCMV_keepall' 'grid' 'timelock_cov' 'LCMV_keepnothing' % 'grid' 'timelock_cov' 'LCMV_keepall_rawtrial' % 'grid' 'timelock_cov' 'LCMV_keepnothing_rawtrial' 'grid' 'timelock_cov_trl' 'MNE_keepall' 'grid' 'timelock_cov_trl' 'MNE_keepnothing' 'grid' 'timelock_cov_trl' 'MNE_keepall_rawtrial' 'grid' 'timelock_cov_trl' 'MNE_keepnothing_rawtrial' 'grid' 'timelock_cov_trl' 'LCMV_keepall' 'grid' 'timelock_cov_trl' 'LCMV_keepnothing' 'grid' 'timelock_cov_trl' 'LCMV_keepall_rawtrial' 'grid' 'timelock_cov_trl' 'LCMV_keepnothing_rawtrial' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_keepall' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_keepall_rawtrial' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_keepnothing' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_keepnothing_rawtrial' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_refdip' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_refchan' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_realfilter' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_fixedori' 'roi' 'freq_mtmfft_fourier_trl' 'MNE_keepall' 'roi' 'freq_mtmfft_fourier_trl' 'MNE_keepnothing' 'roi' 'freq_mtmfft_fourier_trl' 'MNE_keepall_rawtrial' 'roi' 'freq_mtmfft_fourier_trl' 'MNE_keepnothing_rawtrial' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_keepall' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_keepall_rawtrial' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_keepnothing' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_keepnothing_rawtrial' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_refdip' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_refchan' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_realfilter' 'roi' 'freq_mtmfft_fourier_trl' 'DICS_fixedori' 'roi' 'freq_mtmfft_fourier_trl' 'PCC_keepall' %'roi' 'freq_mtmfft_fourier_trl' 'PCC_keepall_rawtrial' 'roi' 'freq_mtmfft_fourier_trl' 'PCC_keepnothing' %'roi' 'freq_mtmfft_fourier_trl' 'PCC_keepnothing_rawtrial' 'roi' 'freq_mtmfft_fourier_trl' 'PCC_refdip' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_keepall' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_keepall_rawtrial' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_keepnothing' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_keepnothing_rawtrial' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_refdip' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_refchan' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_realfilter' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_fixedori' 'roi' 'freq_mtmconvol_fourier_trl' 'MNE_keepall' 'roi' 'freq_mtmconvol_fourier_trl' 'MNE_keepnothing' 'roi' 'freq_mtmconvol_fourier_trl' 'MNE_keepall_rawtrial' 'roi' 'freq_mtmconvol_fourier_trl' 'MNE_keepnothing_rawtrial' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_keepall' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_keepall_rawtrial' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_keepnothing' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_keepnothing_rawtrial' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_refdip' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_refchan' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_realfilter' 'roi' 'freq_mtmconvol_fourier_trl' 'DICS_fixedori' 'roi' 'freq_mtmconvol_fourier_trl' 'PCC_keepall' %'roi' 'freq_mtmconvol_fourier_trl' 'PCC_keepall_rawtrial' 'roi' 'freq_mtmconvol_fourier_trl' 'PCC_keepnothing' %'roi' 'freq_mtmconvol_fourier_trl' 'PCC_keepnothing_rawtrial' 'roi' 'freq_mtmconvol_fourier_trl' 'PCC_refdip' % 'roi' 'freq_mtmfft_trl' 'DICS_keepall' % 'roi' 'freq_mtmfft_trl' 'DICS_keepall_rawtrial' % 'roi' 'freq_mtmfft_trl' 'DICS_keepnothing' % 'roi' 'freq_mtmfft_trl' 'DICS_keepnothing_rawtrial' % 'roi' 'freq_mtmfft_trl' 'DICS_refdip' % 'roi' 'freq_mtmfft_trl' 'DICS_refchan' % 'roi' 'freq_mtmfft_trl' 'DICS_realfilter' % 'roi' 'freq_mtmfft_trl' 'DICS_fixedori' % 'roi' 'freq_mtmfft_trl' 'MNE_keepall' % 'roi' 'freq_mtmfft_trl' 'MNE_keepnothing' % 'roi' 'freq_mtmfft_trl' 'MNE_keepall_rawtrial' % 'roi' 'freq_mtmfft_trl' 'MNE_keepnothing_rawtrial' % 'roi' 'freq_mtmfft_trl' 'DICS_keepall' % 'roi' 'freq_mtmfft_trl' 'DICS_keepall_rawtrial' % 'roi' 'freq_mtmfft_trl' 'DICS_keepnothing' % 'roi' 'freq_mtmfft_trl' 'DICS_keepnothing_rawtrial' % 'roi' 'freq_mtmfft_trl' 'DICS_refdip' % 'roi' 'freq_mtmfft_trl' 'DICS_refchan' % 'roi' 'freq_mtmfft_trl' 'DICS_realfilter' % 'roi' 'freq_mtmfft_trl' 'DICS_fixedori' % 'roi' 'freq_mtmfft_trl' 'PCC_keepall' % 'roi' 'freq_mtmfft_trl' 'PCC_keepall_rawtrial' % 'roi' 'freq_mtmfft_trl' 'PCC_keepnothing' % 'roi' 'freq_mtmfft_trl' 'PCC_keepnothing_rawtrial' % 'roi' 'freq_mtmfft_trl' 'PCC_refdip' % 'roi' 'freq_mtmfft' 'DICS_keepall' % 'roi' 'freq_mtmfft' 'DICS_keepall_rawtrial' % 'roi' 'freq_mtmfft' 'DICS_keepnothing' % 'roi' 'freq_mtmfft' 'DICS_keepnothing_rawtrial' % 'roi' 'freq_mtmfft' 'DICS_refdip' % 'roi' 'freq_mtmfft' 'DICS_refchan' % 'roi' 'freq_mtmfft' 'DICS_realfilter' % 'roi' 'freq_mtmfft' 'DICS_fixedori' % 'roi' 'freq_mtmfft' 'MNE_keepall' % 'roi' 'freq_mtmfft' 'MNE_keepnothing' % 'roi' 'freq_mtmfft' 'MNE_keepall_rawtrial' % 'roi' 'freq_mtmfft' 'MNE_keepnothing_rawtrial' % 'roi' 'freq_mtmfft' 'DICS_keepall' % 'roi' 'freq_mtmfft' 'DICS_keepall_rawtrial' % 'roi' 'freq_mtmfft' 'DICS_keepnothing' % 'roi' 'freq_mtmfft' 'DICS_keepnothing_rawtrial' % 'roi' 'freq_mtmfft' 'DICS_refdip' % 'roi' 'freq_mtmfft' 'DICS_refchan' % 'roi' 'freq_mtmfft' 'DICS_realfilter' % 'roi' 'freq_mtmfft' 'DICS_fixedori' % 'roi' 'freq_mtmfft' 'PCC_keepall' % 'roi' 'freq_mtmfft' 'PCC_keepall_rawtrial' % 'roi' 'freq_mtmfft' 'PCC_keepnothing' % 'roi' 'freq_mtmfft' 'PCC_keepnothing_rawtrial' % 'roi' 'freq_mtmfft' 'PCC_refdip' % 'roi' 'freq_mtmconvol_trl' 'DICS_keepall' % 'roi' 'freq_mtmconvol_trl' 'DICS_keepall_rawtrial' % 'roi' 'freq_mtmconvol_trl' 'DICS_keepnothing' % 'roi' 'freq_mtmconvol_trl' 'DICS_keepnothing_rawtrial' % 'roi' 'freq_mtmconvol_trl' 'DICS_refdip' % 'roi' 'freq_mtmconvol_trl' 'DICS_refchan' % 'roi' 'freq_mtmconvol_trl' 'DICS_realfilter' % 'roi' 'freq_mtmconvol_trl' 'DICS_fixedori' % 'roi' 'freq_mtmconvol_trl' 'MNE_keepall' % 'roi' 'freq_mtmconvol_trl' 'MNE_keepnothing' % 'roi' 'freq_mtmconvol_trl' 'MNE_keepall_rawtrial' % 'roi' 'freq_mtmconvol_trl' 'MNE_keepnothing_rawtrial' % 'roi' 'freq_mtmconvol_trl' 'DICS_keepall' % 'roi' 'freq_mtmconvol_trl' 'DICS_keepall_rawtrial' % 'roi' 'freq_mtmconvol_trl' 'DICS_keepnothing' % 'roi' 'freq_mtmconvol_trl' 'DICS_keepnothing_rawtrial' % 'roi' 'freq_mtmconvol_trl' 'DICS_refdip' % 'roi' 'freq_mtmconvol_trl' 'DICS_refchan' % 'roi' 'freq_mtmconvol_trl' 'DICS_realfilter' % 'roi' 'freq_mtmconvol_trl' 'DICS_fixedori' % 'roi' 'freq_mtmconvol_trl' 'PCC_keepall' % 'roi' 'freq_mtmconvol_trl' 'PCC_keepall_rawtrial' % 'roi' 'freq_mtmconvol_trl' 'PCC_keepnothing' % 'roi' 'freq_mtmconvol_trl' 'PCC_keepnothing_rawtrial' % 'roi' 'freq_mtmconvol_trl' 'PCC_refdip' % 'roi' 'freq_mtmconvol' 'DICS_keepall' % 'roi' 'freq_mtmconvol' 'DICS_keepall_rawtrial' % 'roi' 'freq_mtmconvol' 'DICS_keepnothing' % 'roi' 'freq_mtmconvol' 'DICS_keepnothing_rawtrial' % 'roi' 'freq_mtmconvol' 'DICS_refdip' % 'roi' 'freq_mtmconvol' 'DICS_refchan' % 'roi' 'freq_mtmconvol' 'DICS_realfilter' % 'roi' 'freq_mtmconvol' 'DICS_fixedori' % 'roi' 'freq_mtmconvol' 'MNE_keepall' % 'roi' 'freq_mtmconvol' 'MNE_keepnothing' % 'roi' 'freq_mtmconvol' 'MNE_keepall_rawtrial' % 'roi' 'freq_mtmconvol' 'MNE_keepnothing_rawtrial' % 'roi' 'freq_mtmconvol' 'DICS_keepall' % 'roi' 'freq_mtmconvol' 'DICS_keepall_rawtrial' % 'roi' 'freq_mtmconvol' 'DICS_keepnothing' % 'roi' 'freq_mtmconvol' 'DICS_keepnothing_rawtrial' % 'roi' 'freq_mtmconvol' 'DICS_refdip' % 'roi' 'freq_mtmconvol' 'DICS_refchan' % 'roi' 'freq_mtmconvol' 'DICS_realfilter' % 'roi' 'freq_mtmconvol' 'DICS_fixedori' % 'roi' 'freq_mtmconvol' 'PCC_keepall' % 'roi' 'freq_mtmconvol' 'PCC_keepall_rawtrial' % 'roi' 'freq_mtmconvol' 'PCC_keepnothing' % 'roi' 'freq_mtmconvol' 'PCC_keepnothing_rawtrial' % 'roi' 'freq_mtmconvol' 'PCC_refdip' 'roi' 'timelock' 'MNE_keepall' 'roi' 'timelock' 'MNE_keepnothing' % 'roi' 'timelock' 'MNE_keepall_rawtrial' % 'roi' 'timelock' 'MNE_keepnothing_rawtrial' 'roi' 'timelock' 'LCMV_keepall' 'roi' 'timelock' 'LCMV_keepnothing' % 'roi' 'timelock' 'LCMV_keepall_rawtrial' % 'roi' 'timelock' 'LCMV_keepnothing_rawtrial' 'roi' 'timelock_trl' 'MNE_keepall' 'roi' 'timelock_trl' 'MNE_keepnothing' 'roi' 'timelock_trl' 'MNE_keepall_rawtrial' 'roi' 'timelock_trl' 'MNE_keepnothing_rawtrial' 'roi' 'timelock_trl' 'LCMV_keepall' 'roi' 'timelock_trl' 'LCMV_keepnothing' 'roi' 'timelock_trl' 'LCMV_keepall_rawtrial' 'roi' 'timelock_trl' 'LCMV_keepnothing_rawtrial' 'roi' 'timelock_cov' 'MNE_keepall' 'roi' 'timelock_cov' 'MNE_keepnothing' % 'roi' 'timelock_cov' 'MNE_keepall_rawtrial' % 'roi' 'timelock_cov' 'MNE_keepnothing_rawtrial' 'roi' 'timelock_cov' 'LCMV_keepall' 'roi' 'timelock_cov' 'LCMV_keepnothing' % 'roi' 'timelock_cov' 'LCMV_keepall_rawtrial' % 'roi' 'timelock_cov' 'LCMV_keepnothing_rawtrial' 'roi' 'timelock_cov_trl' 'MNE_keepall' 'roi' 'timelock_cov_trl' 'MNE_keepnothing' 'roi' 'timelock_cov_trl' 'MNE_keepall_rawtrial' 'roi' 'timelock_cov_trl' 'MNE_keepnothing_rawtrial' 'roi' 'timelock_cov_trl' 'LCMV_keepall' 'roi' 'timelock_cov_trl' 'LCMV_keepnothing' 'roi' 'timelock_cov_trl' 'LCMV_keepall_rawtrial' 'roi' 'timelock_cov_trl' 'LCMV_keepnothing_rawtrial' }; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % subfunction that defines the forbidden combinations function forbidden_combinations = test_ft_sourceanalysis_combinations_forbidden forbidden_combinations = {'sheet' 'freq_mtmfft_fourier_trl' 'LCMV_keepall' 'sheet' 'freq_mtmfft_fourier_trl' 'LCMV_keepnothing' 'sheet' 'freq_mtmfft_fourier_trl' 'LCMV_keepall_rawtrial' 'sheet' 'freq_mtmfft_fourier_trl' 'LCMV_keepnothing_rawtrial' 'sheet' 'freq_mtmconvol_fourier_trl' 'LCMV_keepall' 'sheet' 'freq_mtmconvol_fourier_trl' 'LCMV_keepnothing' 'sheet' 'freq_mtmconvol_fourier_trl' 'LCMV_keepall_rawtrial' 'sheet' 'freq_mtmconvol_fourier_trl' 'LCMV_keepnothing_rawtrial' 'sheet' 'freq_mtmfft_trl' 'LCMV_keepall' 'sheet' 'freq_mtmfft_trl' 'LCMV_keepnothing' 'sheet' 'freq_mtmfft_trl' 'LCMV_keepall_rawtrial' 'sheet' 'freq_mtmfft_trl' 'LCMV_keepnothing_rawtrial' 'sheet' 'freq_mtmfft' 'LCMV_keepall' 'sheet' 'freq_mtmfft' 'LCMV_keepnothing' 'sheet' 'freq_mtmfft' 'LCMV_keepall_rawtrial' 'sheet' 'freq_mtmfft' 'LCMV_keepnothing_rawtrial' 'sheet' 'freq_mtmconvol_trl' 'LCMV_keepall' 'sheet' 'freq_mtmconvol_trl' 'LCMV_keepnothing' 'sheet' 'freq_mtmconvol_trl' 'LCMV_keepall_rawtrial' 'sheet' 'freq_mtmconvol_trl' 'LCMV_keepnothing_rawtrial' 'sheet' 'freq_mtmconvol' 'LCMV_keepall' 'sheet' 'freq_mtmconvol' 'LCMV_keepnothing' 'sheet' 'freq_mtmconvol' 'LCMV_keepall_rawtrial' 'sheet' 'freq_mtmconvol' 'LCMV_keepnothing_rawtrial' 'sheet' 'timelock' 'DICS_keepall' 'sheet' 'timelock' 'DICS_keepall_rawtrial' 'sheet' 'timelock' 'DICS_keepnothing' 'sheet' 'timelock' 'DICS_keepnothing_rawtrial' 'sheet' 'timelock' 'DICS_refdip' 'sheet' 'timelock' 'DICS_refchan' 'sheet' 'timelock' 'DICS_realfilter' 'sheet' 'timelock' 'DICS_fixedori' 'sheet' 'timelock' 'DICS_keepall' 'sheet' 'timelock' 'DICS_keepall_rawtrial' 'sheet' 'timelock' 'DICS_keepnothing' 'sheet' 'timelock' 'DICS_keepnothing_rawtrial' 'sheet' 'timelock' 'DICS_refdip' 'sheet' 'timelock' 'DICS_refchan' 'sheet' 'timelock' 'DICS_realfilter' 'sheet' 'timelock' 'DICS_fixedori' 'sheet' 'timelock' 'PCC_keepall' 'sheet' 'timelock' 'PCC_keepall_rawtrial' 'sheet' 'timelock' 'PCC_keepnothing' 'sheet' 'timelock' 'PCC_keepnothing_rawtrial' 'sheet' 'timelock' 'PCC_refdip' 'sheet' 'timelock_trl' 'DICS_keepall' 'sheet' 'timelock_trl' 'DICS_keepall_rawtrial' 'sheet' 'timelock_trl' 'DICS_keepnothing' 'sheet' 'timelock_trl' 'DICS_keepnothing_rawtrial' 'sheet' 'timelock_trl' 'DICS_refdip' 'sheet' 'timelock_trl' 'DICS_refchan' 'sheet' 'timelock_trl' 'DICS_realfilter' 'sheet' 'timelock_trl' 'DICS_fixedori' 'sheet' 'timelock_trl' 'DICS_keepall' 'sheet' 'timelock_trl' 'DICS_keepall_rawtrial' 'sheet' 'timelock_trl' 'DICS_keepnothing' 'sheet' 'timelock_trl' 'DICS_keepnothing_rawtrial' 'sheet' 'timelock_trl' 'DICS_refdip' 'sheet' 'timelock_trl' 'DICS_refchan' 'sheet' 'timelock_trl' 'DICS_realfilter' 'sheet' 'timelock_trl' 'DICS_fixedori' 'sheet' 'timelock_trl' 'PCC_keepall' 'sheet' 'timelock_trl' 'PCC_keepall_rawtrial' 'sheet' 'timelock_trl' 'PCC_keepnothing' 'sheet' 'timelock_trl' 'PCC_keepnothing_rawtrial' 'sheet' 'timelock_trl' 'PCC_refdip' 'sheet' 'timelock_cov' 'DICS_keepall' 'sheet' 'timelock_cov' 'DICS_keepall_rawtrial' 'sheet' 'timelock_cov' 'DICS_keepnothing' 'sheet' 'timelock_cov' 'DICS_keepnothing_rawtrial' 'sheet' 'timelock_cov' 'DICS_refdip' 'sheet' 'timelock_cov' 'DICS_refchan' 'sheet' 'timelock_cov' 'DICS_realfilter' 'sheet' 'timelock_cov' 'DICS_fixedori' 'sheet' 'timelock_cov' 'DICS_keepall' 'sheet' 'timelock_cov' 'DICS_keepall_rawtrial' 'sheet' 'timelock_cov' 'DICS_keepnothing' 'sheet' 'timelock_cov' 'DICS_keepnothing_rawtrial' 'sheet' 'timelock_cov' 'DICS_refdip' 'sheet' 'timelock_cov' 'DICS_refchan' 'sheet' 'timelock_cov' 'DICS_realfilter' 'sheet' 'timelock_cov' 'DICS_fixedori' 'sheet' 'timelock_cov' 'PCC_keepall' 'sheet' 'timelock_cov' 'PCC_keepall_rawtrial' 'sheet' 'timelock_cov' 'PCC_keepnothing' 'sheet' 'timelock_cov' 'PCC_keepnothing_rawtrial' 'sheet' 'timelock_cov' 'PCC_refdip' 'sheet' 'timelock_cov_trl' 'DICS_keepall' 'sheet' 'timelock_cov_trl' 'DICS_keepall_rawtrial' 'sheet' 'timelock_cov_trl' 'DICS_keepnothing' 'sheet' 'timelock_cov_trl' 'DICS_keepnothing_rawtrial' 'sheet' 'timelock_cov_trl' 'DICS_refdip' 'sheet' 'timelock_cov_trl' 'DICS_refchan' 'sheet' 'timelock_cov_trl' 'DICS_realfilter' 'sheet' 'timelock_cov_trl' 'DICS_fixedori' 'sheet' 'timelock_cov_trl' 'DICS_keepall' 'sheet' 'timelock_cov_trl' 'DICS_keepall_rawtrial' 'sheet' 'timelock_cov_trl' 'DICS_keepnothing' 'sheet' 'timelock_cov_trl' 'DICS_keepnothing_rawtrial' 'sheet' 'timelock_cov_trl' 'DICS_refdip' 'sheet' 'timelock_cov_trl' 'DICS_refchan' 'sheet' 'timelock_cov_trl' 'DICS_realfilter' 'sheet' 'timelock_cov_trl' 'DICS_fixedori' 'sheet' 'timelock_cov_trl' 'PCC_keepall' 'sheet' 'timelock_cov_trl' 'PCC_keepall_rawtrial' 'sheet' 'timelock_cov_trl' 'PCC_keepnothing' 'sheet' 'timelock_cov_trl' 'PCC_keepnothing_rawtrial' 'sheet' 'timelock_cov_trl' 'PCC_refdip' 'grid' 'freq_mtmfft_fourier_trl' 'LCMV_keepall' 'grid' 'freq_mtmfft_fourier_trl' 'LCMV_keepnothing' 'grid' 'freq_mtmfft_fourier_trl' 'LCMV_keepall_rawtrial' 'grid' 'freq_mtmfft_fourier_trl' 'LCMV_keepnothing_rawtrial' 'grid' 'freq_mtmconvol_fourier_trl' 'LCMV_keepall' 'grid' 'freq_mtmconvol_fourier_trl' 'LCMV_keepnothing' 'grid' 'freq_mtmconvol_fourier_trl' 'LCMV_keepall_rawtrial' 'grid' 'freq_mtmconvol_fourier_trl' 'LCMV_keepnothing_rawtrial' 'grid' 'freq_mtmfft_trl' 'LCMV_keepall' 'grid' 'freq_mtmfft_trl' 'LCMV_keepnothing' 'grid' 'freq_mtmfft_trl' 'LCMV_keepall_rawtrial' 'grid' 'freq_mtmfft_trl' 'LCMV_keepnothing_rawtrial' 'grid' 'freq_mtmfft' 'LCMV_keepall' 'grid' 'freq_mtmfft' 'LCMV_keepnothing' 'grid' 'freq_mtmfft' 'LCMV_keepall_rawtrial' 'grid' 'freq_mtmfft' 'LCMV_keepnothing_rawtrial' 'grid' 'freq_mtmconvol_trl' 'LCMV_keepall' 'grid' 'freq_mtmconvol_trl' 'LCMV_keepnothing' 'grid' 'freq_mtmconvol_trl' 'LCMV_keepall_rawtrial' 'grid' 'freq_mtmconvol_trl' 'LCMV_keepnothing_rawtrial' 'grid' 'freq_mtmconvol' 'LCMV_keepall' 'grid' 'freq_mtmconvol' 'LCMV_keepnothing' 'grid' 'freq_mtmconvol' 'LCMV_keepall_rawtrial' 'grid' 'freq_mtmconvol' 'LCMV_keepnothing_rawtrial' 'grid' 'timelock' 'DICS_keepall' 'grid' 'timelock' 'DICS_keepall_rawtrial' 'grid' 'timelock' 'DICS_keepnothing' 'grid' 'timelock' 'DICS_keepnothing_rawtrial' 'grid' 'timelock' 'DICS_refdip' 'grid' 'timelock' 'DICS_refchan' 'grid' 'timelock' 'DICS_realfilter' 'grid' 'timelock' 'DICS_fixedori' 'grid' 'timelock' 'DICS_keepall' 'grid' 'timelock' 'DICS_keepall_rawtrial' 'grid' 'timelock' 'DICS_keepnothing' 'grid' 'timelock' 'DICS_keepnothing_rawtrial' 'grid' 'timelock' 'DICS_refdip' 'grid' 'timelock' 'DICS_refchan' 'grid' 'timelock' 'DICS_realfilter' 'grid' 'timelock' 'DICS_fixedori' 'grid' 'timelock' 'PCC_keepall' 'grid' 'timelock' 'PCC_keepall_rawtrial' 'grid' 'timelock' 'PCC_keepnothing' 'grid' 'timelock' 'PCC_keepnothing_rawtrial' 'grid' 'timelock' 'PCC_refdip' 'grid' 'timelock_trl' 'DICS_keepall' 'grid' 'timelock_trl' 'DICS_keepall_rawtrial' 'grid' 'timelock_trl' 'DICS_keepnothing' 'grid' 'timelock_trl' 'DICS_keepnothing_rawtrial' 'grid' 'timelock_trl' 'DICS_refdip' 'grid' 'timelock_trl' 'DICS_refchan' 'grid' 'timelock_trl' 'DICS_realfilter' 'grid' 'timelock_trl' 'DICS_fixedori' 'grid' 'timelock_trl' 'DICS_keepall' 'grid' 'timelock_trl' 'DICS_keepall_rawtrial' 'grid' 'timelock_trl' 'DICS_keepnothing' 'grid' 'timelock_trl' 'DICS_keepnothing_rawtrial' 'grid' 'timelock_trl' 'DICS_refdip' 'grid' 'timelock_trl' 'DICS_refchan' 'grid' 'timelock_trl' 'DICS_realfilter' 'grid' 'timelock_trl' 'DICS_fixedori' 'grid' 'timelock_trl' 'PCC_keepall' 'grid' 'timelock_trl' 'PCC_keepall_rawtrial' 'grid' 'timelock_trl' 'PCC_keepnothing' 'grid' 'timelock_trl' 'PCC_keepnothing_rawtrial' 'grid' 'timelock_trl' 'PCC_refdip' 'grid' 'timelock_cov' 'DICS_keepall' 'grid' 'timelock_cov' 'DICS_keepall_rawtrial' 'grid' 'timelock_cov' 'DICS_keepnothing' 'grid' 'timelock_cov' 'DICS_keepnothing_rawtrial' 'grid' 'timelock_cov' 'DICS_refdip' 'grid' 'timelock_cov' 'DICS_refchan' 'grid' 'timelock_cov' 'DICS_realfilter' 'grid' 'timelock_cov' 'DICS_fixedori' 'grid' 'timelock_cov' 'DICS_keepall' 'grid' 'timelock_cov' 'DICS_keepall_rawtrial' 'grid' 'timelock_cov' 'DICS_keepnothing' 'grid' 'timelock_cov' 'DICS_keepnothing_rawtrial' 'grid' 'timelock_cov' 'DICS_refdip' 'grid' 'timelock_cov' 'DICS_refchan' 'grid' 'timelock_cov' 'DICS_realfilter' 'grid' 'timelock_cov' 'DICS_fixedori' 'grid' 'timelock_cov' 'PCC_keepall' 'grid' 'timelock_cov' 'PCC_keepall_rawtrial' 'grid' 'timelock_cov' 'PCC_keepnothing' 'grid' 'timelock_cov' 'PCC_keepnothing_rawtrial' 'grid' 'timelock_cov' 'PCC_refdip' 'grid' 'timelock_cov_trl' 'DICS_keepall' 'grid' 'timelock_cov_trl' 'DICS_keepall_rawtrial' 'grid' 'timelock_cov_trl' 'DICS_keepnothing' 'grid' 'timelock_cov_trl' 'DICS_keepnothing_rawtrial' 'grid' 'timelock_cov_trl' 'DICS_refdip' 'grid' 'timelock_cov_trl' 'DICS_refchan' 'grid' 'timelock_cov_trl' 'DICS_realfilter' 'grid' 'timelock_cov_trl' 'DICS_fixedori' 'grid' 'timelock_cov_trl' 'DICS_keepall' 'grid' 'timelock_cov_trl' 'DICS_keepall_rawtrial' 'grid' 'timelock_cov_trl' 'DICS_keepnothing' 'grid' 'timelock_cov_trl' 'DICS_keepnothing_rawtrial' 'grid' 'timelock_cov_trl' 'DICS_refdip' 'grid' 'timelock_cov_trl' 'DICS_refchan' 'grid' 'timelock_cov_trl' 'DICS_realfilter' 'grid' 'timelock_cov_trl' 'DICS_fixedori' 'grid' 'timelock_cov_trl' 'PCC_keepall' 'grid' 'timelock_cov_trl' 'PCC_keepall_rawtrial' 'grid' 'timelock_cov_trl' 'PCC_keepnothing' 'grid' 'timelock_cov_trl' 'PCC_keepnothing_rawtrial' 'grid' 'timelock_cov_trl' 'PCC_refdip' 'roi' 'freq_mtmfft_fourier_trl' 'LCMV_keepall' 'roi' 'freq_mtmfft_fourier_trl' 'LCMV_keepnothing' 'roi' 'freq_mtmfft_fourier_trl' 'LCMV_keepall_rawtrial' 'roi' 'freq_mtmfft_fourier_trl' 'LCMV_keepnothing_rawtrial' 'roi' 'freq_mtmconvol_fourier_trl' 'LCMV_keepall' 'roi' 'freq_mtmconvol_fourier_trl' 'LCMV_keepnothing' 'roi' 'freq_mtmconvol_fourier_trl' 'LCMV_keepall_rawtrial' 'roi' 'freq_mtmconvol_fourier_trl' 'LCMV_keepnothing_rawtrial' 'roi' 'freq_mtmfft_trl' 'LCMV_keepall' 'roi' 'freq_mtmfft_trl' 'LCMV_keepnothing' 'roi' 'freq_mtmfft_trl' 'LCMV_keepall_rawtrial' 'roi' 'freq_mtmfft_trl' 'LCMV_keepnothing_rawtrial' 'roi' 'freq_mtmfft' 'LCMV_keepall' 'roi' 'freq_mtmfft' 'LCMV_keepnothing' 'roi' 'freq_mtmfft' 'LCMV_keepall_rawtrial' 'roi' 'freq_mtmfft' 'LCMV_keepnothing_rawtrial' 'roi' 'freq_mtmconvol_trl' 'LCMV_keepall' 'roi' 'freq_mtmconvol_trl' 'LCMV_keepnothing' 'roi' 'freq_mtmconvol_trl' 'LCMV_keepall_rawtrial' 'roi' 'freq_mtmconvol_trl' 'LCMV_keepnothing_rawtrial' 'roi' 'freq_mtmconvol' 'LCMV_keepall' 'roi' 'freq_mtmconvol' 'LCMV_keepnothing' 'roi' 'freq_mtmconvol' 'LCMV_keepall_rawtrial' 'roi' 'freq_mtmconvol' 'LCMV_keepnothing_rawtrial' 'roi' 'timelock' 'DICS_keepall' 'roi' 'timelock' 'DICS_keepall_rawtrial' 'roi' 'timelock' 'DICS_keepnothing' 'roi' 'timelock' 'DICS_keepnothing_rawtrial' 'roi' 'timelock' 'DICS_refdip' 'roi' 'timelock' 'DICS_refchan' 'roi' 'timelock' 'DICS_realfilter' 'roi' 'timelock' 'DICS_fixedori' 'roi' 'timelock' 'DICS_keepall' 'roi' 'timelock' 'DICS_keepall_rawtrial' 'roi' 'timelock' 'DICS_keepnothing' 'roi' 'timelock' 'DICS_keepnothing_rawtrial' 'roi' 'timelock' 'DICS_refdip' 'roi' 'timelock' 'DICS_refchan' 'roi' 'timelock' 'DICS_realfilter' 'roi' 'timelock' 'DICS_fixedori' 'roi' 'timelock' 'PCC_keepall' 'roi' 'timelock' 'PCC_keepall_rawtrial' 'roi' 'timelock' 'PCC_keepnothing' 'roi' 'timelock' 'PCC_keepnothing_rawtrial' 'roi' 'timelock' 'PCC_refdip' 'roi' 'timelock_trl' 'DICS_keepall' 'roi' 'timelock_trl' 'DICS_keepall_rawtrial' 'roi' 'timelock_trl' 'DICS_keepnothing' 'roi' 'timelock_trl' 'DICS_keepnothing_rawtrial' 'roi' 'timelock_trl' 'DICS_refdip' 'roi' 'timelock_trl' 'DICS_refchan' 'roi' 'timelock_trl' 'DICS_realfilter' 'roi' 'timelock_trl' 'DICS_fixedori' 'roi' 'timelock_trl' 'DICS_keepall' 'roi' 'timelock_trl' 'DICS_keepall_rawtrial' 'roi' 'timelock_trl' 'DICS_keepnothing' 'roi' 'timelock_trl' 'DICS_keepnothing_rawtrial' 'roi' 'timelock_trl' 'DICS_refdip' 'roi' 'timelock_trl' 'DICS_refchan' 'roi' 'timelock_trl' 'DICS_realfilter' 'roi' 'timelock_trl' 'DICS_fixedori' 'roi' 'timelock_trl' 'PCC_keepall' 'roi' 'timelock_trl' 'PCC_keepall_rawtrial' 'roi' 'timelock_trl' 'PCC_keepnothing' 'roi' 'timelock_trl' 'PCC_keepnothing_rawtrial' 'roi' 'timelock_trl' 'PCC_refdip' 'roi' 'timelock_cov' 'DICS_keepall' 'roi' 'timelock_cov' 'DICS_keepall_rawtrial' 'roi' 'timelock_cov' 'DICS_keepnothing' 'roi' 'timelock_cov' 'DICS_keepnothing_rawtrial' 'roi' 'timelock_cov' 'DICS_refdip' 'roi' 'timelock_cov' 'DICS_refchan' 'roi' 'timelock_cov' 'DICS_realfilter' 'roi' 'timelock_cov' 'DICS_fixedori' 'roi' 'timelock_cov' 'DICS_keepall' 'roi' 'timelock_cov' 'DICS_keepall_rawtrial' 'roi' 'timelock_cov' 'DICS_keepnothing' 'roi' 'timelock_cov' 'DICS_keepnothing_rawtrial' 'roi' 'timelock_cov' 'DICS_refdip' 'roi' 'timelock_cov' 'DICS_refchan' 'roi' 'timelock_cov' 'DICS_realfilter' 'roi' 'timelock_cov' 'DICS_fixedori' 'roi' 'timelock_cov' 'PCC_keepall' 'roi' 'timelock_cov' 'PCC_keepall_rawtrial' 'roi' 'timelock_cov' 'PCC_keepnothing' 'roi' 'timelock_cov' 'PCC_keepnothing_rawtrial' 'roi' 'timelock_cov' 'PCC_refdip' 'roi' 'timelock_cov_trl' 'DICS_keepall' 'roi' 'timelock_cov_trl' 'DICS_keepall_rawtrial' 'roi' 'timelock_cov_trl' 'DICS_keepnothing' 'roi' 'timelock_cov_trl' 'DICS_keepnothing_rawtrial' 'roi' 'timelock_cov_trl' 'DICS_refdip' 'roi' 'timelock_cov_trl' 'DICS_refchan' 'roi' 'timelock_cov_trl' 'DICS_realfilter' 'roi' 'timelock_cov_trl' 'DICS_fixedori' 'roi' 'timelock_cov_trl' 'DICS_keepall' 'roi' 'timelock_cov_trl' 'DICS_keepall_rawtrial' 'roi' 'timelock_cov_trl' 'DICS_keepnothing' 'roi' 'timelock_cov_trl' 'DICS_keepnothing_rawtrial' 'roi' 'timelock_cov_trl' 'DICS_refdip' 'roi' 'timelock_cov_trl' 'DICS_refchan' 'roi' 'timelock_cov_trl' 'DICS_realfilter' 'roi' 'timelock_cov_trl' 'DICS_fixedori' 'roi' 'timelock_cov_trl' 'PCC_keepall' 'roi' 'timelock_cov_trl' 'PCC_keepall_rawtrial' 'roi' 'timelock_cov_trl' 'PCC_keepnothing' 'roi' 'timelock_cov_trl' 'PCC_keepnothing_rawtrial' 'roi' 'timelock_cov_trl' 'PCC_refdip' };