classdef spherefun < separableApprox
%SPHEREFUN class for representing functions on the unit sphere.
%
%   Class for approximating functions defined on the unit sphere. The
%   functions should be smooth.
%
% SPHEREFUN(F) constructs a SPHEREFUN object representing the function F on
% the unit sphere. F can have the following form:
%    1. A function handle in (x,y,z), e.g., @(x,y,z) x.*y.*z + cos(x).
%    2. A function handle in spherical coordinates (lambda,theta), where
%       lambda is the azimuthal variable and satisfies -pi <= lambda <= pi
%       and theta is the polar angle and satisfies 0 <= theta < pi,
%       e.g., @(lambda,theta) cos(cos(lambda).*sin(theta))
%    3. A matrix of numbers.
% If F is a function handle then it should allow for vectorized evaluations.
%
% If F is a matrix, F = (f_ij), the numbers fij are used as function values
% at tensor equally-spaced points in the intrinsic spherical coordinate
% system, i.e., [-pi,pi]x[0,pi].
%
% SPHEREFUN(F, k) returns a rank k approximation to F.
%
% SPHEREFUN(F, [m n]) returns a representation of F using a degree m
% trigonometric approximation of F in the theta (polar) direction and a
% degree n trigonometric approximation in the lambda (azimuthal) direction.
% The result is compressed in low rank form and the rank k is still
% determined adaptively (satisfying k<=min(m,n)+1).
%
% The SPHEREFUN software system is based on:
%
% A. Townsend, H. Wilber, and G. Wright, Computing with functions in
% spherical and polar geometries I: The sphere, SIAM. J. Sci. Comput., 38-4
% (2016), C403-C425.
%
% See also CHEBFUN2, DISKFUN, SPHEREFUNV

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

% TODO: Include documentation of fixed eps construction

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CLASS CONSTRUCTOR:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods (Access = public, Static = false)

        function f = spherefun(varargin)
            % The main spherefun constructor!

            % Return an empty CHEBFUN:
            if ( (nargin == 0) || isempty(varargin{1}) )
                f.domain = [-pi pi 0 pi];
                return
            end

            f = constructor(f, varargin{:});
        end

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CLASS METHODS:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods
        %f = conj(f);
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% HIDDEN METHODS:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods (Access = public, Static = false, Hidden = true)
        % Project a spherefun to have exact BMC-I symmetry so that it is
        % a continuous function on the sphere.
        f = projectOntoBMCI(f);

        % Fast evaluation of a spherefun using non-uniform fft.
        vals = fastSphereEval( f, lambda, theta );
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% PUBLIC METHODS:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods (Access = public, Static = false)

        % The main bulk of the SPHEREFUN constructor:
        g = constructor(g, op, dom, varargin);

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% STATIC METHODS:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods (Access = public, Static = true)

        % Poisson solver:
        u = poisson(f, const, m, n);

        % Helmholtz solver:
        u = helmholtz(f, K, m, n);

        % Convert matrix of coefficients to a spherefun:
        f = coeffs2spherefun(CFS);

        varargout = coeffs2vals(U, varargin);
        varargout = vals2coeffs(U, varargin);

        % Convert a function in spherical coordinates to one in Cartesian
        % coordinates on the sphere.
        fdf = sphf2cartf(f, lam, th, coord);

        % Degree l Order m spherical harmonic.
        Y = sphharm(l, m, coord);

        % Plot the outline of the landmasses of earth
        h = plotEarth(linespec);

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Private Static methods implemented by SPHEREFUN class.
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods (Access = private, Static = true)
        % Fast evaluation of a spherefun using non-uniform fft.
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CLASS PROPERTIES
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    properties (Access = public)
        % DOMAIN: default is [-pi,pi] x [0,pi] which corresponds to using
        % colatitude for the elevation angle (second input argument).
        % Doubled-up sphere will have a domain of [-pi,pi] x [-pi,pi].
        idxPlus
        idxMinus
        nonZeroPoles = 0;
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Private constant properties
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    properties (Constant)
        % TODO: Add support for this constant here.
        % alpha = 50;  % Growth factor control.
    end

end


%==============================================================================
% 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:  Landmark Based Registration, quadratic transformation
%
% - load data (see setup2DhandData)
% - setup  viewer (viewImage2D), interpolator (splineInter),
% - setup landmarks (LM)
% - run quadratic
%==============================================================================

clear, close all, help(mfilename)

%% setup hand data
setup2DhandData

if FAIRinput('','set new landmarks ? ',0),
  [LM,fig] = getLandmarks(dataT,dataR,omega,m);
  close(fig);
end;

omegaT = omega(1,:);
omegaR = omega(end,:);
xT = getCellCenteredGrid(omegaT,m);
xR = getCellCenteredGrid(omegaR,m);
Tc = imgModel(dataT,omegaT,xT);
Rc = imgModel(dataR,omegaR,xR);

%% visualize data
FAIRfigure(1,'figname',mfilename); clf;
subplot(1,3,1); viewImage(Tc,omegaT,m); hold on;
ph = plotLM(LM(:,1:2),'numbering','on','color','r');
set(ph,'linewidth',2,'markersize',20);
title(sprintf('%s','T&LM'),'fontsize',20);

subplot(1,3,2); viewImage(Rc,omegaR,m); hold on;
ph = plotLM(LM(:,3:4),'numbering','on','color','g','marker','+');
set(ph,'linewidth',2,'markersize',20);
title(sprintf('%s','R&LM'),'fontsize',20);

%% compute landmark based registration
[yc,LM] = LMreg('quadratic',LM(:,1:4),xR);
TLM = imgModel(dataT,omegaT,yc);

subplot(1,3,3); cla; viewImage(TLM,omegaR,m); hold on;
ph = plotLM(LM(:,3:4),'numbering','off','color','g','marker','+');
qh = plotLM(LM(:,7:8),'numbering','off','color','m','marker','x');
rh = plot(LM(:,[3,7])',LM(:,[4,8])','m-','linewidth',3);
set([ph;qh;rh],'linewidth',2,'markersize',20);
title(sprintf('%s','T(y^{quadratic})&LM'),'fontsize',20);
%==============================================================================


% Computing most probable explanation.

% If you don't break ties consistently, loopy can give wrong mpe
% even though the graph has no cycles, and even though the max-marginals are the same.
% This example was contributed by Wentau Yih <wtyih@yahoo.com> 29 Jan 02.

% define loop-free graph structure (all edges point down)
%
% Xe1   Xe2
%  |    |
%  E1   E2
%    \ /
%     R1
%     |
%    Xr1

N = 6;
dag = zeros(N,N);
Xe1 = 1; Xe2 = 2; E1 = 3; E2 = 4; R1 = 5; Xr1 = 6;
dag(Xe1, E1) = 1;
dag(Xe2, E2) = 1;
dag([E1 E2], R1) = 1;
dag(R1, Xr1) = 1;

node_sizes = [ 1 1 2 2 2 1 ];

% create BN

bnet = mk_bnet(dag, node_sizes, 'observed', [Xe1 Xe2 Xr1]);

% fill in CPT

bnet.CPD{Xe1} = tabular_CPD(bnet, Xe1, [1]);
bnet.CPD{Xe2} = tabular_CPD(bnet, Xe2, [1]);
bnet.CPD{E1} = tabular_CPD(bnet, E1, [0.2 0.8]);
bnet.CPD{E2} = tabular_CPD(bnet, E2, [0.3 0.7]);
bnet.CPD{R1} = tabular_CPD(bnet, R1, [1 1 1 0.8 0 0 0 0.2]);
bnet.CPD{Xr1} = tabular_CPD(bnet, Xr1, [0.15 0.85]);

clear engine;
engine{1} = belprop_inf_engine(bnet);
engine{2} = jtree_inf_engine(bnet);
engine{3} = global_joint_inf_engine(bnet);
engine{4} = var_elim_inf_engine(bnet);

evidence = cell(1,N);
evidence{Xe1} = 1;  evidence{Xe2} = 1;  evidence{Xr1} = 1;

mpe = find_mpe(engine{1}, evidence, 'break_ties', 0) % gives wrong results
mpe = find_mpe(engine{1}, evidence)
for i=2:4
  mpe = find_mpe(engine{i}, evidence)
end


function x = slopeinit(xs,X)
%SLOPEINIT    Initialization of slope expansion
%
%  x = slopeinit(xs,X)
%
%This statement with interval quantities xs and X followed by
%  a function evaluation
%
%  y = f(x)
%
%using arithmetic operations and standard functions (overloaded by
%slope operators) implies 3 assertions:
%
%  1)  f(xs) in y.c
%  2)  f(X)  in y.r
%  3)  For all xp in X there exists s in y.s with  f(xp) = f(xs) + s*(xp-xs) .
%
%The expansion point xs and expansion interval X must be real quantities,
%  non-interval input data is converted into interval data to ensure
%  correctness of 1..3).
%
%The call
%
%  slopeinit
%
%without input parameters initializes the slope expansion to xs = X = [].
%
%The slope of arrays is stored in the 'next dimension'. So y.s is
%  3-dimensional for a slope row vector y. Since Matlab does not
%  support multi-dimensional sparse arrays, y.s is not accessible
%  if y has more than one column.
%
%As a simple example of slopes
%
%  xs = [ -3 ; 7.15 ] ;  X = intval(' [ -3.1,-2.9 ]  [ 7,7.1 ] ') ;
%  u = slopeinit( xs , X );
%
%initializes the slope package to have two dependent variables. The
%expansion point is xs=[-3;7.15] with expansion interval X.
%
%For a function f from R^2 to R, y=f(u) computed by overloaded slope
%operators has access y.c, y.r and y.s with the properties listed above.
%Internally, slopes are computed and stored according to
%
%  S.M. Rump: Expansion and Estimation of the Range of Nonlinear Functions,
%    Math. Comp. 65(216), p. 1503-1512 (1996).
%
%In contrast to the usual definition of slopes (see Neumaier's book),
%
%  - rather than one n-dimensional slope, n one-dimensional slopes
%      are calculated treating the function
%        f(X_1,...,X_k-1,z,xs_k+1,...,xs_n)
%      as a function in one variable z.
%  - intersections for the two definitions of multiplication and division
%      sharpens results (note this is not possible for n-dimensional slopes)
%  - intersections of the computed range y.r with y.c+y.s(X-xs) sharpens
%      results
%  - the sharp formulas for slopes of convex and concave functions are
%      used (for details, see the paper).
%
%Slope are useful for verified inclusion of clustered or multiple zeros.
%Sometimes, the range estimation is better than naive interval arithmetic
%or gradient expansion.
%
%For a simple plot of one-dimensional slopes, see slopeplot.
%

% written  12/06/98     S.M. Rump
% modified 09/28/01     S.M. Rump  matrices and multi-dimensional arrays
% modified 04/06/04     S.M. Rump  handling of derivatives of sparse arrays
% modified 04/04/04     S.M. Rump  set round to nearest for safety
% modified 04/06/05     S.M. Rump  rounding unchanged
% modified 08/26/12     S.M. Rump  global variables removed
% modified 10/03/12     S.M. Rump  SlopeSparseArrayDeriv removed
%

  if nargin==0
    INTLAB_SLOPE.NUMVAR = 0;
    INTLAB_SLOPE.Xxs = [];
    setappdata(0,'INTLAB_SLOPE',INTLAB_SLOPE);
    return
  end

  if ~isreal(xs) | ~isreal(X)
    error('Complex numbers not allowed in slope expansion')
  end

  if ( ~isa(xs,'double') & ~isa(xs,'intval') ) | ...
     ( ~isa(X,'double') & ~isa(X,'intval') )
    error('invalid initialization of slopes: input must be double or intval')
  end

  if ~isequal(size(xs),size(X))
    error('invalid initialization of slopes: dimensions do not match')
  end

  % initialize INTLAB constants
  INTLAB_SLOPE.NUMVAR = prod(size(xs));
  dummy.xs = intval(xs);
  dummy.X = intval(X);
  INTLAB_SLOPE.Xxs = dummy.X - dummy.xs;
  INTLAB_SLOPE.Xxs = INTLAB_SLOPE.Xxs(:);
  setappdata(0,'INTLAB_SLOPE',INTLAB_SLOPE);
  x = slope( dummy, 'slopeinit' );


function S_lags=bss_make_lags(S,L)

% create a matrix containing lagged versions of some signal(s).
%
% Usage: S_lags=bss_make_lags(S,L)
%
% Input:
%   - S: n x T matrix containing the input signal(s),
%   - L: number of lagged versions of the signal(s).
%
% Output:
%   - S_lags: n*L x T matrix containing lagged versions of S, S_lags(t)=
%   [s1(t) ; s1(t-1) ; ...; s1(t-L+1); ... ; sn(t) ; sn(t-1) ; ...; sn(t-L+1)]
%
% WARNINGS:
%   * S_lags is zero-padded where necessary,
%   * We use the conventions make_lags(S,0)=makes_lags(S,1)=S.
%
% Developers:  - Cedric Fevotte (fevotte@tsi.enst.fr) - Emmanuel Vincent
% (emmanuel.vincent@irisa.fr) - Remi Gribonval (remi.gribonval@irisa.fr)

[n,T]=size(S);

if L==0
    S_lags=S;
else

    N=n*L;
    S_lags=zeros(N,T);
    for i=1:N
        q=floor((i-1)/L);
        r=mod(i-1,L);
        B=zeros(1,r+1); B(end)=1;
        S_lags(i,:)=filter(B,1,S(q+1,:));
    end

end


function [Population,Archive,Fitness] = EnvironmentalSelection(Population,N)
% The environmental selection of SPEA2

%------------------------------- 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".
%--------------------------------------------------------------------------

    %% Calculate the fitness of each solution
    Fitness = CalFitness(Population.objs);

    %% Environmental selection
    Next    = Fitness < 1;
    Archive = Population(Next);
    if sum(Next) < N
        [~,Rank] = sort(Fitness);
        Next(Rank(1:N)) = true;
    elseif sum(Next) > N
        Del  = Truncation(Population(Next).objs,sum(Next)-N);
        Temp = find(Next);
        Next(Temp(Del)) = false;
        Archive = Population(Next);
    end
    % Population for Next generation
    Population = Population(Next);
    Fitness    = Fitness(Next);
end

function Del = Truncation(PopObj,K)
% Select part of the solutions by truncation

    %% Truncation
    Distance = pdist2(PopObj,PopObj);
    Distance(logical(eye(length(Distance)))) = inf;
    Del = false(1,size(PopObj,1));
    while sum(Del) < K
        Remain   = find(~Del);
        Temp     = sort(Distance(Remain,Remain),2);
        [~,Rank] = sortrows(Temp);
        Del(Remain(Rank(1))) = true;
    end
end


classdef nnslice < nntest
  methods (Test)

    function basic(test)
        sz = [3,3,5,4] ;
        x = test.randn(sz) ;
        dim = 4 ;
        slicePoints = 1:dim - 1 ; % slice along fourth dim
        y = vl_nnslice(x, dim, slicePoints, []) ;

        % check derivatives with numerical approximation
        dzdy = cellfun(@(x) test.randn(size(x)), y, 'Uni', 0) ;
        dzdx = vl_nnslice(x, dim, slicePoints, dzdy, 'inputSizes', {sz}) ;
        dzdy_ = cat(dim, dzdy{:}) ;
        dzdx_ = dzdx{1} ;
        test.der(@(x) forward_wrapper(x, dim, slicePoints), x, dzdy_, dzdx_, 1e-3*test.range) ;
    end
  end
end

% -----------------------------------------------------------------
function y = forward_wrapper(x, dim, slicePoints)
% -----------------------------------------------------------------
  y = vl_nnslice(x, dim, slicePoints, []) ;
  y = cat(dim, y{:}) ;
end


function [x,r,g,info] = spg_lasso(A,b,tau,varargin )
%SPG_LASSO  Solve the LASSO problem
%
%   SPG_LASSO is designed to solve the LASSO problem
%
%   (LASSO)  minimize  ||AX - B||_2  subject to  ||X||_1 <= tau,
%
%   where A is an M-by-N matrix, B is an M-vector, and TAU is a
%   nonnegative scalar.  In all cases below, A can be an explicit M-by-N
%   matrix or matrix-like object for which the operations  A*x  and  A'*y
%   are defined (i.e., matrix-vector multiplication with A and its
%   adjoint.)
%
%   Also, A can be a function handle that points to a function with the
%   signature
%
%   v = A(w,mode)   which returns  v = A *w  if mode == 1;
%                                  v = A'*w  if mode == 2.
%
%   X = SPG_LASSO(A,B,TAU) solves the LASSO problem.
%
%   X = SPG_LASSO(A,B,TAU,OPTIONS) specifies options that are set using
%   SPGSETPARMS.
%
%   [X,R,G,INFO] = SPG_LASSO(A,B,TAU,OPTIONS) additionally returns the
%   residual R = B - A*X, the objective gradient G = A'*R, and an INFO
%   structure.  (See SPGL1 for a description of this last output argument.)
%
%   See also spgl1, spgSetParms, spg_bp, spg_bpdn.

%   Copyright 2008, Ewout van den Berg and Michael P. Friedlander
%   http://www.cs.ubc.ca/labs/scl/spgl1
%   $Id: spg_lasso.m 1074 2008-08-19 05:24:28Z ewout78 $

if ~exist('tau','var'), tau = []; end
if ~exist('b','var') || isempty(b)
    error('Second argument cannot be empty.');
end
if ~exist('A','var') || isempty(A)
    error('First argument cannot be empty.');
end

sigma = [];
x0  = [];
[x,r,g,info] = spgl1(A,b,tau,sigma,x0,varargin{:});


function [Population,Dec,Mask,FrontNo,CrowdDis] = EnvironmentalSelection(Population,Dec,Mask,N)
% The environmental selection of SLMEA

%------------------------------- 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".
%--------------------------------------------------------------------------

    %% Delete duplicated solutions
    objs = Population.objs;
    objs = gather(objs);

    [objs,uni] = unique(objs,'rows');
    Population = Population(uni);
    Dec        = Dec(uni,:);
    Mask       = Mask(uni,:);
    N          = min(N,length(Population));
    %% Non-dominated sorting
    [FrontNo,MaxFNo] = NDSort(objs,gather(Population.cons),N);
    Next = FrontNo < MaxFNo;

    %% Calculate the crowding distance of each solution
    CrowdDis = CrowdingDistance(objs,FrontNo);

    %% Select the solutions in the last front based on their crowding distances
    Last     = find(FrontNo==MaxFNo);
    [~,Rank] = sort(CrowdDis(Last),'descend');
    Next(Last(Rank(1:N-sum(Next)))) = true;

    %% Population for next generation
    Population = Population(Next);
    FrontNo    = FrontNo(Next);
    CrowdDis   = CrowdDis(Next);
    Dec        = Dec(Next,:);
    Mask       = Mask(Next,:);
end


function plota(a,peval,savethis)
% plota(a,peval,savethis)

% figure
% plot(a','.:')
% xlabel('time');
% ylabel('a');
% grid on
% setfontsizefigure(12)
% if savethis
%     SaveImageFULL([peval.res_dir '/a'])
% end

figure
bar(mean(a,2))
hold on
errorbar(1:size(a,1), mean(a,2),std(a,[],2),'+r')
xlabel('component')
ylabel('mean(intensity)')
grid on
setfontsizefigure(12)
if savethis
    SaveImageFULL([peval.res_dir '/a_mean'])
end


function F = besselk(nu, F, scale, pref)
%BESSELK   Modified Bessel function of second kind of a CHEBFUN.
%   K = BESSELK(NU, F) computes the modified Bessel function of second kind
%   K_NU(F) of the nonzero CHEBFUN F. If F passes through the origin in its
%   domain, then an error is returned. The order NU need not be an integer but
%   must be real. The argument F can be complex.
%
%   K = BESSELK(NU, F, SCALE) returns a scaled K_NU(F) specified by SCALE:
%         0 - (default) is the same as BESSELK(NU, F),
%         1 - scales K_NU(F) by exp(F)).
%
%   K = BESSELK(NU, F, SCALE, PREF) uses the CHEBFUNPREF object PREF when
%   building the CHEBFUN K.
%
% See also AIRY, BESSELH, BESSELI, BESSELJ, BESSELY.
%
% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

if ( nargin < 4 )
    pref = chebfunpref();
end
if ( nargin < 3 )
    scale = 0;
end

% Loop over the columns:
for k = 1:numel(F)
    F(k) = columnBesselk(nu, F(k), scale, pref);
end

end

function g = columnBesselk(nu, f, scale, pref)

% Check for roots:
r = roots(f, 'nojump', 'nozerofun');
if ( numel(r) > 0 )
    error('CHEBFUN:CHEBFUN:besselk:zero', 'F has roots in its domain.');
end

% Compose:
g = compose(f, @(x) besselk(nu, x), pref);

% Scale (as described in help documentation):
if ( scale == 1 )
    scl = exp(f);
    g = scl.*g;
end

end


function H = cross(F, G)
%CROSS   Cross product of CHEBFUN3V objects.
%   CROSS(F, G) returns a CHEBFUN3V representing the 3D cross product of
%   the CHEBFUN3V objects F and G.

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

% Empty check:
if ( isempty(F) || isempty(G) )
    H = chebfun3v;
    return
end

% Get number of components:
Fc = F.components;
Gc = G.components;

if ( F.nComponents == 3 && G.nComponents == 3 )
    H = [ Fc{2} .* Gc{3} - Fc{3} .* Gc{2};
          Fc{3} .* Gc{1} - Fc{1} .* Gc{3};
          Fc{1} .* Gc{2} - Fc{2} .* Gc{1}];
else
    error('CHEBFUN:CHEBFUN3V:cross:components', ...
        'CHEBFUN3V objects must be both 3-vectors.');
end

end


clc
clear
close all

% To run this script we recommend running example2 first to create all the
% necessary outpouts from GLMsingle that are going to be reused here.

% This script shows how to find single-trial beta weights in the output of
% the GLMsingle. We will show how to average them to create one response
% to each condition rather then a response to each trial. This will produce
% one beta weight for each condition. Additionaly we will show how to
% calculatea t-statistic for each condition and a contrast between two
% example conditions in the fLoc experiment (number vs. face) using single
% trial betas.

% load design
load('./data/nsdflocexampledataset.mat')

figure(1);clf

%Show design matricies.
for d = 1:length(design)
    subplot(2,2,d)
    imagesc(design{d}); colormap gray; drawnow
    xlabel('Conditions')
    ylabel('TRs')
    title(sprintf('Design matrix for run%i',d))
end

% There are 10 differenet conditions in this dataset.

%%
% This NSD fLOC scan session has 6 repetitions of each condition per run.
% In the code below, we are attempting to locate the indices in the beta
% weight GLMsingle outputs modelmd(x,y,z,trials) that correspond to
% repeated conditions.

% Consolidate design matrices
designALL = cat(1,design{:});

% Construct a vector containing 1-indexed condition numbers in
% chronological order.

corder = [];
for p=1:size(designALL,1)
    if any(designALL(p,:))
        corder = [corder find(designALL(p,:))];
    end
end

% We will now find indices for each condition. First lets find all unique
% condition in the corder list

condition_list = unique(corder);

% We will now create a structure where each cell containst indices for
% different condition.

condition_ind = cell(length(condition_list),1);
for i = 1 : length(condition_list)

    condition_ind{i} =  find(corder == condition_list(i));

end

% Knowing the indicies of each condition we can now load an example output
% of GLMsingle and create 1 beta weight for each condition. In the example
% 1 there are 10 unique conditions.

results = load('./example2outputs/GLMsingle/TYPED_FITHRF_GLMDENOISE_RR.mat');
betas = results.modelmd;
sz = size(betas);
betas_average = zeros([sz(1) sz(2) sz(3) length(condition_ind),1]);

for i = 1 : length(condition_list)

    betas_average(:,:,:,i) = nanmean(betas(:,:,:,condition_ind{i}),4);

end

% Initially there were 240 betas (each of 10 conditions was repeated 24
% times.

fprintf('GLMsingle output had %i betas before averaging \n',size(betas,4))

% After averaging there is 1 beta weight for each condition

fprintf('GLMsingle output has %i betas after averaging \n',size(betas_average,4))

%% Calculate t-statistic for each condition
% We calculate t-stat as the mean over the standard deviation across all
% repetitions of the same condition.

t_stat =  zeros([sz(1) sz(2) sz(3) length(condition_ind),1]);

for n = 1 : length(condition_list)

    t_stat(:,:,:,n) = nanmean(betas(:,:,:,condition_ind{i}),4) ./ (std(betas(:,:,:,condition_ind{i}),[],4)./sqrt(length(condition_ind{i})));

end

%% Calculate a contrast between condition 2 (number) and condition 5 (adult face)

[~,p,~,stats] = ttest2(betas(:,:,:,condition_ind{2}),betas(:,:,:,condition_ind{5}),'dim',4);

%% Plot estiamted contrasts
slices = [20 10];

underlay = data{1}(:,:,:,1);

things2plot = {'t_stat';'stats.tstat'};

figure(1);clf
for f = 1 : length(things2plot)

    slice = slices(f);
    subplot(1,2,f)
    overlay  = eval(things2plot{f});
    overlay  = overlay(:,:,slice);

    brainmask = (overlay < -3 | overlay > 3);

    underlay_im = cmaplookup(underlay,min(underlay(:)),max(underlay(:)),[],gray(256));
    overlay_im  = cmaplookup(overlay,-4,4,[],cmapsign2);

    hold on
    imagesc(squeeze(underlay_im(:,:,slice,:)));
    imagesc(overlay_im,'AlphaData',brainmask);
    axis image
    axis off
    set(gca,'FontSize',14)
    title(sprintf('%s, slice = %i',things2plot{f},slice),'Interpreter','None')

    colormap(cmapsign2)
    c = colorbar;
    c.Ticks = [0 0.5 1];
    c.TickLabels = {'-3';'0';'3'};

end

% The t-statistic (t_stat) shows high values in the visual cortex while the
% t-test between two conditions shows positive voxels in more ventral and
% lateral portions of the brain.


function [y,deriv] = sum_ai_f_of_w_i(w,a,f,b)
% This is an MV2DF. See MV2DF_API_DEFINITION.readme.
%
% Does y = sum_i a_i f(w_i) + b, where f is non-linear.
%
%Notes:
%
%  f is a function handle, with behaviour as demonstrated in the test code
%  of this function.
%
%  b is optional, defaults to 0 if omitted

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

if ~exist('b','var')
    b = 0;
end

if isempty(w)
    y = @(w)sum_ai_f_of_w_i(w,a,f,b);
    return;
end

if isa(w,'function_handle')
    outer = sum_ai_f_of_w_i([],a,f,b);
    y = compose_mv(outer,w,[]);
    return;
end

ntot = length(a);
nz = find(a~=0);
a = a(nz);

if nargin==1
    y = f(w(nz));
else
    [y,dfdw,f2] = f(w(nz));
    deriv = @(Dy) deriv_this(Dy,dfdw.*a,f2,a,nz,ntot);
end
y = y(:);
y = a.'*y + b;

function [g,hess,linear] = deriv_this(Dy,g0,f2,a,nz,ntot)
g = zeros(ntot,1);
g(nz) = Dy*g0(:);
hess = @(d) hess_this(d,g0,f2,Dy,a,nz,ntot);
linear = false;

function [h,Jd] = hess_this(d,g0,f2,Dy,a,nz,ntot)
d = d(nz);
hnz = f2();
hnz = hnz(:).*d(:);
h = zeros(ntot,1);
h(nz) = Dy*(hnz.*a);
if nargout>1
    Jd = g0.'*d(:);
end

function [y,ddx,f2] = test_f(x)
y = log(x);
if nargout>1
    ddx = 1./x;
    f2 = @() -1./(x.^2);
end

function test_this()
n = 10;
a = randn(n,1);
a = bsxfun(@max,a,0);
b = 5;
f = sum_ai_f_of_w_i([],a,@(x)test_f(x),b);

w = 1+rand(n,1);
test_MV2DF(f,w);


% MVNORMRND - Multivariate Normal - Random Number Generation
% Copyright (c) 1998, Harvard University. Full copyright in the file Copyright
%
% Y = mvnormrnd(mu, sigma, n)
%
%   mu = p by 1 mean column vector or n by p matrix of means
%   sigma = covariance matrix
%   n = number of observations to generate
%
%   Y = an n by p matrix of row vectors with mean mu and covariance sigma
%
% Note: works slightly different from Matlab builtin MVNRND.
%
%   if mu is a column vector, n rows will be returned, all with mean mu
%
%   if mu is a matrix, a matrix of the same size will be returned with
%   row Y(i,:) having mean mu(i,:) .
%
% See also: MVNORMPDF, MVNORMLPR

function [Y] = mvnormrnd (mu,sigma,n)

[d1,d2] = size(mu);
S = chol(sigma)';

if d2==1,
  % then mu is a column vector
  X = normrnd(0,1,n,d1);
  Y = X*S' + ones(n,1)*mu' ;
else
  X = normrnd(0,1,d1,d2);
  Y = X*S' + mu ;
end


%==============================================================================
% This code is part of the Matlab-based toolbox
% LagLDDDM - A Lagrangian Gauss--Newton--Krylov Solver for Mass- and
%                        Intensity-Preserving Diffeomorphic Image Registration
%
% For details and license info see
% - https://github.com/C4IR/FAIR.m/tree/master/add-ons/LagLDDMM
%
% function [Sc,dS,d2S] = curvatureST(uc,omega,m,varargin)
%
% Matrix-free spatio-temporal curvature regularization energy for vc
% where vc is cell-centered
%
% Sv) = 0.5 * \int_{\omega}\int_0^1
%               alpha(1)*v(x,t)'*A*v(x,t)+ alpha(2)*v(x,t)'*B*v(x,t) dx dt,
%
% where A is the curvature operator and B the first-order time derivative
% operator.
%
% Input:
%
%   vc          instationary velocity field (cell-centered)
%   omega       spatial domain
%   m           number of discretization points in space
%   varargin    optional parameters (see below)
%
% Optional Input:
%   tspan       time span (default: [0 1])
%   nt          number of time points for velocity
%
%
% Output:
%
%   Sc          current value  (0.5 * hd * uc'* A *uc)
%   dS          derivative     (hd * uc'*A )
%   d2S         Hessian        A
%  if ~matrixFree,  d2S is sparse matrix; else, d2S is struct; endif
%
% see also curvature.m
% ==================================================================================

function [Sc,dS,d2S] = mbCurvatureST(vc,omega,m,varargin)
if nargin == 0
    help(mfilename);
    return;
end

if strcmp(vc,'para')
    Sc = 'cell-centered';       % grid
    dS = 0;                     % matrixFree
    d2S = 'pcg';  % solver
    return;
end

persistent A omegaOld mOld alphaOld ntOld tspanOld

if ~exist('mOld','var'),     mOld = [];     end;
if ~exist('omegaOld','var'), omegaOld = []; end;
if ~exist('alphaOld','var'), alphaOld = []; end;

alpha       = [1 1e-3];
tspan       = [0 1];
nt          = [];
for k=1:2:length(varargin), % overwrites default parameter
    eval([varargin{k},'=varargin{',int2str(k+1),'};']);
end;

dim = numel(omega)/2;

if isempty(nt), % roughly estimate nt
    nt = round(numel(vc)/(prod(m)*dim))-1;
end

    build =  isempty(mOld) || isempty(omegaOld) ...
        || length(mOld) ~= length(m) || length(omegaOld) ~= length(omega) ...
        || any(mOld ~= m) || any(omegaOld~=omega)|| any(alphaOld~=alpha) || any(tspanOld~=tspan) || any(ntOld~=nt);
    if build,
        fprintf('%s - rebuilding op\n',mfilename);
        A = getCurvatureMatrixST(omega,tspan,m,nt,alpha);
        A = A'*A;
        mOld = m; omegaOld = omega; alphaOld = alpha; ntOld = nt; tspanOld = tspan;
    end;
    dS  = vc'*A;
    Sc  = 0.5*dS*vc;
    d2S = A;

function C = getCurvatureMatrixST(omega,tspan,m,nt,alpha)

h   = (omega(2:2:end)-omega(1:2:end))./m;
hd  = prod(h);
% compute time-stepsize
dt = abs(tspan(2)-tspan(1))/nt;

% build gradient matrix for one transformation
C =  getCurvatureMatrix(omega,m);
a = sqrt(alpha(1).*hd.*dt*[1/2;ones(nt-1,1);1/2]);
% apply spatial regularization to all transformations and sum up in
% time
C =  kron(sdiag(a(:)),C);

% get time regularization matrix
if alpha(2)>0
    b = sqrt(alpha(2)*hd.*dt);
    Bt = b * getTimeDiffusionMatrix(nt,dt,prod(m),length(omega)/2);
    C  = [C;Bt];
end

function D = sdiag(v)
D = diag(sparse(v(:)));

function A = getTimeDiffusionMatrix(nt,dt,n,dim)
Dt=spdiags(ones(nt+1,1)*[-1/dt 1/dt],0:1,nt,nt+1);
A = kron(Dt, speye(n*dim)); % 2nd deriveative over time for two components


function e = mohsst5_rmsew(Y, Yh)

Z = Y-Yh;
I = ~isnan(Z);

% Weight proportional to area size
load('mohsst5_data.mat', 'latitude', 'longitude');
%[lat,lon] = meshgrid(latitude, longitude);
[lon,lat] = meshgrid(longitude, latitude);
W = repmat(cosd(lat(:)), [1, size(Y,2)]);

e = rmsew(Z(I), W(I));


function [mps] = ftps2mps(ftps)
% Convert speed from feet per second to meters per hour
mps = ftps*0.3048 ;


function [Im]=Walsh_DWT_Decoding(Header)
%Walsh-Harmard Transform with Tow level Discrete Wavelete Transform for image Decompression
% Designed by  Mohammed M. Siddeq
% Date 2012-2-22
% Email :- mamadmmx76@yahoo.com
%
% this program is used for Decompress grayscale images by using :
% INPUT\  Header : this parameter contains all infmration about compressed file
%
%OUTPUT\  Im : Decoded image from "Header"

% --- Very important for you ----------------------------------------------
%Befroe apply this function you need the following programs:
% 1- "Arith_code.m" and "Arith_Decode.m"
% 2- "Walsh2D_Transform.m"
%Note\ these programs free for download from the following website:
%     www.MathWorks.com  -> Auther = Siddeq

%--------------------------------------------------------------------------
% Example (1) --- for compression grayscale images-------------------------
%    I = imread('D:\images\image1.bmp'); % read an image
%    [Header]=Walsh_DWT_Coding(I,[0.025, 0.025],'db3',2); % Apply function
%
%
%    [Im]=Walsh_DWT_Decoding(Header); % for decoding;
%    imshow(uint8(Im)); % show final decoded image

% Example (2) -------------------------------------------------------------
%    I = imread('D:\images\imageG.bmp'); %-> read an image
%    [Header]=Walsh_DWT_Coding(I,[0.025, 0.025],'db5',3); %-> Apply function
%    save('C:\imageG.WWT', 'Header'); -> save compressed file....
%
%   X=load('C:\imageG.WWT', '-mat'); %-> load compressed file....
%   H=X.Header;
%   Im=Walsh_DWT_Decoding(H); %-> for decoding;
%   imshow(Im); %-> show final decoded image
%
%----------------------------------- Good Luck -------------------------

%--Read Header file for Decoding.....
S_2=double(Header(1).S_2);
S_=double(Header(2).S_);
Code_Arr=double(Header(3).Code_Arr);
Arr_H1=double(Header(4).Arr_H1);
Arr_H2=double(Header(5).Arr_H2);
Code_Data1=double(Header(6).Code_Data1);
Data1_H1=double(Header(7).Data1_H1);
Data1_H2=double(Header(8).Data1_H2);
Code_Data2=double(Header(9).Code_Data2);
Data2_H1=double(Header(10).Data2_H1);
Data2_H2=double(Header(11).Data2_H2);
Code_Data3=double(Header(12).Code_Data3);
Data3_H1=double(Header(13).Data3_H1);
Data3_H2=double(Header(14).Data3_H2);
DC_Values=double(Header(15).DC_Values);
M=double(Header(16).M);
Para=double(Header(17).Para);
F1=double(Header(18).F1);
F2=double(Header(19).F2);
wave_name=Header(20).wave_name;
%---------------------------------------------------------------

Arr_Size=8; %window size 2x2 or 4x4 or 8x8 used by Walsh-Transformed ................

%--------Compute the Quantization Matrix
Q(1:Arr_Size,1:Arr_Size)=1; % initilize quantization matrix........
L=M.*F1;
for i=1:Arr_Size
    for j=1:Arr_Size
        Q(i,j)=round((L)+(i+j).*Para);
    end;
end;

%----------Using Arihtmetic Decoding for extract original data.....
[Arr]=Arith_Decode(Code_Arr,Arr_H1,Arr_H2); % Low-Freqeuncy Decoding...

% High-Frequency Decoding......................................
if (Code_Data1==0)
  Data1(1:S_(1)*S_(2))=0;
else
  [Data1]=Arith_Decode(Code_Data1,Data1_H1,Data1_H2);
end;

if (Code_Data2==0)
 Data2(1:S_(1)*S_(2))=0;
else
 [Data2]=Arith_Decode(Code_Data2,Data2_H1,Data2_H2);
end;

if (Code_Data3==0)
  Data3(1:S_(1)*S_(2))=0;
else
  [Data3]=Arith_Decode(Code_Data3,Data3_H1,Data3_H2);
end;
%-------------------------------------------------------------------------

%Retrun "SAVE_" matrix from one-dimensional array "Arr"
POS=1;
SAVE_(1:S_2(1),1:S_2(2))=0;
sizeofArr=size(Arr);
for j=1:S_2(2)
  if (POS<=sizeofArr(2)) % to be ensure the postions is not exceeding
    for i=1:S_2(1)
      if (POS<=sizeofArr(2)) % to be ensure again not exceeding
        SAVE_(i,j)=Arr(POS);
      end;
      POS=POS+1;
    end;
  end;
end;

% Return "DC_Values" to matrix "SAVE_".....
SAVE_(1:S_2(1),1)=DC_Values(1:S_2(1));

% Deocde - HH2
% Return all original data from array
k=1;

for j=1:S_(2)
    for i=1:S_(1)
        HH2(i,j)=Data3(k);
        k=k+1;
    end;
end;
%-----------------------------------------------------------------------
% Decode HL2
% Return all original data from array
k=1;
for j=1:S_(2)
    for i=1:S_(1)
        HL2(i,j)=Data2(k);
        k=k+1;
    end;
end;
%-----------------------------------------------------------------------
% Decode LH2
% Return all original data from array
k=1;
for j=1:S_(2)
    for i=1:S_(1)
        LH2(i,j)=Data1(k);
        k=k+1;
    end;
end;

%------------------- Reconstruct "LL2" from matrix "SAVE_"
L=1;i=1;
while (i<=S_(1))
    j=1;
    while(j<=S_(2))
        Z=1;
        for k1=1:Arr_Size
            for k2=1:Arr_Size
                T(k1,k2)=SAVE_(L,Z);
                Z=Z+1;
            end;
        end;
        L=L+1;
        %------Apply inverse Quantization and inverse Walsh Transform------
        T=T.*Q;
        X=Walsh2D_Transform(T,Arr_Size,'i');
        D(i:i+Arr_Size-1,j:j+Arr_Size-1)=X(1:Arr_Size,1:Arr_Size);
        j=j+Arr_Size;
    end;
    i=i+Arr_Size;
end;
%-------------------------------------------------------------------------

%Adjustment for D matrix to be same size alike "LH2" or others
RELL(1:S_(1),1:S_(2))=D(1:S_(1),1:S_(2));
%RELL=RELL.*1
% Apply inverse Quantization for each sub-band (just high-Freqeuncy)
LH2=round(LH2.*(M*F2)); HL2=round(HL2.*(M.*F2)); HH2=round(HH2.*(M.*F2));

% Inverse -Wavelet Transform Stage-1
S_=size(LH2); LL2=0;
LL2(1:S_(1),1:S_(2))=RELL(1:S_(1),1:S_(2));
L1=idwt2(LL2,LH2,HL2,HH2,wave_name);
L1=L1*Para;
% Inverse -Wavelet Transform Stage-2
S_=size(L1);
HL(1:S_(1),1:S_(2))=0; % all main sub-bands are zeros

%L=0;
%L(1:S_(1),1:S_(2))=L1(1:S_(1),1:S_(2));

Im=idwt2(L1,HL,HL,HL,wave_name);% Decoded image
Im=uint8(Im);
'Decompression ..OK'
end


function [w, infos] = sag(problem, in_options)
% Stochastic average descent (SAG) algorithm.
%
% Inputs:
%       problem     function (cost/grad/hess)
%       in_options  options
% Output:
%       w           solution of w
%       infos       information
%
% References:
%       N. L. Roux, M. Schmidt, and F. R. Bach,
%       "A stochastic gradient method with an exponential convergence rate for finite training sets,"
%       NIPS, 2012.
%
% This file is part of SGDLibrary.
%
% Created by H.Kasai on Feb. 15, 2016
% Modified by H.Kasai on Mar. 25, 2018

    % set dimensions and samples
    d = problem.dim();
    n = problem.samples();

    % set local options
    local_options.sub_mode = 'SAG';

    % merge options
    options = mergeOptions(get_default_options(d), local_options);
    options = mergeOptions(options, in_options);

    % initialize
    total_iter = 0;
    epoch = 0;
    grad_calc_count = 0;
    w = options.w_init;
    num_of_bachces = floor(n / options.batch_size);

    % prepare an array of gradients, and a valiable of average gradient
    grad_array = zeros(d, num_of_bachces);
    grad_ave = mean(grad_array, 2);

    % store first infos
    clear infos;
    [infos, f_val, optgap] = store_infos(problem, w, options, [], epoch, grad_calc_count, 0);

    % display infos
    if options.verbose > 0
        fprintf('%s: Epoch = %03d, cost = %.16e, optgap = %.4e\n', options.sub_mode, epoch, f_val, optgap);
    end

    % set start time
    start_time = tic();

    % permute samples (ToDo)
    perm_idx = 1:n;

    % main loop
    while (optgap > options.tol_optgap) && (epoch < options.max_epoch)

        for j = 1 : num_of_bachces

            % update step-size
            step = options.stepsizefun(total_iter, options);

            % calculate gradient
            start_index = (j-1) * options.batch_size + 1;
            indice_j = perm_idx(start_index:start_index+options.batch_size-1);
            grad = problem.grad(w, indice_j);

            % update average gradient
            if strcmp(options.sub_mode, 'SAG')
                grad_ave = grad_ave + (grad - grad_array(:, j)) / num_of_bachces;
            else % SAGA
                grad_ave = grad_ave + (grad - grad_array(:, j));
            end
            % replace with new grad
            grad_array(:, j) = grad;

            % update w
            w = w - step * grad_ave;

            % proximal operator
            if ismethod(problem, 'prox')
                w = problem.prox(w, step);
            end

            total_iter = total_iter + 1;
        end

        % measure elapsed time
        elapsed_time = toc(start_time);

        % count gradient evaluations
        grad_calc_count = grad_calc_count + num_of_bachces * options.batch_size;
        epoch = epoch + 1;

        % store infos
        [infos, f_val, optgap] = store_infos(problem, w, options, infos, epoch, grad_calc_count, elapsed_time);

        % display infos
        if options.verbose > 0
            fprintf('%s: Epoch = %03d, cost = %.16e, optgap = %.4e\n', options.sub_mode, epoch, f_val, optgap);
        end
    end

    if optgap < options.tol_optgap
        fprintf('Optimality gap tolerance reached: tol_optgap = %g\n', options.tol_optgap);
    elseif epoch == options.max_epoch
        fprintf('Max epoch reached: max_epochr = %g\n', options.max_epoch);
    end
end


function res = isign(x)
%ISIGN        Interval sign, internal function for slope abs
%

%sign of interval array:
%  +1      for x>=0
%  -1      for x<=0
%  [-1,1]  for 0 in x

% written  12/06/98     S.M. Rump
% modified 12/27/02     S.M. Rump  resinf,ressup changed to type double: fix of Matlab 6.5 discrepancy to 6.0
%

  xinf = inf(x);
  xsup = sup(x);
  resinf = double( xinf>=0 );
  resinf(xsup<=0) = -1;
  ressup = resinf;
  index = ( xinf<0 ) & ( xsup>0 );
  if any(index(:))
    resinf(index) = -1;
    ressup(index) = 1;
  end
  res = infsup(resinf,ressup);


%% stochasticMicrostructure
% Below is a demonstration of the features of the |stochasticMicrostructure| function

%%
clear; close all; clc;

%% Syntax
% |[F,V,C]=stochasticMicrostructure(inputStruct);|

%% Description
% This function generates Stochastic Bicontinuous Microstructures
%
% Input structure and default values:
%
%   inputStruct.L=1; % characteristic length
%   inputStruct.Ns=80; % number of sampling points
%   inputStruct.Nw=120; % number of waves
%   inputStruct.q0=55; % wave number
%   inputStruct.relD=0.5; % relative density
%   inputStruct.anisotropyFactors=[1 1 1]; %Anisotropy factors
%   inputStruct.isocap=1; %Option to cap the isosurface
%
% Based on: Soyarslan et al. "3D stochastic bicontinuous
% microstructures: Generation, topology and elasticity"
% https://doi.org/10.1016/j.actamat.2018.01.005
%
% Original author: Sebastien Callens, September 2020

%% Examples

%%
% Plot settings
cMap=parula(250);
faceAlpha1=1;
faceAlpha2=0.5;
edgeColor1='none';
edgeColor2='none';
fontSize=15;

%% Example 1
inputStruct.L=1; % characteristic length
inputStruct.Ns=75; % number of sampling points
inputStruct.Nw=500; % number of waves
inputStruct.q0=55; % wave number
inputStruct.relD=0.55; % relative density
inputStruct.anisotropyFactors=[1 1 1]; %Anisotropy factors
inputStruct.isocap=1; %Option to cap the isosurface

%%
% Create stochastic structure

[F,V,C]=stochasticMicrostructure(inputStruct);

%%
% Using grouping to keep only largest group
groupOptStruct.outputType='label';
[G,~,groupSize]=tesgroup(F,groupOptStruct); %Group connected faces
[~,indKeep]=max(groupSize); %Index of largest group

%Keep only largest group
F=F(G==indKeep,:); %Trim faces
C=C(G==indKeep,:); %Trim color data
[F,V]=patchCleanUnused(F,V); %Remove unused nodes

%%
% Visualize surface

cFigure;
gpatch(F,V,C,'none');
axisGeom; camlight headlight;
colormap gjet; icolorbar;
gdrawnow;

%%
%
% <<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 ei_values_test ( )

%*****************************************************************************80
%
%% EI_VALUES_TEST demonstrates the use of EI_VALUES.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 February 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'EI_VALUES_TEST:\n' );
  fprintf ( 1, '  EI_VALUES stores values of\n' );
  fprintf ( 1, '  the exponential integral function EI(X).\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      X          EI(X)\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, x, fx ] = ei_values ( n_data );

    if ( n_data == 0 )
      break
    end

    fprintf ( 1, '  %12f  %24.16f\n', x, fx );

  end

  return
end


%GETRECTSUBPIX  Retrieves a pixel rectangle from an image with sub-pixel accuracy
%
%     dst = cv.getRectSubPix(src, patchSize, center)
%     dst = cv.getRectSubPix(..., 'OptionName',optionValue, ...)
%
% ## Input
% * __src__ Source image, 8-bit integer or 32-bit floating-point, 1- or
%   3-channels.
% * __patchSize__ Size of the extracted patch `[w,h]`.
% * __center__ Floating-point coordinates of the center of the extracted
%   rectangle within the source image. The center `[x,y]` must be inside the
%   image.
%
% ## Output
% * __dst__ Extracted patch that has the size `PatchSize`, the same number of
%   channels as `src`, and the specified type in `PatchType`.
%
% ## Options
% * __PatchType__ Depth of the extracted pixels. By default (-1), they have
%   the same depth as `src`. Supports either `uint8` or `single`.
%
% The function cv.getRectSubPix extracts pixels from `src`:
%
%     dst(x,y) = src(x + center(1) - (size(dst,2)-1)*0.5,
%                    y + center(2) - (size(dst,1)-1)*0.5)
%
% where the values of the pixels at non-integer coordinates are retrieved
% using bilinear interpolation. Every channel of multi-channel images is
% processed independently. Also the image should be a single channel or three
% channel image. While the center of the rectangle must be inside the image,
% parts of the rectangle may be outside. In this case, the pixel values
% outside of the image are extrapolated.
%
% See also: cv.Rect.crop, cv.warpAffine, cv.warpPerspective
%


function stats = rmanova2(data,alpha,doplot,ttst)
%
%Repeated-measures two-way ANOVA
%
% :Usage:
% ::
%
%     stats = rmanova2(data,[alpha],[doplot],[ttst]);
%
% :Inputs:
%
%   **data:**
%        can be one of two formats:
%        1. Cell array - each row represents a level of factor 1, and
%           each column represents a level of factor 2. Each cell contains a
%           vector of values of the dependent variable for each subject.
%        2. Matrix - each row represents a trial, with the following
%           columns:
%             - column1 - dependent variable
%             - column2 - grouping variable for subject
%             - column3 - grouping variable for factor 1
%             - column4 - grouping variable for factor 2
%
%   **alpha:**
%        (optional) p-value threshold (default: 0.05)
%
%   **doplot:**
%        (optional) if 1, will produce a line plot.
%                       Works only for cell input data (default: 1)
%
%   **ttst:**
%        (optional) if 1, will perform pairwise t-tests (default: 0)
%
% ..
%    Aaron Schurger (2005.02.04)
%    Derived from Keppel & Wickens (2004) "Design and Analysis" ch. 18
%    Modified by Sam Gershman (2006.11.16)
% ..

if nargin < 2; alpha = 0.05; doplot = 0; ttst = 0; end
if nargin < 3; doplot = 1;  ttst = 0; end
if nargin < 4; ttst = 0; end

if iscell(data);
    Y = []; S = []; F1 = []; F2 = [];
    [m n] = size(data);
    for i = 1:m;
        for j = 1:n;
            Y = cat(1,Y,data{i,j});
            nsubs = length(data{i,j});
            S = cat(2,S,1:nsubs);
            F1 = cat(1,F1,zeros(nsubs,1)+i);
            F2 = cat(1,F2,zeros(nsubs,1)+j);
        end
    end
    S = S';
else
    Y = data(:,1);
    S = data(:,2);
    F1 = data(:,3); F2 = data(:,4);
    clear data
    su = unique(S); f1u = unique(F1); f2u = unique(F2);
    for a = 1:length(f1u);
        for b = 1:length(f2u);
            ii = intersect(find(F1==f1u(a)),find(F2==f2u(b)));
            d = [Y(ii) S(ii)];
            d = sortrows(d,2);
            data{a,b} = d(:,1);
        end
    end
end

F1_lvls = unique(F1);
F2_lvls = unique(F2);
Subjs = unique(S);

a = length(F1_lvls); % # of levels in factor 1
b = length(F2_lvls); % # of levels in factor 2
n = length(Subjs); % # of subjects

INDS = cell(a,b,n); % this will hold arrays of indices
CELLS = cell(a,b,n); % this will hold the data for each subject X condition
MEANS = zeros(a,b,n); % this will hold the means for each subj X condition

% Calculate means for each subject X condition.
% Keep data in CELLS, because in future we may want to allow options for
% how to compute the means (e.g. leaving out outliers > 3stdev, etc...).
for i=1:a % F1
    for j=1:b % F2
        for k=1:n % Subjs
            INDS{i,j,k} = find(F1==F1_lvls(i) & F2==F2_lvls(j) & S==Subjs(k));
            CELLS{i,j,k} = Y(INDS{i,j,k});
            MEANS(i,j,k) = mean(CELLS{i,j,k});
        end
    end
end

% make tables (see table 18.1, p. 402)
AB = reshape(sum(MEANS,3),a,b); % across subjects
AS = reshape(sum(MEANS,2),a,n); % across factor 2
BS = reshape(sum(MEANS,1),b,n); % across factor 1

A = sum(AB,2); % sum across columns, so result is ax1 column vector
B = sum(AB,1); % sum across rows, so result is 1xb row vector
S = sum(AS,1); % sum across columns, so result is 1xs row vector
T = sum(sum(A)); % could sum either A or B or S, choice is arbitrary

% degrees of freedom
dfA = a-1;
dfB = b-1;
dfAB = (a-1)*(b-1);
dfS = n-1;
dfAS = (a-1)*(n-1);
dfBS = (b-1)*(n-1);
dfABS = (a-1)*(b-1)*(n-1);

% bracket terms (expected value)
expA = sum(A.^2)./(b*n);
expB = sum(B.^2)./(a*n);
expAB = sum(sum(AB.^2))./n;
expS = sum(S.^2)./(a*b);
expAS = sum(sum(AS.^2))./b;
expBS = sum(sum(BS.^2))./a;
expY = sum(Y.^2);
expT = T^2 / (a*b*n);

% sums of squares
ssA = expA - expT;
ssB = expB - expT;
ssAB = expAB - expA - expB + expT;
ssS = expS - expT;
ssAS = expAS - expA - expS + expT;
ssBS = expBS - expB - expS + expT;
ssABS = expY - expAB - expAS - expBS + expA + expB + expS - expT;
ssTot = expY - expT;

% mean squares
msA = ssA / dfA;
msB = ssB / dfB;
msAB = ssAB / dfAB;
msS = ssS / dfS;
msAS = ssAS / dfAS;
msBS = ssBS / dfBS;
msABS = ssABS / dfABS;

% f statistic
fA = msA / msAS;
fB = msB / msBS;
fAB = msAB / msABS;

% p values
pA = 1-fcdf(fA,dfA,dfAS);
pB = 1-fcdf(fB,dfB,dfBS);
pAB = 1-fcdf(fAB,dfAB,dfABS);

% return values
 stats.SS1 = ssA;
 stats.df1 = dfA;
 stats.MS1 = msA;
 stats.F1 = fA;
 stats.P1 = pA;
 stats.SS2 = ssB;
 stats.df2 = dfB;
 stats.MS2 = msB;
 stats.F2 = fB;
 stats.P2 = pB;
 stats.SS12 = ssAB;
 stats.df12 = dfAB;
 stats.MS12 = msAB;
 stats.F12 = fAB;
 stats.P12 = pAB;

 stats.alpha = alpha;

 %decision rule
if stats.P1 < alpha; stats.significant1 = 'Yes'; else; stats.significant1 = 'No'; end;
if stats.P2 < alpha; stats.significant2 = 'Yes'; else; stats.significant2 = 'No'; end;
if stats.P12 < alpha; stats.significant12 = 'Yes'; else; stats.significant12 = 'No'; end;

%make line plots
if doplot
    anova_line_plot(data);

%     [m n] = size(data); plotcounter = 0;
%     figure;
%     for i = 1:m;
%         for j = 1:n;
%             plotcounter = plotcounter + 1;
%             subplot(m,n,plotcounter);
%             boxplot(data{i,j});
%             xlabel([num2str(i),',',num2str(j)]);
%             set(gca,'XTickLabel',[]);
%         end
%     end
end

%pairwise t-tests
if ttst;
    disp('Performing post-hoc t-tests...');
    tcounter = 0; a = 0; b = 0;
    [m n] = size(data);
    for t1 = 1:m;
        for t2 = 1:n;
            a = a + 1; b = 0;
            for t3 = 1:m;
                for t4 = 1:n;
                    b = b + 1;
                    if b > a;
                        tcounter = tcounter + 1;
                        [h,p,ci,stat] = ttest(data{t1,t2},data{t3,t4});
                        stats.ttests(tcounter).P = p;
                        stats.ttests(tcounter).comparison = [num2str(t1),',',num2str(t2),' > ',num2str(t3),',',num2str(t4)];
                        stats.ttests(tcounter).means = [mean(data{t1,t2}) mean(data{t3,t4})];
                        stats.ttests(tcounter).ci = ci';
                    end
                end
            end
        end
    end
end

end

function anova_line_plot(anova_dat)

    if ~iscell(anova_dat)
        error('For line plots, enter cells rather than matrix input!');
    end

for i = 1:size(anova_dat, 1)
for j = 1:size(anova_dat, 2)
linedat(i, j) = nanmean(anova_dat{i, j});
lineste(i, j) = ste(anova_dat{i, j});
end
end

% Transpose so F2 is on X-axis, F1 is lines
linedat = linedat';
lineste = lineste';

create_figure('Lines');

plot(linedat, 'o-', 'LineWidth', 3, 'MarkerSize', 12, 'MarkerFaceColor', [.5 .5 .5])

set(gca, 'XLim', [.5 size(anova_dat, 2)+.5], 'XTick', [1:size(anova_dat, 2)]); xlabel('Factor 2');

for j = 1:size(anova_dat, 2), f1names{j} = ['F1: Level ' num2str(j)]; end

legend(f1names)

end


% Show basic use of spm_mlm_bayes

clear all
close all

N=100;
d=2;
p=3;

y=randn(N,d);
x=randn(N,p);
verbose=1;

mlm = spm_mlm_bayes (y,x,'input',verbose);

figure
imagesc(mlm.wmean);
colorbar
ylabel('Inputs');
xlabel('Outputs');
colormap(gray);

disp(sprintf('Model evidence = %1.2f', mlm.fm));


clear all; clc; close all;

OpenBMI('C:\Users\CVPR\Desktop\Open_Github') % Edit the variable BMI if necessary
global BMI;
BMI.EEG_DIR=['G:\data2'];

%% DATA LOAD MODULE
file=fullfile(BMI.EEG_DIR, '\2016_08_05_hkkim_training');
marker= {'1','right';'2','left';'3','foot';'4','rest'};
[EEG.data, EEG.marker, EEG.info]=Load_EEG(file,{'device','brainVision';'marker', marker;'fs', 500});

field={'x','t','fs','y_dec','y_logic','y_class','class', 'chan'};
CNT=opt_eegStruct({EEG.data, EEG.marker, EEG.info}, field);
CNT=prep_selectClass(CNT,{'class',{'right', 'rest'}});

CNT2 = prep_laplacian(CNT, {'Channel', {'C3', 'Cz', 'C4'}})

%% CROSS-VALIDATION MODULE
CV.var.band=[7 20];
CV.var.interval=[750 3500];
CV.prep={ % commoly applied to training and test data before data split
    'CNT=prep_filter(CNT, {"frequency", band})'
    'SMT=prep_segmentation(CNT, {"interval", interval})'
    };
CV.train={
    '[SMT, CSP_W, CSP_D]=func_csp(SMT,{"nPatterns", [3]})'
    'FT=func_featureExtraction(SMT, {"feature","logvar"})'
    '[CF_PARAM]=func_train(FT,{"classifier","LDA"})'
    };
CV.test={
    'SMT=func_projection(SMT, CSP_W)'
    'FT=func_featureExtraction(SMT, {"feature","logvar"})'
    '[cf_out]=func_predict(FT, CF_PARAM)'
    };
CV.option={
'KFold','7'
% 'leaveout'
};

[loss]=eval_crossValidation(CNT, CV); % input : eeg, or eeg_epo


function [params, names] = ardKernExtractParam(kern)

% ARDKERNEXTRACTPARAM Extract parameters from the ARD kernel structure.
% FORMAT
% DESC Extract parameters from the pre-built RBF and linear ARD
% kernel structure into a vector of parameters for optimisation.
% ARG kern : the kernel structure containing the parameters to be
% extracted.
% RETURN param : vector of parameters extracted from the kernel. If
% the field 'transforms' is not empty in the kernel matrix, the
% parameters will be transformed before optimisation (for example
% positive only parameters could be logged before being returned).
%
% FORMAT
% DESC Extract parameters and names of parameters from the
% pre-built RBF and linear ARD kernel structure.
% ARG kern : the kernel structure containing the parameters to be
% extracted.
% RETURN param : vector of parameters extracted from the kernel. If
% the field 'transforms' is not empty in the kernel matrix, the
% parameters will be transformed before optimisation (for example
% positive only parameters could be logged before being returned).
% RETURN names : celly array of strings containing parameter names.
%
% SEEALSO ardKernParamInit, ardKernExpandParam, kernExtractParam, scg, conjgrad
%
% COPYRIGHT : Neil D. Lawrence, 2004
%
% KERN

params = [kern.inverseWidth kern.rbfVariance ...
          kern.biasVariance kern.whiteVariance ...
          kern.linearVariance kern.inputScales];
if nargout > 1
  names{1} = 'ard inverse width';
  names{2} = 'ard rbf variance';
  names{3} = 'ard bias variance';
  names{4} = 'ard white variance';
  names{5} = 'ard linear variance';
  for i = 1:length(kern.inputScales)
    names{5+i} = ['ard input scale ' num2str(i)];
  end
end


function [lh_AR, varx] = ARMLfit(rcs,ng,xg,rc0,lag_max)

% The conditional-likelihood fit.
%
%   rcs = tan(.5*pi*rc)
%   In this way, the reflection coefficient [-1,+1] is mapped to
%   [-Inf,+Inf], allowing the use of unconstrained optimization.

%   S. de Waele, August 2001.

rc = 2/pi*atan(rcs);
if any(~isreal(rc)),lh_AR = +Inf; return; end
nseg = length(xg);
npre = length(rcs)+length(rc0);
a = rc2arset([1 rc0 rc]);
%cor = par2cor(a,lag_max+1);
cor = arma2cor(a,1,lag_max);

sum_s = 0;     %The squared error in the exponent of the normal distribution
     		   %without varx and the factor -.5;
sum_lnd = 0;   %contribution of the log of the determinant without varx and the factor .5;
nobs_used = 0;

for seg = 1:nseg,
    nc = ng{seg};
    if any(floor(nc)~=nc), error('Times must contain only integers.'), end
    xc = xg{seg};
    nobsc = length(nc);
    nobs_used = nobs_used + nobsc;

    obs_start = 1;
    if obs_start == 1,
        obs = 1;
        sum_s = sum_s+xc(1)^2;
        sum_lnd= sum_lnd+log(1);
    end
    for obs = max(2,obs_start):nobsc
        nprev_a = min(obs-1,lag_max); %nprev_a = available previous observations
        it=find(nc(obs)-nc(obs-1:-1:obs-nprev_a)<lag_max+1);
        nprev_a=length(it);
        if nprev_a
            n1 = nc(obs:-1:obs-nprev_a)*ones(1,nprev_a+1);
            n2 = ones(nprev_a+1,1)*nc(obs:-1:obs-nprev_a)';
            lags = abs(n1-n2);
            Rn = cor(1+lags);
            %Notations as in Random signals, K.S. Shanmugan and A.M. Breipohl, p.51.
            x1 = xc(obs);
            x2 = xc(obs-1:-1:obs-nprev_a);
            Rn11 = 1;
            Rn12 = Rn(1,2:end);
            Rn21 = Rn(2:end,1);
            Rn22 = Rn(2:end,2:end);
            muc = Rn12*(Rn22\x2);       % = Conditional mean of x1 given x2
            Rnc = 1-Rn12*(Rn22\Rn21);   % = scaled Conditional variance of x1.
            sum_s = sum_s + (x1-muc)^2/Rnc;
            sum_lnd = sum_lnd + log(Rnc);
        else
            sum_s = sum_s+xc(obs)^2;
            sum_lnd= sum_lnd+log(1);
        end
    end  %for obs =
end      %for seg = 1:nseg

varx = sum_s/nobs_used;

lh_AR = -nobs_used/2*log(varx)-sum_lnd/2 - sum_s/2/varx;

%Turning the Likelihood in an estimate of the K-L discrepancy:
lh_AR = -2*lh_AR;

if isnan(lh_AR), lh_AR = +Inf; end


classdef MaF8 < PROBLEM
% <multi/many> <real>
% MP-DMP

%------------------------------- Reference --------------------------------
% R. Cheng, M. Li, Y. Tian, X. Zhang, S. Yang, Y. Jin, and X. Yao, A
% benchmark test suite for evolutionary many-objective optimization,
% Complex & Intelligent Systems, 2017, 3(1): 67-81.
%------------------------------- 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".
%--------------------------------------------------------------------------

    properties(Access = private)
        Points; % Vertexes
    end
    methods
        %% Default settings of the problem
        function Setting(obj)
            % Parameter setting
            if isempty(obj.M); obj.M = 10; end
            obj.M        = max(obj.M,3);
            obj.D        = 2;
            obj.lower    = [-10000,-10000];
            obj.upper    = [10000,10000];
            obj.encoding = ones(1,obj.D);
            % Generate vertexes
            obj.Points  = [];
            [thera,rho] = cart2pol(0,1);
            [obj.Points(:,1),obj.Points(:,2)] = pol2cart(thera-(1:obj.M)*2*pi/obj.M,rho);
        end
        %% Calculate objective values
        function PopObj = CalObj(obj,PopDec)
            PopObj = pdist2(PopDec,obj.Points);
        end
        %% Generate points on the Pareto front
        function R = GetOptimum(obj,N)
            [X,Y] = ndgrid(linspace(-1,1,ceil(sqrt(N))));
            ND    = inpolygon(X(:),Y(:),obj.Points(:,1),obj.Points(:,2));
            R     = pdist2([X(ND),Y(ND)],obj.Points);
        end
        %% Generate the image of Pareto front
        function R = GetPF(obj)
            if obj.M == 3
                [X,Y]    = ndgrid(linspace(-1,1,40));
                R        = pdist2([X(:),Y(:)],obj.Points);
                ND       = inpolygon(X(:),Y(:),obj.Points(:,1),obj.Points(:,2));
                R(~ND,:) = nan;
                R = {reshape(R(:,1),size(X)),reshape(R(:,2),size(X)),reshape(R(:,3),size(X))};
            else
                R = [];
            end
        end
        %% Display a population in the decision space
        function DrawDec(obj,Population)
            Draw(obj.Points([1:end,1],:),'-k','LineWidth',1.5,{'\it x\rm_1','\it x\rm_2',[]});
            Draw(obj.Points,'o','MarkerSize',6,'Marker','o','Markerfacecolor',[1 1 1],'Markeredgecolor',[.4 .4 .4]);
            Draw(Population.decs);
        end
    end
end


function [nstate] = tapas_sampler_dlinear_cv_gibbs_node(data, model, ...
    inference, state, node)
%% Samples from a linear model with variance using a gibbs step and a
% leave one out approach.
%
% Input
%
% Output
%

% aponteeduardo@gmail.com
% copyright (C) 2016
%

nstate = state;

[np, nc] = size(state.graph{node - 1}.y);
nm = numel(state.graph{node}.y{1}.mu);
% Compute the means

mu = cell(1, nc);

% Initilize at the prior

y = state.graph{node + 1}.y;

% First store the values somewhere
% np + 1 Number of subjects plus prior
values = zeros(size(y{1}.mu, 1), np + 1);
variance = cell(nc, 1);
for i = 1:nc
    values(:, 1) = y{i}.mu;
    for j = 1:np
        values(:, j + 1)  = state.graph{node - 1}.y{j, i};
    end
    y{i}.mu = mean(values, 2);
    % No bessel correction
    variance{i} = var(values, 1, 2);
end

for i = 1:nc
    % Priors
    alpha = state.graph{node + 1}.y{i}.alpha;
    beta = state.graph{node + 1}.y{i}.beta;
    % Sample variance for each of the components
    % The one degree of freedom comes from the prior
    pe = gamrnd(alpha + np/2, 1./(beta + ((np + 1)/2.0) .* variance{i}));
    nstate.graph{node}.y{i}.pe = pe;
    % Update the mean
    nstate.graph{node}.y{i}.mu = y{i}.mu + ...
        (1./sqrt((np + 1) * pe) .* randn(nm, 1));
end

nstate.llh{node} = model.graph{node}.llh(nstate.graph{node}, ...
    nstate.graph{node + 1}, model.graph{node}.htheta);

nstate.llh{node - 1} = model.graph{node - 1}.llh(...
    nstate.graph{node - 1}, nstate.graph{node}, model.graph{node - 1}.htheta);

end


function out = SY_SlidingWindow(y,windowStat,acrossWinStat,numSeg,incMove)
% SY_SlidingWindow  Sliding window measures of stationarity.
%
% This function is based on sliding a window along the time series, measuring
% some quantity in each window, and outputting some summary of this set of local
% estimates of that quantity.
%
% Another way of saying it: calculate 'windowStat' in each window, and computes
% 'acrossWinStat' for the set of statistics calculated in each window.
%
%---INPUTS:
%
% y, the input time series
%
% windowStat, the measure to calculate in each window:
%               (i) 'mean', mean
%               (ii) 'std', standard deviation
%               (iii) 'ent', distribution entropy
%               (iv) 'mom3', skewness
%               (v) 'mom4', kurtosis
%               (vi) 'mom5', the fifth moment of the distribution
%               (vii) 'lillie', the p-value for a Lilliefors Gaussianity test
%               (viii) 'AC1', the lag-1 autocorrelation
%               (ix) 'apen', Approximate Entropy, ApEn(1,0.2)
%               (ix) 'sampen', Sample Entropy, SampEn(2,0.1)
%
% acrossWinStat, controls how the obtained sequence of local estimates is
%                   compared (as a ratio to the full time series):
%                       (i) 'std': standard deviation
%                       (ii) 'ent' histogram entropy
%                       (iii) 'apen': Approximate Entropy, ApEn(1,0.2)
%                       (iii) 'sampen': Sample Entropy, SampEn(2,0.1)
%
% numSeg, the number of segments to divide the time series up into, thus
%       controlling the window length
%
% incMove, the increment to move the window at each iteration, as 1/fraction of the
%       window length (e.g., incMove = 2, means the window moves half the length of the
%       window at each increment)
%
% NOTE: SY_SlidingWindow(y,'mean','std',X,1) is the same as StatAvX, computed as
%                       SY_StatAv(y,'seg',X);
% cf. "Heart rate control in normal and aborted-SIDS infants", S. M. Pincus et al.
%           Am J. Physiol. Regul. Integr. Comp. Physiol. 264(3) R638 (1993)

% ------------------------------------------------------------------------------
% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite the following two papers:
%
% (1) B.D. Fulcher and N.S. Jones, "hctsa: A Computational Framework for Automated
% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).
% DOI: 10.1016/j.cels.2017.10.001
%
% (2) B.D. Fulcher, M.A. Little, N.S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2013).
% DOI: 10.1098/rsif.2013.0048
%
% This function 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/>.
% ------------------------------------------------------------------------------

doPlot = false; % plot outputs

% ------------------------------------------------------------------------------
% Check Inputs
% ------------------------------------------------------------------------------

if nargin < 2 || isempty(windowStat)
    windowStat = 'mean'; % measure within each window
end
if nargin < 3 || isempty(acrossWinStat)
    acrossWinStat = 'std'; % measure across all windows
end
if nargin < 4 || isempty(numSeg)
    numSeg = 5;
end
if nargin < 5 || isempty(incMove)
    incMove = 2;
end

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

winLength = floor(length(y)/numSeg); % length of window
if winLength==0
    warning('Time-series of length %u is too short for %u windows',length(y),numSeg);
    out = NaN;
    return
end
inc = floor(winLength/incMove); % increment to move at each step
% If increment rounded down to zero, prop it up:
if inc == 0
    inc = 1;
end

numSteps = (floor((length(y)-winLength)/inc)+1);
qs = zeros(numSteps,1);

% Convert a step index (stepInd) to a range of indices corresponding to that window:
getWindow = @(stepInd) ((stepInd-1)*inc + 1:(stepInd-1)*inc + winLength);

switch windowStat
    case 'mean' % Sliding window mean
        for i = 1:numSteps
            qs(i) = mean(y(getWindow(i)));
        end
    case 'std' % Sliding window std
        for i = 1:numSteps
            qs(i) = std(y(getWindow(i)));
        end
    case 'ent' % Sliding window distributional entropy
        for i = 1:numSteps
            qs(i) = EN_DistributionEntropy(y(getWindow(i)),'ks',[]);
        end
    case 'apen' % Sliding window ApEn
        for i = 1:numSteps
            qs(i) = EN_ApEn(y(getWindow(i)),1,0.2);
        end
    case 'sampen' % Sliding window SampEn
        for i = 1:numSteps
            sampEn_struct = EN_SampEn(y(getWindow(i)),1,0.1);
            qs(i) = sampEn_struct.sampen1;
        end
    case 'mom3' % Third moment
        for i = 1:numSteps
            qs(i) = DN_Moments(y(getWindow(i)),3);
        end
    case 'mom4' % Fourth moment
        for i = 1:numSteps
            qs(i) = DN_Moments(y(getWindow(i)),4);
        end
    case 'mom5' % Fifth moment
        for i = 1:numSteps
            qs(i) = DN_Moments(y(getWindow(i)),5);
        end
    case 'lillie' % Lilliefors test
        for i = 1:numSteps
            qs(i) = HT_DistributionTest(y(getWindow(i)),'lillie','norm');
        end
    case 'AC1' % Lag-1 autocorrelation
        for i = 1:numSteps
            qs(i) = CO_AutoCorr(y(getWindow(i)),1,'Fourier');
        end
    otherwise
        error('Unknown statistic ''%s''',windowStat)
end

% Check for all errors (e.g., short time series):
if all(isnan(qs))
    warning('These sliding window settings are not suitable for this time series');
    out = NaN;
    return
end

% ------------------------------------------------------------------------------
% Plot
% ------------------------------------------------------------------------------
if doPlot
    figure('color','w'); box('on');
    plot(round(winLength/2):inc:(numSteps-1)*inc+round(winLength/2),qs,'r');
end

% ------------------------------------------------------------------------------
% Compute the output statistic
% ------------------------------------------------------------------------------
switch acrossWinStat
    case 'std'
        % normalized by std of full time series
        out = std(qs)/std(y);
    case 'apen'
        out = EN_ApEn(qs,1,0.2); % ApEn of the sliding window measures
    case 'sampen'
        sampEn_struct = EN_SampEn(qs,2,0.15);
        out = sampEn_struct.quadSampEn1;
    case 'ent'
        % get a load of statistics from kernel-smoothed distribution (inefficient since only one is used)
        kssimpouts = DN_FitKernelSmooth(qs);
        out = kssimpouts.entropy; % distributional entropy
    otherwise
        error('Unknown statistic: ''%s''.',acrossWinStat)
end

end


        % Ciclu repetitiv pentru calcularea coeficientilor binomiali
for k=1:10
    binom(k,1:k+1)=mfun('binomial',k,0:k);
end
        % Afisarea rezultatului
disp('Coeficientii binomiali')
disp(binom)


% This function is designed to determine whether a sphere collides with a
% give triangle

function [haveCollided] = CheckSphereTriangleIntersection(p,r,pa,pb,pc)

% INpUT pcHEpcK
assert(numel(p) == 3,'pcentroid must be a column vector [3x1]');
assert(numel(r) == 1,'Radius must be a scalar');
assert(numel(pa) == 3 && numel(pb) == 3 && numel(pc) == 3,...
       'Vertex point must be a column vector [3x1]');

% pcHEpcK pLpaNpaR SEppaRpaTION
pa = pa - p;
pb = pb - p;
pc = pc - p;
rr = r^2;
V = cross(pb-pa,pc-pa);
d = dot(pa,V);
e = dot(V,V);
sep1 = d^2 > rr*e;
% pcHEpcK VERTIpcES
aa = dot(pa,pa);
ab = dot(pa,pb);
ac = dot(pa,pc);
bb = dot(pb,pb);
bc = dot(pb,pc);
cc = dot(pc,pc);
sep2 = (aa > rr) & (ab > aa) & (ac > aa);
sep3 = (bb > rr) & (ab > bb) & (bc > bb);
sep4 = (cc > rr) & (ac > cc) & (bc > cc);
% pcHEpcK TRIpaNGLE EDGES
papb = pb - pa;
pbpc = pc - pb;
pcpa = pa - pc;
d1 = ab - aa;
d2 = bc - bb;
d3 = ac - cc;
e1 = dot(papb,papb);
e2 = dot(pbpc,pbpc);
e3 = dot(pcpa,pcpa);
Q1 = pa*e1 - d1*papb;
Q2 = pb*e2 - d2*pbpc;
Q3 = pc*e3 - d3*pcpa;
Qpc = pc*e1 - Q1;
Qpa = pa*e2 - Q2;
Qpb = pb*e3 - Q3;
sep5 = dot(Q1,Q1) > (rr*e1*e1) & dot(Q1,Qpc) > 0;
sep6 = dot(Q2,Q2) > (rr*e2*e2) & dot(Q2,Qpa) > 0;
sep7 = dot(Q3,Q3) > (rr*e3*e3) & dot(Q3,Qpb) > 0;
isSeparated = sep1 || sep2 || sep3 || sep4 || sep5 || sep6 || sep7;
haveCollided = ~isSeparated;
end


function p = dirichlet_logProb_fast(a, bar_p)

p = gammaln(sum(a)) - sum(gammaln(a)) + sum((a-1).*bar_p);
K = length(a);
flops(flops + (K+1)*flops_digamma + 3*K);


close all; clear all;

%% Setting of the problem
global s
pde = fracLapdata6;
option.theta = 0.3;
option.estType = 'star';
option.maxIt = 18;
option.maxN = 5e4;
option.solver = 'mg';
option.tol = 1e-6;
[node,elem] = squaremesh([-1,1,-1,1],0.5);
bdFlag = setboundary(node,elem,'Dirichlet');

% %% s = 0.2
% s = 0.2;
% afemfracLap(node,elem,pde,bdFlag,option);
%
% %% s = 0.4
% s = 0.4;
% afemfracLap(node,elem,pde,bdFlag,option);

%% s = 0.6
s = 0.6;
afemfracLap(node,elem,pde,bdFlag,option);

%% s = 0.8
s = 0.8;
afemfracLap(node,elem,pde,bdFlag,option);


% TTEST_CELL - compute paired t-test. Allow fast computation of
%                multiple t-test using matrix manipulation.
%
% Usage:
%    >> [F df] = ttest_cell( { a b } );
%    >> [F df] = ttest_cell(a, b);
%
% Inputs:
%   a,b       = data consisting of PAIRED arrays to be compared. The last
%               dimension of the data array is used to compute the t-test.
% Outputs:
%   T   - T-value
%   df  - degree of freedom (array)
%
% Example:
%   a = { rand(1,10) rand(1,10)+0.5 }
%   [T df] = ttest_cell(a)
%   signif = 1-tcdf(T, df(1))
%
%   % for comparison, the same using the Matlab t-test function
%   [h p ci stats] = ttest(a{1}', b{1}');
%   [ stats.tstat' p]
%
%   % fast computation (fMRI scanner volume 100x100x100 and 10 subjects in
%   % two conditions). The computation itself takes 0.5 seconds instead of
%   % half an hour using the standard approach (1000000 loops and Matlab
%   % t-test function)
%   a = rand(100,100,100,10); b = rand(100,100,100,10);
%   [F df] = ttest_cell({ a b });
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005
%
% Reference:
%   Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill.

% Copyright (C) Arnaud Delorme
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

function [tval, df] = ttest_cell(a,b)

    if nargin < 1
        help ttest_cell;
        return;
    end

    if iscell(a), b = a{2}; a = a{1}; end
    tmpdiff = a-b;
    diff = mymean(tmpdiff,    myndims(a));
    sd   = mystd( tmpdiff,[], myndims(a));
    tval = diff./sd*sqrt(size(a, myndims(a)));
    df   = size(a, myndims(a))-1;

    % check values againg Matlab statistics toolbox
    %[h p ci stats] = ttest(a', b');
    % [ tval stats.tstat' ]

function val = myndims(a)
    if ndims(a) > 2
        val = ndims(a);
    else
        if size(a,1) == 1,
            val = 2;
        elseif size(a,2) == 1,
            val = 1;
        else
            val = 2;
        end
    end;

function res = mymean( data, varargin) % deal with complex numbers
    res = mean( data, varargin{:});
    if ~isreal(data)
        res = abs( res );
    end

function res = mystd( data, varargin) % deal with complex numbers
    if ~isreal(data)
        res = std( abs(data), varargin{:});
    else
        res = sqrt(sum( bsxfun(@minus, data, mean( data, varargin{2})).^2, varargin{2})/(size(data,varargin{2})-1)); % 8 percent speedup
        %res = std( data, varargin{:});
    end


% test for hessian tensor

n = 256;
name = 'barb';
M = load_image(name);
M = rescale(crop(M,n));

options.order = 2;
T = compute_hessian(M, options);

[e1,e2,l1,l2] = perform_tensor_decomp(T);
l1 = abs(l1); l2 = abs(l2);
T = perform_tensor_recomp(e1,e2,l2,l1);

sigma = 5;
T = perform_blurring(T,sigma);

options.sub = 8;
clf;
plot_tensor_field(T, M, options);
figure;
clf;
plot_tensor_field_nb(T, M, options);


% @authors:     Fuxin Li
% @contact:     ahumayun@cc.gatech.edu
% @affiliation: Georgia Institute of Technology
% @date:        Fall 2013 - Summer 2014

function s_feat = compute_all_relevant_features( sp_seg, edge_graph )
% somehow, all the rest are computed on a halfed image, while the last one
% is on full image...
    s_feat = zeros(max(sp_seg(:)), 6);
%    sp_seg_rszd = imresize(sp_seg,0.5,'nearest');
    [cent, bb, area, perim, secondorder] = superpix_regionprops(uint16(sp_seg));
    bb = double(bb);
    bb(:,1:2) = bb(:,1:2) - 0.5;
    bb(:,3:4) = bb(:,3:4) + 0.5;
    % Left and top both have -0.5 as per MATLAB convention
    s_feat(:,1:2) = double(bb(:,1:2));
    % Eccentricity is a bit tricky...
    % Now the secondorder information is non-central, to get centralized
    % moments we need to use (x - centx)^2 = x^2 - 2 x*centx + centx^2
    % but \sum x /N = centx, therefore we get (x-centx)^2 = secondorder_x - 2
    % centx * centx * N + N * centx * centx = secondorder_x - N * centx *
    % centx
    %1/12 is the normalized second central moment of a pixel with unit length.
    uxx = secondorder(:,1) ./ single(area) - cent(:,1).^2 + 1/12;
    uyy = secondorder(:,2) ./ single(area) - cent(:,2).^2 + 1/12;
    % for uxy, we compute (x - centx) (y-centy)  = xy - centx y - centy x -
    % centx centy, using the same idea we can get that is xy - N centx
    % centy
    uxy = secondorder(:,3) ./ single(area) - cent(:,1) .* cent(:,2);
    common = sqrt((uxx - uyy).^2 + 4*uxy.^2);
    MajorAxisLength =  2*sqrt(2)*sqrt(uxx + uyy + common);
    MinorAxisLength = 2*sqrt(2)*sqrt(uxx + uyy - common);
    Eccentricity = 2*sqrt((MajorAxisLength/2).^2 - (MinorAxisLength/2).^2) ./ MajorAxisLength;
    s_feat(:,3) = Eccentricity;
    % Extent, area / bounding box area
    s_feat(:,4) = single(area) ./ single((bb(:,4) - bb(:,2)) .* (bb(:,3) - bb(:,1)));
    % Perimeter
    s_feat(:,5) = perim;
    s_feat(:,6) = sum(edge_graph,2);
    % Left here commented for verification of correctness
%     for i=1:max(sp_seg(:))
% %          s = regionprops(sp_seg==i,'BoundingBox','Eccentricity','EquivDiameter','Extent','Perimeter');
% %          s = s(1);
% %          s_feat(i,1:5) = [s.BoundingBox(1) s.BoundingBox(2) s.Eccentricity s.Extent s.Perimeter];
% %         % Inter-contour energy, change this just to superpixel boundary
%         % energy
%         all_bw = imdilate(sp_seg==i, ones(5,5)) & imdilate(~(sp_seg==i), ones(5,5));
%         s_feat(i,6) = sum(pb_thin(all_bw));
%     end
end


% DEMROBOTWIRELESS3 Wireless Robot data from University of Washington with dynamics and no back constraints.

% FGPLVM

% Fix seeds
randn('seed', 1e5);
rand('seed', 1e5);

dataSetName = 'robotWireless';
experimentNo = 3;

% load data
[Y, lbls] = lvmLoadData(dataSetName);

% Set up model
options = fgplvmOptions('ftc');

latentDim = 2;
d = size(Y, 2);

model = fgplvmCreate(latentDim, d, Y, options);

% Add dynamics model.
options = gpOptions('ftc');
options.kern = kernCreate(model.X, {'rbf', 'white'});
options.kern.comp{1}.inverseWidth = 0.2;
% This gives signal to noise of 0.1:1e-3 or 100:1.
options.kern.comp{1}.variance = 0.1^2;
options.kern.comp{2}.variance = 1e-3^2;
model = fgplvmAddDynamics(model, 'gp', options);

% Optimise the model.
iters = 1000;
display = 1;

model = fgplvmOptimise(model, display, iters);

% Save the results.
capName = dataSetName;;
capName(1) = upper(capName(1));
save(['dem' capName num2str(experimentNo) '.mat'], 'model');

% Load the results and display dynamically.
fgplvmResultsDynamic(dataSetName, experimentNo, 'vector')


function ss=lpczz2ss(zz)
%LPCZZ2SS Convert z-place poles to s-plane poles SS=(ZZ)
%the s-plane is in units of Normalized Hz and so the imaginary part
% of each ss() value is in the range +-0.5
%
% If you multiply ss by the sample frequency, a formant with
% frequency f and bandwidth b will give an s-plane pole-pair
% of approximately -b/2 +- j f

%      Copyright (C) Mike Brookes 1997
%      Version: $Id: lpczz2ss.m,v 1.4 2007/05/04 07:01:39 dmb Exp $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   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 can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

ss=log(max(zz,1e-8))*0.5/pi;


function rhs_lucas_test ( )

%*****************************************************************************80
%
%% RHS_LUCAS_TEST samples the right hand side at the initial time.
%
%  Location:
%
%    http://people.sc.fsu.edu/~jburkardt/m_src/navier_stokes_2d_exact/rhs_lucas_test.m
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 March 2015
%
%  Author:
%
%    John Burkardt
%
  nu = 1.0;
  rho = 1.0;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'RHS_LUCAS_TEST\n' );
  fprintf ( 1, '  Lucas Bystricky Flow\n' );
  fprintf ( 1, '  Sample the Navier-Stokes right hand sides\n' );
  fprintf ( 1, '  at the initial time T = 0, using the unit square.\n' );
  fprintf ( 1, '  Kinematic viscosity NU = %g\n', nu );
  fprintf ( 1, '  Fluid density RHO = %g\n', rho );

  n = 1000;
  xy_lo = 0.0;
  xy_hi = 1.0;
  seed = 123456789;
  [ x, seed ] = r8vec_uniform_ab ( n, xy_lo, xy_hi, seed );
  [ y, seed ] = r8vec_uniform_ab ( n, xy_lo, xy_hi, seed );
  t = 0.0;

  [ f, g, h ] = rhs_lucas ( nu, rho, n, x, y, t );

  fprintf ( 1, '\n' );
  fprintf ( 1, '           Minimum       Maximum\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  F:  %14.6g  %14.6g\n', min ( f ), max ( f ) );
  fprintf ( 1, '  G:  %14.6g  %14.6g\n', min ( g ), max ( g ) );
  fprintf ( 1, '  H:  %14.6g  %14.6g\n', min ( h ), max ( h ) );

  return
end


function normal_01_cdf_values_test ( )

%*****************************************************************************80
%
%% NORMAL_01_CDF_VALUES_TEST demonstrates the use of NORMAL_01_CDF_VALUES.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 November 2005
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'NORMAL_01_CDF_VALUES_TEST:\n' );
  fprintf ( 1, '  NORMAL_01_CDF_VALUES stores values of\n' );
  fprintf ( 1, '  the Normal 01 Cumulative Density Function.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      X                  CDF(X)\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, x, fx ] = normal_01_cdf_values ( n_data );

    if ( n_data == 0 )
      break
    end

    fprintf ( 1, '  %24.16f  %24.16f\n', x, fx );

  end

  return
end


function quad_mesh_test05 ( )

%*****************************************************************************80
%
%% QUAD_MESH_TEST05 tests BOUNDARY_EDGE_COUNT_EULER_Q4_MESH.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 February 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'QUAD_MESH_TEST05\n' );
  fprintf ( 1, '  BOUNDARY_EDGE_COUNT_EULER_Q4_MESH counts the\n' );
  fprintf ( 1, '    boundary edges using Euler''s formula.\n' );

  [ node_num, element_num, hole_num ] = example1_q4_mesh_size ( );

  boundary_edge_num = boundary_edge_count_euler_q4_mesh ( node_num, ...
    element_num, hole_num );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of boundary edges = %d\n', boundary_edge_num );
  fprintf ( 1, '  Correct number =           %d\n', 22 );

  return
end


function phiFaceAverage = upwindMean1D(phi, u)
% This function gets the value of the field variable phi defined
% over the MeshStructure and calculates the upwind average on
% the cell faces, based on the direction of the velocity vector for a uniform mesh.
%
% SYNOPSIS:
%   phiFaceAverage = upwindMean1D(phi, u)
%
% PARAMETERS:
%
%
% RETURNS:
%
%
% EXAMPLE:
%
% SEE ALSO:
%

% Written by Ali A. Eftekhari
% See the license file

% extract the velocity data
% note: size(ux) = [1:m+1, 1:n] and size(uy) = [1:m, 1:n+1]
ux = u.xvalue;

% check the size of the variable and the mesh dimension
Nx = phi.domain.dims(1);

% assign to a temp variable for boundary corrections
phi_tmp = phi.value;

% correct the value of phi at the boundary (calculation trick)
% assign the value of the left boundary to the left ghost cell
phi_tmp(1) = (phi.value(1)+phi.value(2))/2;
% assign the value of the right boundary to the right ghost cell
phi_tmp(end) = (phi.value(end)+phi.value(end-1))/2;

% calculate the average value
xvalue = (ux>0).*phi_tmp(1:Nx+1)+ ...
                        (ux<0).*phi_tmp(2:Nx+2)+ ...
                        0.5*(ux==0).*(phi.value(1:Nx+1)+phi.value(2:Nx+2));
phiFaceAverage=FaceVariable(phi.domain, xvalue, [], []);


function bwn = bw_filter(bw, keepnum)
if nargin < 2
    keepnum = 15;
end
[L, num] = bwlabel(bw, 8);
Ln = zeros(1, num);
stats = regionprops(L, 'Area');
Ln = cat(1, stats.Area);
[Ln, ind] = sort(Ln);
if num>keepnum || num==keepnum
    for i = 1 : num-keepnum
        bw(L == ind(i)) = 0;
    end
end
bwn = bw;


function [FV] = mesh_grow(FV,origin,dist),

% mesh_grow - explode vertices of mesh by specific distance
%
% FV = mesh_grow(FV,origin,dist)
%
% FV is a struct with fields:
%
% FV.vertices   - Nx3 matrix of Cartesian vertex coordindates (X,Y,Z)
% FV.faces      - Mx3 matrix of triangulation of FV.vertices
%
% origin        - 1x3 row vector, usually (0,0,0)
%
% dist          - how far to explode the mesh away from the origin;
%                 this distance is relative to current distance from
%                 the origin, not the total distance from the origin.
%

% $Revision: 1.1 $ $Date: 2009-04-28 22:13:57 $

% Licence:  GNU GPL, no implied or express warranties
% History:  10/2002, Darren.Weber_at_radiology.ucsf.edu
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    xo = origin(1); yo = origin(2); zo = origin(3);

    Nvert = size(FV.vertices,1);

    fprintf('...mesh explosion...'); tic;

    for v = 1:Nvert,

        x = FV.vertices(v,1);
        y = FV.vertices(v,2);
        z = FV.vertices(v,3);

        % Find direction cosines for line from centre to vertex
        d = sqrt( (x-xo)^2 + (y-yo)^2 + (z-zo)^2 );

        l = (x-xo)/d; % cos alpha
        m = (y-yo)/d; % cos beta
        n = (z-zo)/d; % cos gamma

        % now decrease d by dist
        d = d + dist;

        % locate vertex at this new distance
        x = (l * d) + xo;
        y = (m * d) + yo;
        z = (n * d) + zo;

        FV.vertices(v,:) = [ x y z ];
    end

    t = toc; fprintf('...done (%5.2f sec)\n',t);

return


function [varargout] = likGauss(hyp, y, mu, s2, inf, i)

% likGauss - Gaussian likelihood function for regression. The expression for the
% likelihood is
%   likGauss(t) = exp(-(t-y)^2/2*sn^2) / sqrt(2*pi*sn^2),
% where y is the mean and sn is the standard deviation.
%
% The hyperparameters are:
%
% hyp = [  log(sn)  ]
%
% Several modes are provided, for computing likelihoods, derivatives and moments
% respectively, see likFunctions.m for the details. In general, care is taken
% to avoid numerical issues when the arguments are extreme.
%
% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2014-03-04.
%                                      File automatically generated using noweb.
%
% See also LIKFUNCTIONS.M.

if nargin<3, varargout = {'1'}; return; end   % report number of hyperparameters

sn2 = exp(2*hyp);

if nargin<5                              % prediction mode if inf is not present
  if numel(y)==0,  y = zeros(size(mu)); end
  s2zero = 1; if nargin>3, if norm(s2)>0, s2zero = 0; end, end         % s2==0 ?
  if s2zero                                                    % log probability
    lp = -(y-mu).^2./sn2/2-log(2*pi*sn2)/2; s2 = 0;
  else
    lp = likGauss(hyp, y, mu, s2, 'infEP');                         % prediction
  end
  ymu = {}; ys2 = {};
  if nargout>1
    ymu = mu;                                                   % first y moment
    if nargout>2
      ys2 = s2 + sn2;                                          % second y moment
    end
  end
  varargout = {lp,ymu,ys2};
else
  switch inf
  case 'infLaplace'
    if nargin<6                                             % no derivative mode
      if numel(y)==0, y=0; end
      ymmu = y-mu; dlp = {}; d2lp = {}; d3lp = {};
      lp = -ymmu.^2/(2*sn2) - log(2*pi*sn2)/2;
      if nargout>1
        dlp = ymmu/sn2;                      % dlp, derivative of log likelihood
        if nargout>2                    % d2lp, 2nd derivative of log likelihood
          d2lp = -ones(size(ymmu))/sn2;
          if nargout>3                  % d3lp, 3rd derivative of log likelihood
            d3lp = zeros(size(ymmu));
          end
        end
      end
      varargout = {lp,dlp,d2lp,d3lp};
    else                                                       % derivative mode
      lp_dhyp = (y-mu).^2/sn2 - 1;  % derivative of log likelihood w.r.t. hypers
      dlp_dhyp = 2*(mu-y)/sn2;                               % first derivative,
      d2lp_dhyp = 2*ones(size(mu))/sn2;   % and also of the second mu derivative
      varargout = {lp_dhyp,dlp_dhyp,d2lp_dhyp};
    end

  case 'infEP'
    if nargin<6                                             % no derivative mode
      lZ = -(y-mu).^2./(sn2+s2)/2 - log(2*pi*(sn2+s2))/2;    % log part function
      dlZ = {}; d2lZ = {};
      if nargout>1
        dlZ  = (y-mu)./(sn2+s2);                    % 1st derivative w.r.t. mean
        if nargout>2
          d2lZ = -1./(sn2+s2);                      % 2nd derivative w.r.t. mean
        end
      end
      varargout = {lZ,dlZ,d2lZ};
    else                                                       % derivative mode
      dlZhyp = ((y-mu).^2./(sn2+s2)-1) ./ (1+s2./sn2);   % deriv. w.r.t. hyp.lik
      varargout = {dlZhyp};
    end

  case 'infVB'
    % variational lower site bound
    % t(s) = exp(-(y-s)^2/2sn2)/sqrt(2*pi*sn2)
    % the bound has the form: (b+z/ga)*f - f.^2/(2*ga) - h(ga)/2
    n = numel(s2); b = zeros(n,1); y = y.*ones(n,1); z = y;
    varargout = {b,z};
  end
end


function [Population,FrontNo,CrowdDis] = EnvironmentalSelection(Population,N,zmin,zmax)
% The environmental selection of NSGA-II

%------------------------------- 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".
%--------------------------------------------------------------------------

    %% Normalization
    PopObj = Population.objs - repmat(zmin,length(Population),1);
    range  = zmax - zmin;
    if 0.05*max(range) < min(range)
        PopObj = PopObj./repmat(range,length(Population),1);
    end
    [~,x]      = unique(round(PopObj*1e6)/1e6,'rows');
    PopObj     = PopObj(x,:);
    Population = Population(x);
    N          = min(N,length(Population));

    %% Non-dominated sorting
    [FrontNo,MaxFNo] = NDSort_SDR(PopObj,N);
    Next = FrontNo < MaxFNo;

    %% Calculate the crowding distance of each solution
    CrowdDis = CrowdingDistance(PopObj,FrontNo);

    %% Select the solutions in the last front based on their crowding distances
    Last     = find(FrontNo==MaxFNo);
    [~,Rank] = sort(CrowdDis(Last),'descend');
    Next(Last(Rank(1:N-sum(Next)))) = true;

    %% Population for next generation
    Population = Population(Next);
    FrontNo    = FrontNo(Next);
    CrowdDis   = CrowdDis(Next);
end


function [err, Qd, dfx, dmat2] = QRDecom(dmat, cmat)
%
%   [err,] = QRDecom.m ()
%
%Purpose:
%
%
%
%Input Parameters:
%
%
%
%Output Parameters:
%   err : 0 No Problem
%       : 1  Problems
%
%
%
%Key Terms:
%
%More Info :
%
%
%
%
%     Author : Gang Chen
%     Date : Tue Mar 23 16:09:23 EST 2004
%     SSCC/NIMH/ National Institutes of Health, Bethesda MD 20892

%Define the function name for easy referencing
FuncName = 'QRDecom.m';

%Debug Flag
DBG = 1;

%initailize return variables
err = 1;

% Tolerance for computing rank from diag(R) after QR decomposition
%[nrows,ncols] = size(dmat);

% Find the null space of the constraints matrix
[Qc,Rc,Ec] = qr(cmat');
pc = Rrank(Rc);
Qc0 = Qc(:,pc+1:end);

% Do qr decomposition on design matrix projected to null space
Dproj = dmat*Qc0;
[Qd,Rd,Ed] = qr(Dproj,0);
dfx = Rrank(Rd);
Qd = Qd(:,1:dfx);
%Rd = Rd(1:dfx,1:dfx);

% Return reduced design matrix if requested
if nargout>3
   dmat2 = Qd' * dmat;
end

err = 0;
return;


% feldkamp_example.m
% example of how to use feldkamp.m for cone-beam CT reconstruction
% Copyright 2004-8-28, Nicole Caparanis, Patty Laskowsky, Taka Masuda,
% and Jeff Fessler, The University of Michigan
% modified version by Ajay Paidi

if ~isvar('proj')
	down = 1/2;
	nv = 240*down;%240*down;
	nh = 256*down;%256*down;
	na = 224*down;%224*down;
	ds = 1024/nh;
	dt = ds;
	dis_src_det = 949;
	dis_iso_det = 408;
	dis_src_iso = dis_src_det - dis_iso_det;
	dis_foc_src = inf; % flat detector panel
	offset_det_h = 0.25; % quarter detector
	offset_det_v = 0.0;
	horiz = ([-(nh-1)/2:(nh-1)/2]' - offset_det_h) * ds;
	verti = ([-(nv-1)/2:(nv-1)/2]' - offset_det_v) * dt;
	printf('rmax=%g', dis_src_iso*sin(atan(max(abs(horiz)) / dis_src_det)))

ell = [ ...
		[0 0 -72 150 200 15 0 5];
		[0 0 -32 150 200 20 0 10];
        [0 0 12 150 200 15 0 10];
		[0 0 52 150 200 20 0 7];
        [0 0 82 150 200 15 0 10];
        ];

	nx = 240*down;%256*down;
	ny = 256*down;%240*down;
	nz = 112*down;%184*down;
	dx = 2/down; dy = dx; dz = dx;
	x = ellipsoids(nx, ny, nz, ell, dx, dy, dz);

	% cone-beam system geometry, generalized from fan-beam geometry.
	% see ASPIRE users guide under tech. reports on web page for details.
	args = arg_pair('system', NaN, 'nx', nx, 'ny', ny, 'nz', nz, ...
		'nv', nv, 'nh', nh, 'na', na, 'support', 'all', ...
		'orbit', 360, 'orbit_start', 0, ...
		'pixel_size', dx, 'ray_spacing', ds, 'strip_width', 0, ...
		'dis_src_det', dis_src_det, ...
		'dis_iso_det', dis_iso_det, ...
		'dis_foc_src', dis_foc_src, ...
		'offset_source', 0, ...
		'offset_det_h', offset_det_h, ...
		'offset_det_v', offset_det_v);

	pl=230;
	im(pl+1, x, 'x'), cbar
	im(pl+2, proj, 'proj'), cbar
	drawnow
prompt
end

% cone-beam reconstruction
mask = true([nx ny nz]);
recon = feldkamp(proj, 'ramp', mask, args);

% show results (off-center slices worse than central slice)
im(pl+4, recon, 'recon'), cbar
im(pl+5, recon - x, 'error'), cbar
ix = 1:nx; iy = ny/2; iz = nz/2;
subplot(236)
plot(ix, x(ix,iy,iz), '-', ix, recon(ix,iy,iz), '--')
axis([1 nx -1 16]), legend('true', 'recon', 2)
title 'MIDDLE SLICE'
iz=12;
subplot(233)
plot(ix, x(ix,iy,iz), '-', ix, recon(ix,iy,iz), '--')
axis([1 nx -1 16]), legend('true', 'recon')
title(sprintf('SLICE %d', iz))
%figure
%subplot(2,1,1)
%ix1 = nx/2;
%iy1 = ny/2;
%iy = 1:ny;
%ix = 1:nx;
%iz = nx/2;
%plot(iy, x(ix1, iy, iz), '-', iy, recon(ix1,iy,iz), '--');
%title('plot of x vs. y on middle slice')