function [assignment, cost] = assignmentsuboptimal1(distMatrix)
%ASSIGNMENTSUBOPTIMAL1    Compute suboptimal assignment
%   ASSIGNMENTSUBOPTIMAL1(DISTMATRIX) computes a suboptimal assignment
%   (minimum overall costs) for the given rectangular distance or cost
%   matrix, for example the assignment of tracks (in rows) to observations
%   (in columns). The result is a column vector containing the assigned
%   column number in each row (or 0 if no assignment could be done).
%
%   [ASSIGNMENT, COST] = ASSIGNMENTSUBOPTIMAL1(DISTMATRIX) returns the
%   assignment vector and the overall cost.
%
%   The algorithm is designed for distance matrices with many forbidden and
%   singly validated assignments (rows or columns containing only one
%   finite element). The algorithm first searches the matrix for singly
%   validated columns and rejects all assignments with multiply validated
%   rows. Afterwards, singly validated rows are searched and assignments to
%   multiply validated columns are rejected. Then, for each row that
%   validates only with singly validated columns (and the other way
%   around), the minimum element is chosen and the assignment is made. If
%   there are still assignments open, the minimum element in the distance
%   matrix is searched and the corresponding assignment is made.
%
%   In scenarios without any forbidden assignments, the algorithm reduces
%   to the last step, which will provide the same result as ASSIGNMENTOPTIMAL2.
%   If there are only some assignments forbidden, the algorithm will perform
%   poorly because singly validated assignments are preferred.
%
%   The last step can still be optimized, see the comments in
%   ASSIGNMENTOPTIMAL2.
%
%   assignment.html  File Exchange  Donate via PayPal
%
%   Markus Buehren
%   Last modified 05.07.2011

% initialize
[nOfRows, nOfColumns] = size(distMatrix);
nOfValidObservations  = zeros(nOfRows,1);
nOfValidTracks        = zeros(1,nOfColumns);
assignment            = zeros(nOfRows,1);
cost                  = 0;

% compute number of validations for each track
for row=1:nOfRows
  nOfValidObservations(row) = length(find(isfinite(distMatrix(row,:))));
end

if any(nOfValidObservations < nOfColumns)

  if all(nOfValidObservations == 0)
    return
  end

  repeatSteps = 1;
  while repeatSteps

    repeatSteps = 0;

    % step 1: reject assignments of multiply validated tracks to singly validated observations
    for col=1:nOfColumns
      index = isfinite(distMatrix(:,col));
      nOfValidTracks(col) = length(find(index));
      if any(nOfValidObservations(index) == 1)
        index = index & (nOfValidObservations > 1);
        if any(index)
          distMatrix(index, col)      = inf;
          nOfValidObservations(index) = nOfValidObservations(index) - 1;
          nOfValidTracks(col)         = nOfValidTracks(col) - length(find(index));
          repeatSteps = 1;
        end
      end
    end

    % step 2: reject assignments of multiply validated observations to singly validated tracks
    if nOfColumns > 1
      for row=1:nOfRows
        index = isfinite(distMatrix(row,:));
        if any(nOfValidTracks(index) == 1)
          index = index & (nOfValidTracks > 1);
          if any(index)
            distMatrix(row, index)    = inf;
            nOfValidTracks(index)     = nOfValidTracks(index) - 1;
            nOfValidObservations(row) = nOfValidObservations(row) - length(find(index));
            repeatSteps = 1;
          end
        end
      end
    end

  end % while repeatSteps
      %disp(sprintf('xx = %d', xx));

  % for each multiply validated track that validates only with singly validated
  % observations, choose the observation with minimum distance
  for row=1:nOfRows
    if nOfValidObservations(row) > 1
      index = isfinite(distMatrix(row,:));
      if all(nOfValidTracks(index) == 1)
        [minDist, col] = min(distMatrix(row,:));
        assignment(row)    = col;
        cost               = cost + minDist;
        distMatrix(row,:)  = inf;
        distMatrix(:,col)  = inf;
      end
    end
  end

  % for each multiply validated observation that validates only with singly validated
  % tracks, choose the track with minimum distance
  for col=1:nOfColumns
    if nOfValidTracks(col) > 1
      index = isfinite(distMatrix(:,col));
      if all(nOfValidObservations(index) == 1)
        [minDist, row] = min(distMatrix(:,col));
        assignment(row)    = col;
        cost               = cost + minDist;
        distMatrix(row,:)  = inf;
        distMatrix(:,col)  = inf;
      end
    end
  end

end

% now, recursively search for the minimum element and do the assignment
while 1

  % find minimum distance observation-to-track pair
  [minDist, index1] = min(distMatrix, [], 1);
  [minDist, index2] = min(minDist);
  row = index1(index2);
  col = index2;

  if isfinite(minDist)

    % make the assignment
    assignment(row)    = col;
    cost               = cost + minDist;
    distMatrix(row, :) = inf;
    distMatrix(:, col) = inf;

  else
    break
  end

end


%DEMO_MODELASSESMENT2  Demonstration for model assessment when the observation
%                      model is non-Gaussian
%
%  Description
%    We will consider the classification problem in demo_classific.
%    The analysis is conducted with full Gaussian process using
%    both probit and logit likelihood. The performance of these two
%    models are compared by evaluating the ten-fold
%    cross-validation, leave-one-out cross-validation, WAIC, DIC
%    and the effective number of parameters The inference will be
%    conducted using maximum a posterior (MAP) estimate for the
%    parameters using EP and Laplace approximation, via full Markov
%    chain Monte Carlo (MCMC) and with an integration approximation
%    (IA) for the parameters.
%
%    This demo is organised in two parts:
%     1) data analysis with with probit likelihood
%     2) data analysis with with logit likelihood
%
%  See also
%    DEMO_CLASSIFIC1, DEMO_MODELASSESMENT1
%
% Copyright (c) 2009-2010 Jarno Vanhatalo
% Copyright (c) 2010 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.

% =====================================
% 1) data analysis with probit likelihood
% =====================================
disp('Data analysis with probit likelihood')
S = which('demo_classific');
L = strrep(S,'demo_classific.m','demodata/synth.tr');
x=load(L);
y=x(:,end);
y = 2.*y-1;
x(:,end)=[];
[n, nin] = size(x);

DIC=repmat(NaN,1,8);DIC2=repmat(NaN,1,8);DIC_latent=repmat(NaN,1,8);
p_eff=repmat(NaN,1,8);p_eff2=repmat(NaN,1,8);p_eff_latent=repmat(NaN,1,8);p_eff_latent2=repmat(NaN,1,8);

% Create covariance functions
gpcf = gpcf_sexp('lengthScale', [0.9 0.9], 'magnSigma2', 2);

% Set the prior for the parameters of covariance functions
pl = prior_logunif();
gpcf = gpcf_sexp(gpcf, 'lengthScale_prior', pl,'magnSigma2_prior', pl); %

% Create the GP structure
gp = gp_set('lik', lik_probit, 'cf', gpcf, 'jitterSigma2', 1e-4);

% ------- Laplace approximation --------
disp(['Probit with Laplace integration over the latent values '; ...
      'and MAP estimate for the parameters                    '])

% Set the approximate inference method
gp = gp_set(gp, 'latent_method', 'Laplace');

n=length(y);

% Set the options for the optimization
opt=optimset('TolFun',1e-3,'TolX',1e-3);
% Optimize with the quasi-Newton method
gp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);

% Evaluate the effective number of parameters and DIC with focus on
% latent variables.
models{1} = 'pr_Laplace';
p_eff_latent(1) = gp_peff(gp, x, y);
[DIC_latent(1), p_eff_latent2(1)] = gp_dic(gp, x, y);
WAIC(1) = gp_waic(gp,x,y);

% Evaluate the 10-fold cross-validation results.
cvres = gp_kfcv(gp, x, y, 'display', 'fold');
mlpd_cv(1) = cvres.mlpd_cv;

% Evaluate the leave-one-out cross-validation results.
[Ef,Varf,lpy] =  gp_loopred(gp, x, y);
mlpd_loo(1) = mean(lpy);

% ------- Expectation propagation --------
disp(['Probit with EP integration over the latent values and MAP '; ...
      'estimate for the parameters                               '])

% Set the approximate inference method
gp = gp_set(gp, 'latent_method', 'EP');

% Set the options for the optimization
opt=optimset('TolFun',1e-3,'TolX',1e-3);
% Optimize with the BFGS quasi-Newton method
gp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);

% Evaluate the effective number of parameters and DIC with focus on
% latent variables.
models{2} = 'pr_EP';
p_eff_latent(2) = gp_peff(gp, x, y) ;
[DIC_latent(2), p_eff_latent2(2)] = gp_dic(gp, x, y);
WAIC(2) = gp_waic(gp,x,y);

% Evaluate the 10-fold cross-validation results.
cvres = gp_kfcv(gp, x, y, 'display', 'fold');
mlpd_cv(2) = cvres.mlpd_cv;

% Evaluate the leave-one-out cross-validation results.
[Ef,Varf,lpy] =  gp_loopred(gp, x, y);
mlpd_loo(2) = mean(lpy);

% ------- MCMC ---------------
disp(['Probit with MCMC integration over the latent values and '; ...
      'the parameters                                          '])

% Set the approximate inference method
gp = gp_set(gp, 'latent_method', 'MCMC');

% Sample
mcopt.nsamples=220;mcopt.display=20;
[rgp,gp]=gp_mc(gp, x, y, mcopt);
rgp=thin(rgp, 21, 2);

% Evaluate the effective number of parameters and DIC with focus on
% latent variables.
models{3} = 'pr_MCMC';
[DIC(3), p_eff(3)] =  gp_dic(rgp, x, y, 'focus', 'hyper');
[DIC2(3), p_eff2(3)] =  gp_dic(rgp, x, y);
WAIC(3) = gp_waic(rgp,x,y);

% Evaluate the 10-fold cross-validation results.
mcopt.nsamples=50;mcopt.display=20;
cvres = gp_kfcv(gp, x, y, 'inf_method', 'MCMC', 'opt', mcopt, 'display', 'fold');
mlpd_cv(3) = cvres.mlpd_cv;

% Evaluate the leave-one-out cross-validation results.
[Ef,Varf,lpy] =  gp_loopred(rgp, x, y);
mlpd_loo(3) = mean(lpy);

% --- Integration approximation approach ---
disp(['Probit with EP integration over the latent values and '; ...
      'grid integration over the parameters                  '])

% Use EP
gp = gp_set(gp, 'latent_method', 'EP');

% Set the options for the optimization
opt=optimset('TolFun',1e-3,'TolX',1e-3);
% Optimize with the BFGS quasi-Newton method
gp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);

% now perform the integration
clear opt
opt.int_method = 'grid';
opt.step_size = 2;
gp_array = gp_ia(gp, x, y, opt);

models{4} = 'pr_IA';
[DIC(4), p_eff(4)] =  gp_dic(gp_array, x, y, 'focus', 'hyper');
[DIC2(4), p_eff2(4)] =  gp_dic(gp_array, x, y);
WAIC(4) = gp_waic(gp_array,x,y);

% Then the 10 fold cross-validation.
cvres = gp_kfcv(gp, x, y, 'inf_method', 'IA', 'opt', opt, 'display', 'fold');
mlpd_cv(4) = cvres.mlpd_cv;

% Evaluate the leave-one-out cross-validation results.
[Ef,Varf,lpy] =  gp_loopred(gp_array, x, y);
mlpd_loo(4) = mean(lpy);

% =====================================
% 2) data analysis with logit likelihood
% =====================================
disp('Data analysis with logit likelihood')

S = which('demo_classific');
L = strrep(S,'demo_classific.m','demodata/synth.tr');
x=load(L);
y=x(:,end);
y = 2.*y-1;
x(:,end)=[];
[n, nin] = size(x);

% Create covariance functions
gpcf = gpcf_sexp('lengthScale', [0.9 0.9], 'magnSigma2', 2);

% Set the prior for the parameters of covariance functions
pl = prior_logunif();
gpcf = gpcf_sexp(gpcf, 'lengthScale_prior', pl,'magnSigma2_prior', pl); %

% Create the likelihood structure
lik = ('init');

% Create the GP structure
gp = gp_set('lik', lik_logit, 'cf', gpcf, 'jitterSigma2', 1e-4);

% ------- Laplace approximation --------
disp(['Logit with Laplace integration over the latent values and '; ...
      'MAP estimate for the parameters                           '])

% Set the approximate inference method
gp = gp_set(gp, 'latent_method', 'Laplace');

% Set the options for the optimization
opt=optimset('TolFun',1e-3,'TolX',1e-3);
% Optimize with the BFGS quasi-Newton method
gp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);

% Evaluate the effective number of parameters and DIC with focus on
% latent variables.
models{5} = 'lo_Laplace';
p_eff_latent(5) = gp_peff(gp, x, y);
[DIC_latent(5), p_eff_latent2(5)] = gp_dic(gp, x, y);
WAIC(5) = gp_waic(gp,x,y);

% Evaluate the 10-fold cross-validation results.
cvres = gp_kfcv(gp, x, y, 'display', 'fold');
mlpd_cv(5) = cvres.mlpd_cv;

% Evaluate the leave-one-out cross-validation results.
[Ef,Varf,lpy] =  gp_loopred(gp, x, y);
mlpd_loo(5) = mean(lpy);

% ------- Expectation propagation --------
disp(['Logit with EP integration over the latent values and MAP'; ...
      'estimate for the parameters                             '])

% Set the approximate inference method
gp = gp_set(gp, 'latent_method', 'EP');

% Set the options for the optimization
opt=optimset('TolFun',1e-3,'TolX',1e-3);
% Optimize with the BFGS quasi-Newton method
gp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);

% Evaluate the effective number of parameters and DIC with focus on
% latent variables.
models{6} = 'lo_EP';
p_eff_latent(6) = gp_peff(gp, x, y) ;
[DIC_latent(6), p_eff_latent2(6)] = gp_dic(gp, x, y);
WAIC(6) = gp_waic(gp,x,y);

% Evaluate the 10-fold cross-validation results.
cvres = gp_kfcv(gp, x, y, 'display', 'fold');
mlpd_cv(6) = cvres.mlpd_cv;

% Evaluate the leave-one-out cross-validation results.
[Ef,Varf,lpy] =  gp_loopred(gp, x, y);
mlpd_loo(6) = mean(lpy);

% ------- MCMC ---------------
disp(['Logit with MCMC integration over the latent values and '; ...
      'the parameters                                         '])

% Set the approximate inference method
gp = gp_set(gp, 'latent_method', 'MCMC');

% Sample
mcopt.nsamples=200;mcopt.display=20;
[rgp,gp] = gp_mc(gp, x, y, mcopt);
rgp=thin(rgp, 21, 2);

% Evaluate the effective number of parameters and DIC with focus on latent variables.
models{7} = 'lo_MCMC';
[DIC(7), p_eff(7)] =  gp_dic(rgp, x, y, 'focus', 'hyper');
[DIC2(7), p_eff2(7)] =  gp_dic(rgp, x, y);
WAIC(7) = gp_waic(rgp,x,y);

% Evaluate the 10-fold cross-validation results.
mcopt.nsamples=50;mcopt.display=20;
cvres = gp_kfcv(gp, x, y, 'inf_method', 'MCMC', 'opt', mcopt, 'display', 'fold');
mlpd_cv(7) = cvres.mlpd_cv;

% Evaluate the leave-one-out cross-validation results.
[Ef,Varf,lpy] =  gp_loopred(rgp, x, y);
mlpd_loo(7) = mean(lpy);

% --- Integration approximation approach ---
disp(['Logit with EP integration over the latent values and grid '; ...
      'integration over the parameters                           '])

% Use EP
gp = gp_set(gp, 'latent_method', 'EP');

% Set the options for the optimization
opt=optimset('TolFun',1e-3,'TolX',1e-3);
% Optimize with the BFGS quasi-Newton method
gp=gp_optim(gp,x,y,'opt',opt,'optimf',@fminlbfgs);

% now perform the integration
clear opt
opt.int_method = 'grid';
opt.step_size = 2;
gp_array = gp_ia(gp, x, y, opt);

models{8} = 'lo_IA';
[DIC(8), p_eff(8)] =  gp_dic(gp_array, x, y, 'focus', 'hyper');
[DIC2(8), p_eff2(8)] =  gp_dic(gp_array, x, y);
WAIC(8) = gp_waic(gp_array,x,y);

% Then the 10 fold cross-validation.
cvres = gp_kfcv(gp, x, y, 'inf_method', 'IA', 'opt', opt, 'display', 'fold');
mlpd_cv(8) = cvres.mlpd_cv;

% Evaluate the leave-one-out cross-validation results.
[Ef,Varf,lpy] =  gp_loopred(gp_array, x, y);
mlpd_loo(8) = mean(lpy);

%========================================================
% PART 4 Print the results
%========================================================
disp('Summary of the results')

S = '       ';
for i = 1:length(models)
    S = [S '  ' models{i}];
end

S = sprintf([S '\n CV-mlpd  %6.2f    %6.2f  %6.2f  %6.2f   %6.2f    %6.2f  %6.2f  %6.2f'], mlpd_cv);
S = sprintf([S '\n LOO-mlpd %6.2f    %6.2f  %6.2f  %6.2f   %6.2f    %6.2f  %6.2f  %6.2f'], mlpd_loo);
S = sprintf([S '\n ']);
S = sprintf([S '\n WAIC     %6.2f    %6.2f  %6.2f  %6.2f   %6.2f    %6.2f  %6.2f  %6.2f'], WAIC);
S = sprintf([S '\n ']);
S = sprintf([S '\n DIC_h    %6.2f    %6.2f  %6.2f  %6.2f   %6.2f    %6.2f  %6.2f  %6.2f'], DIC);
S = sprintf([S '\n DIC_a    %6.2f    %6.2f  %6.2f  %6.2f   %6.2f    %6.2f  %6.2f  %6.2f'], DIC2);
S = sprintf([S '\n DIC_l    %6.2f    %6.2f  %6.2f  %6.2f   %6.2f    %6.2f  %6.2f  %6.2f'], DIC_latent);
S = sprintf([S '\n peff_h   %6.2f    %6.2f  %6.2f  %6.2f   %6.2f    %6.2f  %6.2f  %6.2f'], p_eff);
S = sprintf([S '\n peff_a   %6.2f    %6.2f  %6.2f  %6.2f   %6.2f    %6.2f  %6.2f  %6.2f'], p_eff2);
S = sprintf([S '\n peff_l   %6.2f    %6.2f  %6.2f  %6.2f   %6.2f    %6.2f  %6.2f  %6.2f'], p_eff_latent);
S = sprintf([S '\n peff_l2  %6.2f    %6.2f  %6.2f  %6.2f   %6.2f    %6.2f  %6.2f  %6.2f'], p_eff_latent2);
S = sprintf([S '\n ']);
S = sprintf([S '\n The notation is as follows:']);
S = sprintf([S '\n pr_*     = probit likelihood and inference method']);
S = sprintf([S '\n lo_*     = logit likelihood and inference method']);
S = sprintf([S '\n CV-mlpd  = mean log predictive density from the 10-fold CV. ']);
S = sprintf([S '\n LOO-mlpd = mean log predictive density from the 10-fold CV. ']);
S = sprintf([S '\n WAIC     = Widely applicable information criterion. ']);
S = sprintf([S '\n DIC_h    = DIC with focus on parameters. ']);
S = sprintf([S '\n DIC_a    = DIC with focus on parameters and laten variables (all). ']);
S = sprintf([S '\n DIC_l    = DIC with focus on latent variables. ']);
S = sprintf([S '\n peff_h   = effective number of parameters (latent variables marginalized). ']);
S = sprintf([S '\n peff_a   = effective number of parameters and latent variables. ']);
S = sprintf([S '\n peff_l   = effective number of latent variables evaluated with gp_peff. ']);
S = sprintf([S '\n peff_l2  = effective number of latent variables evaluated with gp_dic. ']);
S = sprintf([S '\n '])


function out = transpose(in)

%  kronMatrix k.'
%    returns the transpose of the kronMatrix object k
%
%    k = \sum [a{i} (x) b{i}] ==> k.' = \sum [a{i}.' (x) b{i}.']
%
%

% Spring 2002 created by R. Wright
%

% 9/2002 L. Perrone
% Modified code to bring it into line with the new kronMatrix class
%

A = in.a;
B = in.b;
l=length(A);
for i=1:l
 tmp = A{i};
 A{i} = tmp.';
 tmp = B{i};
 B{i} = tmp.';
end
out = kronMatrix(A,B);


function drawAffine(afnv, tsize, color, linewidth)

rect= round(aff2image(afnv', tsize));
inp	= reshape(rect,2,4);

topleft_r = inp(1,1);
topleft_c = inp(2,1);
botleft_r = inp(1,2);
botleft_c = inp(2,2);
topright_r = inp(1,3);
topright_c = inp(2,3);
botright_r = inp(1,4);
botright_c = inp(2,4);
p = line([topleft_c, topright_c], [topleft_r, topright_r]);
set(p, 'Color', color); set(p, 'LineWidth', linewidth); set(p, 'LineStyle', '-');
p = line([topright_c, botright_c], [topright_r, botright_r]);
set(p, 'Color', color); set(p, 'LineWidth', linewidth); set(p, 'LineStyle', '-');
p = line([botright_c, botleft_c], [botright_r, botleft_r]);
set(p, 'Color', color); set(p, 'LineWidth', linewidth); set(p, 'LineStyle', '-');
p = line([botleft_c, topleft_c], [botleft_r, topleft_r]);
set(p, 'Color', color); set(p, 'LineWidth', linewidth); set(p, 'LineStyle', '-');


%% FUNCTION LSSMTC
%   permute labels of L2 match L1 as good as possible
%
%% LICENSE
%   This program is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License
%   along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%   Copyright (C) 2011 - 2012 Quanquan Gu, Jiayu Zhou, and Jieping Ye
%
%   You are suggested to first read the Manual.
%   For any problem, please contact with Jiayu Zhou via jiayu.zhou@asu.edu
%
%   Last modified on June 17, 2012.

function [newL2] = bestMap(L1,L2)
%bestmap: permute labels of L2 match L1 as good as possible
%   [newL2] = bestMap(L1,L2);

%===========
L1 = L1(:);
L2 = L2(:);
if size(L1) ~= size(L2)
    error('size(L1) must == size(L2)');
end
L1 = L1 - min(L1) + 1;      %   min (L1) <- 1;
L2 = L2 - min(L2) + 1;      %   min (L2) <- 1;
%===========    make bipartition graph  ============
nClass = max(max(L1), max(L2));
G = zeros(nClass);
for i=1:nClass
    for j=1:nClass
        G(i,j) = length(find(L1 == i & L2 == j));
    end
end
%===========    assign with hungarian method    ======
[c,t] = hungarian(-G);
newL2 = zeros(nClass,1);
for i=1:nClass
    newL2(L2 == i) = c(i);
end


function  tau = dtauint(z, pp, om, omb, omt, h)
% calculates the integrant for integration of the optical length dtau over the redshift z
% dtau in Mpc^-1 is extracted from interpolation in a table which has been splined.
% pp is the spline of the interpolation for tau values as f of the redshift in this table.
% futher arguments in dtau_tabel are :matter fraction (om), baryon fraction (omb and rel Hubble constant (h)
% ha is the full Hubble factor = sqrt(rho/rho_crit)
%
% D Vangheluwe 31 mrt 2005
% modified for curved space with extra argument omt

global GL_cmb_ka1
ka1 = GL_cmb_ka1;
ha = (1e5 * h) * sqrt(om * (1 + z) .^3 + (ka1/h^2) * (1 + z) .^4 + (omt - om - ka1/h^2) + (1 - omt) * (1 + z) .^2);
tau = ppval(pp, z) .* (1 + z) .^ 2 ./ha;


function [tree,asgn] = vl_hikmeans(data,K,nleaves)
% VL_HIKMEANS  Hierachical integer K-means
%   [TREE,ASGN] = VL_HIKMEANS(DATA,K,NLEAVES) applies integer K-menas
%   recursively to cluster the data DATA, returing a structure TREE
%   representing the clusters and a vector ASGN with the data to
%   cluster assignments. The depth of the recursive partition is
%   computed so that at least NLEAVES are generated.
%
%   VL_HIKMEANS() is built on top of VL_IKMEANS() and requires the
%   data to be of class UINT8.
%
%   TREE is a structure representing the hierarchical clusters.  Each
%   node of the tree is also a structure with fields:
%
%   DEPTH::
%     Depth of the tree (only at the root node)
%
%   CENTERS::
%     K cluster centers
%
%   SUB::
%     Array of K node structures representing subtrees
%     (this field is missing at leaves).
%
%   ASGN is a matrix with one column per datum and height equal to the
%   depth of the tree. Each column encodes the branch of the tree that
%   correspond to each datum.
%
%   Example::
%     ASGN(:,7) = [1 5 3] means that the tree as depth equal to 3 and
%     that the datum X(:,7) corresponds to the branch
%     ROOT->SUB(1)->SUB(5)->SUB(3).
%
%   See also: VL_HIKMEANSPUSH(), VL_HIKMEANSHIST(), VL_IKMEANS(), VL_HELP().

% Copyright (C) 2014 Andrea Vedaldi.
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).


function [x,y,xy] = q2grid(x,y,xy,mv,bound);
%q2grid   biquadratic element grid generator
%   [x,y,xy] = q2grid(x,y,xy,mv,bound);
%   input
%          x          x coordinate vector
%          y          y coordinate vector
%          xy         vertex coordinate vector
%          mv         Q2 macroelement mapping matrix
%          bound      boundary vertex vector
%
% postpocesses Q2 element partitioning information to
% give standard approximation in the case of stretched grids
%   IFISS function: DJS; 28 February 2005.
% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage
xx=xy(:,1); yy=xy(:,2); nvtx=length(xx);
%
%% recompute mid-side points in the case of stretched grids
% y-direction
yv=yy; ny=length(y);
for k=2:2:ny;
yold=y(k); ynew=0.5*(y(k+1)+y(k-1));
l=find(yy==yold); yv(l)=ynew; y(k)=ynew;
end
% x-direction
xv=xx; nx=length(x);
for k=2:2:nx;
xold=x(k); xnew=0.5*(x(k+1)+x(k-1));
l=find(xx==xold); xv(l)=xnew; x(k)=xnew;
end
xy=[xv,yv];
%
% plotting of the grid
mel=length(mv(:,1));
%if mel <= 256,
adj=sparse(nvtx,nvtx);
for i=1:mel
adj(mv(i,1),mv(i,2))=1;
adj(mv(i,2),mv(i,3))=1;
adj(mv(i,3),mv(i,4))=1;
adj(mv(i,4),mv(i,1))=1;
end
figure(10)
gplot(adj,xy,'b')
axis('square')
hold on
plot(xy(:,1),xy(:,2),'ro')
xybd=xy(bound,:);
plot(xybd(:,1),xybd(:,2),'ko')
hold off
title('Q2 finite element subdivision')
drawnow
%end
return


function tests = test_basic_noise
  tests = functiontests(localfunctions);
end

function test1(testCase)
    N = 100;
    S = 100;
    gen = spx.data.noise.Basic(N, S);
    sigma = 1;
    X = gen.gaussian(sigma);
    variance = sum(sum(X.^2)) / (N * S);
    verifyEqual(testCase, sigma, variance, 'RelTol', .1);
end


function double_pendulum(ivp, duration, fps, movie)
% DOUBLE_PENDULUM Animates the double pendulum's (mostly) chaotic behavior.
%
%   author:  Alexander Erlich (alexander.erlich@gmail.com)
%
%   parameters:
%
%   ivp=[phi1; dtphi1; phi2; dtphi2; g; m1; m2; l1; l2]
%
%                               Initial value problem. phi1 and dtphi1 are
%                               the initial angle and anglular velocity. g
%                               is gravity, m1 and l1 mass and rod length.
%                               For an explaining picture, see
%                               documentation file in same folder.
%
%   duration                    The time interval on which the ode is
%                               solved spans from 0 to duration (in sec).
%
%   fps                         Frames Per Second. The framerate is
%                               relevant both for normal (realtime)
%                               animation and movie recording.
%
%   movie                       If false, a normal realtime animation of
%                               the motion of the double pendulum (the
%                               framerate being fps) is shown.
%                               If true, a movie (.avi) is recorded. The
%                               filename is 'doublePendulumAnimation.avi'
%                               and the folder into which it is saved is
%                               the current working directory.
%
%   This function calls double_pendulum_ODE and is, in turn, called by
%   double_pendulum_init.
%
%   Example call:    >> double_pendulum([pi;0;pi;5;9.81;1;1;2;1],100,10,false)
%   Or, simply call  >> double_pendulum_init
%
%   ---------------------------------------------------------------------

clear All; clf;

nframes=duration*fps;
sol=ode45(@double_pendulum_ODE,[0 duration], ivp);
t = linspace(0,duration,nframes);
y=deval(sol,t);

phi1=y(1,:)'; dtphi1=y(2,:)';
phi2=y(3,:)'; dtphi2=y(4,:)';
l1=ivp(8); l2=ivp(9);
% phi1=x(:,1); dtphi1=x(:,2);
% phi2=x(:,3); dtphi2=x(:,4);
% l1=ivp(8); l2=ivp(9);

h=plot(0,0,'MarkerSize',30,'Marker','.','LineWidth',2);
range=1.1*(l1+l2); axis([-range range -range range]); axis square;
set(gca,'nextplot','replacechildren');

    for i=1:length(phi1)-1
        if (ishandle(h)==1)
            Xcoord=[0,l1*sin(phi1(i)),l1*sin(phi1(i))+l2*sin(phi2(i))];
            Ycoord=[0,-l1*cos(phi1(i)),-l1*cos(phi1(i))-l2*cos(phi2(i))];
            set(h,'XData',Xcoord,'YData',Ycoord);
            drawnow;
            F(i) = getframe;
            if movie==false
                pause(t(i+1)-t(i));
            end
        end
    end
    if movie==true
        movie2avi(F,'doublePendulumAnimation.avi','compression','Cinepak','fps',fps)
    end


%% Qudarature
%
%%
%

fun = @(v) v.x .* v.y;

sF = S2FunHarmonic.quadrature(fun)

surf(sF)


function [ net,res,opts ] = rnn_ff( net,opts )
%NET_FF Summary of this function goes here
%   Detailed explanation goes here

    n_frames=opts.parameters.n_frames;
    n_hidden_nodes=opts.parameters.n_hidden_nodes;
    batch_size=opts.parameters.batch_size;

    if opts.use_gpu
        opts.input_data=gpuArray(single(opts.input_data));
        if isfield(opts,'inputs_labels')
            opts.input_labels=gpuArray(single(opts.input_labels));
        end
        if isfield(opts,'input_predicts')
            opts.input_predicts=gpuArray(single(opts.input_predicts));
        end
    end
    if ~isfield(opts.parameters,'Id_w')
       opts.parameters.Id_w=1;
    end

    for f=1:n_frames
        if isfield(opts,'input_predicts')
            res.Fit{f}(1).predicts=opts.input_predicts(:,:,f);
        end
        if isfield(opts,'input_labels')
            res.Fit{f}(1).class=opts.input_labels(:,f);
        end
    end

    opts.loss=zeros(1,n_frames,'like',opts.input_data);

    if isfield(opts,'input_labels')
        opts.err=zeros(2,n_frames,'like',opts.input_data);
    end

    %%%%
    res.Hidden{1}=zeros(n_hidden_nodes,batch_size,'like',opts.input_data);

    for f=1:n_frames
        %Process inputs
        res.Input{f}(1).x=[res.Hidden{f};opts.input_data(:,:,f)];%inputs

        %Input transform
        [ net{1},res.Input{f},opts ] = net_ff( net{1},res.Input{f},opts );

        %Update hidden nodes;
        res.Hidden{f+1}=opts.parameters.Id_w.*res.Hidden{f} + res.Input{f}(end).x;

        %Data fitting transform
        res.Fit{f}(1).x=res.Hidden{f+1};

        [ net{2},res.Fit{f},opts ] = net_ff( net{2},res.Fit{f},opts );

    end

    %stats
    for f=1:n_frames
        if isfield(opts,'input_labels')
            opts.err(:,f)=error_multiclass(res.Fit{f}(1).class,res.Fit{f});
        end
        opts.loss(:,f)=mean(res.Fit{f}(end).x(:));
    end

    if isfield(opts,'input_labels')
        opts.err=mean(opts.err,2)./opts.parameters.batch_size;
    end
    opts.loss=mean(opts.loss(:));
end


function [ ret_box8d ] = getRotateBox8D( box8d, orientation, center_x, center_y)
    boxes = box8d;
    rotate_mat = [cosd(orientation), -sind(orientation); sind(orientation), cosd(orientation)];

    %% move to center
    boxes(:,1) = boxes(:,1) - center_y;
    boxes(:,2) = boxes(:,2) - center_x;
    boxes = boxes(:,[2 1])';
    ret_box8d = rotate_mat * boxes;
    ret_box8d = ret_box8d([2,1],:)';

    %% resotre position
    ret_box8d(:,1) = ret_box8d(:,1) + center_y;
    ret_box8d(:,2) = ret_box8d(:,2) + center_x;

    ret_box8d = round(ret_box8d);
end


function [fusion,params] = linear_fuser(w,scores)
%
%  Does affine fusion of scores: It does a weighted sum of scores and adds
%                                an offset.
%
%  Inputs:
%    scores: M-by-N matrix of N scores for each of M input systems.
%    w: Optional:
%         - when supplied, the output 'fusion' is the vector of fused scores.
%         - when w=[], the output 'fusion' is a function handle, to be used
%                      for training the fuser.
%       w is a (K+1)-vector, with one weight per system, followed by the
%       offset.
%
%    fusion: if w is given, fusion is a vector of N fused scores.
%            if w is not given, fusion is a function handle, so that
%              fusion(w) = @(w) linear_fusion(scores,w).
%    w0: default values for w, to initialize training.
%
%  For training use:
%     [fuser,params] = linear_fuser(train_scores);
%     w0 = get_w0();
%     w = train_binary_classifier(fuser,...,w0,...);
%
%  For test use:
%     fused_scores = linear_fuser(test_scores,w);
%

if nargin==0
    test_this();
    return;
end

if ~exist('scores','var') || isempty(scores)
    fusion = sprintf(['linear fuser:',repmat(' %g',1,length(w))],w);
    return;
end

wsz = size(scores,1)+1;
[whead,wtail] = splitvec_fh(wsz,w);
params.get_w0 = @() zeros(wsz,1);
%params.get_w0 = @() randn(wsz,1);
params.tail = wtail;

fusion = fusion_mv2df(whead,scores);

end

function test_this()

N = 100;
dim = 2;  % number of used systems

% ----------------synthesize training data -------------------
randn('state',0);
means = randn(dim,2)*8; %signal
[tar,non] = make_data(N,means);

% ------------- create system ------------------------------

[fuser,params] = linear_fuser([],[tar,non]);

% ------------- train it ------------------------------

ntar = size(tar,2);
nnon = size(non,2);
classf = [ones(1,ntar),-ones(1,nnon)];

prior = 0.1;
maxiters = 50;
quiet = true;
objfun = [];
w0 = params.get_w0();
[w,cxe] = train_binary_classifier(fuser,classf,w0,objfun,prior,[],0,maxiters,[],[],quiet);
fprintf('train Cxe = %g\n',cxe);

% ------------- test it ------------------------------

[tar,non] = make_data(N,means);

scores = [tar,non];
tail = [1;2;3];
wbig = [w;tail];
[fused_scores,params] = linear_fuser(wbig,scores);
check_tails = [tail,params.tail],
cxe = evaluate_objective(objfun,fused_scores,classf,prior);
fprintf('test Cxe = %g\n',cxe);

plot(fused_scores);

end

function [tar,non] = make_data(N,means)
[dim,K] = size(means);
X = 5*randn(dim,K*N); % noise
ii = 1:N;
for k=1:K
    X(:,ii) = bsxfun(@plus,means(:,k),X(:,ii));
    ii = ii+N;
end
N = K*N;
tar = X(:,1:N/2);
non = X(:,N/2+(1:N/2));

end


function browse_topoplotVAR(cfg, data)

% BROWSE_TOPOPLOTVAR is a simple helper function for FT_DATABROWSER that
% computes the variance of band-pass filtered data and makes a topographic
% plot. It serves to make a quick-and-dirty power topography.
%
% See also BROWSE_MOVIEPLOTER, BROWSE_TOPOPLOTER, BROWSE_MULTIPLOTER, BROWSE_TOPOPLOTVAR, BROWSE_SIMPLEFFT

% Copyright (C) 2009, Robert Oostenveld

% compute the variance, i.e. the broad-band power
timelock        = [];
timelock.label  = data.label;
timelock.time   = mean(data.time{1});
timelock.avg    = sum(ft_preproc_baselinecorrect(data.trial{1}).^2, 2);
timelock.dimord = 'chan_time';

if isfield(data, 'grad')
  timelock.grad = data.grad;
end
if isfield(data, 'elec')
  timelock.elec = data.elec;
end

default             = [];
default.markers     = 'labels';
default.interactive = 'no';
cfg = mergestruct(cfg, default);

figure;
ft_topoplotER(cfg, timelock);


function solver = fiordos(self)

% The first dimin equalities are used to fix some parameters
aux = self.model.F_struc(1:self.dimin,:);

% remove these
self.model.F_struc(1:self.dimin(1),:) = [];
self.model.K.f = self.model.K.f - self.dimin(1);

% Extract all bounds and move from Ab to ub/lb
temp =  presolve_bounds_from_modelbounds(self.model,1);
self.model = temp;
% Any bound constraints?
n = length(temp.lb);
bounded_ub = find(~isinf(temp.ub));
bounded_lb = find(~isinf(temp.lb));
if length(bounded_lb) == n && length(bounded_ub) == n
    % All have finite bounds.
    X = EssBox(n, 'l',temp.lb, 'u',temp.ub);
    X = SimpleSet(X);
elseif  ~isempty(bounded_ub) || ~isempty(bounded_lb)
    % Only some bounds. Keep them as general constraints
    X = [];
    for i = 1:n
        if isinf(temp.lb(i)) && isinf(temp.ub(i))
            X{end+1} = EssRn(1);
        elseif  ~isinf(temp.lb(i)) && ~isinf(temp.ub(i))
            X{end+1} =  EssBox(1, 'l',temp.lb(i), 'u',temp.ub(i));
        elseif isinf(temp.ub(i))
            X{end+1} =  EssRnplus(1, 'shift', temp.lb(i));
        else
            X{end+1} =  EssRnplus(1, 'shift', temp.ub(i),'rot',-1);
        end
    end
    X = SimpleSet(X{:});
else
    % No bounds
    X = EssRn(n);
    X = SimpleSet(X);
end

% Put back a placeholder for fixing the parameters
self.model.F_struc = [aux;self.model.F_struc];
self.model.F_struc(1:self.dimin(1),1)=0; % Now fixed to zero
self.model.K.f = self.model.K.f + self.dimin(1);

op = OptProb('H',2*full(self.model.Q), 'g',self.model.c, 'X',X, 'Ae',-self.model.F_struc(1:self.model.K.f,2:end), 'be','param');

%instantiate solver
s = Solver(op,'approach','primal-dual');
%, 'algoOuter','gm', 'algoInner','fgm');
%optionally change settings, e.g.
%-maximum number of iterations
%s.setSettings('algoOuter', 'maxit',10000);
%s.setSettings('algoInner', 'maxit',9000);
%-gradient-map stopping criterion
%s.setSettings('algoOuter', 'stopg',true, 'stopgEps',1e-3);
%s.setSettings('algoInner', 'stopg',true, 'stopgEps',1e-5);
%generate solver code
s.generateCode('prefix','demo_','forceOverwrite',1);
demo_mex_make();

compiledsolver = @(x)demo_mex(x);
b0 = self.model.F_struc(1:self.model.K.f,1);
B0 = [eye(self.dimin(1));zeros(self.model.K.f-self.dimin(1),self.dimin(1))];
map = self.map;
dimout = self.dimout;
mask = self.mask{1};
solver = @(x)(fiordos_call(compiledsolver,x,B0,b0,mask,map,dimout));


function [tt]=tt_qlaplacez_dn(d)

% returns a rank-8 QTT decomposition of
% Delta_{1}^{-1} \otimes \Id_{2} \ otimes \ldots \otimes \Id_{D} + \ldots +
%  + \Id_{1} \ otimes \ldots \otimes \Id_{D-1} \otimes Delta_{D}^{-1},
% Delta_{k} being a discretization of Laplace operator on 2^{d(k)} points
% uniform grid,
% Dirichlet boundary conditions being imposed
%
% D=size(d,2) must be >= 1
%
% September 3, 2010
% Vladimir Kazeev
% vladimir.kazeev@gmail.com
% INM RAS
% Moscow, Russia
%
% Look for details in the Preprint No. 75, 2010 of
% Max-Planck Institute for Mathematics in the Sciences
% Vladimir A. Kazeev and Boris N. Khoromskij
% On explicit QTT representation of Laplace operator and its inverse
% http://www.mis.mpg.de/publications/preprints/2010/prepr2010-75.html

d=fliplr(d);
D=size(d,2);
tt=cell(sum(d),1);
I=eye(2);
J=zeros(2);
J(1,2)=1;
I2=zeros(2);
I2(2,2)=1;
E=ones(2);

if (D == 1)
	for key=1 : d
		tt{key}=eye(2);
	end
else

	key=0;
	for k=1 : D
		for kappa=1 : d(k)
			key=key+1;
			if (kappa == 1)
				if (k == 1)
					tt{key}=zeros(2,2,5);
					tt{key}(:,:,1)=I+I2+J+J';
					tt{key}(:,:,2)=2*E;
					tt{key}(:,:,3)=I2+J'+E;
					tt{key}(:,:,4)=I2+J+E;
					tt{key}(:,:,5)=I;
				elseif (k == D)
					tt{key}=zeros(2,2,2,4);
					tt{key}(:,:,1,1)=I;
					tt{key}(:,:,2,1)=I+I2+J+J';
					tt{key}(:,:,2,2)=2*E;
					tt{key}(:,:,2,3)=I2+J'+E;
					tt{key}(:,:,2,4)=I2+J+E;
				else
					tt{key}=zeros(2,2,2,8);
					tt{key}(:,:,1,1)=I+I2+J+J';
					tt{key}(:,:,1,2)=2*E;
					tt{key}(:,:,1,3)=I2+J'+E;
					tt{key}(:,:,1,4)=I2+J+E;
					tt{key}(:,:,1,5)=I;
					tt{key}(:,:,2,5)=I+I2+J+J';
					tt{key}(:,:,2,6)=2*E;
					tt{key}(:,:,2,7)=I2+J'+E;
					tt{key}(:,:,2,8)=I2+J+E;
				end
			elseif (kappa == d(k))
				if (k == D)
					tt{key}=zeros(2,2,4);
					tt{key}(:,:,1)=I;
					tt{key}(:,:,2)=I2;
					tt{key}(:,:,3)=J;
					tt{key}(:,:,4)=J';
				elseif (k == 1)
					tt{key}=zeros(2,2,5,2);
					tt{key}(:,:,1,1)=I;
					tt{key}(:,:,2,1)=I2;
					tt{key}(:,:,3,1)=J;
					tt{key}(:,:,4,1)=J';
					tt{key}(:,:,5,2)=I;
				else
					tt{key}=zeros(2,2,8,2);
					tt{key}(:,:,1,1)=I;
					tt{key}(:,:,2,1)=I2;
					tt{key}(:,:,3,1)=J;
					tt{key}(:,:,4,1)=J';
					tt{key}(:,:,5,2)=I;
					tt{key}(:,:,6,2)=I2;
					tt{key}(:,:,7,2)=J;
					tt{key}(:,:,8,2)=J';
				end
			else
				if (k == D)
					tt{key}=zeros(2,2,4,4);
					tt{key}(:,:,1,1)=I;
					tt{key}(:,:,2,2)=2*E;
					tt{key}(:,:,3,3)=E;
					tt{key}(:,:,4,4)=E;
					tt{key}(:,:,2,1)=I2;
					tt{key}(:,:,3,1)=J;
					tt{key}(:,:,4,1)=J';
					tt{key}(:,:,2,3)=I2+J';
					tt{key}(:,:,2,4)=I2+J;
				elseif (k == 1)
					tt{key}=zeros(2,2,5,5);
					tt{key}(:,:,1,1)=I;
					tt{key}(:,:,2,2)=2*E;
					tt{key}(:,:,3,3)=E;
					tt{key}(:,:,4,4)=E;
					tt{key}(:,:,2,1)=I2;
					tt{key}(:,:,3,1)=J;
					tt{key}(:,:,4,1)=J';
					tt{key}(:,:,2,3)=I2+J';
					tt{key}(:,:,2,4)=I2+J;
					tt{key}(:,:,5,5)=I;
				else
					tt{key}=zeros(2,2,8,8);
					tt{key}(:,:,1,1)=I;
					tt{key}(:,:,2,2)=2*E;
					tt{key}(:,:,3,3)=E;
					tt{key}(:,:,4,4)=E;
					tt{key}(:,:,2,1)=I2;
					tt{key}(:,:,3,1)=J;
					tt{key}(:,:,4,1)=J';
					tt{key}(:,:,2,3)=I2+J';
					tt{key}(:,:,2,4)=I2+J;
					tt{key}(:,:,5,5)=I;
					tt{key}(:,:,6,6)=2*E;
					tt{key}(:,:,7,7)=E;
					tt{key}(:,:,8,8)=E;
					tt{key}(:,:,6,5)=I2;
					tt{key}(:,:,7,5)=J;
					tt{key}(:,:,8,5)=J';
					tt{key}(:,:,6,7)=I2+J';
					tt{key}(:,:,6,8)=I2+J;
				end
			end
		end
	end
end

tt=tt_matrix(tt); % @Bydlocode
return
end


function y = G2a(X)
% mca for rtd function
% reduced order A matrix - no opamps
% X = [R1 R2 R3 R4 R5 R6 R7 R8 R9 RT E1]
R1=X(1);R2=X(2);R3=X(3);R4=X(4);R5=X(5);R6=X(6);
R7=X(7);R8=X(8);R9=X(9);RT=X(10);E1=X(11);
%
A=[1/R1+1/R4+1/RT -1/RT -1/R4 0 -1/R1;
-1/RT 1/R5+1/R6+1/RT -1/R5 0 0;
-1/R4 0 1/R2+1/R3+1/R4 -1/R3 0;
0 -1/R5 1/R5+1/R7 0 0;
0 0 0 0 -1/R9];
%
B=[0;E1/R6;E1/R2;0;E1/R8];
C=A\B;y=C(4);


%EEGLAB time-frequency functions (timefreqfunc folder):
%  angtimewarp          - Given two event marker vectors, computes a...
%  bootstat             - Accumulate surrogate data to assess significance by permutation of some...
%  correct_mc           - Compute an upper limit for the number of independent...
%  correctfit           - Correct fit using observed p-values. Use this function...
%  crossf               - Returns estimates and plots event-related coherence (ERCOH)...
%  dftfilt              - Discrete Fourier filter...
%  dftfilt2             - Discrete complex wavelet filters...
%  dftfilt3             - Discrete complex wavelet filters...
%  newcrossf            - Returns estimates and plots event-related coherence (ERCOH)...
%  newtimef             - Return estimates and plots of mean event-related (log) spectral...
%  newtimefbaseln       - Remove baseline power values for newtimef. This...
%  newtimefitc          - Function to compute inter-trial coherence (phase locking...
%  newtimefpowerunit    - Find power unit for y-axis based on input structure.
%  newtimeftrialbaseln  - Remove baseline power values for single trials in...
%  pac                  - Compute phase-amplitude coupling (power of first input...
%  pac_cont             - Compute phase-amplitude coupling (power of first input...
%  rsadjust             - Adjust l-values (Ramberg-Schmeiser distribution)...
%  rsfit                - Find p value for a given value in a given distribution...
%  rsget                - Get the p-value for a given collection of l-values...
%  rspdfsolv            - Sub-function used by RSFIT to searc for optimal...
%  rspfunc              - Sub-function used by RSGET...
%  timef                - Returns estimates and plots of mean event-related spectral...
%  timefreq             - Compute time/frequency decomposition of data trials. This...
%  timewarp             - Given two event marker vectors, computes a matrix...


function varargout = drawGrid3d(varargin)
%DRAWGRID3D Draw a 3D grid on the current axis.
%
%   drawGrid3d
%   draws a 3D square grid, with origin (0,0,0) and spacing 1 in each
%   direction, with bounds corresponding to the bounds of current axis.
%
%   drawGrid3d(SPACING)
%   where spacing is either a scalar or a [1x3] matrix, specifies the size
%   of the unit cell.
%
%   drawGrid3d(ORIGIN, SPACING)
%   Also specify origin of grid. ORIGIN is a [1x3] array.
%
%   drawGrid3d(..., EDGE)
%   specifies whether function should draw edges touching edges of axis.
%   EDGE is a characheter string, which can be :
%   - 'OPEN' : each line start from one face of window to the opposite
%   face. This results in a 'spiky' grid.
%   - 'CLOSED' (default value) : each line stops at the last visible point
%   of the grid for this line. The result looks like a box (no free spikes
%   around the grid).
%
%   H = drawGrid3d(...);
%   return a vector of handles for each LINE object which was crated.
%
%
%   Example
%     figure; hold on; axis equal; axis([-5 65 -5 45 -5 45]); view(3);
%     drawGrid3d([0 0 0], [20 20 20]);
%
%
%   See also
%     drawLine3d, drawEdge3d, clipLine3d, draw

% ------
% Author: David Legland
% E-mail: david.legland@inrae.fr
% Created: 2005-11-17
% Copyright 2005-2022 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas)

%% initialize variables

% Check if axes handle is specified
if isAxisHandle(varargin{1})
    hAx = varargin{1};
    varargin(1) = [];
else
    hAx = gca;
end

% default values
closed = true;
origin = [0 0 0];
spacing = [1 1 1];

% check if grid is open or not
str = '';
if ~isempty(varargin)
    str = varargin{end};
end
if ischar(str)
    if strncmpi(str, 'open', 4)
        closed = false;
    end
    varargin = varargin(1:end-1);
end

% check origin and grid spacing
if length(varargin)==1
    spacing = varargin{1};
elseif length(varargin)==2
    origin = varargin{1};
    spacing = varargin{2};
end

%% Compute internam data

% get axis limits
ax = axis(hAx);
x0 = ax(1); x1 = ax(2);
y0 = ax(3); y1 = ax(4);
z0 = ax(5); z1 = ax(6);

% get first and last coordinates of the grid in each direction
dx = spacing(1); dy = spacing(2); dz = spacing(3);
xe = x0 + mod(origin(1) - x0, dx);
xf = x1 - mod(x1 - origin(1), dx);
ye = y0 + mod(origin(2) - y0, dy);
yf = y1 - mod(y1 - origin(2), dy);
ze = z0 + mod(origin(1) - z0, dz);
zf = z1 - mod(z1 - origin(1), dz);

% update first and last coordinate if grid is 'closed'
if closed
    x0 = xe; x1 = xf;
    y0 = ye; y1 = yf;
    z0 = ze; z1 = zf;
end

%% Draw the grid

h = [];
%TODO: rewrite code, avoiding loops

% draw lines parallel to x axis
for y = ye:dy:yf
    for z = ze:dz:zf
        h = [h; drawEdge3d(hAx, [x0 y z x1 y z])]; %#ok<AGROW>
    end
end

% draw lines parallel to y axis
for x = xe:dx:xf
    for z = ze:dz:zf
        h = [h; drawEdge3d(hAx, [x y0 z x y1 z])]; %#ok<AGROW>
    end
end

% draw lines parallel to z axis
for x = xe:dx:xf
    for y = ye:dy:yf
        h = [h; drawEdge3d(hAx, [x y z0 x y z1])]; %#ok<AGROW>
    end
end

%% Check output arguments

if nargout>0
    varargout{1} = h;
end


function [newnode,newelem]=mergemesh(node,elem,varargin)
%
% [newnode,newelem]=mergemesh(node,elem,varargin)
%
% concatenate two or more tetrahedral meshes or triangular surfaces
%
% author: Qianqian Fang <q.fang at neu.edu>
%
% input:
%      node: node coordinates, dimension (nn,3)
%      elem: tetrahedral element or triangle surface (nn,3) to (nn,5)
%
% output:
%      newnode: the node coordinates after merging, dimension (nn,3)
%      newelem: tetrahedral element or surfaces after merging (nn,4) or (nhn,5)
%
% note: you can call meshcheckrepair for the output newnode and
% newelem to remove the duplicated nodes or elements. mergemesh does
% detect self-intersecting elements when merging; to remove self-intersecting
% elements, you need to use mergesurf().
%
% example:
%
%   [node1,face1,elem1]=meshabox([0 0 0],[10 10 10],1,1);
%   [node2,face2,elem2]=meshasphere([5 5 13.1],3,0.3,3);
%   [newnode,newelem]=mergemesh(node1,elem1,node2,elem2);
%   plotmesh(newnode,newelem);
%   figure;
%   [newnode,newface]=mergemesh(node1,face1,node2,face2);
%   plotmesh(newnode,newface,'x>5');
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

len=length(varargin);
newnode=node;
newelem=elem;
if(len>0 && mod(len,2)~=0)
   error('you must give node and element in pairs');
end

X=mesheuler(newelem);

if(size(newelem,2)==4)
   if(X>=0)
      newelem(:,end+1)=1;
   end
end
if(size(newelem,2)==3)
   newelem(:,end+1)=1;
end
for i=1:2:len
   no=varargin{i};
   el=varargin{i+1};
   baseno=size(newnode,1);
   if(size(no,2)~=size(newnode,2))
        error('input node arrays have inconsistent columns');
   end
   if(size(el,2)==5 || size(el,2)==4)
        el(:,1:4)=el(:,1:4)+baseno;
	if(size(el,2)==4 && X>=0)
	   el(:,5)=1+(i+1)/2;
	end
   	newnode=[newnode;no];
	newelem=[newelem;el];
   elseif(size(el,2)==3 && size(newelem,2)==4)
        el(:,1:3)=el(:,1:3)+baseno;
	if(size(el,2)==3)
	   el(:,4)=1+(i+1)/2;
	end
   	newnode=[newnode;no];
	newelem=[newelem;el];
   else
        error('input element arrays have inconsistent columns');
   end
end


function test_failed=test_thresh
%TEST_THRESH  Compare sparse and full thesholding

test_failed=0;
disp(' ===============  TEST_THRESH ================');
global LTFAT_TEST_TYPE;
if ~strcmpi(LTFAT_TEST_TYPE,'double')
   disp(sprintf('Skipping. Cannot work with sparse matrices of type %s.',LTFAT_TEST_TYPE));
   return;
end

lambda=0.1;

ttypes={'hard','soft','wiener'};

for ii=1:2

  if ii==1
    g=tester_rand(3,4);
    field='REAL  ';
    g(2,2)=lambda;
  else
    g=tester_crand(3,4);
    field='CMPLX ';
    g(2,2)=lambda;
  end;

  for jj=1:3
    ttype=ttypes{jj};

    [xo_full, Nfull] = thresh(g,lambda,ttype,'full');
    [xo_sparse, Nsp] = thresh(g,lambda,ttype,'sparse');

    res = xo_full-xo_sparse;
    res = norm(res(:));

    res2 = Nfull-Nsp;

    [test_failed,fail]=ltfatdiditfail(res,test_failed);
    s=sprintf(['THRESH   %s %s %0.5g %s'],field,ttype,res,fail);
    disp(s);

    [test_failed,fail]=ltfatdiditfail(res2,test_failed);
    s=sprintf(['THRESH N %s %s %0.5g %s'],field,ttype,res2,fail);
    disp(s);

    % Extend lambda to:
    % a) Vector
    lambdavec = lambda*ones(numel(g),1);

    [xo_full2, Nfull2] = thresh(g,lambdavec,ttype,'full');
    [xo_sparse2, Nsp2] = thresh(g,lambdavec,ttype,'sparse');

    res_full = xo_full2-xo_full;
    res_sparse = xo_sparse2-xo_sparse;
    res_full = norm(res_full(:));
    res_sparse = norm(res_sparse(:));

    res_nfull = Nfull2-Nfull;
    res_nsparse = Nfull2-Nfull;

    [test_failed,fail]=ltfatdiditfail(res,test_failed);
    s=sprintf(['THRESH VEC FULL  %s %s %0.5g %s'],field,ttype,res_full,fail);
    disp(s);

    [test_failed,fail]=ltfatdiditfail(res,test_failed);
    s=sprintf(['THRESH VEC SPARSE  %s %s %0.5g %s'],field,ttype,res_sparse,fail);
    disp(s);

    [test_failed,fail]=ltfatdiditfail(res2,test_failed);
    s=sprintf(['THRESH VEC N FULL %s %s %0.5g %s'],field,ttype,res_nfull,fail);
    disp(s);

    [test_failed,fail]=ltfatdiditfail(res2,test_failed);
    s=sprintf(['THRESH VEC N SPARSE %s %s %0.5g %s'],field,ttype,res_nsparse,fail);
    disp(s);

    % b) Same shape as g
    lambdamat = lambda*ones(size(g));

    [xo_full3, Nfull3] = thresh(g,lambdamat,ttype,'full');
    [xo_sparse3, Nsp3] = thresh(g,lambdamat,ttype,'sparse');

    res_full = xo_full3-xo_full;
    res_sparse = xo_sparse3-xo_sparse;
    res_full = norm(res_full(:));
    res_sparse = norm(res_sparse(:));

    res_nfull = Nfull3-Nfull;
    res_nsparse = Nfull3-Nfull;

    [test_failed,fail]=ltfatdiditfail(res,test_failed);
    s=sprintf(['THRESH MAT FULL  %s %s %0.5g %s'],field,ttype,res_full,fail);
    disp(s);

    [test_failed,fail]=ltfatdiditfail(res,test_failed);
    s=sprintf(['THRESH MAT SPARSE %s %s %0.5g %s'],field,ttype,res_sparse,fail);
    disp(s);

    [test_failed,fail]=ltfatdiditfail(res2,test_failed);
    s=sprintf(['THRESH MAT N FULL %s %s %0.5g %s'],field,ttype,res_nfull,fail);
    disp(s);

     [test_failed,fail]=ltfatdiditfail(res2,test_failed);
    s=sprintf(['THRESH MAT N SPARSE %s %s %0.5g %s'],field,ttype,res_nsparse,fail);
    disp(s);

  end;

end;


%% Specifications
minspec=70;
maxspec=200;

%% Find
found= data(:)>minspec & data(:)<maxspec;
Percent=sum(found)/length(found)


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  MATLAB Code for                                                  %
%                                                                   %
%  Multi-Objective Particle Swarm Optimization (MOPSO)              %
%  Version 1.0 - Feb. 2011                                          %
%                                                                   %
%  According to:                                                    %
%  Carlos A. Coello Coello et al.,                                  %
%  "Handling Multiple Objectives with Particle Swarm Optimization," %
%  IEEE Transactions on Evolutionary Computation, Vol. 8, No. 3,    %
%  pp. 256-279, June 2004.                                          %
%                                                                   %
%  Developed Using MATLAB R2009b (Version 7.9)                      %
%                                                                   %
%  Programmed By: S. Mostapha Kalami Heris                          %
%                                                                   %
%         e-Mail: sm.kalami@gmail.com                               %
%                 kalami@ee.kntu.ac.ir                              %
%                                                                   %
%       Homepage: http://www.kalami.ir                              %
%                                                                   %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function i=RouletteWheelSelection(p)

    r=rand;
    c=cumsum(p);
    i=find(r<=c,1,'first');

end


function [c,f,s]=rovnice(x,t,u,DuDx)
global a
% evaluates the quantities defining the
%     differential equation. The input arguments are scalars X and T and
%     vectors U and DUDX that approximate the solution and its partial
%     derivative with respect to x, respectively. PDEFUN returns column
%     vectors: C (containing the diagonal of the matrix c(x,t,u,Dx/Du)),
%     F, and S (representing the flux and source term, respectively).
c=1;
f=a*DuDx;
s=0;


function [RF] = applyEnsembleRF_table(table,Y,categories,cost)

% INITIALIZATION
nNeg = sum(~Y); % Number of negative instances
nPos = sum(Y); % Number of positive instances
indPos = find(Y); % Indexes of positive instances
indNeg = find(~Y); % Indexes of negative instances
nSub = round(nNeg/nPos); % Number of subsets

% RANDOM NUMBER GENERATOR SEED
if ~RandStream.getGlobalStream.Seed
    rng('shuffle')
end

if nargin < 4
    cost = 1;
end

% FIND THE NUMBER OF NEGATIVE INSTANCES IN EACH SUBSET
nNegS = nNeg / nSub; nSup = ceil(nNegS); nInf = floor(nNegS);
if nSup ~= nInf
    nSubInf = nSub - 1; nSubSup = 1; total = nSubInf*nInf + nSubSup*nSup;
    while total ~= nNeg
        nSubInf = nSubInf - 1; nSubSup = nSubSup + 1;
        total = nSubInf*nInf + nSubSup*nSup;
    end
    nNegS = [repmat(nInf,[1,nSubInf]),repmat(nSup,[1,nSubSup])];
else % The number of negative instances in all partitions will be the same
    nNegS = repmat(nSup,[1,nSub]);
end

% FINDING THE INDEXES OF NEGATIVE INSTANCES IN EACH SUBSET
indNegSub = cell(1,nSub);
for i = 1:nSub-1
    indNegSub{i} = zeros(nNegS(i),1);
    indTemp = ceil(numel(indNeg)*rand(nNegS(i),1));
    indTemp = unique(indTemp);
    total = numel(indTemp);
    while total ~= nNegS(i)
        indMore = ceil(numel(indNeg)*rand(nNegS(i)-total,1));
        indTemp = [indTemp;unique(indMore)];
        indTemp = unique(indTemp);
        total = numel(indTemp);
    end
    indNegSub{i}(:) = indNeg(indTemp);
    indNeg(indTemp) = [];
end
indNegSub{end} = indNeg;

% COMPUTING A RANDOM FOREST FOR EACH SUBSET AND APPENDING
ind = [indNegSub{1};indPos];
Xtemp = table(ind,:);
Ytemp = Y(ind);
[Xtemp,Ytemp] = shufflePartition(Xtemp,Ytemp);
RF = TreeBagger(1,Xtemp,Ytemp,'CategoricalPredictors',categories,'SampleWithReplacement','on','Cost',[0,1/cost;1,0]);
for i = 2:nSub
    ind = [indNegSub{i};indPos];
    Xtemp = table(ind,:);
    Ytemp = Y(ind);
    [Xtemp,Ytemp] = shufflePartition(Xtemp,Ytemp);
    RFtemp = TreeBagger(1,Xtemp,Ytemp,'CategoricalPredictors',categories,'SampleWithReplacement','on','Cost',[0,1/cost;1,0]);
    RF = append(RF,RFtemp);
end

end


function sandia_sgmgg_test01 ( )

%*****************************************************************************80
%
%% SANDIA_SGMGG_TEST01 demonstrates the naive coefficient calculations.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 August 2011
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SANDIA_SGMGG_TEST01:\n' );
  fprintf ( 1, '  Demonstrate naive coefficient calculations.\n' );
%
%  Isotropic grid in 2D.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  1) Isotropic grid in 2D\n' );

  dim_num = 2;
  point_num = 7;

  sparse_index = [ ...
    0, 2; ...
    0, 3; ...
    1, 1; ...
    1, 2; ...
    2, 0; ...
    2, 1; ...
    3, 0 ]';

  sandia_sgmgg_coef_naive_test ( dim_num, point_num, sparse_index );
%
%  Isotropic grid in 3D.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  2) Isotropic grid in 3D\n' );

  dim_num = 3;
  point_num = 19;

  sparse_index = [ ...
    0, 1, 0; ...
    0, 2, 0; ...
    0, 3, 0; ...
    1, 0, 0; ...
    1, 1, 0; ...
    1, 2, 0; ...
    2, 0, 0; ...
    2, 1, 0; ...
    3, 0, 0; ...
    0, 0, 1; ...
    0, 1, 1; ...
    0, 2, 1; ...
    1, 0, 1; ...
    1, 1, 1; ...
    2, 0, 1; ...
    0, 0, 2; ...
    0, 1, 2; ...
    1, 0, 2; ...
    0, 0, 3 ]';

  sandia_sgmgg_coef_naive_test ( dim_num, point_num, sparse_index );
%
%  Anisotropic grid in 2D.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  3) Anisotropic grid in 2D\n' );

  dim_num = 2;
  point_num = 8;

  sparse_index = [ ...
    0, 2; ...
    1, 1; ...
    1, 2; ...
    2, 1; ...
    3, 0; ...
    3, 1; ...
    4, 0; ...
    5, 0 ]';

  sandia_sgmgg_coef_naive_test ( dim_num, point_num, sparse_index );
%
%  Generalized grid in 2D.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  4) Generalized grid in 2D\n' );

  dim_num = 2;
  point_num = 8;

  sparse_index = [ ...
    0, 0; ...
    0, 1; ...
    0, 2; ...
    0, 3; ...
    1, 0; ...
    1, 1; ...
    2, 0; ...
    3, 0 ]';

  sandia_sgmgg_coef_naive_test ( dim_num, point_num, sparse_index );

  return
end


function [cmap,cax] = mcColorMap(values,cmap)
%MCCOLORMAP returns the color mappin for values given cmap.
%   MCCOLORMAP uses the color map (CMAP) to define the color mapping for
%   the range in VALUES.
%

% find range of data in values and normalize to [0 1]
maxVal = max(values);
minVal = min(values);
normVal = (values - minVal)./ (maxVal - minVal);

% map to color
noColors = length(cmap);
indx = interp1(0:1/(noColors-1):1,1:noColors,normVal,'nearest');
cmap = cmap(indx,:);
cax = [minVal maxVal];


function im_rec = tomo_recon_fbp(projmat_bp,angles)
%TOMO_RECON_FBP   Tomographic reconstruction using Filtered Back Projection
%   (BP) algorithm.
%
%   Phymhan
%   05-Aug-2013 17:23:35

[n_proj,D] = size(projmat_bp);
if length(angles) ~= n_proj
    fprintf('Size of proj_mat is incorrect.\r')
    im_rec = [];
    return
end
im_rec = zeros(D);
for k = 1:n_proj
    proj_vec = hpf(projmat_bp(k,:));
    im_rot = repmat(proj_vec/D,D,1);
    im_rot = imrotate(im_rot, angles(k), 'bilinear', 'crop');
    %DEBUG
    % image(im_rot);
    % waitforbuttonpress
    % %
    im_rec = im_rec+im_rot/n_proj;
    %DEBUG
    % imagesc(im_rec)
    % waitforbuttonpress
    % %
end
end


function restricedRowBool = getCorrespondingRows(S, rowBool, colBool, mode)
% Returns a boolean vector that is true for a subset of the true rows in
% `rowBool` according to whether the rows 'exclusive', 'inclusive', or
% 'partial' -ly correspond to true entries in `colBool`
%
% USAGE:
%
%    restricedRowBool = getCorrespondingRows(S, rowBool, colBool, mode)
%
% INPUTS:
%    S:                     `m x n` stoichiometric matrix
%    rowBool:               `m x 1` boolean vector
%    colBool:               `n x 1` boolean vector
%    mode:                  'exclusive' , 'inclusive' or 'partial'
%
% OUTPUT:
%    restrictedRowBool:     `m x 1` boolean vector
%
% EXAMPLE:
%
%    S =
%        -1     0     0     0     0
%         2    -3     0     0     0
%         0     4    -5     0     0
%         0     0     6    -7     0
%         0     0     0     0     0
%
%    rowBool = [1; 1; 1; 1; 1];
%    colBool = [1; 1; 1; 0; 0];
%
%    % Therefore, the subset of rows and columns considered for inclusion are
%    %    -1     0     0
%    %     2    -3     0
%    %     0     4    -5
%    %     0     0     6
%    %     0     0     0
%
%    % If mode = 'exclusive' then restrictedRowBool corresponds to this subset
%    %    -1     0     0
%    %     2    -3     0
%    %     0     4    -5
%    % i.e subset of rowBool metabolites exclusively involved in the colBool
%    % reactions
%
%    % If mode = 'inclusive' then restrictedRowBool corresponds to this subset
%    %    -1     0     0
%    %     2    -3     0
%    %     0     4    -5
%    %     0     0     6
%    % i.e subset of rowBool metabolites involved in colBool reactions
%
%    % If mode ='partial' then restrictedRowBool corresponds to the extra rows
%    % with inclusive that are not present with exclusive.
%
% .. Author: - Ronan Fleming, July 2016

if ~islogical(rowBool)
    error('rowBool must be a logical vector')
end
if ~islogical(colBool)
    error('colBool must be a logical vector')
end

[mlt,nlt]=size(S);

if length(rowBool)~=mlt
    error('length of rowBool must equal size(S,1)')
end

if length(colBool)~=nlt
    error('length of rowBool must equal size(S,2)')
end

restricedRowBool=false(mlt,1);
switch mode
    case 'exclusive'
        %metatbolites exclusively involved in certain reactions
        restricedRowBool(rowBool)=     any(S(rowBool, colBool),2)...
                                    & ~any(S(rowBool,~colBool),2);
    case 'inclusive'
        %corresponding reactions involving certain metabolites
        restricedRowBool(rowBool) = any(S(rowBool, colBool),2);
    case 'partial'
        %metatbolites exclusively involved in certain reactions
        restricedRowBool(rowBool)=     any(S(rowBool, colBool),2)...
                                    & ~any(S(rowBool,~colBool),2);

        %corresponding reactions involving certain metabolites
        restricedRowBool2=false(mlt,1);
        restricedRowBool2(rowBool) = any(S(rowBool, colBool),2);
        %difference
        restricedRowBool= restricedRowBool2  & ~restricedRowBool;
   otherwise
        error(['Did not recognise mode: ' mode])
end


function visualizePts3d(pts3d, R, T, figTitle)
%% Visualize 3d reconstruction results with camera & projector extrinsics
% See also: showExtrinsics

%% License
% ACADEMIC OR NON-PROFIT ORGANIZATION NONCOMMERCIAL RESEARCH USE ONLY
% Copyright (c) 2018 Bingyao Huang
% All rights reserved.

% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:

% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.

% If you publish results obtained using this software, please cite our paper.

% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.

%%

% projector origin in world space
% camOrg = [0,0,0];
Rt = R';
prjOrg = (Rt*(-T))';

% draw
figure(Name=[figTitle ' 3d point cloud'], Units='normalized', Position=[0.3 0.3 0.2 0.3]);
hold on;
title([figTitle ' 3d point cloud'] );

% plot camera and projector models
cameraSize = 20 ;
plotCamera('Size', cameraSize, 'Color', 'b', 'Label', 'Camera', 'Opacity', 0);
grid on

% matlab buildtin function takes rotated OpenCV's R
plotCamera('Location', prjOrg, 'Orientation', Rt', 'Size', cameraSize, ...
    'Color', 'r', 'Label', 'Projector', 'Opacity', 0);

% Label the axes
xlabel('X', 'fontsize', 30);
ylabel('Y', 'fontsize', 30);
zlabel('Z', 'fontsize', 30);

% plot the 3d points in green
if(~isempty(pts3d))
    h = scatter3(pts3d(:,1),pts3d(:,2),pts3d(:,3), 10, 'go', 'filled',...
        'MarkerEdgeColor', 'k');
end

hold off;
daspect([1 1 1]);
view(3);
% axis vis3d tight;
h.Clipping = 'off'; % disable clipping

rotate3d on
end


function sparse_grid_gl_test01 ( dim_min, dim_max, level_max_min, ...
  level_max_max )

%*****************************************************************************80
%
%% TEST01 tests SPARSE_GRID_GL_SIZE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DIM_MIN, the minimum spatial dimension to consider.
%
%    Input, integer DIM_MAX, the maximum spatial dimension to consider.
%
%    Input, integer LEVEL_MAX_MIN, the minimum value of LEVEL_MAX to consider.
%
%    Input, integer LEVEL_MAX_MAX, the maximum value of LEVEL_MAX to consider.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST01\n' );
  fprintf ( 1, '  SPARSE_GRID_GL_SIZE returns the number of distinct\n' );
  fprintf ( 1, '  points in a Gauss-Legendre sparse grid.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Note that, unlike most sparse grids, a sparse grid\n' );
  fprintf ( 1, '  based on Gauss-Legendre points is almost entirely \n' );
  fprintf ( 1, '  NOT nested.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Hence the point counts should be much higher than for a grid of\n' );
  fprintf ( 1, '  the same level, but using rules such as Fejer1 or Fejer2 or\n' );
  fprintf ( 1, '  Gauss-Patterson or Newton-Cotes-Open or Newton-Cotes-Open-Half.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Each sparse grid is of spatial dimension DIM,\n' );
  fprintf ( 1, '  and is made up of all product grids of levels up to LEVEL_MAX.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '   DIM: ' );

  for dim_num = dim_min : dim_max
    fprintf ( 1, '  %8d', dim_num );
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '   LEVEL_MAX\n' );
  fprintf ( 1, '\n' );

  for level_max = level_max_min : level_max_max
    fprintf ( 1, '    %4d', level_max );
    for dim_num = dim_min : dim_max
      point_num = sparse_grid_gl_size ( dim_num, level_max );
      fprintf ( 1, '  %8d', point_num );
    end
    fprintf ( 1, '\n' );
  end

  return
end


function [ Model2 ] = NNTest()

    % Extract Features From the Images
    [Features] = LoadImages();
    % Load The Image Classes
    [yTrain] = LoadLabels();

    % Tweak these parameters to get optimum accuracy
    varianceThreshold = 0.90;
    thresholdDifference = 0.0004;
    regularizationRate = 6.5;
    learningRate = 1;
    hiddenNodes = 175;

    [xTrain, projection] = BestFeats(Features, varianceThreshold);

    % Train the Neural Net.
    [ weights1, weights2, ~ ] = NNTrain(xTrain, yTrain, hiddenNodes, ...
                                    learningRate, regularizationRate, ...
                                    thresholdDifference);
    Model2 = struct('weights1', weights1, 'weights2', weights2, ...
             'projection', projection);
    save('Model2.mat', 'Model2');

end


function T=Entropy_Yen(X,Trange);
hg=hist(X,Trange);
pg=hg./sum(hg);
Ti=0;
TrangeSpan=Trange(pg>0);
JT=zeros(length(TrangeSpan),1);
for Tk=TrangeSpan
    Ti=Ti+1;
    PT=sum(pg(Trange<=Tk));
    Cf=-log10(sum((pg(Trange<=Tk)./PT).^2));
    Cb=-log10(sum((pg(Trange>Tk)./(1-PT)).^2));
    JT(Ti)=Cf+Cb;
end
JT(isinf(JT))=0;
JT(isnan(JT))=0;
[~,Tind]=max(JT);
T=TrangeSpan(Tind);
end


function out = grandAverage_prototye(cell_struct, bool_arith)
%% Description
% cell of averaged data
numData = length(cell_struct);

if nargin == 1
    bool_arith = false;
end

for i = 1:numData
    dat = cell_struct{i};

    if isequal(dat.class{1,2}, 'sgnr^2')
        dat.x = atanh(sqrt(abs(dat.x)).*sign(dat.x));
    end
    cell_struct{i} = dat;
end
[time, trials, channels] = size(cell_struct{1}.x);
dat_av = zeros(time, trials, channels);

ncls = size(cell_struct{1}.class, 1);
for cls = 1:ncls
    sW = 0;
    swV = 0;
    for v = 1:numData
        if bool_arith %% options-> Arithmetic or WeightedMean
            W = 1./cell_struct{v}.se(:, cls,:).^2;
        else
            % Arithmetic
            W = 1;
        end
        sW = sW + W;
        swV = swV + W.^2.*cell_struct{v}.se(:, cls, :).^2;
        dat_av(:, cls, :) = dat_av(:, cls,:) + W.*cell_struct{v}.x(:,cls,:);
    end
    dat_av(:, cls,:) = dat_av(:, cls,:)./sW;
    se(:, cls,:) = sqrt(swV)./sW;
end

if isequal(dat.class{1,2}, 'sgnr^2')
    dat_av = tanh(dat_av).*abs(tanh(dat_av));
end

out = cell_struct{1};
out.x = dat_av;
out.se = se;
end


function  [gx] = g_Kalman4bandits (x, P, ~, in)
% // VBA toolbox //////////////////////////////////////////////////////////
%
% [gx] = g_Kalman4bandits (x, P, u, in)
% softmax decision rule for N-armed bandit task as in Daw et al. 2006
%
% /////////////////////////////////////////////////////////////////////////

% Get parameter values
% -------------------------------------------------------------------------
% inverse temperature
beta = exp (P(1)); % exp: [-Inf,Inf] -> [0 Inf]
% bonus to exploration
phi = P(2);

% Extract expectation and variance of each bandit
% -------------------------------------------------------------------------
nBandits = in.nBandits;
mu = x(1 : nBandits);
sigma2 = x(nBandits + (1 : nBandits)) .^ 2;

% apply softmax
% -------------------------------------------------------------------------
gx = VBA_softmax(beta * (mu + phi * sigma2));


function [ellipse, labels] = imInertiaEllipse(img, varargin)
%IMINERTIAELLIPSE Inertia ellipse of a binary or label image
%
%   Deprecated, use 'imEquivalentEllipse' instead.
%
%   ELLI = imInertiaEllipse(IMG)
%   Compute the inertia ellipses of the particles in labeled image IMG. If
%   the image is binary, one ellipse, corresponding to the foreground (i.e.
%   the pixels with value 1) will be computed.
%
%   The result is a N-by-5 array ELLI = [XC YC A B THETA], containing
%   coordinates of ellipse center, lengths of semi major and minor axes,
%   and the orientation (given in degrees, in the direction of the greatest
%   axis).
%
%   The same result could be obtained with the regionprops function. The
%   advantage of using imInertiaEllipse is that equivalent ellipses can be
%   obtained in one call. Orientation of both functions are not consistent.
%
%   ELLI = imInertiaEllipse(IMG, SPACING);
%   ELLI = imInertiaEllipse(IMG, SPACING, ORIGIN);
%   Specifies the spatial calibration of image. Both SPACING and ORIGIN are
%   1-by-2 row vectors. SPACING = [SX SY] contains the size of a pixel.
%   ORIGIN = [OX OY] contains the center position of the top-left pixel of
%   image.
%   If no calibration is specified, spacing = [1 1] and origin = [1 1] are
%   used. If only the sapcing is specified, the origin is set to [0 0].
%
%   ELLI = imInertiaEllipse(..., LABELS)
%   Specify the labels for which the inertia ellipse needs to be computed.
%   The result is a N-by-5 array with as many rows as the number of labels.
%
%
%   Example
%   % Draw a commplex particle together with its equivalent ellipse
%     img = imread('circles.png');
%     imshow(img); hold on;
%     elli = imInertiaEllipse(img);
%     drawEllipse(elli)
%
%   % Compute and display the equivalent ellipses of several particles
%     img = imread('rice.png');
%     img2 = img - imopen(img, ones(30, 30));
%     lbl = bwlabel(img2 > 50, 4);
%     ellipses = imInertiaEllipse(lbl);
%     imshow(img); hold on;
%     drawEllipse(ellipses, 'linewidth', 2, 'color', 'g');
%
%   See also
%     imEquivalentEllipse
%

% ------
% Author: David Legland
% e-mail: david.legland@inra.fr
% Created: 2011-03-30,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.

warning('MatImage:deprecated', ...
    'function imInertiaEllipse is obsolete, use imEquivalentEllipse instead');

%% extract spatial calibration

% default values
spacing = [1 1];
origin  = [1 1];
calib   = false;

% extract spacing
if ~isempty(varargin) && sum(size(varargin{1}) == [1 2]) == 2
    spacing = varargin{1};
    varargin(1) = [];
    calib = true;
    origin = [0 0];
end

% extract origin
if ~isempty(varargin) && sum(size(varargin{1}) == [1 2]) == 2
    origin = varargin{1};
end

%% Initialisations

% check if labels are specified
labels = [];
if ~isempty(varargin) && size(varargin{1}, 2) == 1
    labels = varargin{1};
end

% extract the set of labels, without the background
if isempty(labels)
    labels = imFindLabels(img);
end
nLabels = length(labels);

% allocate memory for result
ellipse = zeros(nLabels, 5);

%% Extract ellipse corresponding to each label

for i = 1:nLabels
    % extract points of the current particle
    [y, x] = find(img==labels(i));

    % transform to physical space if needed
    if calib
        x = (x-1) * spacing(1) + origin(1);
        y = (y-1) * spacing(2) + origin(2);
    end

    % compute centroid, used as center of inertia ellipse
    xc = mean(x);
    yc = mean(y);

    % recenter points (should be better for numerical accuracy)
    x = x - xc;
    y = y - yc;

    % number of points
    n = length(x);

    % compute inertia parameters. 1/12 is the contribution of a single
    % pixel, then for regions with only one pixel the resulting ellipse has
    % positive radii.
    Ixx = sum(x.^2) / n + spacing(1)^2/12;
    Iyy = sum(y.^2) / n + spacing(2)^2/12;
    Ixy = sum(x.*y) / n;

    % compute ellipse semi-axis lengths
    common = sqrt( (Ixx - Iyy)^2 + 4 * Ixy^2);
    ra = sqrt(2) * sqrt(Ixx + Iyy + common);
    rb = sqrt(2) * sqrt(Ixx + Iyy - common);

    % compute ellipse angle and convert into degrees
    theta = atan2(2 * Ixy, Ixx - Iyy) / 2;
    theta = theta * 180 / pi;

    % create the resulting inertia ellipse
    ellipse(i,:) = [xc yc ra rb theta];
end


% A patch group is a matrix pg of size
%
%     px x px x ch x pt x np
%
% where px is the spatial  size of the patch
%       pt is the temporal size of the patch
%       ch is the number of channels
%       np is the number of patches in the group
%
% This function transforms the patch group in to
% an RGB image with all the patches in the group,
% of size
%
%     pt*(px+sw)-sw x np*(px+sw)-sw x ch
%
% The temporal slices of the patch are stacked vertically,
% with separators of sw pixels. Each patch is then stacked
% horizontally, also with separators of sw pixels.
%
% This function was written to use from patch_group.
%
function pp = build_patch_image(pp, force_one_row, sc, sw)

px = size(pp,1);
pt = size(pp,4);
np = size(pp,5);

if nargin < 2,
	force_one_row = false;
end

if nargin < 3,
	sc = 255;
end

if nargin < 4,
	sw = 1;
end

if (size(sc,2) ~= 1) && (size(sc,2) ~= 3),
	error('The separator colormap should have either 1 or 3 channels')
end

ch = max(size(pp,3),size(sc,2));

if (max(size(sc)) == 1),

	pp = permute(pp, [2 1 4 5 3]);
	pp = cat(2, pp, 0*sc*ones(px, sw, pt, np, ch));
	pp = reshape(pp, [px, pt*(px + sw), np, ch]);

	pp = permute(pp, [2 1 3 4]);
	pp = cat(2, pp, sc*ones(pt*(px + sw), sw, np, ch));
	pp = reshape(pp, [pt*(px + sw), np*(px + sw), ch]);

	pp = pp(1:pt*(px + sw) - sw, 1:np*(px + sw) - sw, :);

	% if resulting image is too long and narrow, split it in more rows
	if (force_one_row == false) && (10*pt < np)

		% factorize np into m*n minimizing the perimeter m+n
		m = floor(sqrt(np));
		while mod(np,m) ~= 0,
			m = m - 1;
		end
		n = np/m;

		if (10*m*pt < n)
			m = floor(sqrt(np));
			n = ceil(np/m);
		end

		% separator between rows of patches has to be wider than separator between
		% the frames of a patch
		swr = sw * (1 + (pt > 1));
		ppp = sc*ones(m*(pt*(px + sw) - sw + swr) - swr, n*(px + sw) - sw, ch);
		for i = 0:m-1,

			start_pp  = i*n*(px + sw) + 1;
			until_pp  = min(i*n*(px + sw) + n*(px + sw) - sw, size(pp,2));
			range_ppp = i*(pt*(px + sw) - sw + swr) + [1:pt*(px + sw) - sw];
			ppp(range_ppp,1:1+until_pp - start_pp,:) = pp(:,start_pp:until_pp,:);

		end

		pp = ppp;

	end

else

	m = 1;

	% if resulting image is too long and narrow, split it in more rows
	if (force_one_row == false) && (10*pt < np)

		% factorize np into m*n minimizing the perimeter m+n
		m = floor(sqrt(np));
		while mod(np,m) ~= 0,
			m = m - 1;
		end

	end

	n = np/m;

	if size(sc,2) < ch, sc = repmat (sc, [1  1 ch]);
	else                sc = reshape(sc, [np 1 ch]);
	end

	if size(pp,3) < ch, pp = repmat(pp,[1 1 ch]);
	end

	ppp = zeros(m*(pt*(px + sw) + sw),n*(px + 2*sw), ch);
	for i = 1:np,

		scp = sc(i,:,:);

		p = pp(:,:,:,:,i);
		p = permute(p, [2 1 4 5 3]);
		sep = zeros([px, sw, pt, 1, ch]);
		p = cat(2, p, repmat(reshape(scp,[1, 1, 1, 1, ch]), px, sw, pt));
		p = squeeze(reshape(p, [px, pt*(px + sw), 1, ch]));

		% usando cat, agregar bordes derecho, izq, y superior
		p = permute(p, [2 1 3]);
		p = cat(1, repmat(scp, sw, px), p);
		p = cat(2, repmat(scp, pt*(px+sw) + sw, sw), p);
		p = cat(2, p, repmat(scp, pt*(px+sw) + sw, sw));

		[ni,mi] = ind2sub([n,m],i);
		ppp((mi-1)*size(p,1) + [1:size(p,1)],...
		    (ni-1)*size(p,2) + [1:size(p,2)],:) = p;

	end

	pp = ppp;

end


function pde = jumpmgdata2
%% Data of JUMPMG1
%
% Copyright (C)  Long Chen. See COPYRIGHT.txt for details.

pde = struct('f',@f,'g_D',@g_D,'d',@omega);

    function s = f(p) % load data (right hand side function)
    s = zeros(size(p,1),1);
    end

    function s = g_D(p) % Dirichlet boundary condition
    s = zeros(size(p,1),1);
    x = p(:,1);
    idx = (abs(x-1)<eps);
    s(idx) = 1;
    s(~idx) = 0;
    end

    function c = omega(p) % diffusion constant
    global epsilon
    c = zeros(size(p,1),1);
    x = p(:,1); y = p(:,2); z = p(:,3);
    idx = ((x>0) & (x<0.5) & (y>0) & (y<0.5) & (z>0) & (z<0.5)) | ...
          ((x<0) & (x>-0.5) & (y<0) & (y>-0.5) & (z<0) & (z>-0.5));
    c(idx) = 1;
    c(~idx) = epsilon;
    end
end


%% Importing Vectors
%
%%
% Large lists of vectors can be imported from a text file by the command

fname = fullfile(mtexDataPath,'vector3d','vectors.txt');
v = vector3d.load(fname,'ColumnNames',{'polar angle','azimuth angle'})

%%
% In order to visualize large lists of specimen directions scatter plots

scatter(v,'upper')

%%
% or contour plots may be helpful

contourf(v,'upper')


function coef = plotnsdgtreal(coef,a,varargin)
%PLOTNSDGTREAL Plot NSDGTREAL coefficients
%   Usage:  plotnsdgtreal(c,a,fs,dynrange);
%
%   Input parameters:
%         coef     : Cell array of coefficients.
%         a        : Vector of time positions of windows.
%         fs       : signal sample rate in Hz (optional).
%         dynrange : Colorscale dynamic range in dB (optional).
%
%   `plotnsdgtreal(coef,a)` plots coefficients computed using |nsdgtreal| or
%   |unsdgtreal|. For more details on the format of the variables *coef* and *a*,
%   please read the function help for these functions.
%
%   `plotnsdgtreal(coef,a,fs)` does the same assuming a sampling rate of
%   *fs* Hz of the original signal.
%
%   `plotnsdgtreal(coef,a,fs,dynrange)` additionally limits the dynamic range.
%
%   `C=plotnsdgtreal(...)` returns the processed image data used in the
%   plotting. Inputting this data directly to `imagesc` or similar
%   functions will create the plot. This is useful for custom
%   post-processing of the image data.
%
%   `plotnsdgtreal` supports all the optional parameters of |tfplot|. Please
%   see the help of |tfplot| for an exhaustive list. In addition, the
%   following parameters may be specified:
%
%     'xres',xres  Approximate number of pixels along x-axis /time.
%                  Default value is 800
%
%     'yres',yres  Approximate number of pixels along y-axis / frequency
%                  Default value is 600
%
%   See also: tfplot, nsdgt, nsdgtreal

%   AUTHOR : Florent Jaillet & Peter L. Søndergaard
%   TESTING: OK
%   REFERENCE: NA

if nargin<2
  error('%s: Too few input parameters.',upper(mfilename));
end;

definput.import={'ltfattranslate','tfplot'};

definput.keyvals.xres=800;
definput.keyvals.yres=600;

[flags,kv,fs]=ltfatarghelper({'fs','dynrange'},definput,varargin);

timepos=cumsum(a)-a(1);

N=length(a);
cwork=zeros(kv.yres,N);

%% -------- Interpolate in frequency ---------------------

for ii=1:N
  column=coef{ii};
  M=length(column);
  cwork(:,ii)=interp1(linspace(0,1,M),column,linspace(0,1,kv.yres),'nearest');
end;

%% --------  Interpolate in time -------------------------

% Time step in next equidistant spacing on the x-axis (in samples)
aplot=timepos(end)/kv.xres;

% Time positions where we want our pixels plotted (in samples)
xr=(0:kv.xres-1)*aplot;

coef=zeros(kv.yres,kv.xres);
for ii=1:kv.yres
  data=interp1(timepos,cwork(ii,:).',xr,'nearest').';
  coef(ii,:)=data;
end;

yr=[0,1];

coef=tfplot(coef,aplot,yr,'argimport',flags,kv);

if nargout<1
    clear coef;
end


function [relamps,Y,E,avgTC] = eventBoldContrast(tc,selectedConds,avgTC,unitFree,plotFlag)
% Calculate and plot the relative time series amplitudes for various
% experimental conditions
%
%   [relamps,Y,E,avgTC] = eventBoldContrast(tc,selectedConds,[avgTC],[unitFree],[plotFlag]);
%
% returns:
% relamps: the contrast values for every event
% Y: the average contrast value per condition
% E: standard error per condition
% avgTC: the mean time course of all the events in all conditions (r, baseline
% for contrast computation)
%
% The model is based on Ress & Heeger (Nature Neuroscience, 2000).  The
% relative amplitudes are  (after our recent edits) probably a misnomer.
% The values returned here are the percent contrast of the modulation.
%
% The model used here is this.  We assume that the basic time course of
% each condition has the same shape function, say r(t). They differ only by
% noise and a scalar, a*r(t) + N. We estimate the basic shape of the time
% course by averaging all of the conditions. This reduces the effect of the
% noise (N).  Then we compare the amplitude of the response by looking at
% the scalar (dot, inner) product of the measurements for one condition
% with respect to the estimated average.
%
% At present, the calculation of the relative amplitude is
%
%       a =  s . r / sqrt(r.r)
%
% where r is the average set to a mean of zero, and s is the time course
% for the selected condition, also set to a mean of zero.
%
% The logic for this is as follows.  The angle, theta, between s and r is
%
%     cos(theta) = s.r / |s||r|
%
% The length of the projection of s onto r is |x|/|s| = cos(theta).
% Putting these together,
%
%      |x| = |s|* (s.r) / |s||r|
%      |x| = (s.r)/|r|
%      |x| = (s.r)/sqrt(r.r)
%
% The |r| is the lenth of r and this is sqrt(dot(r,r,))
% Units, scaling: taking the sqrt in the denominator has the effect of keeping the
% original scale of the subject's signal. so, the units are %modulation now.
%
% unitFree flag: if this is set to 1, we do not take the square root in the denominator.
% this leaves us with a unit less measure, but one that is more comparable
% across subjects, which can be used for a group analysis, if overall signal
% variations are considered irrelevant.
%
% Limitations.
% If different conditions have different time courses, this too will be
% missed by this analysis.
%
% tc: a structure containing the time course information for an
% experiment.
%
% HISTORY
% 02/23/04 ras: wrote it. This is the first new functionality to
% timeCourseUI since incorporating it into mrLoadRet.
% 07/04 ras: now everything uses er_chopTSeries, so the relamps
% are already calculated. Nonetheless, I'm keeping the old calculations
% here, since with relamps in particular, having some conditions not
% selected may significantly change the mean time course, fundamentally
% changing the usefulness of the estimate. (e.g., if there's a baseline
% condition with a fundamentally diff't shape than other conds, disabling
% it, then recomputing makes sense.)
% 08/05 MBS, BW Comments. also changed the way relAmps are computed - avgTC
% is normalized to mean zero and unit size
%

if ieNotDefined('tc'), error('Time course structure required'); end
if ieNotDefined('selectedConds'), selectedConds = find(tc_selectedConds(tc)); end
if ieNotDefined('avgTC'),    avgTC = []; end
if ieNotDefined('unitFree'), unitFree = 0; end
if ieNotDefined('plotFlag'), plotFlag = 1; end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% clean up existing objects in figure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plotFlag
    otherAxes = findobj('Type','axes','Parent',gcf);
    delete(otherAxes);
    otherUiControls = findobj('Type','uicontrol','Parent',gcf);
    delete(otherUiControls);
    cla
end

% params
prestim = 1;

% tx contains the frame # in tc.wholeTc at which each trial starts
tx = round([(tc.trials.onsetSecs./tc.TR)+1 length(tc.wholeTc)]);
% intervals = diff(tx);

% figure out selected conditions, trials, labels, and colors

whichConds = tc.condNums(selectedConds);
nConds = length(whichConds);
trials = find(ismember(tc.trials.cond,whichConds));
nTrials = length(trials);

colors = tc.condColors(selectedConds);
labels = tc.condNames(selectedConds);

% initialize selTrials matrix to be NaNs of the size of the shortest trial
% minInt = min(intervals(trials)) + prestim;
% selTrials = NaN*ones(minInt,nTrials);

% get selected trials, avg time course of selected trials
selTrials = [];
for i = 1:nTrials
    rng = tx(trials(i))-prestim:tx(trials(i)+1)-1;
    rng = round(rng);
    rng = rng(rng>0 & rng<length(tc.wholeTc)); % clip to fit data
    selTrials(1:length(rng),i) = tc.wholeTc(rng)';
    conds(i) = tc.trials.cond(trials(i));
end

% normalize everything to have a mean zero
for i = 1:nTrials
    offset = mean(selTrials(:,i));
    selTrials(:,i) = selTrials(:,i) - offset;
end

% we calculate the avgTC after normalizing each trial, so its mean is set to zero too
if isempty(avgTC), avgTC = mean(selTrials,2);
else
    if length(avgTC) ~= size(selTrials,1)
        error('User supplied avgTC has length %.0f.  Should have length %.0f\n',...
            length(avgTC),size(selTrials,1));
    end
end

% take dot product of each trial's time course w/ avg
relamps = NaN*ones(1,nTrials);
for i = 1:nTrials
    relamps(i) = dot(avgTC,selTrials(:,i));
end

if unitFree % this will give Ress' measure, no units
    relamps = relamps / dot(avgTC,avgTC);
else
    % this will give a bold contrast measure
    relamps = relamps / sqrt(dot(avgTC,avgTC));
end

% get mean and stdev of each condition
for c = 1:length(whichConds)
    ind = (conds==whichConds(c));
	Y(c) = mean(relamps(ind));
	E(c) = std(relamps(ind)) ./ sqrt(sum(ind));
end

%%%%% plot color bars for each cond
% (gum to keep legend from being erased:)
if plotFlag

    % figure out nice axis range
    maxY = max([0 1.2*max(Y)]);
    minY = min([0 1.2*min(Y)]);
    AX = [0 nConds+1 minY maxY];

    set(gcf,'NextPlot','add');
    set(gca,'Visible','off');
    subplot('Position',get(gca,'Position'))
    mybar(Y,E,labels,labels,colors);
    ylabel('Relative amplitude');
    hold on

    % append calculated relamps to tc struct
    tc.relamps = relamps;
    if isfield(tc,'ui'),  set(gcf,'UserData',tc); end
end

return


%==============================================================================
% This code is part of the Matlab-based toolbox
% FAIR - Flexible Algorithms for Image Registration.
% For details see
% - https://github.com/C4IR and
% - http://www.siam.org/books/fa06/
%==============================================================================
%
% Tutorial for FAIR: SSD versus translations, linearInter, HNSP level=8
%
%==============================================================================

clear, close all, help(mfilename)

setup2DHNSPData;
level = 8; m = ML{level}.m;
imgModel('set','imgModel','linearInter');
[T,R] = imgModel('coefficients',ML{level}.T,ML{level}.R,omega);
xc    = getCellCenteredGrid(omega,m);
Rc    = imgModel(R,omega,xc);

trafo('set','trafo','translation2D');
figure(1); clf;
[w1,w2] = ndgrid(0.2*linspace(-1,1,21),0.2*linspace(-1,1,21));
dc  = zeros(size(w1));
for j=1:numel(dc),
  yc = trafo([w1(j);w2(j)],xc);
  Tc = imgModel(T,omega,yc);
  dc(j) = SSD(Tc,Rc,omega,m);
  viewImage(Tc,omega,m); FAIRpause(1/100)
end;
figure(1); clf; surf(w1,w2,dc); hold on; grid off; contour(w1,w2,dc)
title(sprintf('translation, m=[%d,%d]',m)); view(-135,33);
%==============================================================================


function res = my_non_maxima(I, radii, threshold)

% non maxima supression, odd size mask
mask = 2*radii+1;
max = ordfilt2(I,mask^2,true(mask));

% Maxima and Threshold
res = (I==max) & (I >threshold);

return


function [ title, key, totcrd, ptrcrd, indcrd, valcrd, rhscrd, mxtype, ...
  nrow, ncol, nnzero, neltvl, ptrfmt, indfmt, valfmt, rhsfmt, rhstyp, ...
  nrhs, nrhsix, colptr, rowind, values, rhsval, rhsptr, rhsind, guess, ...
  exact ] = hb_file_read ( input_unit )

%*****************************************************************************80
%
%% HB_FILE_READ reads an HB file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 April 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Iain Duff, Roger Grimes, John Lewis,
%    User's Guide for the Harwell-Boeing Sparse Matrix Collection,
%    October 1992.
%
%  Parameters:
%
%    Input, integer INPUT_UNIT, the unit from data is read.
%
%    Output, character ( len = 72 ) TITLE, a title for the matrix.
%
%    Output, character ( len = 8 ) KEY, an identifier for the matrix.
%
%    Output, integer TOTCRD, the total number of lines of data.
%
%    Output, integer PTRCRD, the number of input lines for pointers.
%
%    Output, integer INDCRD, the number of input lines for row indices.
%
%    Output, integer VALCRD, the number of input lines for numerical values.
%
%    Output, integer RHSCRD, the number of input lines for right hand sides.
%
%    Output, character ( len = 3 ) MXTYPE, the matrix type.
%    First character is R for Real, C for complex, P for pattern only.
%    Second character is S for symmetric, U for unsymmetric, H for
%      Hermitian, Z for skew symmetric, R for rectangular.
%    Third character is A for assembled and E for unassembled
%      finite element matrices.
%
%    Output, integer NROW, the number of rows or variables.
%
%    Output, integer NCOL, the number of columns or elements.
%
%    Output, integer NNZERO.  In the case of assembled sparse matrices,
%    this is the number of nonzeroes.  In the case of unassembled finite
%    element matrices, in which the right hand side vectors are also
%    stored as unassembled finite element vectors, this is the total
%    number of entries in a single unassembled right hand side vector.
%
%    Output, integer NELTVL, the number of finite element matrix entries,
%    set to 0 in the case of assembled matrices.
%
%    Output, character ( len = 16 ) PTRFMT, the format for reading pointers.
%
%    Output, character ( len = 16 ) INDFMT, the format for reading indices.
%
%    Output, character ( len = 20 ) VALFMT, the format for reading values.
%
%    Output, character ( len = 20 ) RHSFMT, the format for reading values
%    of the right hand side.
%
%    Output, character ( len = 3 ) RHSTYP, the right hand side type.
%    First character is F for full storage or M for same as matrix.
%    Second character is G if starting "guess" vectors are supplied.
%    Third character is X if exact solution vectors are supplied.
%    Ignored if NRHS = 0.
%
%    Output, integer NRHS, the number of right hand sides.
%
%    Output, integer NRHSIX, the number of row indices (set to 0
%    in the case of unassembled matrices.)  Ignored if NRHS = 0.
%
%    Output, integer COLPTR(NCOL+1), COLPTR(I) points to the location of
%    the first entry of column I in the sparse matrix structure.
%
%    Output, integer ROWIND(NNZERO) or ROWIND(NELTVL), the row index of
%    each item.
%
%    Output, real VALUES(NNZERO) or VALUES(NELTVL), the nonzero values
%    of the matrix.
%
%    If RHSTYP(1:1) == 'F':
%
%      Output, integer RHSPTR(*), is not used.
%
%      Output, integer RHSIND(*), is not used.
%
%      Output, real RHSVAL(NROW,NRHS), contains NRHS dense right hand
%      side vectors.
%
%    If RHSTYP(1:1) = 'M' and MXTYPE(3:3) = 'A':
%
%      Output, integer RHSPTR(NRHS+1), RHSPTR(I) points to the location of
%      the first entry of right hand side I in the sparse right hand
%      side vector.
%
%      Output, integer RHSIND(NRHSIX), indicates, for each entry of
%      RHSVAL, the corresponding row index.
%
%      Output, real RHSVAL(NRHSIX), contains the value of the right hand
%      side entries.
%
%    If RHSTYP(1:1) = 'M' and MXTYPE(3:3) = 'E':
%
%      Output, integer RHSPTR(*), is not used.
%
%      Output, integer RHSIND(*), is not used.
%
%      Output, real RHSVAL(NNZERO,NRHS), contains NRHS unassembled
%      finite element vector right hand sides.
%
%    Output, real GUESS(NROW,NRHS), the starting guess vectors.
%
%    Output, real EXACT(NROW,NRHS), the exact solution vectors.
%

%
%  Read the header block.
%
  [ title, key, totcrd, ptrcrd, indcrd, valcrd, rhscrd, mxtype, ...
    nrow, ncol, nnzero, neltvl, ptrfmt, indfmt, valfmt, rhsfmt, rhstyp, ...
    nrhs, nrhsix ] = hb_header_read ( input_unit );
%
%  Read the matrix structure.
%
  [ colptr, rowind ] = hb_structure_read ( input_unit, ncol, mxtype, ...
    nnzero, neltvl, ptrcrd, ptrfmt, indcrd, indfmt );
%
%  Read the matrix values.
%
  values = hb_values_read ( input_unit, valcrd, mxtype, nnzero, neltvl, ...
    valfmt );
%
%  Read the right hand sides.
%
  [ rhsval, rhsptr, rhsind ] = hb_rhs_read ( input_unit, nrow, nnzero, ...
    nrhs, nrhsix, rhscrd, ptrfmt, indfmt, rhsfmt, mxtype, rhstyp );
%
%  Read the starting guesses.
%
  guess = hb_guess_read ( input_unit, nrow, nrhs, rhscrd, rhsfmt, rhstyp );
%
%  Read the exact solutions.
%
  exact = hb_exact_read ( input_unit, nrow, nrhs, rhscrd, rhsfmt, rhstyp );

  return
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This test compares the result of the inverse dynamic function using both:
%   a) the Newton-Euler algorithm
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function test_forwarddynamics()
close all
global robot g q0 qd0 tau total_simulation_time

g=[0  -9.81 0]'; %y0 axis
%initial position and joint speed
q0 = [0 0]';
qd0 = [0 0]';
tau = [0 0]';%no torques applied
total_simulation_time = 5;
%select friction or not
robot.dynamics.friction = 1;

fprintf('\nTHE SIMULATION PRESENTS THE ROBOT AT AN INITIAL POSITION WHEN NO TORQUES ARE APPLIED\n')

%load robot parameters
robot=load_robot('example', '2dofplanar');

% drawrobot3d(robot, q0);
% adjust_view(robot);

[t q qd] = forward_test_A();

figure, plot(t, q, 'r'), hold

[t q qd] = forward_test_B();

plot(t, q, 'b')

speed = 10
animate(robot,[q(1,1:speed:length(q)); q(2,1:speed:length(q))])

function [t q qd] = forward_test_A()
global robot g q0 qd0 tau total_simulation_time

fprintf('\nCOMPUTING FORWARD DYNAMICS (this may take a while)')

%this may take a while, since it requires integration
%of the acceleration at each time step
[t q qd] = forwarddynamic(robot, total_simulation_time, q0, qd0, tau, g, []);

function [t q qd] = forward_test_B()
global total_simulation_time

[t, y] = runge_kutta(@forward_dynamic_robot2, [0 0 0 0]', [0 total_simulation_time], 0.01);

%Assign joint variables and joint speeds.
q = y(1:2,:);
qd = y(3:4,:);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Helper function to simulate the movement of a 2 DOF robot
% Called from function exerciseD()
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xd = forward_dynamic_robot2(t, y)
global tau g robot
%we must return the solution of
% [dx1/dt; dx2/dt], in this case [qd; qdd]
t
qdd=forwarddynamics_2dofplanar(robot, y(1:2,1), y(3:4,1), tau, -sum(g), [0 0 0 0 0 0]);
xd = [y(3:4,1); qdd];


%Create A figure
figure
mainAxes = axes;
plot(mainAxes ,1:5,1:5,'r',1:5,1:0.5:3,'b');
xlabel 'This is an X Axis Label'
ylabel 'This is a Y Axis Label'
title('A Generic Title');
legend('Red Line','Blue Line');
set(gca,'Layer','Top')

%Break The Axes
h = breakxaxis([2 3]);

%Un-Break The X Axes
%unbreakxaxes(h)


function [ft3] = oz2ft3(oz)
% Convert volume from US liquid ounces to cubic feet.
% Chad Greene 2012
ft3 = oz*0.0010443793403;


% Surround matrix with NaNs
function [R]=NanMat(Data,GridSize,varargin)
%Input = Data: a m*n matrix
% GridSize: Optional, only needed if data is entered as a list
%           a 1x2 vector of size of original grid. (npx,npy)
%output = R: a m+2*n+2 matrix in which Data is preserved and surrounded by
%NaN's

%Reshape the data list to a grid
if (length(varargin) == 2)
L = reshape (Data,GridSize(1),GridSize(2));
else
    L = Data;
end
% create a matrix sames size as L but with 2 extra rows and columns, and
% fill it with NaN
R=zeros((size(L,1)+2),(size(L,2)+2))*NaN;
%Insert L into middle of matrix
R(2:end-1,2:end-1)= L;
end