function [cIX,gIX] = MakeFoxels(cIX,gIX,M_0,cIX_reg,isWkmeans,clusParams,absIX,i_fish)
% Obtain foxels (functional voxels)

% if isAutoclusWithAllCells,
%     cIX_reg = (1:size(M_0,1))';
% else
%     cIX_reg = cIX;
% end

%% set params
% default:
% thres_reg2 = 0.5;
thres_reg = 0.5;
% thres_merge = 0.5;
% thres_cap = 0.3;
thres_minsize = 10;
numK1 = 20;
avrFxsize = 10;
numK2 = round(length(cIX)/avrFxsize/numK1);

isShowProgress = 1;

% optional override:
if exist('clusParams','var'),
    if ~isempty(clusParams),
        thres_reg = clusParams.reg1; % correlation coeff
        thres_minsize = clusParams.minSize; % number of cells
        numK1 = clusParams.k1;

        isShowProgress = 0;
    end
else

end

    %% 1. k-means (2-step)
    % 1.1. first level k-means
    k1Start = tic;
    if isWkmeans,
        if isShowProgress,
            disp(['kmeans step 1: k = ' num2str(numK1)]);
        end
        gIX = Kmeans_Direct(M_0(cIX,:),numK1);
    else
        [gIX, numK1] = SqueezeGroupIX(gIX);
    end
    k1Time = toc(k1Start);

    % 1.2. divide each of the above clusters again
    if isShowProgress,
        disp(['kmeans step 2: k = ' num2str(numK2)]);
    end
    k2Start = tic;

    gIX_old = gIX;

    % temporarily suppress kmeans warnings
    wid = 'stats:kmeans:FailedToConverge';
    orig_warn = warning('off',wid);

    for i = 1:numK1,
        IX = find(gIX_old == i);
        M_sub = M_0(cIX(IX),:);
        rng('default');
        if numK2<length(IX),
            gIX_sub = kmeans(M_sub,numK2,'distance','correlation');
        else
            gIX_sub = kmeans(M_sub,length(IX),'distance','correlation');
        end
        gIX(IX) = (i-1)*numK2+gIX_sub;
    end
    % restore warnings
    warning(orig_warn);

    k2Time = toc(k2Start);

    %% 2. Regression with the centroid of each cluster
    if isShowProgress,
        disp('regression to make foxels');
    end
    reg0Start = tic;

    Reg = FindCentroid_Direct(gIX,M_0(cIX,:));
    [cIX,gIX,numFoxels] = AllCentroidRegression_SizeThres_direct(M_0(cIX_reg,:),cIX_reg,thres_reg,Reg,thres_minsize/2);

    reg0Time = toc(reg0Start);

%     if exist('absIX','var') && exist('i_fish','var'),
%         clusgroupID = 2;
%         SaveCluster_Direct(cIX,gIX,absIX,i_fish,'foxels',clusgroupID);
%     end

    %% (3. report timing)
    disp(['(Size) nFox:' num2str(numFoxels)]);
    disp(['(Time) k1:' num2str(k1Time) ...
        ' k2:' num2str(k2Time) ...
        ' reg0:' num2str(reg0Time)]);
end


function [header_size, version, f_height, f_width, bytes_per_chunk, ...
          max_n_frames, data_format] = fmf_read_header( filename )
% [header_size,version,nr,nc,bytes_per_chunk,nframes,data_format] = fmf_read_header(filename)
%
% reads FlyMovieFormat header data from FILENAME
%
% HEADER_SIZE is in bytes for the appropriate file format (fmf VERSION)
% F_HEIGHT and F_WIDTH are the number of pixels in a frame
% BYTES_PER_CHUNK is the number of bytes per frame in the file
% MAX_N_FRAMES is the number of frames in the file
%
% JAB 7/1/04
%
% Fixed bug in reading number of frames.
%
% KMB 05/22/07

header_size = 28;

fp = fopen( filename, 'r' );

% read header
version = double( fread( fp, 1, 'uint32' ) );
if (version ~= 1) && (version ~= 3),
  error( 'version not supported -- FMF versions 1 and 3 only' );
end

if version == 1,
  data_format = 'MONO8';
  bits_per_pixel = 8;
end

if version == 3,
  format_len = double( fread( fp, 1, 'uint32' ) );
  data_format = strcat( char( fread( fp, format_len))');
  bits_per_pixel = double( fread( fp, 1, 'uint32' ) );
  header_size = header_size + format_len + 8;
end

f_height = double( fread( fp, 1, 'uint32' ) );
f_width = double( fread( fp, 1, 'uint32' ) );
bytes_per_chunk = double( fread( fp, 1, 'uint64' ) );
frame_count_location = ftell(fp);
max_n_frames = double( fread( fp, 1, 'uint64' ) );

if max_n_frames <= 0,
  fprintf('Resorting to computing number of frames from size of file.\n');
  pcurr = ftell(fp);
  fseek(fp,0,'eof');
  nbytestot = ftell(fp);
  fseek(fp,pcurr,'bof');
  max_n_frames = floor((nbytestot - header_size) / bytes_per_chunk);
end

fclose( fp );


function truncated_normal_sparse_grid_test ( )

%*****************************************************************************80
%
%% TRUNCATED_NORMAL_SPARSE_GRID_TEST tests TRUNCATED_NORMAL_SPARSE_GRID library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 February 2014
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TRUNCATED_NORMAL_SPARSE_GRID_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the TRUNCATED_NORMAL_SPARSE_GRID library.\n' );

  tno_order_test ( );
  tno_test ( );
  tno_persistence_test ( );
  tno_sparse_grid_test ( );

  tno_sparse_grid_size_test ( );
  tno_sparse_grid_test ( )
  tno_sparse_grid_write_test ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TRUNCATED_NORMAL_SPARSE_GRID_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function y = cvx_s_banded( m, n, lower, upper )
%CVX_S_BANDED (U,L)-banded matrices.

if nargin < 3,
    error( 'Bandwidth arguments missing.' );
elseif ~isnumeric( lower ) || length( lower ) ~= 1 || lower < 0 || lower ~= floor( lower ),
    error( 'Bandwidth arguments must be nonnegative integers.' );
elseif nargin < 4,
    upper = lower;
elseif ~isnumeric( upper ) || length( upper ) ~= 1 || upper < 0 || upper ~= floor( upper ),
    error( 'Bandwidth arguments must be nonnegative integers.' );
end

c  = 0 : n - 1;
c  = c( ones( 1, m ), : );
r  = ( 0 : m - 1 )';
r  = r( :, ones( 1, n ) );
temp = r - c;
temp = temp <= lower & temp >= -upper;
r  = r( temp );
c  = c( temp );
y = sparse( 1 : length( r ), r + m * c + 1, 1, length( r ), m * n );

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


function confMatrixShow( CM, types, pvPairs, nDigits, showCnts )
% Used to display a confusion matrix.
%
% See confMatrix for general format and info on confusion matricies. This
% function normalizes the CM before displaying, hence all values range in
% [0,1] and rows sum to 1.
%
% USAGE
%  confMatrixShow( CM, [types], [pvPairs], [nDigits], [showCnts] )
%
% INPUTS
%  CM          - [nTypes x nTypes] confusion array -- see confMatrix
%  types       - [] cell array of length nTypes of text labels
%  pvPairs     - [{'FontSize',20}] parameter / value list for text.m
%  nDigits     - [2] number of digits after decimal to display
%  showCnts    - [0] show total count per row to the right
%
% OUTPUTS
%
% EXAMPLE
%  CM = randint2(6,6,[1,100])+eye(6)*500;
%  types = { 'anger','disgust','fear','joy','sadness','surprise' };
%  confMatrixShow( CM, types, {'FontSize',20}, [], 0 )
%  title('confusion matrix','FontSize',24);
%
% See also confMatrix, imLabel, dispMatrixIm
%
% Piotr's Computer Vision Matlab Toolbox      Version 2.50
% Copyright 2014 Piotr Dollar.  [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]

if( nargin<2 ); types=[]; end
if( nargin<3 || isempty(pvPairs)); pvPairs = {'FontSize',20}; end
if( nargin<4 || isempty(nDigits)); nDigits=2; end
if( nargin<5 || isempty(showCnts)); showCnts=0; end
if( nDigits<1 || nDigits>10 ); error('too few or too many digits'); end
if( any(CM(:)<0) ); error( 'CM must have non-negative entries' ); end

% normalize and round appropriately
cnts = sum(CM,2);
CM = CM ./ repmat( cnts+eps, [1 size(CM,2)] );
CM = round(CM*10^nDigits) / 10^nDigits;

% display as image using dispMatrixIm
dispMatrixIm(CM,'maxM',1,'maxLen',nDigits+1,'show0',0,...
  'fStr','%f','invert',1,'pvPairs',pvPairs); axis square;

% now add type labels
if( ~isempty(types) )
  imLabel( types, 'left', 0, pvPairs );
  imLabel( types, 'bottom', -35, pvPairs );
  if(showCnts), imLabel(int2str2(cnts),'right',0,pvPairs); end
end


function results = vl_test_whistc(varargin)
% VL_TEST_WHISTC
vl_test_init ;

function test_acc()
x = ones(1, 10) ;
e = 1 ;
o = 1:10 ;
vl_assert_equal(vl_whistc(x, o, e), 55) ;

function test_basic()
x = 1:10 ;
e = 1:10 ;
o = ones(1, 10) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;

x = linspace(-1,11,100) ;
o = ones(size(x)) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;

function test_multidim()
x = rand(10, 20, 30) ;
e = linspace(0,1,10) ;
o = ones(size(x)) ;

vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ;
vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ;
vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ;

function test_nan()
x = rand(10, 20, 30) ;
e = linspace(0,1,10) ;
o = ones(size(x)) ;
x(1:7:end) = NaN ;

vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ;
vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ;
vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ;

function test_no_edges()
x = rand(10, 20, 30) ;
o = ones(size(x)) ;
vl_assert_equal(histc(1, []), vl_whistc(1, 1, [])) ;
vl_assert_equal(histc(x, []), vl_whistc(x, o, [])) ;
vl_assert_equal(histc(x, [], 1), vl_whistc(x, o, [], 1)) ;
vl_assert_equal(histc(x, [], 2), vl_whistc(x, o, [], 2)) ;
vl_assert_equal(histc(x, [], 3), vl_whistc(x, o, [], 3)) ;


function points3d(varargin)
%POINTS3D Description of functions operating on 3D points.
%
%   Points are represented by their 3 Cartesian coordinates:
%   P = [X Y Z];
%
%   Arrays of points consist in N*3 arrays, each row being a point.
%
%   See also
%   isCoplanar, distancePoints, boundingBox3d
%   anglePoints3d, angleSort3d, sphericalAngle
%   sph2cart2, cart2sph2, cart2cyl, cyl2cart
%   transformPoint3d, clipPoints3d
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2008-10-13,    using Matlab 7.4.0.287 (R2007a)
% Copyright 2008 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.


function [ac] = printResult(X, label, K, kmeansFlag)

if kmeansFlag == 1
    indic = litekmeans(X, K, 'Replicates',20);
else
    [~, indic] = max(X, [] ,2);
end
result = bestMap(label, indic);
[ac, nmi_value, cnt] = CalcMetrics(label, indic);
disp(sprintf('ac: %0.4f\t%d/%d\tnmi:%0.4f\t', ac, cnt, length(label), nmi_value));


function [tn, xn,lambda] = calcDiscreteMap(obj, t, x, varargin)
    % calculates the discrete map of the dynamical system that maps
    % xminus from xplus. Subclasses must implement this method by its
    % own.
    %
    % @note By default, this discrete map will be a Identity map.
    % For specific discrete map, please implement as a subclass of
    % this class
    %
    % Parameters:
    % t: the time instant
    % x: the pre-impact states @type colvec
    %
    % Return values:
    % tn: the time after reset @type double
    % xn: the post-impact states @type colvec
    % lambda: the impulsive wrench @type struct

    R = obj.R;
    cstr_name = fieldnames(obj.ImpactConstraints);

    nx = obj.numState;
    qminus = x(1:nx);
    dqminus = x(nx+1:end);

    if isempty(cstr_name)
        qplus = R*qminus;
        dqplus = R*dqminus;
    else
        q = R*qminus;
        dq = R*dqminus;

        %% impact constraints
        cstr = struct2array(obj.ImpactConstraints);
        n_cstr = length(cstr);
        % determine the total dimension of the holonomic constraints
        cdim = sum([cstr.Dimension]);
        % initialize the Jacobian matrix
        Je = zeros(cdim,nx);

        idx = 1;
        for i=1:n_cstr
            c_obj = cstr(i);
            cstr_indices = idx:idx+c_obj.Dimension-1;

            % calculate the Jacobian
            [Jh] = calcJacobian(c_obj,q,dq);
            Je(cstr_indices,:) = Jh;
            idx = idx + c_obj.Dimension;
        end

        % inertia matrix
        De = calcMassMatrix(obj,q);

        % % Compute Dynamically Consistent Contact Null-Space from Lagrange
        % % Multiplier Formulation
        %         DbarInv = Je * (De \ transpose(Je));
        %         I = eye(nx);
        %         Jbar = De \ transpose(transpose(DbarInv) \ Je );
        %         Nbar = I - Jbar * Je;
        % % Apply null-space projection
        %         dqplus = Nbar * dq;

        nImpConstr = size(Je,1);
        A = [De -Je'; Je zeros(nImpConstr)];
        b = [De*dq; zeros(nImpConstr,1)];
        y = A\b;

        ImpF = y((obj.numState+1):end);

        idx = 1;
        for i=1:n_cstr
            c_obj = cstr(i);
            cstr_indices = idx:idx+c_obj.Dimension-1;

            % calculate the Jacobian
            lambda.(c_obj.InputName) = ImpF(cstr_indices);
            idx = idx + c_obj.Dimension;
        end

        dqplus = y(1:obj.numState);

        qplus  = q;

    end

    tn = t;
    xn = [qplus; dqplus];
end


function y = cot(x)
%COT          Implements  cot(x)  for intervals
%
%   y = cot(x)
%
%interval standard function implementation
%

% written  12/30/98     S.M. Rump
% modified 09/13/99     S.M. Rump  complex allowed, sparse input, NaN input,
%                                  major revision, improved accuracy
% modified 09/02/00     S.M. Rump  rounding unchanged after use
% modified 04/04/04     S.M. Rump  set round to nearest for safety
%                                    accelaration for sparse input
% modified 04/06/05     S.M. Rump  rounding unchanged
% modified 12/04/05     S.M. Rump  extreme values for approximate part
% modified 09/06/07     S.M. Rump  approximate std fcts removed
% modified 09/28/08     S.M. Rump  check for rounding to nearest improved
% modified 10/20/08     S.M. Rump  check for zero omitted
% modified 10/18/08     S.M. Rump  StdFctsException ignore/NaN
% modified 08/26/12     S.M. Rump  global variables removed
% modified 10/13/12     S.M. Rump  INTLAB_INTVAL_STDFCTS
%

  e = 1e-30;
  if 1+e==1-e                           % fast check for rounding to nearest
    rndold = 0;
  else
    rndold = getround;
    setround(0)
  end

  if x.complex
    if issparse(x.mid)
      x.mid = full(x.mid);
      x.rad = full(x.rad);
    end
    y = cos(x)./sin(x);
    if rndold
      setround(rndold)
    end
    return
  end

  INTLAB_STDFCTS_PI = getappdata(0,'INTLAB_STDFCTS_PI');
  if issparse(x.inf)
    x.inf = full(x.inf);
    x.sup = full(x.sup);
  end

  y = x;

  % transform x.inf and x.sup mod pi/2
  [ xinfinf , xinfsup , Sinf ] = modpi2(x.inf);
  [ xsupinf , xsupsup , Ssup ] = modpi2(x.sup);

  % indices with result +/- inf
  setround(1)
  delta = x.sup-x.inf;
  Tinf = Sinf + 2;
  Tinf(Tinf>7) = Tinf(Tinf>7) - 8;
  Tsup = Ssup + 2;
  Tsup(Tsup>7) = Tsup(Tsup>7) - 8;
  indexinf = ( delta >= INTLAB_STDFCTS_PI.PIINF ) | ...
    ( floor(Tinf/4) ~= floor(Tsup/4) ) | ...
    ( ( x.inf<=0 ) & ( x.sup>=0 ) );
  Sinf(Sinf>3) = Sinf(Sinf>3) - 4;
  Ssup(Ssup>3) = Ssup(Ssup>3) - 4;

  % transformation of input arguments by modpi2:
  %   [ xinf,xsup,s ] = modpi2(y)  ==>  0 <= s <= 7, 0 <= x <= pi/4 and
  %   x = -pi/2 + y + s*pi/4 + 2k*pi        for s even
  %   x =       - y + (s-1)*pi/4 + 2k*pi    for s odd

  y.inf(:) = -inf;
  y.sup(:) = inf;

  % treat non-infinity intervals
  Sinf(indexinf) = -1;
  Ssup(indexinf) = -1;

  % save warning status
  wng = warning;
  warning off

  % treat infimum
  index = ( Ssup==0 );
  if any(index(:))
    y.inf(index) = - tan_pos(xsupsup(index),1);
  end
  index = ( Ssup==1 );
  if any(index(:))
    y.inf(index) = 1 ./ ( - tan_pos(xsupinf(index),-1) );
  end
  index = ( Ssup==2 );
  if any(index(:))
    res = tan_pos(xsupsup(index),1);
    setround(-1)
    y.inf(index) = 1 ./ res;
  end
  index = ( Ssup==3 );
  if any(index(:))
    y.inf(index) = tan_pos(xsupinf(index),-1);
  end

  % treat supremum
  index = ( Sinf==0 );
  if any(index(:))
    y.sup(index) = - tan_pos(xinfinf(index),-1);
  end
  index = ( Sinf==1 );
  if any(index(:))
    y.sup(index) = 1 ./ ( - tan_pos(xinfsup(index),1) );
  end
  index = ( Sinf==2 );
  if any(index(:))
    res = tan_pos(xinfinf(index),-1);
    setround(1)
    y.sup(index) = 1 ./ res;
  end
  index = ( Sinf==3 );
  if any(index(:))
    y.sup(index) = tan_pos(xinfsup(index),1);
  end

  % restore warning status
  warning(wng);
  setround(0)                        % set rounding to nearest

  index = isnan(x.inf);
  if any(index(:))
    y.inf(index) = NaN;
    y.sup(index) = NaN;
  end
  INTLAB_STDFCTS_EXCPTN = getappdata(0,'INTLAB_STDFCTS_EXCPTN');
  if INTLAB_STDFCTS_EXCPTN==3      % ignore input out of range (ignore-mode)
    index = ( x.inf==0 ) & ( x.sup==0 );
    if ~isempty(find(index))              % completely exceptional arguments to NaN
      setappdata(0,'INTLAB_STDFCTS_EXCPTN_',1);
      y.inf(index) = NaN;
      y.sup(index) = NaN;
    end
  elseif INTLAB_STDFCTS_EXCPTN==2  % any input out of range to NaN (NaN-mode)
    index = ( x.inf<=0 ) & ( 0<=x.sup );
    if ~isempty(find(index))              % exceptional arguments to NaN
      setappdata(0,'INTLAB_STDFCTS_EXCPTN_',1);
      y.inf(index) = NaN;
      y.sup(index) = NaN;
    end
  end

  setround(rndold)


function cc_io_test02 ( )

%*****************************************************************************80
%
%% CC_IO_TEST02 tests CC_HEADER_READ and CC_DATA_READ.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 July 2014
%
%  Author:
%
%    John Burkardt
%
  prefix = 'simple';

  fprintf ( 1, '\n' );
  fprintf ( 1, 'CC_IO_TEST02\n' );
  fprintf ( 1, '  Read a sparse matrix in CC format from 3 files.\n' );
%
%  Read the header.
%
  [ ncc, n ] = cc_header_read ( prefix );
%
%  Read the matrix data.
%
  [ icc, ccc, acc ] = cc_data_read ( prefix, ncc, n );
%
%  Print the CC matrix.
%
  m = n;
  cc_print ( m, n, ncc, icc, ccc, acc, '  The matrix in 1-based CC format:' );

  return
end


function imsegs = im2superpixels(im, method, varargin )
    if nargin < 3
        % default parameters to generate superpixels
        switch method
            case 'pedro'
                sigma = 0.8;
                k = 100;
                min_size = 150;
            case 'SLIC'
                num_superpixel = 200;
            otherwise
                error( 'unknown method to generate superpixels.' );
        end
    else
        switch method
            case 'pedro'
                para = varargin{1};
                sigma = para(1);
                k = para(2);
                min_size = para(3);
            case 'SLIC'
                num_superpixel = varargin{1};
            otherwise
                error( 'unknown method to generate superpixels.' );
        end
    end

%     prefix = num2str(floor(rand(1)*10000000));
%     fn1 = ['./tmpim' prefix '.ppm'];
%     fn2 = ['./tmpimsp' prefix '.ppm'];
%     segcmd = ['E:\playerkk\code\MATLAB\segment\segment ', num2str(seg_para(1)),...
%         ' ', num2str(seg_para(2)), ' ', num2str(seg_para(3))];
%
%     imwrite(im, fn1);
%     system([segcmd ' ' fn1 ' ' fn2]);
    if isa(im, 'uint8')
        im = double(im);
    end

    if max(im(:)) < 10
        im = double(im * 255);
    end

    switch method
        case 'pedro'
            segim = mexSegment(im, sigma, k, int32(min_size));
        case 'SLIC'
            segim = uint8(mexSLIC(uint32(im), num_superpixel));
        otherwise
            error( 'unknown method to generate superpixels.' );
    end
    imsegs = processSuperpixelImage(segim);


function ob = mridft(kx, ky, t, we, xval, yval, fov, N)
%function ob = mridft(kx, ky, t, we, xval, yval, fov, N)
%	Construct MRI object, which can do Ax and A'y operations
%       Brad Sutton    University of Michigan

%	default object
ob.kx = 0;	% should these be []'s
ob.ky = 0;
ob.t = 0;
ob.we = 0;
ob.xval = 0;
ob.yval = 0;
ob.is.empty	= true;
ob.is.transpose = false;
ob.fov = 0;  %FOV in cm's
ob.n = 0;
%ob.version = 1.0;

if nargin == 0
	ob = class(ob, 'mridft');
	return
end

if isa(kx, 'mridft')
	ob = kx;
	return
end

if nargin ~= 8
	help mridft
	error nargin
end

	%	fill object
	ob.kx = kx;
	ob.ky = ky;
	ob.t = t;
	ob.we = we;
	ob.xval = xval;
	ob.yval = yval;
        ob.fov = fov;
        ob.n = N;

	ob.is.empty	= false;

%	ob.m = size(we);	% image size
%	ob.n = size(we);

	ob = class(ob, 'mridft');


function k = findrows(A, b)
%FINDROWS Find indices of a given row within a matrix.
%
%   FINDROWS(A, B) returns a column vector with the indices of the rows
%   in the matrix A that are identical to the row vector B.  If no rows
%   in A are identical to B, an empty vector is returned.
%
%   The methods uses a for-loop, but it uses less memory and is in many
%   cases a lot faster than the vectorized methods
%
%      find( all( A == repmat(b, size(A, 1), 1), 2 ) )
%      find( all( A == b(ones(size(A, 1), 1),:), 2 ) )
%
%   See also FIND, FINDCOLS.

%   Author:      Peter J. Acklam
%   Time-stamp:  2002-03-03 13:51:15 +0100
%   E-mail:      pjacklam@online.no
%   URL:         http://home.online.no/~pjacklam

if isempty(A)
    k = [];
    return
end

k = find( A(:,1) == b(1));
top = size(A, 2);
for j = 2:top
    k = k(A(k,j) == b(j));
    if isempty(k)
        return
    end
end


function element_size = p09_element_size ( )

%*****************************************************************************80
%
%% P09_ELEMENT_SIZE returns a typical element size for problem 09.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Per-Olof Persson and Gilbert Strang,
%    A Simple Mesh Generator in MATLAB,
%    SIAM Review,
%    Volume 46, Number 2, June 2004, pages 329-345.
%
%  Parameters:
%
%    Input, real ELEMENT_SIZE, a typical element size.
%
  element_size = 0.005;

  return
end


function igood = check_clusters(hid, ss, rmax)

nmax = max(hid);
igood = zeros(nmax,1);
for j = 1:nmax
    ix = hid==j;
    if sum(ix)>0
        igood(j) = is_good(ss(ix), rmax);
    end
end
end

function igood = is_good(ss, rmax)
dt = 1/1000;
fcontamination = 0.1;
[K, Qi, Q00, Q01, rir] = ccg(ss, ss, 500, dt); % % compute the auto-correlogram with 500 bins at 1ms bins
Q = min(Qi/(max(Q00, Q01))); % this is a measure of refractoriness
R = min(rir); % this is a second measure of refractoriness (kicks in for very low firing rates)
if Q<fcontamination && R<rmax
   igood = 1;
else
    igood = 0;
end

end


function M = mult(disc, f)
%MULT    Multiplication operator for the TRIGSPEC class.
%   M = MULT(A, F) returns the multiplication operator that represents
%   u(x) -> F(x)u(x), in the Fourier basis.
%
% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% Obtaining some useful information:
n = disc.dimension;
dom = disc.domain;

% Convert to a TRIGTECH-based CHEBFUN. Use a non-adaptive construction:
% we know that the TRIGTECH-based CHEBFUN will have a length smaller
% than the CHEBTECH-based CHEBFUN.
f = chebfun(f, dom, 'periodic', length(f));
f = simplify(f);

% Call TRIGSPEC/MULTMAT.
M = trigspec.multmat(n, f);

end


function Offspring = OperatorGA(Problem,Parent,Parameter)
%OperatorGA - Crossover and mutation operators of genetic algorithm.
%
%   Off = OperatorGA(Pro,P) uses genetic operators to generate offsprings
%   for problem Pro based on parents P. If P is an array of SOLUTION
%   objects, then Off is also an array of SOLUTION objects. While if P is a
%   matrix of decision variables, then Off is also a matrix of decision
%   variables, i.e., the offsprings are not evaluated. P is split into two
%   subsets P1 and P2 with the same size, where each object or row of P1
%   and P2 is used to generate two offsprings. Different operators are used
%   for different encoding schemes.
%
%   Off = OperatorGA(Pro,P,{proC,disC,proM,disM}) specifies the parameters
%   of operators, where proC is the probability of crossover, disC is the
%   distribution index of simulated binary crossover, proM is the
%   expectation of the number of mutated variables, and disM is the
%   distribution index of polynomial mutation.
%
%   Example:
%       Offspring = OperatorGA(Problem,Parent)
%       Offspring = OperatorGA(Problem,Parent.decs,{1,20,1,20})
%
%   See also OperatorGAhalf

%------------------------------- Reference --------------------------------
% [1] K. Deb, K. Sindhya, and T. Okabe, Self-adaptive simulated binary
% crossover for real-parameter optimization, Proceedings of the Annual
% Conference on Genetic and Evolutionary Computation, 2007, 1187-1194.
% [2] K. Deb and M. Goyal, A combined genetic adaptive search (GeneAS) for
% engineering design, Computer Science and informatics, 1996, 26: 30-45.
% [3] L. Davis, Applying adaptive algorithms to epistatic domains,
% Proceedings of the International Joint Conference on Artificial
% Intelligence, 1985, 162-164.
% [4] D. B. Fogel, An evolutionary approach to the traveling salesman
% problem, Biological Cybernetics, 1988, 60(2): 139-144.
%------------------------------- 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".
%--------------------------------------------------------------------------

    if nargin > 2
        [proC,disC,proM,disM] = deal(Parameter{:});
    else
        [proC,disC,proM,disM] = deal(1,20,1,20);
    end
    if isa(Parent(1),'SOLUTION')
        evaluated = true;
        Parent    = Parent.decs;
    else
        evaluated = false;
    end
    Parent1   = Parent(1:floor(end/2),:);
    Parent2   = Parent(floor(end/2)+1:floor(end/2)*2,:);
    Offspring = zeros(2*size(Parent1,1),size(Parent1,2));
    Type      = arrayfun(@(i)find(Problem.encoding==i),1:5,'UniformOutput',false);
    if ~isempty([Type{1:2}])    % Real and integer variables
        Offspring(:,[Type{1:2}]) = GAreal(Parent1(:,[Type{1:2}]),Parent2(:,[Type{1:2}]),Problem.lower([Type{1:2}]),Problem.upper([Type{1:2}]),proC,disC,proM*length([Type{1:2}])/size(Parent1,2),disM);
    end
    if ~isempty(Type{3})        % Label variables
        Offspring(:,Type{3}) = GAlabel(Parent1(:,Type{3}),Parent2(:,Type{3}),Problem.lower(Type{3}),Problem.upper(Type{3}),proC,proM*length(Type{3})/size(Parent1,2));
    end
    if ~isempty(Type{4})        % Binary variables
        Offspring(:,Type{4}) = GAbinary(Parent1(:,Type{4}),Parent2(:,Type{4}),proC,proM*length(Type{4})/size(Parent1,2));
    end
    if ~isempty(Type{5})        % Permutation variables
        Offspring(:,Type{5}) = GApermutation(Parent1(:,Type{5}),Parent2(:,Type{5}),proC);
    end
    if evaluated
        Offspring = Problem.Evaluation(Offspring);
    end
end

function Offspring = GAreal(Parent1,Parent2,lower,upper,proC,disC,proM,disM)
% Genetic operators for real and integer variables

    %% Simulated binary crossover
    [N,D] = size(Parent1);
    beta  = zeros(N,D);
    mu    = rand(N,D);
    beta(mu<=0.5) = (2*mu(mu<=0.5)).^(1/(disC+1));
    beta(mu>0.5)  = (2-2*mu(mu>0.5)).^(-1/(disC+1));
    beta = beta.*(-1).^randi([0,1],N,D);
    beta(rand(N,D)<0.5) = 1;
    beta(repmat(rand(N,1)>proC,1,D)) = 1;
    Offspring = [(Parent1+Parent2)/2+beta.*(Parent1-Parent2)/2
                 (Parent1+Parent2)/2-beta.*(Parent1-Parent2)/2];

    %% Polynomial mutation
    Lower = repmat(lower,2*N,1);
    Upper = repmat(upper,2*N,1);
    Site  = rand(2*N,D) < proM/D;
    mu    = rand(2*N,D);
    temp  = Site & mu<=0.5;
    Offspring       = min(max(Offspring,Lower),Upper);
    Offspring(temp) = Offspring(temp)+(Upper(temp)-Lower(temp)).*((2.*mu(temp)+(1-2.*mu(temp)).*...
                      (1-(Offspring(temp)-Lower(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1))-1);
    temp = Site & mu>0.5;
    Offspring(temp) = Offspring(temp)+(Upper(temp)-Lower(temp)).*(1-(2.*(1-mu(temp))+2.*(mu(temp)-0.5).*...
                      (1-(Upper(temp)-Offspring(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1)));
end

function Offspring = GAlabel(Parent1,Parent2,lower,upper,proC,proM)
% Genetic operators for label variables

    %% Uniform crossover
    [N,D] = size(Parent1);
    k     = rand(N,D) < 0.5;
    k(repmat(rand(N,1)>proC,1,D)) = false;
    Offspring1    = Parent1;
    Offspring2    = Parent2;
    Offspring1(k) = Parent2(k);
    Offspring2(k) = Parent1(k);
    Offspring     = [Offspring1;Offspring2];

    %% Bitwise mutation
    Site = rand(2*N,D) < proM/D;
    Rand = round(unifrnd(repmat(lower,2*N,1),repmat(upper,2*N,1)));
    Offspring(Site) = Rand(Site);
end

function Offspring = GAbinary(Parent1,Parent2,proC,proM)
% Genetic operators for binary variables

    %% Uniform crossover
    [N,D] = size(Parent1);
    k     = rand(N,D) < 0.5;
    k(repmat(rand(N,1)>proC,1,D)) = false;
    Offspring1    = Parent1;
    Offspring2    = Parent2;
    Offspring1(k) = Parent2(k);
    Offspring2(k) = Parent1(k);
    Offspring     = [Offspring1;Offspring2];

    %% Bit-flip mutation
    Site = rand(2*N,D) < proM/D;
    Offspring(Site) = ~Offspring(Site);
end

function Offspring = GApermutation(Parent1,Parent2,proC)
% Genetic operators for permutation variables

    %% Order crossover
    [N,D]     = size(Parent1);
    Offspring = [Parent1;Parent2];
    k = randi(D,1,2*N);
    for i = 1 : N
        if rand < proC
            Offspring(i,k(i)+1:end)   = setdiff(Parent2(i,:),Parent1(i,1:k(i)),'stable');
            Offspring(i+N,k(i)+1:end) = setdiff(Parent1(i,:),Parent2(i,1:k(i)),'stable');
        end
    end

    %% Slight mutation
    k = randi(D,1,2*N);
    s = randi(D,1,2*N);
    for i = 1 : 2*N
        if s(i) < k(i)
            Offspring(i,:) = Offspring(i,[1:s(i)-1,k(i),s(i):k(i)-1,k(i)+1:end]);
        elseif s(i) > k(i)
            Offspring(i,:) = Offspring(i,[1:k(i)-1,k(i)+1:s(i)-1,k(i),s(i):end]);
        end
    end
end


function [totSec hh mm ss fract] = dcm_hhmmss(dateStr)
if ~ischar(dateStr)
    dateStr = num2str(dateStr);
end
hh = str2double(dateStr(1,1:2));
mm = str2double(dateStr(1,3:4));
ss = str2double(dateStr(1,5:6));
fract_start = find(dateStr,'.');
fract = str2double(dateStr(1,fract_start+1:end));
totSec = hh*60*60 + mm*60 + ss;
end


function dendrogramplot(c);

% Private method. See ../plot for details.

% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks
% $Date$
% $Revision$

if ~isa(c,'correlation')
    error('First input must be a correlation object');
end;

if isempty(get(c,'LINK'))
    error('LINK field must be filled in input object');
end;

if ~isempty(get(c,'LAG'))
    disp('NOTE: Time corrections from LAG field have not been applied to traces yet.');
end;

% CREATE DENDROGRAM PLOT
[H,tmp,perm] = dendrogram(c.link,length(c.trig),'Orientation','right');
set(gcf,'Color','w','Position',[50 50 680 880]);
ylabel('event number','FontSize',16);
set(gca,'XGrid','on');
box on; hold on;
set(gcf,'Position',[0 0 640 1024]);

% SWITCH X AXIS LABELS
set(gca,'XDir','reverse');
% Fix by GT based on email by Kyle Brill, July 2016, see Issue 51
%label = 1- str2num(get(gca,'XTickLabel'));
label = 1- str2double(get(gca,'XTickLabel'));
set(gca,'XTickLabel',label);
%xlabel('distance (dissimilarlity)','FontSize',16);
xlabel('inter-cluster correlation','FontSize',16);

% MODIFY Y AXIS LABELS
if ~isempty(c.clust)
    YT = (get(gca,'YTickLabel'));
	%YT = strcat(YT,' (',num2str(c.clust(perm)),')');
    set(gca,'YTickLabel',YT);
    ylabel('event number (and cluster)','FontSize',16);
end

% PREP PRINT OUT
set(gcf, 'paperorientation', 'portrait');
set(gcf, 'paperposition', [.25 .25 8 10.5] );

% ADD WIGGLE PLOT
perm = fliplr(perm);
if length(perm)>=100
    plot(c,'sha',1,perm);
else
    plot(c,'wig',1,perm);
end

set(gcf,'Position',[641 0 640 1024]);


clear
    % Generarea unei celule goale de dimensiunea 2x2
Q=cell(2,2)
    % Incarcarea celulei
Q={ones(3), [1 3 6 7 6]; ['TN ';'SL ';'DMI';'NDD'], logical(eye(3))};
    % Afisarea informatiilor aferente celulei
whos Q
    % Afisarea continutului inregei celule i a unui element a acesteia
disp('Afisarea intregei celule:')
disp(Q)
disp('Afisarea unui elelement din celula:')
disp(Q{2,1})


Nneurons = [10,10]; % the number of neurons in each sequence
Dt = [10,10]; % the number of time steps between each neuron in the sequence
Pseq = [1,1]; % the probability of the sequence occuring
NeuronNoise = 0.001; % the noise in a neurons firing rate
SeqNoiseTime = [0,0]; % the noise in the sequence aka jitter (p of each neuron jittered 1 dt)
SeqNoiseNeuron = [1,1]; % the probability that a neuron participates in a given seq
T = 10000;
shared  = 1;
%%
V = data.sequences(T,Nneurons,Dt,NeuronNoise,SeqNoiseTime,SeqNoiseNeuron,shared);


function mpc = order_radial(mpc)
%ORDER_RADIAL  Performs oriented ordering to buses and branches.
%
%   mpc = order_radial(mpc)
%
%   orders the branches by the the principle of oriented ordering:
%   indicies of sending nodes are smaller than the indicies of the
%   receiving nodes. The branch index is equal to the index of their
%   receiving node. The ordering is taken from:
%   D. Rajicic, R. Ackovski and R. Taleski, "Voltage correction power flow,"
%   IEEE Transactions on Power Delivery, vol. 9, no. 2, pp. 1056-1062, Apr 1994.
%
%   See also RADIAL_PF.

%% define named indices into bus, gen, branch matrices
define_constants;
%% Initialize
slack = mpc.bus(mpc.bus(:,BUS_TYPE) == REF, 1);
[f, t] = deal(mpc.branch(:,F_BUS),mpc.branch(:,T_BUS));
nl = size(mpc.branch,1);
branch_number = (1:nl)';
mpc.branch_order = [];
mpc.loop = [];
mpc.bus_order = slack;
%% Bus and branch ordering
iter = 1;
while ~isempty(f) && iter <= nl
    % For each of the "from" buses that are in bus_order,
    % add the corresponding "to" buses to it. If both "from" and "to" are
    % in bus_order, the branch is forming loop. Add corresponding branch
    % numbers to branch_order or to loop.
    mf = ismember(f,mpc.bus_order);
    mt = ismember(t,mpc.bus_order);
    is_loop = mf & mt;
    % Add branch to loop and delete it from the list
    if any(is_loop)
        mpc.loop = [mpc.loop; branch_number(is_loop)];
        mf(is_loop) = [];
%         mt(is_loop) = [];
        f(is_loop) = [];
        t(is_loop) = [];
        branch_number(is_loop) = [];
    end
    % Add unique buses to bus_order
    if any(mf)
        u = unique(t(mf)); % unique buses
        [junk,i] = intersect(t.*mf,u); % first occurence of unique buses in t
        mpc.bus_order = [mpc.bus_order; t(i)];
        % Add branch to branch_order and delete it from the list
        mpc.branch_order = [mpc.branch_order; branch_number(i)];
        mf(i) = [];
%         mt(i) = [];
        f(i) = [];
        t(i) = [];
        branch_number(i) = [];
    end
    % Add any remaining branch to loop and delete it from the list
    if any(mf)
        mpc.loop = [mpc.loop; branch_number(mf)];
        f(mf) = [];
        t(mf) = [];
        branch_number(mf) = [];
    end
    % For each of the "to" buses that are in bus_order,
    % add the corresponding "from" buses to it. If both "from" and "to" are
    % in bus_order, the branch is forming loop. Add corresponding branch
    % numbers to branch_order or to loop.
    mf = ismember(f,mpc.bus_order);
    mt = ismember(t,mpc.bus_order);
    is_loop = mf & mt;
    % Add branch to loop and delete it from the list
    if any(is_loop)
        mpc.loop = [mpc.loop; branch_number(is_loop)];
        mt(is_loop) = [];
%         mf(is_loop) = [];
        f(is_loop) = [];
        t(is_loop) = [];
        branch_number(is_loop) = [];
    end
    % Add unique buses to bus_order
    if any(mt)
        u = unique(f(mt)); % unique buses
        [junk,i] = intersect(f.*mt,u); % first occurence of unique buses in f
        mpc.bus_order = [mpc.bus_order; f(i)];
        % Add branch to branch_order and delete it from the list
        mpc.branch_order = [mpc.branch_order; branch_number(i)];
%         mf(i) = [];
        mt(i) = [];
        f(i) = [];
        t(i) = [];
        branch_number(i) = [];
    end
    % Add any remaining branch to loop and delete it from the list
    if any(mt)
        mpc.loop = [mpc.loop; branch_number(mt)];
        f(mt) = [];
        t(mt) = [];
        branch_number(mt) = [];
    end
    iter = iter + 1;
end
if ~isempty(f)
    mpc.not_connected = branch_number;
else
    mpc.not_connected = [];
end
%% Reorder bus, branch and gen.
if isempty(mpc.loop)
    % Permute rows in branch
    mpc.branch = mpc.branch(mpc.branch_order,:);
    % Make an "inverse" vector out of bus_order
    mpc.bus_order_inv = sparse(mpc.bus_order,ones(nl+1,1),1:nl+1);
    % Swap indicies in "from" and "to" buses using bus_order_inv
    [f, t] = deal(mpc.branch(:,F_BUS),mpc.branch(:,T_BUS));
    f = mpc.bus_order_inv(f);
    t = mpc.bus_order_inv(t);
    % Reverse branch orientation of "from" is biger than "to"
    mpc.br_reverse = f > t;
    [f(mpc.br_reverse), t(mpc.br_reverse)] = deal(t(mpc.br_reverse), f(mpc.br_reverse));
    % Put new "from" and "to" indicies in branch
    mpc.branch(:,[F_BUS T_BUS]) = [f t];
    % Make an "inverse" vector out of branch_order
    mpc.branch_order_inv = sparse(mpc.branch_order,ones(nl,1),1:nl);
    % Permute rows in bus and replace bus indicies
    mpc.bus = mpc.bus(mpc.bus_order,:);
    mpc.bus(:,BUS_I) = mpc.bus_order_inv(mpc.bus(:,BUS_I));
    % Replace bus indicies in gen
    mpc.gen(:,GEN_BUS) = mpc.bus_order_inv(mpc.gen(:,GEN_BUS));
end


function z = ne(x,y)
%NE Not equal (~=) for sptensors.
%
%   A ~= B compares the elements of A and B for equality. The arguments can
%   be a pair of sptensors, an sptensor and a tensor, or an sptensor and a
%   scalar.  Regardless, the result is always returned as a sparse tensor.
%
%   See also SPTENSOR.
%
%MATLAB Tensor Toolbox.
%Copyright 2012, Sandia Corporation.

% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2012) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt

%% Observations for sparse matrix case.
% The result of a ~= 5 is sparse.
% The result of a ~= 0 is sparse.
% The result of a ~= full(a) is sparse.

%% Case 1: One argument is a scalar
if isscalar(y)
    if y == 0
        z = sptensor(x.subs,true,size(x));
    else
        subs1 = x.subs(x.vals ~= y,:);
        subs2 = setdiff(allsubs(x),x.subs,'rows');
        z = sptensor([subs1;subs2],true,size(x));
    end
    return;
end

% Call back with the arguments reversed.
if isscalar(x)
    z = ne(y,x);
    return;
end

%% Case 2: Both x and y are tensors or some sort
% Check that the sizes match
if ~isequal(x.size,y.size)
    error('Size mismatch');
end

% Case 2a: Two sparse tensors
if isa(x,'sptensor') && isa(y,'sptensor')

    % find entries where either x *or* y is nonzero, but not both
    subs1 = setxor(x.subs,y.subs,'rows');
    % find entries where both are nonzero, but inequal
    subs2 = intersect(x.subs,y.subs,'rows');
    subs2 = subs2(extract(x,subs2) ~= extract(y,subs2),:);
    % put it all together
    z = sptensor([subs1;subs2],true,size(x));
    return;

end

% Case 2b: y is a dense tensor
if isa(y,'tensor')

    % find entries where x is zero but y is nonzero
    subs1 = setdiff(allsubs(x),union(x.subs,find(y == 0),'rows'),'rows');

    % find entries where x is nonzero but not equal to y
    subs2 = x.subs(x.vals ~= y(x.subs,'extract'),:);

    % put it all together
    z = sptensor([subs1;subs2],true,size(x));
    return;

end

%% Otherwise
error('The arguments must be two sptensors or an sptensor and a scalar.');


function sgmga_unique_index_tests ( )

%****************************************************************************80
%
%% SGMGA_UNIQUE_INDEX_TESTS calls SGMGA_UNIQUE_INDEX_TEST with various arguments.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 June 2010
%
%  Author:
%
%    John Burkardt
%
%  Local Parameters:
%
%    Local, real TOL, a tolerance for point equality.
%    A value of sqrt ( eps ) is reasonable, and will allow the code to
%    consolidate points which are equal, or very nearly so.  A value of
%    -1.0, on the other hand, will force the code to use every point, regardless
%    of duplication.
%
  addpath ( '../sandia_rules' );

  timestamp ( );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'SGMGA_UNIQUE_INDEX_TESTS\n' );
  fprintf ( 1, '  Call SGMGA_UNIQUE_INDEX_TEST with various arguments\n' );
%
%  Set the point equality tolerance.
%
  tol = sqrt ( eps );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  All tests will use a point equality tolerance of %f\n', tol );

  dim_num = 2;
  for dim = 1 : dim_num
    importance(dim,1) = 1.0;
  end
  level_weight = sgmga_importance_to_aniso ( dim_num, importance );
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 1 ]';
  growth = [ 6, 6 ]';
  np = [ 0, 0 ]';
  np_sum = sum ( np(1:dim_num) );
  p = [];
  sgmga_unique_index_test ( dim_num, importance, level_weight, ...
    level_max_min, level_max_max, rule, growth, np, p, tol );

  dim_num = 2;
  for dim = 1 : dim_num
    importance(dim,1) = dim;
  end
  level_weight = sgmga_importance_to_aniso ( dim_num, importance );
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 1 ]';
  growth = [ 6, 6 ]';
  np = [ 0, 0 ]';
  np_sum = sum ( np(1:dim_num) );
  p = [];
  sgmga_unique_index_test ( dim_num, importance, level_weight, ...
    level_max_min, level_max_max, rule, growth, np, p, tol );

  dim_num = 3;
  for dim = 1 : dim_num
    importance(dim,1) = 1.0;
  end
  level_weight = sgmga_importance_to_aniso ( dim_num, importance );
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 1, 1 ]';
  growth = [ 6, 6, 6 ]';
  np = [ 0, 0, 0 ]';
  np_sum = sum ( np(1:dim_num) );
  p = [];
  sgmga_unique_index_test ( dim_num, importance, level_weight, ...
    level_max_min, level_max_max, rule, growth, np, p, tol );

  dim_num = 3;
  for dim = 1 : dim_num
    importance(dim,1) = dim;
  end
  level_weight = sgmga_importance_to_aniso ( dim_num, importance );
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 1, 1 ]';
  growth = [ 6, 6, 6 ]';
  np = [ 0, 0, 0 ]';
  np_sum = sum ( np(1:dim_num) );
  p = [];
  sgmga_unique_index_test ( dim_num, importance, level_weight, ...
    level_max_min, level_max_max, rule, growth, np, p, tol );

  dim_num = 2;
  for dim = 1 : dim_num
    importance(dim,1) = dim;
  end
  level_weight = sgmga_importance_to_aniso ( dim_num, importance );
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 3 ]';
  growth = [ 6, 6 ]';
  np = [ 0, 0 ]';
  np_sum = sum ( np(1:dim_num) );
  p = [];
  sgmga_unique_index_test ( dim_num, importance, level_weight, ...
    level_max_min, level_max_max, rule, growth, np, p, tol );

  dim_num = 2;
  for dim = 1 : dim_num
    importance(dim,1) = dim;
  end
  level_weight = sgmga_importance_to_aniso ( dim_num, importance );
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 4 ]';
  growth = [ 6, 3 ]';
  np = [ 0, 0 ]';
  np_sum = sum ( np(1:dim_num) );
  p = [];
  sgmga_unique_index_test ( dim_num, importance, level_weight, ...
    level_max_min, level_max_max, rule, growth, np, p, tol );

  dim_num = 2;
  for dim = 1 : dim_num
    importance(dim,1) = dim;
  end
  level_weight = sgmga_importance_to_aniso ( dim_num, importance );
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 7 ]';
  growth = [ 6, 3 ]';
  np = [ 0, 0 ]';
  np_sum = sum ( np(1:dim_num) );
  p = [];
  sgmga_unique_index_test ( dim_num, importance, level_weight, ...
    level_max_min, level_max_max, rule, growth, np, p, tol );

  dim_num = 2;
  for dim = 1 : dim_num
    importance(dim,1) = dim;
  end
  level_weight = sgmga_importance_to_aniso ( dim_num, importance );
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 8 ]';
  growth = [ 6, 3 ]';
  np = [ 0, 1 ]';
  np_sum = sum ( np(1:dim_num) );
  p(1) = 1.5;
  sgmga_unique_index_test ( dim_num, importance, level_weight, ...
    level_max_min, level_max_max, rule, growth, np, p, tol );

  dim_num = 2;
  for dim = 1 : dim_num
    importance(dim,1) = dim;
  end
  level_weight = sgmga_importance_to_aniso ( dim_num, importance );
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 2, 9 ]';
  growth = [ 6, 3 ]';
  np = [ 0, 2 ]';
  np_sum = sum ( np(1:dim_num) );
  p(1,1) = 0.5;
  p(2,1) = 1.5;
  sgmga_unique_index_test ( dim_num, importance, level_weight, ...
    level_max_min, level_max_max, rule, growth, np, p, tol );

  dim_num = 2;
  for dim = 1 : dim_num
    importance(dim,1) = dim;
  end
  level_weight = sgmga_importance_to_aniso ( dim_num, importance );
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 6, 10 ]';
  growth = [ 3, 4 ]';
  np = [ 1, 0 ]';
  np_sum = sum ( np(1:dim_num) );
  p(1) = 2.0;
  sgmga_unique_index_test ( dim_num, importance, level_weight, ...
    level_max_min, level_max_max, rule, growth, np, p, tol );

  dim_num = 3;
  for dim = 1 : dim_num
    importance(dim,1) = dim;
  end
  level_weight = sgmga_importance_to_aniso ( dim_num, importance );
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 4, 5 ]';
  growth = [ 6, 3, 3 ]';
  np = [ 0, 0, 0 ]';
  np_sum = sum ( np(1:dim_num) );
  p = [];
  sgmga_unique_index_test ( dim_num, importance, level_weight, ...
    level_max_min, level_max_max, rule, growth, np, p, tol );
%
%  Try a case with a dimension of "0 importance".
%
  dim_num = 3;
  importance = [ 1.0, 0.0, 1.0 ];
  level_weight = sgmga_importance_to_aniso ( dim_num, importance );
  level_max_min = 0;
  level_max_max = 3;
  rule = [ 1, 1, 1 ]';
  growth = [ 6, 6, 6 ]';
  np = [ 0, 0, 0 ]';
  np_sum = sum ( np(1:dim_num) );
  p = [];
  sgmga_unique_index_test ( dim_num, importance, level_weight, ...
    level_max_min, level_max_max, rule, growth, np, p, tol );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SGMGA_UNIQUE_INDEX_TESTS:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );

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

  rmpath ( '../sandia_rules' );

  return
end


classdef TestMinEnclosingCircle
    %TestMinEnclosingCircle

    properties (Constant)
        p = [0 0; 1 0; 2 2; 3 3; 3 4];
    end

    methods (Static)
        function test_1
            [c,r] = cv.minEnclosingCircle(TestMinEnclosingCircle.p);
            validateattributes(c, {'numeric'}, {'vector', 'numel',2});
            validateattributes(r, {'numeric'}, {'scalar'});
        end

        function test_2
            [c,r] = cv.minEnclosingCircle(num2cell(TestMinEnclosingCircle.p,2));
            validateattributes(c, {'numeric'}, {'vector', 'numel',2});
            validateattributes(r, {'numeric'}, {'scalar'});
        end

        function test_error_argnum
            try
                cv.minEnclosingCircle();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end


function hh = logbar(edges,vals,width,colors,hax)

if nargin < 3,
  width = .8;
end

edges = edges(:)';
nbins = numel(edges)-1;
sz = size(vals);
if ~any(sz==nbins),
  error('vals should be ndata x nbins');
end

if ~ismatrix(vals),
  error('vals must be 1- or 2-dimensional');
end
if sz(2) ~= nbins && sz(1) == nbins,
  vals = vals';
end
ndata = size(vals,1);

if nargin < 5,
  hax = gca;
end
hfig = get(hax,'Parent');

if nargin < 4 || isempty(colors),
  colors = get(hfig,'Colormap');
  if size(colors,1) > ndata,
    colors = colors(round(linspace(1,size(colors,1),ndata)),:);
  elseif size(colors,1) < ndata,
    colors = colors(modrange(1:ndata,1,size(colors,1)),:);
  end
elseif size(colors,1) < ndata,
  colors = colors(modrange(1:ndata,1,size(colors,1)),:);
end

dedge = diff(edges)*width;
off0 = (1-width)/2;
hh = nan(1,ndata);
holdstate = ishold;
for i = 1:ndata,
  off1 = off0 + (i-1)/ndata;
  off2 = off0 + i/ndata;
  x1 = edges(1:end-1)+off1*dedge;
  x2 = edges(1:end-1)+off2*dedge;
  x = [x1;x1;x2;x2];
  y = [zeros(1,nbins);vals([i,i],:);zeros(1,nbins)];
  hh(i) = patch(x(:),y(:),colors(i,:),'Parent',hax);
  if i == 1,
    hold(hax,'on');
  end
end
if holdstate == 0,
  hold(hax,'off');
end

set(hax,'XScale','log');


function gf=gradloglikGaP(x, varargin)
% f=loglikGaP(x, varargin)
% complete log likellihood of the GaP model
% Vxt = varargin{1};      %data
% sigpsf = varargin{2};  %std deviation of the PSF gaussian approx
% alpha = varargin{3}; %parameters of the Gamma prior on the blinking
% beta = varargin{4}; %parameters of the Gamma prior on the blinking
% peval = varargin{5}; %parameters
% x(1:end-2*peval.ncomp) is Hkt

Vxt = varargin{1};      %data
sigpsf = varargin{2};  %std deviation of the PSF gaussian approx
alpha = varargin{3}; %parameters of the Gamma prior on the blinking
beta = varargin{4}; %parameters of the Gamma prior on the blinking
peval = varargin{5}; %parameters

% % % Hkt_linear=x(1:end-peval.ncomp*2); % intensities
cx=x(end-peval.ncomp*2+1:end-peval.ncomp); %x-coordinates of the centers
cy=x(end-peval.ncomp+1:end); % y-coordinates of the centers
% % %
% % % Hkt_linear=x; % intensities
Hkt_linear=varargin{6};
% % % cy=varargin{7};
% % %

sigpsf_vec=repmat(sigpsf,peval.ncomp,1); %all psfs same sigma
cxy_vec=[cx'+1, cy'+1];
% cxy_vec=[cx', cy'];
a_vec=1./(sigpsf_vec.^2*2*pi); % all normalised to 1

Hkt=reshape(Hkt_linear, peval.ncomp, peval.nt);
% generate PSFs from given parameters:
Wxkpix=gauss2dmultislice([peval.nx, peval.ny, peval.ncomp], cxy_vec, sigpsf_vec, a_vec);
Wxkpix=normalizePSF(Wxkpix); %normalize PSFs to 1
Wxk=reshape(Wxkpix,peval.nx*peval.ny, peval.ncomp);
[Wxkbg,Hktbg]=addbg(Wxk, Hkt, peval.bg);
P=Wxkbg*Hktbg; %current approximation

%linear grasdient shifted by cx
xxvc = lineargrad([peval.nx, peval.ny, peval.ncomp], cx, 'xx');
yyvc = lineargrad([peval.nx, peval.ny, peval.ncomp], cy, 'yy');

% dW/dcx:
Wxtcx=1/sigpsf^2*xxvc.*Wxk;
% dW/dcy:
Wxtcy=1/sigpsf^2*yyvc.*Wxk;

% d(log(L))/dHkt:
% % % gfHkt=(alpha-1)*1./Hkt - 1/beta +
% Wxk'*(Vxt./P-eye(peval.nx*peval.ny,peval.nt));
gfHkt= Wxk'*(Vxt./P)-1; %without background (->not Wxkgb) and d(log(L)/dcx)
% d(log(L))/dcx:
gfcx=diag(Wxtcx'*(Vxt./P-ones(peval.nx*peval.ny, peval.nt))*Hkt');

% d(log(L))/dcy:
gfcy=diag(Wxtcy'*(Vxt./P-ones(peval.nx*peval.ny, peval.nt))*Hkt');

% % % gf = [reshape(gfHkt',1,peval.nt*peval.ncomp), gfcx', gfcy'];
%gf = [reshape(gfHkt,1,peval.nt*peval.ncomp)];
gf = [gfcx', gfcy'];
end
function Wnorm=normalizePSF(W)
sw=size(W);
Wr=reshape(W, sw(1)*sw(2),sw(3));
q=squeeze(sum(Wr,1));
Wrnorm=Wr./repmat(q,sw(1)*sw(2),1);
Wnorm=reshape(Wrnorm,sw(1), sw(2), sw(3));
end
function xxvc = lineargrad(sizevec, cx, dir)
switch dir
    case 'xx'
%         xxp=double(xx(sizevec, 'true')); %linear function - pixels
        xxp=double(xx(sizevec, 'corner')); %linear function - pixels
    case 'yy'
%         xxp=double(yy(sizevec, 'true')); %linear function - pixels
        xxp=double(yy(sizevec, 'corner')); %linear function - pixels
    otherwise
        error('Wrong dir')
end

xxv=reshape(xxp,sizevec(1)*sizevec(2),sizevec(3)); %linear function - vector
xxvc=xxv-repmat(cx,sizevec(1)*sizevec(2),1);
% xxp=double(xx([peval.nx, peval.ny, peval.ncomp], 'true')); %linear function - pixels
%yyp=double(yy([peval.nx, peval.ny, peval.ncomp], 'true'));
% xxv=reshape(xxp,peval.nx*peval.ny,peval.ncomp); %linear function - vector
%yyv=reshape(yyp,peval.nx*peval.ny,peval.ncomp);
% xxvc=xxv-repmat(cx,peval.ncomp,1);
%yyvc=yyv-repmat(cy,peval.ncomp,1);
end


function [out] = prep_grandAverage(dat)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% prep_grandAverage
%
% Synopsis:
%   [out] = prep_grandAverage(dat,<var>)
%
% Example :
%   [out] = prep_grandAverage({dat1,dat2,...,datN});
%
% Arguments:
%     dat - Segmented data, structure or data itself, in a cell type
%
% Returns:
%     out - Data structure averaged across subjects
%
% Description:
%    This function averages the data across subjects. It is recommended that
%    input data be separated by each class in advance.
%     continuous data should be [time * channels]
%     epoched data should be [time * channels * trials]
%
% See also 'https://github.com/PatternRecognition/OpenBMI'
%
% Min-ho Lee, 01-2018
% mh_lee@korea.ac.kr
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
s = length(dat);
x = cell(1,s);
if isstruct(dat{1})
    if ~prod(cellfun(@(x) isfield(x,'x'),dat))
        warning('OpenBMI: Data structure must have a field named ''x''');return
    end
    EachDataSize=cellfun(@(y) size(y.x), dat,'UniformOutput',false);
    if ~isequal(EachDataSize{:})
        warning('OpenBMI: Data size must be same (Epoched or continuous)');return
    end
% chan, class °°ÀºÁö È®ÀÎ ÇÊ¿ä.
    for i=1:s
        x{i} = dat{i}.x;
    end
    nd = ndims(dat{1}.x);
elseif isnumeric(dat{1}) && (ismatrix(dat{1}) || ndims(dat{1})==3)
    EachDataSize=cellfun(@size, dat,'UniformOutput',false);
    if ~isequal(EachDataSize{:})
        warning('OpenBMI: Data size must be same (Epoched or continuous)');return
    end
    x = dat;
    nd = ndims(dat{1});
else
    warning('OpenBMI: Check for format or dimension of the data');return
end

switch nd
    case 2
        Dat = cat(3,x{:});
        M = mean(Dat,3);
    case 3
        Dat = cat(4,x{:});
        M = mean(Dat,4);
end

if isstruct(dat{1})
    out = rmfield(dat{1},'x');
    out.x = M;
elseif isnumeric(dat{1})
    out = M;
end


function [ alphas, betas, scaling, finalLikelihood] = CCRF_training_gradient_descent( nIterations, nExamples, learningRate, threshold, x, y, yUnnormed, masks, alphas, betas, lambda_a, lambda_b, similarityFNs, useIndicators, verbose)
%GRADIENTDESCENTCCRF Performs CCRF gradient descen given the initial state
%and gradient descent parameters
%   Detailed explanation goes here

    if(verbose)
        logLikelihood = zeros(round(nIterations/10)+1, 1);
        alphaTrack = zeros(nIterations, numel(alphas));
        betaTrack = zeros(nIterations, numel(betas));
    end

    logAlphas = log(alphas);
    logBetas = log(betas);

    K = numel(similarityFNs);

    %calculate similarity measures for each of the sequences
    Similarities = cell(nExamples, 1);
    PrecalcQ2s = cell(nExamples,1);
    PrecalcQ2sFlat = cell(nExamples,1);

    PrecalcYqDs = zeros(nExamples, K);

    for q = 1 : nExamples

        yq = y{q};
        xq = x{q};
        mask = masks{q};

        n = size(yq, 1);
        Similarities{q} = zeros([n, n, K]);
%         PrecalcQ2s{q} = zeros([n, n, K]);
        PrecalcQ2s{q} = cell(K,1);
%         PrecalcQ2sFlat{q} = cell(K,1);
        PrecalcQ2sFlat{q} = zeros((n*(n+1))/2,K);
        % go over all of the similarity metrics and construct the
        % similarity matrices
        for k=1:K
            Similarities{q}(:,:,k) = similarityFNs{k}(xq, mask);
            S = Similarities{q}(:,:,k);
            D =  diag(sum(S));
            B = D - S;
%             PrecalcQ2s{q}(:,:,k) = B;
            PrecalcQ2s{q}{k} = B;
%             PrecalcQ2sFlat{q}{k} = PrecalcQ2s{q}{k}(logical(tril(ones(size(S)))));
            PrecalcQ2sFlat{q}(:,k) = B(logical(tril(ones(size(S)))));
            PrecalcYqDs(q,k) = -yq'*B*yq;
        end
    end

    %stochastic gradient descent
    for iter = 1 : nIterations
        prevAlphas = alphas;
        prevBetas = betas;

        for q = 1 : nExamples

            yq = y{q};
            xq = x{q};
            mask = masks{q};

            PrecalcQ2 = PrecalcQ2s{q};
            PrecalcQ2Flat = PrecalcQ2sFlat{q};
            [ logGradientsAlphas, logGradientsBetas] = gradientCCRF(alphas, betas, lambda_a, lambda_b, PrecalcQ2, xq, yq, mask, PrecalcYqDs(q, :), useIndicators, PrecalcQ2Flat);

%             [logGradientAlphasAnalytical, logGradientBetasAnalytical] = gradientAnalytical(PrecalcQ2, alphas, betas, lambda, xq, yq, mask);
%
%             diffInGradientsAlpha = mean(abs(logGradientsAlphas - logGradientAlphasAnalytical));
%             diffInGradientsBeta = mean(abs(logGradientsBetas - logGradientBetasAnalytical));

            %update log alpha
            logAlphas = logAlphas + learningRate * logGradientsAlphas;
            alphas = exp(logAlphas);

            %update log beta
            logBetas = logBetas + learningRate * logGradientsBetas;
            betas = exp(logBetas);

            if(verbose)
                %record alpha and beta values for each iteration for debug purposes
                alphaTrack(iter,:) = alphas(:);
                betaTrack(iter,:) = betas;
            end
        end

        %check for convergence
        if (norm([prevAlphas;prevBetas] - [alphas;betas])/norm([prevAlphas;prevBetas]) < threshold || norm([logGradientsAlphas;logGradientsBetas]) < threshold)
            break;
        end

        if(verbose)
            if(mod(iter, 10)==0)
                logLikelihood(iter/10 + 1) = LogLikelihoodCCRF(y, x, masks, alphas, betas, lambda_a, lambda_b, PrecalcQ2sFlat, useIndicators);
                fprintf('Iteration %d; logL %f\n', iter, logLikelihood(iter/10 + 1));
            end

        end
    end

    % establish the scaling
    scaling = getScaling(alphas, betas, x, yUnnormed, masks, PrecalcQ2s, useIndicators);

    if(verbose)
        figure
        subplot(1,3,1)
        plot(betaTrack(1:iter,:));
        title('beta');
        subplot(1,3,2)
        plot(alphaTrack(1:iter,:))
        title('alpha');
        subplot(1,3,3)
        plot(logLikelihood(1:round(iter/10),:))
        title('log likelihood');
        finalLikelihood = LogLikelihoodCCRF(y, x, masks, alphas, betas, lambda_a, lambda_b, PrecalcQ2sFlat, useIndicators);
        fprintf('Final log likelihood at iteration %d; logL %f, learning rate %f\n', iter, finalLikelihood, learningRate);
    else
        finalLikelihood = LogLikelihoodCCRF(y, x, masks, alphas, betas, lambda_a, lambda_b, PrecalcQ2sFlat, useIndicators);
        fprintf('Final log likelihood at iteration %d; logL %f, learning rate %f\n', iter, finalLikelihood, learningRate);
    end

end


function S=generateSAbsolute( anim )
% Generate S tranformed by R and t
%
% USAGE
%  anim = anim.generateSAbsolute()
%
% INPUTS
%  anim     - Animation object (help Animation for details)
%
% OUTPUTS
%  S        - anim.S after R, t have been applied (or homographies)
%
% EXAMPLE
%
% See also GENERATETOYANIMATION
%
% Vincent's Structure From Motion Toolbox      Version 3.0
% Copyright (C) 2008-2011 Vincent Rabaud.  [vrabaud-at-cs.ucsd.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the GPL [see external/gpl.txt]

if isempty(anim.S)
  warning('S is not defined nor computable'); S=[]; return;
end
if (isempty(anim.R) || isempty(anim.t)) && (isempty(anim.P))
  warning('Need to define R,t or P'); S=[]; return;
end

if size(anim.P,2)==3
  % homography case
  if size(anim.S,3)==1
    S = multiTimes( anim.P, anim.S, 1 );
  else
    S = multiTimes( anim.P, anim.S, 2 );
  end
else
  % compute the projected points for normal camera and 3D points
  if isempty(anim.R)
    if size(anim.S,3)==1
      S = bsxfun( @plus, multiTimes( anim.P(:,1:3,:), anim.S, 1 ), ...
        anim.P(:,4,:) );
    else
      S = bsxfun( @plus, multiTimes( anim.P(:,1:3,:), anim.S, 2 ), ...
        anim.P(:,4,:) );
    end
  else
    if size(anim.S,3)==1
      S = bsxfun( @plus, multiTimes( anim.R, anim.S, 1 ), ...
        reshape(anim.t, 3, 1, anim.nFrame ) );
    else
      S = bsxfun( @plus, multiTimes( anim.R, anim.S, 2 ), ...
        reshape(anim.t, 3, 1, anim.nFrame ) );
    end
  end
end


function [ra, dec] = apstar (tjd, n, rai, deci, pmra, pmdec, parlax, radvel)

% apparent place of a star

%  tjd    = tt julian date for apparent place (in)

%  n      = body identification number for the earth (in) (no longer used)

%  rai    = icrs right ascension in hours (in)

%  deci   = icrs declination in degrees (in)

%  pmra   = icrs proper motion in ra in milliarcseconds/year (in)

%  pmdec  = icrs proper motion in dec in milliarcseconds/year (in)

%  parlax = parallax in milliarcseconds (in)

%  radvel = radial velocity in kilometers/second (in)

%  ra     = apparent right ascension in hours (out)

%  dec    = apparent declination in degrees (out)

% note: coordinate system for output ra and dec is equator and equinox of date

% ported from NOVAS 3.1

%%%%%%%%%%%%%%%%%%%%%%%

locatn = 0;

icoord = 1;

ttjd = tjd;

object = 'star';

star(1) = rai;

star(2) = deci;

star(3) = pmra;

star(4) = pmdec;

star(5) = parlax;

star(6) = radvel;

observ = zeros(6, 1);

skypos = place (ttjd, object, locatn, icoord, star, observ);

ra = skypos(4);

dec = skypos(5);


classdef SuperpixelLSC < handle
    %SUPERPIXELLSC  Class implementing the LSC (Linear Spectral Clustering) superpixels algorithm
    %
    % As described in [LiCVPR2015LSC].
    %
    % LSC (Linear Spectral Clustering) produces compact and uniform
    % superpixels with low computational costs. Basically, a normalized cuts
    % formulation of the superpixel segmentation is adopted based on a
    % similarity metric that measures the color similarity and space proximity
    % between image pixels. LSC is of linear computational complexity and high
    % memory efficiency and is able to preserve global properties of images.
    %
    % ## References
    % [LiCVPR2015LSC]:
    % > Zhengqin Li and Jiansheng Chen. "Superpixel Segmentation using Linear
    % > Spectral Clustering". IEEE Conference on Computer Vision and Pattern
    % > Recognition (CVPR), June 2015.
    %
    % See also: cv.SuperpixelLSC.SuperpixelLSC, cv.SuperpixelSLIC,
    %  cv.SuperpixelSEEDS, superpixels
    %

    properties (SetAccess = private)
        % Object ID
        id
    end

    methods
        function this = SuperpixelLSC(img, varargin)
            %SUPERPIXELLSC  Class implementing the LSC (Linear Spectral Clustering) superpixels
            %
            %     obj = cv.SuperpixelLSC(img)
            %     obj = cv.SuperpixelLSC(img, 'OptionName',optionValue, ...)
            %
            % ## Input
            % * __img__ Image to segment.
            %
            % ## Options
            % * __RegionSize__ Chooses an average superpixel size measured in
            %   pixels. default 10
            % * __Ratio__ Chooses the enforcement of superpixel compactness
            %   factor of superpixel. default 0.075
            %
            % The function initializes a SuperpixelLSC object for the input
            % image. It sets the parameters of superpixel algorithm, which
            % are: `RegionSize` and `Ratio`. It preallocate some buffers for
            % future computing iterations over the given image. An example of
            % LSC is ilustrated in the following picture.
            % For enanched results it is recommended for color images to
            % preprocess image with little gaussian blur with a small 3x3
            % kernel and additional conversion into CieLAB color space.
            %
            % ![image](https://docs.opencv.org/3.3.1/superpixels_lsc.png)
            %
            % See also: cv.SuperpixelLSC.iterate
            %
            this.id = SuperpixelLSC_(0, 'new', img, varargin{:});
        end

        function delete(this)
            %DELETE  Destructor
            %
            %     obj.delete()
            %
            % See also: cv.SuperpixelLSC
            %
            if isempty(this.id), return; end
            SuperpixelLSC_(this.id, 'delete');
        end
    end

    %% Algorithm
    methods
        function clear(this)
            %CLEAR  Clears the algorithm state
            %
            %     obj.clear()
            %
            % See also: cv.SuperpixelLSC.empty, cv.SuperpixelLSC.load
            %
            SuperpixelLSC_(this.id, 'clear');
        end

        function b = empty(this)
            %EMPTY  Checks if detector object is empty
            %
            %     b = obj.empty()
            %
            % ## Output
            % * __b__ Returns true if the detector object is empty (e.g in the
            %   very beginning or after unsuccessful read).
            %
            % See also: cv.SuperpixelLSC.clear, cv.SuperpixelLSC.load
            %
            b = SuperpixelLSC_(this.id, 'empty');
        end

        function save(this, filename)
            %SAVE  Saves the algorithm parameters to a file
            %
            %     obj.save(filename)
            %
            % ## Input
            % * __filename__ Name of the file to save to.
            %
            % This method stores the algorithm parameters in the specified
            % XML or YAML file.
            %
            % See also: cv.SuperpixelLSC.load
            %
            SuperpixelLSC_(this.id, 'save', filename);
        end

        function load(this, fname_or_str, varargin)
            %LOAD  Loads algorithm from a file or a string
            %
            %     obj.load(fname)
            %     obj.load(str, 'FromString',true)
            %     obj.load(..., 'OptionName',optionValue, ...)
            %
            % ## Input
            % * __fname__ Name of the file to read.
            % * __str__ String containing the serialized model you want to
            %   load.
            %
            % ## Options
            % * __ObjName__ The optional name of the node to read (if empty,
            %   the first top-level node will be used). default empty
            % * __FromString__ Logical flag to indicate whether the input is a
            %   filename or a string containing the serialized model.
            %   default false
            %
            % This method reads algorithm parameters from the specified XML or
            % YAML file (either from disk or serialized string). The previous
            % algorithm state is discarded.
            %
            % See also: cv.SuperpixelLSC.save
            %
            SuperpixelLSC_(this.id, 'load', fname_or_str, varargin{:});
        end

        function name = getDefaultName(this)
            %GETDEFAULTNAME  Returns the algorithm string identifier
            %
            %     name = obj.getDefaultName()
            %
            % ## Output
            % * __name__ This string is used as top level XML/YML node tag
            %   when the object is saved to a file or string.
            %
            % See also: cv.SuperpixelLSC.save, cv.SuperpixelLSC.load
            %
            name = SuperpixelLSC_(this.id, 'getDefaultName');
        end
    end

    %% SuperpixelLSC
    methods
        function num = getNumberOfSuperpixels(this)
            %GETNUMBEROFSUPERPIXELS  Calculates the actual amount of superpixels on a given segmentation computed and stored in object
            %
            %     num = obj.getNumberOfSuperpixels()
            %
            % ## Output
            % * __num__ actual amount of superpixels.
            %
            % See also: cv.SuperpixelLSC.iterate
            %
            num = SuperpixelLSC_(this.id, 'getNumberOfSuperpixels');
        end

        function iterate(this, varargin)
            %ITERATE  Calculates the superpixel segmentation on a given image with the initialized parameters in the object
            %
            %     obj.iterate()
            %     obj.iterate('OptionName',optionValue, ...)
            %
            % ## Options
            % * __NumIterations__ Number of iterations. Higher number improves
            %   the result. default 10
            %
            % The function computes the superpixels segmentation of an image
            % with the parameters initialized with the constructor. The
            % algorithms starts from a grid of superpixels and then refines
            % the boundaries by proposing updates of edges boundaries.
            %
            % This function can be called again without the need of
            % initializing the algorithm with the constructor This save the
            % computational cost of allocating memory for all the structures
            % of the algorithm.
            %
            % See also: cv.SuperpixelLSC.getLabels
            %
            SuperpixelLSC_(this.id, 'iterate', varargin{:});
        end

        function labels = getLabels(this)
            %GETLABELS  Returns the segmentation labeling of the image
            %
            %     labels = obj.getLabels()
            %
            % ## Output
            % * __labels__ Return a `int32` integer array containing the
            %   labels of the superpixel segmentation. The labels are in the
            %   range `[0, obj.getNumberOfSuperpixels()]`.
            %
            % The function returns an image with the labels of the superpixel
            % segmentation. The labels are in the range
            % `[0, obj.getNumberOfSuperpixels()]`.
            %
            % Each label represents a superpixel, and each pixel is assigned
            % to one superpixel label.
            %
            % See also: cv.SuperpixelLSC.iterate
            %
            labels = SuperpixelLSC_(this.id, 'getLabels');
        end

        function img = getLabelContourMask(this, varargin)
            %GETLABELCONTOURMASK  Returns the mask of the superpixel segmentation stored in object
            %
            %     img = obj.getLabelContourMask()
            %     img = obj.getLabelContourMask('OptionName',optionValue, ...)
            %
            % ## Output
            % * __img__ Return `logical` image mask where 1 indicates that the
            %   pixel is a superpixel border, and 0 otherwise.
            %
            % ## Options
            % * __ThickLine__ If false, the border is only one pixel wide,
            %   otherwise all pixels at the border are masked. default true
            %
            % The function return the boundaries of the superpixel
            % segmentation.
            %
            % See also: cv.SuperpixelLSC.iterate, boundarymask
            %
            img = SuperpixelLSC_(this.id, 'getLabelContourMask', varargin{:});
            img = (img == 255);  % fg:uint8(255), bg:uint8(0)
        end

        function enforceLabelConnectivity(this, varargin)
            %ENFORCELABELCONNECTIVITY  Enforce label connectivity
            %
            %     obj.enforceLabelConnectivity()
            %     obj.enforceLabelConnectivity('OptionName',optionValue, ...)
            %
            % ## Options
            % * __MinElementSize__ The minimum element size in percents that
            %   should be absorbed into a bigger superpixel. Given resulted
            %   average superpixel size valid value should be in 0-100 range,
            %   25 means that less then a quarter sized superpixel should be
            %   absorbed, this is default. default 20
            %
            % The function merge component that is too small, assigning the
            % previously found adjacent label to this component. Calling this
            % function may change the final number of superpixels.
            %
            % See also: cv.SuperpixelLSC.iterate
            %
            SuperpixelLSC_(this.id, 'enforceLabelConnectivity', varargin{:});
        end
    end

end


function [tSeries, tSerr] = meanTSeries(vw, scanNum, roi, getRawData)
% Computes the mean tSeries, averaged over ROIcoords, for scanNum.
%
%   tSeries = meanTSeries(vw, scanNum, [roi], [getRawData])
%
% scanNum: scan number
% roi:     roi specification (ROI coords, name of loaded ROI, or ROI
%           struct). It can also be a cell array, in which case the
%           returned tSeries will also be a cell array, one entry for each
%           ROI.
% getRawData: if true, then do not detrend and do not convert to % signal
%
% djh, 7/98
% djh, 2/2001
% - updated to mrLoadRet-3.0
% - updated to work for gray and flat views
% bw/ab 6/2003
% - wrote getSlicesROI, ROIcoords2cellArray and inserted here so
%   we could use those routines in other places, too.
% Ress, 4/05 One fix and a new feature:
% Fix: Added code to properly ignore bad-flagged (NaN) values when taking
%       the mean. Feature: Now returns spatial SEM as an optional second
%       output argument; note that this estimate needs to be scaled up by a
%       voxel-size dependent spatial correlation factor
if notDefined('roi'),        roi         = vw.selectedROI; end
if notDefined('getRawData'), getRawData  = false;            end

% make sure the ROI is properly specified
roi = tc_roiStruct(vw, roi);

% if the ROI is empty, don't bother with the rest of this function
if length(roi) == 1 && isempty(roi.coords)
    tSeries = [];
    tSerr = [];
    return
end

% get the set of ROI coords as a cell array
for n = 1:length(roi)
    ROIcoords{n} = roi(n).coords;
end

% Find the slice indices for this collection of ROIs
sliceInds = getSlicesROI(vw, ROIcoords);

nROIs = length(ROIcoords);

tSeries = cell(1,nROIs);
tSerr   = cell(1, nROIs);

nFrames               = viewGet(vw, 'numFrames', scanNum);
detrend               = detrendFlag(vw,scanNum);
inhomoCorrection      = inhomoCorrectionFlag(vw, scanNum);
temporalNormalization = temporalNormalizationFlag(vw, scanNum);
smoothFrames          = detrendFrames(vw,scanNum);

if getRawData
    detrend = false;
    inhomoCorrection      = false;
    temporalNormalization = false;
    %smoothFrames = 0;
end

% Take first pass through ROIs to see which slices to load
switch vw.viewType
    case {'Inplane' 'Flat'}
        sliceInds = [];
        for r=1:nROIs
            if isempty(ROIcoords{r})
                disp('MeanTSeries: ignoring empty ROI in this slice')
            else
                sliceInds = [sliceInds, ROIcoords{r}(3,:)];
            end
        end
        sliceInds = unique(sliceInds);
    case {'Gray' 'Volume'}
        sliceInds = 1;
    otherwise
        myErrorDlg('meanTSeries: Only for Inplane, Gray, or Flat views.');
end

% Load tSeries & divide by mean, but don't detrend yet.
% Otherwise, detrending the entire tSeries is much slower. DJH
detrendNow    = false;
noMeanRemoval = false;
if getRawData,	noMeanRemoval = true; end % just get the raw data!

vw = percentTSeries(vw,scanNum,sliceInds,detrendNow,inhomoCorrection,temporalNormalization,noMeanRemoval);

for r=1:nROIs
    % Extract time-series
    subtSeries = getTSeriesROI(vw,ROIcoords{r});
    if ~isempty(subtSeries)

        % Detrend now (faster to do it now after extracting subtSeries for a small subset of the voxels)
        subtSeries = detrendTSeries(subtSeries, detrend, smoothFrames);
        % Add 'em up
        if isempty(tSeries{r})
            numPts{r} = sum(isfinite(subtSeries), 2);
            subtSeries(~isfinite(subtSeries)) = 0;
            tSerr{r} = sum(subtSeries.^2, 2);
            tSeries{r} = sum(subtSeries, 2);
        else
            numPts{r} = numPts{r} + sum(isfinite(subtSeries), 2);
            subtSeries(~isfinite(subtSeries)) = 0;
            tSerr{r} = tSerr{r} + sum(subtSeries.^2, 2);
            tSeries{r} = tSeries{r} + sum(subtSeries,2);
        end
    end
end

% Final pass through ROIs to turn sum into mean
for r=1:nROIs
    if isempty(numPts{r})
        tSeries{r} = zeros(nFrames,1);
        tSerr{r} = zeros(nFrames, 1);
    else
        tSeries{r} = tSeries{r} ./ numPts{r};
        tSerr{r} = sqrt((tSerr{r} ./ numPts{r}.^2) - tSeries{r}.^2./numPts{r});
    end
end

if (nROIs==1)
    tSeries = tSeries{1};
    tSerr = tSerr{1};
end

% Clean up (because didn't detrend the whole tSeries properly)
vw.tSeries=[];
vw.tSeriesScan=NaN;
vw.tSeriesSlice=NaN;

return;


function T = myones(sizes)
% MYONES Like the built-in ones, except myones(k) produces a k*1 vector instead of a k*k matrix,
% T = myones(sizes)

if length(sizes)==0
  T = 1;
elseif length(sizes)==1
  T = ones(sizes, 1);
else
  T = ones(sizes(:)');
end


classdef TestEstimateGlobalMotionRansac
    %TestEstimateGlobalMotionRansac

    methods (Static)
        function test_1
            im1 = cv.imread(fullfile(mexopencv.root(),'test','RubberWhale1.png'), ...
                'Grayscale',true, 'ReduceScale',2);
            im2 = cv.imread(fullfile(mexopencv.root(),'test','RubberWhale2.png'), ...
                'Grayscale',true, 'ReduceScale',2);
            pt1 = cv.goodFeaturesToTrack(im1, 'MaxCorners',200);
            pt2 = cv.goodFeaturesToTrack(im2, 'MaxCorners',200);
            models = {'Translation', 'TranslationAndScale', 'Rotation', ...
                'Rigid', 'Similarity', 'Affine'};
            for i=1:numel(models)
                [M,rmse,ninliers] = cv.estimateGlobalMotionRansac(pt1, pt2, ...
                    'MotionModel',models{i}, 'RansacParams',models{i});
                validateattributes(M, {'numeric'}, {'2d', 'size',[3 3]});
                validateattributes(rmse, {'numeric'}, {'scalar', 'real'});
                validateattributes(ninliers, {'numeric'}, {'scalar', 'integer'});
            end
        end

        function test_error_argnum
            try
                cv.estimateGlobalMotionRansac();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end


function pot = dpot(domain, sizes, T)
% DPOT Make a discrete (sparse) potential.
% pot = dpot(domain, sizes, T, spar)
%
% sizes(i) is the size of the i'th domain element.
% T defaults to all 1s.

%assert(length(sizes) == length(domain));

pot.domain = domain(:)'; % so we can see it when we display
if nargin < 3
  pot.T = myones(sizes);
  %pot.T = ones(1,prod(sizes)); % 1D vector
else
   if isempty(T)
      pot.T = [];
   else
      if issparse(T)
         pot.T = T;
      else
         pot.T = myreshape(T, sizes);
      end
   end
end
pot.sizes = sizes(:)';
pot = class(pot, 'dpot');


function [grade,X,SR,improve,AppSet] = LocalSearch2(Problem,X,SR,improve,AppSet)
% Local Search 2 of MTS

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

    if ~improve
        SR = SR / 2;
        if all(SR<1e-8)
            SR = (Problem.upper-Problem.lower).*(rand(1,length(SR))/10+0.4);
        end
    end
    improve = false;
    grade   = 0;
    for l = 1 : length(SR)
        chosen = rand(1,length(SR)) < 1/4;
        old_X  = X;
        dec    = X.dec;
        dec(chosen) = dec(chosen) + SR(chosen).*(rand(1,sum(chosen))*2-1);
        X      = Problem.Evaluation(dec);
        [grade,improve,AppSet] = Grading(X,old_X,grade,improve,AppSet,Problem.N);
        if all(old_X.obj<=X.obj)
            dec = old_X.dec;
            dec(chosen) = dec(chosen) - 0.5*SR(chosen).*(rand(1,sum(chosen))*2-1);
            X   = Problem.Evaluation(dec);
            [grade,improve,AppSet] = Grading(X,old_X,grade,improve,AppSet,Problem.N);
            if all(old_X.obj<=X.obj)
                X = old_X;
            end
        end
    end
end


function V = vmp_read_volume(info)
% function for readingV MP BrainVoyager ( .vmp ) volume file
%
% volume = vmp_read_volume(file-header)
%
% examples:
% 1: info = vmp_read_volumegipl_read_header()
%    V = gvmp_read_volume(info);
%    imshow(squeeze(V(:,:,round(end/2))),[]);
%
% 2: V = vmp_read_volume('test.vmp');

if(~isstruct(info)), info=vmp_read_header(info); end

fp = fopen(info.Filename, 'rb', 'ieee-le');
if (fp == -1)
    error('The file was not found or could not be oppened')
end
% check version type
if fread(fp, 1, 'int16') ~= 3
    fclose(fp);
    error('Only version 3 files are supported')
end

% check number of maps
if fread(fp, 1, 'int32') ~= 1
    fclose(fp);
    error('Only vmp file with one map are supported')
end

% check number of maps
stat_type = fread(fp, 1, 'int32');
if stat_type ~= 1 & stat_type ~= 4
    fclose(fp);
    error('Only F and t tests are supported')
end

% skip a few fields
fseek(fp, 17, 'cof');

df1 = fread(fp, 1, 'int32');
df2 = fread(fp, 1, 'int32');

% skip a few fields
fseek(fp, 21, 'cof');
while true
    if fread(fp, 1, 'int8') == 0
        break
    end
end
fseek(fp, 12, 'cof');

% find the dimensions
x_start = fread(fp, 1, 'int32');
x_stop  = fread(fp, 1, 'int32');
DimX    = (x_stop - x_start) / 3;

y_start = fread(fp, 1, 'int32');
y_stop  = fread(fp, 1, 'int32');
DimY    = (y_stop - y_start) / 3;

z_start = fread(fp, 1, 'int32');
z_stop  = fread(fp, 1, 'int32');
DimZ    = (z_stop - z_start) / 3;

fseek(fp, 4, 'cof');

% read the data
len = (3*DimX+1) * (3*DimY+1) * (3*DimZ+1);
V = fread(fp, len, 'float');

fclose(fp);


function joint = combine_marginals_into_joint(marginalsT, hnodes, ns)

jointT = dpot(hnodes, ns(hnodes));
for i=hnodes(:)'
  jointT = multiply_by_pot(jointT, marginalsT{i});
end
m = pot_to_marginal(jointT);
joint = m.T(:);


function [output] = mesh2edge(mesh)

% MESH2EDGE finds the edge lines from a triangulated mesh or the edge
% surfaces from a tetrahedral or hexahedral mesh. An edge is defined as an
% element that does not border any other element. This also implies that a
% closed triangulated surface has no edges.
%
% Use as
%   [edge] = mesh2edge(mesh)
%
% See also POLY2TRI

% Copyright (C) 2013-2020, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

if isfield(mesh, 'tri')
  % make a list of all edges
  edge1 = mesh.tri(:, [1 2]);
  edge2 = mesh.tri(:, [2 3]);
  edge3 = mesh.tri(:, [3 1]);
  edge = cat(1, edge1, edge2, edge3);

elseif isfield(mesh, 'tet')
  % make a list of all triangles that form the tetraheder
  tri1 = mesh.tet(:, [1 2 3]);
  tri2 = mesh.tet(:, [2 3 4]);
  tri3 = mesh.tet(:, [3 4 1]);
  tri4 = mesh.tet(:, [4 1 2]);
  edge = cat(1, tri1, tri2, tri3, tri4);

elseif isfield(mesh, 'hex')
  % make a list of all "squares" that form the cube/hexaheder
  % FIXME should be checked, this is impossible without a drawing
  square1 = mesh.hex(:, [1 2 3 4]);
  square2 = mesh.hex(:, [5 6 7 8]);
  square3 = mesh.hex(:, [1 2 6 5]);
  square4 = mesh.hex(:, [2 3 7 6]);
  square5 = mesh.hex(:, [3 4 8 7]);
  square6 = mesh.hex(:, [4 1 5 8]);
  edge = cat(1, square1, square2, square3, square4, square5, square6);

end % isfield(mesh)

% soort all polygons in the same direction
% keep the original as "edge" and the sorted one as "sedge"
sedge = sort(edge, 2);

% % find the edges that are not shared -> count the number of occurences
% n = size(sedge,1);
% occurences = ones(n,1);
% for i=1:n
%   for j=(i+1):n
%     if all(sedge(i,:)==sedge(j,:))
%       occurences(i) = occurences(i)+1;
%       occurences(j) = occurences(j)+1;
%     end
%   end
% end
%
% % make the selection in the original, not the sorted version of the edges
% % otherwise the orientation of the edges might get flipped
% edge = edge(occurences==1,:);

% find the edges that are not shared
indx = findsingleoccurringrows(sedge);
edge = edge(indx, :);

% replace pnt by pos
mesh = fixpos(mesh);

% the naming of the edges in the output depends on what they represent
output.pos = mesh.pos;
if isfield(mesh, 'tri')
  % these have two vertices in each edge element
  output.line = edge;
  fprintf('reducing triangles to %d lines\n', size(edge,1));
elseif isfield(mesh, 'tet')
  % these have three vertices in each edge element
  output.tri = edge;
  fprintf('reducing tetraheders to %d triangles\n', size(edge,1));
elseif isfield(mesh, 'hex')
  % these have four vertices in each edge element
  output.poly = edge;
  fprintf('reducing hexaheders to %d polygons\n', size(edge,1));
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1833#c12
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function indx = findsingleoccurringrows(X)
[X, indx] = sortrows(X);
sel  = any(diff([X(1,:)-1; X],1),2) & any(diff([X; X(end,:)+1],1),2);
indx = indx(sel);

function indx = finduniquerows(X)
[X, indx] = sortrows(X);
sel  = any(diff([X(1,:)-1; X],1),2);
indx = indx(sel);


function [ abd, ipvt, info ] = sgbfa ( abd, lda, n, ml, mu )

%*****************************************************************************80
%
%% SGBFA factors a real band matrix by elimination.
%
%  Discussion:
%
%    SGBFA is usually called by SGBCO, but it can be called
%    directly with a saving in time if RCOND is not needed.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 November 2006
%
%  Author:
%
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Dongarra, Moler, Bunch and Stewart,
%    LINPACK User's Guide,
%    SIAM, (Society for Industrial and Applied Mathematics),
%    3600 University City Science Center,
%    Philadelphia, PA, 19104-2688.
%    ISBN 0-89871-172-X
%
%  Parameters:
%
%    Input, real ABD(LDA,N), the matrix in band
%    storage.  The columns of the matrix are stored in the columns of ABD
%    and the diagonals of the matrix are stored in rows ML+1 through
%    2*ML+MU+1 of ABD.
%
%    Input, integer LDA, the leading dimension of the array ABD.
%    2*ML + MU + 1 <= LDA is required.
%
%    Input, integer N, the order of the matrix.
%
%    Input, integer ML, MU, the number of diagonals below and above the
%    main diagonal.  0 <= ML < N, 0 <= MU < N.
%
%    Output, real ABD(LDA,N), an upper triangular matrix in band storage
%    and the multipliers which were used to obtain it.  The factorization
%    can be written A = L*U where L is a product of permutation and unit lower
%    triangular matrices and U is upper triangular.
%
%    Output, integer IPVT(N), the pivot indices.
%
%    Output, integer INFO, error flag.
%    0, normal value.
%    K, if U(K,K) == 0.0D+00.  This is not an error condition for this
%      subroutine, but it does indicate that SGBSL will divide by zero if
%      called.  Use RCOND in SGBCO for a reliable indication of singularity.
%
  m = ml + mu + 1;
  info = 0;
%
%  Zero initial fill-in columns.
%
  j0 = mu + 2;
  j1 = min ( n, m ) - 1;

  for jz = j0 : j1
    i0 = m + 1 - jz;
    abd(i0:ml,jz) = 0.0;
  end

  jz = j1;
  ju = 0;
%
%  Gaussian elimination with partial pivoting.
%
  for k = 1 : n-1
%
%  Zero out the next fill-in column.
%
    jz = jz + 1;
    if ( jz <= n )
      abd(1:ml,jz) = 0.0;
    end
%
%  Find L = pivot index.
%
    lm = min ( ml, n-k );
    l = isamax ( lm+1, abd(m:m+lm,k), 1 ) + m - 1;
    ipvt(k) = l + k - m;
%
%  Zero pivot implies this column already triangularized.
%
    if ( abd(l,k) == 0.0 )

      info = k;
%
%  Interchange if necessary.
%
    else

      if ( l ~= m )
        t = abd(l,k);
        abd(l,k) = abd(m,k);
        abd(m,k) = t;
      end
%
%  Compute multipliers.
%
      abd(m+1:m+lm,k) = - abd(m+1:m+lm,k) / abd(m,k);
%
%  Row elimination with column indexing.
%
      ju = min ( max ( ju, mu+ipvt(k) ), n );
      mm = m;

      for j = k+1 : ju
        l = l - 1;
        mm = mm - 1;
        t = abd(l,j);
        if ( l ~= mm )
          abd(l,j) = abd(mm,j);
          abd(mm,j) = t;
        end
        abd(mm+1:mm+lm,j) = ...
          saxpy ( lm, t, abd(m+1:m+lm,k), 1, abd(mm+1:mm+lm,j), 1 );
      end

    end

  end

  ipvt(n) = n;

  if ( abd(m,n) == 0.0 )
    info = n;
  end

  return
end


% reshape() - reshape of memory mapped underlying array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008

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

function obj = reshape(obj,d1,d2,d3)

    % decode length
    % -------------
    if nargin > 3
        d1 = [ d1 d2 d3 ];
    elseif nargin > 2
        d1 = [ d1 d2 ];
    end;

    if prod(size(obj)) ~= prod(d1)
        error('Wrong dimensions for reshaping');
    end;

    if obj.transposed
        d1 = [d1(2:end) d1(1)];
    end;

    obj.dimensions = d1;


function tran06_values_test ( )

%*****************************************************************************80
%
%% TRAN06_VALUES_TEST demonstrates the use of TRAN06_VALUES.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 February 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TRAN06_VALUES_TEST:\n' );
  fprintf ( 1, '  TRAN06_VALUES stores values of\n' );
  fprintf ( 1, '  the transportation function of order 6.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      X               FX\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

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

    if ( n_data == 0 )
      break
    end

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

  end

  return
end


function NewGoal = GeneGoal(PopObj,NGoal)
% Generate new goals

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

    Gmax    = max(PopObj,[],1)*1.2;
    Gmin    = min(PopObj,[],1);
    NewGoal = unifrnd(repmat(Gmin,NGoal,1),repmat(Gmax,NGoal,1));
end


function symObj = symmetrise(obj)
% symmetrise embedding
%
% Syntax
%
%   symE = symmetrise(e)
%
% Input
%  e - @embedding
%
% Output
%  symE - @embedding invariant with respect to all symmetry elements
%

symObj = mean( rotate_outer(obj, obj.CS.properGroup.rot),1);
symObj = reshape(symObj, size(obj));

end


function data = getImageBatch(imagePaths, varargin)
% GETIMAGEBATCH  Load and jitter a batch of images

opts.useGpu = false ;
opts.prefetch = false ;
opts.numThreads = 1 ;

opts.imageSize = [227, 227] ;
opts.cropSize = 227 / 256 ;
opts.keepAspect = true ;
opts.subtractAverage = [] ;

opts.jitterFlip = false ;
opts.jitterLocation = false ;
opts.jitterAspect = 1 ;
opts.jitterScale = 1 ;
opts.jitterBrightness = 0 ;
opts.jitterContrast = 0 ;
opts.jitterSaturation = 0 ;

opts = vl_argparse(opts, varargin);

args{1} = {imagePaths, ...
           'NumThreads', opts.numThreads, ...
           'Pack', ...
           'Interpolation', 'bicubic', ...
           'Resize', opts.imageSize(1:2), ...
           'CropSize', opts.cropSize * opts.jitterScale, ...
           'CropAnisotropy', opts.jitterAspect, ...
           'Brightness', opts.jitterBrightness, ...
           'Contrast', opts.jitterContrast, ...
           'Saturation', opts.jitterSaturation} ;

if ~opts.keepAspect
  % Squashign effect
  args{end+1} = {'CropAnisotropy', 0} ;
end

if opts.jitterFlip
  args{end+1} = {'Flip'} ;
end

if opts.jitterLocation
  args{end+1} = {'CropLocation', 'random'} ;
else
  args{end+1} = {'CropLocation', 'center'} ;
end

if opts.useGpu
  args{end+1} = {'Gpu'} ;
end

if ~isempty(opts.subtractAverage)
  args{end+1} = {'SubtractAverage', opts.subtractAverage} ;
end

args = horzcat(args{:}) ;

if opts.prefetch
  vl_imreadjpeg(args{:}, 'prefetch') ;
  data = [] ;
else
  data = vl_imreadjpeg(args{:}) ;
  data = data{1} ;
end


function [v] = tapas_mh_mc3g_arc(ollh, olpp, nllh, nlpp, ...
    ratio, T)
%% Acceptance rejection criterion for metropolis hastings in the context of
% population mcmc generalized for hierarchical models.
%
% aponteeduardo@gmail.com
% copyright (C) 2016
%

v = nllh .* T + nlpp - (ollh .* T + olpp) + ratio;

nansv = isnan(v);
v(nansv) = -inf;

v = rand(size(v)) < exp(min(v, 0));

assert(all(-inf < nllh(v) + nlpp(v)), 'tapas:mh', ...
    '-inf value in the new samples');

end


function [cY,mY,ng] = motion_metrics(Y,bnd,batch_size,var_name)

% computes several metrics for the quantitative assessment of the registration

% INPUTS
% Y:            registered time series in a loaded or memory mapped array
% bnd:          number of pixels to be exluded to avoid NaN effects
%                   [x_beg,x_end,y_be,y_end,z_beg,z_end]
% batch_size:   size of batch to be read for memory mapped files
% var_name:     in case of memory mapped files use this variable

% OUTPUTS
% cY:           correlation coefficient of each frame with the mean
% mY:           mean image
% ng:           norm of gradient of mean image

if nargin == 1 || isempty(bnd); bnd = zeros(6,1); end
if nargin < 3|| isempty(batch_size); batch_size = 1000; end

memmap = isobject(Y);

if memmap
    if ~exist('var_name','var')
        try sizY = size(Y,'Y'); var_name = 'Y'; catch; sizY = size(Y,'M'); var_name = 'M'; end
    end
else
    sizY = size(Y);
end

dimsY = length(sizY);
nd = dimsY - 1;
d = prod(sizY(1:end-1));
T = sizY(end);

if isscalar(bnd); bnd = ones(2*(dimsY-1),1)*bnd; end
if dimsY == 3; sizY(3) = 1; bnd(5:6) = 0; end

if memmap
    cY = zeros(T,1);
    mY = zeros(sizY(1:end-1));

    for t = 1:batch_size:T
        y_temp = single(load_data(Y,t,batch_size));
        sy = size(y_temp,ndims(y_temp));
        delta = nanmean(y_temp,ndims(y_temp));
        mY = mY*(t-1)/(t+sy-1) + sy*delta/(t+sy-1);
    end

    m_temp = mY(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4),bnd(5)+1:sizY(3)-bnd(6));
    mYr = m_temp(:);
    for t = 1:batch_size:T
        y_temp = single(load_data(Y,t,batch_size));
        sy = size(y_temp,ndims(y_temp));
        if nd == 2; y_temp = y_temp(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4),:); end
        if nd == 3; y_temp = y_temp(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4),bnd(5)+1:sizY(3)-bnd(6),:); end
        Yr = reshape(y_temp,[],sy);
        if any(any(isnan(Yr))) || any(isnan(mYr));
            cY(t:min(t+batch_size-1,T)) = corr(Yr,mYr,'rows','p');
        else
            cY(t:min(t+batch_size-1,T)) = corr(Yr,mYr);
        end
    end
else
    Y = single(Y);
    nd = ndims(Y)-1;
    mY = nanmean(Y,nd+1);
    if nd == 2
        Yr = Y(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4),:);
        mYr = mY(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4));
    else
        Yr = Y(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4),bnd(5)+1:sizY(3)-bnd(6),:);
        mYr = mY(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4),bnd(5)+1:sizY(3)-bnd(6));
    end
    Yr = reshape(Yr,[],T);
    mYr = mYr(:);
    if any(any(isnan(Yr))) || any(isnan(mYr));
        cY = corr(Yr,mYr,'rows','p');
    else
        cY = corr(Yr,mYr);
    end
end

if ismatrix(mY);
    [gx,gy] = gradient(mY);
    ng = norm(sqrt(gx.^2+gy.^2),'fro');
elseif ndims(Y)-1 == 3;
    [gx,gy,gz] = gradient(mY);
    ng = sqrt(sum(gx(:).^2+gy(:).^2+gz(:).^2));
end

    function y_temp = load_data(X,t,batch_size)
        lY = min(T-t+1,batch_size);
        if ~memmap
            y_temp = reshape(X(d*(t-1) + (1:d)),[sizY(1:end-1),lY]);
        else
            if strcmp(var_name,'Y')
                if dimsY == 3
                    y_temp = double(X.Y(:,:,t:t+lY-1));
                else
                    y_temp = double(X.Y(:,:,:,t+lY-1));
                end
            elseif strcmp(var_name,'M')
                if dimsY == 3
                    y_temp = double(X.M(:,:,t+lY-1));
                else
                    y_temp = double(X.M(:,:,:,t+lY-1));
                end
            else
                error('unknown variable name')
            end
        end
    end
end


function piecewise_linear_product_integral_test ( )

%*****************************************************************************80
%
%% PIECEWISE_LINEAR_PRODUCT_INTEGRAL_TEST tests the PIECEWISE_LINEAR_PRODUCT_INTEGRAL library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 April 2009
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'PIECEWISE_LINEAR_PRODUCT_INTEGRAL_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the PIECEWISE_LINEAR_PRODUCT_INTEGRAL library.\n' );

  piecewise_linear_product_integral_test01 ( );
  piecewise_linear_product_integral_test02 ( );
  piecewise_linear_product_integral_test03 ( );
  piecewise_linear_product_integral_test04 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'PIECEWISE_LINEAR_PRODUCT_INTEGRAL_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function cmap = revjetCmap(numGrays,numColors)
%
% cmap = revjetCmap(numGrays,numColors)
%
% Makes colormap array with:
%   gray scale - 1:numGrays
%   jet colors - numGrays+1:numGrays+numColors
%
% djh 1/98

if ~exist('numGrays','var')
    numGrays = 128;
end
if ~exist('numColors','var')
    numColors = 128;
end

cmap = zeros(numGrays+numColors,3);
cmap(1:numGrays+numColors,:) = [gray(numGrays);1-jet(numColors)];