text:
function container = properties_load(directory, pattern)
% properties_load Load tracker runtime properties from files
%

candidates = dir(fullfile(directory, sprintf('%s_*.value', pattern)));

container = struct();
container.names = {};
container.data = {};

for p = 1:numel(candidates)

    [~, name, ~] = fileparts(candidates(p).name);

    parameter_name = name(length(pattern)+2:end);

    data = cell(0, 0);

    fp = fopen(fullfile(directory, candidates(p).name), 'r');

    while true
         line = fgets(fp);

         if line == -1
             break;
         end

         [value, numeric] = str2num(line(1:end-1)); %#ok<ST2NM>

         if ~numeric
            value = line(1:end-1);
         end

         if isempty(value)
             value = [];
         end;

         data{end+1, 1} = value; %#ok<AGROW>

    end;

    fclose(fp);

    container.names{end+1} = parameter_name;

    if isempty(container.data)
        container.data = data;
    else
        container.data = cat(1, container.data, data);
    end;

end;

author: votchallenge

repo: toolkit-legacy


text:
function varargout = spm_SpUtil(varargin)
% Space matrix utilities
% FORMAT varargout = spm_SpUtil(action,varargin)
%
%_______________________________________________________________________
%
% spm_SpUtil is a multi-function function containing various utilities
% for Design matrix and contrast construction and manipulation. In
% general, it accepts design matrices as plain matrices or as space
% structures setup by spm_sp.
%
% Many of the space utilities are computed using an SVD of the design
% matrix. The advantage of using space structures is that the svd of
% the design matrix is stored in the space structure, thereby saving
% unnecessary repeated computation of the SVD. This presents a
% considerable efficiency gain for large design matrices.
%
% Note that when space structures are passed as arguments is is
% assummed that their basic fields are filled in. See spm_sp for
% details of (design) space structures and their manipulation.
%
% Quick Reference    :
%---------------------
% ('isCon',x,c)      :
% ('allCon',x,c)     :
% ('ConR',x,c)       :
% ('ConO',x,c)       :
% ('size',x,dim)     :
% ('iX0check',i0,sL) :
%---------------------
% ('i0->c',x,i0)     : Out : c
% ('c->Tsp',x,c)     : Out : [X1o [X0]]
% ('+c->Tsp',x,c)    : Out : [ukX1o [ukX0]]
% ('i0->x1o',x,i0)   : Use ('i0->c',x,i0) and ('c->Tsp',X,c)
% ('+i0->x1o',x,i0)  : Use ('i0->c',x,i0) and ('+c->Tsp',X,c)
% ('X0->c',x,X0)     :~
% ('+X0->c',x,cukX0) :~
%---------------------
% ('trRV',x[,V])     :
% ('trMV',x[,V])     :
% ('i0->edf',x,i0,V) :
%
%---------------------
%
% Improvement compared to the spm99 beta version :
%
% Improvements in df computation using spm_SpUtil('trRV',x[,V]) and
% spm_SpUtil('trMV',sX [,V]). The degrees of freedom computation requires
% in general that the trace of RV and of RVRV be computed, where R is a
% projector onto either a sub space of the design space or the residual
% space, namely the space that is orthogonal to the design space. V is
% the (estimated or assumed) variance covariance matrix and is a number
% of scans by number of scans matrix which can be huge in some cases. We
% have (thanks to S Rouquette and JB) speed up this computation
% by using matlab built in functions of the frobenius norm and some theorems
% on trace computations.
%
% ======================================================================
%
% FORMAT i = spm_SpUtil('isCon',x,c)
% Tests whether weight vectors specify contrasts
% x   - Design matrix X, or space structure of X
% c   - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
%       Must have column dimension matching that of X
%       [defaults to eye(size(X,2)) to test uniqueness of parameter estimates]
% i   - logical row vector indiciating estimability of contrasts in c
%
% A linear combination of the parameter estimates is a contrast if and
% only if the weight vector is in the space spanned by the rows of X.
%
% The algorithm works by regressing the contrast weight vectors using
% design matrix X' (X transposed). Any contrast weight vectors will be
% fitted exactly by this procedure, leaving zero residual. Parameter
% tol is the tolerance applied when searching for zero residuals.
%
% Christensen R (1996)
%   "Plane Answers to Complex Questions"
%    2nd Ed. Springer-Verlag, New York
%
% Andrade A, Paradis AL, Rouquette S and Poline JB, NeuroImage 9, 1999
%                           ----------------
%
% FORMAT i = spm_SpUtil('allCon',x,c)
% Tests whether all weight vectors specify contrasts:
% Same as all(spm_SpUtil('isCon',x,c)).
%
%                           ----------------
%
% FORMAT r = spm_SpUtil('ConR',x,c)
% Assess orthogonality of contrasts (wirit the data)
% x   - Design matrix X, or space structure of X
% c   - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
%       Must have column dimension matching that of X
%       defaults to eye(size(X,2)) to test independence of parameter estimates
% r   - Contrast correlation matrix, of dimension the number of contrasts.
%
% For the general linear model Y = X*B + E, a contrast weight vector c
% defines a contrast c*B. This is estimated by c*b, where b are the
% least squares estimates of B given by b=pinv(X)*Y. Thus, c*b = w*Y,
% where weight vector w is given by w=c*pinv(X); Since the data are
% assummed independent, two contrasts are indpendent if the
% corresponding weight vectors are orthogonal.
%
% r is the matrix of normalised inner products between the weight
% vectors corresponding to the contrasts. For iid E, r is the
% correlation matrix of the contrasts.
%
% The logical matrix ~r will be true for orthogonal pairs of contrasts.
%
%                           ----------------
%
% FORMAT r = spm_SpUtil('ConO',x,c)
% Assess orthogonality of contrasts (wirit the data)
% x   - Design matrix X, or space structure of X
% c   - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
%       Must have column dimension matching that of X
%       [defaults to eye(size(X,2)) to test uniqueness of parameter estimates]
% r   - Contrast orthogonality matrix, of dimension the number of contrasts.
%
% This is the same as ~spm_SpUtil('ConR',X,c), but uses a quicker
% algorithm by looking at the orthogonality of the subspaces of the
% design space which are implied by the contrasts:
%       r = abs(c*X'*X*c')<tol
%
%                           ----------------
%
% FORMAT c = spm_SpUtil('i0->c',x,i0)
% Return F-contrast for specified design matrix partition
% x   - Design matrix X, or space structure of X
% i0  - column indices of null hypothesis design matrix
%
% This functionality returns a rank n mxp matrix of contrasts suitable
% for an extra-sum-of-squares F-test comparing the design X, with a
% reduced design. The design matrix for the reduced design is X0 =
% X(:,i0), a reduction of n degrees of freedom.
%
% The algorithm, due to J-B, and derived from Christensen, computes the
% contrasts as an orthonormal basis set for the rows of the
% hypothesised redundant columns of the design matrix, after
% orthogonalisation with respect to X0. For non-unique designs, there
% are a variety of ways to produce equivalent F-contrasts. This method
% produces contrasts with non-zero weights only for the hypothesised
% redundant columns.
%
%                           ----------------
%
% case {'x0->c'}                %-
% FORMAT c = spm_SpUtil('X0->c',sX,X0)
%                           ----------------
%
% FORMAT [X1,X0] = spm_SpUtil('c->TSp',X,c)
% Orthogonalised partitioning of design space implied by F-contrast
% x   - Design matrix X, or space structure of X
% c   - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
%       Must have column dimension matching that of X
% X1o - contrast space - design matrix corresponding according to contrast
%       (orthogonalised wirit X0)
% X0  - matrix reduced according to null hypothesis
%       (of same size as X but rank deficient)
% FORMAT [uX1,uX0] = spm_SpUtil('c->TSp+',X,c)
%        + version to deal with the X1o and X0 partitions in the "uk basis"
%
% ( Note that unless X0 is reduced to a set of linearely independant   )
% ( vectors, c will only be contained in the null space of X0.  If X0  )
% ( is "reduced", then the "parent" space of c must be reduced as well )
% ( for c to be the actual null space of X0.                           )
%
% This functionality returns a design matrix subpartition whose columns
% span the hypothesised null design space of a given contrast. Note
% that X1 is orthogonal(ised) to X0, reflecting the situation when an
% F-contrast is tested using the extra sum-of-squares principle (when
% the extra distance in the hypothesised null space is measured
% orthogonal to the space of X0).
%
% Note that the null space design matrix will probably not be a simple
% sub-partition of the full design matrix, although the space spanned
% will be the same.
%
%                           ----------------
%
% FORMAT X1 = spm_SpUtil('i0->x1o',X,i0)
% x   - Design matrix X, or space structure of X
% i0  - Columns of X that make up X0 - the reduced model (Ho:B1=0)
% X1  - Hypothesised null design space, i.e. that part of X orthogonal to X0
% This offers the same functionality as the 'c->TSp' option, but for
% simple reduced models formed from the columns of X.
%
% FORMAT X1 = spm_SpUtil('i0->x1o+',X,i0)
%        + version to deal with the X1o and X0 partitions in the "uk basis"
%
%                           ----------------
%
% FORMAT [trRV,trRVRV] = spm_SpUtil('trRV',x[,V])
% trace(RV) & trace(RVRV) - used in df calculation
% x      - Design matrix X, or space structure of X
% V      - V matrix [defult eye] (trRV == trRVRV if V==eye, since R idempotent)
% trRV   - trace(R*V),     computed efficiently
% trRVRV - trace(R*V*R*V), computed efficiently
% This uses the Karl's cunning understanding of the trace:
%              (tr(A*B) = sum(sum(A'*B)).
% If the space of X is set, then algorithm uses x.u to avoid extra computation.
%
%                           ----------------
%
% FORMAT [trMV, trMVMV]] = spm_SpUtil('trMV',x[,V])
% trace(MV) & trace(MVMV) if two ouput arguments.
% x      - Design matrix X, or space structure of X
% V      - V matrix [defult eye] (trMV == trMVMV if V==eye, since M idempotent)
% trMV   - trace(M*V),     computed efficiently
% trMVMV - trace(M*V*M*V), computed efficiently
% Again, this uses the Karl's cunning understanding of the trace:
%              (tr(A*B) = sum(sum(A'.*B)).
% If the space of X is set, then algorithm uses x.u to avoid extra computation.
%
%                           ----------------
%
% OBSOLETE use FcUtil('H') for spm_SpUtil('c->H',x,c)
% Extra sum of squares matrix O for beta's from contrast
% x   - Design matrix X, or space structure of X
% c   - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
%       Must have column dimension matching that of X
% O   - Matrix such that b'*O*b = extra sum of squares for F-test of contrast c
%
%                           ----------------
%
% OBSOLETE use spm_sp('=='...) for spm_SpUtil('c==X1o',x,c) {or 'cxpequi'}
% x   - Design matrix X, or space structure of X
% c   - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
%       Must have column dimension matching that of X
% b   - True is c is a spanning set for space of X
%       (I.e. if contrast and space test the same thing)
%
%                           ----------------
%
% FORMAT [df1,df2] = spm_SpUtil('i0->edf',x,i0,V) {or 'edf'}
% (effective) df1 and df2 the residual df for the projector onto the
% null space of x' (residual forming projector) and the numerator of
% the F-test where i0 are the columns for the null hypothesis model.
% x   - Design matrix X, or space structure of X
% i0  - Columns of X corresponding to X0 partition X = [X1,X0] & with
%       parameters B = [B1;B0]. Ho:B1=0
% V   - V matrix
%
%                           ----------------
%
% FORMAT  sz           = spm_SpUtil('size',x,dim)
% FORMAT [sz1,sz2,...] = spm_SpUtil('size',x)
% Returns size of design matrix
% (Like MatLab's `size`, but copes with design matrices inside structures.)
% x   - Design matrix X, or structure containing design matrix in field X
%       (Structure needn't be a space structure.)
% dim - dimension which to size
% sz  - size
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Andrew Holmes Jean-Baptiste Poline
% $Id: spm_SpUtil.m 4137 2010-12-15 17:18:32Z guillaume $

% (frobenius norm trick by S. Rouquette)

%-Format arguments
%-----------------------------------------------------------------------
if nargin==0, error('do what? no arguments given...')
else action = varargin{1}; end

switch lower(action),

case {'iscon','allcon','conr','cono'}
%=======================================================================
% i = spm_SpUtil('isCon',x,c)
if nargin==0, varargout={[]}; error('isCon : no argument specified'), end;
if nargin==1,
   varargout={[]}; warning('isCon : no contrast specified'); return;
end;
if ~spm_sp('isspc',varargin{2})
     sX = spm_sp('Set',varargin{2});
else sX = varargin{2}; end
if nargin==2, c=eye(spm_sp('size',sX,2)); else c=varargin{3}; end;
if isempty(c), varargout={[]}; return, end

switch lower(action)
    case 'iscon'
        varargout = { spm_sp('eachinspp',sX,c) };
    case 'allcon'
        varargout = {spm_sp('isinspp',sX,c)};
    case 'conr'
        if size(c,1) ~= spm_sp('size',sX,2)
            error('Contrast not of the right size'), end
        %-Compute inner products of data weight vectors
        % (c'b = c'*pinv(X)*Y = w'*Y
        % (=> w*w' = c'*pinv(X)*pinv(X)'*c == c'*pinv(X'*X)*c
        r   = c'*spm_sp('XpX-',sX)*c;
        %-normalize by "cov(r)" to get correlations
        r   = r./(sqrt(diag(r))*sqrt(diag(r))');
        r(abs(r) < sX.tol)=0;       %-set near-zeros to zero
        varargout = {r};                %-return r
    case 'cono'
        %-This is the same as ~spm_SpUtil('ConR',x,c), and so returns
        % the contrast orthogonality (though not their corelations).
        varargout = { abs(c'* spm_sp('XpX',sX) *c) < sX.tol};
end

case {'+c->tsp','c->tsp'}    %- Ortho. partitioning implied by F-contrast
%=======================================================================
% spm_SpUtil('c->Tsp',sX,c)
% + version of 'c->tsp'.
% The + version returns the same in the base u(:,1:r).

%--------- begin argument check ------------------------------
if nargin ~= 3, error(['Wrong number of arguments in ' action])
else sX = varargin{2}; c = varargin{3}; end;
if nargout > 2, error(['Too many output arguments in ' action]), end;
if ~spm_sp('isspc',sX),  sX = spm_sp('set',varargin{2}); end;
if sX.rk == 0, error('c->Tsp null rank sX == 0'); end;
if ~isempty(c) && spm_sp('size',sX,2) ~= size(c,1),
   error(' c->TSp matrix & contrast dimensions don''t match');
end
%--------- end argument check ---------------------------------

%- project c onto the space of  X' if needed
%-------------------------------------------
if ~isempty(c) && ~spm_sp('isinspp',sX,c),
   warning([sprintf('\n') 'c is not a proper contrast in ' action ...
            ' in ' mfilename sprintf('\n') '!!! projecting...' ]);
   disp('from'), c, disp('to'), c = spm_sp('oPp:',sX,c)
end

cukFlag = strcmp(lower(action),'+c->tsp');

switch nargout
% case 0
%   warning(['no output demanded in ' mfilename ' ' action])
case {0,1}
   if ~isempty(c) && any(any(c))               %- c not empty & not null
      if cukFlag, varargout = { spm_sp('cukxp-:',sX,c) };
      else        varargout = { spm_sp('xp-:',sX,c) };
      end
   else if isempty(c), varargout = { [] };     %- c empty
       else                                    %- c null
           if cukFlag, varargout = { spm_sp('cukx',sX,c) };
           else        varargout = { spm_sp('x',sX)*c };
           end
       end
   end

case 2
   if ~isempty(c) && any(any(c))         %- not empty and not null
      if cukFlag,
         varargout = {
        spm_sp('cukxp-:',sX,c), ...      %- X1o
        spm_sp('cukx',sX,spm_sp('r',spm_sp('set',c))) };      %- X0
      else
         varargout = {
        spm_sp(':',sX, spm_sp('xp-:',sX,c)), ...              %- X1o
        spm_sp(':',sX, ...
               spm_sp('x',sX)*spm_sp('r',spm_sp('set',c))) }; %- X0
      end
   else
      if isempty(c),                     %- empty
         if cukFlag, varargout = { [], spm_sp('cukx',sX) };
         else        varargout = { [], spm_sp('x',sX) };
         end
      else                               %- null
         if cukFlag,
            varargout = { spm_sp(':',sX,spm_sp('cukx',sX,c)), ...
                          spm_sp(':',sX,spm_sp('cukx',sX)) };
         else
            varargout = { spm_sp('x',sX)*c, spm_sp('x',sX)};
         end
      end;
   end

otherwise
   error(['wrong number of output argument in ' action]);
end

case {'i0->x1o','+i0->x1o'} %- Space tested whilst keeping size of X(i0)
%=======================================================================
% X1o = spm_SpUtil('i0->X1o',sX,i0)

% arguments are checked in calls to spm_Util
%--------------------------------------------
if nargin<3, error('Insufficient arguments'),
else sX = varargin{2}; i0 = varargin{3}; end;

cukFlag = strcmp(lower(action),'+i0->x1o');

c  = spm_SpUtil('i0->c',sX,i0);

if cukFlag,
   varargout = { spm_SpUtil('+c->TSp',sX,c) };
else
   varargout = { spm_SpUtil('c->TSp',sX,c) };
end

case {'i0->c'}                 %-
%=======================================================================
% c = spm_SpUtil('i0->c',sX,i0)
%
% if i0 == [] : returns a proper contrast
% if i0 == [1:size(sX.X,2)] : returns [];
%
%- Algorithm : avoids the pinv(X0) and insure consistency
%- Get the estimable parts of c0 and c1
%- remove from c1_estimable the estimable part of c0.
%- Use the rotation making X1o orthog. to X0.
%- i0 is checked when Fc is created
%- If i0 defines a space that is the space of X but with
%- fewer vectors, c is null.

%--------- begin argument check --------------------------------
if nargin<3, error('Insufficient arguments'),
else sX = varargin{2}; i0 = varargin{3}; end;
if ~spm_sp('isspc',sX),  sX = spm_sp('set',varargin{2}); end;
if spm_sp('rk',sX) == 0, error('i0->c null rank sX == 0'); end;
sL  = spm_sp('size',sX,2);
i0  = sf_check_i0(i0,sL);
%--------- end argument check ----------------------------------

c0  = eye(sL); c0 = c0(:,i0);
c1  = eye(sL); c1 = c1(:,setdiff(1:sL,i0));

%- try to avoid the matlab error when doing svd of matrices with
%- high multiplicities. (svd convergence pb)

if ~ spm_sp('isinspp',sX,c0), c0 = spm_sp('oPp:',sX,c0); end;
if ~ spm_sp('isinspp',sX,c1), c1 = spm_sp('oPp:',sX,c1); end;

if ~isempty(c1)
   if ~isempty(c0)
      %- varargout = { spm_sp('res',spm_sp('set',opp*c0),opp*c1) };
      %- varargout = { c1 - c0*pinv(c0)*c1 }; NB: matlab pinv uses
      %- svd: will fail if spm_sp('set')  fails.

      varargout = { spm_sp('r:',spm_sp('set',c0),c1) };

   else varargout = { spm_sp('xpx',sX) }; end;
else
   varargout = { [] };  %- not zeros(sL,1) : this is return when
            %- appropriate
end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case {'+x0->c','x0->c'}             %-
%=======================================================================
% c = spm_SpUtil('X0->c',sX,X0)
% c = spm_SpUtil('+X0->c',sX,cukX0)
% + version of 'x0->c'.
% The + version returns the same in the base u(:,1:r).

warning('Not tested for release - provided for completeness');
cukFlag = strcmp(lower(action),'+x0->c');

%--------- begin argument check ---------
if nargin<3, error('Insufficient arguments'),
else
   sX = varargin{2};
   if cukFlag, cukX0 = varargin{3}; else X0 = varargin{3}; end
end
if ~spm_sp('isspc',sX),  sX = spm_sp('set',varargin{2}); end
if spm_sp('rk',sX) == 0, error(['null rank sX == 0 in ' action]); end
if cukFlag
   if ~isempty(cukX0) && spm_sp('rk',sX) ~= size(cukX0,1),
      cukX0, spm_sp('rk',sX),
      error(['cukX0 of wrong size ' mfilename ' ' action]), end
else
   if ~isempty(X0) && spm_sp('size',sX,1) ~= size(X0,1),
      X0, spm_sp('size',sX,1),
      error(['X0 of wrong size ' mfilename ' ' action]),X0, end
end
%--------- end argument check ---------

if cukFlag
   if isempty(cukX0), X0 = []; else X0 = spm_sp('ox',sX)*cukX0; end
end

varargout = { sf_X0_2_c(X0,sX) };

case {'c->h','betarc'}  %-Extra sum of squares matrix for beta's from
                        %- contrast : use F-contrast if possible
%=======================================================================
% H = spm_SpUtil('c->H',sX,c)
error(' Obsolete : Use F-contrast utilities  ''H'' or ''Hsqr''... ');

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

%=======================================================================
%=======================================================================
%       trace part
%=======================================================================
%=======================================================================
%

case 'trrv'                      %-Traces for (effective) df calculation
%=======================================================================
% [trRV,trRVRV]= spm_SpUtil('trRV',x[,V])

if nargin == 1, error('insufficient arguments');
else sX = varargin{2};  end;

if ~spm_sp('isspc',sX), sX = spm_sp('Set',sX); end;

rk = spm_sp('rk',sX);
sL = spm_sp('size',sX,1);

if  sL == 0,
    warning('space with no dimension ');
    if nargout==1, varargout = {[]};
    else varargout = {[], []}; end
else

   if nargin > 2 && ~isempty(varargin{3})

    V = varargin{3};
    u = sX.u(:,1:rk);
    clear sX;
    if nargout==1
        %-only trRV needed
        if rk==0 || isempty(rk),  trMV = 0;
        else trMV = sum(sum( u .* (V*u) ));
        end
        varargout = { trace(V) - trMV};
    else
        %-trRVRV is needed as well
        if rk==0 || isempty(rk),
            trMV = 0;
            trRVRV = (norm(V,'fro'))^2;
         trV = trace(V);
         clear V u
        else
           Vu = V*u;
           trV = trace(V);
           trRVRV = (norm(V,'fro'))^2;
                   clear V;
           trRVRV = trRVRV - 2*(norm(Vu,'fro'))^2;
           trRVRV = trRVRV + (norm(u'*Vu,'fro'))^2;
           trMV = sum(sum( u .* Vu ));
                   clear u Vu
        end
        varargout = {(trV - trMV), trRVRV};
    end

   else  %- nargin == 2 | isempty(varargin{3})

    if nargout==1
        if rk==0 || isempty(rk), varargout = {sL};
        else varargout = {sL - rk};
        end
    else
        if rk==0 || isempty(rk),  varargout = {sL,sL};
        else varargout = {sL - rk, sL - rk};
        end
    end

    end
end

case 'trmv'                     %-Traces for (effective) Fdf calculation
%=======================================================================
% [trMV, trMVMV]] = spm_SpUtil('trMV',sX [,V])
%
% NB : When V is given empty, the routine asssumes it's identity
% This is used in spm_FcUtil.

if nargin == 1, error('insufficient arguments');
else sX = varargin{2}; end;
if ~spm_sp('isspc',sX), sX = spm_sp('Set',sX); end;
rk = spm_sp('rk',sX);

if isempty(rk)
    warning('Rank is empty');
    if nargout==1, varargout = {[]};
    else varargout = {[], []}; end
    return;
elseif  rk==0, warning('Rank is null in spm_SpUtil trMV ');
    if nargout==1, varargout = {0};
    else varargout = {0, 0}; end
    return;
end;

if nargin > 2 && ~isempty(varargin{3}) %- V provided, and assumed correct !

    V = varargin{3};
    u = sX.u(:,1:rk);
    clear sX;

    if nargout==1
        %-only trMV needed
        trMV = sum(sum(u' .* (u'*V) ));
        varargout = {trMV};
    else
        %-trMVMV is needed as well
        Vu = V*u;
                clear V
        trMV = sum(sum( u .* Vu ));
        trMVMV = (norm(u'*Vu,'fro'))^2;
            clear u Vu
        varargout = {trMV, trMVMV};
    end

else  % nargin == 2 | isempty(varargin{3}) %-no V specified: trMV == trMVMV
    if nargout==1
        varargout = {rk};
    else
        varargout = {rk, rk};
    end
end

case {'i0->edf','edf'}                  %-Effective F degrees of freedom
%=======================================================================
% [df1,df2] = spm_SpUtil('i0->edf',sX,i0,V)
%-----------------------------------------------------------------------
%--------- begin argument check ----------------------------------------
if nargin<3, error('insufficient arguments'),
else i0 = varargin{3}; sX = varargin{2}; end
if ~spm_sp('isspc',sX), sX = spm_sp('Set',sX); end;
i0  = sf_check_i0(i0,spm_sp('size',sX,2));
if nargin == 4, V=varargin{4}; else V = eye(spm_sp('size',sX,1)); end;
if nargin>4, error('Too many input arguments'), end;
%--------- end argument check ------------------------------------------

warning(' Use F-contrast utilities if possible ... ');

[trRV,trRVRV]    = spm_SpUtil('trRV', sX, V);
[trMpV,trMpVMpV] = spm_SpUtil('trMV',spm_SpUtil('i0->x1o',sX, i0),V);
varargout = {trMpV^2/trMpVMpV, trRV^2/trRVRV};

%=======================================================================
%=======================================================================
%       Utilities
%=======================================================================
%=======================================================================

case 'size'                                      %-Size of design matrix
%=======================================================================
% sz = spm_SpUtil('size',x,dim)

if nargin<3, dim=[]; else dim = varargin{3}; end
if nargin<2, error('insufficient arguments'), end

if isstruct(varargin{2})
   if isfield(varargin{2},'X')
    sz = size(varargin{2}.X);
   else error('no X field'); end;
else
    sz = size(varargin{2});
end

if ~isempty(dim)
    if dim>length(sz), sz = 1; else sz = sz(dim); end
    varargout = {sz};
elseif nargout>1
    varargout = cell(1,min(nargout,length(sz)));
    for i=1:min(nargout,length(sz)), varargout{i} = sz(i); end
else
    varargout = {sz};
end

case 'ix0check'                                      %-
%=======================================================================
% i0c = spm_SpUtil('iX0check',i0,sL)

if nargin<3, error('insufficient arguments'),
else i0 = varargin{2}; sL = varargin{3}; end;

varargout = {sf_check_i0(i0,sL)};

otherwise
%=======================================================================
error('Unknown action string in spm_SpUtil')

%=======================================================================
end

%=======================================================================
function i0c = sf_check_i0(i0,sL)
% NB : [] = sf_check_i0([],SL);
%

if all(ismember(i0,[0,1])) && length(i0(:))==sL, i0c=find(i0);
elseif ~isempty(i0) && any(floor(i0)~=i0) || any(i0<1) || any(i0>sL)
    error('logical mask or vector of column indices required')
else i0c = i0; end

%=======================================================================
function c = sf_X0_2_c(X0,sX)
%
%- Algorithm to avoids the pinv(X0) and insure consistency
%- Get a contrast that span the space of X0 and is estimable
%- Get the orthogonal complement and project onto the estimable space
%- Strip zeros columns and use the rotation making X1o orthog. to X0
% !!! tolerance dealing ?

if ~isempty(X0)

   sc0 = spm_sp('set',spm_sp('x-',sX,X0));
   if  sc0.rk
      c = spm_sp('oPp:',sX,spm_sp('r',sc0));
   else
      c = spm_sp('oPp',sX);
   end;
   c  = c(:,any(c));
   sL = spm_sp('size',sX,2);

   %- why the   "& size(X0,2) ~= sL"   !!!?
   if isempty(c) && size(X0,2) ~= sL
      c = zeros(sL,1);
   end

else
   c = spm_sp('xpx',sX);
end

%- c = spm_sp('r',sc0,spm_sp('oxp',sX)); would also works.

author: spm


text:
function Write_ActuatorPower(FileWritingSetup)
% Write_Power(FileWritingSetup)
%
% FUNCTION:
%
%   This function writes a function that computes the power being used by
%   the actuators on the robot.
%
%
% INPUTS: FileWritingSetup.
%
%   States = [2N x 2] cell array where the first column is the name of
%       the states, and the second column is comments about that states.
%       The index of a state in this array will match the index in the
%       dynamics function to be written. This function assumes a second
%       order system that is being written in first order form, so if
%       States{i,1} = z, then States{i+N,1} = dz; Furthermore, the output
%       (dStates) will have the form: dStates(i,:) = dz,
%       and dStates(i+N,:) = ddz.
%
%   Power = struct with a field for each actuator.
%
%   Actuators = [P x 2] cell array giving the names of each of the
%       actuators and their comments.
%
%   Directory = the name of the directory to write the files in.
%
%
% OUTPUTS:
%   This function will write the function power()
%
%
% NOTE:
%
%   1)  It is assumed that the symbols in all of the inputs are self
%       consistent; that is - if Contacts{1,1} = H1, then there must be a field
%       in Dyn.(FileNames{i,1}) called H1.
%
%
% Written by Matthew Kelly
% December 8, 2013
% Cornell University
%
% See also DERIVE_EOM

States = FileWritingSetup.States;
Power = FileWritingSetup.Power;
Directory = FileWritingSetup.Directory;
Actuators = FileWritingSetup.Actuators;
Kinematics = FileWritingSetup.Kinematics;

CurrDir = cd;
if ~exist(Directory,'dir')
    mkdir(Directory);
end
cd(Directory);

fid = fopen('actuatorPower.m','w');

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
%                         Function Header                             %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%

fprintf(fid,'function Power = actuatorPower(States, Actuators, Phase)\n');
fprintf(fid,'%% function Power = actuatorPower(States, Actuators, Phase)\n');
fprintf(fid,'%%\n%% Computer Generated File -- DO NOT EDIT \n');
fprintf(fid,['%%\n%% This function was created by the function '...
    'Write_Power()\n']);
fprintf(fid,['%% ' datestr(now) '\n%%\n']);
fprintf(fid,'%%  ARGUMENTS: \n');
fprintf(fid,'%%   States = [Nstate x Ntime] matrix of states \n');
fprintf(fid,'%%   Actuator = [Nactuator x Ntime] matrix of actuator values \n');
fprintf(fid,'%%   Phase = {''D'',''F'',''S1'',S2''} or omit. \n');
fprintf(fid,'%%       Since the ankle torques are acting against the ground, they should \n');
fprintf(fid,'%%       be set to zero when a given leg is in flight. If Phase is included, \n');
fprintf(fid,'%%       then this function will force these inputs to be zero. If it is \n');
fprintf(fid,'%%       ommitted, then it is assumed that the user has done that error \n');
fprintf(fid,'%%       checking. \n');
fprintf(fid,'%% \n');
fprintf(fid,'%%  RETURNS: \n');
fprintf(fid,'%%   Power = a struct with fields for each actuator: \n');
fprintf(fid,'%%       leg one (linear force actuator) \n');
fprintf(fid,'%%       leg two (linear force actuator) \n');
fprintf(fid,'%%       ankle one (torque actuator) \n');
fprintf(fid,'%%       ankle two (torque actuator) \n');
fprintf(fid,'%%       hip (torque from leg one on leg two \n');
fprintf(fid,'%% \n');
fprintf(fid,'%%\n');
fprintf(fid,'%% Matthew Kelly \n%% Cornell University \n%% \n\n');
fprintf(fid,'%% \n');
fprintf(fid,'%% See also DERIVE_EOM \n');

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
%                           Parse Inputs                              %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%

for idxState=1:size(States,1)
    fprintf(fid,[States{idxState,1} ' = States(:,' num2str(idxState) '); %% ' ...
        States{idxState,2} '\n']);
end %idxState
fprintf(fid,'\n');

fprintf(fid,'if nargin==2\n');
fprintf(fid,'    Phase = '''';\n');
fprintf(fid,'end\n');
fprintf(fid,' \n');

for idxAct=1:size(Actuators,1)

    if strcmp(Actuators{idxAct,1},'T1')
        fprintf(fid,'if strcmp(Phase,''F'') || strcmp(Phase, ''S2'') \n');
        fprintf(fid,['    ' Actuators{idxAct,1} ' = zeros(size(Actuators,1),1); %%Foot One not in contact with ground!\n']);
        fprintf(fid,'else\n');
        fprintf(fid,['    ' Actuators{idxAct,1} ' = Actuators(:,' num2str(idxAct) '); %% ' Actuators{idxAct,2} '\n']);
        fprintf(fid,'end\n');
    elseif strcmp(Actuators{idxAct,1},'T2')
        fprintf(fid,'if strcmp(Phase,''F'') || strcmp(Phase, ''S1'') \n');
        fprintf(fid,['    ' Actuators{idxAct,1} ' = zeros(size(Actuators,1),1); %%Foot Two not in contact with ground!\n']);
        fprintf(fid,'else\n');
        fprintf(fid,['    ' Actuators{idxAct,1} ' = Actuators(:,' num2str(idxAct) '); %% ' Actuators{idxAct,2} '\n']);
        fprintf(fid,'end\n');
    else
        fprintf(fid,[Actuators{idxAct,1} ' = Actuators(:,' num2str(idxAct) '); %% ' Actuators{idxAct,2} '\n']);
    end

end %idxAct
fprintf(fid,'\n');

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
%         Intermediate Steps and Common Expressions                   %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%

fprintf(fid,'%% Intermediate Calculations\n');
fNames = fieldnames(Kinematics);
for i=1:length(fNames)
    if strcmp(fNames{i},'th1') || strcmp(fNames{i},'th2')  %Don't need these!
        fprintf(fid,['%% ' fNames{i} ' = ' vectorize(Kinematics.(fNames{i})) ';\n']);
    else
        fprintf(fid,[fNames{i} ' = ' vectorize(Kinematics.(fNames{i})) ';\n']);
    end
end
fprintf(fid,'\n');

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%
%                          Write Outputs                              %
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%

FieldNames = fieldnames(Power);
for i=1:length(FieldNames)
    fprintf(fid,['Power.' FieldNames{i} ' = ' vectorize(Power.(FieldNames{i})) ';\n']);
end
fprintf(fid,'\n');
fprintf(fid,'end\n');
fclose(fid);

cd(CurrDir);

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%  ~~~~~~~~~~~~~~~~~~~ Sub Functions  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function characterExpression = vectorize(symbolicExpression)

        characterExpression = char(symbolicExpression);
        characterExpression = strrep(characterExpression,'*','.*');
        characterExpression = strrep(characterExpression,'/','./');
        characterExpression = strrep(characterExpression,'^','.^');
end

author: MatthewPeterKelly

repo: dscTutorials


text:
recall_i = 0:0.1:1.0;
fh = figure(1);clf;colormap(lines);
pr_wzr = [1.0000    0.5767    0.4589    0.3738    0.3135    0.2703    0.2331    0.2031    0.1722    0.1383    0.0250
1.0000    0.6796    0.5637    0.4768    0.4179    0.3639    0.3143    0.2654    0.2194    0.1662    0.0250
1.0000    0.7184    0.6358    0.5793    0.5322    0.4842    0.4371    0.3928    0.3345    0.2533    0.0250];
plot(recall_i,pr_wzr(1,:),recall_i,pr_wzr(2,:),recall_i,pr_wzr(3,:)); hold on;

eval_mvcnn = load('data/features/l11/evalRet.mat');
eval_mvcnn_metric = load('data/features/l12/evalRet.mat');
eval_fv = load('data/features/l5/evalRet.mat');

info = eval_fv.info;
pr_fv = zeros(size(info.recall_i,1),length(recall_i));
for i=1:size(info.recall_i,1),
    [recall_all,I] = unique(info.recall_i(i,:));
    precision_all = info.precision_i(i,I);
    pr_fv(i,:) = interp1(recall_all,precision_all,recall_i);
end

info = eval_mvcnn.info;
pr_mvcnn = zeros(size(info.recall_i,1),length(recall_i));
for i=1:size(info.recall_i,1),
    [recall_all,I] = unique(info.recall_i(i,:));
    precision_all = info.precision_i(i,I);
    pr_mvcnn(i,:) = interp1(recall_all,precision_all,recall_i);
end

info = eval_mvcnn_metric.info;
pr_mvcnn_metric = zeros(size(info.recall_i,1),length(recall_i));
for i=1:size(info.recall_i,1),
    [recall_all,I] = unique(info.recall_i(i,:));
    precision_all = info.precision_i(i,I);
    pr_mvcnn_metric(i,:) = interp1(recall_all,precision_all,recall_i);
end
plot(recall_i,mean(pr_fv),recall_i,mean(pr_mvcnn),recall_i,mean(pr_mvcnn_metric));
grid on; axis square;
legend('Spherical Harmonic','Light Field','3D ShapeNets','Fisher vector', 'Ours (MVCNN)','Ours (MVCNN+metric)');
ylabel('Precision');
xlabel('Recall');

print(fh,'pr.eps','-depsc');

author: suhangpro

repo: mvcnn

save_path: github-repos/MATLAB/suhangpro-mvcnn


text:
function [bfSeriesNo] = getSeriesNoFromName(inputMoviePath,bfSeriesName,varargin)
	% [bfSeriesNo] = getSeriesNoFromName(inputFilePath,bfSeriesName,varargin)
	%
	% Returns series number for Bio-Formats series with name given by user.
	%
	% Biafra Ahanonu
	% started: 2022.07.15 [08:10:16]
	%
	% Inputs
	% 	inputFilePath - Str: path to Bio-Formats compatible file.
	% 	bfSeriesName - Str: name of series within the file. Can be a regular expression.
	%
	% Outputs
	% 	bfSeriesNo - Int: series number (1-based indexing) matching the input series name. NaN is output if no series is found.
	%
	% Options (input as Name-Value with Name = options.(Name))
	% 	% File ID connection from calling bfGetReader(inputFilePath), this is to save time on larger files by avoiding opening the connection again.
	% 	options.fileIdOpen = '';

	% Changelog
		%
	% TODO
		%

	try
		bfSeriesNo = ciapkg.bf.getSeriesNoFromName(inputMoviePath,bfSeriesName,'passArgs',varargin);
	catch err
		disp(repmat('@',1,7))
		disp(getReport(err,'extended','hyperlinks','on'));
		disp(repmat('@',1,7))
	end
end

author: bahanonu

repo: ciatah

save_path: github-repos/MATLAB/bahanonu-ciatah


text:
function pass = test_constructor_turbo(pref)

% NB:  This test checks basic construction syntax only.  Accuracy testing is
% done in the corresponding test in tests/chebtech.

% Get preferences.
if ( nargin < 1 )
    pref = chebfunpref();
end

% Check that the right number of coefficients were calculated.
f_plain = chebfun(@exp, pref);
f_turbo = chebfun(@exp, 'turbo');
pass(1) = length(f_turbo) == 2*length(f_plain);

% Try an array-valued example.
f_plain = chebfun(@(x) [exp(x) 1./(x + 5)], pref);
f_turbo = chebfun(@(x) [exp(x) 1./(x + 5)], 'turbo');
pass(2) = length(f_turbo) == 2*length(f_plain);

% Try specifying a number of coefficients.
f = chebfun(@exp, 75, 'turbo');
pass(3) = length(f) == 75;

% Try specifying a number of coefficients for an array-valued input.
f = chebfun(@(x) [exp(x) 1./(x + 5)], 75, 'turbo');
pass(4) = length(f) == 75;

% Check that things work for constructions with breakpoints.
f_plain = chebfun(@exp, [-1 0 1], pref);
f_turbo = chebfun(@exp, [-1 0 1], 'turbo');
pass(5) = length(f_turbo) == 2*length(f_plain);

f_plain = chebfun(@(x) exp(x).*sign(x), 'splitting', 'on', pref);
f_turbo = chebfun(@(x) exp(x).*sign(x), 'splitting', 'on', 'turbo');
pass(6) = length(f_turbo) == 2*length(f_plain);

% Check that things work for constructions with exponents.
f_plain = chebfun(@(x) sin(x).*sqrt(1 + x), 'exps', [0.5 0], pref);
f_turbo = chebfun(@(x) sin(x).*sqrt(1 + x), 'exps', [0.5 0], 'turbo');
pass(7) = length(f_turbo) == 2*length(f_plain);

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
%DISPERROR Display error matrix with information on classifiers and datasets
%
%	DISPERROR(DATA,CLASSF,ERROR,STD,FID)
%
% INPUT
%   DATA     Cell array of M datasets or dataset names (strings)
%   CLASSF   Cell array of N mappings or mapping names (strings)
%   ERROR    M*N matrix of (average) error estimates
%   STD      M*N matrix of standard devations on ERROR (optional)
%   FID      File in which results are written (default: 1)
% OUTPUT
%
% DESCRIPTION
% Displays the matrix ERROR matrix with error estimates for N
% classifiers related to M datasets. This routine is called by TESTC
% and CROSVALL to display results.
%
% EXAMPLE
% testsets  = {gendath gendatb gendatd(100,5)}
% trainsets = {gendath gendatb gendatd(100,5)}
% classifiers = {nmc fisherc qdc svc}
% testc(testsets,prmap(trainsets,classifiers))
%
% SEE ALSO (PRTools Guide)
% MAPPINGS, DATASETS, TESTC, PRCROSSVAL

% $Id: disperror.m,v 1.3 2007/06/05 12:43:35 duin Exp $

function disperror (data,classf,err,stdev,fid)

	if nargin < 5, fid = 1; end
	% Check arguments.
	if (nargin > 3) & (any(size(err) ~= size(stdev)))
		error('size of matrix with standard deviations should match matrix with errors')
	end
	if (~iscell(classf)) | (~isstr(classf{1}) & ~ismapping(classf{1}))
		error('cell array of mappings or mapping names expected')
	end
	if (~iscell(data)) | (~isstr(data{1}) & ~isdataset(data{1}))
		error('cell array of datasets or datasets names expected')
	end

	[m,n] = size(err);
	if (length(data) ~= m)
		error('size of dataset cell array should equal number of rows in error matrix');
	end

	if (length(classf) ~= n)
		error('size of classifier cell array should equal number of columns in error matrix');
	end

	% If datasets are supplied, extract their names.
	for j = 1:m
		if (isdataset(data{j}))
			data{j} = getname(data{j});
		end
	end

	% If classifiers are supplied, extract their names.
	for j = 1:n
		if (ismapping(classf{j}))
			classf{j} = getname(classf{j});
		end
  end

  if n >=  m

    if m == 1
      fprintf(fid, ' %s \n\n',data{1});
    else
      fprintf(fid,'\n');
      for j = 1:m
        fprintf(fid,'\n  data_%i : %20s',j,data{j});
      end
      fprintf(fid,'\n\n                      ');
      for j = 1:m
        fprintf(fid,'  data_%i',j);
      end
      fprintf(fid,'\n\n');
    end

    for i = 1:n
      fprintf(fid,'  %-22s',classf{i});
      fprintf(fid,'  %5.3f',err(:,i)');
      if (nargin > 3)
        fprintf(fid,' (%5.3f)',stdev(:,i)');
        fprintf(fid,'\n');
      end
      fprintf(fid,'\n');
    end

  else

    if (n == 1)
      fprintf(fid,' %s \n\n',classf{1});
    else
      fprintf(fid,'\n');
      for i = 1:n
        fprintf(fid,'\n  clsf_%i : %s',i,classf{i});
      end
      fprintf(fid,'\n\n                      ');
      for i = 1:n
        fprintf(fid,'  clsf_%i',i);
      end
      fprintf(fid,'\n\n');
    end

    for j = 1:m
      fprintf(fid,'  %s',data{j});
      fprintf(fid,' %7.3f',err(j,:));
      if (nargin > 3)
        fprintf(fid,'\n                      ');
        fprintf(fid,' %7.3f',stdev(j,:));
        fprintf(fid,'\n');
      end
      fprintf(fid,'\n');
    end

  end
  fprintf(fid,'\n');

return

author: marianux

repo: ecg-kit

save_path: github-repos/MATLAB/marianux-ecg-kit


text:
%% |dirPlus| demo
% The |dirPlus| function recursively collects a list of files or
% subdirectories from a folder tree, allowing you to specify the selection
% criteria for how the list is collected and formatted. For the following
% examples, we'll be using the main MATLAB toolbox path.
%%

rootPath = 'C:\Program Files\MATLAB\R2016b\toolbox\matlab';
format compact

%% The 'FileFilter' option
% By default, |dirPlus| will collect a list of files. We can specify a
% <https://www.mathworks.com/help/matlab/matlab_prog/regular-expressions.html
% regular-expression> pattern to filter the file names on, collecting a
% list of files that match. Here's an example that uses the 'FileFilter'
% option to recursively find every file with a '.m' extension:

fileList = dirPlus(rootPath, 'FileFilter', '\.m$');
fprintf('%d files found.\n', size(fileList, 1));
fprintf('%s\n', fileList{1:5}, '...');

%%
% It's a pretty long list, so I've only shown the first 5 files it finds.
% Notice they are listed with the full path prepended by default.

%%
% If you have multiple match expressions to filter on, you can use
% <https://www.mathworks.com/help/matlab/matlab_prog/regular-expressions.html#f0-42884
% grouping operators> to include them all in one expression. For example,
% this will find every '.jpg', '.bmp', and '.tif' file:

fileList = dirPlus(rootPath, 'FileFilter', '\.(jpg|bmp|tif)$');
fprintf('%d files found.\n', size(fileList, 1));
fprintf('%s\n', fileList{1:5}, '...');

%% The 'ReturnDirs' option
% We can instead collect a list of subdirectories by setting the
% 'ReturnDirs' option to |true|:

dirList = dirPlus(rootPath, 'ReturnDirs', true);
fprintf('%d directories found.\n', size(dirList, 1));
fprintf('%s\n', dirList{1:5}, '...');

%%
% Note that the output list will be ordered by subdirectory depth (i.e. all
% subdirectories at depth 0, followed by all subdirectories at depth 1,
% etc.). Any settings for 'FileFilter' will be ignored.

%% The 'DirFilter' option
% We can filter subdirectories just like we filter files using the
% 'DirFilter' option. This will give us a list of subdirectories containing
% the string |'addons'|:

dirList = dirPlus(rootPath, 'ReturnDirs', true, 'DirFilter', 'addons');
fprintf('%d directories found.\n', size(dirList, 1));
fprintf('%s\n', dirList{:});

%%
% There are 4 subdirectories in our root directory with |'addons'| in the
% name. Let's say we wanted to find any '.m' files in subdirectories with
% |'addons'| in the name. We can use the 'DirFilter' and 'FileFilter'
% options like so:

fileList = dirPlus(rootPath, 'DirFilter', 'addons', 'FileFilter', '\.m$');
fprintf('%d files found.\n', size(fileList, 1));
fprintf('%s\n', fileList{:});

%%
% No files found? We know from the <dirPlus_demo.html#2 *'FileFilter'*>
% example above that there are '.m' files present in
% |rootPath\addons\cef\+matlab\+internal\+addons\|. Shouldn't these show
% up? And for that matter, why didn't '+addons' show up in the list of
% subdirectories containing the string |'addons'|? There's another option
% setting at work here...

%% The 'RecurseInvalid' option
% When a subdirectory doesn't match the 'DirFilter' regular expression
% pattern (marking it as "invalid"), a few things happen:
%
% # That subdirectory is not included in any output lists returned with the
% 'ReturnDirs' option.
% # The file contents of that subdirectory are not included in any output
% lists returned.
% # *By default*, the recursive search does not go any further down the
% folder tree for that subdirectory. This is why the '+addons' folder is
% not found or searched through in the prior examples: it is nested within
% invalid folders (namely, 'cef').
%
% In some cases we'd like the recursive search to continue through
% subdirectories even when their contents are excluded. Setting the
% 'RecurseInvalid' option to |true| accomplishes this:

fileList = dirPlus(rootPath, 'DirFilter', 'addons', 'FileFilter', '\.m$', ...
                             'RecurseInvalid', true);
fprintf('%d files found.\n', size(fileList, 1));
fprintf('%s\n', fileList{:});

%%
% And now we can see those '.m' files in the deeply nested '+addons'
% subdirectory.

%% The 'Struct' option
% Instead of getting the output as a cell array of files/subdirectories, we
% can have |dirPlus| return a structure array of the form returned by the
% <https://www.mathworks.com/help/matlab/ref/dir.html |dir|> function by
% setting the 'Struct' option to |true|:

fileList = dirPlus(rootPath, 'Struct', true, 'FileFilter', '\.m$');
fprintf('%d files found.\n', size(fileList, 1));
display(fileList(1));

%% The 'Depth' option
% If we don't want to search quite so far down the folder tree, we can
% limit the search depth with the 'Depth' option. Let's see how many '.m'
% files are in the root folder:

fileList = dirPlus(rootPath, 'FileFilter', '\.m$', 'Depth', 0);
fprintf('%d files found.\n', size(fileList, 1));

%%
% Looks like none are. They are all contained in subdirectories. Let's see
% how many are located in just the immediate subdirectories of the root
% folder:

fileList = dirPlus(rootPath, 'FileFilter', '\.m$', 'Depth', 1);
fprintf('%d files found.\n', size(fileList, 1));

%% The 'PrependPath' option
% Maybe we just want the file/subdirectory names, but don't care about the
% absolute paths. In this case, we just set the 'PrependPath' option to
% |false|:

fileList = dirPlus(rootPath, 'FileFilter', '\.m$', 'PrependPath', false);
fprintf('%d files found.\n', size(fileList, 1));
fprintf('%s\n', fileList{1:5}, '...');

%% The 'ValidateFileFcn' option
% Sometimes we might want to select files based on a more complicated
% criteria than just what's in their names. In this case, we can use the
% 'ValidateFileFcn' option to specify a function that is to be run on each
% file found. This function should accept as input a structure of the form
% returned by the <https://www.mathworks.com/help/matlab/ref/dir.html
% |dir|> function and return a logical value (|true| to collect it in the
% list, |false| to ignore it). First, let's find all the '.png' files:

fileList = dirPlus(rootPath, 'FileFilter', '\.png$');
fprintf('%d files found.\n', size(fileList, 1));

%%
% Now, we can specify an anonymous function that gets the byte size of each
% file and returns |true| for only those greater than 250KB:

bigFcn = @(s) (s.bytes > 512^2);
fileList = dirPlus(rootPath, 'FileFilter', '\.png$', ...
                             'ValidateFileFcn', bigFcn);
fprintf('%s\n', fileList{:});

%%
% Just the one.

%% The 'ValidateDirFcn' option
% We can apply more complicated validation criteria for subdirectories as
% well using the 'ValidateDirFcn' option. Let's say we want to find all the
% '.m' files that are not contained within a
% <https://www.mathworks.com/help/matlab/matlab_oop/scoping-classes-with-packages.html
% package folder> (i.e. one that starts with '+'). Here's one way to do it:

dirFcn = @(s) ~strcmp(s.name(1), '+');
fileList = dirPlus(rootPath, 'ValidateDirFcn', dirFcn, 'FileFilter', '\.m$');
fprintf('%d files found.\n', size(fileList, 1));
fprintf('%s\n', fileList{1:5}, '...');

%%
% In this case, you could actually do this using a 'DirFilter' regular
% expression as well:

fileList = dirPlus(rootPath, 'DirFilter', '^[^+]', 'FileFilter', '\.m$');
fprintf('%d files found.\n', size(fileList, 1));
fprintf('%s\n', fileList{1:5}, '...');

author: jtkim-kaist

repo: Speech-enhancement


text:
function y = polycomb(varargin)

% Simplified Version of Combvec (Mark Beale, 12-15-93)

y = varargin{1};
for i=2:length(varargin)
    z = varargin{i};
    y = [copy_blocked(y,size(z,2)); copy_interleaved(z,size(y,2))];
end

%=========================================================
function b = copy_blocked(m,n)

[mr,mc] = size(m);
b = zeros(mr,mc*n);
ind = 1:mc;
for i=[0:(n-1)]*mc
  b(:,ind+i) = m;
end
%=========================================================

function b = copy_interleaved(m,n)

[mr,mc] = size(m);
b = zeros(mr*n,mc);
ind = 1:mr;
for i=[0:(n-1)]*mr
  b(ind+i,:) = m;
end
b = reshape(b,mr,n*mc);

author: Sable

repo: mcbench-benchmarks


text:
%% RATE OF CONVERGENCE OF ADAPTIVE FINITE ELEMENT METHOD USING WG ELEMENT
%
% This example is to show the rate of convergence of the lowest order
% finite element approximation of the second order elliptic equation.
%
% # Lshape problem.
% # Kellogg problem.

clear all; close all;
%% Kellogg problem
[node,elem] = squaremesh([-1 1 -1 1], 0.5);
bdFlag = setboundary(node,elem,'Dirichlet');
pde = Kelloggdata;
option.L0 = 1;
option.maxIt = 100;
option.maxN = 1e4;
option.theta = 0.2;
option.plotflag = 1;
err = afemPoisson(node,elem,pde,bdFlag,option);
figure;
showrate2(err.N,err.H1,40,'k-*','||Du-Du_h||',err.N,err.eta,40,'-+','eta');
latexerrtable(err.N,[err.H1 err.eta])

%% Lshape problem
[node,elem] = squaremesh([-1,1,-1,1],1);
[node,elem] = delmesh(node,elem,'x>0 & y<0');
bdFlag = setboundary(node,elem,'Dirichlet');
pde = Lshapedata;
format shorte
option.L0 = 1;
option.maxIt = 25;
option.printlevel = 1;
% option.elemType = 'WG';
option.plotflag = 1;
err = afemPoisson(node,elem,pde,bdFlag,option);

repo: Aero-matlab


text:
function [meanImage] = motionCompComputeMean(view, scans, frames)

%    meanImage = motionCompComputeMean(view, [scans], [frames])
%
% gb 01/22/05
%
% Computes mean image across frames for all scans
% Default : scans = current scan
%           frames = all frames

% Initilizes arguments and variables
global dataTYPES
curType = viewGet(view,'curdatatype');

if ieNotDefined('scans')
    scans = viewGet(view,'curScan');
end
if ieNotDefined('frames')
    frames = 1:(dataTYPES(curType).scanParams(scans(1)).nFrames);
end

nVoxels = sliceDims(view,scans(1));
nSlices = numberSlices(view,scans(1));

% In order to save memory, it is necessary to compute the mean scan after scan.
%       - If the input 'scans' is a single value, it returns the mean image
%         across this scan.
%       - If the input 'scans' is an array, it calls it recursively scan
%         after scan and computes the mean of the different mean images

if length(scans) == 1

    % If 'scans' is a single value
    % Loads the whole volume
    scan = scans;
    tSeriesAllSlices = motionCompLoadImages(view, scan);

    % Computes the mean image across frames for this scan
    meanImage = mean(tSeriesAllSlices(frames,:,:,:),1);

    return

else

    % If 'scans' is an array
    % Initializes the variable
    meanImages = zeros([length(scans) nVoxels nSlices]);

    % Calls itself recursively scan after scan
    for scanIndex = 1:length(scans)
        scanNum = scans(scanIndex);

        fprintf('Computing mean for scan %d... ',scanNum);
        [meanImages(scanIndex,:,:,:)] = motionCompComputeMean(view, scanNum, frames);
        fprintf('Done\n');
    end

    % Computes the mean of the mean images
    meanImage = mean(meanImages,1);

    return
end

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function simulatedSamples = tapas_physio_simulate_pulse_samples(t, c, ...
    nSimulatedSamples, positionString, verbose)
% Simulates samples at start/end of physiological recording by estimating
% pulse template and average pulse rate, and continuing those
%
% simulatedSamples = tapas_physio_simulate_pulse_samples(t, c, ...
%     nSimulatedSamples, positionString, verbose)%
% IN
%
% OUT
%
% EXAMPLE
%   tapas_physio_simulate_pulse_samples
%
%   See also tapas_physio_get_cardiac_pulse_template tapas_physio_read_physlogfiles

% Author:   Lars Kasper
% Created:  2019-01-26
% Copyright (C) 2019 TNU, Institute for Biomedical Engineering,
%                    University of Zurich and ETH Zurich.
%
% This file is part of the TAPAS PhysIO Toolbox, which is released under
% the terms of the GNU General Public License (GPL), version 3. You can
% redistribute it and/or modify it under the terms of the GPL (either
% version 3 or, at your option, any later version). For further details,
% see the file COPYING or <http://www.gnu.org/licenses/>.

doDebug = verbose.level >=2;

% add artificial time series before
simulatedPulses = zeros(nSimulatedSamples, 1);
[pulseTemplate, idxPulses, meanPulseRateInSamples] = ...
    tapas_physio_get_cardiac_pulse_template(t, c, verbose, ...
    'doNormalizeTemplate', false, 'shortenTemplateFactor', .99);

doPrepend = false;
doAppend = false;
switch positionString
    case {'pre', 'before'}
        doPrepend = true;
        % Create last simulated pulse:
        % if first detected pulse in orig time series is further from start
        % than meanPulseRate, assume a regular heart beat also all the way
        % to the start, i.e. spacing by a multiple of meanPulseRateInSamples
        % to last simulated pulse
        if mod(idxPulses(1), meanPulseRateInSamples) == 0
            % if earliest pulse at multiple of pulse rate,
            % then next pulse would be just before start of orig time
            % series
            idxLastSimulatedPulse = nSimulatedSamples;
        else
            idxLastSimulatedPulse = nSimulatedSamples - meanPulseRateInSamples ...
                + mod(idxPulses(1), meanPulseRateInSamples);
        end
        % put 1 where pulses should occur before start of time series,
        % given earliest pulse and mean pulse rate, fill backwards...
        simulatedPulses(idxLastSimulatedPulse:-meanPulseRateInSamples:1) = 1;
    case {'post', 'after'}
        doAppend = true;
        % Create first simulated pulse:
        % if last detected pulse in orig time series is further from end
        % than meanPulseRate, assume a regular heart beat also all the way
        % to the end, i.e. spacing by a multiple of meanPulseRateInSamples
        % to first simulated pulse
        nSamplesOrig = numel(c);
        idxFirstSimulatedPulse = meanPulseRateInSamples ...
           - mod(nSamplesOrig - idxPulses(end), meanPulseRateInSamples);

        % put 1 where pulses should occur after end of time series
        % given last pulse event in orig time series and mean pulse rate...
        simulatedPulses(idxFirstSimulatedPulse:meanPulseRateInSamples:end) = 1;
    otherwise
        tapas_physio_log(...
            sprintf('Unknown positionString ''%s'' for simulating samples; Use ''pre'' or ''post''', positionString),...
            verbose, 2)
end

% ...and convolve with pulse template
% **TODO** tapas_physio_conv
simulatedSamples = conv(simulatedPulses, pulseTemplate, 'same');

if doDebug
    dt = t(2) - t(1);
    if doPrepend
        tNew = -flip(1:nSimulatedSamples)'*dt+t(1);
    elseif doAppend
        tNew = (1:nSimulatedSamples)'*dt+t(end);
    end
    verbose.fig_handles(end+1) = tapas_physio_get_default_fig_params();
    stringTitle = sprintf('Preproc: Added simulated samples %s time series', positionString);

    % plot orig time series and extension by simulated samples
    plot(t,c); hold all;
    plot(tNew, simulatedSamples);

    % plot time events of actual and simulated pulses as stems
    idxSimulatedPulses = find(simulatedPulses);
    stem(t(idxPulses), ones(numel(idxPulses)));
    stem(tNew(idxSimulatedPulses), ones(numel(idxSimulatedPulses)));

    % plot template pulse centered on one simulated pulse
    tStart = tNew(idxSimulatedPulses(1));
    nSamplesTemplate = numel(pulseTemplate);
    tTemplate = tStart+dt*(-ceil(pulseTemplate/2)+(0:(nSamplesTemplate-1)))';
    plot(tTemplate, pulseTemplate);
    title(stringTitle);
end

author: translationalneuromodeling

repo: tapas


text:
function addToPath2(cerrPath)

G = dir(cerrPath);

for i = 1:numel(G)
    Gi = G(i);
    if Gi.isdir
        if ~strcmp(Gi.name(1),'.')
            subpath = fullfile(Gi.folder,Gi.name);
            %disp(['Adding to path ... ' subpath]);
            addpath(genpath(subpath));
        end
    end
end

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function varargout = panel_options(varargin)
% PANEL_OPTIONS:  Set general Brainstorm configuration.
%
% USAGE:  [bstPanelNew, panelName] = panel_options('CreatePanel')
%                                    panel_options('SystemPathRemove', rmPath)          % Update system path
%                             PATH = panel_options('SystemPathRemove', rmPath, PATH)    % Update user defined path (do not change system path)

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2009-2023

eval(macro_method);
end

%% ===== CREATE PANEL =====
function [bstPanelNew, panelName] = CreatePanel() %#ok<DEFNU>
    % Java initializations
    import java.awt.*;
    import javax.swing.*;
    global GlobalData;
    % Constants
    panelName = 'Preferences';

    % Create main main panel
    jPanelNew = gui_river();

    % ===== LEFT =====
    jPanelLeft = gui_river();
    jPanelNew.add('vtop', jPanelLeft);
    % ===== LEFT: SYSTEM =====
    jPanelSystem = gui_river([5 2], [0 15 8 15], 'System');
        jCheckUpdates    = gui_component('CheckBox', jPanelSystem, 'br', 'Automatic updates', [], [], []);
        if (bst_get('MatlabVersion') >= 804)
            jCheckSmooth = gui_component('CheckBox', jPanelSystem, 'br', 'Use smooth Matlab graphics', [], [], []);
        else
            jCheckSmooth = [];
        end
        jCheckDownsample = gui_component('CheckBox', jPanelSystem, 'br', 'Downsample recordings for faster display', [], [], []);
        jCheckGfp        = gui_component('CheckBox', jPanelSystem, 'br', 'Display GFP over time series', [], [], []);
        jCheckForceComp  = gui_component('CheckBox', jPanelSystem, 'br', 'Force mat-files compression (slower)', [], [], []);
        jCheckIgnoreMem  = gui_component('CheckBox', jPanelSystem, 'br', 'Ignore memory warnings', [], [], []);
        if ~ispc
            jCheckSystemCopy  = gui_component('CheckBox', jPanelSystem, 'br', 'Use system calls to copy/move files', [], [], []);
        else
            jCheckSystemCopy = [];
        end
    jPanelLeft.add('hfill', jPanelSystem);
    % ===== LEFT: OPEN GL =====
    jPanelOpengl = gui_river([5 2], [0 15 8 15], 'OpenGL rendering');
        jRadioOpenNone = gui_component('Radio', jPanelOpengl, '',   'OpenGL: Disabled (no transparency)', [], [], []);
        jRadioOpenSoft = gui_component('Radio', jPanelOpengl, 'br', 'OpenGL: Software (slow)', [], [], []);
        jRadioOpenHard = gui_component('Radio', jPanelOpengl, 'br', 'OpenGL: Hardware (accelerated)', [], [], []);
        % Group buttons
        jButtonGroup = ButtonGroup();
        jButtonGroup.add(jRadioOpenNone);
        jButtonGroup.add(jRadioOpenSoft);
        jButtonGroup.add(jRadioOpenHard);
        % On mac systems: opengl software is not supported
        if strncmp(computer,'MAC',3)
            jRadioOpenSoft.setEnabled(0);
        end
    jPanelLeft.add('br hfill', jPanelOpengl);
    % ===== LEFT: INTERFACE SCALING =====
    jPanelScaling = gui_river([5 2], [0 0 5 0], 'Interface scaling (%)');
        % Slider labels
        labelTable = java.util.Hashtable();
        labelTable.put(uint32(1), gui_component('label',[],'','100'));
        labelTable.put(uint32(2), gui_component('label',[],'','125'));
        labelTable.put(uint32(3), gui_component('label',[],'','150'));
        labelTable.put(uint32(4), gui_component('label',[],'','200'));
        labelTable.put(uint32(5), gui_component('label',[],'','250'));
        labelTable.put(uint32(6), gui_component('label',[],'','300'));
        labelTable.put(uint32(7), gui_component('label',[],'','400'));
        % Slider config
        jSliderScaling = JSlider(1,7,1);
        jSliderScaling.setLabelTable(labelTable);
        jSliderScaling.setPaintTicks(1);
        jSliderScaling.setMajorTickSpacing(1);
        jSliderScaling.setPaintLabels(1);
        jPanelScaling.add('hfill', jSliderScaling);
    jPanelLeft.add('br hfill', jPanelScaling);

    % ===== RIGHT =====
    jPanelRight = gui_river();
    jPanelNew.add(jPanelRight);
    % ===== RIGHT: FOLDERS =====
    jPanelFolders = gui_river([5 5], [0 15 15 15], 'Installation folders');
        % Temporary directory
        gui_component('Label', jPanelFolders, '', 'Brainstorm temporary directory: ', [], [], []);
        jTextTempDir   = gui_component('Text', jPanelFolders, 'br hfill', '', [], [], []);
        jButtonTempDir = gui_component('Button', jPanelFolders, [], '...', [], [], @TempDirectory_Callback);
        jButtonTempDir.setMargin(Insets(2,2,2,2));
        jButtonTempDir.setFocusable(0);
        % BrainSuite folder
        gui_component('Label', jPanelFolders, 'br', 'BrainSuite installation folder: ', [], [], []);
        jTextBsDir   = gui_component('Text', jPanelFolders, 'br hfill', '', [], [], []);
        jButtonBsDir = gui_component('Button', jPanelFolders, [], '...', [], [], @BsDirectory_Callback);
        jButtonBsDir.setMargin(Insets(2,2,2,2));
        jButtonBsDir.setFocusable(0);
        % Python executable
        jLabelPythonExe  = gui_component('Label', jPanelFolders, 'br', 'Python executable: ', [], [], []);
        jTextPythonExe   = gui_component('Text', jPanelFolders, 'br hfill', '', [], [], []);
        jButtonPythonExe = gui_component('Button', jPanelFolders, [], '...', [], [], @PythonExe_Callback);
        jButtonPythonExe.setMargin(Insets(2,2,2,2));
        jButtonPythonExe.setFocusable(0);
        if ~exist('pyenv', 'builtin') && ~exist('pyversion', 'builtin')
            jLabelPythonExe.setEnabled(0);
            jTextPythonExe.setEnabled(0);
            jButtonPythonExe.setEnabled(0);
        end
    jPanelRight.add('br hfill', jPanelFolders);

    % ===== RIGHT: SIGNAL PROCESSING =====
    jPanelProc = gui_river([5 5], [0 15 15 15], 'Processing');
        jCheckUseSigProc = gui_component('CheckBox', jPanelProc, 'br', 'Use Signal Processing Toolbox (Matlab)',    [], 'If selected, some processes will use the Matlab''s Signal Processing Toolbox functions.
Else, use only the basic Matlab function.', []);
        jBlockSizeLabel = gui_component('Label',  jPanelProc, 'br', 'Memory block size in Mb (default: 100Mb): ', [], [], []);
        blockSizeTooltip = 'Maximum size of data blocks to be read in memory, in megabytes.
Ensure this does not exceed the available RAM in your computer.';
        jBlockSize = gui_component('Text',  jPanelProc, [], '', [], [], []);
        jBlockSizeLabel.setToolTipText(blockSizeTooltip);
        jBlockSize.setToolTipText(blockSizeTooltip);
    jPanelRight.add('br hfill', jPanelProc);

    % ===== RIGHT: RESET =====
    if (GlobalData.Program.GuiLevel == 1)
        jPanelReset = gui_river([5 5], [0 15 15 15], 'Reset Brainstorm');
            gui_component('Label',  jPanelReset, [], 'Reset database and options to defaults: ', [], [], []);
            gui_component('Button', jPanelReset, [], 'Reset', [], [], @ButtonReset_Callback);
            gui_component('Label',  jPanelReset, 'br', 'Empty temporary directory: ', [], [], []);
            gui_component('Button', jPanelReset, [], 'Empty', [], [], @(h,ev)gui_brainstorm('EmptyTempFolder', 1));
        jPanelRight.add('br hfill', jPanelReset);
    end

    % ===== BOTTOM =====
    jPanelBottom = gui_river();
    jPanelNew.add('br hfill', jPanelBottom);
    % MEMORY
    [MaxVar, TotalMem] = bst_get('SystemMemory');
    if ~isempty(MaxVar) && ~isempty(TotalMem)
        % Display memory info
        jPanelMem = gui_river([0 0], [0 15 8 15]);
        labelBottom = sprintf('Max variable size: %d Mb       Memory available: %d Mb', MaxVar, TotalMem);
        jPanelLeft.add('br hfill', jPanelMem);
    else
        labelBottom = '';
    end

    % ===== VALIDATION BUTTONS =====
    gui_component('Label', jPanelBottom, '', labelBottom, [], [], []);
    gui_component('Label', jPanelBottom, 'hfill', ' ');
    gui_component('Button', jPanelBottom, 'right', 'Cancel', [], [], @ButtonCancel_Callback);
    gui_component('Button', jPanelBottom, [], 'Save', [], [], @ButtonSave_Callback);

    % ===== LOAD OPTIONS =====
    LoadOptions();

    % ===== CREATE PANEL =====
    bstPanelNew = BstPanel(panelName, ...
                           jPanelNew, ...
                           struct());

%% =================================================================================
%  === CONTROLS CALLBACKS  =========================================================
%  =================================================================================
%% ===== LOAD OPTIONS =====
    function LoadOptions()
        % GUI
        jCheckForceComp.setSelected(bst_get('ForceMatCompression'));
        jCheckUpdates.setSelected(bst_get('AutoUpdates'));
        jCheckGfp.setSelected(bst_get('DisplayGFP'));
        jCheckDownsample.setSelected(bst_get('DownsampleTimeSeries') > 0);
        jCheckIgnoreMem.setSelected(bst_get('IgnoreMemoryWarnings'));
        if ~isempty(jCheckSmooth)
            jCheckSmooth.setSelected(bst_get('GraphicsSmoothing') > 0);
        end
        if ~isempty(jCheckSystemCopy)
            jCheckSystemCopy.setSelected(bst_get('SystemCopy'));
        end
        switch bst_get('DisableOpenGL')
            case 0
                jRadioOpenHard.setSelected(1);
            case 1
                jRadioOpenNone.setSelected(1);
            case 2
                if strncmp(computer,'MAC',3)
                    jRadioOpenHard.setSelected(1);
                else
                    jRadioOpenSoft.setSelected(1);
                end
        end
        % Interface scaling
        switch (bst_get('InterfaceScaling'))
            case 100,       jSliderScaling.setValue(1);
            case 125,       jSliderScaling.setValue(2);
            case 150,       jSliderScaling.setValue(3);
            case {175,200}, jSliderScaling.setValue(4);
            case 250,       jSliderScaling.setValue(5);
            case 300,       jSliderScaling.setValue(6);
            case 400,       jSliderScaling.setValue(7);
        end
        % Temporary folder
        jTextTempDir.setText(bst_get('BrainstormTmpDir'));
        % BrainSuite folder
        jTextBsDir.setText(bst_get('BrainSuiteDir'));
        % Python config
        jTextPythonExe.setText(bst_get('PythonExe'));
        % Use signal processing toolbox
        isToolboxInstalled = (exist('kaiserord', 'file') > 0);
        jCheckUseSigProc.setEnabled(isToolboxInstalled);
        jCheckUseSigProc.setSelected(bst_get('UseSigProcToolbox'));
        processOptions = bst_get('ProcessOptions');
        jBlockSize.setText(num2str(processOptions.MaxBlockSize * 8 / 1024 / 1024));
    end

%% ===== SAVE OPTIONS =====
    function SaveOptions()
        bst_progress('start', 'Brainstorm preferences', 'Applying preferences...');
        % ===== GUI =====
        bst_set('ForceMatCompression', jCheckForceComp.isSelected());
        bst_set('AutoUpdates', jCheckUpdates.isSelected());
        bst_set('DisplayGFP',  jCheckGfp.isSelected());
        bst_set('IgnoreMemoryWarnings',  jCheckIgnoreMem.isSelected());
        if jCheckDownsample.isSelected()
            bst_set('DownsampleTimeSeries', 5);
        else
            bst_set('DownsampleTimeSeries', 0);
        end
        if ~isempty(jCheckSystemCopy)
            bst_set('SystemCopy', jCheckSystemCopy.isSelected());
        end
        if ~isempty(jCheckSmooth)
            % Update value
            isSmoothing = jCheckSmooth.isSelected();
            isChangedSmoothing = (bst_get('GraphicsSmoothing') ~= isSmoothing);
            bst_set('GraphicsSmoothing', isSmoothing);
            % Update open figures
            if isChangedSmoothing
                % Get all figures
                hFigAll = bst_figures('GetFiguresByType', {'DataTimeSeries', 'ResultsTimeSeries', '3DViz', 'Topography', 'MriViewer', 'Timefreq', 'Spectrum', 'Pac', 'Image'});
                % Set figurs properties
                if ~isempty(hFigAll)
                    if isSmoothing
                        set(hFigAll, 'GraphicsSmoothing', 'on');
                    else
                        set(hFigAll, 'GraphicsSmoothing', 'off');
                    end
                end
            end
        end

        % === OPENGL ===
        % Get selected status
        if jRadioOpenHard.isSelected()
            DisableOpenGL = 0;
        elseif jRadioOpenNone.isSelected()
            DisableOpenGL = 1;
        else
            DisableOpenGL = 2;
        end
        % Apply changes
        if (DisableOpenGL ~= bst_get('DisableOpenGL'))
            bst_set('DisableOpenGL', DisableOpenGL);
            StartOpenGL();
        end

        % ===== INTERFACE SCALING =====
        previousScaling = bst_get('InterfaceScaling');
        switch (jSliderScaling.getValue())
            case 1,  InterfaceScaling = 100;
            case 2,  InterfaceScaling = 125;
            case 3,  InterfaceScaling = 150;
            case 4,  InterfaceScaling = 200;
            case 5,  InterfaceScaling = 250;
            case 6,  InterfaceScaling = 300;
            case 7,  InterfaceScaling = 400;
        end
        bst_set('InterfaceScaling', InterfaceScaling);

        % ===== DATA IMPORT =====
        % Temporary directory
        oldTmpDir = bst_get('BrainstormTmpDir');
        newTmpDir = char(jTextTempDir.getText());
        if ~file_compare(oldTmpDir, newTmpDir)
            % Make sure it is different from and does not contain the database directory
            dbDir = bst_get('BrainstormDbDir');
            if file_compare(newTmpDir, dbDir)
                java_dialog('warning', 'Your temporary and database directories must be different.');
            elseif dir_contains(newTmpDir, dbDir)
                java_dialog('warning', 'Your temporary directory cannot contain your database directory.');
            else
                % If resetting tmp directory with an empty value
                if isempty(newTmpDir)
                    bst_set('BrainstormTmpDir', '');
                % If temp directory changed: create directory if it doesn't exist
                elseif file_exist(newTmpDir) || mkdir(newTmpDir)
                    bst_set('BrainstormTmpDir', newTmpDir);
                else
                    java_dialog('warning', 'Could not create temporary directory.');
                end
            end
        end
        % BrainSuite directory
        oldBsDir = bst_get('BrainSuiteDir');
        newBsDir = char(jTextBsDir.getText());
        if ~file_compare(oldBsDir, newBsDir)
            % Folder doesn't exist
            if ~isempty(newBsDir) && ~file_exist(newBsDir)
                java_dialog('warning', 'Selected BrainSuite folder doesn''t exist. Ignoring...');
            elseif ~isempty(newBsDir) && ~file_exist(bst_fullfile(newBsDir, 'bdp'))
                java_dialog('warning', 'Selected folder does not contain a valid BrainSuite install (missing "bdp" folder). Ignoring...');
            else
                bst_set('BrainSuiteDir', newBsDir);
            end
        end

        % ===== PYTHON =====
        % Get saved configuration
        oldPythonExe = bst_get('PythonExe');
        % Get new configuration
        newPythonExe = char(jTextPythonExe.getText());
        % If something changed
        if ~isequal(newPythonExe, oldPythonExe)
            % Save new values in user preferences
            bst_set('PythonExe', newPythonExe);
            % Set the new version of Python in Matlab
            try
                [pyVer, newPythonExe, isLoaded] = bst_python_ver(newPythonExe);
            catch
                bst_error('You must close and restart Matlab for this change to take effect.', 'Python exectutable', 0);
            end
            % Initialize Python if possible
            bst_python_init('Initialize', 1);
        end

        % ===== PROCESSING OPTIONS =====
        % Use signal processing toolbox
        bst_set('UseSigProcToolbox', jCheckUseSigProc.isSelected());
        % Memory block size (Valid values: between 1MB and 1TB)
        blockSize = str2num(jBlockSize.getText());
        if ~isempty(blockSize) && blockSize >= 1 && blockSize <= 1e6
            processOptions = bst_get('ProcessOptions');
            processOptions.MaxBlockSize = blockSize * 1024 * 1024 / 8; % Mb to bytes
            bst_set('ProcessOptions', processOptions);
        end
        bst_progress('stop');

        % If the scaling was changed: Restart brainstorm
        if (previousScaling ~= InterfaceScaling)
            brainstorm stop;
            brainstorm;
        end
    end

%% ===== SAVE OPTIONS =====
    function ButtonSave_Callback(varargin)
        % Save options
        SaveOptions()
        % Hide panel
        gui_hide(panelName);
    end

%% ===== CANCEL BUTTON =====
    function ButtonCancel_Callback(varargin)
        % Hide panel
        gui_hide(panelName);
    end

%% ===== TEMP DIRECTORY SELECTION =====
    % Callback for '...' button
    function TempDirectory_Callback(varargin)
        % Get the initial path
        initDir = bst_get('BrainstormTmpDir', 1);
        % Open 'Select directory' dialog
        tempDir = uigetdir(initDir, 'Select temporary directory.');
        % If no directory was selected : return without doing anything
        if (isempty(tempDir) || (tempDir(1) == 0))
            return
        end
        % Else : update control text
        jTextTempDir.setText(tempDir);
        % Focus main brainstorm figure
        jBstFrame = bst_get('BstFrame');
        jBstFrame.setVisible(1);
    end

%% ===== BRAINSUITE DIRECTORY SELECTION =====
    % Callback for '...' button
    function BsDirectory_Callback(varargin)
        % Get the initial path
        initDir = bst_get('BrainSuiteDir', 1);
        % Open 'Select directory' dialog
        bsDir = uigetdir(initDir, 'Select BrainSuite directory.');
        % If no directory was selected : return without doing anything
        if (isempty(bsDir) || (bsDir(1) == 0) || (~isempty(initDir) && file_compare(initDir, bsDir)))
            return;
        % Directory is not a valid folder
        elseif ~file_exist(bst_fullfile(bsDir, 'bdp'))
            java_dialog('warning', 'Selected folder does not contain a valid BrainSuite install (missing folder "bdp").');
            return;
        end
        % Else : update control text
        jTextBsDir.setText(bsDir);
        % Focus main brainstorm figure
        jBstFrame = bst_get('BstFrame');
        jBstFrame.setVisible(1);
    end

%% ===== PYTHON EXECUTABLE =====
    % Callback for '...' button
    function PythonExe_Callback(varargin)
        % Get the initial path
        initExe = bst_get('PythonExe');
        % Ask for python path
        newExe = java_getfile( 'open', ...
            'Select Python executable', ...  % Window title
            bst_fileparts(initExe), 'single', 'files', ...     % Default directory, Selection mode
            {{'*'}, 'Python executable (version 3.5 or higher)', 'Python'}, 'Python');
        if isempty(newExe) || isequal(initExe, newExe)
            return;
        end
        % Else : update control text
        jTextPythonExe.setText(newExe);
        % Focus main brainstorm figure
        jBstFrame = bst_get('BstFrame');
        jBstFrame.setVisible(1);
    end

% %% ===== QT DIRECTORY SELECTION =====
%     % Callback for '...' button
%     function QtDirectory_Callback(varargin)
%         % Get the initial path
%         PythonConfig = bst_get('PythonConfig', 1);
%         initDir = PythonConfig.QtDir;
%         % Open 'Select directory' dialog
%         qtDir = uigetdir(initDir, 'Select Qt plugin directory.');
%         % If no directory was selected : return without doing anything
%         if (isempty(qtDir) || (qtDir(1) == 0) || (~isempty(initDir) && file_compare(initDir, qtDir)))
%             return;
%         % Directory is not avalid Qt folder (test on windows only)
%         elseif ispc && ~file_exist(bst_fullfile(qtDir, 'qwindows.dll'))
%             java_dialog('warning', 'Selected folder does not contain a valid Qt plugin install (qwindows.dll missing).');
%             return;
%         end
%         % Else : update control text
%         jTextQtDir.setText(qtDir);
%         % Focus main brainstorm figure
%         jBstFrame = bst_get('BstFrame');
%         jBstFrame.setVisible(1);
%     end
%
% %% ===== ADD PYTHON PATH =====
%     % Callback for '+' button
%     function AddPath_Callback(varargin)
%         % Get the initial path
%         PythonConfig = bst_get('PythonConfig', 1);
%         if ~isempty(PythonConfig.PythonPath)
%             initPath = str_split(PythonConfig.PythonPath);
%             initDir = initPath{1};
%         else
%             initPath = {};
%             initDir = [];
%         end
%         % Open 'Select directory' dialog
%         addDir = uigetdir(initDir, 'Add folder to system path');
%         % If no directory was selected : return without doing anything
%         if (isempty(addDir) || (addDir(1) == 0) || ismember(addDir, initPath))
%             return;
%         end
%         % New python path
%         if ~isempty(PythonConfig.PythonPath)
%             newPath = [PythonConfig.PythonPath, pathsep, addDir];
%         else
%             newPath = addDir;
%         end
%         % Else : update control text
%         jTextPythonPath.setText(newPath);
%         % Focus main brainstorm figure
%         jBstFrame = bst_get('BstFrame');
%         jBstFrame.setVisible(1);
%     end
end

%% ===== START OPENGL =====
function [isOpenGL, DisableOpenGL] = StartOpenGL()
    global GlobalOpenGLStatus;
    % Get configuration
    DisableOpenGL = bst_get('DisableOpenGL');
    isOpenGL = 1;
    isUnixWarning = 0;

    % ===== MATLAB < 2014b =====
    if (bst_get('MatlabVersion') < 804)
        % Define OpenGL options
        switch DisableOpenGL
            case 0
                if strncmp(computer,'MAC',3)
                    OpenGLMode = 'autoselect';
                elseif isunix && ~isempty(GlobalOpenGLStatus)
                    OpenGLMode = 'autoselect';
                    disp('BST> Warning: You have to restart Matlab to switch between software and hardware OpenGL.');
                else
                    OpenGLMode = 'hardware';
                end
                FigureRenderer = 'opengl';
            case 1
                OpenGLMode = 'neverselect';
                FigureRenderer = 'zbuffer';
            case 2
                if strncmp(computer,'MAC',3)
                    OpenGLMode = 'autoselect';
                elseif isunix && ~isempty(GlobalOpenGLStatus)
                    OpenGLMode = 'autoselect';
                    disp('BST> Warning: You have to restart Matlab to switch between software and hardware OpenGL.');
                else
                    OpenGLMode = 'software';
                end
                FigureRenderer = 'opengl';
        end
        % Configure OpenGL
        try
            opengl(OpenGLMode);
        catch
            isOpenGL = 0;
        end
        % Check that OpenGL is running
        s = opengl('data');
        if isempty(s) || isempty(s.Version)
            isOpenGL = 0;
        end
        % Figure types for which the OpenGL renderer is used
        figTypes = {'3DViz', 'Topography', 'MriViewer', 'Timefreq', 'Pac', 'Image'};

    % ===== MATLAB >= 2014b =====
    else
        % Start OpenGL
        s = opengl('data');
        if isempty(s) || isempty(s.Version)
            isOpenGL = 0;
        end
        % Linux: Cannot change the OpenGL mode at runtime
        if isunix
            if ~isOpenGL
                DisableOpenGL = 1;
            % If the requested configuration is not the current OpenGL status: Error
            elseif (DisableOpenGL == 0) && (s.Software == 1)
                isUnixWarning = 1;
                DisableOpenGL = 2;
                bst_set('DisableOpenGL', DisableOpenGL);
            elseif (DisableOpenGL == 2) && (s.Software == 0)
                isUnixWarning = 1;
                DisableOpenGL = 0;
                bst_set('DisableOpenGL', DisableOpenGL);
            end
        % MacOSX: No software OpenGL
        elseif strncmp(computer,'MAC',3)
            % Nothing to do
        % Windows: Try to change the current status hardware/software
        else
            try
                if (DisableOpenGL == 0)
                    opengl('hardware');
                elseif (DisableOpenGL == 2)
                    opengl('software');
                end
                s = opengl('data');
            catch
                isOpenGL = 0;
            end
        end
        % Configure OpenGL
        switch DisableOpenGL
            case 0,  FigureRenderer = 'opengl';
            case 1,  FigureRenderer = 'painters';
            case 2,  FigureRenderer = 'opengl';
        end
        % Figure types for which the OpenGL renderer is used
        figTypes = {'DataTimeSeries', 'ResultsTimeSeries', 'Spectrum', '3DViz', 'Topography', 'MriViewer', 'Timefreq', 'Pac', 'Image'};
    end

    % Add comment if not running Brainstorm
    if isappdata(0, 'BrainstormRunning')
        fprintf(1, 'BST> OpenGL status: ');
    end
    % If OpenGL is running: save status
    if isOpenGL
        GlobalOpenGLStatus = DisableOpenGL;
        if (DisableOpenGL == 1)
            disp('disabled');
        elseif s.Software
            disp('software');
        else
            disp('hardware');
        end
    else
        GlobalOpenGLStatus = -1;
        FigureRenderer = 'painters';
        disp('failed');
    end

    % Display warning
    if isUnixWarning
        disp('BST> Warning: Switching between hardware and software at runtime is not possible on Linux systems.');
        disp('BST> To force Matlab to use the software OpenGL: matlab -softwareopengl');
        disp('BST> To force Matlab to use the hardware OpenGL: matlab -nosoftwareopengl');
    end

    % ===== UPDATE FIGURES =====
    % Get all figures
    hFigAll = bst_figures('GetFiguresByType', figTypes);
    % Set figures renderers
    if ~isempty(hFigAll)
        bst_progress('start', 'OpenGL configuration', 'Updating figures...');
        set(hFigAll, 'Renderer', FigureRenderer);
        drawnow;
        bst_progress('stop');
    end
end

%% ===== BUTTON: RESET =====
function ButtonReset_Callback(varargin)
    % Ask user confirmation
    isConfirm = java_dialog('confirm', ...
        ['You are about to reinitialize your Brainstorm installation, this will:' 10 10 ...
         ' - Detach all the protocols from the database (without deleting any file)' 10 ...
         ' - Reset all the Brainstorm and processes preferences' 10 ...
         ' - Restart Brainstorm as if it was the first time on this computer' 10 10 ...
         'Reset Brainstorm now?' 10 10], ...
        'Reset Brainstorm');
    if ~isConfirm
        return;
    end
    % Close panel
    gui_hide('Preferences');
    % Reset and restart brainstorm
    brainstorm stop;
    brainstorm reset;
    brainstorm;
end

%% ===== SYSTEM PATH: REMOVE DIR =====
% USAGE:         panel_options('SystemPathRemove', rmPath)          % Update system path
%         PATH = panel_options('SystemPathRemove', rmPath, PATH)    % Update user defined path (do not change system path)
function PATH = SystemPathRemove(rmPath, PATH)
    % Parse inputs
    if (nargin < 2)
        PATH = getenv('PATH');
        isSystemPath = 1;
    else
        isSystemPath = 0;
    end
    % Get system path
    PATH = getenv('PATH');
    PATH_split = str_split(PATH, pathsep);
    % Find elements to remove
    rm_split = str_split(rmPath, pathsep);
    iRm = find(ismember(PATH_split, rm_split));
    if isempty(iRm)
        return;
    end
    % Display removed path
    for i = 1:length(iRm)
        disp(['BST> Removed from system path:  ' PATH_split{iRm(i)}]);
    end
    % Remove elements from path string
    PATH_split(iRm) = [];
    PATH = '';
    for i = 1:length(PATH_split)
        if (i == 1)
            PATH = PATH_split{i};
        else
            PATH = [PATH, pathsep, PATH_split{i}];
        end
    end
    % Update system path
    if isSystemPath
        setenv('PATH', PATH);
    end
end

%% ===== SYSTEM PATH: ADD DIR =====
% USAGE:         panel_options('SystemPathAdd', rmPath)          % Update system path
%         PATH = panel_options('SystemPathAdd', rmPath, PATH)    % Update user defined path (do not change system path)
function PATH = SystemPathAdd(addPath, PATH)
    % Parse inputs
    if (nargin < 2)
        PATH = getenv('PATH');
        isSystemPath = 1;
    else
        isSystemPath = 0;
    end
    % Get system path
    PATH_split = str_split(PATH, pathsep);
    % Check which folders are not yet in the system path
    add_split = str_split(addPath, pathsep);
    for iPath = 1:length(add_split)
        if isdir(add_split{iPath}) && ~ismember(add_split{iPath}, PATH_split)
            PATH = [PATH, pathsep, add_split{iPath}];
            disp(['BST> Added to system path: ' add_split{iPath}]);
        end
    end
    % Update system path
    if isSystemPath
        setenv('PATH', PATH);
    end
end

author: brainstorm-tools


text:
clc;
close all;
clearvars;
make mex_lansvd.cpp;
options.verbosity = 1;
A = spx.data.mtx_mkt.abb313;
options.k = 4;
[U, S, V, details] = spx.fast.lansvd(A, 'k', 4, 'verbosity', 0);
% [U, S, V, details] = spx.fast.lansvd(A, options);

SS = svds(A, 4);

fprintf('Singular values by SVDS: ');
spx.io.print.vector(SS);
fprintf('Singular values by LANSVD: ');
spx.io.print.vector(S);

[U, S, V, details] = spx.fast.lansvd(A, 'lambda', 7.51);
fprintf('Singular values by LANSVD: ');
spx.io.print.vector(S);

author: indigits

repo: sparse-plex


text:
function model = rmGridFit_twoGaussiansToG(model,prediction,data,params,t)
% rmGridFit_twoGaussiansToG - core of ToG fit
%
% model = rmGridFit_twoGaussiansToG(model,prediction,data,params);
%
% Second gaussian can go positive or negative.
%
% 2008/01 SOD: split of from rmGridFit.

% input check
if nargin < 4,
    error('Not enough arguments');
end

% some variables we need
rssinf         = inf(size(data(1,:)),'single');
trends         = t.trends;
t_id           = t.dcid+2;

% stimulus sequence is needed because make second pRF on the fly
allstimimages = rmDecimate(params.analysis.allstimimages,...
    params.analysis.coarseDecimate);

%-----------------------------------
%--- fit different receptive fields profiles
%--- another loop --- and a slow one too
%-----------------------------------
tic; progress = 0;
for n=1:numel(params.analysis.x0),
    %-----------------------------------
    % progress monitor (10 dots) and time indicator
    %-----------------------------------
    if floor(n./numel(params.analysis.x0).*10)>progress,
        if progress==0,
            % print out estimated time left
            esttime = toc.*10;
            if floor(esttime./3600)>0,
                fprintf(1,'[%s]:Estimated processing time: %d hours.\t(%s)\n',...
                    mfilename, ceil(esttime./3600), datestr(now));
            else
                fprintf(1, '[%s]:Estimated processing time: %d minutes.\t(%s)\n',...
                    mfilename, ceil(esttime./60), datestr(now));
            end;
            fprintf(1,'[%s]:Grid (x,y,sigma) fit:',mfilename);drawnow;
        end;
        % progress monitor
        fprintf(1,'.');drawnow;
        progress = progress + 1;
    end;

    %-----------------------------------
    %--- first make all second rf profiles
    %-----------------------------------
    sigmaNew = params.analysis.sigmaRatio.*params.analysis.sigmaMajor(n);
    % limit to sigmaRatioMaxVal
    sigmaNew = sigmaNew(sigmaNew<=params.analysis.sigmaRatioMaxVal);
    % add sigmaRatioInfVal which essentially is on/off
    sigmaNew = [sigmaNew; params.analysis.sigmaRatioInfVal]; %#ok<AGROW>

    % Now we make it: slightly different call for speed reasons.
    z = zeros(size(sigmaNew));
    tmprf   = rfGaussian2d(params.analysis.X - params.analysis.x0(n),...
        params.analysis.Y - params.analysis.y0(n),...
        sigmaNew,sigmaNew, ...
        false, z, z);
    prediction2 = allstimimages*tmprf;

    %-----------------------------------
    %--- try two rf profiles, yet another loop
    %-----------------------------------
    for sr = 1:numel(sigmaNew),
        %-----------------------------------
        % Now apply GLM, see *_oneGaussian for logic.
        % New rules for this one:
        % 1. first Gaussian has to be positive
        % 2. there should be a positive response in the
        % center at all times. This
        % assumes Gaussians are unscaled (see rfGaussian2d).
        %-----------------------------------
        X     = [prediction(:,n) prediction2(:,sr) trends];
        b     = pinv(X)*data;
        rss   = rssinf;
        keep  = b(1,:)>0 & b(1,:)>-b(2,:);
        rss(keep) = sum((data(:,keep)-X*b(:,keep)).^2);

        %-----------------------------------
        %--- store data with lower rss
        %-----------------------------------
        minRssIndex = rss < model.rss;

        % now update
        model.x0(minRssIndex)       = params.analysis.x0(n);
        model.y0(minRssIndex)       = params.analysis.y0(n);
        model.s(minRssIndex)        = params.analysis.sigmaMajor(n);
        model.s_major(minRssIndex)        = params.analysis.sigmaMajor(n);
        model.s_minor(minRssIndex)        = params.analysis.sigmaMajor(n);
        model.s_theta(minRssIndex)        = params.analysis.theta(n);
        model.rss(minRssIndex)      = rss(minRssIndex);
        model.b([1:2 t_id],minRssIndex)    = b(:,minRssIndex);
        model.s2(minRssIndex)       = sigmaNew(sr);
    end;
end;

% end time monitor
et  = toc;
if floor(esttime/3600)>0,
    fprintf(1,'Done[%d hours].\t(%s)\n', ceil(et/3600), datestr(now));
else
    fprintf(1,'Done[%d minutes].\t(%s)\n', ceil(et/60), datestr(now));
end;
drawnow;
return;


text:
function predicted = classify_costs_classtree_multiclass_learner( CLASSIFIER, x )
% function predicted = classify_costs_classtree_multiclass_learner( CLASSIFIER, x )
% Classify a set of projected using pixel-wise grey level difference.
%
% Input:
%   CLASSIFIER, a structure returned by train_classtree_multiclass_learner.m
%   x, Pxn matrix (P is the number of pixels per image n is the number
%      of images).
%
% Output:
%     predicted -- 1 x n matrix with the lower cost  weak
%                   classifier output for the input data in x.
%
% See also:
%   train_COST_SAMME.m

% Author: Jose M. Buenaposada
n           = size(x,2);

% Evaluate the classification tree on the training data.
z = CLASSIFIER.TREE.eval( x' );
predicted = cellfun(@(x) str2double(x), z);

author: MengyangPu

repo: EDTER

save_path: github-repos/MATLAB/MengyangPu-EDTER


text:
% Purpose: Outputs DQ Table on Epoched Dataset (not ERP)
%
% Format :
%
% pop_DQ_preavg(ALLEEG,parameters)
%
% INPUTS:
%
% EEG or ALLEEG     - input dataset
%
%

function pop_DQ_preavg(ALLEEG, varargin)

%ERP = preloadERP;

if nargin < 1
    help pop_DQ_preavg
    return
end

if isobject(ALLEEG) % eegobj
    whenEEGisanObject
    return
end

if nargin == 1
    currdata = evalin('base', 'CURRENTSET');

    if currdata==0
        msgboxText =  'pop_DQ_preavg() error: cannot average an empty dataset!!!';
        title      = 'ERPLAB: No data';
        errorfound(msgboxText, title);
        return
    end

    % read values in memory for this function
    def  = erpworkingmemory('pop_DQ_preavg');
    % def{1} - dataset indx, def{2} - artcrit, def{3} - wavg, def{4} - stderror, def{5} - exclude boundaries,
    % def{6} - ERP type, def{7} - wintaper type, def{8} - wintaper function,
    % def{9} - data quality flag, def{10} - DQ_spec_structure,
    % def{11} - DQ pre-avg flag, def {12} - DQ_custom_wins

     if isempty(def) || numel(def)~=12
        % Should not be empty, and have exactly 12 elements. Else, fallback to:
        def = {1 1 1 1 1 0 0 [] 1 [] 1 0};

    end

    % epochs per dataset
    nepochperdata = zeros(1, length(ALLEEG));
    for k=1:length(ALLEEG)
        if isempty(ALLEEG(k).data)
            nepochperdata(k) = 0; % JLC.08/20/13
        else
            nepochperdata(k) = ALLEEG(k).trials;
        end
    end

    timelimits = 1000 * [ALLEEG(currdata).xmin ALLEEG(currdata).xmax]; % ms

    %
    % preAverager GUI
    %

    answer = DQ_preavg(currdata, def, nepochperdata, timelimits);

    if isempty(answer)
        disp('User selected Cancel')
        return
    end
    setindex = answer{1};   % datasets to average

    if numel(setindex) > 1
        disp('This tool cannot consider more than one .set file at a time!')
        return
    end

    %
    % Artifact rejection criteria for averaging
    %
    %  artcrite = 0 --> averaging all (good and bad trials)
    %  artcrite = 1 --> averaging only good trials
    %  artcrite = 2 --> averaging only bad trials
    %  artcrite is cellarray  --> averaging only specified epoch indices
    artcrite  = answer{2};
    if ~iscell(artcrite)
        if artcrite==0
            artcritestr = 'all';
        elseif artcrite==1
            artcritestr = 'good';
        elseif artcrite==2
            artcritestr = 'bad';
        else
            artcritestr = artcrite;
        end
    else
        artcritestr = artcrite; % fixed bug. May 1, 2012
    end

    % Standard deviation option. 1= yes, 0=no
    stderror    = answer{4};

    % exclude epochs having boundary events
    excbound = answer{5};

    % Compute ERP, evoked power spectrum (EPS), and total power
    % spectrum (TPS).
    compu2do = answer{6}; % 0:ERP; 1:ERP+TPS; 2:ERP+EPS; 3:ERP+BOTH
    wintype  = answer{7}; % taper data with window: 0:no; 1:yes
    wintfunc = answer{8}; % taper function and (sub)window

    % Write the analytic Standardized Measurment Error info
    DQ_flag = answer{9};
    DQ_spec = answer{10};
    DQ_preavg_txt = answer{11};
    DQcustom_wins = answer{12};

    % store setting in erplab working memory
    def(1:12)    = {setindex, artcrite, 1, stderror, excbound, compu2do, wintype, wintfunc,DQ_flag,DQ_spec,DQ_preavg_txt,DQcustom_wins};
    erpworkingmemory('pop_DQ_preavg', def);

    if stderror==1
        stdsstr = 'on';
    else
        stdsstr = 'off';
    end
    if excbound==1
        excboundstr = 'on';
    else
        excboundstr = 'off';
    end
    if wintype==1
        wintypestr = wintfunc;
    else
        wintypestr = 'off';
    end

    %Here, use ERP_averager behind the scence

    [ERPpreavg, erpcom]  = pop_averager(ALLEEG, 'DSindex', setindex, 'Criterion', artcritestr,...
        'SEM', stdsstr, 'Saveas', 'off', 'Warning', 'off', 'ExcludeBoundary', excboundstr,...
        'DQ_flag',DQ_flag,'DQ_spec',DQ_spec, 'DQ_preavg_txt', DQ_preavg_txt,'DQ_custom_wins', DQcustom_wins, 'History', '');

    pause(0.1);

    %Here, pass hidden ERP struct to DQTableGUI
    ALLERP = [];
    CURRENTPREAVG = 1;
    ERPpreavg.erpname = ALLEEG(setindex).setname; %setname instead of erpname in DQ Table

    DQ_Table_GUI(ERPpreavg,ALLERP,CURRENTPREAVG,1);

end

end

author: ucdavis

repo: erplab

save_path: github-repos/MATLAB/ucdavis-erplab