function s2de_test ( )

%*****************************************************************************80
%
%% S2DE_TEST tests the S2DE library.
%
%  Location:
%
%    http://people.sc.fsu.edu/~jburkardt/m_src/stokes_2d_exact/s2de_test.m
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 February 2015
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'S2DE_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the S2DE library.\n' );

  uvp_stokes1_test ( );
  resid_stokes1_test ( );
  gnuplot_stokes1_test ( );

  uvp_stokes2_test ( );
  resid_stokes2_test ( );
  gnuplot_stokes2_test ( );

  uvp_stokes3_test ( );
  resid_stokes3_test ( );
  gnuplot_stokes3_test ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'S2DE_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  timestamp ( );

  return
end


% create a sub network that takes in waveforms and produces fourier
% coefficients

function layer = genNetworkSTFT2LogSpec(stftLayer, useLog, logConst)
layer = stftLayer;

layer{end+1} = PowerNode(stftLayer{end}.dim(1));
if useLog
    if nargin<3
        logConst = 0.00;
    end
    layer{end+1} = LogarithmNode(layer{end}.dim(1), logConst);
end

layer = ConnectLinearGraph(layer);
layer = FinishLayer_obj(layer);

end


function blas1_z_test06 ( )

%*****************************************************************************80
%
%% TEST06 tests ZAXPY.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 May 2006
%
%  Author:
%
%    John Burkardt
%
  n = 5;

  x = [ ...
      2.0 -1.0 * i, ...
     -4.0 -2.0 * i, ...
      3.0  1.0 * i, ...
      2.0  2.0 * i, ...
     -1.0 -1.0 * i ];
  y = [ ...
     -1.0,  0.0 * i, ...
      0.0, -3.0 * i, ...
      4.0,  0.0 * i, ...
     -3.0,  4.0 * i, ...
     -2.0,  0.0 * i ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST06\n' );
  fprintf ( 1, '  ZAXPY adds a multiple of one complex vector to another.\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  X = \n' );
  fprintf ( 1, '\n' );
  for j = 1 : n
    fprintf ( 1, '  %6d  %10f  %10f\n', j, real ( x(j) ), imag ( x(j) ) );
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Y = \n' );
  fprintf ( 1, '\n' );
  for j = 1 : n
    fprintf ( 1, '  %6d  %10f  %10f\n', j, real ( y(j) ), imag ( y(j) ) );
  end

  s = 0.50 - 1.00 * i;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  The scalar multiplier is: ( %f  %f )\n', ...
    real ( s ), imag ( s ) );

  y = zaxpy ( n, s, x, 1, y, 1 );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  A * X + Y = \n' );
  fprintf ( 1, '\n' );
  for j = 1 : n
    fprintf ( 1, '  %6d  %10f  %10f\n', j, real ( y(j) ), imag ( y(j) ) );
  end

  return
end


function [volCc,dims] = mrAnatGetBrainVolume(brainMask)
%
% [volCc,dims] = mrAnatGetbrainVolume([brainMask=uigetfile])
%
% Returns the brain volume (in cubic centimeters) for the specified brain
% mask. Optionally also returns the left-right, anterior-posterior and
% superior-inferior dimensions (in centimeters) of the brain.
%
% If you don't have a brain mask, use mrAnatExtractBrain.
%
% 2008.08.14 RFD wrote it.
% 2008.09.09 RFD fixed x,y bug in dims- the first two dims were flipped.

if(~exist('brainMask','var')||isempty(brainMask))
    [f,p] = uigetfile({'*.nii.gz';'*.*'},'Select a brain mask NIFTI file...');
    if(isnumeric(f)), disp('User canceled.'); return; end
    brainMask = fullfile(p,f);
end

if(ischar(brainMask))
    % It's a nifti file
    brainMask = niftiRead(brainMask);
end

mm = brainMask.pixdim(1:3);
ccPerPixel = prod(mm)/1000;
volCc = numel(find(brainMask.data)) * ccPerPixel;

if(nargout>1)
    tmp = sum(brainMask.data,3);
    y = find(sum(tmp,1));
    y = [y(1) y(end)];
    x = find(sum(tmp,2));
    x = [x(1) x(end)];
    tmp = squeeze(sum(brainMask.data,1));
    z = find(sum(tmp,1));
    z = [z(1) z(end)];
    dims = [diff(x)*mm(1) diff(y)*mm(2) diff(z)*mm(3)];
    dims = dims./10;
end

return;

bd = '/biac3/wandell4/data/reading_longitude/dti_y1';
d = dir(fullfile(bd,'*04*'));
n = 0;
for(ii=1:numel(d))
    f = fullfile(bd,d(ii).name,'t1','t1_mask.nii.gz');
    if(exist(f,'file'))
        n = n+1;
        [volCc(n),dims(n,:)] = mrAnatGetBrainVolume(f);
        sc{n} = d(ii).name;
    end
end

[behData,colNames] = dtiGetBehavioralData(sc);

sexInd = strmatch('Sex (1=male)',colNames);
boys = behData(:,sexInd)==1;
fprintf('boys = %0.1fcc (%0.2f), girls = %0.1fcc (%0.2f)\n', mean(volCc(boys)), std(volCc(boys)), mean(volCc(~boys)), std(volCc(~boys)));

brInd = strmatch('Basic reading (W-J)',colNames);
necrosisControls = ~boys & behData(:,brInd)>=90;
mn = mean(volCc(necrosisControls));
sd = std(volCc(necrosisControls));

[sVol, sDims] = mrAnatGetBrainVolume('/biac1/wandell/data/radiationNecrosis/dti/al060406/t1/t1_mask.nii.gz');
% Compute the percentile:
[hcnt,hcent] = hist(volCc(necrosisControls),50);
pctile = sum(hcnt(find(sVol>hcent)))/sum(hcnt)*100;
fprintf('Controls: mean = %0.0fcc (%0.1f); S = %0.0fcc (%0.0f %%tile)\n', mn, sd, sVol, pctile);


% normaliseiris - performs normalisation of the iris region by
% unwraping the circular region into a rectangular block of
% constant dimensions.
%
% Usage:
% [polar_array, polar_noise] = normaliseiris(image, x_iris, y_iris, r_iris,...
% x_pupil, y_pupil, r_pupil,eyeimage_filename, radpixels, angulardiv)
%
% Arguments:
% image                 - the input eye image to extract iris data from
% x_iris                - the x coordinate of the circle defining the iris
%                         boundary
% y_iris                - the y coordinate of the circle defining the iris
%                         boundary
% r_iris                - the radius of the circle defining the iris
%                         boundary
% x_pupil               - the x coordinate of the circle defining the pupil
%                         boundary
% y_pupil               - the y coordinate of the circle defining the pupil
%                         boundary
% r_pupil               - the radius of the circle defining the pupil
%                         boundary
% eyeimage_filename     - original filename of the input eye image
% radpixels             - radial resolution, defines vertical dimension of
%                         normalised representation
% angulardiv            - angular resolution, defines horizontal dimension
%                         of normalised representation
%
% Output:
% polar_array
% polar_noise
%
% Author:
% Libor Masek
% masekl01@csse.uwa.edu.au
% School of Computer Science & Software Engineering
% The University of Western Australia
% November 2003

function [polar_array, polar_noise] = normaliseiris(image, x_iris, y_iris, r_iris,...
x_pupil, y_pupil, r_pupil,eyeimage_filename, radpixels, angulardiv, method)

global DIAGPATH

radiuspixels = radpixels + 2;
angledivisions = angulardiv-1;

r = 0:(radiuspixels-1);

theta = 0:2*pi/angledivisions:2*pi;

x_iris = double(x_iris);
y_iris = double(y_iris);
r_iris = double(r_iris);

x_pupil = double(x_pupil);
y_pupil = double(y_pupil);
r_pupil = double(r_pupil);

% calculate displacement of pupil center from the iris center
ox = x_pupil - x_iris;
oy = y_pupil - y_iris;

if ox <= 0
    sgn = -1;
elseif ox > 0
    sgn = 1;
end

if ox==0 && oy > 0

    sgn = 1;

end

r = double(r);
theta = double(theta);

a = ones(1,angledivisions+1)* (ox^2 + oy^2);

% need to do something for ox = 0
if ox == 0
    phi = pi/2;
else
    phi = atan(oy/ox);
end

b = sgn.*cos(pi - phi - theta);

% calculate radius around the iris as a function of the angle
r = (sqrt(a).*b) + ( sqrt( a.*(b.^2) - (a - (r_iris^2))));

r = r - r_pupil;

rmat = ones(1,radiuspixels)'*r;

rmat = rmat.* (ones(angledivisions+1,1)*[0:1/(radiuspixels-1):1])';
rmat = rmat + r_pupil;

% exclude values at the boundary of the pupil iris border, and the iris scelra border
% as these may not correspond to areas in the iris region and will introduce noise.
%
% ie don't take the outside rings as iris data.
rmat  = rmat(2:(radiuspixels-1), :);

% calculate cartesian location of each data point around the circular iris
% region
xcosmat = ones(radiuspixels-2,1)*cos(theta);
xsinmat = ones(radiuspixels-2,1)*sin(theta);

xo = rmat.*xcosmat;
yo = rmat.*xsinmat;

xo = x_pupil+xo;
yo = y_pupil-yo;

% extract intensity values into the normalised polar representation through
% interpolation
[x,y] = meshgrid(1:size(image,2),1:size(image,1));
polar_array = interp2(x,y,image,xo,yo);

% create noise array with location of NaNs in polar_array
polar_noise = zeros(size(polar_array));
coords = find(isnan(polar_array));
polar_noise(coords) = 1;

polar_array = double(polar_array)./255;

% start diagnostics, writing out eye image with rings overlayed

% get rid of outling points in order to write out the circular pattern
coords = find(xo > size(image,2));
xo(coords) = size(image,2);
coords = find(xo < 1);
xo(coords) = 1;

coords = find(yo > size(image,1));
yo(coords) = size(image,1);
coords = find(yo<1);
yo(coords) = 1;

xo = round(xo);
yo = round(yo);

xo = int32(xo);
yo = int32(yo);

ind1 = sub2ind(size(image),double(yo),double(xo));

image = uint8(image);

image(ind1) = 255;
%get pixel coords for circle around iris
[x,y] = circlecoords([x_iris,y_iris],r_iris,size(image));
ind2 = sub2ind(size(image),double(y),double(x));
%get pixel coords for circle around pupil
[xp,yp] = circlecoords([x_pupil,y_pupil],r_pupil,size(image));
ind1 = sub2ind(size(image),double(yp),double(xp));

image(ind2) = 255;
image(ind1) = 255;

% % write out rings overlaying original iris image
% w = cd;
% % cd(DIAGPATH);
%
% imwrite(image,[eyeimage_filename,'_method',num2str(method),'-normal.jpg'],'jpg');
%
% cd(w);
%
% % end diagnostics

%replace NaNs before performing feature encoding
coords = find(isnan(polar_array));
polar_array2 = polar_array;
polar_array2(coords) = 0.5;
avg = sum(sum(polar_array2)) / (size(polar_array,1)*size(polar_array,2));
polar_array(coords) = avg;


function model = gpsimMapUpdateG(model)

% GPSIMMAPUPDATEG Update the nonlinear transformation of f.
% FORMAT
% DESC updates the fields of model associated with the non-linear
% transformation of f, namely g, g_grad and g_grad2.
% ARG model : the model to be updated.
% ARG model : the model with the updated g representation.
%
% COPYRIGHT : Neil D. Lawrence, 2006
%
% MODIFIED : Pei Gao, 2008
%
% SEEALSO : gpsimMapFunctionalExpandParam, gpsimMapCreate

% SHEFFIELDML

% Remove mean function value from m (if mean function present).
if isfield(model, 'meanFunction') & ~isempty(model.meanFunction)
  f = model.f + modelOut(model.meanFunction, model.mapt);
else
  f = model.f;
end

% make sure f is a column vector
f = reshape(f, length(f), 1);

if model.ngParam == 0

switch model.nonLinearity
   case 'linear'
    model.g=f;        %linear case
    model.g_grad=ones(size(model.g));
    model.g_grad2=zeros(size(model.g));
    model.g_grad3=zeros(size(model.g));
    model.isConcave = true; % Is the log likelihood concave?
   case 'exp'
    model.g=exp(f);   %positive TF concentrations
%   model.gParam
%   if ~isempty(model.gParam)
%   model.ngParam = length(model.gParam(1,:));
%   model.dg = [];
%   model.dg2 = [];
%   end
    model.g_grad=model.g;
    model.g_grad2=model.g;
    model.g_grad3=model.g;
    model.isConcave = true;
   case 'quadratic'
    model.g=f.*f;
    model.g_grad=2*f;
    model.g_grad2=2*ones(size(f));
    model.isConcave = false;
   case 'negLogLogit'
    model.g=log(1+exp(f));   %positive TF concentrations
    model.g_grad=sigmoid(f);
    model.g_grad2=model.g_grad.*(1-model.g_grad);
    model.isConcave = true;
   case 'sigmoid'
    model.g = sigmoid(f);
    model.g_grad = model.g.*(1 - model.g);
    model.g_grad2 = model.g.*(1-model.g) - 2*model.g.*(model.g.*(1-model.g));
    model.isConcave = false;
   case 'repression'
    model.g = gpsimModelFunctions(model,'g');
    model.g_grad = gpsimModelFunctions(model,'grad');
    model.g_grad2 = gpsimModelFunctions(model,'grad2');
    model.g_grad3 = gpsimModelFunctions(model,'grad3');;
    model.isConcave = true; %% ??
   case 'activation'
    model.g = gpsimModelFunctions(model,'g');
    model.g_grad = gpsimModelFunctions(model,'grad');
    model.g_grad2 = gpsimModelFunctions(model,'grad2');
    model.g_grad3 = gpsimModelFunctions(model,'grad3');
    model.isConcave = true; %% ??
    if ~isempty(model.gParam)
      model.ngParam = length(model.gParam(1,:));
      model.dg = gpsimModelFunctions(model,'paramGrad');
      model.dg2 = gpsimModelFunctions(model,'paramGrad2');
    end
   otherwise
    error('Invalid non-linearity.')
end

else
  model.g = gpsimModelFunctions(model,'g');
  model.g_grad = gpsimModelFunctions(model,'grad');
  model.g_grad2 = gpsimModelFunctions(model,'grad2');
  model.g_grad3 = gpsimModelFunctions(model,'grad3');
  model.isConcave = true;
  model.dg = gpsimModelFunctions(model,'paramGrad');
  model.dggrad = gpsimModelFunctions(model,'paramGgrad');
  model.dggrad2 = gpsimModelFunctions(model,'paramGgrad2');
end


function test_bug3417

% WALLTIME 00:20:00
% MEM 3gb
% DEPENDENCY

% ... works fine on his computer, which has a 2012 version of FieldTrip and Matlab 2013a.
% But when we try to run either a later version of Fieldtrip (e.g. 2015) or a later version
% of Matlab (e.g. 2017b), we get the following bug:
%
% Error using findcluster (line 50)
% invalid dimension of spatdimneighbstructmat

% figure 4

%% SL - one sample t

load(dccnpath('/home/common/matlab/fieldtrip/data/test/bug3417.mat'))

freqs=14; % or 21
times=81;

cond1=permute(SL_Fig4,[3,1,2]);
cond1=cond1(:,1:freqs,:);

cond2=cond1;
cond2(:,:,:)=0;

data1.globspctrm=cond1;
data2.globspctrm=cond2;

[subj,~,freq] = size(data1.globspctrm);
nsubj = subj;

cfg.statistic = 'depsamplesT';
cfg.design = zeros(2,2*nsubj);
cfg.design(1,:)=[ones(1,nsubj) ones(1,nsubj)+1];
cfg.design(2,:)=[1:nsubj 1:nsubj];
cfg.ivar = 1;
cfg.uvar = 2;

data1.label = {'Positive'};
data2.label = {'Negative'};
data1.dimord = 'rpt_freq_time'; % does clustering in 2 dimensions (freq, time)
data2.dimord = 'rpt_freq_time';
data1.freq = [1:freqs];
data2.freq = [1:freqs];
data1.time =[1:times];
data2.time= [1:times];

% fix the invalid data structure, see ft_datatype_freq
data1.dimord = 'rpt_chan_freq_time';
data2.dimord = 'rpt_chan_freq_time';
data1.globspctrm = reshape(data1.globspctrm, [nsubj 1 freqs times]);
data2.globspctrm = reshape(data2.globspctrm, [nsubj 1 freqs times]);
data1.label = {'TheSame'};
data2.label = {'TheSame'};

cfg.parameter = 'globspctrm'; % 'avg', 'cohspctrm'
cfg.method = 'montecarlo'; %  'montecarlo',   'analytic' , 'stats', 'crossvalidate'

cfg.neighbours = [];
cfg.channel = 'all';
cfg.correctm = 'cluster'; % 'no', 'max', 'cluster', 'bonferroni', 'holm', 'hochberg', 'fdr' (default = 'no')

cfg.clusterstatistc = 'wcm'; % 'wcm', 'maxsum', 'maxsize'
cfg.clusterthreshold = 'parametric'; %  'parametric', 'nonparametric_individual', 'nonparametric_common'
cfg.numrandomization = 1000;
cfg.clusteralpha = 0.05;
cfg.tail = 0;

stats = ft_freqstatistics(cfg,data1,data2);

figure;

subplot(2,3,1)
tres=squeeze(mean(cond1,1));
imagesc(tres)
colorbar
title('Adult SL: Mean')
ylabel('Frequencies')
xlabel('Time')

subplot(2,3,4)
tres=squeeze(stats.stat)
imagesc(tres)
colorbar
title('SL: t matrix')
ylabel('Frequencies')
xlabel('Time')

subplot(2,3,5)
Positive_cluster=squeeze(stats.posclusterslabelmat);
Positive_cluster(Positive_cluster > 1) = 0; % keep just cluster 1
imagesc(Positive_cluster)
title(['Positive cluster: p=' num2str(stats.posclusters(1, 1).prob)])
colorbar
ylabel('Frequencies')
xlabel('Time')

subplot(2,3,6)
Negative_cluster=squeeze(stats.negclusterslabelmat);
Negative_cluster(Negative_cluster > 1) = 0; % keep just cluster 1
imagesc(Negative_cluster)
title(['Negative cluster: p=' num2str(stats.negclusters(1, 1).prob)])
colorbar
ylabel('Frequencies')
xlabel('Time')

%% JA - one sample t

load(dccnpath('/home/common/matlab/fieldtrip/data/test/bug3417.mat'))

freqs=14; % or 21
times=81;

cond1=permute(JA_Fig4,[3,1,2]);
cond1=cond1(:,1:freqs,:);

data1.globspctrm=cond1;
data2.globspctrm=cond2;

[subj,~,freq] = size(data1.globspctrm);
nsubj = subj;

cfg.statistic = 'depsamplesT';
cfg.design = zeros(2,2*nsubj);
cfg.design(1,:)=[ones(1,nsubj) ones(1,nsubj)+1];
cfg.design(2,:)=[1:nsubj 1:nsubj];
cfg.ivar = 1;
cfg.uvar = 2;

data1.label = {'Positive'};
data2.label = {'Negative'};
data1.dimord = 'rpt_freq_time'; % does clustering in 2 dimensions (freq, time)
data2.dimord = 'rpt_freq_time';
data1.freq = [1:freqs];
data2.freq = [1:freqs];
data1.time =[1:times];
data2.time= [1:times];

% fix the invalid data structure, see ft_datatype_freq
data1.dimord = 'rpt_chan_freq_time';
data2.dimord = 'rpt_chan_freq_time';
data1.globspctrm = reshape(data1.globspctrm, [nsubj 1 freqs times]);
data2.globspctrm = reshape(data2.globspctrm, [nsubj 1 freqs times]);
data1.label = {'TheSame'};
data2.label = {'TheSame'};

cfg.parameter = 'globspctrm'; % 'avg', 'cohspctrm'
cfg.method = 'montecarlo'; %  'montecarlo',   'analytic' , 'stats', 'crossvalidate'

cfg.neighbours = [];
cfg.channel = 'all';
cfg.correctm = 'cluster'; % 'no', 'max', 'cluster', 'bonferroni', 'holm', 'hochberg', 'fdr' (default = 'no')

cfg.clusterstatistc = 'wcm'; % 'wcm', 'maxsum', 'maxsize'
cfg.clusterthreshold = 'parametric'; %  'parametric', 'nonparametric_individual', 'nonparametric_common'
cfg.numrandomization = 1000;
cfg.clusteralpha = 0.05;
cfg.tail = 0;

stats = ft_freqstatistics(cfg,data1,data2)

figure;

subplot(2,3,1)
tres=squeeze(mean(cond1,1));
imagesc(tres)
colorbar
title('Adult SL: Mean')
ylabel('Frequencies')
xlabel('Time')

subplot(2,3,4)
tres=squeeze(stats.stat)
imagesc(tres)
colorbar
title('SL: t matrix')
ylabel('Frequencies')
xlabel('Time')

subplot(2,3,5)
Positive_cluster=squeeze(stats.posclusterslabelmat);
Positive_cluster(Positive_cluster > 1) = 0; % keep just cluster 1
imagesc(Positive_cluster)
title(['Positive cluster: p=' num2str(stats.posclusters(1, 1).prob)])
colorbar
ylabel('Frequencies')
xlabel('Time')

subplot(2,3,6)
Negative_cluster=squeeze(stats.negclusterslabelmat);
Negative_cluster(Negative_cluster > 1) = 0; % keep just cluster 1
imagesc(Negative_cluster)
title(['Negative cluster: p=' num2str(stats.negclusters(1, 1).prob)])
colorbar
ylabel('Frequencies')
xlabel('Time')

%% SJ vs. AJ

load(dccnpath('/home/common/matlab/fieldtrip/data/test/bug3417.mat'))

freqs=14; % or 21
times=81;

cond1=permute(SL_Fig4,[3,1,2]);
cond2=permute(JA_Fig4,[3,1,2]);

cond1=cond1(:,1:freqs,:);
cond2=cond2(:,1:freqs,:);

data1.globspctrm=cond1;
data2.globspctrm=cond2;

[subj,~,freq] = size(data1.globspctrm);
nsubj = subj;

cfg.statistic = 'depsamplesT';
cfg.design = zeros(2,2*nsubj);
cfg.design(1,:)=[ones(1,nsubj) ones(1,nsubj)+1];
cfg.design(2,:)=[1:nsubj 1:nsubj];
cfg.ivar = 1;
cfg.uvar = 2;

data1.label = {'Positive'};
data2.label = {'Negative'};
data1.dimord = 'rpt_freq_time'; % does clustering in 2 dimensions (freq, time)
data2.dimord = 'rpt_freq_time';
data1.freq = [1:freqs];
data2.freq = [1:freqs];
data1.time =[1:times];
data2.time= [1:times];

% fix the invalid data structure, see ft_datatype_freq
data1.dimord = 'rpt_chan_freq_time';
data2.dimord = 'rpt_chan_freq_time';
data1.globspctrm = reshape(data1.globspctrm, [nsubj 1 freqs times]);
data2.globspctrm = reshape(data2.globspctrm, [nsubj 1 freqs times]);
data1.label = {'TheSame'};
data2.label = {'TheSame'};

cfg.parameter = 'globspctrm'; % 'avg', 'cohspctrm'
cfg.method = 'montecarlo'; %  'montecarlo',   'analytic' , 'stats', 'crossvalidate'

cfg.neighbours = [];
cfg.channel = 'all';
cfg.correctm = 'cluster'; % 'no', 'max', 'cluster', 'bonferroni', 'holm', 'hochberg', 'fdr' (default = 'no')

cfg.clusterstatistc = 'wcm'; % 'wcm', 'maxsum', 'maxsize'
cfg.clusterthreshold = 'parametric'; %  'parametric', 'nonparametric_individual', 'nonparametric_common'
cfg.numrandomization = 1000;
cfg.clusteralpha = 0.05;
cfg.tail = 0;

stats = ft_freqstatistics(cfg,data1,data2)

figure;

subplot(2,3,1)
tres=squeeze(mean(cond1,1));
imagesc(tres)
colorbar
title('Adult SL: Mean')
ylabel('Frequencies')
xlabel('Time')

subplot(2,3,2)
tres=squeeze(mean(cond2,1));
imagesc(tres)
colorbar
title('Adult JA: Mean')
ylabel('Frequencies')
xlabel('Time')

subplot(2,3,4)
tres=squeeze(stats.stat)
imagesc(tres)
colorbar
title('SL vs. JA: t matrix')
ylabel('Frequencies')
xlabel('Time')

subplot(2,3,5)
Positive_cluster=squeeze(stats.posclusterslabelmat);
Positive_cluster(Positive_cluster > 1) = 0; % keep just cluster 1
imagesc(Positive_cluster)
title(['SL > JA cluster: p=' num2str(stats.posclusters(1, 1).prob)])
colorbar
ylabel('Frequencies')
xlabel('Time')

subplot(2,3,6)
Negative_cluster=squeeze(stats.negclusterslabelmat);
Negative_cluster(Negative_cluster > 1) = 0; % keep just cluster 1
imagesc(Negative_cluster)
title(['SL < JA cluster: p=' num2str(stats.negclusters(1, 1).prob)])
colorbar
ylabel('Frequencies')
xlabel('Time')


function plot_data_against_probabilities(sv,type,specs)

if nargin<3

    specs=[3,3];

    if nargin<2

        type='state';

    end

end

% myLimits=[-sqrt(eps),1+sqrt(eps)];

[f,the_regimes,endog,data,tex]=load_filters(sv);

switch type

    case 'state'

        probs=f.smoothed_state_probabilities;

    case 'regime'

        probs=f.smoothed_regime_probabilities;

    otherwise

    error('second input must be either "state" or "regime"')

end

r0=specs(1);

c0=specs(2);

all_regimes=fieldnames(probs);

all_regimes(strcmp(all_regimes,'const_1'))=[];

for iv=1:numel(endog)

    vn=endog{iv};

    utils.plot.multiple(@plotfuncr,all_regimes,...
        [vn,' against smoothed ',type,' probabilities'],r0,c0);

    if ~isempty(tex)

        [~,h]=sup_label(tex.(vn),'t');

        set(h,'fontsize',12)

    end

end

    function [mytex,leg]=plotfuncr(vname)

        dd=data.(vn)(probs.(vname).date_numbers);

        [AX,H1,H2]=plotyy(probs.(vname),dd,'linewidth',2);

        axis(AX,'tight')

        if isempty(tex)

            mytex=vname;

        else

            mytex=tex.(vname);

        end

        if strcmp(type,'regime')

            vname(1:numel('regime'))=[];

            vname=strrep(vname,'_','');

            mytex=sprintf('%s(%s)',mytex,the_regimes{str2double(vname)});

        end

        leg='';

    end

end


%% Grain Tutorial
%
%%
% The following script is a quick guide through the grain reconstruction
% capabilities of MTEX. It uses the same data set as in the corresponding
% publication
% <https://www.researchgate.net/publication/51806709_Grain_detection_from_2d_and_3d_EBSD_data-Specification_of_the_MTEX_algorithm
% Grain detection from 2d and 3d EBSD data>. Data courtesy of Daniel Rutte
% and Bret Hacker, Stanford.

mtexdata mylonite

% plot a phase map
plot(ebsd)

%%
% The phase map shows a multi-phase rock specimen with Andesina, Quartz,
% Biotite and Orthoclase. Lets restrict it to a smaller region of interest.
% The rectangle is defined by [xmin, ymin, xmax-xmin, ymax-ymin].

region = [19000 1500 4000 1500];
% overlay the selected region on the phase map
rectangle('position',region,'edgecolor','k','linewidth',2)

%%
% Now copy the EBSD data within the selected rectangle to a new variable

ebsd_region = ebsd(inpolygon(ebsd,region))

%% Grain Reconstruction
% Next we reconstruct the grains and grain boundaries in the region of
% interest, using a 15 degree orientation change threshold.

grains = calcGrains(ebsd_region,'angle',15*degree)

% plot a phase map of the region of interest
plot(ebsd_region)

% overlay the grain boundaries
hold on
plot(grains.boundary,'color','k','linewidth',1.5)
hold off

%%
% We may also visualize the different quarz orientations together with the
% grain boundaries.

% plot a phase map of three of the phases based on the grains data
plot(grains({'Andesina','Biotite','Orthoclase'}),'FaceAlpha',0.4)

hold on
% add the quarz orientations as ipf map based on EBSD data
plot(ebsd_region('Quartz'),ebsd_region('Quartz').orientations)

% plot grain boundaries so that those in the Quartz are shown
plot(grains.boundary,'color','black');
legend off
hold off

%%
% For the map created, most of the phases are coloured based on where they
% exist, while only the Quartz phase is colored according to the
% orientation. The quartz orientations are colured using the following ipf
% color key

close all
ipfKey = ipfColorKey(ebsd_region('Quartz'));
plot(ipfKey)

%%
% Alternatively, we may colorize each quarz grain according to its mean
% orientation.  Again, the other phases are colured based on where they
% exist.

plot(grains({'Andesina','Biotite','Orthoclase'}),'FaceAlpha',0.4)
hold on
plot(grains('Quartz'),grains('Quartz').meanOrientation)
legend off

%% Highlight specific boundaries
% We can create a phase map with certain grain boundaries highlighted.  In
% this case, we highlight where adjacent grains of Andesina and Orthoclase
% have a misorientation with rotational axis close to the c-axis.

close all
% copy all boundaries between Andesina Orthoclase to a new variable
AOboundary = grains.boundary('Andesina','Orthoclase');
% copy the misorientation angle of this boundary in radians to a new variable.
angle = AOboundary.misorientation.angle;

plot(grains,'FaceAlpha',0.4)
hold on
% highlight boundaries where the angle between the Andesina and Orthoclase phase is over 160 degrees
plot(AOboundary(angle>160*degree),'linewidth',2,'linecolor','red')
hold off

%%
% We can also represent the angular misorientation data between these two
% phases as a histogram.

figure;histogram(angle./degree)
xlabel('angle in degrees of boundary segment')
ylabel('count of boundary segments')
title('angular relationships between Andesina and Orthoclase')


function [kg] = slug2kg(slug)
% Convert units of mass from slugs to kilograms.
% Chad A. Greene 2012
kg = slug*14.5939;


clear; close all; clc;

n = 150;
xx = linspace(-4,4,n);
my_polynomial = [1, -2, -3, 4];
yy = polyval(my_polynomial, xx);

n_step = 150;

newVid = VideoWriter('pic1', 'MPEG-4'); % New
newVid.FrameRate = 30;
newVid.Quality = 100;
open(newVid);

figure('position',[490, 110, 900, 650],'color','w');
for i_step = 1:n_step
    yy2plot = (yy - zeros(1, n)) * i_step / n_step + zeros(1, n);
    plot2DPlane(-4,4,-6,6,false);
    hold on;

    if i_step == 1

        plot(xx, zeros(1,n),'linewidth',2);
        xlim([-3, 4])
        ylim([-6, 6])
        grid on;
        xlabel('$$x$$','interpreter','latex');
        ylabel('$$y = f(x)$$','interpreter','latex');
        title('$$y=f(x)=x^3-2x^2-3x+4$$','interpreter','latex')

        for i = 1:29 % 첫 장면에서 1.5초 대기할 수 있도록

            writeVideo(newVid, getframe(gcf))
        end
        drawnow;
        cla;
    end
    plot2DPlane(-4,4,-6,6,false);

    plot(xx, yy2plot,'linewidth',2);
    xlim([-3, 4])
    ylim([-6, 6])
    grid on;
    xlabel('$$x$$','interpreter','latex');
    ylabel('$$y = f(x)$$','interpreter','latex');
    title('$$y=f(x)=x^3-2x^2-3x+4$$','interpreter','latex')
    drawnow;

    writeVideo(newVid, getframe(gcf))

    if i_step < n_step
        cla;
    end
end

for i = 1:30 % 마지막 장면에서 1.5초 더 대기할 수 있도록
    writeVideo(newVid, getframe(gcf))
end

close(newVid)


function det = sgbdi ( abd, lda, n, ml, mu, ipvt )

%*****************************************************************************80
%
%% SGBDI computes the determinant of a band matrix factored by SGBCO or SGBFA.
%
%  Discussion:
%
%    If the inverse is needed, use SGBSL N times.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 November 2006
%
%  Author:
%
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Dongarra, Moler, Bunch and Stewart,
%    LINPACK User's Guide,
%    SIAM, (Society for Industrial and Applied Mathematics),
%    3600 University City Science Center,
%    Philadelphia, PA, 19104-2688.
%    ISBN 0-89871-172-X
%
%  Parameters:
%
%    Input, real ABD(LDA,N), the output from SGBCO or SGBFA.
%
%    Input, integer LDA, the leading dimension of the array ABD.
%
%    Input, integer N, the order of the matrix.
%
%    Input, integer ML, MU, the number of diagonals below and above the
%    main diagonal.  0 <= ML < N, 0 <= MU < N.
%
%    Input, integer IPVT(N), the pivot vector from SGBCO or SGBFA.
%
%    Output, real DET(2), the determinant of the original matrix.
%      determinant = DET(1) * 10.0**DET(2)
%    with  1.0 <= abs ( DET(1) ) < 10.0 or DET(1) = 0.0.
%
  ten = 10.0;

  m = ml + mu + 1;
  det(1) = 1.0;
  det(2) = 0.0;

  for i = 1 : n

    if ( ipvt(i) ~= i )
      det(1) = -det(1);
    end

    det(1) = abd(m,i) * det(1);

    if ( det(1) == 0.0 )
      return
    end

    while ( abs ( det(1) ) < 1.0 )
      det(1) = ten * det(1);
      det(2) = det(2) - 1.0;
    end

    while ( ten <= abs ( det(1) ) )
      det(1) = det(1) / ten;
      det(2) = det(2) + 1.0;
    end

  end

  return
end


function [circle, labels] = imEnclosingCircle(img, varargin)
% Minimal enclosing circle of a region.
%
%   CIRC = imEnclosingCircle(IMG)
%   Computes the minimal enclosing circle around a binary region, or
%   around each labeled region in the input image.
%
%
%   CIRC = imEnclosingCircle(IMG, SPACING);
%   CIRC = imEnclosingCircle(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].
%
%   CIRC = imEnclosingCircle(..., LABELS)
%   Specify the labels for which the enclosing circle needs to be computed.
%   The result is a N-by-3 array with as many rows as the number of labels.
%
%
%   Example
%   % Draw a commplex region together with its enclosing circle
%     img = imread('circles.png');
%     imshow(img); hold on;
%     circ = imEnclosingCircle(img);
%     drawCircle(circ)
%
%   % Compute and display the equivalent ellipses of several regions
%     img = imread('rice.png');
%     img2 = img - imopen(img, ones(30, 30));
%     lbl = bwlabel(img2 > 50, 4);
%     circles = imEnclosingCircle(lbl);
%     imshow(img); hold on;
%     drawCircle(circles, 'linewidth', 2, 'color', 'g');
%
%   See also
%     drawCircle, enclosingCircle
%     imInscribedCircle, imInertiaEllipse, imInertiaEllipse
%
%   References
%   Based on a file from Yazan Ahed (yash78@gmail.com)
%   which was rewritten from a Java applet by Shripad Thite:
%   http://heyoka.cs.uiuc.edu/~thite/mincircle/
%

% ------
% Author: David Legland
% e-mail: david.legland@inrae.fr
% Created: 2012-07-08,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2012 INRA - Cepia Software Platform.

%% Process input arguments

% 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

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

%% Initialisations

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

% allocate memory for result
circle = zeros(nLabels, 3);

%% Iterate over labels

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

    % works on convex hull (faster), or on original points if the hull
    % could not be computed
    try
        inds = convhull(x, y);
        pts = [x(inds) y(inds)];
    catch %#ok<CTCH>
        pts = [x y];
    end

    % works on pixel corners rather than on pixel centers
    x = pts(:,1);
    y = pts(:,2);
    pts = [x-0.5 y-0.5 ; x+0.5 y-0.5 ; x-0.5 y+0.5 ; x+0.5 y+0.5];

    % convex hull again, to remove duplicates
    inds = convhull(pts(:,1), pts(:,2));
    pts = pts(inds, :);

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

    circle(i,:) = recurseCircle(size(pts, 1), pts, 1, zeros(3, 2));
end

function circ = recurseCircle(n, p, m, b)
%    n: number of points given
%    m: an argument used by the function. Always use 1 for m.
%    bnry: an argument (3x2 array) used by the function to set the points that
%          determines the circle boundary. You have to be careful when choosing this
%          array's values. I think the values should be somewhere outside your points
%          boundary. For my case, for example, I know the (x,y) I have will be something
%          in between (-5,-5) and (5,5), so I use bnry as:
%                       [-10 -10
%                        -10 -10
%                        -10 -10]

if m == 4
    circ = createCircle(b(1,:), b(2,:), b(3,:));
    return;
end

circ = [Inf Inf 0];

if m == 2
    circ = [b(1,1:2) 0];
elseif m == 3
    c = (b(1,:) + b(2,:))/2;
    circ = [c distancePoints(b(1,:), c)];
end

for i = 1:n
    if distancePoints(p(i,:), circ(1:2)) > circ(3)
        if sum(b(:,1)==p(i,1) & b(:,2)==p(i,2)) == 0
            b(m,:) = p(i,:);
            circ = recurseCircle(i, p, m+1, b);
        end
    end
end

function dist = distancePoints(p1, p2)

dist = hypot(p2(:,1) - p1(:,1), p2(:,2) - p1(:,2));


function [minM, maxM] = getMinMaxIM(IM,NHOOD)
% function [minM, maxM] = getMinMaxIM(IM,NHOOD)
%
% This function returns min and max for the local neighborhood NHOOD
%
% APA, 04/26/2012

% ---- No reflection required if our NHOOD is symmetric ------

% % NHOOD is reflected across its origin in order for IMDILATE
% % to return the local maxima of I in NHOOD if it is asymmetric. A symmetric NHOOD
% % is naturally unaffected by this reflection.
% reflectH = NHOOD(:);
% reflectH = flipud(reflectH);
% reflectH = reshape(reflectH, size(NHOOD));
% maxMat = imdilate(IM,reflectH);

maxM = imdilate(IM,NHOOD);

% IMERODE returns the local minima of IM in NHOOD.
minM = imerode(IM,NHOOD);

end


function [Xgp Ygp]=projectToGroundPlane(Xi, Yi, sceneInfo)
%
% (C) Anton Andriyenko, 2012
%
% The code may be used free of charge for non-commercial and
% educational purposes, the only requirement is that this text is
% preserved within the derivative work. For any other purpose you
% must contact the authors for permission. This code may not be
% redistributed without written permission from the authors.

[F N]=size(Xi);
Xgp=zeros(size(Xi));
Ygp=zeros(size(Xi));

for t=1:F
    extar=find(Xi(t,:));
    for id=extar
        [Xgp(t,id) Ygp(t,id) zw]=imageToWorld(Xi(t,id), Yi(t,id), sceneInfo.camPar);
    end
end

end


function mpe = find_mpe(engine, local_evidence)
% FIND_MPE Find the most probable explanation of the data
% function mpe = find_mpe(engine, local_evidence
%
% local_evidence{i}(j) = Pr(observation at node i | S(i)=j)
%
% This finds the marginally most likely value for each hidden node.
% It may give inconsistent results if there are ties.

[mpe, niter] = bp_mpe_mrf2(engine.mrf2.adj_mat, engine.mrf2.pot, local_evidence, ...
			   'max_iter', engine.max_iter, 'momentum', engine.momentum, ...
			   'tol', engine.tol);


function Fitness = CalFitness(C,Population)
% Calculate the fitness of each solution in terms of a single level

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

    PopObj = Population.objs;
    PopCon = Population.cons;
    if any(isnan(PopObj(:,1)))  % Lower level
        PopObj = PopObj(:,2);
        PopCon = PopCon(:,C+1:end);
    else                        % Upper level
        PopObj = PopObj(:,1);
        PopCon = PopCon(:,1:C);
    end
    if isempty(PopCon)
        PopCon = zeros(size(PopObj,1),1);
    else
        PopCon = sum(max(0,PopCon),2);
    end
    Feasible = PopCon <= 0;
    Fitness  = Feasible.*PopObj + ~Feasible.*(PopCon+1e10);
end


function best_weights = GetBestMixingWeightForHarmonics(standard_deviation_list)
% Best mixing of instantaneous frequencies with common mean
% and built-in constraint (safeguard version designed for harmonics information mixing)
%
% best_weights = GetBestMixingWeightForHarmonics(sdListOrg)
%
% Input argument
%   standard_deviation_list    : standard deviation of each variable
%
% Output argument
%   best_weights   : best set of weights for mixing random variables
%
% Note
%   This mixing consists of heuristics. Re-design is needed.

% Copyright 2016 Google Inc. All Rights Reserved.
% Author: hidekik@google.com (Hideki Kawahara)

original_list_length = length(standard_deviation_list);
safe_list = (1:original_list_length)';
safe_list = safe_list(standard_deviation_list > 0 & ...
  standard_deviation_list < 100 * min(abs(standard_deviation_list)));
sdLsafe_SD_list = standard_deviation_list(safe_list);
n_of_safe_SD = length(sdLsafe_SD_list);
if n_of_safe_SD > 0
  H = ones(n_of_safe_SD-1, n_of_safe_SD-1) * sdLsafe_SD_list(n_of_safe_SD) ^ 2;
  H = H + diag(sdLsafe_SD_list(1:n_of_safe_SD - 1) .^ 2);
  v = ones(n_of_safe_SD - 1, 1) * sdLsafe_SD_list(n_of_safe_SD) ^ 2;
  a = H \ v; % revised 23/May/2016 from inv(H) * v
  if sum(a) > 1
    a = a / sum(a);
  end;
  w = [a; 1 - sum(a)];
  best_weights = zeros(original_list_length, 1);
  best_weights(safe_list) = w;
else
  best_weights = zeros(original_list_length, 1);
  best_weights(1) = 1;
end;
end


function optodedistance = ft_nirs_optodedistance(datain)
% FT_NIRS_OPTODEDISTANCE computes distances between pairs of optodes.
%
% Use as
%   distance = ft_nirs_optodedistance(indata)
% where indata is nirs data.
%
% See also FT_NIRS_REFERENCECHANNELSUBTRACTION

% You are using the FieldTrip NIRS toolbox developed and maintained by
% Artinis Medical Systems (http://www.artinis.com). For more information
% on FieldTrip, see http://www.fieldtriptoolbox.org
%
% This work is licensed under a Creative Commons Attribution-ShareAlike 4.0
% International License. To view a copy of this license, visit
% http://creativecommons.org/licenses/by-sa/4.0/ or send a letter to
% Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
%
% Creative Commons Attribution-ShareAlike 4.0 International License:
% -----------------------------------
% You are free to:
%
%     Share - copy and redistribute the material in any medium or format
%     Adapt - remix, transform, and build upon the material
%     for any purpose, even commercially.
%
%     The licensor cannot revoke these freedoms as long as you follow the
%     license terms.
%
% Under the following terms:
%
%     Attribution - You must give appropriate credit, provide a link to
%                    the license, and indicate if changes were made. You
%                    may do so in any reasonable manner, but not in any way
%                    that suggests the licensor endorses you or your use.
%
%     ShareAlike - If you remix, transform, or build upon the material,
%                   you must distribute your contributions under the same
%                   license as the original.
%
%     No additional restrictions - You may not apply legal terms or
%                                   technological measures that legally
%                                   restrict others from doing anything the
%                                   license permits.
%
% -----------------------------------
%
% This toolbox is not to be used for medical or clinical purposes.
%
% Copyright (c) 2016 by Artinis Medical Systems.
% Contact: askforinfo@artinis.com
%
% Main programmer:
% Marc van Wanrooij, DCN, http://www.neural-code.com
% Jörn M. Horschig, Artinis Medical Systems BV, http://www.artinis.com
% $Id$

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the initial part deals with parsing the input options and data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ensure that the input data is raw NIRS-data, this will also do
% backward-compatibility conversions of old data that for example was
% read from an old *.mat file
datain = ft_checkdata(datain, 'datatype', 'raw', 'senstype', 'nirs');

%% Relevant parameters
label	= datain.label; % transformed channel label, combination Receiver and Transmitter
olabel	= datain.opto.optolabel; % optode label
opos	= datain.opto.optopos; % optode positions

npos	= numel(label);

xf		= opos(:,1);
yf		= opos(:,2);

%% determine distance between Receiver and Transmitter optodes
optodedistance				= NaN(npos,1);

for posIdx=1:npos
  str	= label{posIdx};
  c = textscan(str, '%s%s%s', 'Delimiter', {'-', ' '});

  chanRstr = c{1};
  chanTstr = c{2};

  idxR		= match_str(olabel,chanRstr);
  idxT		= match_str(olabel,chanTstr);

  optodedistance(posIdx)	= sqrt( (xf(idxR)-xf(idxT)).^2+(yf(idxR)-yf(idxT)).^2 ); % Pythagorean theorem
end


function [dist,proj] = ref_3d_projection(ref,EAST,NORTH,h)

% SYNTAX:
%   [dist,proj] = ref_3d_projection(ref,EAST,NORTH,h)
%
% INPUT:
%   ref = reference path (X,Y,Z coordinates of the vertices)
%   EAST = estimated trajectory in UTM coordinates (EAST)
%   NORTH = estimated trajectory in UTM coordinates (NORTH)
%   h = ellipsoid height
%
% OUTPUT:
%   dist = 3D distance of each estimated point from the reference
%   proj = projected trajectory
%
% DESCRIPTION:
%   3D projection on a reference path.
%   At the moment working only for adjacency matrix as in the following
%   example:
%
%   adj_mat = [ 0 1 0 0 0 1
%               1 0 1 0 0 0
%               0 1 0 1 0 0
%               0 0 1 0 1 0
%               0 0 0 1 0 1
%               1 0 0 0 1 0 ];

%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:
%  Contributors:     ...
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   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/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

%close the path by connecting the first and the last points
ref = [ref;ref(1,:)];

%computation of the angular coefficients
ax = ref(2:end,1) - ref(1:end-1,1);
ay = ref(2:end,2) - ref(1:end-1,2);
az = ref(2:end,3) - ref(1:end-1,3);

%normalization on the segment distance
ad = sqrt(ax.^2 + ay.^2 + az.^2);
ax = ax ./ ad;
ay = ay ./ ad;
az = az ./ ad;

%offset of the curvilinear coordinate
s0 = [0; cumsum(ad)];

for j = 1 : length(EAST)
    pos_R(1) = EAST(j);
    pos_R(2) = NORTH(j);
    pos_R(3) = h(j);

    d0 = sqrt((pos_R(1) - ref(:,1)).^2 + ...
              (pos_R(2) - ref(:,2)).^2 + ...
              (pos_R(3) - ref(:,3)).^2);

    [dmin0 i0] = min(d0);

    %projection on the reference path
    bx = pos_R(1) - ref(1:end-1,1) + ax.*s0(1:end-1);
    by = pos_R(2) - ref(1:end-1,2) + ay.*s0(1:end-1);
    bz = pos_R(3) - ref(1:end-1,3) + az.*s0(1:end-1);

    s_R = (ax.*bx + ay.*by + az.*bz) ./ (ax.^2 + ay.^2 + az.^2);

    pos_R_proj(:,1) = ref(1:end-1,1) + ax .* (s_R - s0(1:end-1));
    pos_R_proj(:,2) = ref(1:end-1,2) + ay .* (s_R - s0(1:end-1));
    pos_R_proj(:,3) = ref(1:end-1,3) + az .* (s_R - s0(1:end-1));

    %computation of the minimum distance
    d = sqrt((pos_R(1) - pos_R_proj(:,1)).^2 + ...
        (pos_R(2) - pos_R_proj(:,2)).^2 + ...
        (pos_R(3) - pos_R_proj(:,3)).^2);

    [dmin i] = min(d);

    %position in cartesian coordinates
    while (dmin < dmin0) & ((pos_R_proj(i,1) < min(ref(i,1),ref(i+1,1))) | (pos_R_proj(i,1) > max(ref(i,1),ref(i+1,1))) | ...
            (pos_R_proj(i,2) < min(ref(i,2),ref(i+1,2))) | (pos_R_proj(i,2) > max(ref(i,2),ref(i+1,2))) | ...
            (pos_R_proj(i,3) < min(ref(i,3),ref(i+1,3))) | (pos_R_proj(i,3) > max(ref(i,3),ref(i+1,3))))

        d(i) = 9e99;
        [dmin i] = min(d);

    end

    if dmin0 < dmin
        dist(j,1) = dmin0;

        proj(j,1) = ref(i0,1);
        proj(j,2) = ref(i0,2);
        proj(j,3) = ref(i0,3);

    else
        dist(j,1) = dmin;

        proj(j,1) = pos_R_proj(i,1);
        proj(j,2) = pos_R_proj(i,2);
        proj(j,3) = pos_R_proj(i,3);
    end
end


%
% Overview: Test ECGBeatFitter program for mean ECG beat extraction and
% parameter optimization. The script does the following:
% 1. Reads the ECG data in the sample_ecg_datam file in the 'Physionet-Cardiovascular-Signal-Toolbox/Tools/ECG_Analysis_Tools/MV/testdata/' subfolder.
% 2. Estimates the average ECG beat for the first fifteen seconds.
% 3. The ECGBeatFitter algorithm is used to estimate the parameters of
% Gaussian functions that accurately estimate the shape of the average ECG
% beat. The number of Gaussians is specified by selecting points along the
% average beat in the ECGBeatFitter GUI.
% 4. The output of the script are the parameters for the Gaussians stored in the following variables:
%
%   ai: contains the amplitudes of the Gaussians.
%   bi: contains the standard deviations of the Gaussians.
%   tetai: contains the phase of each Gaussian function.
%
% 5. These parameters may be estimated for each of the x, y and z
% components of a VCG and substituted into the generate_resp_modulated_ecg
% function in the Physionet-Cardiovascular-Signal-Toolbox to generate an artificial
% VCG with a morphology similar to VCG used for estimating the parameters.
% The Dower transform may be applied to generate 12 lead ECG from the VCG.
%
%
% ORIGINAL SOURCE AND AUTHORS:
% Open Source ECG Toolbox, version 1.0, November 2006
% Released under the GNU General Public License
% Copyright (C) 2006  Reza Sameni
% Sharif University of Technology, Tehran, Iran -- LIS-INPG, Grenoble, France
% reza.sameni@gmail.com
% editted by Ismail Sadiq on 11/29/2020.

% This program is free software; you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by the
% Free Software Foundation; either version 2 of the License, or (at your
% option) any later version.
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
% Public License for more details. You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

clc
clear
close all;

% Load test ecg data
addpath(genpath('../../../../../PhysioNet-Cardiovascular-Signal-Toolbox-master/')); % add all dependencies from cardiovascular signal toolbox
sig = load('./testdata/mvm/sample_ecg_datam');
siginfo = readheader('./testdata/mvm/sample_ecg_datam.hea');
fs = siginfo.freq;
ecg = (sig.val - siginfo.adczero)./siginfo.gain; data=ecg(1:15000);% Adjust signal according to gain and dc offset
clear siginfo sig ecg;

t = (0:length(data)-1)/fs;

f = 1;                                          % approximate R-peak frequency

bsline = LPFilter(data,.7/fs);                  % baseline wander removal (may be replaced by other approaches)
%bsline = BaseLineKF(data,.5/fs);                % baseline wander removal (may be replaced by other approaches)

data1 = data-bsline;

%//////////////////////////////////////////////////////////////////////////
% Making the data noisy
SNR = 20;
SignalPower = mean(data1.^2);
NoisePower = SignalPower / 10^(SNR/10);
x = data1 + sqrt(NoisePower)*randn(size(data1));
%//////////////////////////////////////////////////////////////////////////

peaks = PeakDetection(x,f/fs);                  % peak detection

[phase, phasepos] = PhaseCalculation(peaks);     % phase calculation

teta = 0;                                       % desired phase shift
pphase = PhaseShifting(phase,teta);             % phase shifting

bins = round(fs/3);                                     % number of phase bins
[ECGmean,ECGsd,meanphase] = MeanECGExtraction(x,pphase,bins,1); % mean ECG extraction

OptimalParams = ECGBeatFitter(ECGmean,ECGsd,meanphase);               % ECG beat fitter GUI

% display the optimal parameters
L = length(OptimalParams)/3;
ai = OptimalParams(1:L)
bi = OptimalParams(L+1:2*L)
tetai = OptimalParams(2*L+1:3*L)


function out = sampleInSeconds(stimList,ISI,varargin)
% out = sampleInSeconds(stimList,ISI,varargin)
% input: stimList, output: stimlist sampled in .1 seconds
%                          OR sampled at your specified frequency

scale = ceil(ISI*10);

if nargin > 2
    scale = round(ISI/varargin{1});
end

numstim = size(stimList,1);

out = zeros(numstim*scale,1);

for i = 0:numstim-1

    out(i*scale+1,1) = stimList(i+1,1);

end

return


%  Figure 7.21      Feedback Control of Dynamic Systems, 5e
%                        Franklin, Powell, Emami
%
% Script to generate fig. 7.21.
clf;
num=1;
den=[1 0 0 0 0];
rlocus(num,den);
title('Fig. 7.21 Symmetric root locus for satellite system')
grid;


function calpak_test337 ( )

%*****************************************************************************80
%
%% CALPAK_TEST337 tests MONTH_EG_LUNAR.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 March 2013
%
%  Author:
%
%    John Burkardt
%
  n_test = 2;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALPAK_TEST337\n' );
  fprintf ( 1, '  For the Egyptian Lunar calendar,\n' );
  fprintf ( 1, '  MONTH_LENGTH_EG_LUNAR returns month lengths.\n' );

  y_test(1) = 1;
  y_test(2) = 2;

  for i_test = 1 : n_test

    y = y_test(i_test);
    sy = y_to_s_eg_lunar ( y );
    months = year_length_months_eg_lunar ( y );
    days = year_length_eg_lunar ( y );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  %d\n', y );
    fprintf ( 1, '  %s\n', sy );
    fprintf ( 1, '  Year length in months = %d\n', months );
    fprintf ( 1, '  Year length in days = %d\n', days );
    fprintf ( 1, '\n' );

    for m = 1 : months
      month_name = month_to_month_name_eg_lunar ( m );
      fprintf ( 1, '  %10s  %2d\n', month_name, month_length_eg_lunar ( y, m ) );
    end

  end

  return
end


function c = horzcat(varargin)
% function C=horzcat(A,B);
%
% DESCRIPTION
%   Horizontal concatenation of polynomial objects.
%
% INPUTS
%   A,B: polynomials
%
% OUTPUTS
%   C:  horizontal concatenation of input matrices.
%
% SYNTAX
%   [A B]
%       Horizontal concatenation of polynomial matrices A and B.
%       A and B must have the same number of rows.
%   [A1 A2 A3 ...]
%       Horizontal concatenation of several polynomial matrices.
%   C = horzcat(A1,A2,...);
%       Function-call form of horizontal concatenation.
%
% See also vertcat

% 6/8/2002: PJS  Initial Coding

if nargin==1
    c = varargin{1};
else
    % Promote a to polynomial
    a = polynomial(varargin{1});
    [nra,nca] = size(a);

    % Promote b to polynomial
    b = polynomial(varargin{2});
    [nrb,ncb] = size(b);

    if isempty(b);
        c = a;
    elseif isempty(a);
        c = b;
    elseif nra==nrb
        % Get Dimensions
        nta = size(a.degmat,1);
        nva = length(a.varname);
        ntb = size(b.degmat,1);
        nvb = length(b.varname);

        if nva==0 && nvb==0
            % Combine constant terms
            ar = combine(a);
            coef1 = reshape(ar.coefficient,[nra nca]);
            br = combine(b);
            coef2 = reshape(br.coefficient,[nrb ncb]);

            % Stack Coefficients and Form Polynomial
            coefficient = [coef1 coef2];
            c = polynomial(coefficient);
        else
            % Form Degmat, Varname, and Matdim
            adeg = a.degmat;
            bdeg = b.degmat;
            degmat = blkdiag(adeg,bdeg);
            varname = [a.varname(:); b.varname(:)];
            matdim = [nra nca+ncb];

            % Stack up Coefficients
            coef1 = [a.coefficient zeros(nta,nra*ncb)];
            coef2 = [zeros(ntb,nrb*nca) b.coefficient];
            coefficient = [coef1; coef2];

            % Form Polynomial and combine terms
            chkval = 0; % skip validity check
            c = polynomial(coefficient,degmat,varname,matdim,chkval);
            c = combine(c);
        end
    else
        error('All columns must have the same row dimension')
    end

    if nargin>2
        c = horzcat(c,varargin{3:end});
    end
end


function varargout = lap(varargin)
%LAP   Laplacian of a CHEBFUN2.
%   L = LAP(F) returns a CHEBFUN2 representing the Laplacian of F.
%
%   This is shorthand for LAPLACIAN(F).
%
% See also CHEBFUN2/LAPLACIAN.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% Call SEPARABLEAPPROX/LAP:
[varargout{1:nargout}] = lap@separableApprox(varargin{:});

end


 function ob = Ginterp1(mask, varargin)
%function ob = Ginterp1(mask, options)
%|
%| Construct Ginterp1 object for 1D image registration.
%| This method does not have an adjoint.
%|
%| See Ginterp1_test() below for example usage.
%|
%| in
%|	mask	size(image)	logical array of object support.
%|
%| options
%|	'interp1_arg'	{}	arguments to interp1 for 'forward' operation
%|
%| out
%|	ob [nd np]	np = sum(mask(:)), so it is already "masked"
%|			nd = numel(interp1_arg{2})
%|
%| Copyright 2013-12-05, Jeff Fessler, University of Michigan

if nargin == 1 && streq(mask, 'test'), Ginterp1_test, return, end
if nargin < 1, ir_usage, end

arg.mask = mask;

% option defaults
arg.interp1_x = [];
arg.interp1_xq = [];
arg.interp1_arg = {'linear', 0};

% options specified by name/value pairs
arg = vararg_pair(arg, varargin);

if isempty(arg.interp1_x) || isempty(arg.interp1_xq)
	fail '"interp1_arg" and "interp1_x" required'
end

arg.ndim = ndims(mask);
if arg.ndim == 2 && size(mask,2) == 1
	arg.ndim = 1;
else
	fail 'only 1D mask allowed'
end

if streq(arg.interp1_arg{1}, 'linear')
	abs_arg = {'abs', @(ob) ob}; % linear interpolation uses nonnegative coefficients
else
	abs_arg = {}; % unknown
end

arg.fun_forw = @(arg, x) ...
	interp1(arg.interp1_x, x, arg.interp1_xq, arg.interp1_arg{:});
arg.fun_back = @(arg, y) fail('interp adjoint not done');

% build object
idim = size(mask);
if numel(idim) == 2 && idim(2) == 1
	idim = idim(1); % 1d
end
ob = fatrix2('mask', mask, 'arg', arg, ...
	'idim', idim, 'odim', numel(arg.interp1_xq), ...
	abs_arg{:}, 'forw', arg.fun_forw, 'back', arg.fun_back);

% Ginterp1_test()
function Ginterp1_test

nx = 8;
mask = true(nx,1);
mask(1) = false;
xq = linspace(0,nx+1, 101);

A = Ginterp1(mask, 'interp1_x', 1:nx, 'interp1_xq', xq);

if 0 % todo
	fatrix2_tests(A, 'complex', 0, 'halt', 0, ...
		'check1', false, 'full', false) % because of bad adjoint
%	test_adjoint(A, 'complex', 1);
else
	warn 'adjoint not tested'
end

im plc 1 2
Af = full(A);
im(1, Af'), axis xy, axis normal

im subplot 2
x = [1:nx]' .* mask;
y = A * x;

plot(1:nx, x, 'o', xq, y, '.-')


function outpoints = mni2tal(inpoints)
% Converts coordinates from MNI brain to best guess
% for equivalent Talairach coordinates
% FORMAT outpoints = mni2tal(inpoints)
% Where inpoints is N by 3 or 3 by N matrix of coordinates
%  (N being the number of points)
% outpoints is the coordinate matrix with Talairach points
% Matthew Brett 10/8/99

dimdim = find(size(inpoints) == 3);
if isempty(dimdim)
  ft_error('input must be a N by 3 or 3 by N matrix')
end
if dimdim == 2
  inpoints = inpoints';
end

% Transformation matrices, different zooms above/below AC
upT = [
    0.9900    0.0000    0.0000    0.0000
    0.0000    0.9688    0.0460    0.0000
    0.0000   -0.0485    0.9189    0.0000
    0.0000    0.0000    0.0000    1.0000
      ];

downT = [
    0.9900    0.0000    0.0000    0.0000
    0.0000    0.9688    0.0420    0.0000
    0.0000   -0.0485    0.8390    0.0000
    0.0000    0.0000    0.0000    1.0000
    ];

tmp = inpoints(3,:)<0;  % 1 if below AC
inpoints = [inpoints; ones(1, size(inpoints, 2))];
inpoints(:, tmp) = downT * inpoints(:, tmp);
inpoints(:, ~tmp) = upT * inpoints(:, ~tmp);
outpoints = inpoints(1:3, :);
if dimdim == 2
  outpoints = outpoints';
end


function  dC=dervar3(C,n)

%DERVAR3 for core rotations
%
%function dC=dervar3(C,n)
%
%This function determines the derivative of the nth mode of
%the core rotation expression for the 3-way case w.r.t.
%maximization of the variance of the core
%
%This version has been optimized for speed, see below for a
%more easy to read scheme.

% Copyright (C) 1995-2006  Rasmus Bro & Claus Andersson
% Copenhagen University, DK-1958 Frederiksberg, Denmark, rb@life.ku.dk
%
% This program is free software; you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation; either version 2 of the License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
% You should have received a copy of the GNU General Public License along with
% this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
% Street, Fifth Floor, Boston, MA  02110-1301, USA.

% $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $

W = size(C);
C = reshape(C,W(1),prod(W(2:end)));

mc = mean(mean(C.^2));
E = (C.^2 - mc).*C;
dC = zeros(W(n),W(n));
W1 = W(1);
W2 = W(2);
W3 = W(3);

if n==1,
   for a=1:W1,
      for b=1:W1,

         dc=0;
         for j=1:W3,
            tmp_0 = W2*(j-1);
            idxja = [1:W2] + tmp_0;
            dc = dc + sum(C(b,idxja).*E(a,idxja));
         end;

         dC(a,b) = dc;
      end;
   end;
end;

if n==2,
   for a=1:W2,
      for b=1:W2,

         dc=0;
         for j=1:W3,
            tmp_1 = W2*(j-1);
            idxja = a + tmp_1;
            idxjb = b + tmp_1;
            dc = dc + sum(C(:,idxjb).*E(:,idxja));
         end;

         dC(a,b) = dc;
      end;
   end;
end;

if n==3,
   for a=1:W3,
      tmp_2 = W2*(a-1);
      for b=1:W3,
         tmp_3 = W2*(b-1);

         dc=0;
         for j=1:W2,
            idxja = j + tmp_2;
            idxjb = j + tmp_3;
            dc = dc + sum(C(:,idxjb).*E(:,idxja));
         end;

         dC(a,b) = dc;
      end;
   end;
end;

%----------------------------------------------------------------------------------------
%function  dC=dervar3(C,W,n)
%
%%function dC=dervar3(C,W,n)
%
%%This function determines the derivative of the nth mode of
%%the core rotation expression for the 3-way case w.r.t.
%%maximization of the variance of the core
%
%mc=mean(mean(C.^2));
%dC=zeros(W(n),W(n));
%
%if n==1,
%   for a=1:W(1),
%      for b=1:W(1),
%
%         dc=0;
%         for i=1:W(2),
%            for j=1:W(3),
%               [idxia idxja]=getindxn(W,[a i j]);
%               [idxib idxjb]=getindxn(W,[b i j]);
%               dc = dc + (C(idxia,idxja)^2 - mc)*C(idxib,idxjb)*C(idxia,idxja);
%            end;
%         end;
%
%         dC(a,b) = dc;
%      end;
%   end;
%end;
%
%if n==2,
%   for a=1:W(2),
%      for b=1:W(2),
%
%         dc=0;
%         for i=1:W(1),
%            for j=1:W(3),
%               [idxia idxja]=getindxn(W,[i a j]);
%               [idxib idxjb]=getindxn(W,[i b j]);
%               dc = dc + (C(idxia,idxja)^2 - mc)*C(idxib,idxjb)*C(idxia,idxja);
%            end;
%         end;
%
%         dC(a,b) = dc;
%      end;
%   end;
%end;
%
%if n==3,
%   for a=1:W(3),
%      for b=1:W(3),
%
%         dc=0;
%         for i=1:W(1),
%            for j=1:W(2),
%               [idxia idxja]=getindxn(W,[i j a]);
%               [idxib idxjb]=getindxn(W,[i j b]);
%               dc = dc + (C(idxia,idxja)^2 - mc)*C(idxib,idxjb)*C(idxia,idxja);
%            end;
%         end;
%
%         dC(a,b) = dc;
%      end;
%   end;
%end;


function Matdetec2 = findMatdetecFootprint(DetectFootPrint,XPsizeOut,YPsizeOut)
% Fixed the calculation of footprint of Sentinel-2 detector based on old
% version of Sentinel-2 data (17/12/2021 Shi)

clear Matdetec k
% sorted foot print from 1 to 4
[DetectFootPrint.Ndect, idnews] = sort(DetectFootPrint.Ndect);
DetectFootPrint.Nband = DetectFootPrint.Nband(idnews);
DetectFootPrint.Data = DetectFootPrint.Data(idnews);

for i = 1:length(DetectFootPrint.Ndect)

  IDX = knnsearch(XPsizeOut',DetectFootPrint.Data{i,1}(:,1));
  IDY = knnsearch(YPsizeOut,DetectFootPrint.Data{i,1}(:,2));

  dum2 = single(poly2mask(double(IDX), double(IDY),length(XPsizeOut),length(XPsizeOut))) ;
  clear IDX IDY;
  dum2 = conv2(dum2,ones(3),'same')>0; % to fill boundary
  Matdetec(:,:,i) = dum2;
  clear dum*

  %   find orientation of detect + slope for computing perpendicular kernel
  I=nan(size(Matdetec,2),1);
  for ii=1:size(Matdetec,1)
    dum=find(Matdetec(ii,:,i)==1,1,'first');
    if ~isempty(dum)
      I(ii,1)=dum;
    end
  end
  clear dum;
  J = [1:size(Matdetec,1)]' ;
  test = ~isnan(I) & I > 1 & I < size(Matdetec,2);
  warning off all % if warning => not enough point => slope=0 => good because tile boundary
  k{i,1} = polyfit(J(test),I(test),1);
  clear test;

  I=nan(size(Matdetec,2),1);
  for ii=1:size(Matdetec,1)
    dum=find(Matdetec(ii,:,i)==1,1,'last');
    if ~isempty(dum)
      I(ii,1)=dum;
    end
  end
  J = [1:size(Matdetec,1)]' ;
  test = ~isnan(I) & I > 1 & I < size(Matdetec,2);
  k{i,2} = polyfit(J(test),I(test),1);
  clear test;
  warning on all

end

% mediane
for i = 1:length(DetectFootPrint.Ndect)-1
  mediane = mean( [k{i,2} ; k{i+1,1}] ) ;

  k{i,2} = mediane ;
  k{i+1,1} = mediane ;
  clear mediane;
end
J = [1:size(Matdetec,1)]' ;
I = [1:size(Matdetec,2)] ;

[Jmat Imat] = meshgrid(I,J);
clear I J;

Matdetec2 = nan(size(Matdetec,1),size(Matdetec,2));
clear Matdetec;
for i = 1:length(DetectFootPrint.Ndect)

  liminf = polyval(k{i,1},Jmat);
  limsup = polyval(k{i,2},Jmat);

  if sum(k{i,2}) == 0 % footprint at low-right corner
      Matdetec2(Imat>=liminf) = DetectFootPrint.Ndect(i) ;
  elseif sum(k{i,1}) == 0 % footprint at up-left corner
     Matdetec2(Imat<=limsup) = DetectFootPrint.Ndect(i) ;
  else
     Matdetec2(Imat>=liminf & Imat<=limsup) = DetectFootPrint.Ndect(i) ;
  end
  clear liminf limsup;
end
clear Imat ImatJ k;

Matdetec2 = Matdetec2';


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   PARAMETERS Returns a data structure containing the parameters of the
%   KUKA KR30 L16 2
%
%   Author: Arturo Gil. Universidad Miguel Hern�ndez de Elche.
%   email: arturo.gil@umh.es date:   08/01/2012
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Copyright (C) 2012, by Arturo Gil Aparicio
%
% This file is part of ARTE (A Robotics Toolbox for Education).
%
% ARTE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% ARTE 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with ARTE.  If not, see <http://www.gnu.org/licenses/>.
function robot = parameters()

robot.DH.theta= '[-q(1) q(2)-pi/2 q(3)   q(4) q(5) q(6)]';
robot.DH.d='[0.815          0     0    1.545 0 0.158]';
robot.DH.a='[0.350         1.2    0.145    0 0 0]';
robot.DH.alpha= '[-pi/2 0 -pi/2 pi/2 -pi/2 0]';

robot.J=[];
robot.name= 'KUKA_KR30_L16_2';

robot.inversekinematic_fn = 'inversekinematic_kuka_kr_30_L16_2(robot, T)';

%number of degrees of freedom
robot.DOF = 6;

%rotational: 0, translational: 1
robot.kind=['R' 'R' 'R' 'R' 'R' 'R'];

%minimum and maximum rotation angle in rad
robot.maxangle =[deg2rad(-185) deg2rad(185); %Axis 1, minimum, maximum
                deg2rad(-135) deg2rad(35); %Axis 2, minimum, maximum
                deg2rad(-120) deg2rad(158); %Axis 3
                deg2rad(-350) deg2rad(350); %Axis 4
                deg2rad(-130) deg2rad(130); %Axis 5
                deg2rad(-350) deg2rad(350)]; %Axis 6

%maximum absolute speed of each joint rad/s or m/s
robot.velmax = [deg2rad(100); %Axis 1, rad/s
                deg2rad(80); %Axis 2, rad/s
                deg2rad(80); %Axis 3, rad/s
                deg2rad(230); %Axis 4, rad/s
                deg2rad(165); %Axis 5, rad/s
                deg2rad(249)];%Axis 6, rad/s
% end effectors maximum velocity
robot.linear_velmax = 2.0; %m/s
robot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time
%base reference system
robot.T0 = eye(4);

%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION
%position, velocity and acceleration
robot=init_sim_variables(robot);

% GRAPHICS
robot.graphical.has_graphics=1;
robot.graphical.color = [200 20 40]./255;
%for transparency
robot.graphical.draw_transparent=0;
%draw DH systems
robot.graphical.draw_axes=1;
%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for
%bigger robots
robot.graphical.axes_scale=1;
%adjust for a default view of the robot
robot.axis=[-2 2 -2 2 0 2.5];
%read graphics files
robot = read_graphics(robot);

%DYNAMICS
robot.has_dynamics=0;


%% DEMO_febio_0005_cube_tension_compression_shear
% Below is a demonstration for:
%
% * Building geometry for a cube with hexahedral elements
% * Defining the boundary conditions
% * Coding the febio structure
% * Running the model
% * Importing and visualizing the displacement and stress results

%% Keywords
%
% * febio_spec version 3.0
% * febio, FEBio
% * compression, tension, compressive, tensile, shear
% * displacement control, displacement boundary condition
% * hexahedral elements, hex8
% * cube, box, rectangular
% * static, solid
% * hyperelastic, Ogden
% * displacement logfile
% * stress logfile

%%

clear; close all; clc;

%% Plot settings
fontSize=20;
faceAlpha1=0.8;
markerSize=40;
markerSize2=20;
lineWidth=3;

%% Control parameters

% Path names
defaultFolder = fileparts(fileparts(mfilename('fullpath')));
savePath=fullfile(defaultFolder,'data','temp');

% Defining file names
febioFebFileNamePart='tempModel';
febioFebFileName=fullfile(savePath,[febioFebFileNamePart,'.feb']); %FEB file name
febioLogFileName=[febioFebFileNamePart,'.txt']; %FEBio log file name
febioLogFileName_disp=[febioFebFileNamePart,'_disp_out.txt']; %Log file name for exporting displacement
febioLogFileName_stress=[febioFebFileNamePart,'_stress_out.txt']; %Log file name for exporting stress

%Specifying dimensions and number of elements
cubeSize=10;
sampleWidth=cubeSize; %Width
sampleThickness=cubeSize; %Thickness
sampleHeight=cubeSize; %Height
pointSpacings=2*ones(1,3); %Desired point spacing between nodes
numElementsWidth=round(sampleWidth/pointSpacings(1)); %Number of elemens in dir 1
numElementsThickness=round(sampleThickness/pointSpacings(2)); %Number of elemens in dir 2
numElementsHeight=round(sampleHeight/pointSpacings(3)); %Number of elemens in dir 3

%Define applied displacement
stretchLoad=1.3;
displacementMagnitude=(stretchLoad*sampleHeight)-sampleHeight; %The displacement magnitude

%Material parameter set
c1=1e-3; %Shear-modulus-like parameter
m1=8; %Material parameter setting degree of non-linearity
k_factor=1e2; %Bulk modulus factor
k=c1*k_factor; %Bulk modulus

% FEA control settings
numTimeSteps=10; %Number of time steps desired
max_refs=25; %Max reforms
max_ups=0; %Set to zero to use full-Newton iterations
opt_iter=6; %Optimum number of iterations
max_retries=5; %Maximum number of retires
dtmin=(1/numTimeSteps)/100; %Minimum time step size
dtmax=1/numTimeSteps; %Maximum time step size

%% Creating model geometry and mesh
% A box is created with tri-linear hexahedral (hex8) elements using the
% |hexMeshBox| function. The function offers the boundary faces with
% seperate labels for the top, bottom, left, right, front, and back sides.
% As such these can be used to define boundary conditions on the exterior.

% Create a box with hexahedral elements
cubeDimensions=[sampleWidth sampleThickness sampleHeight]; %Dimensions
cubeElementNumbers=[numElementsWidth numElementsThickness numElementsHeight]; %Number of elements
outputStructType=2; %A structure compatible with mesh view
[meshStruct]=hexMeshBox(cubeDimensions,cubeElementNumbers,outputStructType);

%Access elements, nodes, and faces from the structure
E=meshStruct.elements; %The elements
V=meshStruct.nodes; %The nodes (vertices)
Fb=meshStruct.facesBoundary; %The boundary faces
Cb=meshStruct.boundaryMarker; %The "colors" or labels for the boundary faces
elementMaterialIndices=ones(size(E,1),1); %Element material indices

%%
% Plotting model boundary surfaces and a cut view

hFig=cFigure;

subplot(1,2,1); hold on;
title('Model boundary surfaces and labels','FontSize',fontSize);
gpatch(Fb,V,Cb,'k',faceAlpha1);
colormap(gjet(6)); icolorbar;
axisGeom(gca,fontSize);

hs=subplot(1,2,2); hold on;
title('Cut view of solid mesh','FontSize',fontSize);
optionStruct.hFig=[hFig hs];
meshView(meshStruct,optionStruct);
axisGeom(gca,fontSize);

drawnow;

%% Defining the boundary conditions
% The visualization of the model boundary shows colors for each side of the
% cube. These labels can be used to define boundary conditions.

%Define supported node sets
logicFace=Cb==5; %Logic for current face set
Fr=Fb(logicFace,:); %The current face set
bcSupportList=unique(Fr(:)); %Node set part of selected face

%Prescribed displacement nodes
logicPrescribe=Cb==6; %Logic for current face set
Fr=Fb(logicPrescribe,:); %The current face set
bcPrescribeList=unique(Fr(:)); %Node set part of selected face

%%
% Visualizing boundary conditions. Markers plotted on the semi-transparent
% model denote the nodes in the various boundary condition lists.

hf=cFigure;
title('Boundary conditions','FontSize',fontSize);
xlabel('X','FontSize',fontSize); ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize);
hold on;

gpatch(Fb,V,'kw','k',0.5);

hl(1)=plotV(V(bcSupportList,:),'k.','MarkerSize',markerSize);
hl(2)=plotV(V(bcPrescribeList,:),'r.','MarkerSize',markerSize);

legend(hl,{'BC support','BC prescribe'});

axisGeom(gca,fontSize);
camlight headlight;
drawnow;

%% Defining the FEBio input structure
% See also |febioStructTemplate| and |febioStruct2xml| and the FEBio user
% manual.

%Get a template with default settings
[febio_spec]=febioStructTemplate;

%febio_spec version
febio_spec.ATTR.version='3.0';

%Module section
febio_spec.Module.ATTR.type='solid';

%Create control structure for use by all steps
stepStruct.Control.time_steps=numTimeSteps;
stepStruct.Control.step_size=1/numTimeSteps;
stepStruct.Control.solver.max_refs=max_refs;
stepStruct.Control.solver.max_ups=max_ups;
stepStruct.Control.time_stepper.dtmin=dtmin;
stepStruct.Control.time_stepper.dtmax=dtmax;
stepStruct.Control.time_stepper.max_retries=max_retries;
stepStruct.Control.time_stepper.opt_iter=opt_iter;

%Add template based default settings to proposed control section
[stepStruct.Control]=structComplete(stepStruct.Control,febio_spec.Control,1); %Complement provided with default if missing

%Remove control field (part of template) since step specific control sections are used
febio_spec=rmfield(febio_spec,'Control');

febio_spec.Step.step{1}.Control=stepStruct.Control;
febio_spec.Step.step{1}.ATTR.id=1;
febio_spec.Step.step{2}.Control=stepStruct.Control;
febio_spec.Step.step{2}.ATTR.id=2;
febio_spec.Step.step{3}.Control=stepStruct.Control;
febio_spec.Step.step{3}.ATTR.id=3;
febio_spec.Step.step{4}.Control=stepStruct.Control;
febio_spec.Step.step{4}.ATTR.id=4;
febio_spec.Step.step{5}.Control=stepStruct.Control;
febio_spec.Step.step{5}.ATTR.id=5;

%Material section
materialName1='Material1';
febio_spec.Material.material{1}.ATTR.name=materialName1;
febio_spec.Material.material{1}.ATTR.type='Ogden';
febio_spec.Material.material{1}.ATTR.id=1;
febio_spec.Material.material{1}.c1=c1;
febio_spec.Material.material{1}.m1=m1;
febio_spec.Material.material{1}.c2=c1;
febio_spec.Material.material{1}.m2=-m1;
febio_spec.Material.material{1}.k=k;

% Mesh section
% -> Nodes
febio_spec.Mesh.Nodes{1}.ATTR.name='Object1'; %The node set name
febio_spec.Mesh.Nodes{1}.node.ATTR.id=(1:size(V,1))'; %The node id's
febio_spec.Mesh.Nodes{1}.node.VAL=V; %The nodel coordinates

% -> Elements
partName1='Part1';
febio_spec.Mesh.Elements{1}.ATTR.name=partName1; %Name of this part
febio_spec.Mesh.Elements{1}.ATTR.type='hex8'; %Element type
febio_spec.Mesh.Elements{1}.elem.ATTR.id=(1:1:size(E,1))'; %Element id's
febio_spec.Mesh.Elements{1}.elem.VAL=E; %The element matrix

% -> NodeSets
nodeSetName1='bcSupportList';
nodeSetName2='bcPrescribeList';

febio_spec.Mesh.NodeSet{1}.ATTR.name=nodeSetName1;
febio_spec.Mesh.NodeSet{1}.node.ATTR.id=bcSupportList(:);

febio_spec.Mesh.NodeSet{2}.ATTR.name=nodeSetName2;
febio_spec.Mesh.NodeSet{2}.node.ATTR.id=bcPrescribeList(:);

%MeshDomains section
febio_spec.MeshDomains.SolidDomain.ATTR.name=partName1;
febio_spec.MeshDomains.SolidDomain.ATTR.mat=materialName1;

%Boundary condition section
%-> Fix boundary conditions
febio_spec.Boundary.bc{1}.ATTR.type='fix';
febio_spec.Boundary.bc{1}.ATTR.node_set=nodeSetName1;
febio_spec.Boundary.bc{1}.dofs='x,y,z';

%STEP 1 Tension
febio_spec.Step.step{1}.Boundary.bc{1}.ATTR.type='prescribe';
febio_spec.Step.step{1}.Boundary.bc{1}.ATTR.node_set=nodeSetName2;
febio_spec.Step.step{1}.Boundary.bc{1}.dof='z';
febio_spec.Step.step{1}.Boundary.bc{1}.scale.ATTR.lc=1;
febio_spec.Step.step{1}.Boundary.bc{1}.scale.VAL=displacementMagnitude;
febio_spec.Step.step{1}.Boundary.bc{1}.relative=1;

febio_spec.Step.step{1}.Boundary.bc{2}.ATTR.type='fix';
febio_spec.Step.step{1}.Boundary.bc{2}.ATTR.node_set=nodeSetName2;
febio_spec.Step.step{1}.Boundary.bc{2}.dofs='x,y';

%STEP 2 Return form tension
febio_spec.Step.step{2}.Boundary.bc{1}.ATTR.type='prescribe';
febio_spec.Step.step{2}.Boundary.bc{1}.ATTR.node_set=nodeSetName2;
febio_spec.Step.step{2}.Boundary.bc{1}.dof='z';
febio_spec.Step.step{2}.Boundary.bc{1}.scale.ATTR.lc=2;
febio_spec.Step.step{2}.Boundary.bc{1}.scale.VAL=-displacementMagnitude;
febio_spec.Step.step{2}.Boundary.bc{1}.relative=1;

febio_spec.Step.step{2}.Boundary.bc{2}.ATTR.type='fix';
febio_spec.Step.step{2}.Boundary.bc{2}.ATTR.node_set=nodeSetName2;
febio_spec.Step.step{2}.Boundary.bc{2}.dofs='x,y';

%STEP 3 Compression
febio_spec.Step.step{3}.Boundary.bc{1}.ATTR.type='prescribe';
febio_spec.Step.step{3}.Boundary.bc{1}.ATTR.node_set=nodeSetName2;
febio_spec.Step.step{3}.Boundary.bc{1}.dof='z';
febio_spec.Step.step{3}.Boundary.bc{1}.scale.ATTR.lc=3;
febio_spec.Step.step{3}.Boundary.bc{1}.scale.VAL=-displacementMagnitude;
febio_spec.Step.step{3}.Boundary.bc{1}.relative=1;

febio_spec.Step.step{3}.Boundary.bc{2}.ATTR.type='fix';
febio_spec.Step.step{3}.Boundary.bc{2}.ATTR.node_set=nodeSetName2;
febio_spec.Step.step{3}.Boundary.bc{2}.dofs='x,y';

%STEP 4 Return from compression
febio_spec.Step.step{4}.Boundary.bc{1}.ATTR.type='prescribe';
febio_spec.Step.step{4}.Boundary.bc{1}.ATTR.node_set=nodeSetName2;
febio_spec.Step.step{4}.Boundary.bc{1}.dof='z';
febio_spec.Step.step{4}.Boundary.bc{1}.scale.ATTR.lc=4;
febio_spec.Step.step{4}.Boundary.bc{1}.scale.VAL=displacementMagnitude;
febio_spec.Step.step{4}.Boundary.bc{1}.relative=1;

febio_spec.Step.step{4}.Boundary.bc{2}.ATTR.type='fix';
febio_spec.Step.step{4}.Boundary.bc{2}.ATTR.node_set=nodeSetName2;
febio_spec.Step.step{4}.Boundary.bc{2}.dofs='x,y';

%STEP 5 Shear
febio_spec.Step.step{5}.Boundary.bc{1}.ATTR.type='prescribe';
febio_spec.Step.step{5}.Boundary.bc{1}.ATTR.node_set=nodeSetName2;
febio_spec.Step.step{5}.Boundary.bc{1}.dof='x';
febio_spec.Step.step{5}.Boundary.bc{1}.scale.ATTR.lc=5;
febio_spec.Step.step{5}.Boundary.bc{1}.scale.VAL=displacementMagnitude;
febio_spec.Step.step{5}.Boundary.bc{1}.relative=1;

febio_spec.Step.step{5}.Boundary.bc{2}.ATTR.type='fix';
febio_spec.Step.step{5}.Boundary.bc{2}.ATTR.node_set=nodeSetName2;
febio_spec.Step.step{5}.Boundary.bc{2}.dofs='y,z';

%LoadData section
% -> load_controller
febio_spec.LoadData.load_controller{1}.ATTR.id=1;
febio_spec.LoadData.load_controller{1}.ATTR.type='loadcurve';
febio_spec.LoadData.load_controller{1}.interpolate='LINEAR';
febio_spec.LoadData.load_controller{1}.points.point.VAL=[0 0; 1 1];

febio_spec.LoadData.load_controller{2}.ATTR.id=2;
febio_spec.LoadData.load_controller{2}.ATTR.type='loadcurve';
febio_spec.LoadData.load_controller{2}.interpolate='LINEAR';
febio_spec.LoadData.load_controller{2}.points.point.VAL=[1 0; 2 1];

febio_spec.LoadData.load_controller{3}.ATTR.id=3;
febio_spec.LoadData.load_controller{3}.ATTR.type='loadcurve';
febio_spec.LoadData.load_controller{3}.interpolate='LINEAR';
febio_spec.LoadData.load_controller{3}.points.point.VAL=[2 0; 3 1];

febio_spec.LoadData.load_controller{4}.ATTR.id=4;
febio_spec.LoadData.load_controller{4}.ATTR.type='loadcurve';
febio_spec.LoadData.load_controller{4}.interpolate='LINEAR';
febio_spec.LoadData.load_controller{4}.points.point.VAL=[3 0; 4 1];

febio_spec.LoadData.load_controller{5}.ATTR.id=5;
febio_spec.LoadData.load_controller{5}.ATTR.type='loadcurve';
febio_spec.LoadData.load_controller{5}.interpolate='LINEAR';
febio_spec.LoadData.load_controller{5}.points.point.VAL=[4 0; 5 1];

%Output section
% -> log file
febio_spec.Output.logfile.ATTR.file=febioLogFileName;
febio_spec.Output.logfile.node_data{1}.ATTR.file=febioLogFileName_disp;
febio_spec.Output.logfile.node_data{1}.ATTR.data='ux;uy;uz';
febio_spec.Output.logfile.node_data{1}.ATTR.delim=',';
febio_spec.Output.logfile.node_data{1}.VAL=1:size(V,1);

febio_spec.Output.logfile.element_data{1}.ATTR.file=febioLogFileName_stress;
febio_spec.Output.logfile.element_data{1}.ATTR.data='s1';
febio_spec.Output.logfile.element_data{1}.ATTR.delim=',';
febio_spec.Output.logfile.element_data{1}.VAL=1:size(E,1);

%% Quick viewing of the FEBio input file structure
% The |febView| function can be used to view the xml structure in a MATLAB
% figure window.

%%
% |febView(febio_spec); %Viewing the febio file|

%% Exporting the FEBio input file
% Exporting the febio_spec structure to an FEBio input file is done using
% the |febioStruct2xml| function.

febioStruct2xml(febio_spec,febioFebFileName); %Exporting to file and domNode

%% Running the FEBio analysis
% To run the analysis defined by the created FEBio input file the
% |runMonitorFEBio| function is used. The input for this function is a
% structure defining job settings e.g. the FEBio input file name. The
% optional output runFlag informs the user if the analysis was run
% succesfully.

febioAnalysis.run_filename=febioFebFileName; %The input file name
febioAnalysis.run_logname=febioLogFileName; %The name for the log file
febioAnalysis.disp_on=1; %Display information on the command window
febioAnalysis.runMode='external';%'internal';

[runFlag]=runMonitorFEBio(febioAnalysis);%START FEBio NOW!!!!!!!!

%% Import FEBio results

if runFlag==1 %i.e. a succesful run

    %%
    % Importing nodal displacements from a log file
    dataStruct=importFEBio_logfile(fullfile(savePath,febioLogFileName_disp),1,1);

    %Access data
    N_disp_mat=dataStruct.data; %Displacement
    timeVec=dataStruct.time; %Time

    %Create deformed coordinate set
    V_DEF=N_disp_mat+repmat(V,[1 1 size(N_disp_mat,3)]);

    %%
    % Importing element stress from a log file
    dataStruct=importFEBio_logfile(fullfile(savePath,febioLogFileName_stress),1,1);

    %Access data
    E_stress_mat=dataStruct.data;

    %%
    % Plotting the simulated results using |anim8| to visualize and animate
    % deformations

    DN_magnitude=sqrt(sum(N_disp_mat(:,:,end).^2,2)); %Current displacement magnitude

    % Create basic view and store graphics handle to initiate animation
    hf=cFigure; %Open figure
    gtitle([febioFebFileNamePart,': Press play to animate']);
    title('Displacement magnitude [mm]','Interpreter','Latex')
    hp=gpatch(Fb,V_DEF(:,:,end),DN_magnitude,'k',1); %Add graphics object to animate
    hp.Marker='.';
    hp.MarkerSize=markerSize2;
    hp.FaceColor='interp';
    gpatch(Fb,V,0.5*ones(1,3),'k',0.25); %A static graphics object

    axisGeom(gca,fontSize);
    colormap(gjet(250)); colorbar;
    caxis([0 max(DN_magnitude)]);
    axis(axisLim(V_DEF)); %Set axis limits statically
        camlight headlight;

    % Set up animation features
    animStruct.Time=timeVec; %The time vector
    for qt=1:1:size(N_disp_mat,3) %Loop over time increments
        DN_magnitude=sqrt(sum(N_disp_mat(:,:,qt).^2,2)); %Current displacement magnitude

        %Set entries in animation structure
        animStruct.Handles{qt}=[hp hp]; %Handles of objects to animate
        animStruct.Props{qt}={'Vertices','CData'}; %Properties of objects to animate
        animStruct.Set{qt}={V_DEF(:,:,qt),DN_magnitude}; %Property values for to set in order to animate
    end
    anim8(hf,animStruct); %Initiate animation feature
    drawnow;

        %%
    % Plotting the simulated results using |anim8| to visualize and animate
    % deformations

    [CV]=faceToVertexMeasure(E,V,E_stress_mat(:,:,end));

    % Create basic view and store graphics handle to initiate animation
    hf=cFigure; %Open figure
    gtitle([febioFebFileNamePart,': Press play to animate']);
    title('$\sigma_{1}$ [MPa]','Interpreter','Latex')
    hp=gpatch(Fb,V_DEF(:,:,end),CV,'k',1); %Add graphics object to animate
    hp.Marker='.';
    hp.MarkerSize=markerSize2;
    hp.FaceColor='interp';
    gpatch(Fb,V,0.5*ones(1,3),'k',0.25); %A static graphics object

    axisGeom(gca,fontSize);
    colormap(gjet(250)); colorbar;
%     caxis([min(E_stress_mat(:)) max(E_stress_mat(:))]);
    axis(axisLim(V_DEF)); %Set axis limits statically
    camlight headlight;

    % Set up animation features
    animStruct.Time=timeVec; %The time vector
    for qt=1:1:size(N_disp_mat,3) %Loop over time increments

        [CV]=faceToVertexMeasure(E,V,E_stress_mat(:,:,qt));

        %Set entries in animation structure
        animStruct.Handles{qt}=[hp hp]; %Handles of objects to animate
        animStruct.Props{qt}={'Vertices','CData'}; %Properties of objects to animate
        animStruct.Set{qt}={V_DEF(:,:,qt),CV}; %Property values for to set in order to animate
    end
    anim8(hf,animStruct); %Initiate animation feature
    drawnow;

end

%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% 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/>.


function [B, elapse] = BRE_compress(A, model)
%   This is a wrapper function of Binary Reconstructive Embedding testing.
%
%	Usage:
%	[B,elapse] = BRE_compress(A, model)
%
%	      A: Rows of vectors of data points. Each row is sample point
%     model: The model generated by BRE_learn.
%
%	      B: The binary code of the input data A. Each row is sample point
%    elapse: The coding time (testing time).
%
%
%
%   version 2.0 --Nov/2016
%   version 1.0 --Jan/2013
%
%   Written by  Yue Lin (linyue29@gmail.com)
%               Deng Cai (dengcai AT gmail DOT com)
%

tmp_T = tic;

Ktest = A*model.X';
H_query = zeros(size(A,1),size(model.W,2));
for b = 1:size(model.W,2)
    H_query(:,b) = Ktest(:,model.hash_inds(:,b))*model.W(:,b);
end
B = (H_query>0);

elapse = toc(tmp_T);
end


function images = rmfilter_energy(images, display)

% simlpe energy filter:
%   (1) subtract background intenstity
%   (2) rectify
%   (3) divide by maximum
%       (max = greatest absolute distance from background)

try
    % look up min, max, and bk from screen calibration
    Cmap.min  = min(display.stimRgbRange);
    Cmap.max  = max(display.stimRgbRange);
    Cmap.bk   = display.backColorIndex;
catch
    % if not found assume them from image matrix
    Cmap.min  = min(images(:));
    Cmap.max  = max(images(:));
    Cmap.bk   = round(mean(images(:)));
end

images = double(images);
images = images - Cmap.bk;
images = sqrt(images.^2);
maxEnergy = double(max(Cmap.max - Cmap.bk, Cmap.bk - Cmap.min));
maxEnergy = double(maxEnergy);
images = images  / maxEnergy;

end


function node_num = grid_q4_node_num ( nelemx, nelemy )

%*****************************************************************************80
%
%% GRID_Q4_NODE_NUM counts the nodes in a grid of Q4 elements.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 February 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NELEMX, NELEMY, the number of elements along the
%    X and Y directions.  The number of elements generated will be
%    NELEMX * NELEMY.
%
%    Output, integer NODE_NUM, the number of nodes in the grid.
%
  node_num = ( nelemx + 1 ) * ( nelemy + 1 );

  return
end


function lagrange_interp_1d_test ( )

%*****************************************************************************80
%
%% LAGRANGE_INTERP_1D_TEST tests the LAGRANGE_INTERP_1D library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 August 2012
%
%  Author:
%
%    John Burkardt
%
  addpath ( '../r8lib' )
  addpath ( '../test_interp_1d' )

  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'LAGRANGE_INTERP_1D_TEST:\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the LAGRANGE_INTERP_1D library.\n' );
  fprintf ( 1, '  The R8LIB library is needed.\n' );
  fprintf ( 1, '  The test needs the TEST_INTERP_1D library.\n' );

  prob_num = p00_prob_num ( );
  for prob = 1 : prob_num
    for nd = [ 4, 8, 16, 32, 64, 256 ]
      lagrange_interp_1d_test02 ( prob, nd );
    end
  end

  prob_num = p00_prob_num ( );
  for prob = 1 : prob_num
    for nd = [ 4, 8, 16, 32, 64, 256 ]
      lagrange_interp_1d_test03 ( prob, nd );
    end
  end
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'LAGRANGE_INTERP_1D_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  rmpath ( '../r8lib' )
  rmpath ( '../test_interp_1d' )

  return
end


classdef PESAII < ALGORITHM
% <multi> <real/integer/label/binary/permutation>
% Pareto envelope-based selection algorithm II
% div --- 10 --- The number of divisions in each objective

%------------------------------- Reference --------------------------------
% D. W. Corne, N. R. Jerram, J. D. Knowles, and M. J. Oates, PESA-II:
% Region-based selection in evolutionary multiobjective optimization,
% Proceedings of the Annual Conference on Genetic and Evolutionary
% Computation, 2001, 283-290.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        function main(Algorithm,Problem)
            %% Parameter setting
            div = Algorithm.ParameterSet(10);

            %% Generate random population
            Population = Problem.Initialization();

            %% Optimization
            while Algorithm.NotTerminated(Population)
                MatingPool = MatingSelection(Population.objs,Problem.N,div);
                Offspring  = OperatorGA(Problem,Population(MatingPool));
                Population = EnvironmentalSelection([Population,Offspring],Problem.N,div);
            end
        end
    end
end


function test_bug3192

% WALLTIME 00:10:00
% MEM 2gb
% DEPENDENCY ft_plot_mesh ft_plot_box ft_plot_headmodel ft_plot_dipole ft_plot_headshape

% one color for all vertex
cfg = [];
cfg.sourcemodel.xgrid  = -20:5:20;
cfg.sourcemodel.ygrid  = -20:5:20;
cfg.sourcemodel.zgrid  = -20:5:20;
grid  = ft_prepare_sourcemodel(cfg);
figure, ft_plot_mesh(grid, 'vertexcolor', 'blue', 'facecolor', 'brain', 'edgecolor', 'skull')

% different colors for each vertex
c = [];
temp = {'r','b'};
for iPos=1:length(grid.pos), c = [c temp{mod(iPos,2)+1}]; end
figure, ft_plot_mesh(grid, 'vertexcolor', c)

figure, ft_plot_box([-1 1 2 3], 'facecolor', 'brain')

% ft_plot_sens, _vol, _headshape, and _dipole just forward to ft_plot_mesh
elecs = [];
elecs.elecpos = [23 42 -31; 69 52 1; 61 67 26; 52 65 45];
elecs.label = {'1' '2' '3' '4'};
figure, ft_plot_sens(elecs, 'edgecolor', 'red')

load(dccnpath('/home/common/matlab/fieldtrip/template/headmodel/standard_singleshell.mat'))
figure, ft_plot_headmodel(vol, 'edgecolor', 'blue', 'vertexcolor', 'red', 'facecolor', 'brain')

vol.pos = [23 42 -31; 69 52 1; 61 67 26; 52 65 45];
figure, ft_plot_headshape(vol, 'edgecolor', 'blue', 'vertexcolor', 'red', 'facecolor', 'brain')

figure, ft_plot_dipole([1 2 3], [1 2 3], 'color', 'brain')


function images = loadMNISTImages(filename)
%loadMNISTImages returns a 28x28x[number of MNIST images] matrix containing
%the raw MNIST images

fp = fopen(filename, 'rb');
assert(fp ~= -1, ['Could not open ', filename, '']);

magic = fread(fp, 1, 'int32', 0, 'ieee-be');
assert(magic == 2051, ['Bad magic number in ', filename, '']);

numImages = fread(fp, 1, 'int32', 0, 'ieee-be');
numRows = fread(fp, 1, 'int32', 0, 'ieee-be');
numCols = fread(fp, 1, 'int32', 0, 'ieee-be');

images = fread(fp, inf, 'unsigned char=>unsigned char');
images = reshape(images, numCols, numRows, numImages);
images = permute(images,[2 1 3]);

fclose(fp);

% Reshape to #pixels x #examples
images = reshape(images, size(images, 1) * size(images, 2), size(images, 3));
% Convert to double and rescale to [0,1]
images = double(images) / 255;

end