function [X, fX, i] = minimize_lbfgsb(X, f, length, varargin)

% Minimize a differentiable multivariate function using quasi Newton.
%
% Usage: [X, fX, i] = minimize_lbfgsb(X, f, length, P1, P2, P3, ... )
%
% X       initial guess; may be of any type, including struct and cell array
% f       the name or pointer to the function to be minimized. The function
%         f must return two arguments, the value of the function, and it's
%         partial derivatives wrt the elements of X. The partial derivative
%         must have the same type as X.
% length  length of the run; if it is positive, it gives the maximum number of
%         line searches, if negative its absolute gives the maximum allowed
%         number of function evaluations. Optionally, length can have a second
%         component, which will indicate the reduction in function value to be
%         expected in the first line-search (defaults to 1.0).
% P1, P2  ... parameters are passed to the function f.
%
% X       the returned solution
% fX      vector of function values indicating progress made
% i       number of iterations (line searches or function evaluations,
%         depending on the sign of "length") used at termination.
%
% The function returns when either its length is up, or if no further progress
% can be made (ie, we are at a (local) minimum, or so close that due to
% numerical problems, we cannot get any closer). NOTE: If the function
% terminates within a few iterations, it could be an indication that the
% function values and derivatives are not consistent (ie, there may be a bug in
% the implementation of your "f" function).
%
% Copyright (C) 2010 by Hannes Nickisch, 2010-02-05

% global variables serve as communication interface between calls
global minimize_lbfgsb_iteration_number
global minimize_lbfgsb_objective
global minimize_lbfgsb_gradient
global minimize_lbfgsb_X

% init global variables
minimize_lbfgsb_iteration_number = 0;
minimize_lbfgsb_objective = Inf;
minimize_lbfgsb_gradient = 0*unwrap2vec(X);
minimize_lbfgsb_X = X;

X0 = X;
lb = -Inf*ones(size(unwrap2vec(X0)));
ub =  Inf*ones(size(unwrap2vec(X0)));
maxiter = abs(length); % max number of iterations

% no callback routine used so far
% m is the number of saved vectors used to estimate the Hessian
% factr is the precision 1e-12
X = lbfgsb( unwrap2vec(X0), lb, ub, 'minimize_lbfgsb_objfun', ...
                                'minimize_lbfgsb_gradfun', ...
         {f,X0,varargin{:}}, [], ...
         'maxiter',maxiter, 'm',4, 'factr',1e-12, 'pgtol',1e-5);
i = minimize_lbfgsb_iteration_number;
fX = minimize_lbfgsb_objective;
X = rewrap(X0,X);

% clear global variables
clear minimize_lbfgsb_iteration_number
clear minimize_lbfgsb_objective
clear minimize_lbfgsb_gradient
clear minimize_lbfgsb_X

% Extract the numerical values from "s" into the column vector "v". The
% variable "s" can be of any type, including struct and cell array.
% Non-numerical elements are ignored. See also the reverse rewrap.m.
function v = unwrap2vec(s)
  v = [];
  if isnumeric(s)
    v = s(:);                       % numeric values are recast to column vector
  elseif isstruct(s)
    v = unwrap2vec(struct2cell(orderfields(s)));% alphabetize, conv to cell, recurse
  elseif iscell(s)
    for i = 1:numel(s)            % cell array elements are handled sequentially
      v = [v; unwrap2vec(s{i})];
    end
  end                                                  % other types are ignored

% Map the numerical elements in the vector "v" onto the variables "s" which can
% be of any type. The number of numerical elements must match; on exit "v"
% should be empty. Non-numerical entries are just copied. See also unwrap2vec.m.
function [s v] = rewrap(s, v)
  if isnumeric(s)
    if numel(v) < numel(s)
      error('The vector for conversion contains too few elements')
    end
    s = reshape(v(1:numel(s)), size(s));           % numeric values are reshaped
    v = v(numel(s)+1:end);                       % remaining arguments passed on
  elseif isstruct(s)
    [s p] = orderfields(s); p(p) = 1:numel(p);     % alphabetize, store ordering
    [t v] = rewrap(struct2cell(s), v);                % convert to cell, recurse
    s = orderfields(cell2struct(t,fieldnames(s),1),p); % conv to struct, reorder
  elseif iscell(s)
    for i = 1:numel(s)            % cell array elements are handled sequentially
      [s{i} v] = rewrap(s{i}, v);
    end
  end                                            % other types are not processed


function m = uminus(k)
%  kronMatrix/uminus
%
%     -k negates the elements of k.
%
%     -kron(k) == kron(-k)

m = k;
if (length(m.a) > length(m.b))
   m.b = -(m.b);
else
   m.a = -(m.a);
end


function savemphtxt(node, face, elem, filename)
%
% savemphtxt(node, face, elem, filename)
%
% save tetrahedron mesh to comsol file (.mphtxt)
%
% author: Donghyeon Kim (danielkim<at> gist.ac.kr)
% date: 2011/09/29
%
% input:
%      node: input, node list, dimension (nn,3)
%      face: input, surface face element list with label, dimension (be,4)
%      elem: input, tetrahedron element list with label, dimension (ne,5)
%      filename: input, output file name
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

n_node = size(node,1);
n_face = size(face,1);
n_elem = size(elem,1);

elem(:,1:4)=meshreorient(node(:,1:3),elem(:,1:4));

if(size(face,2)<4)
    face(:,4)=1;
elseif(min(face(:,4))==0)
    face(:,4)=face(:,4)+1;
end

if(size(elem,2)<5)
    elem(:,5)=1;
elseif(min(elem(:,5))==0)
    elem(:,5)=elem(:,5)+1;
end

fp = fopen(filename,'w');
fprintf(fp,'# Created by iso2mesh (http://iso2mesh.sf.net)\n');
fprintf(fp,'0 1\n1\n5 mesh1\n1\n3 obj\n\n');
fprintf(fp,'0 0 1\n4 Mesh\n2\n3\n%d\n1\n',n_node);

% Write Node information
fprintf(fp,'%.16f %.16f %.16f\n',node(:,1:3).');
fprintf(fp, '\n2\n\n3 tri\n');

% Write Tri information
fprintf(fp, '\n3\n');
fprintf(fp, '%d\n\n',n_face);
fprintf(fp,'%d %d %d\n',face(:,1:3).');

fprintf(fp, '\n1\n0\n');
fprintf(fp, '%d\n',n_face);
fprintf(fp,'%d\n',face(:,4).');

fprintf(fp, '\n%d\n',n_face);
fprintf(fp,'%d %d\n', zeros(0,n_face));

% Write Tet information
fprintf(fp, '\n\n3 tet\n4\n\n%d\n', n_elem);
fprintf(fp,'%d %d %d %d\n',elem(:,1:4).');

fprintf(fp, '\n4\n0\n%d\n%d\n', n_elem);
fprintf(fp,'%d\n',elem(:,5).');

fprintf(fp,'\n0\n');
fclose(fp);


function changed = Changed(Problem,Population)
% Detect whether the problem changes

%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    RePop1  = Population(randperm(end,ceil(end/10)));
    RePop2  = Problem.Evaluation(RePop1.decs);
    changed = ~isequal(RePop1.objs,RePop2.objs) || ~isequal(RePop1.cons,RePop2.cons);
end


%combfirst Returns the first combination in order of shifting the least left
%number to the right.
%
%  function com=combfirst(n, k)
%
%n and k has the meaning of combination number.
function com=combfirst(n, k)

com=find(1 == ones(1,k-1));
com=[com k-1];

return


function plotSuperVsRectangleOptim
mCase = 'Middle';
folderR = ['/home/alex/Desktop/ExperimentingPlotRectangle',mCase,'/'];
[iter,cost,maxStress] = obtainCostShapes(folderR);
f = figure();
h{1} = plot(iter,[cost;maxStress]','b');
hline = findobj(gcf, 'type', 'line');
set(hline(1),'LineStyle','--')

folderS = ['/home/alex/Desktop/ExperimentingPlotSuperEllipse',mCase,'/'];
[iter,costS,maxStressS] = obtainCostShapes(folderS);
hold on
h{2} = plot(iter,[costS;maxStressS]','r');
hline = findobj(gcf, 'type', 'line');
set(hline(1),'LineStyle','--')

leg = {'Rectangle Amplified Stress p', 'Amplified Stress max',...
       'Superellipse Amplified Stress p', 'Superellipse Stress max'};
legend(leg)
printer = plotPrinter(f,h);
path = '/home/alex/Dropbox/GregoireMeetings/GregoireMeeting25Janvier';
output = fullfile(path,['Convergence',mCase]);
printer.print(output)

end

function [iter,stress,maxStress] = obtainCostShapes(folder)
fNameMon = fullfile(folder,'Monitoring.fig');
h = openfig(fNameMon);
handles = findobj(h,'Type','line');
iter = get(handles(5),'Xdata');
stress = get(handles(11),'Ydata');
maxStress = get(handles(4),'Ydata');
close(h)
end


function gpcf = gpcf_constant(varargin)
%GPCF_CONSTANT  Create a constant covariance function
%
%  Description
%    GPCF = GPCF_CONSTANT('PARAM1',VALUE1,'PARAM2,VALUE2,...)
%    creates a squared exponential covariance function structure in
%    which the named parameters have the specified values. Any
%    unspecified parameters are set to default values.
%
%    GPCF = GPCF_CONSTANT(GPCF,'PARAM1',VALUE1,'PARAM2,VALUE2,...)
%    modify a covariance function structure with the named
%    parameters altered with the specified values.
%
%    Parameters for constant covariance function [default]
%      constSigma2       - magnitude (squared) [0.1]
%      constSigma2_prior - prior for constSigma2 [prior_logunif]
%
%    Note! If the prior is 'prior_fixed' then the parameter in
%    question is considered fixed and it is not handled in
%    optimization, grid integration, MCMC etc.
%
%  See also
%    GP_SET, GPCF_*, PRIOR_*, MEAN_*

% Copyright (c) 2007-2010 Jarno Vanhatalo
% Copyright (c) 2010      Jaakko Riihimaki, Aki Vehtari

% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.

  ip=inputParser;
  ip.FunctionName = 'GPCF_CONSTANT';
  ip.addOptional('gpcf', [], @isstruct);
  ip.addParamValue('constSigma2',0.1, @(x) isscalar(x) && x>0);
  ip.addParamValue('constSigma2_prior',prior_logunif, @(x) isstruct(x) || isempty(x));
  ip.parse(varargin{:});
  gpcf=ip.Results.gpcf;

  if isempty(gpcf)
    init=true;
    gpcf.type = 'gpcf_constant';
  else
    if ~isfield(gpcf,'type') && ~isequal(gpcf.type,'gpcf_constant')
      error('First argument does not seem to be a valid covariance function structure')
    end
    init=false;
  end

  % Initialize parameter
  if init || ~ismember('constSigma2',ip.UsingDefaults)
    gpcf.constSigma2=ip.Results.constSigma2;
  end

  % Initialize prior structure
  if init
    gpcf.p=[];
  end
  if init || ~ismember('constSigma2_prior',ip.UsingDefaults)
    gpcf.p.constSigma2=ip.Results.constSigma2_prior;
  end

  if init
    % Set the function handles to the subfunctions
    gpcf.fh.pak = @gpcf_constant_pak;
    gpcf.fh.unpak = @gpcf_constant_unpak;
    gpcf.fh.lp = @gpcf_constant_lp;
    gpcf.fh.lpg = @gpcf_constant_lpg;
    gpcf.fh.cfg = @gpcf_constant_cfg;
    gpcf.fh.ginput = @gpcf_constant_ginput;
    gpcf.fh.cov = @gpcf_constant_cov;
    gpcf.fh.trcov  = @gpcf_constant_trcov;
    gpcf.fh.trvar  = @gpcf_constant_trvar;
    gpcf.fh.recappend = @gpcf_constant_recappend;
  end

end

function [w, s] = gpcf_constant_pak(gpcf, w)
%GPCF_CONSTANT_PAK  Combine GP covariance function parameters into
%                   one vector.
%
%  Description
%    W = GPCF_CONSTANT_PAK(GPCF) takes a covariance function
%    structure GPCF and combines the covariance function
%    parameters and their hyperparameters into a single row
%    vector W. This is a mandatory subfunction used for example
%    in energy and gradient computations.
%
%       w = [ log(gpcf.constSigma2)
%             (hyperparameters of gpcf.constSigma2)]'
%
%  See also
%    GPCF_CONSTANT_UNPAK

  w = []; s = {};

  if ~isempty(gpcf.p.constSigma2)
    w = log(gpcf.constSigma2);
    s = [s 'log(constant.constSigma2)'];
    % Hyperparameters of constSigma2
    [wh sh] = gpcf.p.constSigma2.fh.pak(gpcf.p.constSigma2);
    w = [w wh];
    s = [s sh];
  end
end

function [gpcf, w] = gpcf_constant_unpak(gpcf, w)
%GPCF_CONSTANT_UNPAK  Sets the covariance function parameters
%                     into the structure
%
%  Description
%    [GPCF, W] = GPCF_CONSTANT_UNPAK(GPCF, W) takes a covariance
%    function structure GPCF and a parameter vector W, and
%    returns a covariance function structure identical to the
%    input, except that the covariance parameters have been set
%    to the values in W. Deletes the values set to GPCF from W
%    and returns the modified W. This is a mandatory subfunction
%    used for example in energy and gradient computations.
%
%    Assignment is inverse of
%       w = [ log(gpcf.constSigma2)
%             (hyperparameters of gpcf.constSigma2)]'
%
%  See also
%   GPCF_CONSTANT_PAK

  gpp=gpcf.p;
  if ~isempty(gpp.constSigma2)
    gpcf.constSigma2 = exp(w(1));
    w = w(2:end);
    % Hyperparameters of magnSigma2
    [p, w] = gpcf.p.constSigma2.fh.unpak(gpcf.p.constSigma2, w);
    gpcf.p.constSigma2 = p;
  end
end

function lp = gpcf_constant_lp(gpcf)
%GPCF_CONSTANT_LP  Evaluate the log prior of covariance function parameters
%
%  Description
%    LP = GPCF_CONSTANT_LP(GPCF) takes a covariance function
%    structure GPCF and returns log(p(th)), where th collects the
%    parameters. This is a mandatory subfunction used for example
%    in energy computations.
%
%  See also
%    GPCF_CONSTANT_PAK, GPCF_CONSTANT_UNPAK, GPCF_CONSTANT_LPG, GP_E

% Evaluate the prior contribution to the error. The parameters that
% are sampled are from space W = log(w) where w is all the
% "real" samples. On the other hand errors are evaluated in the
% W-space so we need take into account also the Jacobian of
% transformation W -> w = exp(W). See Gelman et.al., 2004,
% Bayesian data Analysis, second edition, p24.

  lp = 0;
  gpp=gpcf.p;
  if ~isempty(gpp.constSigma2)
    lp = gpp.constSigma2.fh.lp(gpcf.constSigma2, gpp.constSigma2) +log(gpcf.constSigma2);
  end
end

function lpg = gpcf_constant_lpg(gpcf)
%GPCF_CONSTANT_LPG  Evaluate gradient of the log prior with respect
%               to the parameters.
%
%  Description
%    LPG = GPCF_CONSTANT_LPG(GPCF) takes a covariance function
%    structure GPCF and returns LPG = d log (p(th))/dth, where th
%    is the vector of parameters. This is a mandatory subfunction
%    used for example in gradient computations.
%
%  See also
%    GPCF_CONSTANT_PAK, GPCF_CONSTANT_UNPAK, GPCF_CONSTANT_LP, GP_G

  lpg = [];
  gpp=gpcf.p;

  if ~isempty(gpcf.p.constSigma2)
    lpgs = gpp.constSigma2.fh.lpg(gpcf.constSigma2, gpp.constSigma2);
    lpg = [lpg lpgs(1).*gpcf.constSigma2+1 lpgs(2:end)];
  end
end

function DKff = gpcf_constant_cfg(gpcf, x, x2, mask, i1)
%GPCF_CONSTANT_CFG  Evaluate gradient of covariance function
%                   with respect to the parameters
%
%  Description
%    DKff = GPCF_CONSTANT_CFG(GPCF, X) takes a
%    covariance function structure GPCF, a matrix X of input
%    vectors and returns DKff, the gradients of covariance matrix
%    Kff = k(X,X) with respect to th (cell array with matrix
%    elements). This is a mandatory subfunction used in gradient
%    computations.
%
%    DKff = GPCF_CONSTANT_CFG(GPCF, X, X2) takes a
%    covariance function structure GPCF, a matrix X of input
%    vectors and returns DKff, the gradients of covariance matrix
%    Kff = k(X,X2) with respect to th (cell array with matrix
%    elements). This subfunction is needed when using sparse
%    approximations (e.g. FIC).
%
%    DKff = GPCF_CONSTANT_CFG(GPCF, X, [], MASK)
%    takes a covariance function structure GPCF, a matrix X of
%    input vectors and returns DKff, the diagonal of gradients of
%    covariance matrix Kff = k(X,X2) with respect to th (cell
%    array with matrix elements). This subfunction is needed when
%    using sparse approximations (e.g. FIC).
%
%  See also
%    GPCF_CONSTANT_PAK, GPCF_CONSTANT_UNPAK, GPCF_CONSTANT_LP, GP_G

  [n, m] =size(x);

  DKff = {};

  if nargin==5
    % Use memory save option
    if i1==0
      % Return number of hyperparameters
      if ~isempty(gpcf.p.constSigma2)
        DKff=1;
      else
        DKff=0;
      end
      return
    end
  end

  % Evaluate: DKff{1} = d Kff / d constSigma2
  %           DKff{2} = d Kff / d coeffSigma2
  % NOTE! Here we have already taken into account that the parameters are transformed
  % through log() and thus dK/dlog(p) = p * dK/dp

  % evaluate the gradient for training covariance
  if nargin == 2 || (isempty(x2) && isempty(mask))

    if ~isempty(gpcf.p.constSigma2)
      DKff{1}=ones(n)*gpcf.constSigma2;
    end

    % Evaluate the gradient of non-symmetric covariance (e.g. K_fu)
  elseif nargin == 3 || isempty(mask)
    if size(x,2) ~= size(x2,2)
      error('gpcf_constant -> _ghyper: The number of columns in x and x2 has to be the same. ')
    end

    if ~isempty(gpcf.p.constSigma2)
      DKff{1}=ones([n size(x2,1)])*gpcf.constSigma2;
    end

    % Evaluate: DKff{1}    = d mask(Kff,I) / d constSigma2
    %           DKff{2...} = d mask(Kff,I) / d coeffSigma2
  elseif nargin == 4 || nargin == 5

    if ~isempty(gpcf.p.constSigma2)
      DKff{1}=ones(n,1)*gpcf.constSigma2; % d mask(Kff,I) / d constSigma2
    end
  end
  if nargin==5
    DKff=DKff{1};
  end

end

function DKff = gpcf_constant_ginput(gpcf, x, x2, i1)
%GPCF_CONSTANT_GINPUT  Evaluate gradient of covariance function with
%                      respect to x.
%
%  Description
%    DKff = GPCF_CONSTANT_GINPUT(GPCF, X) takes a covariance
%    function structure GPCF, a matrix X of input vectors and
%    returns DKff, the gradients of covariance matrix Kff =
%    k(X,X) with respect to X (cell array with matrix elements).
%    This subfunction is needed when computing gradients with
%    respect to inducing inputs in sparse approximations.
%
%    DKff = GPCF_CONSTANT_GINPUT(GPCF, X, X2) takes a covariance
%    function structure GPCF, a matrix X of input vectors and
%    returns DKff, the gradients of covariance matrix Kff =
%    k(X,X2) with respect to X (cell array with matrix elements).
%    This subfunction is needed when computing gradients with
%    respect to inducing inputs in sparse approximations.
%
%    DKff = GPCF_CONSTANT_GINPUT(GPCF, X, X2, i) takes a covariance
%    function structure GPCF, a matrix X of input vectors
%    and returns DKff, the gradients of covariance matrix Kff =
%    k(X,X2), or k(X,X) if X2 is empty, with respect to ith
%    covariate in X. This subfunction is needed when using
%    memory save option in gp_set.
%
%  See also
%    GPCF_CONSTANT_PAK, GPCF_CONSTANT_UNPAK, GPCF_CONSTANT_LP, GP_G

  [n, m] =size(x);
  if nargin==4
    % Use memory save option
    if i1==0
      % Return number of covariates
      if isfield(gpcf,'selectedVariables')
        DKff=length(gpcf.selectedVariables);
      else
        DKff=m;
      end
      return
    end
  end

  if nargin == 2 || isempty(x2)
    ii1 = 0;
    for i=1:m
      for j = 1:n
        ii1 = ii1 + 1;
        DKff{ii1} = zeros(n);
      end
    end

  elseif nargin == 3 || nargin == 4
    %K = feval(gpcf.fh.cov, gpcf, x, x2);

    ii1 = 0;
    for i=1:m
      for j = 1:n
        ii1 = ii1 + 1;
        DKff{ii1} = zeros(n, size(x2,1));
        gprior(ii1) = 0;
      end
    end
  end
  if nargin==5
    DKff=DKff{1};
  end
end

function C = gpcf_constant_cov(gpcf, x1, x2, varargin)
%GP_CONSTANT_COV  Evaluate covariance matrix between two input vectors
%
%  Description
%    C = GP_CONSTANT_COV(GP, TX, X) takes in covariance function
%    of a Gaussian process GP and two matrixes TX and X that
%    contain input vectors to GP. Returns covariance matrix C.
%    Every element ij of C contains covariance between inputs i
%    in TX and j in X. This is a mandatory subfunction used for
%    example in prediction and energy computations.
%
%  See also
%    GPCF_CONSTANT_TRCOV, GPCF_CONSTANT_TRVAR, GP_COV, GP_TRCOV

  if isempty(x2)
    x2=x1;
  end
  [n1,m1]=size(x1);
  [n2,m2]=size(x2);

  if m1~=m2
    error('the number of columns of X1 and X2 has to be same')
  end

  C = ones(n1,n2)*gpcf.constSigma2;
end

function C = gpcf_constant_trcov(gpcf, x)
%GP_CONSTANT_TRCOV  Evaluate training covariance matrix of inputs
%
%  Description
%    C = GP_CONSTANT_TRCOV(GP, TX) takes in covariance function
%    of a Gaussian process GP and matrix TX that contains
%    training input vectors. Returns covariance matrix C. Every
%    element ij of C contains covariance between inputs i and j
%    in TX. This is a mandatory subfunction used for example in
%    prediction and energy computations.
%
%  See also
%    GPCF_CONSTANT_COV, GPCF_CONSTANT_TRVAR, GP_COV, GP_TRCOV

  n =size(x,1);
  C = ones(n,n)*gpcf.constSigma2;

end

function C = gpcf_constant_trvar(gpcf, x)
%GP_CONSTANT_TRVAR  Evaluate training variance vector
%
%  Description
%    C = GP_CONSTANT_TRVAR(GPCF, TX) takes in covariance function
%    of a Gaussian process GPCF and matrix TX that contains
%    training inputs. Returns variance vector C. Every
%    element i of C contains variance of input i in TX. This is
%    a mandatory subfunction used for example in prediction and
%    energy computations.
%
%  See also
%    GPCF_CONSTANT_COV, GP_COV, GP_TRCOV

  n =size(x,1);
  C = ones(n,1)*gpcf.constSigma2;

end

function reccf = gpcf_constant_recappend(reccf, ri, gpcf)
%RECAPPEND Record append
%
%  Description
%    RECCF = GPCF_CONSTANT_RECAPPEND(RECCF, RI, GPCF) takes a
%    covariance function record structure RECCF, record index RI
%    and covariance function structure GPCF with the current MCMC
%    samples of the parameters. Returns RECCF which contains all
%    the old samples and the current samples from GPCF. This
%    subfunction is needed when using MCMC sampling (gp_mc).
%
%  See also
%    GP_MC and GP_MC -> RECAPPEND

  if nargin == 2
    % Initialize the record
    reccf.type = 'gpcf_constant';

    % Initialize parameters
    reccf.constSigma2 = [];

    % Set the function handles
    reccf.fh.pak = @gpcf_constant_pak;
    reccf.fh.unpak = @gpcf_constant_unpak;
    reccf.fh.lp = @gpcf_constant_lp;
    reccf.fh.lpg = @gpcf_constant_lpg;
    reccf.fh.cfg = @gpcf_constant_cfg;
    reccf.fh.cov = @gpcf_constant_cov;
    reccf.fh.trcov  = @gpcf_constant_trcov;
    reccf.fh.trvar  = @gpcf_constant_trvar;
    reccf.fh.recappend = @gpcf_constant_recappend;
    reccf.p=[];
    reccf.p.constSigma2=[];
    if ~isempty(ri.p.constSigma2)
      reccf.p.constSigma2 = ri.p.constSigma2;
    end

  else
    % Append to the record
    gpp = gpcf.p;

    % record constSigma2
    reccf.constSigma2(ri,:)=gpcf.constSigma2;
    if isfield(gpp,'constSigma2') && ~isempty(gpp.constSigma2)
      reccf.p.constSigma2 = gpp.constSigma2.fh.recappend(reccf.p.constSigma2, ri, gpcf.p.constSigma2);
    end
  end
end


function failed_old_fixsource

% MEM 1gb
% WALLTIME 00:10:00
% DEPENDENCY

% this script tests the fixsource function which is part of ft_checkdata

%-------------------------------------
%generate data
rand('twister',20090408);
data = [];
data.fsample = 1000;
data.cfg     = [];

nsmp  = 1000;
nchan = 80;
for k = 1:10
  data.trial{k} = randn(nchan,nsmp);
  data.time{k}  = ([1:nsmp]-1)./data.fsample;
end

%create grad-structure and add to data
[pnt,tri] = mesh_sphere(162);
nrm       = surface_normals(pnt, tri, 'vertex');
pnt       = pnt.*12;
[srt,ind] = sort(pnt(:,3),'descend');
grad      = [];
grad.pnt  = pnt(ind(1:nchan),:);
grad.ori  = nrm(ind(1:nchan),:);
grad.tra  = eye(nchan);
for k = 1:nchan
  grad.label{k} = ['chan',num2str(k,'%03d')];
end
data.grad  = grad;
data.label = grad.label;

%create vol
vol   = [];
vol.o = [0 0 2];
vol.r = 8;

%prepare leadfields and grid
cfg                 = [];
cfg.sourcemodel.resolution = 1.5;
cfg.headmodel       = vol;
cfg.grad            = grad;
grid                = ft_prepare_leadfield(cfg);

%do spectral analysis
cfg        = [];
cfg.method = 'mtmfft';
cfg.output = 'fourier';
cfg.foilim = [2 100];
cfg.pad    = 1;
cfg.tapsmofrq = 3;
freq       = ft_freqanalysis(cfg, data);

%do timelocked analysis
cfg            = [];
cfg.covariance = 'yes';
cfg.covariancewindow = [0 0.999];
cfg.keeptrials = 'yes';
tlck           = ft_timelockanalysis(cfg, data);

%-----------------------------------------------

%-----------------------------------------------
%source reconstruction part

%without fixedori
cfgs           = [];
cfgs.grid      = grid;
cfgs.frequency = 20;
cfgs.method    = 'dics';
cfgs.lambda    = '10%';
cfgs.keepfilter = 'yes';
cfgs.feedback  = 'textbar';
cfgs.vol       = vol;
cfgs.fixedori  = 'no';
cfgs.keepcsd   = 'yes';
cfgs.realfilter = 'yes';
cfgs.keepleadfield = 'yes';
source         = ft_sourceanalysis(cfgs,freq);
sdics          = ft_checkdata(source, 'sourcerepresentation', 'new');

cfgs.sourcemodel.filter = sdics.filter;
cfgs.method      = 'pcc';
cfgs.keepmom     = 'yes';
source           = ft_sourceanalysis(cfgs, freq);
spcc1            = ft_checkdata(source, 'sourcerepresentation', 'new', 'haspow', 'yes');
%this gives a warning

cfgsd            = [];
cfgsd.projectmom = 'yes';
sd               = ft_sourcedescriptives(cfgsd, source);
spcc2            = ft_checkdata(sd, 'sourcerepresentation', 'new', 'haspow', 'yes');

%with fixedori
cfgs.grid     = grid;
cfgs.method   = 'dics';
cfgs.keepmom  = 'no';
cfgs.fixedori = 'yes';
source        = ft_sourceanalysis(cfgs, freq);
sdics2        = ft_checkdata(source, 'sourcerepresentation', 'new');

cfgs.sourcemodel.filter = sdics2.filter;
cfgs.method      = 'pcc';
cfgs.keepmom     = 'yes';

%there are two ways for not crashing the second round of ft_sourceanalysis
%with fixori = 'yes';
if all(islogical(source.inside))
  insidevec = find(source.inside);
else
  insidevec = source.inside;
end
for k = 1:numel(insidevec)
  kk = insidevec(k);
  cfgs.sourcemodel.leadfield{kk} = sdics2.leadfield{kk}*sdics2.ori{kk};
end
source = ft_sourceanalysis(cfgs, freq);
spcc1f = ft_checkdata(source, 'sourcerepresentation', 'new', 'haspow', 'yes');
%FIXME known problem: ori-field is missing here

% alternative
% append a mom to the grid as (3xN) matrix
cfgs.sourcemodel.mom = zeros(size(sourcemodel.pos))';
for k = 1:numel(insidevec)
  kk = insidevec(k);
  cfgs.sourcemodel.mom(:,kk) = sdics2.ori{kk};
end
%FIXME there's an issue here with mom being expected to be Nx3 and 3xN in ft_inverse_pcc
source = ft_sourceanalysis(cfgs, freq);
try,
  spcc2f = ft_checkdata(source, 'sourcerepresentation', 'new', 'haspow', 'yes');
catch
  error('this does not work');
end

%call sourcedescriptives to get a .trial field
cfgsd            = [];
cfgsd.keeptrials = 'yes';
sd               = ft_sourcedescriptives(cfgsd, source);
spcc3f           = ft_checkdata(sd, 'sourcerepresentation', 'new');

%lcmv
cfgs           = [];
cfgs.grid      = grid;
cfgs.frequency = 20;
cfgs.method    = 'lcmv';
cfgs.lambda    = '10%';
cfgs.keepfilter = 'yes';
cfgs.feedback  = 'textbar';
cfgs.vol       = vol;
cfgs.fixedori  = 'no';
cfgs.keepcov   = 'yes';
cfgs.keepleadfield = 'yes';
source         = ft_sourceanalysis(cfgs,tlck);
slcmv          = ft_checkdata(source, 'sourcerepresentation', 'new');

cfgs.sourcemodel.filter = slcmv.filter;
cfgs.rawtrial    = 'yes';
%cfgs.keepfilter  = 'no';
source           = ft_sourceanalysis(cfgs, tlck);
slcmv2           = ft_checkdata(source, 'sourcerepresentation', 'new');


function varargout = findContour(img, varargin)
%FINDCONTOUR Chain neigbor pixels to form a contour
%
%   Deprecated: replaced by function 'imChainPixels'
%
%   usage:
%   POINTS = findContour(IMG), or
%   [PX, PY] = findContour(IMG)
%   returns a list of points, chaining points visible in the image.
%   IMG shoud be a binary image, containing a single 8-connected loop.
%
%   See Also
%   bwboundaries
%
%   -----
%
%   author: David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 01/11/2003.
%

%   HISTORY
%   06/04/2004 add to graph lib, correct x-y ordering, and add doc.

warning('malimpa:deprecated', ...
    '"findContour" is deprecated, use "imChainPixels" instead');

% set to logical
img = img~=0;

% find points in the image
[pty, ptx] = find(img);

% Initialize iteration : first set the initial point
points = zeros(length(ptx), 2);
x0 = ptx(1);
y0 = pty(1);
points(1, 1) = x0;
points(1, 2) = y0;

% Then set the second point, in the neighbourhood of the first point
vois = findNeighbors(img, [x0 y0]);
x = vois(1, 1);
y = vois(1, 2);
points(2, 1) = x;
points(2, 2) = y;

% For each point, find all neighbours (should be only 2)
% Compare with point previously processed, and choose the other one.
% then shift points references, and loop until all points are processed.
for p=3:length(points)
    vois = findNeighbors(img, [x y]);
    if vois(1,1)==x0 && vois(1,2)==y0
        x0 = x;
        y0 = y;
        x = vois(2, 1);
        y = vois(2, 2);
    else
        x0 = x;
        y0 = y;
        x = vois(1, 1);
        y = vois(1, 2);
    end
    points(p, 1) = x;
    points(p, 2) = y;
end

% format results to match output
if nargout==1
    varargout{1} = points;
elseif nargout==2
    varargout{1} = points(:, 1);
    varargout{2} = points(:, 2);
end

return

function neighList = findNeighbors(img, coord)

xp = coord(1);
yp = coord(2);
neighList = [];
nv = 0;

for x = xp-1:xp+1
    if img(yp-1, x)
        nv = nv+1;
        neighList(nv, 1) = x; %#ok<AGROW>
        neighList(nv, 2) = yp-1;%#ok<AGROW>
    end
    if img(yp+1, x)
        nv = nv+1;
        neighList(nv, 1) = x;%#ok<AGROW>
        neighList(nv, 2) = yp+1;%#ok<AGROW>
    end
end

if img(yp, xp-1)
    nv = nv+1;
    neighList(nv, 1) = xp-1;
    neighList(nv, 2) = yp;
end
if img(yp, xp+1)
    nv = nv+1;
    neighList(nv, 1) = xp+1;
    neighList(nv, 2) = yp;
end


classdef tuneAD9361AGC < AD9361TRx & gen80211aTestWaveform & demod80211aTestWaveform
    properties (Access = public)
        %%
        % Toggle SIM_STUDY to control whether a simulation study or
        % a physical experiments-based study using a radio is conducted
        % SIM_STUDY - true/false
        SIM_STUDY = true
        % SIM_MODE controls the simulation mode as follows:
        %   value  |     channel     |   radio
        %---------------------------------------
        %     0    |   AWGN          |    No
        %     1    |   AWGN          |    Yes
        %     2    |   AWGN+Fading   |    No
        %     3    |   AWGN+Fading   |    Yes
        SIM_MODE = 3
        % GAIN_MODE controls whether the simulated gain applied to each
        % packet is constant or varying (applicable when SIM_STUDY is
        % set to true and SIM_MODE is set to 1 or 3)
        % 0 - uniform
        % 1 - non-uniform
        % If GAIN_MODE is set to 1, but SIM_MODE is set to 0 or 2, no AGC
        % is applied to the received signal and therefore, more bad packets
        % might be received than what is expected.
        GAIN_MODE = 1
        % SNR (dB) of the received test waveform (applicable when SIM_STUDY
        % is set to true)
        snr
    end

    methods
        %%
        % sim_settings needs to have the following fields:
        % SIM_STUDY - see above
        % SIM_MODE - see above
        % GAIN_MODE - see above
        % snr - SNR (dB)
        %
        % wlan_settings needs to have the following fields:
        % fc - carrier frequency
        % numPackets - number of WLAN frames
        % mcs - WLAN's MCS Index
        % seed - 0/xyz (0 - random seed; xyz - seed value)
        % See gen80211aTestWaveform.m for more details.
        %
        % ad9361_settings needs to have the following fields:
        % AGC_MODE - AGC mode (manual/slow/fast/receiver control)
        % LOG_ADC_OUTPUT - true/false (Toggle to log ADC block - It is
        % suggested that this quantity is set to false unless the number of
        % simulated packets is small. ADC runs at a higher rate than the
        % sample clock. So, the size of the log file will be significantly
        % larger if set to true.)
        % SAVE_LOG_DATA - true/false (Toggle to save log data to file)
        %
        % See AD9361TRx.m for more details.
        function obj = tuneAD9361AGC(sim_settings, wlan_settings, varargin)
            % generate IEEE 802.11a compliant test waveform
            obj = obj@gen80211aTestWaveform(sim_settings, wlan_settings);

            % apply AGC settings to the model and run simulations
            obj = obj@AD9361TRx(sim_settings, varargin);

            % demodulate IEEE 802.11a compliant test waveform
            obj = obj@demod80211aTestWaveform(sim_settings);

            obj.SIM_STUDY = sim_settings.SIM_STUDY;
            obj.SIM_MODE = sim_settings.SIM_MODE;
            obj.GAIN_MODE = sim_settings.GAIN_MODE;
            obj.snr = sim_settings.snr;
        end
    end
end


function huffman_test1
% HUFFMAN_TEST1
% This is a simple test to have a code profile of the functions

%   $Author: Giuseppe Ridino' $
%   $Revision: 1.0 $  $Date: 02-Jul-2004 16:47:25 $

profile clear
profile on -history

tic

data = uint8(256*sin(1:100000));
[zipped,info] = norm2huff(data);
unzipped = huff2norm(zipped,info);

toc

unzipped = uint8(unzipped);
ok = isequal(data,unzipped)

profile off
profile report


function [bboxes,idx] = doNMS(bboxes, thresh)

if isempty(bboxes)
    return
end
tmp = bboxes(:,1);
idx = 1;
for i = 2:size(bboxes,2)
    if max(getIOUFloat(tmp',bboxes(:,i)')) < thresh
        tmp = [tmp bboxes(:,i)];
        idx = [idx i];
    end
end
bboxes = tmp;


function y = upsample2(x,K)
for i = 1:size(x,3)
    y(:,:,i) = upsample(upsample(x(:,:,i),K)',K)';
end
end


%% t_glmComputeContrastMap
%
% Illustrates how to compute a contrast map for later projection onto a 3D
% mesh.
%
% Before proceeding with tutorial:
%	* Run t_glmRun.
%
% See also T_GLMRUN.
%
% Tested 01/04/2011 - MATLAB r2008a, Fedora 12, Current Repos
%
% Stanford VISTA
%

%% Initialize the key variables and data path:
% Data directory (where the mrSession file is located)
dataDir = fullfile(mrvDataRootPath,'functional','vwfaLoc');
dataType = 'MotionComp';

%% Retain original directory, change to data directory
curDir = pwd;
cd(dataDir);

%% Retrieve data structure and set data type:
vw_ip = initHiddenInplane();
vw_ip = viewSet(vw_ip, 'currentDataType', dataType);

%% Get information re: the experiment/trials:
stimuli = er_concatParfiles(vw_ip);
nConds = length(stimuli.condNums);

%% Print condition numbers and names for input into contrast fxn:
fprintf('[##] - Condition Name\n');
fprintf('---------------------\n');
for i = 1:nConds
    fprintf('[%02d] - %s\n', stimuli.condNums(i), stimuli.condNames{i});
end

%% Choose active and control conditions:
activeConds     = [0]; % Fixation
% versus
controlConds    = [1 2]; % Word & WordScramble

% Choose a name for the contrast - left empty to assign default
contrastName    = [];

vw_ip = viewSet(vw_ip, 'currentDataType', 'GLMs');
%% Compute the contrast map for view on mesh:
computeContrastMap2(vw_ip, activeConds, controlConds, contrastName);

%% Return to the original directory.
cd(curDir);

%% END


classdef prtFeatSelSfs < prtFeatSel
% prtFeatSelSfs   Sequential forward feature selection object.
%
%    FEATSEL = prtFeatSelSfs creates a sequental forward feature selection
%    object.
%
%    FEATSEL = prtFeatSelSfs(PROPERTY1, VALUE1, ...) constructs a
%    prttFeatSelSfs object FEATSEL with properties as specified by
%    PROPERTY/VALUE pair
%
%    A prtFeatSelSfsobject has the following properties:
%
%    nFeatures             - The number of features to be selected
%    showProgressBar       - Flag indicating whether or not to show the
%                            progress bar during feature selection.
%    evaluationMetric      - The metric to be used to determine which
%                            features are selected. evaluationMetric must
%                            be a function handle. The function handle must
%                            be in the form:
%                            @(dataSet)prtEval(prtClass, dataSet, varargin)
%                            where prtEvak is a prtEval function, prtClass
%                            is a prt classifier object, and varargin
%                            represents optional input arguments to a
%                            prtEval function.
%
%    peformance            - The performance obtained by the using the
%                            features selected.
%    selectedFeatures      - The indices of the features selected that gave
%                            the best performance.
%
%   A prtFeatSelExhaustive object inherits the TRAIN and RUN methods
%   from prtClass.
%
%   Example:
%
%   dataSet = prtDataGenFeatureSelection;         % Generate a data set
%   featSel = prtFeatSelSfs;          % Create a feature selction object
%   featSel.nFeatures = 3;            % Select only one feature of the data
%   featSel = featSel.train(dataSet); % Train the feature selection object
%   outDataSet = featSel.run(dataSet);% Extract the data set with only the
%                                     % selected features
%
%   %   Change the scoring function to prtScorePdAtPf, and change the
%   %   classification method to prtClassMAP
%
%   featSel.evaluationMetric = @(DS)prtEvalPdAtPf(prtClassMap, DS, .9);
%
%   featSel = featSel.train(dataSet);
%   outDataSet = featSel.run(dataSet);
%
 % See Also:  prtFeatSelStatic, prtFeatSelExhaustive

    properties (SetAccess=private)
        name = 'Sequentual Feature Selection' % Sequentual Feature Selection
        nameAbbreviation = 'SFS' % SFS
    end

    properties
        % General Classifier Properties
        nFeatures = 3;                    % The number of features to be selected
        evaluationMetric = @(DS)prtEvalAuc(prtClassFld,DS);   % The metric used to evaluate performance
    end

    properties (SetAccess = protected)
        performance = [];        % The evalutationMetric for the selected features
        selectedFeatures = [];   % The integer values of the selected features
    end

    methods
        function Obj = prtFeatSelSfs(varargin)
            Obj.isCrossValidateValid = false;
            Obj = prtUtilAssignStringValuePairs(Obj,varargin{:});
        end

        function Obj = set.nFeatures(Obj,val)
            if ~prtUtilIsPositiveScalarInteger(val);
                error('prt:prtFeatSelSfs','nFeatures must be a positive scalar integer.');
            end
            Obj.nFeatures = val;
        end

        function Obj = set.evaluationMetric(Obj,val)
            assert(isa(val, 'function_handle') && nargin(val)>=1,'prt:prtFeatSelExhaustive','evaluationMetric must be a function handle that accepts one input argument.');
            Obj.evaluationMetric = val;
        end

    end
    methods (Access=protected,Hidden=true)

        function Obj = trainAction(Obj,DS)

            nFeatsTotal = DS.nFeatures;
            nSelectFeatures = min(nFeatsTotal,Obj.nFeatures);

            Obj.performance = nan(1,nSelectFeatures);
            Obj.selectedFeatures = nan(1,nSelectFeatures);

            sfsSelectedFeatures = [];

            if Obj.showProgressBar
                h = prtUtilProgressBar(0,'Feature Selection - SFS','autoClose',true);
            end

            for j = 1:nSelectFeatures

                if Obj.showProgressBar && j == 1
                    h2 = prtUtilProgressBar(0,sprintf('Selecting Feature %d',j),'autoClose',false);
                elseif Obj.showProgressBar
                    h2.titleStr = sprintf('Selecting Feature %d',j);
                    h2.update(0);
                end

                availableFeatures = setdiff(1:nFeatsTotal,sfsSelectedFeatures);
                cPerformance = nan(size(availableFeatures));
                for i = 1:length(availableFeatures)
                    currentFeatureSet = cat(2,sfsSelectedFeatures,availableFeatures(i));
                    tempDataSet = DS.retainFeatures(currentFeatureSet);

                    cPerformance(i) = Obj.evaluationMetric(tempDataSet);

                    if Obj.showProgressBar
                        h2.update(i/length(availableFeatures));
                    end
                end

                if Obj.showProgressBar
                    % Make sure it's closed.
                    h2.update(1);
                end

                if all(~isfinite(cPerformance))
                    error('prt:prtFeatSelSfs','All evaluation matrics resulted in non-finite values. Check evalutionMetric');
                end

                % Randomly choose the next feature if more than one provide the same performance
                val = max(cPerformance);
                newFeatInd = find(cPerformance == val);
                newFeatInd = newFeatInd(max(1,ceil(rand*length(newFeatInd))));

                % In the (degenerate) case when rand==0, set the index to the first one
                Obj.performance(j) = val;
                sfsSelectedFeatures = cat(2,sfsSelectedFeatures,availableFeatures(newFeatInd));

                if Obj.showProgressBar
                    h.update(j/nSelectFeatures);
                end
            end
            Obj.selectedFeatures = sfsSelectedFeatures;
            if Obj.showProgressBar
                % Make sure it's closed.
                h.update(1);
            end
        end

        function DataSet = runAction(Obj,DataSet)
            if ~Obj.isTrained
                error('prt:prtFeatSelSfs','Attempt to run a prtFeatSel that is not trained');
            end
            DataSet = DataSet.retainFeatures(Obj.selectedFeatures);
        end
    end
end


classdef TestPCTSignatures
    %TestPCTSignatures

    methods (Static)
        function test_1
            img = imread(fullfile(mexopencv.root(),'test','books_left.jpg'));

            pct = cv.PCTSignatures();
            sig = pct.computeSignature(img);
            validateattributes(sig, {'numeric'}, {'2d', 'size',[NaN 8]});

            sigs = pct.computeSignatures({img, img});
            validateattributes(sigs, {'cell'}, {'vector', 'numel',2});

            out = cv.PCTSignatures.drawSignature(img, sig);
            validateattributes(out, {class(img)}, {'size',size(img)});
        end

        function test_2
            initPoints = cv.PCTSignatures.generateInitPoints(2000, 'Uniform');
            pct = cv.PCTSignatures(initPoints, 400);
            pct.GrayscaleBits = 4;
            assert(isequal(pct.GrayscaleBits, 4));
        end
    end

end


function varargout = decode(varargin)
% DECODE M-file for decode.fig
%      DECODE, by itself, creates a new DECODE or raises the existing
%      singleton*.
%
%      H = DECODE returns the handle to a new DECODE or the handle to
%      the existing singleton*.
%
%      DECODE('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in DECODE.M with the given input arguments.
%
%      DECODE('Property','Value',...) creates a new DECODE or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before decode_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to decode_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help decode

% Last Modified by GUIDE v2.5 27-Jul-2003 22:01:41

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @decode_OpeningFcn, ...
                   'gui_OutputFcn',  @decode_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin & isstr(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before decode is made visible.
function decode_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to decode (see VARARGIN)

% Choose default command line output for decode
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes decode wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = decode_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in b1.
function b1_Callback(hObject, eventdata, handles)
% hObject    handle to b1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=697;f2=1209;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;
sound(y,fs)
subdecode;
% --- Executes on button press in b2.
function b2_Callback(hObject, eventdata, handles)
% hObject    handle to b2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=697;f2=1336;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
% --- Executes on button press in A.
function A_Callback(hObject, eventdata, handles)
% hObject    handle to A (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=697;f2=1663;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
% --- Executes on button press in b3.
function b3_Callback(hObject, eventdata, handles)
% hObject    handle to b3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=697;f2=1447;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
% --- Executes on button press in b4.
function b4_Callback(hObject, eventdata, handles)
% hObject    handle to b4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=770;f2=1209;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
% --- Executes on button press in b5.
function b5_Callback(hObject, eventdata, handles)
% hObject    handle to b5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=770;f2=1336;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
% --- Executes on button press in B.
function B_Callback(hObject, eventdata, handles)
% hObject    handle to B (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=770;f2=1633;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
% --- Executes on button press in b6.
function b6_Callback(hObject, eventdata, handles)
% hObject    handle to b6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=770;f2=1477;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
%--- Executes on button press in b7.
function b7_Callback(hObject, eventdata, handles)
% hObject    handle to b7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=852;f2=1209;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
% --- Executes on button press in b8.
function b8_Callback(hObject, eventdata, handles)
% hObject    handle to b8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=852;f2=1336;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
% --- Executes on button press in C.
function C_Callback(hObject, eventdata, handles)
% hObject    handle to C (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=852;f2=1633;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
% --- Executes on button press in b9.
function b9_Callback(hObject, eventdata, handles)
% hObject    handle to b9 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=852;f2=1477;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
% --- Executes on button press in ba.
function ba_Callback(hObject, eventdata, handles)
% hObject    handle to ba (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=941;f2=1209;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
% --- Executes on button press in b0.
function b0_Callback(hObject, eventdata, handles)
% hObject    handle to b0 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=941;f2=1336;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
% --- Executes on button press in D.
function D_Callback(hObject, eventdata, handles)
% hObject    handle to D (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=941;f2=1633;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs)
subdecode;
% --- Executes on button press in bn.
function bn_Callback(hObject, eventdata, handles)
% hObject    handle to bn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t=[0:0.000125:.05];
fs=8000;
f1=941;f2=1477;
y1=.25*sin(2*pi*f1*t);
y2=.25*sin(2*pi*f2*t);
y=y1+y2;sound(y,fs);
subdecode;

% --- Executes on button press in info.
function info_Callback(hObject, eventdata, handles)
% hObject    handle to info (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
msgbox('File was created by: Randolf C. Sequera                                       BSECE Adamson University Philippines','Info','warn')

% --- Executes on button press in close.
function close_Callback(hObject, eventdata, handles)
% hObject    handle to close (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
close;


%Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
%Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
%   notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
%   notice, this list of conditions and the following disclaimer in the
%   documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

function test_flann
data_path = './';
outcome = {'FAILED!!!!!!!!!', 'PASSED'};

failed = 0;
passed = 0;
cnt = 0;
ok = 1;

    function assert(condition)
        if (~condition)
            ok = 0;
        end
    end

    function run_test(name, test)
        ok = 1;
        cnt = cnt + 1;
        tic;
        fprintf('Test %d: %s...',cnt,name);
        test();
        time = toc;
        if (ok)
            passed = passed + 1;
        else
            failed = failed + 1;
        end
        fprintf('done (%g sec) : %s\n',time,cell2mat(outcome(ok+1)))
    end

    function status
        fprintf('-----------------\n');
        fprintf('Passed: %d/%d\nFailed: %d/%d\n',passed,cnt,failed,cnt);
    end

    dataset = [];
    testset = [];
    function test_load_data
        % load the datasets and testsets
        % use single precision for better memory efficiency
        % store the features one per column because MATLAB
        % uses column major ordering
        % The dataset.dat and testset.dat files can be downloaded from:
        % http://people.cs.ubc.ca/~mariusm/uploads/FLANN/datasets/dataset.dat
        % http://people.cs.ubc.ca/~mariusm/uploads/FLANN/datasets/testset.dat
        dataset = single(load([data_path 'dataset.dat']))';
        testset = single(load([data_path 'testset.dat']))';

        assert(size(dataset,1) == size(testset,1));
    end
    run_test('Load data',@test_load_data);

	match = [];
    dists = [];
    function test_linear_search
        [match,dists] = flann_search(dataset, testset, 10, struct('algorithm','linear'));
        assert(size(match,1) ==10 && size(match,2) == size(testset,2));
    end
    run_test('Linear search',@test_linear_search);

    function test_kdtree_search
        [result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','kdtree',...
                                                          'trees',8,...
                                                          'checks',64));
        n = size(match,2);
        precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
        assert(precision>0.9);
        assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
    end
    run_test('kd-tree search',@test_kdtree_search);

    function test_kmeans_search
        [result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','kmeans',...
                                                          'branching',32,...
                                                          'iterations',3,...
                                                          'checks',120));
        n = size(match,2);
        precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
        assert(precision>0.9);
        assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
    end
    run_test('k-means search',@test_kmeans_search);

    function test_composite_search
        [result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','composite',...
                                                          'branching',32,...
                                                          'iterations',3,...
                                                          'trees', 1,...
                                                          'checks',64));
        n = size(match,2);
        precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
        assert(precision>0.9);
        assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
    end
    run_test('composite search',@test_composite_search);

    function test_autotune_search
        [result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','autotuned',...
                                                          'target_precision',0.95,...
                                                          'build_weight',0.01,...
                                                          'memory_weight',0));
        n = size(match,2);
        precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
        assert(precision>0.9);
        assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
    end
    run_test('search with autotune',@test_autotune_search);

    function test_index_kdtree_search
        [index, search_params ] = flann_build_index(dataset, struct('algorithm','kdtree', 'trees',8,...
                                                          'checks',64));
        [result, ndists] = flann_search(index, testset, 10, search_params);
        n = size(match,2);
        precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
        assert(precision>0.9);
        assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
    end
    run_test('index kd-tree search',@test_index_kdtree_search);

    function test_index_kmeans_search
        [index, search_params ] = flann_build_index(dataset, struct('algorithm','kmeans',...
                                                          'branching',32,...
                                                          'iterations',3,...
                                                          'checks',120));
        [result, ndists] = flann_search(index, testset, 10, search_params);
        n = size(match,2);
        precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
        assert(precision>0.9);
        assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
    end
    run_test('index kmeans search',@test_index_kmeans_search);

    function test_index_kmeans_search_gonzales
        [index, search_params ] = flann_build_index(dataset, struct('algorithm','kmeans',...
                                                          'branching',32,...
                                                          'iterations',3,...
                                                          'checks',120,...
                                                          'centers_init','gonzales'));
        [result, ndists] = flann_search(index, testset, 10, search_params);
        n = size(match,2);
        precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
        assert(precision>0.9);
        assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
    end
    run_test('index kmeans search gonzales',@test_index_kmeans_search_gonzales);

    function test_index_kmeans_search_kmeanspp
        [index, search_params ] = flann_build_index(dataset, struct('algorithm','kmeans',...
                                                          'branching',32,...
                                                          'iterations',3,...
                                                          'checks',120,...
                                                          'centers_init','kmeanspp'));
        [result, ndists] = flann_search(index, testset, 10, search_params);
        n = size(match,2);
        precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
        assert(precision>0.9);
        assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
    end
    run_test('index kmeans search kmeanspp',@test_index_kmeans_search_kmeanspp);

    function test_index_composite_search
        [index, search_params ] = flann_build_index(dataset,struct('algorithm','composite',...
                                                          'branching',32,...
                                                          'iterations',3,...
                                                          'trees', 1,...
                                                          'checks',64));
        [result, ndists] = flann_search(index, testset, 10, search_params);
        n = size(match,2);
        precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
        assert(precision>0.9);
        assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
    end
    run_test('index composite search',@test_index_composite_search);

   function test_index_autotune_search
        [index, search_params, speedup ] = flann_build_index(dataset,struct('algorithm','autotuned',...
                                                          'target_precision',0.95,...
                                                          'build_weight',0.01,...
                                                          'memory_weight',0));
        [result, ndists] = flann_search(index, testset, 10, search_params);
        n = size(match,2);
        precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
        assert(precision>0.9);
        assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
    end
    run_test('index autotune search',@test_index_autotune_search);

    status();
end


function a = cv(algo,hyper)

%=====================================================================================
%  Cross validation object
%=====================================================================================
%  a=cv(algo,hyperParam) Returns a cv object on algorithm algo using with
%                        given Hyperparameters.
%
%  Possible hyperparameters (with defaults):
%   folds=5               - number of folds
%   repeats=1             - can do n*CV for reduced variance
%   balanced=0            - determines if cv shall be balanced  (same number of
%                            positives in each fold)
%   store_all=1           - determines if models trained in all folds shall be stored
%   output_train_error=0  - determines wheter to output training error on each fold
%                            (else cv error, i.e  test left out fold as default)
%   train_on_fold=0       - determines to  test on left out fold and train on the
%                            rest (set to true for the opposite).
%   store_trialbytrial=0  - whether to store the field a.trialbytrial, the rows of
%                            which are [i, foldnumber, y_i, f(x_i)] for each index
%                            i of a data point on which the algorithm was tested
%
%  Model:
%   child                 - stored in child algorithm
%
%  Methods:
%   train                 - selfexplanatory
%   test                  - selfexplanatory
%=====================================================================================
% Reference :
% Author    :
% Link      :
%=====================================================================================

  % <<---- Initialisation of Hyperparams ---->>
  a.folds=5;
  a.repeats=1;
  a.balanced=0;
  a.store_all=1;
  a.output_train_error=0;
  a.train_on_fold=0;
  a.store_trialbytrial=0;
  a.trialbytrial=[];

  % <<---- Initialisation of model ---->>
  if nargin>0
   a.child{1}=algo;
  else
   a.child{1}=svm;
  end

  % <<---- convert {} to group({}) ---->>
  if isa(a.child{1},'cell')
      a.child{1}=group(a.child{1});
  end;

  p=algorithm('cv');
  a= class(a,'cv',p);
  if nargin==2,
    eval_hyper;
  end;

  if a.store_all
    for i=2:a.folds*a.repeats
     a.child{i}=a.child{1};
    end
  end


function test_suite = test_clipLine3d
%testClipLine3d  One-line description here, please.
%   output = testClipLine3d(input)
%
%   Example
%   testClipLine3d
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2009-06-22,    using Matlab 7.7.0.471 (R2008b)
% Copyright 2009 INRA - Cepia Software Platform.

test_suite = functiontests(localfunctions);

function testOx(testCase) %#ok<*DEFNU>
% line parallel to Ox axis
box     = [0 100 0 100 0 100];
line    = [10 20 30 10 0 0];

clipped = clipLine3d(line, box);
edge    = [0 20 30 100 20 30];
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

function testOx_outside(testCase)

% line parallel to Ox axis
box     = [0 100 0 100 0 100];

line    = [10 -20 30 10 0 0];
edge    = NaN(1, 6);
clipped = clipLine3d(line, box);
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

line    = [-10 120 30 10 0 0];
edge    = NaN(1, 6);
clipped = clipLine3d(line, box);
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

line    = [10 20 -30 10 0 0];
edge    = NaN(1, 6);
clipped = clipLine3d(line, box);
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

line    = [10 20 130 10 0 0];
edge    = NaN(1, 6);
clipped = clipLine3d(line, box);
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

function testOy(testCase)
% line parallel to Ox axis
box     = [0 100 0 100 0 100];
line    = [10 20 30 0 10 0];

clipped = clipLine3d(line, box);
edge    = [10 0 30 10 100 30];
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

function testOy_outside(testCase)

% line parallel to Ox axis
box     = [0 100 0 100 0 100];

line    = [-10 20 30 0 10 0];
edge    = NaN(1, 6);
clipped = clipLine3d(line, box);
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

line    = [110 20 30 0 10 0];
edge    = NaN(1, 6);
clipped = clipLine3d(line, box);
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

line    = [10 20 -30 0 10 0];
edge    = NaN(1, 6);
clipped = clipLine3d(line, box);
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

line    = [10 20 130 0 10 0];
edge    = NaN(1, 6);
clipped = clipLine3d(line, box);
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

function testOz(testCase)
% line parallel to Ox axis
box     = [0 100 0 100 0 100];
line    = [10 20 30 0 0 10];

clipped = clipLine3d(line, box);
edge    = [10 20 0 10 20 100];
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

function testOz_outside(testCase)
% line parallel to Ox axis
box     = [0 100 0 100 0 100];

line    = [-10 20 30 0 0 10];
edge    = NaN(1, 6);
clipped = clipLine3d(line, box);
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

line    = [110 20 30 0 0 10];
edge    = NaN(1, 6);
clipped = clipLine3d(line, box);
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

line    = [10 -20 30 0 0 10];
edge    = NaN(1, 6);
clipped = clipLine3d(line, box);
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

line    = [10 120 30 0 0 10];
edge    = NaN(1, 6);
clipped = clipLine3d(line, box);
testCase.assertEqual(edge, clipped, 'AbsTol', .001);

function testArray(testCase)

% test for several lines with multiple directions
box     = [0 100 0 100 0 100];
lineOx  = [10 20 30 10 0 0];
lineOy  = [10 20 30 0 10 0];
lineOz  = [10 20 30 0 0 10];
lines   = [lineOx;lineOy;lineOz];
clipped = clipLine3d(lines, box);

testCase.assertEqual(3, size(clipped, 1));

% the same, but with some lines outside the box
box     = [0 100 0 100 0 100];
lineOx1 = [ 10  20  30 10 0 0];
lineOx2 = [ 10 -20  30 10 0 0];
lineOx3 = [ 10  20 -30 10 0 0];
lineOy1 = [ 10  20  30 0 10 0];
lineOy2 = [-10  20  30 0 10 0];
lineOy3 = [ 10  20 -30 0 10 0];
lineOz1 = [ 10  20  30 0 0 10];
lineOz2 = [-10  20  30 0 0 10];
lineOz3 = [ 10 -20  30 0 0 10];
lines   = [...
    lineOx1;lineOx2;lineOx3;...
    lineOy1;lineOy2;lineOy3;
    lineOz1;lineOz2;lineOz3];
clipped = clipLine3d(lines, box);

testCase.assertEqual(9, size(clipped, 1));
testCase.assertEqual(6, size(clipped, 2));
testCase.assertEqual(6*6, sum(isnan(clipped(:))));


function [vertex_coords, faces, magic] = read_surf(fname, flag)
%
% [vertex_coords, faces] = read_surf(fname)
%
% or
%
% [vertex_coords, faces] = read_surf(fname, flag)
%
% reads a the vertex coordinates and face lists from a surface file
% note that reading the faces from a quad file can take a very long
% time due to the goofy format that they are stored in. If the faces
% output variable is not specified, they will not be read so it
% should execute pretty quickly.
%
% if a second optional boolean flag is specified to be true, this will determine whether
% the ASCII formatted coregistration information is read from the bottom of the file.
% This coregistration information is applied to the vertex_coords, to represent the
% surface in the coordinate system of the corresponding volume. The function's default
% is not to use this coregistration information.

% changes:
%  - 20220518: also optionally read the transformation information that is present as
%    ASCII text at the bottom of the binary file. I could not find documentation
%    online about this, but based on some limited trial and error it seems that
%    the translation information (i.e. a shift of the origin), and possibly the
%    voxel scaling can be used to represent the vertex coordinates in the coordinate
%    system of the volume from which the surface was derived. This option makes sense
%    if the surface is to be directly related to a volume, without the resulting
%    headaches of mismatching coordinate systems.
%
% read_surf.m
%
% Original Author: Bruce Fischl
% CVS Revision Info:
%    $Author: fischl $
%    $Date: 2014/04/30 12:59:03 $
%    $Revision: 1.7 $
%
% Copyright (C) 2011 The General Hospital Corporation (Boston, MA) "MGH"
%
% Terms and conditions for use, reproduction, distribution and contribution
% are found in the 'FreeSurfer Software License Agreement' contained
% in the file 'LICENSE' found in the FreeSurfer distribution, and here:
%
% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense
%
% Reporting: freesurfer@nmr.mgh.harvard.edu
%

if nargin<2
  flag = false;
end

%fid = fopen(fname, 'r') ;
%nvertices = fscanf(fid, '%d', 1);
%all = fscanf(fid, '%d %f %f %f %f\n', [5, nvertices]) ;
%curv = all(5, :)' ;

% open it as a big-endian file

%QUAD_FILE_MAGIC_NUMBER =  (-1 & 0x00ffffff) ;
%NEW_QUAD_FILE_MAGIC_NUMBER =  (-3 & 0x00ffffff) ;

TRIANGLE_FILE_MAGIC_NUMBER =  16777214 ;
QUAD_FILE_MAGIC_NUMBER =  16777215 ;
NEW_QUAD_FILE_MAGIC_NUMBER =  16777213 ;

fid = fopen(fname, 'rb', 'b') ;
if (fid < 0)
  str = sprintf('could not open surface file %s.', fname) ;
  error(str) ;
end
magic = fread3(fid) ;

if((magic == QUAD_FILE_MAGIC_NUMBER) || (magic == NEW_QUAD_FILE_MAGIC_NUMBER))
  vnum = fread3(fid) ;
  fnum = fread3(fid) ;
  vertex_coords = fread(fid, vnum*3, 'int16') ./ 100 ;
  if (nargout > 1)
    for i=1:fnum
      for n=1:4
        faces(i,n) = fread3(fid) ;
      end
    end
  end
elseif (magic == TRIANGLE_FILE_MAGIC_NUMBER)
  fgets(fid) ;
  fgets(fid) ;
  vnum = fread(fid, 1, 'int32') ;
  fnum = fread(fid, 1, 'int32') ;
  % possibly the comment line was not followed by two \n’s, this patch is suggested by J.M.Schoffelen, 20190502
  if round(abs(vnum))~=vnum || round(abs(fnum))~=fnum
    frewind(fid);
    fread3(fid);
    fgets(fid);
    vnum = fread(fid, 1, 'int32') ;
    fnum = fread(fid, 1, 'int32') ;
  end
  vertex_coords = fread(fid, vnum*3, 'float32') ;
  if (nargout > 1)
    faces = fread(fid, fnum*3, 'int32') ;
    faces = reshape(faces, 3, fnum)' ;
  end
else
  fprintf('ERROR: magic number %d unknown\n',magic);
  vertex_coords = [];
  faces = [];
  return;
end

vertex_coords = reshape(vertex_coords, 3, vnum)' ;

if flag
  % JM the below is based a bit on trial and error, but tries to extract
  % coregistration information, that may be present as plain text at the
  % bottom of the file. I could not find any documentation online about this,
  % but anecdotally this info can be used to align the mesh with the
  % specified volume. Note that only a translation seems to be required, I am
  % not sure about the voxelsize scaling
  tline = fgetl(fid);
  if ~isempty(strfind(tline, 'volume info valid'))
    while tline~=-1
      tline = fgetl(fid);

      % the following assumes that the text lines are of a structure:
      % something = something else
      if ischar(tline)
        [v, rest] = strtok(tline);
        [equalsign, rest] = strtok(rest);
        if isequal(v, 'filename')
          [r, rest] = strtok(rest);
          eval(sprintf('%s = ''%s'';', v, rest));
        else
          eval(sprintf('%s = [%s];', v, rest));
        end
      end
    end
    R = diag(voxelsize); % not sure about this
    M = [R cras';0 0 0 1];
    tmp = [vertex_coords ones(size(vertex_coords,1),1)] * M';
    vertex_coords = tmp(:,1:3);
  end
end

fclose(fid);


function grafica2000nudos
%%%%%%%%%%%%%%%%%%           SAP2000 v14           %%%%%%%%%%%%%%%%%%%%%
%programa registrado por MECAVIL ingenieria-ciencia
%bresler_lin@hotmail.com
%numera los nudos
%clf
%cla
graficaTRIDIMENSIONAL
[frini frfin elmprp ielmprp conecc inud nud]=frame3dsap2000longitud;
%%%%%%%%%%%%%%%%%%%%%%
%enumeracion frames%%%
%%%%%%%%%%%%%%%%%%%%%%
%M=(frfin(:,[2 3 4])+frini(:,[2 3 4]))./2;
%axis('auto')

%for i=1:1:ielmprp
% text(M(i,1),M(i,2),M(i,3),[{'\color{blue}'} [,int2str( conecc(i,1) ),]],'FontSize',7)
%end
%%%%%%%%%%%%%%%%%%%%%%
%enumeracion nudos%%%
%%%%%%%%%%%%%%%%%%%%%%
figure(1),hold on
for i=1:1:inud
 text(nud(i,2),nud(i,3),nud(i,4),[{'\color[rgb]{0 0 0}'} [,int2str(nud(i) ),]],'FontSize',8)
end
hold off


function signal = flt_clean_flatlines(varargin)
% Remove channels with abnormal data from a continuous data set.
% Signal = flt_clean_flatlines(Signal,MaxFlatlineDuration,MaxAllowedJitter)
%
% This is an automated artifact rejection function which ensures that
% the data contains no flat-lined channels.
%
% In:
%   Signal : continuous data set, assumed to be appropriately high-passed (e.g. >0.5Hz or
%            with a 0.5Hz - 2.0Hz transition band)
%
%   MaxFlatlineDuration : Maximum tolerated flatline duration. In seconds. If a channel has a longer
%                         flatline than this, it will be considered abnormal. Default: 5
%
%   MaxAllowedJitter : Maximum tolerated jitter during flatlines. As a multiple of epsilon.
%                      Default: 20
%
%   InitializeOn : Initialize on time range. If a time range is given as [start,end], either in
%                  seconds or as fractions of the whole data (if both <= 1), then where applicable
%                  the filter will be initialized only on that subset of the whole data. As a
%                  result, the filter will not have to be retrained in each cross-validation
%                  fold. (default: [])
% Out:
%   Signal : data set with flat channels removed
%
% Examples:
%   % use with defaults
%   eeg = flt_clean_flatlines(eeg);
%
% See also:
%   flt_clean_settings
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-07-06

% flt_clean_flatlines_version<1.0> -- for the cache

if ~exp_beginfun('filter') return; end;

declare_properties('name','FlatlineCleaning', 'follows','flt_selchans', 'precedes','flt_laplace', 'independent_channels',true, 'independent_trials','initialize_on');

arg_define(varargin, ...
    arg_norep({'signal','Signal'}), ...
    arg({'max_flatline_duration','MaxFlatlineDuration'}, 5, [0 Inf], 'Maximum tolerated flatline duration. In seconds. If a channel has a longer flatline than this, it will be considered abnormal.'), ...
    arg({'max_allowed_jitter','MaxAllowedJitter'}, 20, [0 Inf], 'Maximum tolerated jitter during flatlines. As a multiple of epsilon.'), ...
    arg({'initialize_on','InitializeOn'},[],[0 0 600 Inf],'Initialize on time range. If a time range is given as [start,end], either in seconds or as fractions of the whole data (if both <= 1), then where applicable the filter will be initialized only on that subset of the whole data. As a result, it will not have to be retrained in each cross-validation fold.','shape','row'),...
    arg_deprecated({'min_stddev','MinimumStdDev'}, 0.0001, [0 Inf], 'This parameter has no function any more.'), ...
    arg_norep('removed_channels',unassigned));

% flag channels
if ~exist('removed_channels','var')
    if ~isempty(initialize_on)
        ref_section = exp_eval(set_selinterval(signal,initialize_on,quickif(all(initialize_on<=1),'fraction','seconds')));
    else
        ref_section = signal;
    end
    removed_channels = [];
    for c=1:ref_section.nbchan
        zero_intervals = reshape(find(diff([false abs(diff(ref_section.data(c,:)))<(max_allowed_jitter*eps) false])),2,[])';
        if max(zero_intervals(:,2) - zero_intervals(:,1)) > max_flatline_duration*ref_section.srate
            removed_channels(end+1) = c; end
    end
end

% execute
if ~isempty(removed_channels)
    retain_channels = true(1,size(signal.data,1));
    retain_channels(removed_channels) = false;
    signal.data = signal.data(retain_channels,:,:,:,:,:,:,:);
    signal.chanlocs = signal.chanlocs(retain_channels);
    signal.nbchan = size(signal.data,1);
end

exp_endfun('append_online',{'removed_channels',removed_channels});


%FFNC Feed-forward neural net classifier back-end
%
% 	[W,HIST] = FFNC (ALG,A,UNITS,ITER,W_INI,T,FID)
%
% INPUT
% 	ALG   Training algorithm: 'bpxnc' for back-propagation (default), 'lmnc'
%         for Levenberg-Marquardt
% 	A     Training dataset
% 	UNITS Array indicating number of units in each hidden layer (default: [5])
% 	ITER  Number of iterations to train (default: inf)
% 	W_INI Weight initialisation network mapping (default: [], meaning
%         initialisation by Matlab's neural network toolbox)
% 	T     Tuning set (default: [], meaning use A)
%   FID   File ID to write progress to (default [], see PRPROGRESS)
%
% OUTPUT
% 	W     Trained feed-forward neural network mapping
% 	HIST  Progress report (see below)
%
% DESCRIPTION
% This function should not be called directly, but through one of its
% front-ends, BPXNC or LMNC. Uses the Mathworks' Neural Network toolbox.
%
% SEE ALSO (PRTools Guide)
% MAPPINGS, DATASETS, BPXNC, LMNC, NEURC, RNNC, RBNC, PRPROGRESS

% Copyright: R.P.W. Duin, duin@ph.tn.tudelft.nl
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands

% $Id: ffnc.m,v 1.10 2009/07/26 18:43:12 duin Exp $

function [w,hist] = ffnc(alg,a,units,max_iter,w_ini,tt,fid)

		% Settings for the various training algorithms.

  checktoolbox('nnet');

	if (strcmp(alg,'bpxnc'))
		mapname = 'BP-NeuralNet';
	elseif (strcmp(alg,'lmnc'))
		mapname = 'LM-NeuralNet';
	else
		error('illegal training algorithm specified');
	end;

	% Check arguments

	if (nargin < 7), fid = []; end;
	if (nargin < 6) | (isempty(tt))
		prwarning(2,'no tuning set supplied, using training set for tuning (risk of overfit)');
		if (nargin < 2), t = []; else, t = a; end;
    tt = []; % preserve input for regopt calls
  else
    t = tt;
	end
	if (nargin < 5) | (isempty(w_ini))
		prwarning(3,'no initialisation supplied, using Nguyen-Widrow random initialisation');
		w_ini = [];
	end
	if (nargin < 4) | (isempty(max_iter))
		prwarning(3,'no maximum number of iterations supplied, assuming infinite');
		max_iter = inf;
	end
	if (nargin < 3) | (isempty(units))
		prwarning(2,'no network architecture specified, assuming one hidden layer of 5 units');
		units = 5;
	end
	if (nargin < 2) | (isempty(a))
		w = prmapping(alg,{units,max_iter,w_ini,t,fid});
		w = setname(w,mapname);
		hist = [];
		return
	end

	a = setprior(a,getprior(a));
	t = setprior(a,getprior(t));

  if isnan(units) % optimize complexity parameter: number of neurons
		defs = {5,[],[],[],[]};
		parmin_max = [1,30;0,0;0,0;0,0;0,0];
		[w,hist] = regoptc(a,alg,{units,max_iter,w_ini,tt,fid},defs,[1],parmin_max,testc([],'soft'),0);
		return
  end

	% Training target values.

	prwarning (4, 'using training targets 0.9/0.1');
	target_high	= 0.9;
	target_low	= 0.1;

	% Check whether the dataset is valid.

	islabtype(a,'crisp');
	isvaldfile(a,1,2); 							% At least 1 object per class, 2 classes
	a = testdatasize(a);
	t = testdatasize(t);
	iscomdset(a,t);   							% Check whether training and tuning set match
	%a = setprior(a,getprior(a));
	%t = setprior(a,getprior(t));

	[m,k,c] = getsize(a);
	lablist = getlablist(a);

  nodipimage('set');

	% Standard training parameters.

	disp_freq   = inf;
	err_goal 		= 0.02/m;						% Mean-squared error goal, stop if reached
	trnsf_fn	  = 'logsig';					% Transfer function
  perf_fn     = 'mse';            % Performance function

	% Settings for the different training algorithms.

	tp.show   = disp_freq;
	tp.time   = inf;
	tp.goal   = err_goal;

  %DXD apparently this is now required:
  tp.showWindow = 0;
  tp.showCommandLine = 0;
	if (strcmp(alg,'bpxnc'))
		trnalg 					= 'traingdx';
		lrnalg 					= 'learngdm';
		burnin       		= 500;			% Never stop training before this many iters
		tp.epochs    		= min(50,max_iter); 	% Iteration unit
		tp.lr        		= 0.01;			% BP, initial value for adaptive learning rate
		tp.lr_inc    		= 1.05;			% BP, multiplier for increasing learning rate
		tp.lr_dec    		= 0.7;			% BP, multiplier for decreasing learning rate
		tp.mc        		= 0.95;			% BP, momentum
		tp.max_perf_inc = 1.04;			% BP, error ratio
		tp.min_grad  		= 1e-6;			% BP, minimum performance gradient
		tp.max_fail  		= 5;				% BP, maximum validation failures
		speed           = 10000;    % waitbar speed
	elseif (strcmp(alg,'lmnc'))
		trnalg 					= 'trainlm';
		lrnalg 					= 'learngdm';
		burnin       		= 50;				% Never stop training before this many iters
		tp.epochs 	 		= min(1,max_iter); 		% Iteration unit
		%tp.mem_reduc 		= 1;				% Trade-off between memory & speed
		tp.max_fail  		= 1; 				% LM, maximum validation failures
		tp.min_grad  		= 1e-6;			% LM, minimum gradient, stop if reached
		tp.mu  	    		= 0.001;		% LM, initial value for adaptive learning rate
		tp.mu_inc    		= 10;				% LM, multiplier for increasing learning rate
		tp.mu_dec    		= 0.1;			% LM, multiplier for decreasing learning rate
		tp.mu_max    		= 1e10;			% LM, maximum learning rate
		speed           = 100;      % waitbar speed
	end;

	% Scale each feature to the range [0,1].
	prwarning(3,'scaling such that training set features have range [0,1]');
	ws = scalem(a,'domain'); a_scaled = a*ws; t_scaled = t*ws;

	% Set number of network outputs: 1 for 2 classes, c for c > 2 classes.
	if (c == 2), cout = 1; else cout = c; end

	% Create target matrix: row C contains a high value at position C,
	% the correct class, and a low one for the incorrect ones (place coding).
	if (cout > 1)
    target = target_low * ones(c,c) + (target_high - target_low) * eye(c);
	else
		target = [target_high; target_low];
	end

	% Create the target arrays for both datasets.
	target_a = target(getnlab(a),:)';
	target_t = target(getnlab(t),:)';

	% Create the network layout: K inputs, N(:) hidden units, COUT outputs.
	numlayers = length(units)+1; numunits = [k,units(:)',cout];
	transfer_fn = cellstr(char(ones(numlayers,1)*trnsf_fn));

	% Create network and set training parameters. The network is initialised
	% by the Nguyen-Widrow rule by default.

	warning('OFF','NNET:Obsolete')
	net = newff(ones(numunits(1),1)*[0 1],numunits(2:end),...
							transfer_fn,trnalg,lrnalg,perf_fn);
    net.trainParam = tp;

	% If an initial network is specified, use its weights and biases.

	if (~isempty(w_ini))
		% Use given initialisation.
		[data,lab,type_w] = get(w_ini,'data','labels','mapping_file');
		if (strcmp(type_w,'sequential'))
			a_scaled = a*data{1}; t_scaled = t*data{1}; ws = data{1};
			[data,lab,type_w] = get(data{2},'data','labels','mapping_file');
		end

		% Check whether the mapping's dimensions are the same as the network's.
		[kw,cw] = size(w_ini); net_ini = data{1};
		if (~strcmp(type_w,'neurc')) | (kw ~= k) | (cw ~= c) | ...
				(net.numInputs  ~= net_ini.numInputs) | ...
				(net.numLayers  ~= net_ini.numLayers) | ...
				(net.numOutputs ~= net_ini.numOutputs) | ...
				any(net.biasConnect ~= net_ini.biasConnect) | ...
				any(net.inputConnect ~= net_ini.inputConnect) | ...
				any(net.outputConnect ~= net_ini.outputConnect)
			error('incorrect size initialisation network supplied')
		end
		% Check whether the initialisation network was trained on the same data.
		[dummy1,nlab,dummy2] = renumlab(lablist,lab);
		if (max(nlab) > c)
			error('initialisation network should be trained on same classes')
		end
		net.IW = net_ini.IW; net.LW = net_ini.LW; net.b = net_ini.b;
	end

	% Initialize loop

	opt_err = inf; opt_iter = inf; opt_net = net;
	iter = 0; this_iter = 1; hist = [];

	% Loop while
	% - training has not gone on for longer than 50 iterations or 2 times the
	%   number of iterations for which the error was minimal, and
	% - the number of iterations does not exceed the maximum
	% - the actual training function still performed some iterations

	prprogress(fid,'%s: neural net, %i units: \n',alg,units);
	prprogress(fid,'%i %5.3f %5.3f\n',0,1,1);

	s = sprintf('%s: neural net, %i units',alg,units);
	prwaitbar(100,s);
  while ((iter <= 2*opt_iter) | (iter < burnin)) & ...
				(iter < max_iter) & (this_iter > 0) & (opt_err > 0)
		prwaitbar(100,100-100*exp(-iter/speed));
		% Call TRAIN, from Matlab's NN toolbox.

		prwarning(4,'[%d] calling NNETs train', iter);
		%net.trainParam.mu = min(net.trainParam.mu_max*0.9999,net.trainParam.mu);
		%net.trainParam.mem_reduc = 1;
    %net.efficiency.memoryReduction = 1;
    if verLessThan('nnet','7.0')
      net.trainParam.mem_reduc = 1;
    else
      net.efficiency.memoryReduction = 1;
    end
		net.trainParam.showWindow = 0;
		net.trainParam.showCommandLine = 0;

		[net,tr] = train(net,+a_scaled',target_a);
		this_iter = length(tr.epoch)-1; iter = iter + this_iter;

		% Copy current learning rate as the one to start with for the next time.
		if (strcmp(alg,'bpxnc'))
			net.trainParam.lr = tr.lr(end);
		else
			net.trainParam.mu = tr.mu(end);
		end;

		% Map train and tuning set.
  	w = prmapping('neurc','trained',{net},lablist,k,c);
  	w = setname(w,mapname);

		% Calculate mean squared errors (MSE).
  	out_a = a_scaled*w; out_t = t_scaled*w;
		mse_a = mean(mean(((out_a(:,1:cout))-target_a').^2,1));
		mse_t = mean(mean(((out_t(:,1:cout))-target_t').^2,1));

		% Calculate classification errors.
		e_a = testc(a_scaled,w); e_t = testc(t_scaled,w);

		% If this error is minimal, store the iteration number and weights.
  	if (e_t < opt_err)
  		opt_err = e_t; opt_iter = iter; opt_net = net;
  	end
		w1 = cell2mat(net.IW); w1 = w1(:);
		%w2 = cell2mat(net.LW'); bugfix, doesnot work for multilayer networks
		%w2 = w2(:);
		netLW = net.LW(:);
		w2 = [];
		for j=1: length(netLW)
			ww = netLW{j};
			w2 = [w2; ww(:)];
		end
  	hist = [hist; iter e_a e_t mse_a mse_t ...
						mean([w1; w2].^2)];
		prprogress(fid,'%i %5.3f %5.3f\n',iter,e_t,opt_err);

  end
	prwaitbar(0);

	% Create mapping.

  w = ws*prmapping('neurc','trained',{opt_net},lablist,k,c);
  w = setname(w,mapname);
	w = setcost(w,a);

  nodipimage('reset');

return

%NODIPIMAGE Remove or reset DIPIMAGE path
%
%   NODIPIMAGE(FLAG)
%
% INPUT
%  FLAG  'set' or 'reset'. Removes DIPIMAGE from the path ('set')or adds
%        it again if it was removed ('reset')
%
% DESCRIPTION
% DIPIMAGE and the NNET toolbox both contain a routine MSE. If MSE is found
% in the DIPIMAGE path this path is removed ('set') or re-established.

function nodipimage(flag)

persistent DIPPATH

if strcmp(flag,'set')

  DIPPATH = fileparts(which('mse'));
  [ff,pp] = fileparts(DIPPATH);
  if strcmp(pp,'dipimage')
    rmpath(DIPPATH);
  else
    DIPPATH = [];
  end

elseif strcmp(flag,'reset')

  if ~isempty(DIPPATH)
    addpath(DIPPATH);
  end

else

  error('Unknown option')

end


function pars = build_parameters_structure_v4(R, opts, varargin)

%BUILD_PARAMETERS_STRUCTURE Build parameters structure used for function ibTB.

%   Copyright (C) 2009 Cesare Magri
%   Version 4.0.0

% -------
% LICENSE
% -------
% This software is distributed free under the condition that:
%
% 1. it shall not be incorporated in software that is subsequently sold;
%
% 2. the authorship of the software shall be acknowledged and the following
%    article shall be properly cited in any publication that uses results
%    generated by the software:
%
%      Magri C, Whittingstall K, Singh V, Logothetis NK, Panzeri S: A
%      toolbox for the fast information analysis of multiple-site LFP, EEG
%      and spike train recordings. BMC Neuroscience 2009 10(1):81;
%
% 3.  this notice shall remain in place in each source file.

if isempty(varargin)
    msg = 'No output option specified';
    error('buildParsStruct:noOutputOptSpecified', msg);
end

% R -----------------------------------------------------------------------
if ndims(R)==3
    [pars.Nc, size2ofR, pars.Ns] = size(R);
else
    msg = 'Response matrix must be a 3D matrix.';
    error('buildParsStruct:Rnot3D', msg);
end;

% NT ----------------------------------------------------------------------
% If the number of trials per stimulus is constant, NT can be provided
% as a scalar. In this case, the array version is built internally.
if isscalar(opts.nt)
    pars.Nt = ones(pars.Ns,1) * opts.nt;
    maxNt = pars.Nt;
else
    if length(opts.nt)~=pars.Ns
        msg = 'size(R,3) must match length(opts.nt). Try transposing nt.';
        error('buildParsStruct:lengthNt_vs_size3R', msg);
    end

    % R and NT compatibility:
    pars.Nt = opts.nt(:);
    maxNt = max(pars.Nt);
end

% R and NT compatibility:
if maxNt~=size2ofR
    msg = 'max(nt) must be equal to size(R,2).';
    error('buildParsStruct:maxNt_vs_size2R', msg);
end

% METHOD ------------------------------------------------------------------
pars.method = opts.method;
switch lower(opts.method)
    case {'dr'}
        pars.methodFunc = @direct_method_v5b;
        pars.methodNum = 1;
    case {'gs'}
        pars.methodFunc = @gaussian_method_v7_1_0;
        pars.methodNum = 2;
    otherwise
        msg = ['Undefined method ' pars.method];
        error('buildParsStruct:methodNotFound', msg);
end;

% BIAS --------------------------------------------------------------------
switch lower(opts.bias)
    case 'naive'
        pars.biasCorrNum = 0;
    case 'qe'
        pars.biasCorrNum = 1;
    case 'pt'
        pars.biasCorrNum = 2;
    case 'gsb'
        pars.biasCorrNum = 3;
    otherwise
        msg = ['Bias correction option ''' opts.bias ''' not found'];
        error('buildParsStruct:biasCorrNotFound', msg);
end

% BTSP (optional) ---------------------------------------------------------
pars.numberOfSpecifiedOptions = 0;
if isfield(opts, 'btsp')
    pars.numberOfSpecifiedOptions = pars.numberOfSpecifiedOptions + 1;

    if round(opts.btsp)~=opts.btsp
        msg = 'opts.btsp must be an integer.';
        error('buildParsStruct:btspNotInteger', msg);
    else
        pars.btsp = opts.btsp;
    end
else
    % No bootstrap:
    pars.btsp = 0;
end

% OUTPUT LIST -------------------------------------------------------------
% Checking which output-options have been selected and keeping track of the
% position they have in VARARGIN: this will allow do provide the outputs in
% the correct order.
pars.Noutput = length(varargin); % number of ouputs

varargin = lower(varargin);
pars.HR    = strcmpi(varargin, 'hr'      );
pars.HRS   = strcmpi(varargin, 'hrs'     );
pars.HlR   = strcmpi(varargin, 'hlr'     );
pars.HlRS  = strcmpi(varargin, 'hirs'    );
pars.HiR   = strcmpi(varargin, 'hir'     );
pars.ChiR  = strcmpi(varargin, 'chir'    );
pars.HshR  = strcmpi(varargin, 'hshr'    );
pars.HshRS = strcmpi(varargin, 'hshrs'   );
% See note in ENTROPY regarding this quantity:
pars.HiRS  = strcmpi(varargin, 'hirsdef' );

if pars.Nc>1
    pars.doHR    = any(pars.HR   );
    pars.doHRS   = any(pars.HRS  );
    pars.doHlR   = any(pars.HlR  );
    pars.doHlRS  = any(pars.HlRS );
    pars.doHiR   = any(pars.HiR  );
    pars.doHiRS  = any(pars.HiRS );
    pars.doChiR  = any(pars.ChiR );
    pars.doHshR  = any(pars.HshR );
    pars.doHshRS = any(pars.HshRS);
else
    pars.doHR    = any(pars.HR | pars.HlR | pars.HiR | pars.ChiR | pars.HshR);
    pars.doHRS   = any(pars.HRS | pars.HlRS | pars.HiRS | pars.HshRS);
    pars.doHlR   = false;
    pars.doHlRS  = false;
    pars.doHiR   = false;
    pars.doHiRS  = false;
    pars.doChiR  = false;
    pars.doHshR  = false;
    pars.doHshRS = false;
end

% ADDCHECKS (optionals) ---------------------------------------------------
if isfield(opts, 'verbose') && opts.verbose
    pars.numberOfSpecifiedOptions = pars.numberOfSpecifiedOptions + 1;
    pars.lengthVarargin = length(varargin);

    pars.addChecks = true;
else
    pars.addChecks = false;
end

if any(pars.addChecks)
	additional_checks_v4(R, pars, opts);
end;


function [sumRes, resJ, H]=fobj_rician_fix(x, meas, protocol, model, sig, constants, fix, x0)
% Wrapper for fobj_rician for use with fmincon_fix.
%
% x is the encoded model parameter values
%
% meas is the measurements
%
% protocol is the measurement protocol
%
% model is a string encoding the model
%
% sig is the standard deviation of the Gaussian distributions underlying
% the Rician noise
%
% constants contains values required to compute the model signals.
%
% fix is a binary array specifying which parameters are fixed and which
% vary.
%
% x0 is the full starting point including the fixed parameters.
%
% author: Daniel C Alexander (d.alexander@ucl.ac.uk)
%

% Construct the full parameter list including fixed values.
xf = fix.*x0;
xf(find(fix==0)) = x;

% Now call the full objective function.
if(nargout == 1)
    sumRes = fobj_rician(xf, meas, protocol, model, sig, constants);
elseif(nargout == 2)
    [sumRes resJ] = fobj_rician(xf, meas, protocol, model, sig, constants);
else
    [sumRes, resJ, H] = fobj_rician(xf, meas, protocol, model, sig, constants);
end


function model = yalmip2dsdp(interfacedata);

[C,A,b,blk] = sedumi2dsdp(interfacedata.F_struc,interfacedata.c,interfacedata.K);
interfacedata.options.dsdp.dual_quadratic=spalloc(length(interfacedata.c),length(interfacedata.c),0);
interfacedata.options.dsdp.printyes = (interfacedata.options.verbose>0);
model.A = A;
model.C = C;
model.b = b;
model.options = interfacedata.options.dsdp


function [trg] = read_eep_trg(fn);

% READ_EEP_TRG reads triggers from an EEProbe *.trg file
%
% This function returns an Nx1 array with the N triggers
%
% [trg] = read_eep_trg(filename)
%
% trg(i).time   ... trigger latency in ms
% trg(i).offset ... byte offset
% trg(i).code   ... trigger code (string)
% trg(i).type   ... numeric value of trg.code
%
% where i as number between 1 and N (the number of triggers found)
%
% An EEProbe trigger file is formatted like
%   0.00195312 256
%   0.000     10350  __
%   17.033   2242926   1
%   20.535   2701934   5
%   21.096   2775406  13
%   21.098   2775662   8
%   ...
% where the first column is the trigger latency in seconds, the second
% column is the byte offset in the file and the third column is the triggercode.
% The triggercode can be numeric or a string. The first line of the file contains the
% sample duration.
%
% Author: Robert Oostenveld, Aalborg University, Denmark, 11 March 2003
%
% See also READ_EEP_CNT, READ_EEP_REJ, READ_EEP_AVR
%

% Copyright (C) 2002, Robert Oostenveld
%                     Aalborg University, Denmark
%                     http://www.smi.auc.dk/~roberto/
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

% $Log: read_eep_trg.m,v $
% Revision 1.2  2005/06/08 08:16:37  mvelde
% converted files to unix format
%
% Revision 1.1  2004/11/26 13:17:02  jwiskerke
% Added m-files without binary code in maple distribution.
%
% Revision 1.2  2003/10/24 13:34:41  Maarten-Jan Hoeve
% Added GNU Licence and updated revision history
%
% Revision 1.1.1.2  2003/10/17 09:55:20  mvelde
% updated: consistent copyrights, arguments/data labels, fixed some typos
%
% Revision 1.1.1.1  2003/03/11 15:24:51  roberto
% updated help and copyrights
% ANT Software BV, The Netherlands, www.ant-software.nl / info@ant-software.nl
%

trg = [];

fid = fopen(fn, 'rb');
if fid<0
   return
end

header = fgetl(fid);
while ~feof(fid)
  tmp = fscanf(fid, '%f %d %s', 3);
  if ~isempty(tmp)
    new.time   = tmp(1)*1000;			% in ms
    new.offset = tmp(2)+1;			% offset 1
    new.code   = char(tmp(3:end));		% string
    new.type   = str2double(new.code);		% numeric
    trg = [trg; new];
  end
end

fclose(fid);