function [ top, btri, bedg, triangle_node, triangle_neighbor ] = swapec ( ...
  i, top, btri, bedg, node_num, node_xy, triangle_num, triangle_node, ...
  triangle_neighbor, work )

%*****************************************************************************80
%
%% SWAPEC swaps diagonal edges until all triangles are Delaunay.
%
%  Discussion:
%
%    The routine swaps diagonal edges in a 2D triangulation, based on
%    the empty circumcircle criterion, until all triangles are Delaunay,
%    given that I is the index of the new vertex added to the triangulation.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 February 2005
%
%  Author:
%
%    Original FORTRAN77 version by Barry Joe,
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Barry Joe,
%    GEOMPACK - a software package for the generation of meshes
%    using geometric algorithms,
%    Advances in Engineering Software,
%    Volume 13, pages 325-331, 1991.
%
%  Parameters:
%
%    Input, integer I, the index of the new vertex.
%
%    Input/output, integer TOP, the index of the top of the stack.
%    On output, TOP is zero.
%
%    Input/output, integer BTRI, BEDG; on input, if positive, are the
%    triangle and edge indices of a boundary edge whose updated indices
%    must be recorded.  On output, these may be updated because of swaps.
%
%    Input, integer NODE_NUM, the number of node.
%
%    Input, real NODE_XY(2,NODE_NUM), the coordinates of
%    the points.
%
%    Input, integer TRIANGLE_NUM, the number of triangles.
%
%    Input/output, integer TRIANGLE_NODE(3,TRIANGLE_NUM), the triangle incidence list.
%    May be updated on output because of swaps.
%
%    Input/output, integer TRIANGLE_NEIGHBOR(3,TRIANGLE_NUM), the triangle neighbor list;
%    negative values are used for links of the counter-clockwise linked
%    list of boundary edges;  May be updated on output because of swaps.
%
%      LINK = -(3*I + J-1) where I, J = triangle, edge index.
%
%    Workspace, integer WORK(MAXST); on input, entries 1 through TOP
%    contain the indices of initial triangles (involving vertex I)
%    put in stack; the edges opposite I should be in interior;  entries
%    TOP+1 through MAXST are used as a stack.
%

%
%  Determine whether triangles in stack are Delaunay, and swap
%  diagonal edge of convex quadrilateral if not.
%
  x = node_xy(1,i);
  y = node_xy(2,i);

  while ( 1 )

    if ( top <= 0 )
      break
    end

    t = work(top);
    top = top - 1;

    if ( triangle_node(1,t) == i )
      e = 2;
      b = triangle_node(3,t);
    elseif ( triangle_node(2,t) == i )
      e = 3;
      b = triangle_node(1,t);
    else
      e = 1;
      b = triangle_node(2,t);
    end

    a = triangle_node(e,t);
    u = triangle_neighbor(e,t);

    if ( triangle_neighbor(1,u) == t )
      f = 1;
      c = triangle_node(3,u);
    elseif ( triangle_neighbor(2,u) == t )
      f = 2;
      c = triangle_node(1,u);
    else
      f = 3;
      c = triangle_node(2,u);
    end

    swap = diaedg ( x, y, node_xy(1,a), node_xy(2,a), node_xy(1,c), node_xy(2,c), ...
      node_xy(1,b), node_xy(2,b) );

    if ( swap == 1 )

      em1 = i4_wrap ( e - 1, 1, 3 );
      ep1 = i4_wrap ( e + 1, 1, 3 );
      fm1 = i4_wrap ( f - 1, 1, 3 );
      fp1 = i4_wrap ( f + 1, 1, 3 );

      triangle_node(ep1,t) = c;
      triangle_node(fp1,u) = i;
      r = triangle_neighbor(ep1,t);
      s = triangle_neighbor(fp1,u);
      triangle_neighbor(ep1,t) = u;
      triangle_neighbor(fp1,u) = t;
      triangle_neighbor(e,t) = s;
      triangle_neighbor(f,u) = r;

      if ( 0 < triangle_neighbor(fm1,u) )
        top = top + 1;
        work(top) = u;
      end

      if ( 0 < s )

        if ( triangle_neighbor(1,s) == u )
          triangle_neighbor(1,s) = t;
        elseif ( triangle_neighbor(2,s) == u )
          triangle_neighbor(2,s) = t;
        else
          triangle_neighbor(3,s) = t;
        end

        top = top + 1;

        if ( node_num < top )
          fprintf ( 1, '\n' );
          fprintf ( 1, 'SWAPEC - Fatal error!\n' );
          fprintf ( 1, '  Exceeded stacksize.\n' );
          error ( 'SWAPEC - Fatal error!' );
        end

        work(top) = t;

      else

        if ( u == btri & fp1 == bedg )
          btri = t;
          bedg = e;
        end

        l = - ( 3 * t + e - 1 );
        tt = t;
        ee = em1;

        while ( 0 < triangle_neighbor(ee,tt) )

          tt = triangle_neighbor(ee,tt);

          if ( triangle_node(1,tt) == a )
            ee = 3;
          elseif ( triangle_node(2,tt) == a )
            ee = 1;
          else
            ee = 2;
          end

        end

        triangle_neighbor(ee,tt) = l;

      end

      if ( 0 < r )

        if ( triangle_neighbor(1,r) == t )
          triangle_neighbor(1,r) = u;
        elseif ( triangle_neighbor(2,r) == t )
          triangle_neighbor(2,r) = u;
        else
          triangle_neighbor(3,r) = u;
        end

      else

        if ( t == btri & ep1 == bedg )
          btri = u;
          bedg = f;
        end

        l = - ( 3 * u + f - 1 );
        tt = u;
        ee = fm1;

        while ( 0 < triangle_neighbor(ee,tt) )

          tt = triangle_neighbor(ee,tt);

          if ( triangle_node(1,tt) == b )
            ee = 3;
          elseif ( triangle_node(2,tt) == b )
            ee = 1;
          else
            ee = 2;
          end

        end

        triangle_neighbor(ee,tt) = l;

      end

    end

  end

  return
end


%------------------------------ PolyMesher -------------------------------%
% Ref: C Talischi, GH Paulino, A Pereira, IFM Menezes, "PolyMesher: A     %
%      general-purpose mesh generator for polygonal elements written in   %
%      Matlab," Struct Multidisc Optim, DOI 10.1007/s00158-011-0706-z     %
%-------------------------------------------------------------------------%
function d = dLine(P,x1,y1,x2,y2)
% By convention, a point located at the left hand side of the line
% is inside the region and it is assigned a negative distance value.
a = [x2-x1,y2-y1]; a = a/norm(a);
b = [P(:,1)-x1,P(:,2)-y1];
d = b(:,1)*a(2) - b(:,2)*a(1);
d = [d,d];
%-------------------------------------------------------------------------%


function [Pro,Res] = transferoperator(HB,NL,isFreeNode)
%% TRANSFEROPERATOR transfer operators between multilevel meshes
%
%  [Pro,Res] = transferoperator(HB,NL) construct matrix representation of
%  transfer operators between levels. All output are cell(level,1).
%
%  In the input, HB is the hierarchical structure of nodes. NL records the
%  starting and ending indices of nodes in each level. see HBstructure or
%  HBstructure3.
%
%  Prolongation (Pro) and restrction (Res) is constructed using standard
%  linear finite element basis and Res = Pro'.
%
%  See also mg, HBstructure, HBstructure3.
%
%  Reference: L. Chen. MultiGrid Methods.

if ~exist('isFreeNode','var'), isFreeNode = []; end
level = length(NL)-1;
Pro = cell(level,1);
Res = cell(level,1);
for j = level:-1:2
    % fine node and coarse node index
    fineNodeRange = NL(j)+1:NL(j+1);
    fineNode = HB(fineNodeRange,1);
    nFineNode = NL(j+1)-NL(j);
    coarseNode = (1:NL(j))';
    isCoarseNode = true(NL(j+1),1);
    isCoarseNode(fineNode) = false;
    coarseNodeFineIdx = find(isCoarseNode);
    ii = [coarseNodeFineIdx; fineNode; fineNode];
    jj = [coarseNode; HB(fineNodeRange,2); HB(fineNodeRange,3)];
    ss = [ones(NL(j),1); 0.5*ones(nFineNode,1); 0.5*ones(nFineNode,1)];
    % remove fix dof from index
    if ~isempty(isFreeNode)
        isFreeNodeC = isFreeNode;
        isFreeNodeC(fineNode) = [];
        Nfree = sum(isFreeNode);
        NfreeC = sum(isFreeNodeC);
        idx = isFreeNode(ii) & isFreeNodeC(jj);
        idxMap(isFreeNode) = (1:Nfree)';
        idxMapC(isFreeNodeC) = (1:NfreeC)';
        ii = idxMap(ii(idx));
        jj = idxMapC(jj(idx));
        ss = ss(idx);
        % generate prolongation matrix
        Pro{j-1} = sparse(ii,jj,ss,Nfree,NfreeC);
        isFreeNode = isFreeNodeC;
    else
        Pro{j-1} = sparse(ii,jj,ss,NL(j+1),NL(j));
    end
    Res{j} = Pro{j-1}';
end


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, 2015-07-13.
%                                      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 isempty(y),  y = zeros(size(mu)); end
  s2zero = 1; if nargin>3&&numel(s2)>0&&norm(s2)>eps, s2zero = 0; 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 isempty(y), 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 res = smoothPolygon(poly, M)
%SMOOTHPOLYGON Smooth a polygon using local averaging.
%
%   RES = smoothPolygon(POLY, M)
%   POLY contains the polygon vertices, and M is the size of smoothing
%   (given as the length of the convolution window).
%
%
%   Example
%     img = imread('circles.png');
%     img = imfill(img, 'holes');
%     contours = bwboundaries(img');
%     contour = contours{1};
%     imshow(img); hold on; drawPolygon(contour, 'b');
%     contourf = smoothPolygon(contour, 11);
%     drawPolygon(contourf, 'm');
%
%   See also
%     polygons2d, smoothPolyline, simplifyPolygon, resamplePolygon

% ------
% Author: David Legland
% E-mail: david.legland@grignon.inra.fr
% Created: 2015-02-17, using Matlab 8.4.0.150421 (R2014b)
% Copyright 2015-2022 INRA - Cepia Software Platform

% compute the number of elements before and after
M1 = floor((M - 1) / 2);
M2 = ceil((M - 1) / 2);

% repeat beginning and end of contour
poly2 = [poly(end-M1+1:end, :) ; poly ; poly(1:M2,:)];

% create convolution vector
v2 = ones(M, 1) / M;

% apply contour filtering
res(:,1) = conv(poly2(:,1), v2, 'same');
res(:,2) = conv(poly2(:,2), v2, 'same');

% keep the interesting part
res = res(M1+1:end-M2, :);


function [Xi,ODEs] = sparsifyDynamics(Theta,dXdt,LHS_Sym,lambda,N,Sym_Struct,disp,NormalizeLib)
% Copyright 2015, All Rights Reserved
% Code by Steven L. Brunton
% For Paper, "Discovering Governing Equations from Data:
%        Sparse Identification of Nonlinear Dynamical Systems"
% by S. L. Brunton, J. L. Proctor, and J. N. Kutz

% compute Sparse regression: sequential least squares
%%
% Modified By: K
% Last Updated
%% Normalize the library data
if NormalizeLib==1
    % Change thisinto parfor to increase the speed if you have a large
    % library

    %parfor norm_k=1:size(Theta,2)

    % Else use the normal for loop
     for norm_k=1:size(Theta,2)
        normLib(norm_k) = norm(Theta(:,norm_k));
        Theta(:,norm_k) = Theta(:,norm_k)/normLib(norm_k);
    end
end

%% Peform sparse regression
Xi = Theta\dXdt;  % initial guess: Least-squares
[n,m]=size(dXdt);

% lambda is our sparsification knob.
for k=1:N
    smallinds = (abs(Xi)<lambda);   % find small coefficients
    Xi(smallinds)=0;                % and threshold
    for ind = 1:m                   % n is state dimension
        biginds = ~smallinds(:,ind);
        % Regress dynamics onto remaining terms to find sparse Xi
        Xi(biginds,ind) = Theta(:,biginds)\dXdt(:,ind);
    end
end

%% Now output the SINDy Identified ODEs

% Now retrive the parameters
if NormalizeLib==1
    for norm_k=1:length(Xi)
        Xi(norm_k,:) = Xi(norm_k,:)/normLib(norm_k);
    end
end

for i=1:m
     ODEs(i,1)=vpa(cell2sym(Sym_Struct)*Xi(:,i));
end

%% Choose whether you want to display the final discovered equation

if disp==1
     fprintf('The SINDy-PI discovered PDE is:\n')
     digits(6)
     for i=1:m
          fprintf(strcat('\t',char(LHS_Sym),'=',char(simplify(ODEs(i,1))),'\n'));
     end
end


function square_grid_test03 ( )

%*****************************************************************************80
%
%% SQUARE_GRID_TEST03 uses a square with different sizes in each dimension.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 August 2014
%
%  Author:
%
%    John Burkardt
%
  a = [   0.0, -2.0 ];
  b = [ +10.0, +2.0 ];
  c = [ 3, 4 ];
  ns = [ 3, 3 ];

  n = ns(1) * ns(2);

  fprintf ( 1, '\n' );
  fprintf ( 1, 'SQUARE_GRID_TEST03\n' );
  fprintf ( 1, '  Create a grid using SQUARE_GRID.\n' );
  fprintf ( 1, '  Use a different physical size in every dimension.\n' );
  fprintf ( 1, '  Number of grid points N = %d\n', n );
  fprintf ( 1, '\n' );
  fprintf ( 1, '     I    NS     C      A         B\n' );
  fprintf ( 1, '\n' );
  for i = 1 : 2
    fprintf ( 1, '  %4d  %4d  %4d  %8.4f  %8.4f\n', i, ns(i), c(i), a(i), b(i) );
  end

  x = square_grid ( n, ns, a, b, c );
  r8mat_transpose_print ( 2, n, x, '  Grid points:' );

  return
end


function [seg, SEG_l] = ahmLinSegment(l,t)

% AHMLINSEGMENT  AHM line endpoints.
%   AHMLINSEGMENT(L,T) returns the 3D segment corresponding to the HMG line
%   L at abscissas T = [t1;t2].
%
%   [s,S_l] = AHMLINSEGMENT(...) returns the Jacobian wrt L.
%
%   See also AHMLINENDPOINTS, AHMLIN2SEG, AHMLIN2IDPPNTS.

%   Copyright 2009 Teresa Vidal.

% abscissas
t1 = t(1);
t2 = t(2);

% support 3d segment
[s, S_l] = ahmLin2seg(l);

% support points
p1 = s(1:3);
p2 = s(4:6);

P1_l = S_l(1:3,:);
P2_l = S_l(4:6,:);

% 3d endpoints
e1 = (1-t1)*p1 + t1*p2;
e2 = (1-t2)*p1 + t2*p2;

E1_p1 = 1-t1;
E1_p2 = t1;
E2_p1 = 1-t2;
E2_p2 = t2;

E1_l = E1_p1*P1_l + E1_p2*P2_l;
E2_l = E2_p1*P1_l + E2_p2*P2_l;

% 3d segment
seg   = [e1;e2];
SEG_l = [E1_l;E2_l];

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB 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.
%
%   SLAMTB 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 SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE


function op = smooth_entropy()
%SMOOTH_ENTROPY The entropy function -sum( x_i log(x_i) )
op = @smooth_entropy_impl;

function [ v, g ] = smooth_entropy_impl( x )
if any( x < 0 ),
    v = -Inf;
    if nargout > 1,
        g = NaN * ones(size(x));
    end
else
    logx = log(max(x,realmin));
    v = - tfocs_dot( x, logx );
    if nargout > 1,
        g = - logx - 1;
    end
end

% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.
% Copyright 2013 California Institute of Technology and CVX Research.
% See the file LICENSE for full license information.


function pf = noisepf(pf,fak,background,varargin)
% simulate diffraction counts
%
% noisepf simulates realistic diffraction counts by generating random
% samples of the Poisson distribution with mean m = alpha * pdf + bg
%
% Syntax
%   pdfn = noisepf(pdf,alpha,bg)
%
% Input
%  pf    - @PoleFigure
%  alpha - uniform radiation (double)
%  bg    - background radiation (double)
%
% Options
%  NONNEGATIV - force data to be non negative
%
% See also
% SO3Fun/calcPoleFigure

if nargin == 2, background = 0;end
if numel(fak) == 1, fak = repmat(fak,pf.numPF,1);end

for i = 1:pf.numPF
  pf.allI{i} = ...
  randp(fak(i)*pf.allI{i} + background) - background;
  if check_option(varargin,'NONNEGATIV')
    pf.allI{i}(pf.allI{i} < 0) = 0;
  end
end


function [out] = evap_10(p1,S,Smax,Ep,dt)
%evap_10

% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter
% This file is part of the Modular Assessment of Rainfall-Runoff Models
% Toolbox (MARRMoT).
% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY
% WARRANTY. See <https://www.gnu.org/licenses/> for details.

% Flux function
% ------------------
% Description:  Evaporation from bare soil scaled by relative storage
% Constraints:  Ea <= Ep
%               Ea <= S/dt
% @(Inputs):    p1   - fraction of area that is bare soil [-]
%               S    - current storage [mm]
%               Smax - maximum storage [mm]
%               Ep   - potential evapotranspiration rate [mm/d]
%               dt   - time step size [d]

out = max(min(p1.*S./Smax.*Ep,S/dt),0);

end


classdef nncaffepool < nntest

  properties
    x
  end

  properties (TestParameter)
    type = {'avg', 'max'}
    poolx = {1 2 3}
    pooly = {1 2}
    pool = {1 2 3}
    pad = {0 1 2}
    stride = {1 2 3 4}
    stridex = {1 2 3}
    stridey = {1 2}
    padLeft = {0 1 2}
    padRight = {0 1 2}
    padTop = {0 1 2}
    padBottom = {0 1 2}
  end

  methods (TestClassSetup)
    function data(test,device)
      % make sure that all elements in x are different. in this way,
      % we can compute numerical derivatives reliably by adding a delta < .5.
      x = test.randn(15,14,3,2) ;
      x(:) = randperm(numel(x))' ;
      test.x = x ;
      test.range = 10 ;
      if strcmp(device,'gpu'), test.x = gpuArray(test.x) ; end
    end
  end

  methods (Test)
    function basic(test,poolx,pooly)
      % Test whether the avg pool output is equal to its emulation with
      % convolutional layer
      x = test.x ;
      stride = 1 ;
      pad = 0 ;
      pool = [pooly poolx] ;
      args = {'stride',stride,'pad',pad, 'method', 'avg'};
      y = vl_nncaffepool(x,pool,args{:}) ;
      y_conv = vl_nnconv(gather(x), ...
                         ones(pooly,poolx,1,size(x,3),test.currentDataType)./poolx./pooly, ...
                         zeros(1,size(x,3),test.currentDataType), ...
                         'stride', stride, ...
                         'pad', pad);
      test.eq(y, y_conv, 1e-3); % Does not pass with 1e-4
    end

    function pool_type(test, type, pool, pad, stride)
      x = test.x ;
      if pad > pool-1, return ; end
      args = {'stride',stride,'pad',pad,'method',type};
      y = vl_nncaffepool(x,pool,args{:}) ;
      dzdy = test.randn(size(y)) ;
      dzdx = vl_nncaffepool(x,pool,dzdy,args{:}) ;
      test.der(@(x) vl_nncaffepool(x,pool,args{:}), ...
               x, dzdy, dzdx, test.range * 1e-2) ;
    end

    function pool_type_and_pad(test, type, poolx, pooly, stride)
      x = test.x ;
      stride = 1 ;
      pad = 0 ;
      pool = [pooly poolx] ;
      args = {'stride',stride,'pad',pad,'method',type};
      y = vl_nncaffepool(x,pool,args{:}) ;
      dzdy = test.randn(size(y)) ;
      dzdx = vl_nncaffepool(x,pool,dzdy,args{:}) ;
      test.der(@(x) vl_nncaffepool(x,pool,args{:}), ...
               x, dzdy, dzdx, test.range * 1e-2) ;
    end

    function pool_type_and_stride(test, type, stridex, stridey)
      x = test.x ;
      pad = 0 ;
      pool = [3 2] ;
      stride = [stridey stridex] ;
      args = {'stride',stride,'pad',pad,'method',type};
      y = vl_nncaffepool(x,pool,args{:}) ;
      dzdy = test.randn(size(y)) ;
      dzdx = vl_nncaffepool(x,pool,dzdy,args{:}) ;
      test.der(@(x) vl_nncaffepool(x,pool,args{:}), ...
               x, dzdy, dzdx, test.range * 1e-2) ;
    end

    function asym_pad1(test, type, padLeft, padRight)
      x = test.x ;
      pool = [3 4] ;
      stride = [2 1] ;
      pad = [0 0 padLeft padRight] ;
      args = {'stride',stride,'pad',pad,'method',type};
      y = vl_nncaffepool(x,pool,args{:}) ;
      dzdy = test.randn(size(y)) ;
      dzdx = vl_nncaffepool(x,pool,dzdy,args{:}) ;
      test.der(@(x) vl_nncaffepool(x,pool,args{:}), ...
               x, dzdy, dzdx, test.range * 1e-2) ;
    end

    function asym_pad2(test, type, padTop, padBottom)
      x = test.x ;
      pool = [3 4] ;
      stride = [2 1] ;
      pad = [padTop padBottom 2 1] ;
      args = {'stride',stride,'pad',pad,'method',type};
      y = vl_nncaffepool(x,pool,args{:}) ;
      dzdy = test.randn(size(y)) ;
      dzdx = vl_nncaffepool(x,pool,dzdy,args{:}) ;
      test.der(@(x) vl_nncaffepool(x,pool,args{:}), ...
               x, dzdy, dzdx, test.range * 1e-2) ;
    end
  end
end


function Q = up_expert_findQ(b, data, del0, delta)
% This program finds Q for KV02
%
% function Q = up_expert_findQ(b, data, del0, delta, N)
%
% Q: A modification of the random walk wealth distribution P
%
% b: portfolio
% data: market sequence
% del0, delta: parameters
%
% Example: Q = up_expert_findQ(b, data, del0, delta, N);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This file is part of OLPS: http://OLPS.stevenhoi.org/
% Original authors: Bin LI, Steven C.H. Hoi
% Contributors:
% Change log:
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[~, N] = size(data);  % Number of stocks,Time period.

P = prod(data(:, :)*b);

Q = P*min(1, exp((b(N)-(2*del0))/(N*delta)));

end


clc, clear
c=[3 8 2 10 3;8 7 2 9 7;6 4 2 7 5
   8 4 2 3 5;9 10 6 9 10];
c=c(:); a=zeros(10,25); intcon=1:25;
for i=1:5
   a(i,(i-1)*5+1:5*i)=1;
   a(5+i,i:5:25)=1;
end
b=ones(10,1); lb=zeros(25,1); ub=ones(25,1);
x=intlinprog(c,intcon,[],[],a,b,lb,ub);
x=reshape(x,[5,5])


function x7 = testNet(x, net, Params)

    N=size(x,1);
    W=net.W;B=net.B;
    dropP=Params.dropP;
    %% forward
    [x1,~]=dropout(x,dropP(1));%N*V
    x2=x1*W{1}+repmat(B{1},N,1);%N*neuronN
    x3=max(0,x2);%ReLU
    [x4, ~]=dropout(x3,dropP(2));
    x5=x4*W{2}+repmat(B{2},N,1);
    x6=(exp(x5)-exp(-x5))./(exp(x5)+exp(-x5));%Sigmoid%N*neuronN
    x7=x6*W{3}+repmat(B{3},N,1);%N*M
end


% Compute the log intensity for the inverse link function g(f) = exp(-exp(-f)).
%
% The function is used in GLM likelihoods such as likPoisson, likGamma, likBeta
% and likInvGauss.
%
% Copyright (c) by Hannes Nickisch, 2013-10-16.

function [lg,dlg,d2lg,d3lg] = glm_invlink_expexp(f)
  lg = -exp(-f);
  if nargout>1
    dlg = -lg;
    if nargout>2
      d2lg = lg;
      if nargout>2
        d3lg = -lg;
      end
    end
  end


% load dataset
load('SimTest.mat');
% current data
steering_req_vec = debug.debug_mvdc_curvvel_tracking_debug_Req_Delta_rad.Data;
steering_vec = debug.debug_VehicleSensorData_Delta_Wheel_rad.Data;
kappa_vec = debug.debug_mvdc_state_estimation_debug_StateEstimate_kappa_radpm.Data;
velocity_vec = debug.debug_mvdc_state_estimation_debug_StateEstimate_v_mps.Data;
curv_req = debug.debug_mvdc_curvvel_tracking_debug_Curv_TargetCurv_radpm.Data;

% parameters
filter_coeff_virtual_ss = 0.07;
P_VDC_SCLearn_Sigma = 0.01;
P_VDC_SCLearn_LengthScales = [0.04, 5];
l_front_m = 1.51;
l_rear_m = 1.388;
P_VDC_SCLearn_FilterCoeff = 0.999;
P_VDC_SCLearn_KappaMax_radpm = 0.13;
P_VDC_SCLearn_vMax_mps = 60;
P_VDC_MinVelSlipCalc_mps = 3;

% iterate via all data points
steering_steady_virtual = zeros(length(steering_req_vec)+1, 1);
steering_comp = zeros(length(steering_req_vec), 1);
% clear persistent variaables
clear learnSteeringCharacteristic;
for i = 1:1:length(steering_req_vec)
    % call steering characteristic update
    [SC_Kappa_Out, SC_Vel_Out, SC_DeltaNeutral_Out, SC_meas] =...
        learnSteeringCharacteristic(steering_steady_virtual(i), ...
                                        kappa_vec(i), velocity_vec(i), P_VDC_SCLearn_Sigma, ...
                            P_VDC_SCLearn_LengthScales, l_front_m, l_rear_m, ...
                            P_VDC_SCLearn_FilterCoeff, P_VDC_SCLearn_KappaMax_radpm, ...
                            P_VDC_SCLearn_vMax_mps, P_VDC_MinVelSlipCalc_mps);
    steering_steady_virtual(i+1) = (1-filter_coeff_virtual_ss)*steering_steady_virtual(i) + ...
                                    filter_coeff_virtual_ss*steering_req_vec(i);
    steering_comp(i) = interp2(SC_Vel_Out, SC_Kappa_Out, SC_DeltaNeutral_Out,...
                            velocity_vec(i), curv_req(i),...
                            'linear', 0);
end

%% visualize Results
close all;

figure;
surface(SC_Vel_Out, SC_Kappa_Out, SC_DeltaNeutral_Out);
colorbar;
xlabel('Velocity in mps');
ylabel('Kappa in radpm');
zlabel('Steering Angle Correction in rad');
title('Smoothed Understeer Compensation Profile');

figure;
surface(SC_Vel_Out, SC_Kappa_Out, SC_meas);
colorbar;
xlabel('Velocity in mps');
ylabel('Kappa in radpm');
zlabel('Steering Angle Correction in rad');
title('Raw Understeer Compensation Profile');

% visualize steering time values
figure;
plot(steering_vec);
grid on; hold on;
plot(kappa_vec*2.898);
plot(steering_req_vec);
plot(steering_steady_virtual);
plot(steering_comp);
legend('steering', 'neutral', 'req', 'virtual_ss', 'ff');


% This is material illustrating the methods from the book
% Financial Modelling  - Theory, Implementation and Practice with Matlab
% source
% Wiley Finance Series
% ISBN 978-0-470-74489-5
%
% Date: 02.05.2012
%
% Authors:  Joerg Kienitz
%           Daniel Wetterau
%
% Please send comments, suggestions, bugs, code etc. to
% kienitzwetterau_FinModelling@gmx.de
%
% (C) Joerg Kienitz, Daniel Wetterau
%
% Since this piece of code is distributed via the mathworks file-exchange
% it is covered by the BSD license
%
% This code is being provided solely for information and general
% illustrative purposes. The authors will not be responsible for the
% consequences of reliance upon using the code or for numbers produced
% from using the code.

function y = pcev(t,f,f0,sigma, beta)
%Probability Distribution from CEV dynamics
%   dS(t) = sigma S(t)^beta dW(t)
%   t = maturity
%   f0 = spot
%   f = forward
%   sigma = volatility
%   beta = CEV exponent

nu = sigma^2*t;
k = 2 ./(nu * (2-beta)^2);
x = k.*f0^(2-beta);
w = k.*f.^(2-beta);

q = 1 / ( 2 - beta);

wbess = (2-beta) .* (x .* w.^(1-2.*beta)).^(1/(4-2*beta)) ...
    .* exp(-x-w) .*k .^(1 ./(2-beta));

Z = 2 * sqrt(x.*w);

bess = besseli(q,Z);

y= wbess.* bess;

end


function [varargout] = likGaussHe(hyp, y, s, 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, 2015-07-13.
%                                      File automatically generated using noweb.
%
% See also LIKFUNCTIONS.M.

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

if isempty(s)
    sn2 = exp(2*hyp);
else
    sn2_base = exp(2*hyp);
    sn2 = sn2_base + s.^2;
end

if nargin<6                              % prediction mode if inf is not present
  if isempty(y);  y = zeros(size(mu)); end
  if isempty(s);  s = zeros(size(mu)); end
  s2zero = 1; if nargin>4&&numel(s2)>0&&norm(s2)>eps, s2zero = 0; end  % s2==0 ?
  if s2zero                                                    % log probability
    lp = -(y-mu).^2./sn2/2-log(2*pi*sn2)/2; s2 = 0;
  else
    lp = likGaussHe(hyp, y, s, 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 isempty(y), 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<7                                             % 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 eer_val = eer(tar,non)
% Calculates the equal error rate from a set of target and
% non-target scores.
% Inputs:
%   tar: vector of target scores
%   non: vector of non-target scores
% Output:
%   eer: the equal error rate.

assert(isvector(tar))
assert(isvector(non))

[Pmiss,Pfa] = rocch(tar,non);
eer_val = rocch2eer(Pmiss,Pfa);


function [Ain,bin,Aeq,beq] = mix2gen(A,b,e)
%MIX2GEN  Convert Mixed linear constraints to General Linear inequality and equality
%   [A,b,Aeq,beq] = mix2gen(A,b,e)
%
%   Use -1 for <=, 0 for =, and 1 for >= in vector e

%   Copyright (C) 2011 Jonathan Currie (IPL)

if(size(A,1) ~= length(b))
    error('A and b sizes do not correspond');
end
if(length(b) ~= length(e))
    error('b and e are not the same length!');
end
if(any(e < -1) || any(e > 1))
    error('The vector e must only contain values -1, 0 or 1');
end

eq = find(e == 0);
leq = find(e == -1);
geq = find(e == 1);

%Transpose as neccesary
if(size(b,2) > 1)
    b = b';
end

%Process Equality Constraints
if(isempty(eq))
    Aeq = []; beq = [];
else
    Aeq = A(eq,:);
    beq = b(eq);
end

%Process <= Constraints
if(isempty(leq))
    Ain = []; bin = [];
else
    Ain = A(leq,:);
    bin = b(leq);
end

%Process >= Constraints
if(~isempty(geq))
    Ain = [Ain;-A(geq,:)];
    bin = [bin;-b(geq)];
end


%Trajectory_Examples.m
%
% This script contains a few sample "roads". SetPts are a series of points
% along the road, to which a polynomial is fit. Therer are also a few
% simulation parameters associated with each example.
%

Params.Sim.Example_Number = Example_Number;
switch Example_Number
    case 1
        Params.Traj.Func = false;
        Params.Traj.SetPts = [...
            0,0;
            10,5;
            20,9;
            40,9;
            60,0;
            80,-10];
        Params.Traj.Order = 4;
        Params.Sim.IC_Error = [0;0;0;0];
        Max_Pos_Err = 0.5;
        Params.Ctl.Minimum_Goal_Distance = 1; %(m) how far to "look ahead"
        Simulation_Duration = 60;
        Control_Frequency = 50;   %Hz

    case 2
        %This one appears to work reasonably well
        Params.Traj.Func = false;
        Params.Traj.SetPts = [...
            0,0;
            10,5;
            20,9;
            40,9;
            60,0;
            65,-2.5;
            70, -5;
            75,-8
            80,-12];
        Params.Traj.Order = 4;
        Params.Sim.IC_Error = [0;0;0;0];
        Max_Pos_Err = 0.5;
        Params.Ctl.Minimum_Goal_Distance = 1; %(m) how far to "look ahead"
        Simulation_Duration = 50;
        Control_Frequency = 50;   %Hz

    case 3
        Params.Traj.Func = false;
        Params.Traj.SetPts = [...
            0 0;
            5 0;
            10 1;
            15 3;
            20 2;
            25 0;
            30 -3;
            35 -8;
            40 -13;
            45 -20;
            50 -30;
            55 -40];
        Params.Traj.Order = 4;
        Params.Sim.IC_Error = [0;0;0;0];
        Max_Pos_Err = 1.5;
        Params.Ctl.Minimum_Goal_Distance = 1; %(m) how far to "look ahead"
        Simulation_Duration = 125;
        Control_Frequency = 40;   %Hz

 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    case 4
        %USED IN PRESENTATION - MAIN RESULT

	    Params.Traj.Func = true;
        x = linspace(0,150,Params.Traj.Npts+1)';
        Params.Traj.x = x;
        Params.Traj.y = sin(x/20).*25.*x.^2/(150^2);
        Params.Sim.IC_Error = [0;0;0;0];
        Max_Pos_Err = 1.5;  %used for setting lqr gains
        Params.Ctl.Minimum_Goal_Distance = 1; %(m) how far to "look ahead"
        Simulation_Duration = 90;
        Control_Frequency = 50;   %Hz
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    case 5
        % Works
        Params.Traj.Func = true;
        x = linspace(0,150,Params.Traj.Npts+1)';
        Params.Traj.x = x;
        Params.Traj.y = sin(x/15).*25;
        Params.Sim.IC_Error = [0;0;0;0];
        Max_Pos_Err = 1.5;
        Params.Ctl.Minimum_Goal_Distance = 1; %(m) how far to "look ahead"
        Simulation_Duration = 160;
        Control_Frequency = 10;   %Hz

    case 6
      % USED IN PRESENTATION - Appendix 1
      %Long version of 5 (many turns)  -- good demonstration
        Params.Traj.Func = true;
        Params.Traj.Npts = 250; %Override the number of points
        Params.Traj.Max_Rd_Idx = 245;
        x = linspace(0,350,Params.Traj.Npts+1)';
        Params.Traj.x = x;
        Params.Traj.y = sin(x/20+pi/3).*cos(x/100)*25;
        Params.Sim.IC_Error = [0;0;0;0];
        Max_Pos_Err = 1.5;  %used for setting lqr gains
        Params.Ctl.Minimum_Goal_Distance = 1; %(m) how far to "look ahead"
        Simulation_Duration = 235;
        Control_Frequency = 50;   %Hz

    case 7
        %Cosine Road
        Params.Traj.Npts = 150;
        Freq = 0.35;
        Amp = 25;
        Params.Traj.Func = true;
        x = linspace(0,150,Params.Traj.Npts+1)';
        Params.Traj.x = x;
        Params.Traj.y = Amp*cos((2*pi/Amp)*x*Freq+0.1);
        Params.Sim.IC_Error = [0;0;0;0];
        Max_Pos_Err = 1.5;
        Params.Ctl.Minimum_Goal_Distance = 1; %(m) how far to "look ahead"
        Simulation_Duration = 250;
        Control_Frequency = 50;   %Hz

     case 8
      %REALLY LONG version of 5 (many turns)  -- good demonstration
        Params.Traj.Func = true;
        Params.Traj.Npts = 1000; %Override the number of points
        Params.Traj.Max_Rd_Idx = 995;
        x = linspace(0,350,Params.Traj.Npts+1)';
        Params.Traj.x = x;
        Params.Traj.y = sin(x/20+pi/3).*cos(x/100)*25;
        Params.Sim.IC_Error = [0;0;0;0];
        Max_Pos_Err = 1.5;  %used for setting lqr gains
        Params.Ctl.Minimum_Goal_Distance = 2; %(m) how far to "look ahead"
        Simulation_Duration = 235*4;
        Control_Frequency = 50;   %Hz

    otherwise
        error('Invalid Example Number')

end


function [f, df, d2f] = nlp_costfcn(om, x)
%NLP_COSTFCN  Evaluates objective function, gradient and Hessian.
%   [F, DF, D2F] = NLP_COSTFCN(OM, X)
%
%   Objective function evaluation routine, suitable for use with MIPS,
%   FMINCON, etc. Computes objective function value, gradient and Hessian.
%
%   Inputs:
%     OM : Opt-Model object
%     X : optimization vector
%
%   Outputs:
%     F   : value of objective function
%     DF  : (optional) gradient of objective function (column vector)
%     D2F : (optional) Hessian of objective function (sparse matrix)
%
%   Examples:
%       f = nlp_costfcn(om, x);
%       [f, df] = nlp_costfcn(om, x);
%       [f, df, d2f] = nlp_costfcn(om, x);
%
%   See also NLP_CONSFCN, NLP_HESSFCN.

%   MP-Opt-Model
%   Copyright (c) 1996-2020, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MP-Opt-Model.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://github.com/MATPOWER/mp-opt-model for more info.

%%----- evaluate objective function -----
%% general nonlinear costs
if nargout == 3
    [f, df, d2f]    = om.eval_nln_cost(x);
    if om.qdc.NS
        [fq, dfq, d2fq] = om.eval_quad_cost(x);
        f = f + sum(fq);
        df = df + dfq;
        d2f = d2f + d2fq;
    end
elseif nargout == 2
    [f, df]   = om.eval_nln_cost(x);
    if om.qdc.NS
        [fq, dfq] = om.eval_quad_cost(x);
        f = f + sum(fq);
        df = df + dfq;
    end
else
    f  = om.eval_nln_cost(x);
    if om.qdc.NS
        fq = om.eval_quad_cost(x);
        f = f + sum(fq);
    end
end


function [p,q,D,sc] = dpfast(M,C,T,G)
% [p,q,D,sc] = dpfast(M,C,T,G)
%    Use dynamic programming to find a min-cost path through matrix M.
%    Return state sequence in p,q; full min cost matrix as D and
%    local costs along best path in sc.
%    This version gives the same results as dp.m, but uses dpcore.mex
%    to run ~200x faster.
%    C is a step matrix, with rows (i step, j step, cost factor)
%    Default is [1 1 1.0;0 1 1.0;1 0 1.0];
%    Another good one is [1 1 1;1 0 1;0 1 1;1 2 2;2 1 2]
%    T selects traceback origin: 0 is to any edge; 1 is top right (default);
%    T > 1 finds path to min of anti-diagonal T points away from top-right.
%    Optional G defines length of 'gulleys' for T=0 mode; default 0.5
%    (i.e. accept path to only 50% of edge nearest top-right)
% 2003-04-04,2005-04-04 dpwe@ee.columbia.edu $Header: /Users/dpwe/projects/dtw/RCS/dpfast.m,v 1.6 2008/03/14 14:40:50 dpwe Exp dpwe $

% Copyright (c) 2003 Dan Ellis <dpwe@ee.columbia.edu>
% released under GPL - see file COPYRIGHT

if nargin < 2
  % Default step / cost matrix
  C = [1 1 1.0;0 1 1.0;1 0 1.0];
end

if nargin < 3
  % Default: path to top-right
  T = 1;
end

if nargin < 4
  % how big are gulleys?
  G = 0.5;  % half the extent
end

if sum(isnan(M(:)))>0
  error('dpwe:dpfast:NAN','Error: Cost matrix includes NaNs');
end

if min(M(:)) < 0
  disp('Warning: cost matrix includes negative values; results may not be what you expect');
end

[r,c] = size(M);

% Core cumulative cost calculation coded as mex
[D,phi] = dpcore(M,C);

p = [];
q = [];

%% Traceback from top left?
%i = r;
%j = c;

if T == 0
  % Traceback from lowest cost "to edge" (gulleys)
  TE = D(r,:);
  RE = D(:,c);
  % eliminate points not in gulleys
  TE(1:round((1-G)*c)) = max(max(D));
  RE(1:round((1-G)*r)) = max(max(D));
  if (min(TE) < min(RE))
    i = r;
    j = max(find(TE==min(TE)));
  else
    i = max(find(RE==min(RE)));
    j = c;
  end
else
  if min(size(D)) == 1
    % degenerate D has only one row or one column - messes up diag
    i = r;
    j = c;
  else
    % Traceback from min of antidiagonal
    %stepback = floor(0.1*c);
    stepback = T;
    slice = diag(fliplr(D),-(r-stepback));
    [mm,ii] = min(slice);
    i = r - stepback + ii;
    j = c + 1 - ii;
  end
end

p=i;
q=j;

sc = M(p,q);

while i > 1 & j > 1
%  disp(['i=',num2str(i),' j=',num2str(j)]);
  tb = phi(i,j);
  i = i - C(tb,1);
  j = j - C(tb,2);
  p = [i,p];
  q = [j,q];
  sc = [M(i,j),sc];
end


function designs = get_design_set(name, d_0)
%GET_DESIGN_SET Gets a set of arrays designs for simulations.
%Inputs:
%   name - 'SameAperture': four designs with the same aperture.
%          'SameNumSensor': four designs with the same number of sensors.
%          'Nested10': seven nested arrays with the same number of sensors.
%   d_0 - Minimal inter-element spacing.
%Output:
%   designs - A cell array of array designs.
switch lower(name)
    case 'sameaperture'
        % same aperture
        designs = { ...
            design_array_1d('coprime', [2 3], d_0, '2M', 'Co-prime (2,3)') ...
            design_array_1d('custom', [0 1 2 6 9]*d_0, d_0, 'MRA 5') ...
            design_array_1d('nested', [1 5], d_0, 'Nested (1,5)') ...
            design_array_1d('nested', [4 2], d_0, 'Nested (4,2)') ...
        };
    case 'samenumsensor'
        designs = { ...
            design_array_1d('coprime', [3 5], d_0, '2M', 'Co-prime (3,5)') ...
            design_array_1d('custom', [0 1 4 10 16 22 28 30 33 35]*d_0, d_0, 'MRA 10') ...
            design_array_1d('nested', [4 6], d_0, 'Nested (4,6)') ...
            design_array_1d('nested', [3 7], d_0, 'Nested (3,7)') ...
        };
    case 'nested10'
        designs = { ...
            design_array_1d('nested', [2 8], d_0, 'Nested (2,8)') ...
            design_array_1d('nested', [3 7], d_0, 'Nested (3,7)') ...
            design_array_1d('nested', [4 6], d_0, 'Nested (4,6)') ...
            design_array_1d('nested', [5 5], d_0, 'Nested (5,5)') ...
            design_array_1d('nested', [6 4], d_0, 'Nested (6,4)') ...
            design_array_1d('nested', [7 3], d_0, 'Nested (7,3)') ...
            design_array_1d('nested', [8 2], d_0, 'Nested (8,2)') ...
        };
    otherwise
        error('Unknown design set ''%s''.', name);
end
end


function [] = mci_plot_dist (dist,j,xlims)
% Plot probability density
% FORMAT [] = mci_plot_dist (dist,j,xlims)
%
% dist      struct with fields
%
% .Ep       posterior mean
% .P        [Np x Ns] sample matrix
% .ind      indices of samples dist burn-in
% .names
% .ks       set to 1 for kernel smoothing (default)
% j         jth variable
% xlims     xlims(1,2) for lower/upper limits
%__________________________________________________________________________
% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging

% Will Penny
% $Id: mci_plot_dist.m 6697 2016-01-27 14:57:28Z spm $

try, ks=dist.ks; catch, ks=1; end

if nargin > 2
    limits=1;
else
    limits=0;
end
lw=2;

switch lower(dist.type),
    case 'boxplot',
        boxplot(dist.P(j,dist.ind));
    case 'sample',
        if ks
            [g,xi]=ksdensity(dist.P(j,dist.ind));
            plot(xi,g,dist.color,'LineWidth',lw);set(gca,'YTick',[]);
        else
            hist(dist.P(j,dist.ind),20);
        end
    case 'gaussian',
        m=dist.Ep(j);s=sqrt(full(dist.Cp(j,j)));
        xi=linspace(m-4*s,m+4*s,100);
        g=spm_Npdf(xi,m,s^2);
        plot(xi,g,dist.color,'LineWidth',lw);set(gca,'YTick',[]);
end
set(gca,'FontSize',16);
xlabel(dist.names{j});
grid on

if limits
    xlim([xlims(1) xlims(2)]);
end


function Lrho = construct_connection_Laplacian(measurements)
%function Lrho = construct_connection_Laplacian(measurements)
%
% This function computes and returns the connection Laplacian for the
% rotational observations (see eq. (15) of the paper).

D = length(measurements.t{1}); % D = dimension of SE(d)
N = max(max(measurements.edges));  % N = number of nodes in the pose graph
M = size(measurements.edges,1); % M = number of edges in the pose graph

% The number of nonzero elements in the connection Laplacian; there are
% 2*D^2*M nonzero elements corresponding to the off-diagonal blocks
% containing the raw measurements (one dxd rotation matrix above the main
% diagonal, and another below, for each of the M measurements, plus D*N
% nonzero elements along the main diagonal for the scaled identity
% matrices.  Note that in the case of multiple observations between two
% nodes x_i and x_j the corresponding (i,j) block in the connection
% Laplacian should contain the *sum* of the weighted observations
% kappa_{ij} R_{ij} between these nodes.  We achieve this result below by
% exploiting the fact that MATLAB's sparse() command forms the resulting
% sparse matrix by *summing* values with the same (i,j) indices.

% Copyright (C) 2016 by David M. Rosen

D2 = D^2;
off_diag_inc = 2*D2;

NNZ = off_diag_inc * M + D*N;

%Allocate storage for the row, column, and value vectors

rows = zeros(1, NNZ);
cols = zeros(1, NNZ);
vals = zeros(1, NNZ);

degs = zeros(1, N);  %Vector to store the degrees of the nodes

%Iterate over the measurements in the pose graph
for k = 1:M

    %EXTRACT MEASUREMENT DATA
    i = measurements.edges(k, 1);  %The node that this edge leaves
    j = measurements.edges(k, 2);  %The node that this edge enters

    Rij = measurements.R{k};  %The rotation matrix for this observation

    kappa = measurements.kappa{k};  %The precision for this rotational observation

    %PROCESS MEASUREMENT DATA

    %Increment the degrees of the ith and jth nodes by kappa
    degs(i) = degs(i) + kappa;
    degs(j) = degs(j) + kappa;

    %Set the (i,j)th DxD block of Lrho = -kappa*Rij
    [r, c, Rvect] = rcvize_matrix(Rij, i, j);
    rows(off_diag_inc*(k - 1) + 1 : off_diag_inc*(k-1) + D2) = r;
    cols(off_diag_inc*(k - 1) + 1 : off_diag_inc*(k-1) + D2) = c;
    vals(off_diag_inc*(k - 1) + 1 : off_diag_inc*(k-1) + D2) = -kappa*Rvect;

    %Set the (j,i)th DxD block of Lrho = -kappa*R_ij^T
    [r, c, Rvect] = rcvize_matrix(Rij', j, i);
    rows(off_diag_inc*(k - 1) + D2 + 1 : off_diag_inc*(k-1) + off_diag_inc) = r;
    cols(off_diag_inc*(k - 1) + D2 + 1 : off_diag_inc*(k-1) + off_diag_inc) = c;
    vals(off_diag_inc*(k - 1) + D2 + 1 : off_diag_inc*(k-1) + off_diag_inc) = -kappa*Rvect;
end

%Now set the diagonal elements to be D-fold copies of the degrees of each
%node

rows(off_diag_inc*M + 1 : NNZ) = [1:D*N];
cols(off_diag_inc*M + 1 : NNZ) = [1:D*N];
vals(off_diag_inc*M + 1 : NNZ) = kron(degs, ones(1,D));

Lrho = sparse(rows, cols, vals, D*N, D*N);

end


function [ inlierPointsLeft, inlierPointsRight ] = extractBinnedFeatures( viLeftImage, viRightImage )

inlierPointsLeft = [];
inlierPointsRight = [];
       % Binning

        uBin = 1:floor(size(viLeftImage,2)/6):size(viLeftImage,2);
        vBin = 1:floor(size(viLeftImage,1)/2):size(viLeftImage,1);
        uBinSize = diff([uBin,size(viLeftImage,2)]);
        vBinSize = diff([vBin,size(viLeftImage,1)]);
        [UBIN, VBIN] = meshgrid(uBin, vBin);
        [UBINSIZE, VBINSIZE] = meshgrid(uBinSize, vBinSize);
        UBIN = UBIN(:);
        VBIN = VBIN(:);
        UBINSIZE = UBINSIZE(:);
        VBINSIZE = VBINSIZE(:);

        for b = 1:size(UBIN,1)
            roiVec = [UBIN(b), VBIN(b), UBINSIZE(b), VBINSIZE(b)];

            %Detect strongest corners
            leftPoints = detectSURFFeatures(viLeftImage,'ROI',roiVec);
            rightPoints = detectSURFFeatures(viRightImage,'ROI',roiVec);

            %leftPoints = leftPoints.selectStrongest(50);
            %rightPoints = rightPoints.selectStrongest(50);

            %Extract features and stereo match
           [featuresLeft, validLeftPoints] = extractFeatures(viLeftImage, leftPoints);
           [featuresRight, validRightPoints] = extractFeatures(viRightImage, rightPoints);

            indexPairs = matchFeatures(featuresLeft, featuresRight);
            matchedPointsLeft = validLeftPoints(indexPairs(:, 1), :);
            matchedPointsRight = validRightPoints(indexPairs(:, 2), :);

            inliers = abs((matchedPointsLeft.Location(:, 2) - matchedPointsRight.Location(:, 2))) <= 1 & abs((matchedPointsLeft.Location(:, 1) - matchedPointsRight.Location(:, 1))) > 3;

            inlierPointsLeft = [inlierPointsLeft; matchedPointsLeft(inliers).Location];
            inlierPointsRight = [inlierPointsRight; matchedPointsRight(inliers).Location];
        end

end


function components_test02 ( )

%*****************************************************************************80
%
%% COMPONENTS_TEST02 tests I4MAT_COMPONENTS on a simple case.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 March 2011
%
%  Author:
%
%    John Burkardt
%
  m = 9;
  n = 17;

  a = [ ...
    0, 0, 0, 0, 0, 0, 0, 0, 0; ...
    0, 0, 1, 0, 0, 1, 0, 0, 0; ...
    0, 1, 1, 0, 1, 1, 1, 0, 0; ...
    0, 1, 1, 1, 1, 1, 1, 0, 0; ...
    0, 0, 1, 1, 1, 0, 0, 0, 0; ...
    0, 0, 1, 1, 1, 0, 0, 0, 0; ...
    0, 1, 1, 1, 0, 1, 0, 1, 0; ...
    0, 1, 1, 0, 0, 1, 0, 1, 0; ...
    0, 0, 1, 0, 0, 0, 0, 1, 0; ...
    0, 0, 0, 0, 1, 0, 1, 1, 0; ...
    0, 1, 0, 1, 1, 0, 1, 0, 0; ...
    0, 1, 1, 1, 1, 1, 0, 0, 0; ...
    0, 0, 1, 1, 0, 1, 0, 1, 0; ...
    0, 0, 1, 1, 0, 1, 0, 1, 0; ...
    0, 1, 1, 0, 1, 0, 1, 1, 0; ...
    0, 1, 0, 0, 1, 0, 1, 1, 0; ...
    0, 0, 0, 0, 0, 0, 0, 0, 0 ]';

  fprintf ( 1, '\n' );
  fprintf ( 1, 'COMPONENTS_TEST02\n' );
  fprintf ( 1, '  I4MAT_COMPONENTS finds and labels connected\n' );
  fprintf ( 1, '  components in a 2D integer array.\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  A:\n' );
  fprintf ( 1, '\n' );
  for i = 1 : m
    fprintf ( 1, '    ' );
    for j = 1 : n
      fprintf ( 1, '%d', a(i,j) );
    end
    fprintf ( 1, '\n' );
  end

  [ component_num, c ] = i4mat_components ( m, n, a );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of components = %d\n', component_num );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  C:\n' );
  fprintf ( 1, '\n' );
  for i = 1 : m
    fprintf ( 1, '    ' );
    for j = 1 : n
      fprintf ( 1, '%d', c(i,j) );
    end
    fprintf ( 1, '\n' );
  end

  return
end


function patches = img2patch_index(img, patchSize, stride)

m = size(img, 1); n = size(img, 2);
a = patchSize(1); b = patchSize(2); c = stride;

if stride > 1
	aCut = mod(m, a); bCut = mod(n, b);
	img = img(1:end-aCut, 1:end-bCut);
end

% Extended image from the original image
imgExt = [ img img(:, 1:b-c); img(1:a-c, :) img(1:a-c, 1:b-c) ];

if stride == 1
	patches = im2col(imgExt, patchSize, 'sliding');
return
end

iMat = zeros(size(img), class(img));
iMat( 1:c:end, 1:c:end ) = 1; % Take patches in distances of 'stride'
iPatch = find(iMat);
[i, j] = ind2sub(size(img), iPatch);
patches = zeros(prod(patchSize), length(iPatch));
for k = 1:length(iPatch)
	patch = imgExt(i(k):i(k)+a-1, j(k):j(k)+b-1);
	patches(:, k) = patch(:);
end

end % img2patch_index


%Copyright 2013 The MathWorks, Inc
function [sCol,sRx,sRD,sMFilt,sTVG,threshold] = setupRx(nint,nf,pfa,maxrange,range_gates,sWav,sAnt,fc)
%% Collector
sCol = phased.Collector('Sensor',sAnt,'Wavefront','Plane',...
                        'OperatingFrequency',fc);

%% Receiver Preamp
sRx = phased.ReceiverPreamp('Gain',20,'NoiseBandwidth',sWav.SweepBandwidth,...
                            'NoiseFigure',nf,'EnableInputPort',true,...
                            'SeedSource','Property','Seed',2007);

%% Range Doppler Estimator
sRD = phased.RangeDopplerResponse(...
    'DopplerWindow','Chebyshev','DopplerSidelobeAttenuation',60,...
    'SampleRate',sWav.SampleRate,'DopplerOutput','Speed','OperatingFrequency',fc);

%% Matched Filter
match_sig = getMatchedFilter(sWav);
sMFilt    = phased.MatchedFilter('Coefficients',match_sig);

%% Time Varying Gain
lambda   = physconst('LightSpeed')/fc;
rng_loss = 2*fspl(range_gates,lambda);   % Factor 2 for round trip
ref_loss = 2*fspl(maxrange,lambda);      % Reference loss for maximum range

sTVG = phased.TimeVaryingGain('RangeLoss',rng_loss,'ReferenceLoss',ref_loss);

%% Detection Threshold
npower    = noisepow(sWav.SweepBandwidth,nf,sRx.ReferenceTemperature);
sG        = phased.ArrayGain('SensorArray',sAnt);
gain      = step(sG,fc,0);
threshold = npower * norm(match_sig)^2 * db2pow(gain)...
                   * db2pow(npwgnthresh(pfa,nint,'noncoherent'));


function [Y,SetupStruc] = OnMVDR(S,Transfer,SetupStruc)
K = SetupStruc.K;
hop = SetupStruc.hop;
win = SetupStruc.win;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
N = size(S,2);
frame_N = size(S,3);
blockWin = repmat(win,[1 N frame_N]);
X = fft(S.*blockWin);
K_m = K/2+1;
Num = size(Transfer,3);
Y = zeros((frame_N-1)*hop+K,Num);
Y_f = zeros(K,frame_N,Num);
%%%%%%%%%%%%%%%%%%%%%%%%%% Initial the coefficients stored in 'SetupStruc'
if(~isfield(SetupStruc,'W'))
    SetupStruc.W = permute(Transfer,[2 3 1])/N;
    SetupStruc.V = zeros(N,Num,K_m);
    sign_Int = 1;
    SetupStruc.R = zeros(N,N,K_m);
    SetupStruc.WNG = [];
%     SetupStruc.miu = [];
%     SetupStruc.mag = [];
else
    sign_Int = 0;
end
WNG_set = -5;
WNG = zeros(1,K_m);
% miu_ = zeros(1,K_m);
% mag = zeros(1,K_m);
delta2 = 10^(WNG_set/10);
for i = 2:K_m
    X_f = permute(X(i,:,:),[2 3 1]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%% MVDR processing
    W_f = zeros(N,Num);
    Steer = permute(Transfer(i,:,:),[2 3 1]);
    if(sign_Int==1 || SetupStruc.alpha==1)
        R = X_f*X_f'/frame_N;
    else
        R = (1-SetupStruc.alpha)*SetupStruc.R(:,:,i)+SetupStruc.alpha*(X_f*X_f')/frame_N;
        SetupStruc.R(:,:,i) = R;
    end
    miu = 2/3/sum(real(diag(R)));
    for j = 1:Num
        h = Steer(:,j);
        mo2 = h'*h;
        Wc = h/mo2;
        Pc0 = eye(N)-Wc*h';
        V = SetupStruc.V(:,j,i);
        W = SetupStruc.W(:,j,i);
        V = Pc0*(V-miu*R*W);
        b2 = 1/delta2-1/mo2;
        if(V'*V<=b2)
            W = Wc+V;
        else
            W = Wc+sqrt(b2)*V/sqrt(V'*V);
        end
        W_f(:,j) = W;
        SetupStruc.V(:,j,i) = V;
    end
    SetupStruc.W(:,:,i) = W_f;
    WNG(i) = -10*log10(W_f(:,1)'*W_f(:,1));
%     mag(i) = abs(W_f(:,1)'*Steer(:,1));
%     miu_(i) = miu;
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    Y_ = W_f'*X_f;
    Y_f(i,:,:) = Y_.';
    if(i~=K_m)
        Y_f(K+2-i,:,:) = Y_';
    end
end
SetupStruc.WNG = [SetupStruc.WNG;WNG];
% SetupStruc.miu = [SetupStruc.miu;miu_];
% SetupStruc.mag = [SetupStruc.mag;mag];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Recover signals
if(K/hop==2)
    win = ones(K,1);
end
for i = 1:Num
    Y(:,i) = overlapadd(real(ifft(Y_f(:,:,i)))',win,hop);
end
return;


%rf_freqshift.m
%Jamie Near, McGill University 2014.
%
% USAGE:
% RF_shift=rf_freqshift(RF,Tp,F);
%
% DESCRIPTION:
% Apply a frequency shift to an RF pulse.
%
% INPUTS:
% RF         = RF pulse definition structure.
% Tp         = duration of the rf pulse in [ms].
% F          = amount that you would like to frequency shift the rf pulse in [Hz].
%
% OUTPUTS:
% RF_shift   = Output rf pulse following frequency shift.

function RF_shift=rf_freqshift(RF,Tp,F)

N=size(RF.waveform,1);
Tp=Tp/1000;
dt=Tp/N;
t=[0:dt:Tp-dt];

phaseRamp = t * F * 360;

RF_shift=RF;
RF_shift.waveform(:,1)=RF_shift.waveform(:,1)+phaseRamp';
RF_shift.f0=RF.f0+F;


function [newnode,newelem]=highordertet(node,elem,order)
%
% [newnode,newelem]=highordertet(node,elem)
%
% generate high-order straight-edge tetrahedral mesh from
% the 1st order tetrahedral mesh
%
% author: Qianqian Fang, <q.fang at neu.edu>
%
% input:
%    node: list of nodes
%    elem: list of elements (each row are indices of nodes of each element)
%    order: optional, the order of the generated mesh; if missing, order=2
%
% output:
%    newnode: all new edge-nodes on the output mesh
%    newelem: the indices of the edge nodes for each original tet element
%
%    currently, this function only supports order=2
%    to combine the newnode/newelem with the old mesh, one should use
%
%    elemfull=[elem(:,1:4) newelem+size(node,1)]; % 10-node element
%    nodefull=[node;newnode];
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

if(nargin<3)
    order=2;
end
if(order>=3 || order<=1)
    error('currently this function only supports order=2');
end
[edges,idx,newelem]=uniqedges(elem(:,1:4));
newnode=node(edges',1:3);
newnode=reshape(newnode',[3,2,size(edges,1)]);
newnode=squeeze(mean(permute(newnode,[3 2 1]),2));


function y = quadratic(x, sigma, type)
%QUADRATIC   Quadratic "robust" function.
%   QUADRATIC(X, SIGMA, TYPE) evaluates the Quadratic "robust" function
%   with sigma SIGMA at point(s) X.
%   TYPE selects the evaluation type:
%    - 0: function value
%    - 1: first derivative
%    - 2: second derivative
%
%   This is a private member function of the class 'robust_function'.
%
%   Author:  Stefan Roth, Department of Computer Science, TU Darmstadt
%   Contact: sroth@cs.tu-darmstadt.de
%   $Date:  $
%   $Revision: $

% Copyright 2004-2007, Brown University, Providence, RI. USA
% Copyright 2007-2010 TU Darmstadt, Darmstadt, Germany.
%
%                          All Rights Reserved
%
% All commercial use of this software, whether direct or indirect, is
% strictly prohibited including, without limitation, incorporation into in
% a commercial product, use in a commercial service, or production of other
% artifacts for commercial purposes.
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for research purposes is hereby granted without fee,
% provided that the above copyright notice appears in all copies and that
% both that copyright notice and this permission notice appear in
% supporting documentation, and that the name of the author and Brown
% University not be used in advertising or publicity pertaining to
% distribution of the software without specific, written prior permission.
%
% For commercial uses contact the Technology Venture Office of Brown University
%
% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO
% THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
% FITNESS FOR ANY PARTICULAR PURPOSE.  IN NO EVENT SHALL THE AUTHOR OR
% BROWN UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
% DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
% PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
% ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
% THIS SOFTWARE.

  switch (type)
   case 0
    y = x.^2 / sigma^2;
   case 1
    y = 2 * x / sigma^2;
   case 2
    y = repmat(2 / sigma^2, size(x));
  end


classdef CEC2013_F12 < PROBLEM
% <single> <real> <large>
% Shifted Rosenbrock's function

%------------------------------- Reference --------------------------------
% X. Li, K. Tang, M. N. Omidvar, Z. Yang, and K. Qin, Benchmark functions
% for the CEC'2013 special session and competition on large-scale global
% optimization, RMIT University, Australia, 2013.
%------------------------------- 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
        Xopt;	% Optimal decision vector
    end
    methods
        %% Default settings of the problem
        function Setting(obj)
            CallStack = dbstack('-completenames');
            load(fullfile(fileparts(CallStack(1).file),'CEC2013.mat'),'Data');
            obj.Xopt = Data{12};
            obj.M    = 1;
            obj.D    = 1000;
            obj.lower    = zeros(1,obj.D) - 100;
            obj.upper    = zeros(1,obj.D) + 100;
            obj.encoding = ones(1,obj.D);
        end
        %% Calculate objective values
        function PopObj = CalObj(obj,PopDec)
            PopObj = Rosenbrock(PopDec-repmat(obj.Xopt,size(PopDec,1),1));
        end
    end
end

function F = Rosenbrock(X)
    F = sum(100*(X(:,1:end-1).^2-X(:,2:end)).^2+(X(:,1:end-1)-1).^2,2);
end


%% Execute this file to collect validation data for model identification

x0 = x(end,:);
tspanV =[tspan(end):dt:20];

options = odeset('RelTol',1e-10,'AbsTol',1e-10*ones(1,n));

switch InputSignalType
    case 'sine2'
        A = 2;
        forcing = @(x,t) [(A*(sin(1*t)+sin(.1*t))).^2];
        [t_valid,x_valid]=ode45(@(t,x) LorenzSys(t,x,forcing(x,t),p),tspanV,x0,options);
        u_valid = forcing(0,tspanV);

    case 'chirp'
        A = 10;
        forcing = @(x,t) A*chirp(t,[],max(tspanV),1.).^2;
        [t_valid,x_valid]=ode45(@(t,x) LorenzSys(t,x,forcing(x,t),p),tspanV,x0,options);
        u_valid = forcing(0,tspanV);

    case 'noise'
        vareps = 0.01;
        Diff = @(t,x) [0; vareps];
        SDE = sde(@(t,x) LorenzSys(t,x,forcing(x,t),p),Diff,'StartState',x0');
        rng(1,'twister')
        [x_valid, t_valid, u_valid] = simByEuler(SDE, length(tspanV), 'DeltaTime', dt);
        u_valid = u_valid';
        x_valid = x_valid(1:end-1,:); t_valid = t_valid(1:end-1);
    case 'prbs'
        A = 1;
        taulim = [0.1 5];
        states = [-1 1];
        Nswitch = 300;
        forcing = @(x,t) A*prbs(taulim, Nswitch, states, t,0);

        [t_valid,x_valid]=ode45(@(t,x) LorenzSys(t,x,forcing(x,t),p),tspanV,x0,options);

        u_valid = zeros(size(tspanV));
        for i = 1:length(tspanV)
            u_valid(i) = forcing(0,tspanV(i));
        end
        figure,plot(tspanV,u_valid)

    case 'sphs'
        Pf = 1; % Fundamental period
        K = 8;
        A = 10;
        forcing = @(x,t) A*sphs(Pf,K,t);
        [t_valid,x_valid]=ode45(@(t,x) LorenzSys(t,x,forcing(x,t),p),tspanV,x0,options);
        u_valid = forcing(0,tspanV);

    case 'mixed'
        A = [4 5 4 3];
        Pf = 8; % Fundamental period
        K = 16;
        taulim = [0.1 3];
        states = [-1 1];
        Nswitch = 40;

        tspan1 = [0:dt:100];
        forcing = @(x,t) SI_Input(t,A,Pf,K,tspan1,taulim, Nswitch, states);
        [t_valid,x_valid] = ode45(@(t,x) LorenzSys(t,x,forcing(x,t),p),tspan1,x0,options);

        u_valid = zeros(size(tspan1));
        for i = 1:length(tspan1)
            u_valid(i) = forcing(0,tspan1(i));
        end
        figure,plot(tspan1,u_valid)

        A = 2;
        tspanv = [100:dt:200];
        forcingV = @(x,t) [(A*(sin(1*t)+sin(.1*t))).^2];
        [tv,xv]=ode45(@(t,x) LorenzSys(t,x,forcing(x,t),p),tspanv,x_valid(end,:),options);
        uv = forcingV(0,tspanv);

        u_valid = [u_valid, uv(2:end)];
        x_valid = [x_valid; xv(2:end,:)];
        t_valid = tspanV';
end

T = length(tspanV);
N = length(tspanV);

%% Show data
figure;
plot(t_valid,x_valid,'LineWidth',1.5)
xlabel('Time')
ylabel('xi')
legend('x','y','z')
set(gca,'LineWidth',1, 'FontSize',14)
set(gcf,'Position',[100 100 300 200])
set(gcf,'PaperPositionMode','auto')


function [firstCrossing, pointOfCrossing] = BF_PointOfCrossing(x,threshold)
% BF_PointOfCrossing  Linearly interpolate to the point of crossing a threshold
%
%---INPUT:
% x, a vector
% threshold, a threshold x crosses.
%
%---OUTPUTS:
% firstCrossing, the first discrete value after which a crossing event has occurred
% pointOfCrossing, the (linearly) interpolated point of crossing

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

% Find index of x at which the first crossing event occurs:
if x(1) > threshold
    firstCrossing = find((x - threshold < 0),1,'first');
else
    firstCrossing = find((x - threshold > 0),1,'first');
end

if isempty(firstCrossing)
    % Never crosses
    N = length(x);
    firstCrossing = N;
    pointOfCrossing = N;
else
    % Continuous version---the point of crossing
    valueBeforeCrossing = x(firstCrossing - 1);
    valueAfterCrossing = x(firstCrossing);
    pointOfCrossing = firstCrossing - 1 + (threshold - valueBeforeCrossing)/(valueAfterCrossing - valueBeforeCrossing);
end

end


function [W, info] = MTFLCd_ADMM_WSolver...
    (Xdiag, yvect, Thvect, Zvect, rho, lambda1, lambda2, opts)
%
% Multi-Task Feature Learning with Calibration - ADMM
% Subproblem: W
% diagnoalized version.
%
% Objective
%   min_W {   rho/2 sum_i^m ||theta_i/rho - z_i + y+i - X_iwi||
%           + lambda2/2 ||W||_F^2 + lambda1 ||W||_{1,2}
%          }
%
% INPUT
%  X - cell array of {n_i by d matrices} by m
%  y - cell array of {n_i by 1 vectors}  by m
%  Th - cell array of {n_i by 1 vectors} by m
%  Z  - cell array of {n_i by 1 vectors} by m
%  rho - parameter of the augmented Lagrange
%  lambda1 - regularization parameter of the l2,1 norm penalty
%  lambda2 - regularization parameter of the Fro norm penalty
%  opts - MANDATORY optimization options.
%
% OUTPUT
%  W - task weight d by m.
%
% Author: Jiayu

%% Initialization

W0 = opts.init; % the outer loop must pass in the last solution

funcVal = zeros(opts.maxIter,1);

TrZy = Thvect/rho - Zvect + yvect;

%% Computation

bFlag = 0;

W     = W0;
W_old = W0;

gamma = 1; gamma_inc = 2;

t =1; t_old = 1;
for iter = 1: opts.maxIter
    alpha = (t_old  -1 )/t;
    V = W + alpha * (W - W_old);

    [fV, gV] = smoothObj(V);

    for lsIter = 1:100
        W = proj(V - gV/gamma, lambda1/gamma);
        f = smoothObj(W);

        delta_W = W - V;
        r_sum = sum(sum(delta_W.^2));

        if(r_sum <= 1e-20), bFlag = 1; break; end

        if f<= fV + sum(sum(delta_W .* gV)) + gamma/2 * r_sum
            break;
        end

        gamma = gamma * gamma_inc;
    end

    W_old = W;

    funcVal(iter) = f + lambda1 * sum(sqrt(sum(W.^2, 2)));

    if(bFlag), break; end

    % convergence
    if(iter>1)
        if (abs( funcVal(iter) - funcVal(iter-1) ) ...
                <= opts.tol* abs(funcVal(iter-1)))
            break;
        end
    end

    t_old = t;
    t = 0.5 * (1 + (1+ 4 * t^2)^0.5);
end

info.funcVal = funcVal(1:iter);

%% Nested functions
    function [X] = proj(D, t) % l2.1 norm projection.
        X = repmat(max(0, 1 - t./sqrt(sum(D.^2,2))),1,size(D,2)).*D;
    end

    function [f, g] = smoothObj(W)
        f = 0.5 * lambda2 *sum(sum(W.^2));
        tpVect = TrZy - Xdiag * W(:);
        f = f +  0.5 * rho * sum(tpVect.^2);
        if nargout >= 2
            g = reshape(lambda2 * W(:) - rho * (Xdiag' * tpVect), size(W));
        end
    end

end


function [um] = km2um(km)
% Convert length from kilometers to microns (aka micrometers).
% Chad A. Greene 2012
um = km*1000000000;


function T = auxstructure3(elem)
%% AUXSTRUCTURE3 auxiliary structure for a 3-D triangulation.
%
%  T = AUXSTRUCTURE3(elem) constucts the indices map between elements,
%  faces, edges and nodes, and the boundary edge information. T is a struct
%  data.
%
%  T.neighor(1:NT,1:4): the indices map of neighbor information of elements,
%  where neighbor(t,i) is the global index of the element oppoiste to the
%  i-th vertex of the t-th element.
%
%  T.elem2face(1:NT,1:4): the indices map from elements to faces, where
%  elem2face(t,i) is the global index of the  edge opposite to the i-th
%  vertex of t-th elemment.
%
%  T.face(1:NF,1:3): faces, where face(k,i) is the global index of the i-th
%  vetex of the k-th face, and face(k,1)<face(k,2)<face(k,3).
%
%  T.bdFace(1:Nbd,1:3): boundary faces with positive oritentation, where
%  bdFace(k,i) is the global index of the i-th vetex of the k-th boundary
%  face. The positive oritentation means that the order of the three
%  vertices of bdFace(k,:) satisfy the right-handed system and normal
%  points the outside of the domain. Note that this requires elem is
%  positive ordered, i.e., the signed volume of each tetrahedron is
%  positive. If not, use elem = fixorder3(node,elem) to fix the order.
%
%  T.face2elem(1:NF,1:4): the indices map from faces to elements, where
%  face2elem(k,1:2) are two global indices of the elements sharing the k-th
%  face, and face2elem(k,3:4) are local indices of e to edge2elem(k,1:2).
%
%  To save space all the data type in T is uint32. When use them as a input
%  of sparse(i,j,s,m,n), please change them into double type.
%
%  See also auxstructure.
%
% Copyright (C) Long Chen. See COPYRIGHT.txt for details.

NT = size(elem,1);
totalFace = uint32([elem(:,[2 3 4]); elem(:,[1 4 3]); ...
                    elem(:,[1 2 4]); elem(:,[1 3 2])]);
matlabversion = version;
if str2double(matlabversion(end-5:end-2)) > 2012
    [face, i2, j] = unique(sort(totalFace,2),'rows','lagacy');
else
    [face, i2, j] = unique(sort(totalFace,2),'rows');
end
i1(j(4*NT:-1:1)) = 4*NT:-1:1; i1 = i1';
k1 = ceil(i1/NT); t1 = i1 - NT*(k1-1);
k2 = ceil(i2/NT); t2 = i2 - NT*(k2-1);
idx = (i1 ~= i2);
neighbor = uint32(accumarray([[t1(idx),k1(idx)];[t2,k2]],[t2(idx);t1],[NT 4]));
elem2face = uint32(reshape(j,NT,4));
face2elem = uint32([t1,t2,k1,k2]);
bdElem = t1(t1 == t2);
bdk1 = k1(t1 == t2);
% consistent ordering of faces is used.
bdFace = [elem(bdElem(bdk1==1),[2 3 4]); elem(bdElem(bdk1==2),[1 4 3]);...
          elem(bdElem(bdk1==3),[1 2 4]); elem(bdElem(bdk1==4),[1 3 2])];
T = struct('neighbor',neighbor,'elem2face',elem2face,'face',uint32(face),...
           'face2elem',face2elem,'bdElem',bdElem,'bdFace',uint32(bdFace));


% eeg_interp_scalp3d_test - Script to test 3D interpolation of scalp potentials

clear

p = eeg_toolbox_defaults;
p = eeg_open(p);
p = elec_open(p);
p = mesh_open(p);

p = mesh_plot(p);

close all

scalpvert = p.mesh.data.vertices{3};

Mean = mean(scalpvert);
STD  = std(scalpvert);

Min = Mean - 3*STD;
Max = Mean + 3*STD;

delta = 0.05;
Xd = Min(1):delta:Max(1);
Yd = Min(2):delta:Max(2);
Zd = Min(3):delta:Max(3);

[x0,y0,z0] = meshgrid(Xd,Yd,Zd);

X0 = [x0(:), y0(:), z0(:)];

X = p.mesh.data.vertices{4};
v = p.volt.data(1,:)';

v0 = griddatan(X,v,X0);
v0 = reshape(v0, size(x0));

V = v0(:);
Vfinite = find(isfinite(V));
X0finite = X0(Vfinite,:);

trisurf(convhulln(X0finite),X0finite(:,1),X0finite(:,2),X0finite(:,3),Vfinite,'EdgeColor','none','FaceColor','interp');

fprintf('\ndone\n');
return

%X0scalpindices = dsearchn(X0,scalpvert);
X0scalpindices = dsearchn(X0finite,scalpvert);

newscalpvert(:,1) = x0(X0scalpindices);
newscalpvert(:,2) = y0(X0scalpindices);
newscalpvert(:,3) = z0(X0scalpindices);
newvoltage = v0(X0scalpindices);

trisurf(convhulln(newscalpvert),newscalpvert(:,1),newscalpvert(:,2),newscalpvert(:,3),newvoltage,'EdgeColor','none','FaceColor','interp');

return

Vplot = mean(v);

Hp = patch(isosurface(x0,y0,z0,v0,Vplot));
isonormals(x0,y0,z0,v0,Hp);
set(Hp,'FaceColor','red','EdgeColor','none');
view(3);
camlight;
lighting phong
%axis equal
title('Interpolated isosurface from scattered data')


% ObserveEvidence Modify a vector of factors given some evidence.
%   F = ObserveEvidence(F, E) sets all entries in the vector of factors, F,
%   that are not consistent with the evidence, E, to zero. F is a vector of
%   factors, each a data structure with the following fields:
%     .var    Vector of variables in the factor, e.g. [1 2 3]
%     .card   Vector of cardinalities corresponding to .var, e.g. [2 2 2]
%     .val    Value table of size prod(.card)
%   E is an N-by-2 matrix, where each row consists of a variable/value pair.
%     Variables are in the first column and values are in the second column.

function F = ObserveEvidence(F, E)

% Iterate through all evidence

for i = 1:size(E, 1),
    v = E(i, 1); % variable
    x = E(i, 2); % value

    % Check validity of evidence
    if (x == 0),
        warning(['Evidence not set for variable ', int2str(v)]);
        continue;
    end;

    for j = 1:length(F),
		  % Does factor contain variable?
        indx = find(F(j).var == v);

        if (~isempty(indx)),

		  	   % Check validity of evidence
            if (x > F(j).card(indx) || x < 0 ),
                error(['Invalid evidence, X_', int2str(v), ' = ', int2str(x)]);
            end;

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            % YOUR CODE HERE
            % Adjust the factor F(j) to account for observed evidence
            % Hint: You might find it helpful to use IndexToAssignment
            %       and SetValueOfAssignment
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
           for i = 1:length(F(j).val)
		  assign = IndexToAssignment(i,F(j).card);
		  if assign(indx)!=x
			  F(j) = SetValueOfAssignment(F(j),assign,0);
		  end
	  end
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

				% Check validity of evidence / resulting factor
            if (all(F(j).val == 0)),
                warning(['Factor ', int2str(j), ' makes variable assignment impossible']);
            end;

        end;
    end;
end;

end


function cvt_test11 ( )

%*****************************************************************************80
%
%% CVT_TEST11 tests CVT.
%
%  Discussion:
%
%    In this test, we initialize the generators to grid points; this is
%    an unstable CVT solution.  The data would "prefer" to be in a
%    different form.  However, even if we take 2000 steps of CVT iteration,
%    the data is still only slowly progressing towards that other
%    configuration.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 November 2006
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST11\n' );
  fprintf ( 1, '  CVT computes a Centroidal Voronoi Tessellation.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  In this test, we initialize the generators to\n' );
  fprintf ( 1, '  grid points; this is an unstable CVT solution.\n' );

  dim_num = 2;
  n = 16;
  batch = 1000;
  init = 4;
  init_string = 'user initialization';
  it_max = 40;
  it_fixed = 1;
  sample = 0;
  sample_num = 1000;
  sample_string = 'uniform';
  seed = 123456789;

  seed_init = seed;
%
%  Initialize the tuple generator.
%
  rank = -1;
  ngrid = 4;
  tuple(1:dim_num) = tuple_next_fast ( ngrid, dim_num, rank );
%
%  Pick points on a grid.
%
  for rank = 0 : n-1
    tuple(1:dim_num) = tuple_next_fast ( ngrid, dim_num, rank );
    r(1:dim_num,rank+1) = ( 2 * tuple(1:dim_num)' - 1 ) / ( 2 * ngrid );
  end

  r8mat_transpose_print ( dim_num, n, r, '  Initial generators (rows):' );

  [ r, seed, it_num, it_diff, energy ] = cvt ( dim_num, n, batch, init, ...
    sample, sample_num, it_max, it_fixed, seed, r );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Dimension DIM_NUM =        %12d\n', dim_num );
  fprintf ( 1, '  Number of points N =       %12d\n', n );
  fprintf ( 1, '  Initial SEED =             %12d\n', seed_init );
  fprintf ( 1, '  Current SEED =             %12d\n', seed );
  fprintf ( 1, '  INIT =                    "%s".\n', init_string );
  fprintf ( 1, '  Max iterations IT_MAX =    %12d\n', it_max );
  fprintf ( 1, '  IT_FIXED (fixed samples) = %12d\n', it_fixed );
  fprintf ( 1, '  Iterations IT_NUM =        %12d\n', it_num );
  fprintf ( 1, '  Difference IT_DIFF =       %14f\n', it_diff );
  fprintf ( 1, '  CVT ENERGY =               %14f\n', energy );
  fprintf ( 1, '  SAMPLE =                  "%s".\n', sample_string );
  fprintf ( 1, '  Samples SAMPLE_NUM    =    %12d\n', sample_num );
  fprintf ( 1, '  Sampling BATCH size =      %12d\n', batch );
  fprintf ( 1, '  EPSILON (unit roundoff) =  %12e\n', eps );

  r8mat_transpose_print ( dim_num, n, r, '  Generators (rows):' );

  return
end


function pde = SinFlat(am,ap,bm,bp,x0,y0,z0,n)
%% USAGE: polynomial solution for Poisson equation
%  Last Modified: 02/21/2020 by Xu Zhang

%% PDE Structure
pde = struct('intf',@intf,...
    'exactu1',@exactu1,'exactu2',@exactu2,'exactu3',@exactu3,...
    'um1',@um1,'um2',@um2,'um3',@um3,'up1',@up1,'up2',@up2,'up3',@up3,...
    'Dxu',@Dxu,'Dxum',@Dxum,'Dxup',@Dxup,'Dyu',@Dyu,...
    'Dyum',@Dyum,'Dyup',@Dyup,'Dzu',@Dzu,'Dzum',@Dzum,'Dzup',@Dzup,...
    'f1',@f1,'f2',@f2,'f3',@f3,...
    'fm1',@fm1,'fm2',@fm2,'fm3',@fm3,...
    'fp1',@fp1,'fp2',@fp2,'fp3',@fp3,...
    'A',@A,'Am',@Am,'Ap',@Ap,'one',@one,...
    'B',@B,'Bm',@Bm,'Bp',@Bp);

pde.bm = bm;
pde.bp = bp;
pde.am = am;
pde.ap = ap;
%% interface function
    function u = intf(x,y,z)
        u = n(1)*(x-x0)+n(2)*(y-y0)+n(3)*(z-z0);
    end

%% exact solution
    function u = exactu1(x,y,z)
        u = um1(x,y,z);
        id = intf(x,y,z) > 0;
        u(id) = up1(x(id),y(id),z(id));
    end
    function u = exactu2(x,y,z)
        u = um2(x,y,z);
        id = intf(x,y,z) > 0;
        u(id) = up2(x(id),y(id),z(id));
    end
    function u = exactu3(x,y,z)
        u = um3(x,y,z);
        id = intf(x,y,z) > 0;
        u(id) = up3(x(id),y(id),z(id));
    end
    function u = um1(x,y,z)
        u = sin(pi*ker(x,y,z))/am;
    end
    function u = um2(x,y,z)
        u = sin(pi*ker(x,y,z))/am;
    end
    function u = um3(x,y,z)
        u = sin(pi*ker(x,y,z))/am;
    end
    function u = up1(x,y,z)
        u = sin(pi*ker(x,y,z))/ap;
    end
    function u = up2(x,y,z)
        u = sin(pi*ker(x,y,z))/ap;
    end
    function u = up3(x,y,z)
        u = sin(pi*ker(x,y,z))/ap;
    end
    function u = ker(x,y,z)
        u = n(1)*(x-x0)+n(2)*(y-y0)+n(3)*(z-z0);
    end

%% Boundary Function
    function u = gD1(x,y,z)
        u = exactu1(x,y,z);
    end
    function u = gD2(x,y,z)
        u = exactu2(x,y,z);
    end
    function u = gD3(x,y,z)
        u = exactu3(x,y,z);
    end
%% Derivative of the exact solution
    function u = Dxu(x,y,z)
        u = Dxum(x,y,z);
        id = intf(x,y,z) > 0;
        u(id) = Dxup(x(id),y(id),z(id));
    end
    function u = Dyu(x,y,z)
        u = Dyum(x,y,z);
        id = intf(x,y,z) > 0;
        u(id) = Dyup(x(id),y(id),z(id));
    end
    function u = Dzu(x,y,z)
        u = Dzum(x,y,z);
        id = intf(x,y,z) > 0;
        u(id) = Dzup(x(id),y(id),z(id));
    end
    function u = Dxum(x,y,z)
        u = cos(pi*ker(x,y,z))*pi*(n(2)-n(3))/am;
    end
    function u = Dyum(x,y,z)
        u = cos(pi*ker(x,y,z))*pi*(n(3)-n(1))/am;
    end
    function u = Dzum(x,y,z)
        u = cos(pi*ker(x,y,z))*pi*(n(1)-n(2))/am;
    end
    function u = Dxup(x,y,z)
        u = cos(pi*ker(x,y,z))*pi*(n(2)-n(3))/ap;
    end
    function u = Dyup(x,y,z)
        u = cos(pi*ker(x,y,z))*pi*(n(3)-n(1))/ap;
    end
    function u = Dzup(x,y,z)
        u = cos(pi*ker(x,y,z))*pi*(n(1)-n(2))/ap;
    end

%% right hand side function
    function u = f1(x,y,z)
        u = fm1(x,y,z);
        id = intf(x,y,z) > 0;
        u(id) = fp1(x(id),y(id),z(id));
    end
    function u = f2(x,y,z)
        u = fm2(x,y,z);
        id = intf(x,y,z) > 0;
        u(id) = fp2(x(id),y(id),z(id));
    end
    function u = f3(x,y,z)
        u = fm3(x,y,z);
        id = intf(x,y,z) > 0;
        u(id) = fp3(x(id),y(id),z(id));
    end

    function u = fm1(x,y,z)
        u = -sin(pi*ker(x,y,z))*pi^2*(n(1)*(n(2)+n(3))-n(2)^2-n(3)^2)+um1(x,y,z)*bm;
    end
    function u = fm2(x,y,z)
        u = -sin(pi*ker(x,y,z))*pi^2*(n(2)*(n(1)+n(3))-n(1)^2-n(3)^2)+um2(x,y,z)*bm;
    end
    function u = fm3(x,y,z)
        u = -sin(pi*ker(x,y,z))*pi^2*(n(3)*(n(1)+n(2))-n(1)^2-n(2)^2)+um3(x,y,z)*bm;
    end
    function u = fp1(x,y,z)
        u = -sin(pi*ker(x,y,z))*pi^2*(n(1)*(n(2)+n(3))-n(2)^2-n(3)^2)+up1(x,y,z)*bp;
    end
    function u = fp2(x,y,z)
        u = -sin(pi*ker(x,y,z))*pi^2*(n(2)*(n(1)+n(3))-n(1)^2-n(3)^2)+up2(x,y,z)*bp;
    end
    function u = fp3(x,y,z)
        u = -sin(pi*ker(x,y,z))*pi^2*(n(3)*(n(1)+n(2))-n(1)^2-n(2)^2)+up2(x,y,z)*bp;
    end

%% Diffusion coefficient function
    function u = A(x,y,z)
        u = Am(x,y,z);
        id = intf(x,y,z) > 0;
        u(id) = Ap(x(id),y(id),z(id));
    end
    function u = Am(x,y,z)
        u = am*ones(size(x));
    end
    function u = Ap(x,y,z)
        u = ap*ones(size(x));
    end
%% Mass coefficient function
    function u = B(x,y,z)
        u = Bm(x,y,z);
        id = intf(x,y,z) > 0;
        u(id) = Bp(x(id),y(id),z(id));
    end
    function u = Bm(x,y,z)
        u = bm*ones(size(x));
    end
    function u = Bp(x,y,z)
        u = bp*ones(size(x));
    end

%% Other function
    function u = one(x,y,z)
        u = ones(size(x));
    end
end


%DEMSOM1 Demonstrate SOM for visualisation.
%
%	Description
%	 This script demonstrates the use of a SOM with  a two-dimensional
%	grid to map onto data in  two-dimensional space.  Both on-line and
%	batch training algorithms are shown.
%
%	See also
%	SOM, SOMPAK, SOMTRAIN
%

%	Copyright (c) Ian T Nabney (1996-2001)

randn('state', 42);
rand('state', 42);
nin = 2;
ndata = 300;
% Give data an offset so that network has something to learn.
x = rand(ndata, nin) + ones(ndata, 1)*[1.5 1.5];

clc;
disp('This demonstration of the SOM, or Kohonen network, shows how the')
disp('network units after training lie in regions of high data density.')
disp('First we show the data, which is generated uniformly from a square.')
disp('Red crosses denote the data and black dots are the initial locations')
disp('of the SOM units.')
disp(' ')
disp('Press any key to continue.')
pause
net = som(nin, [8, 7]);
c1 = sompak(net);
h1 = figure;
plot(x(:, 1), x(:, 2), 'r+');
hold on
plot(c1(:,1), c1(:, 2), 'k.');
drawnow;  % Force figure to be drawn before training starts
options = foptions;

% Ordering phase
options(1) = 1;
options(14) = 50;
%options(14) = 5; % Just for testing
options(18) = 0.9;  % Initial learning rate
options(16) = 0.05; % Final learning rate
options(17) = 8;    % Initial neighbourhood size
options(15) = 1;    % Final neighbourhood size

disp('The SOM network is trained in two phases using an on-line algorithm.')
disp('Initially the neighbourhood is set to 8 and is then reduced')
disp('linearly to 1 over the first 50 iterations.')
disp('Each iteration consists of a pass through the complete')
disp('dataset, while the weights are adjusted after each pattern.')
disp('The learning rate is reduced linearly from 0.9 to 0.05.')
disp('This ordering phase puts the units in a rough grid shape.')
disp('Blue circles denote the units at the end of this phase.')
disp(' ')
disp('Press any key to continue.')
pause
net2 = somtrain(net, options, x);
c2 = sompak(net2);
plot(c2(:, 1), c2(:, 2), 'bo');
drawnow;

% Convergence phase
options(1) = 1;
options(14) = 400;
options(18) = 0.05;
options(16) = 0.01;
options(17) = 0;
options(15) = 0;

disp('The second, convergence, phase of learning just updates the winning node.')
disp('The learning rate is reduced from 0.05 to 0.01 over 400 iterations.')
disp('Note how the error value does not decrease monotonically; it is')
disp('difficult to decide when training is complete in a principled way.')
disp('The units are plotted as green stars.')
disp(' ')
disp('Press any key to continue.')
pause
net3 = somtrain(net2, options, x);
c3 = sompak(net3);
plot(c3(:, 1), c3(:, 2), 'g*');
drawnow;

% Now try batch training
options(1) = 1;
options(6) = 1;
options(14) = 50;
options(17) = 3;
options(15) = 0;
disp('An alternative approach to the on-line algorithm is a batch update')
disp('rule.  Each unit is updated to be the average weights')
disp('in a neighbourhood (which reduces from 3 to 0) over 50 iterations.');
disp('Note how the error is even more unstable at first, though eventually')
disp('it does converge.')
disp('The final units are shown as black triangles.')
disp(' ')
disp('Press any key to continue.')
pause
net4 = somtrain(net, options, x);
c4 = sompak(net4);
plot(c4(:, 1), c4(:, 2), 'k^')
legend('Data', 'Initial weights', 'Weights after ordering', ...
    'Weights after convergence', 'Batch weights', 2);
drawnow;

disp(' ')
disp('Press any key to end.')
disp(' ')
pause

close(h1);


function l = l1dn_inverse ( n, h )

%*****************************************************************************80
%
%% L1DN_INVERSE stores the inverse of the 1D DN Laplacian.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 October 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of points.
%    N must be at least 3.
%
%    Input, real H, the spacing between points.
%
%    Output, real L(N,N), the inverse of the Laplacian matrix.
%
  if ( n < 3 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'L1DN_INVERSE - Fatal error!\n' );
    fprintf ( 1, '  N < 3.\n' );
    error ( 'L1DN_INVERSE - Fatal error!' );
  end

  l = zeros ( n, n );

  for j = 1 : n
    for i = 1 : n
      l(i,j) = min ( i, j ) * h * h;
    end
  end

  return
end


function hermite_polynomial_test14 ( )

%*****************************************************************************80
%
%% HERMITE_POLYNOMIAL_TEST14 tests H_POLYNOMIAL_COEFFICIENTS.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 March 2012
%
%  Author:
%
%    John Burkardt
%
  n = 5;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'HERMITE_POLYNOMIAL_TEST14\n' );
  fprintf ( 1, '  H_POLYNOMIAL_COEFFICIENTS determines the physicist''s Hermite \n' );
  fprintf ( 1, '  polynomial coefficients.\n' );

  c = h_polynomial_coefficients ( n );

  for i = 0 : n
    fprintf ( 1, '\n' );
    fprintf ( 1, '  H(%d) = \n', i );
    fprintf ( 1, '\n' );
    for j = i : -1 : 0
      if ( c(i+1,j+1) == 0.0 )

      elseif ( j == 0 )
        fprintf ( 1, '  %f\n', c(i+1,j+1) );
      elseif ( j == 1 )
        fprintf ( 1, '  %f * x\n', c(i+1,j+1) );
      else
        fprintf ( 1, '  %f * x^%d\n', c(i+1,j+1), j );
      end
    end
  end

  return
end


function linpack_z_test37 ( )

%*****************************************************************************80
%
%% TEST37 tests ZTRSL.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 June 2009
%
%  Author:
%
%    John Burkardt
%
  n = 10;
  lda = n;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST37\n' );
  fprintf ( 1, '  For a double precision complex (C)\n' );
  fprintf ( 1, '  triangular matrix (TR),\n' );
  fprintf ( 1, '  ZTRSL solves a linear system.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  The matrix order is N = %d\n', n );
%
%  Set the matrix.
%
  seed = 123456789;

  for i = 1 : n
    for j = 1 : i
      [ a(i,j), seed ] = c8_uniform_01 ( seed );
    end
    a(i,i+1:n) = 0.0;
  end
%
%  Set the desired solution
%
  for i = 1 : n
    x(i) = complex ( i, 10 * i );
  end
%
%  Compute the corresponding right hand side.
%
  b(1:n) = a(1:n,1:n) * transpose ( x(1:n) );
%
%  Solve the lower triangular system.
%
  job = 0;
  [ b, info ] = ztrsl ( a, lda, n, b, job );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Computed                     Exact\n' );
  fprintf ( 1, '  Solution                     Solution\n' );
  fprintf ( 1, '\n' );
  for i = 1 : n
    fprintf ( 1, '  (%8f  %8f)  (%8f  %8f)\n', ...
      real ( b(i) ), imag ( b(i) ), real ( x(i) ), imag ( x(i) ) );
  end

  return
end


function i = dyad(j)
% dyad -- Index entire j-th dyad of 1-d wavelet xform
%  Usage
%    ix = dyad(j);
%  Inputs
%    j     integer
%  Outputs
%    ix    list of all indices of wavelet coeffts at j-th level
%
    i = (2^(j)+1):(2^(j+1)) ;

%
% Copyright (c) 1993. David L. Donoho
%

%
%  Part of Wavelab Version 850
%  Built Tue Jan  3 13:20:40 EST 2006
%  This is Copyrighted Material
%  For Copying permissions see COPYING.m
%  Comments? e-mail wavelab@stat.stanford.edu


function h_ax = plotSphFunctionGrid(F, aziRes, polarRes, realComplex, h_ax)
%PLOTSPHFUNCTIONGRID Plots a spherical function defined on a grid
%
%   F:  matrix of function values on the grid points
%   aziRes: grid resolution at azimuth (degrees)
%   polarRes: grid resolution in elevation (degrees)
%   realComplex: {'real','complex'} if the function is real then it is
%                plotted with one surface for its positive part and one for
%                its negative part. If it is complex, the magnitude
%                function is plotted, with its phase mapped on the colormap
%   h_ax: optional argument to define an axis handle for the plot,
%         otherwise the new axis handle is returned
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   Archontis Politis, 20/02/2015
%   archontis.politis@aalto.fi
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin==4
    figure
    h_ax = axes;
elseif nargin==3
    figure
    h_ax = axes;
    realComplex = 'complex';
else
    axes(h_ax);
end

% construct grid
azi = 0:aziRes:360;
elev = 0:polarRes:180;
azi_rad = azi*pi/180;
elev_rad = elev*pi/180;
[Az, El] = meshgrid(azi_rad, elev_rad);

% construct real positive and negative parts if real function
D_x = cos(Az).*sin(El).*squeeze(abs(F));
D_y = sin(Az).*sin(El).*squeeze(abs(F));
D_z = cos(El).*squeeze(abs(F));

if isequal(realComplex, 'real')
    Dp_x = D_x.*(F>=0);
    Dp_y = D_y.*(F>=0);
    Dp_z = D_z.*(F>=0);
    Dn_x = D_x.*(F<0);
    Dn_y = D_y.*(F<0);
    Dn_z = D_z.*(F<0);
elseif isequal(realComplex, 'complex')
    Dm_x = D_x.* abs(F);
    Dm_y = D_y.* abs(F);
    Dm_z = D_z.* abs(F);
end

% plot 3d axes
maxF = max(max(abs(F)));
line([0 1.5*maxF],[0 0],[0 0],'color',[1 0 0])
line([0 0],[0 1.5*maxF],[0 0],'color',[0 1 0])
line([0 0],[0 0],[0 1.5*maxF],'color',[0 0 1])

% plot function
hold on
if isequal(realComplex, 'real')
    Hp = surf(Dp_x, Dp_y, Dp_z);
    Hn = surf(Dn_x, Dn_y, Dn_z);
    set(Hp, 'FaceColor', 'b')
    set(Hp, 'EdgeAlpha', 1)
    set(Hn, 'FaceColor', 'r')
    set(Hn, 'EdgeAlpha', 1)
elseif isequal(realComplex, 'complex')
    Hm = surf(Dm_x, Dm_y, Dm_z, angle(F));
    set(Hm, 'EdgeAlpha', 1)
end
xlabel('x')
ylabel('y')
zlabel('z')
light('Position',[0 0 1],'Style','infinite');
light('Position',[-1 -1 -1],'Style','infinite');
light('Position',[0 0 -1],'Style','infinite');
material shiny
axis equal
grid

end


function [fMshift, fProbability, fBic, mProblikelihood, fAICc] = calc_loglikelihood_dM(mCat1, mCat2)
% function [fMshift, fProbability, fBic, mProblikelihood] = calc_loglikelihood_dM(mCat1, mCat2);
% ----------------------------------------------------------------------------------------------
% Calculate log-likelihood estimation of magnitude shift dM between to periods
%
% Incoming variable
% mCat1 : EQ catalog period 1 (Catalog to be modified)
% mCat2 : EQ catalog period 2 (Observed catalog)
%
% Outgoing variable
% fProbability : log-likelihood probabilty
% fMshift      : Magnitude shift with the lowest  max. lieklihood score
% fBic         : Bayesian Information Criterion value
% mProblikelihood : Solution matrix shift and likelihood score
%
% Author: J. Woessner, woessner@seismo.ifg,.ethz.ch
% last update: 28.10.02

% Initialize
mProblikelihood = [];
vfProbability = [];
vMshift = [];

% Determine exact time period
fPeriod1 = max(mCat1(:,3)) - min(mCat1(:,3));
fPeriod2 = max(mCat2(:,3)) - min(mCat2(:,3));

mCat1Mod = mCat1;

for fMshift = -0.5:0.1:0.5
    % Apply shift
    mCat1Mod(:,6) = mCat1Mod(:,6)+fMshift;
    % Initialize values
    fMinMag = min([min(mCat1Mod(:,6)) min(mCat2(:,6))]);
    fMaxMag = max([max(mCat1Mod(:,6)) max(mCat2(:,6))]);

    [vPredFMD,vBin1] = hist(mCat1Mod(:,6),0:0.1:fMaxMag);
    [vObsFMD,vBin2] = hist(mCat2(:,6),0:0.1:fMaxMag);
    % Time normalization and round due to Poisson distribution calculation in calc_log10poisspdf
    vPredFMD = ceil(vPredFMD./fPeriod1);
    vObsFMD = ceil(vObsFMD./fPeriod2);
    % Calculate the likelihoods for both models
    vProb_ = calc_log10poisspdf(vObsFMD',vPredFMD');
    % Sum the probabilities
    fProbability = (-1) * sum(vProb_);
    vfProbability = [vfProbability; fProbability];
    vMshift = [vMshift; fMshift];
    mCat1Mod = mCat1;
end

%%% Find the minimum loglikelihodd score: if the minimum score is obtained several times, calculate MEAN
%%% of the magnitude shift
vdMloglikeli = [vfProbability vMshift];
vSel = (vdMloglikeli == min(vdMloglikeli(:,1)));
vdMloglikeli = vdMloglikeli(vSel,:);
if length(vdMloglikeli(:,1)) > 1
    fProbability = min(vdMloglikeli(:,1));
    fMshift = mean(vdMloglikeli(:,2));
else
    fProbability = vdMloglikeli(:,1);
    fMshift = vdMloglikeli(:,2);
end
% Solution matrix
mProblikelihood = [vMshift vfProbability];

nDegFree = 1; % Magnitude shift is the degree of freedom
n_samples = length(mCat1(:,6))+length(mCat2(:,6));
%% Bayesian Information Criterion (BIC)
fBic = 2*fProbability + 2*log(n_samples)*nDegFree;
%% Corrected Akaike Information Criterion (AICc)
fAICc = -2*(-fProbability)+2*nDegFree+2*nDegFree*(nDegFree+1)/(n_samples-nDegFree-1);


function [ha] = m22ha(m2)
% Convert area from square meters to hectares.
% Chad A. Greene 2012
ha = m2*0.0001 ;


function res = spm_eeg_specest_mtmspec(S, data, time)
% Plugin for spm_eeg_tf using SPM implementation of multitaper method
% FORMAT res = spm_eeg_specest_mtmspec(S, data, time)
%
% S                     - input structure
% fields of S:
%    S.bandwidth   - time bandwidth parameter determining the degree of
%                    spectral smoothing (typically 3 or 4).
%    S.frequencies - vector of frequencies
%    S.timeres     - time resolution in ms (length of the sliding time-window)
%    S.timestep    - time step (in ms) to slide the time-window by.
%
% Output:
%  res -
%   If no input is provided the plugin returns a cfg branch for itself
%
%   If input is provided:
%      res.fourier - the complex output of wavelet transform (in the case
%                    of single taper)
%      res.pow     - power (in case of multiple tapers, phase is not computed)
%      res.time    - time axis
%      res.freq    - frequency axis
%______________________________________________________________________________________
% Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak based on the code contributed by Krish Singh
% $Id: spm_eeg_specest_mtmspec.m 4021 2010-07-28 12:43:16Z vladimir $

%-This part if for creating a config branch that plugs into spm_cfg_eeg_tf
% Any parameters can be specified and they are then passed to the plugin
% when it's called.
%--------------------------------------------------------------------------
if nargin == 0
    timeres = cfg_entry;
    timeres.tag = 'timeres';
    timeres.name = 'Time resolution';
    timeres.strtype = 'r';
    timeres.num = [1 1];
    timeres.val = {400};
    timeres.help = {'Length of the sliding time window (in ms)'};

    timestep = cfg_entry;
    timestep.tag = 'timestep';
    timestep.name = 'Time step';
    timestep.strtype = 'r';
    timestep.num = [1 1];
    timestep.val = {50};
    timestep.help = {'Step to slide the time window by (in ms)'};

    bandwidth = cfg_entry;
    bandwidth.tag = 'bandwidth';
    bandwidth.name = 'Time bandwidth';
    bandwidth.strtype = 'n';
    bandwidth.num = [1 1];
    bandwidth.val = {3};
    bandwidth.help = {'Time bandwidth parameter (e.g. 3 or 4)'};

    mtmspec = cfg_branch;
    mtmspec.tag = 'mtmspec';
    mtmspec.name = 'SPM multitaper';
    mtmspec.val = {timeres, timestep, bandwidth};

    res = mtmspec;

    return
elseif nargin < 3
    error('Three input arguments are required');
end

%-Defaults
%--------------------------------------------------------------------------
if ~isfield(S, 'timeres')
    S.timeres = 400;
end

if ~isfield(S, 'timestep')
    S.timestep = 50;
end

if ~isfield(S, 'bandwidth')
    S.bandwidth = 3;
end

%-Data dimensions
%--------------------------------------------------------------------------
fsample = 1./diff(time(1:2));

timeres  = 1e-3*S.timeres;
timestep = 1e-3*S.timestep;

if timestep>timeres
    error('Time resolution should exceed time step');
end

%-Do the spectral analysis
%--------------------------------------------------------------------------
res = [];
[p, f, t] = spm_mmtspec(data', fsample, S.frequencies, timeres, timestep, S.bandwidth);

if size(data, 1) == 1
    res.pow = shiftdim(p, -1);
else
    res.pow = permute(p, [3 1 2]);
end

res.freq = f;

dt = (time(end)-time(1))./length(t);

res.time = (time(1)+dt/2):dt:time(end);