function word_num = s_word_count ( s )

%*****************************************************************************80
%
%% S_WORD_COUNT counts the number of "words" in a string.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 January 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string S, the string to be examined.
%
%    Output, integer WORD_NUM, the number of "words" in the string.
%    Words are presumed to be separated by one or more blanks.
%
  word_num = 0;
  s_length = length ( s );

  if ( s_length <= 0 )
    return;
  end

  blank = 1;

  for i = 1 : s_length

    if ( s(i) == ' ' )
      blank = 1;
    elseif ( blank == 1 )
      word_num = word_num + 1;
      blank = 0;
    end

  end

  return
end


function cmap = ft_colormap(varargin)

% FT_COLORMAP is a wrapper function with the same usage as the normal COLORMAP
% function, but it also knows about the colormaps from BREWERMAP and some colormaps
% from MATPLOTLIB. The recommended colormaps include 'parula', 'cividis', 'balance',
% and '*RdBu'.
%
% Use as
%   ft_colormap(name)
%   ft_colormap(name, n)
%   ft_colormap(handle, name)
%   ft_colormap(handle, name, n)
%
% The name is a string that specifies the colormap (see below). The optional handle
% can be used to specify the current figure (which is the default, see GCF) or the
% current axes (see GCA). The optional parameter n determines the number of steps or
% unique colors in the map (by default 64).
%
% The colormaps from MATLAB include 'parula', 'jet', 'hsv', 'hot', 'cool', 'spring',
% 'summer', 'autumn', 'winter', 'gray', 'bone', 'copper', 'pink', 'lines',
% 'colorcube', 'prism', and 'flag'.
%
% The colormaps from MATPLOTLIB include 'cividis', 'inferno', 'magma', 'plasma',
% 'tab10', 'tab20', 'tab20b', 'tab20c', 'twilight', and 'viridis'.
%
% The colormaps from BREWERMAP include 'BrBG', 'PRGn', 'PiYG', 'PuOr', 'RdBu',
% 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral', 'Accent', 'Dark2', 'Paired', 'Pastel1',
% 'Pastel2', 'Set1', 'Set2', 'Set3', 'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens',
% 'Greys', 'OrRd', 'Oranges', 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu', 'Reds',
% 'YlGn', 'YlGnBu', 'YlOrBr', and 'YlOrRd', plus their reverse when prefixed with '*'.
%
% The colormaps from CMOCEAN include 'thermal', 'haline', 'solar', 'ice', 'gray',
% 'oxy', 'deep', 'dense', 'algae', 'matter', 'turbid', 'speed', 'amp', 'tempo',
% 'rain', 'phase', 'topo', 'balance', 'delta', 'curl', 'diff', and 'tarn'.
%
% The colormaps from COLORCET include 'blueternary', 'coolwarm', 'cyclicgrey',
% 'depth', 'divbjy', 'fire', 'geographic', 'geographic2', 'gouldian', 'gray',
% 'greenternary', 'grey', 'heat', 'phase2', 'phase4', 'rainbow', 'rainbow2',
% 'rainbow3', 'rainbow4', 'redternary', 'reducedgrey', 'yellowheat', and all the ones
% with symbolic names.
%
% To reverse any of these these colormaps you can add a minus sign in front, like
% '-phase', '-balance' or '-RdBu'.
%
% Relevant publications:
% - Crameri et al. 2020. The misuse of colour in science communication. https://doi.org/10.1038/s41467-020-19160-7
% - Cooper et al. 2021. Over the rainbow: Guidelines for meaningful use of colour maps in neurophysiology. https://doi.org/10.1016/j.neuroimage.2021.118628
% - Kovesi 2015, Good colour maps: How to design them. https://doi.org/10.48550/arXiv.1509.03700
%
% See also COLORMAP, COLORMAPEDITOR, BREWERMAP, MATPLOTLIB, CMOCEAN, COLORCET

% Copyright (C) 2022, Jan-Mathijs Schoffelen, 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$

ft_hastoolbox('brewermap', 2);  % check and give a warning if it cannot be added
ft_hastoolbox('matplotlib', 2); % check and give a warning if it cannot be added
ft_hastoolbox('cmocean', 2);
ft_hastoolbox('colorcet', 2);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% interpret the input arguments

% please note that ishandle('parula') returns a logical array
% hence the all(ishandle(...)), which in that case returns false

if nargin==0
  % apply the default colormap
  handle = gcf;
  name   = 'default';
  n      = 64;

elseif nargin==1 && isnumeric(varargin{1})
  % the user specified an Nx3 array as colormap
  handle = gcf;
  name   = varargin{1}; % note that this is not a string, it is dealt with below
  n      = nan;

elseif nargin==1 && all(ishandle(varargin{1}))
  % apply the default colormap on the specified handle
  handle = varargin{1};
  name   = 'default';
  n      = 64;

elseif nargin==1 && ischar(varargin{1})
  % apply the specified colormap on the current figure
  handle = gcf;
  name   = varargin{1};
  n      = 64;

elseif nargin==2 && all(ishandle(varargin{1}))
  % apply the specified colormap on the specified handle
  handle = varargin{1};
  name   = varargin{2};
  n      = 64;

elseif nargin==2 && ischar(varargin{1})
  % apply the specified colormap with specified N on the current figure
  handle = gcf;
  name   = varargin{1};
  n      = varargin{2};

elseif nargin==3 && all(ishandle(varargin{1}))
  % apply the specified colormap with specified N on the specified handle
  handle = varargin{1};
  name   = varargin{2};
  n      = varargin{3};

else
  ft_error('incorrect input arguments');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% construct the colormap

% the ones from brewermap are not m-files on disk
brewerlist = repmat(brewermap('list'), [2 1]);
% also include the reverse ones
for k = 1:numel(brewerlist)/2
  brewerlist{k} = sprintf('*%s', brewerlist{k});
end

% the ones from cmocean are not m-files on disk
cmoceanlist = {
  'thermal'
  'haline'
  'solar'
  'ice'
  'gray'
  'oxy'
  'deep'
  'dense'
  'algae'
  'matter'
  'turbid'
  'speed'
  'amp'
  'tempo'
  'rain'
  'phase'
  'topo'
  'balance'
  'delta'
  'curl'
  'diff'
  'tarn'
  };
% also include the reverse ones
for k = 1:numel(cmoceanlist)
  cmoceanlist{end+1} = sprintf('-%s', cmoceanlist{k});
end

% the ones from colorcet are not m-files on disk
colorcetlist = {
  'blueternary'
  'coolwarm'
  'cyclicgrey'
  'depth'
  'divbjy'
  'fire'
  'geographic'
  'geographic2'
  'gouldian'
  'gray'
  'greenternary'
  'grey'
  'heat'
  'phase2'
  'phase4'
  'rainbow'
  'rainbow2'
  'rainbow3'
  'rainbow4'
  'redternary'
  'reducedgrey'
  'yellowheat'
  };
% also include the reverse ones
for k = 1:numel(colorcetlist)
  colorcetlist{end+1} = sprintf('-%s', colorcetlist{k});
end

if isnumeric(name)
  % the user specified an Nx3 array as colormap
  cmap = name;
elseif ismember(name, brewerlist)
  cmap = brewermap(n, name);
elseif startsWith(name, '-') && ismember(name(2:end), brewerlist)
  cmap = brewermap(n, strrep(name, '-', '*'));
elseif ismember(name, cmoceanlist)
  cmap = cmocean(name, n);
elseif ismember(name, colorcetlist)
  cmap = colorcet(name, 'n', n, 'reverse', false);
elseif startsWith(name, '-') && ismember(name(2:end), colorcetlist)
  cmap = colorcet(name(2:end), 'n', n, 'reverse', true);
elseif isequal(name, 'default')
  % requires separate handling, because there's no function called default,
  % the default is taken care of by colormap
  cmap = name;
else
  % this works both for the MATLAB and the MATPLOTLIB colormaps
  % which have the different colormaps available as an m-file
  if name(1)=='-'
    cmap = flipud(feval(name(2:end), n));
  else
    cmap = feval(name, n);
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% apply the colormap and/or return it

if nargout>0
  % apply it to the specified figure or axis and return it as a Nx3 array
  colormap(handle, cmap)
else
  % only apply it to the current figure
  colormap(handle, cmap)
  clear cmap
end


        % Lansarea utilitarului Profiler cu optiunea cea mai completa
profile on -detail operator -history
        % Secventa simpla de program de analizat
x=0:pi/1e6:2*pi;
y=funct1(x);
z=funct2(x);
        % Comandarea generarii unui raport si salvarea lui in fisierul raport
profile report raport
        % Comandarea generarii reprezentarii rezultatelor statistice
profile plot
        % Stergerea tuturor inregistrarilor
profile clear


  classdef viewPC < matlab.System & matlab.system.mixin.CustomIcon
    % Untitled Add summary here
    %
    % This template includes the minimum set of functions required
    % to define a System object with discrete state.

    % Public, tunable properties
    properties

    end

    properties(DiscreteState)
        xyz;
        p1;
        p2;
        p3;
    end

    % Pre-computed constants
    properties(Access = private)

    end

    methods(Access = protected)
        function stepImpl(obj,xyzpoint)
            % Perform one-time calculations, such as computing constants
            obj.p1 = xyzpoint(:,1);
            obj.p2 = xyzpoint(:,2);
            obj.p3 = xyzpoint(:,3);

            obj.xyz = [obj.p1,obj.p2,obj.p3];
            pcshow(obj.xyz)
        end

        function num = getNumInputsImpl(~)
            num = 1;
        end
        function num = getNumOutputsImpl(~)
            num = 0;
        end
        function resetImpl(obj)

        end
    end
  end


function varargout=cent2frq(varargin)
%
% For calling details please see v_cent2frq.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_cent2frq.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: cent2frq.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_cent2frq(varargin{:});
else
    v_cent2frq(varargin{:});
end


function ziggurat_test ( )

%*****************************************************************************80
%
%% ZIGGURAT_TEST tests the ZIGGURAT library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 May 2008
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'ZIGGURAT_TEST\n' );
  fprintf ( 1, '  MATLAB version.\n' );
  fprintf ( 1, '  Test the ZIGGURAT library.\n' );
%
%  Make sure that SEED controls the sequence and can restart it.
%
  ziggurat_test001 ( );
  ziggurat_test02 ( );
  ziggurat_test03 ( );
  ziggurat_test04 ( );
%
%  Measure the time it takes to generate a lot of variables.
%
  sample_num = 100000;

  ziggurat_test05 ( sample_num );
  ziggurat_test06 ( sample_num );
  ziggurat_test07 ( sample_num );
  ziggurat_test08 ( sample_num );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'ZIGGURAT_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


%% Bonus Examples
% Tucker McClure
% Copyright 2013 The MathWorks, Inc.

%% Bonus 1: Please
% If it doesn't work, try saying "please".

please = @(f) feval(curly({fprintf('Since you asked nicely...\n'), f}, 2));

% Example:
please(@why)

%% Bonus 2: Anonymous Do-While
% In the examples, we didn't show how to create a do-while loop
% anonymously. Here it is.

dowhile = @(x0, cont, fcn, cleanup) recur(... % Make the recursion.
    @(f, x) use(fcn(x), @(z) ...              %   Run the fcn, save as z.
                iif(cont(z), @() f(f, z), ... %   Continue?
                    true,    cleanup(z))),... % Stop, clean up.
    x0);                                      % Initial state

% Create a function to draw sets of numbers until it draws n positive
% numbers in a row.
draw_until_all_positive = @(n) dowhile([], ...               % No x0
                                       @(x) any(x < 0), ...  % Until all >0
                                       @(~) randn(1, n), ... %   Draw set
                                       @(x) x);              % Return set

fprintf('Draw numbers until we get 5 positive numbers in a row.\n');
draw_until_all_positive(5)

%% Bonus 3: A Large Program
% This is probably not the world's best example of good programming
% practices, but it does serve to illustrate that entire programs *can* be
% built with anonymous functions (whether or not they *should* be built
% this way or whether this is the best way to do it are very different
% questions).
%
% This example uses most of the techniques developed in the
% functional_programming_examples (though it uses the .m versions instead
% of the anonymous versions), including |forloop|, |iif|, |last|, |use|,
% |recur|, |tern|, and |void|. Creating this example also served to prompt
% me to make functions that simplify programming this way.

% Set up the figure.
figure(1);
clf();
set(1, 'Color', 'k');
axis([-20 20 0 25], 'off');
set(gca(), 'Position', [0 0 1 1]);
hold('on');

% Create some constants.
nf = 6;       % Number of fireworks
np = 100;     % Number of particles per firework
n  = nf * np; % Total number of particles
dt = 1/24;    % Time step

% Create some fireworks.
create_fireworks = @() forloop([], nf, @(p,~) ...
    use(2*randn, rand, @(x, y) ...
    [p repmat([2*x, -5*y, 5*x, 20*y+30]', 1, np)]));

% Plot the fireworks.
random_color = @() 1./(1+exp(-20*(rand(1, 3)-0.4))); % It's a sigmoid fcn.
create_plot = @(x0) forloop([], nf, @(h,~) ...
    [h plot(x0(1,:), x0(2,:), '.', 'Color', random_color())]);
limit = @(x) min(max(x, 0), 1);
update_plot = @(x, h, k) forloop([], nf, @(~,z) ...
    void(@() set(h(z), 'XData', x(1, np*(z-1)+1:np*z), ...
                       'YData', x(2, np*(z-1)+1:np*z), ...
                       'Color', limit(1.03-1e-3*k) * get(h(z),'Color'))));

% Propagate the fireworks' particles. At k == 25, make them explode.
explode  = @(x) x + [zeros(2, n); 5*randn(2, n)];
Phi      = expm(dt*[0 0 1 0; 0 0 0 1; 0 0 -1 0; 0 0 0 -1]);
g        = repmat([0 -dt*9.81 0 -0.5*9.81*dt^2]', 1, n);
update_x = @(k, x) Phi * tern(k==25, @() explode(x), @() x) + g;

% Functions to change callback and show text.
set_callback = @(cb) void(@() set(gcf, 'WindowButtonDownFcn', cb));
show_text    = @() text(0, 1, 'Click for fireworks.', ...
                        'HorizontalAlignment', 'center', ...
                        'Color', 'w');

% Create the anonymous program.
fireworks = @() recur(@(self) {...                 % To reference itself.
    set_callback([]), ...                          % Clear the callback.
    void(@() delete(findobj('Type', 'text'))), ... % Delete the text.
    use(create_fireworks(), @(x0) ...              % Create positions, x0.
    use(create_plot(x0),    @(h) ...               % Plot, keep handle, h.
    {forloop(x0, 100, @(x,k) ...                   % Loop from k=1:100.
             last(update_plot(x,h,k), ...          %   Update plot.
                  void(@() pause(dt)), ...         %   Wait.
                  {update_x(k,x)})), ...           %   Update state.
	 void(@() delete(h))} ...                      % Delete fireworks.
    )), ...                                        % (End of x0, h scope.)
	show_text(), ...                               % Create text again.
    set_callback(@(~, ~) self(self))});            % Restore callback.

% Execute the anonymous program, which will also attach 'fireworks' to the
% button click callback.
fireworks();


function table_io_test ( )

%*****************************************************************************80
%
%% TABLE_IO_TEST tests the TABLE_IO library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 September 2006
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TABLE_IO_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the TABLE_IO library.\n' );

  table_io_test01 ( );
  table_io_test02 ( );
  table_io_test03 ( );
  table_io_test04 ( );
  table_io_test05 ( );
  table_io_test06 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TABLE_IO_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function value = p55_param ( action, name, value )

%*****************************************************************************80
%
%% P55_PARAM sets or gets real scalar parameters for problem 55.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string ACTION,
%    'GET' to get a parameter.
%    'RANDOMIZE' to randomize a parameter,
%    'SET' to set a parameter.
%
%    Input, string NAME, the name of the variable.
%    'C' is the coefficient.
%    'X0' is the base point.
%
%    Input/output, real VALUE.
%    * If ACTION = 'SET', then VALUE is an input quantity, and is the
%      new value to be assigned to NAME.
%    * If ACTION = 'GET', then VALUE is an output quantity, and is the
%      current value of NAME.
%
  persistent c;
  persistent x0;

  if ( s_eqi ( action, 'get' ) )

    if ( s_eqi ( name, 'c' ) )
      if ( isempty ( c ) )
        c = 3.0;
      end
      value = c;
    elseif ( s_eqi ( name, 'x0' ) )
      if ( isempty ( x0 ) )
        x0 = 0.75;
      end
      value = x0;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P55_PARAM - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name.\n' );
      error ( 'P55_PARAM - Fatal error!' );
    end

  elseif ( s_eqi ( action, 'random' ) )

    if ( s_eqi ( name, 'c' ) )
      c = rand ( );
    elseif ( s_eqi ( name, 'x0' ) )
      x0 = rand ( );
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P55_PARAM - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name.\n' );
      error ( 'P554_PARAM - Fatal error!' );
    end

  elseif ( s_eqi ( action, 'set' ) )

    if ( s_eqi ( name, 'c' ) )
      c = value;
    elseif ( s_eqi ( name, 'x0' ) )
      x0 = value;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P55_PARAM - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name.\n' );
      error ( 'P55_PARAM - Fatal error!' );
    end

  else

    fprintf ( 1, '\n' );
    fprintf ( 1, 'P55_PARAM - Fatal error!\n' );
    fprintf ( 1, '  Unrecognized action.\n' );
    error ( 'P55_PARAM - Fatal error!' );

  end

  return
end


function message = sysrequirements_for_testing(varargin)
% Checking whether the functions needed for testing are installed.
%     In order to run m-functions timing_arraylab_engines and
%     testing_memory_usage, you need to have installed in your system:
%         - MATLAB R2007a or later (you need the builtin function BSXFUN)
%         - GENOP (MATLAB Central file #10333)
%         - BSXFUN substitute (MATLAB Central file #23005)
%         - TIMEIT (MATLAB Central file #18798)

% Paolo de Leva
% University of Rome, Foro Italico, Rome, Italy
% 2009 Feb 22

disp ' '
disp(['You are running MATLAB version ' version])
errorflag = false;

  bsxfunflag = false;
  bsxmexflag = false;
   genopflag = false;
bsxtimesflag = false;
  timeitflag = false;

for i = 1:nargin
    switch varargin{i}
        case 'bsxfun',     bsxfunflag = true;
        case 'bsxmex',     bsxmexflag = true;
        case 'genop',       genopflag = true;
        case 'bsxtimes', bsxtimesflag = true;
        case 'timeit',     timeitflag = true;
    end
end

% Check to see if BSXFUN is a builtin function.
if bsxfunflag && ~exist('bsxfun', 'builtin')
    disp ' '
    w = (['WARNING: You need MATLAB 7.4 (R2007a) or a later version, because  '
          '         you need the builtin function BSXFUN (its replacements for'
          '         releases prior to R2007a are also tested here).           ']);
    disp (w)
    errorflag = true;
end

if genopflag && ~exist('genop', 'file')
    disp ' '
    w = (['WARNING: You need to download GENOP (MATLAB Central file #10333,'
          '         http://www.mathworks.com/matlabcentral/fileexchange)   '
          '         and move it into the current directory.                ']);
    disp (w)
    errorflag = true;
end

if bsxmexflag && (~exist('bsxfun', 'file') || ~exist('bsx_times', 'file'))
    disp ' '
    w = (['WARNING: You need to download Schwarz''s BSXFUN substitute (file #23005'
          '         http://www.mathworks.com/matlabcentral/fileexchange), install'
          '         it, add to the MATLAB search path the directory in which you '
          '         installed it (use PATHTOOL to set the path).                 '
          '         Do not forget to run MAKE_BSX_MEX to build BSX_TIMES.        ']);
      disp (w)
    errorflag = true;
end

if bsxtimesflag && ~exist('bsx_times', 'file')
    disp ' '
    w = (['WARNING: You need to download Schwarz''s BSXFUN substitute (file #23005'
          '         http://www.mathworks.com/matlabcentral/fileexchange), install'
          '         it, delete BSXFUN.M to avoid a conflict with the builtin     '
          '         BSXFUN, run MAKE_BSX_MEX to build BSX_TIMES, and move        '
          '         BSX_TIMES to the current directory.                          ']);
      disp (w)
    errorflag = true;
end

if timeitflag
    verdate = datenum(version('-date'), 'mmmm dd, yyyy');
    minimumdate = datenum(2005,6,21); % Correct version of functions TIC/TOC
    if verdate < minimumdate
        disp ' '
        w = (['WARNING: You need MATLAB 7.1 (R14SP3) or a later version, because '
              '         you need an accurate and precise version of the builtin  '
              '         functions TIC and TOC, supporting the undocumented syntax'
              '         T = TIC; ...; ELAPSED_TIME = TOC(T).                     ']);
        disp (w)
        errorflag = true;
    elseif ~exist('timeit', 'file')
        disp ' '
        w = (['WARNING: You need to download TIMEIT (MATLAB Central file #18798,   '
              '         http://www.mathworks.com/matlabcentral/fileexchange),      '
              '         install it, and add to the MATLAB search path the directory'
              '         in which you installed it (use PATHTOOL to set the path).  ']);
        disp (w)
        errorflag = true;
    end
end

if errorflag
    message = (['Before running this function you must install the above\n', ...
                'mentioned software']);
else
    message = false;
end


function class_info=gen_class_info_voc()

class_info=[];

class_info.class_names = { 'background', 'aeroplane', 'bicycle', 'bird', 'boat',  'bottle', 'bus',...
            'car', 'cat', 'chair', 'cow', 'diningtable','dog', 'horse',...
            'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor', ...
            'void'}';

void_class_value=255;
class_info.class_label_values=uint8([0:20 void_class_value]);
class_info.background_label_value=uint8(0);
class_info.void_label_values=uint8(void_class_value);

% addpath ../libs/VOCdevkit_2012/VOCcode
class_info.mask_cmap = VOClabelcolormap(256);

class_info=process_class_info(class_info);

end


function [eeg] = read_eep_cnt(fn);

% READ_EEP_CNT reads continuous EEG data from an EEProbe *.cnt file
% and returns a structure containing the header and data information.
%
% eeg = read_eep_cnt(filename, sample1, sample2)
%
% where sample1 and sample2 are the begin and end sample of the data
% to be read.
%
% eeg.label    ... labels of EEG channels
% eeg.rate     ... sampling rate
% eeg.npnt     ... number of sample in data segment
% eeg.nchan    ... number of channels
% eeg.nsample
% eeg.time     ... array [1 x npnt] of time points (ms)
% eeg.data     ... array [nchan x npnt] containing eeg data (uV)
% eeg.trigger  ... array [n, 4] containing trigger information
%
% Author: Robert Oostenveld, Aalborg University, Denmark, 11 March 2003
%
% See also READ_EEP_TRG, READ_EEP_REJ, READ_EEP_AVR
%

% Copyright (C) 2002, Robert Oostenveld
%                     Aalborg University, Denmark
%                     http://www.smi.auc.dk/~roberto/
%
% 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

% $Log: not supported by cvs2svn $
% Revision 1.1  2004/11/19 14:55:38  jwiskerke
% Added files for use with matlab
%
% Revision 1.1  2004/11/19 14:39:29  jwiskerke
% Initial input into cvs. These files should work.
%
% Revision 1.2  2003/10/24 13:34:41  Maarten-Jan Hoeve
% Added GNU Licence and updated revision history
%
% Revision 1.1.1.2  2003/10/17 09:55:20  mvelde
% updated: consistent copyrights, arguments/data labels, fixed some typos
%
% Revision 1.1.1.1  2003/03/11 15:24:51  roberto
% updated help and copyrights
%
% ANT Software BV, The Netherlands, www.ant-neuro.com / info@ant-neuro.com
%

error('could not locate mex file');


%SIMILARRECTS  Class for grouping object candidates, detected by Cascade Classifier, HOG etc.
%
%     b = cv.SimilarRects(r1, r2)
%     b = cv.SimilarRects(r1, r2, 'OptionName',optionValue, ...)
%
% ## Input
% * __r1__ First input rectangle, 4-element vector `[x,y,w,h]`.
% * __r2__ Second input rectangle.
%
% ## Output
% * __b__ logical output indicate whether rectangles are similar.
%
% ## Options
% * __EPS__ Relative difference between sides of the rectangles to consider
%   similar. default 0.2
%
% See also: cv.groupRectangles, cv.groupRectangles_meanshift
%


% Script to extract gray matter from pial and smoothwm surfaces
% Uses mri_surfacemask routine. Only runs on RH / i386 I think

fs_dir='/raid/MRI/toolbox/MGH/freesurfer/bin/Linux';
fsl_dir='/raid/MRI/toolbox/FSL/fsl/bin/';

hemi='rh';
subjid='norcia_fs_WB';

% Run mri_surfacemask on both the rh.smoothwm and rh.pial
fileBase=['/raid/MRI/anatomy/FREESURFER_SUBS/',subjid];
fileNameToProcess=[fileBase,'/surf/',hemi,'.pial'];
anatomyToUse=[fileBase,'/mri/T1/'];
outFileName=[fileBase,'/mri/',hemi,'_pial'];
fs_command=['echo ',fs_dir,'/mri_surfacemask ',anatomyToUse,' ',fileNameToProcess,' ',outFileName,'.img | csh'];
disp(fs_command);
tic

system(fs_command);
toc
% Load in the pial image
[pialIm,dims,scalesmbpp,endian]=read_avw([outFileName]);

fileNameToProcess=[fileBase,'/surf/',hemi   ,'.smoothwm'];
outFileName=[fileBase,'/mri/',hemi,'_smoothwm'];
fs_command=['echo ',fs_dir,'/mri_surfacemask ',anatomyToUse,' ',fileNameToProcess,' ',outFileName,'.img | csh'];
disp(fs_command);
tic
dos(fs_command);
toc

% Load in the smoothwm image
[wmIm,dims,scalesmbpp,endian]=read_avw(outFileName);

% Binarize and 'and' them
wmIm(wmIm>0)=1;

pialIm(pialIm>0)=1;
grayIm=pialIm-wmIm;
grayIm(grayIm~=1)=0;
grayIm(grayIm~=0)=255;

outFileName=[fileBase,'/mri/',hemi,'_grayMask'];
grayIm=permute(grayIm,[1 3 2]);

save_avw((grayIm),outFileName,'b',scalesmbpp);

% Resulting analyze files can be imported to EMSE and a region defined on
% them using the thresholding / growing routines.
% The dimensions are ordered correctly but must be flipped front/back,
% top/bottom AND left/right!


% SB2_USEROPTIONS  User option specification for SPARSEBAYES
%
% OPTIONS = SB2_USEROPTIONS(parameter1, value1, parameter2, value2,...)
%
% OUTPUT ARGUMENTS:
%
%	OPTIONS		An options structure to pass to SPARSEBAYES
%
% INPUT ARGUMENTS:
%
%	Optional number of parameter-value pairs to specify the following:
%
%	ITERATIONS	Number of interations to run for.
%
%	TIME		Time limit to run for, expressed as a space-separated
%				string. e.g. '1.5 hours', '30 minutes', '1 second'.
%
%	DIAGNOSTICLEVEL	Integer [0,4] or string to determine the verbosity of
%					diagnostic output.
%					0 or 'ZERO' or 'NONE'	No output
%					1 or 'LOW'				Low level of output
%					2 or 'MEDIUM'			etc...
%					3 or 'HIGH'
%					4 or 'ULTRA'
%
%	DIAGNOSTICFILE	Filename to write diagnostics to file instead of
%					the default stdout.
%
%	MONITOR		Integer number: diagnostic information is output
%				every MONITOR iterations.
%
%	FIXEDNOISE	True/false whether the Gaussian noise is to be fixed
%				(default: false.
%
%	FREEBASIS	Indices of basis vectors considered "free" and not
%				constrained by the Bayesian prior (e.g. the "bias").
%
%	CALLBACK	External function to call each iteration of the algorithm
%				(string). Intended to facilitate graphical demos etc.
%
%	CALLBACKDATA	Arbitrary additional data to pass to the CALLBACK
%					function.
%
% EXAMPLE:
%
%	OPTIONS = SB2_UserOptions('diagnosticLevel','medium',...
%				  'monitor',25,...
%				  'diagnosticFile', 'logfile.txt');
%
% NOTES:
%
% Each option (field of OPTIONS) is given a default value in
% SB2_USEROPTIONS. Any supplied property-value pairs over-ride those
% defaults.
%

%
% Copyright 2009, Vector Anomaly Ltd
%
% This file is part of the SPARSEBAYES library for Matlab (V2.0).
%
% SPARSEBAYES 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.
%
% SPARSEBAYES 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 SPARSEBAYES in the accompanying file "licence.txt"; if not, write to
% the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
% MA 02110-1301 USA
%
% Contact the author: m a i l [at] m i k e t i p p i n g . c o m
%
function OPTIONS = SB2_UserOptions(varargin)

% Ensure arguments are supplied in pairs
%
if rem(nargin,2)
  error('Arguments to SB2_UserOptions should be (property, value) pairs')
end
% Any options specified?
numSettings	= nargin/2;

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

% Set defaults
%
% Assume we will infer the noise in the Gaussian case
%
OPTIONS.fixedNoise		= false;
%
% Option to allow subset of the basis (e.g. bias) to be unregularised
%
OPTIONS.freeBasis		= [];
%
% Option to set max iterations to run for
%
OPTIONS.iterations		= 10000;
%
% Option to set max time to run for
%
OPTIONS.time			= 10000; % seconds
%
% Set options for monitoring and recording the algorithm's progress
%
OPTIONS.monitor			= 0;
OPTIONS.diagnosticLevel	= 0;
OPTIONS.diagnosticFID	= 1; % stdout
OPTIONS.diagnosticFile_	= [];
%
% Option to call a function during each iteration (to create demos etc)
%
OPTIONS.callback		= false;
OPTIONS.callbackFunc	= [];
OPTIONS.callbackData	= {};

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

% Parse string/variable pairs

for n=1:numSettings
  property_	= varargin{(n-1)*2+1};
  value		= varargin{(n-1)*2+2};
  switch upper(property_)
    %
   case 'FIXEDNOISE',
    OPTIONS.fixedNoise	= value;
    %
   case 'FREEBASIS',
    OPTIONS.freeBasis	= value;
    %
   case 'ITERATIONS',
    OPTIONS.iterations	= value;
	%
   case 'TIME',
    OPTIONS.time		= timeInSeconds(value);
    %
   case 'MONITOR',
    OPTIONS.monitor		= value;
    %
   case 'DIAGNOSTICLEVEL',
    OPTIONS.diagnosticLevel	= value;
    MAX_LEVEL	= 4;
    if ischar(value)
      switch upper(value)
       case {'ZERO','NONE'},
	OPTIONS.diagnosticLevel	= 0;
       case 'LOW',
	OPTIONS.diagnosticLevel	= 1;
       case 'MEDIUM',
	OPTIONS.diagnosticLevel	= 2;
       case 'HIGH',
	OPTIONS.diagnosticLevel	= 3;
       case 'ULTRA',
	OPTIONS.diagnosticLevel	= 4;
       otherwise,
	error('Unrecognised textual diagnostic level: ''%s''\n', value)
      end
    elseif isnumeric(value)
      if value>=0 & value<=MAX_LEVEL
	OPTIONS.diagnosticLevel		= value;
      else
	error(['Supplied level should be integer in [0,%d], '...
	       'or one of ZERO/LOW/MEDIUM/HIGH/ULTRA'], MAX_LEVEL);

      end
    end
    %
   case 'DIAGNOSTICFILE',
    OPTIONS.diagnosticFile_	= value;
    OPTIONS.diagnosticFID	= -1; % It will be opened later
    %
   case 'CALLBACK',
    OPTIONS.callback		= true;
    OPTIONS.callbackFunc	= value;
    if exist(OPTIONS.callbackFunc)~=2
      error('Callback function ''%s'' does not appear to exist\n', value)
    end
    %
   case 'CALLBACKDATA',
    OPTIONS.callbackData	= value;
   otherwise,
    error('Unrecognised user option: ''%s''\n', property_)
    %
  end
end

%%
%% Support function: parse time specification
%%
function s = timeInSeconds(value_)
%
[v_ r_]				= strtok(value_,' ');
v					= str2num(v_);
r_(isspace(r_))		= [];
switch upper(r_)
 case {'SECONDS', 'SECOND'}
  s	= v;
 case {'MINUTES', 'MINUTE'}
  s = 60*v;
 case {'HOURS', 'HOUR'}
  s = 3600*v;
 otherwise,
  error('Badly formed time string: ''%s''', value_)
end
% Returns time in seconds
%


%% Copyright (C) 2014, 2019 Colin B. Macdonald
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy is free software; you can redistribute it and/or modify
%% it under the terms of the GNU General Public License as published
%% by the Free Software Foundation; either version 3 of the License,
%% or (at your option) any later version.
%%
%% This software 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 software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.

function [vars,s1,s2] = helper_symfun_binops(f, g)

  if (isa(f,'symfun')) && (isa(g, 'symfun'))
    %disp('debug: symfun <op> symfun')
    if ~isequal(f.vars, g.vars)
      error('arithmetric operators on symfuns must have same vars')
    end
    vars = f.vars;
    s1 = formula (f);
    s2 = formula (g);
  elseif (isa(f,'symfun'))
    %disp('debug: symfun <op> sym')
    vars = f.vars;
    s1 = formula (f);
    s2 = g;
  elseif (isa(g, 'symfun'))
    %disp('debug: sym <op> symfun')
    vars = g.vars;
    s1 = f;
    s2 = formula (g);
  else
    error('Tertium Non Datur')
  end


function [v0, vl, vu, vt] = params_var(om, name, idx)
%PARAMS_VAR  Returns initial value, lower bound and upper bound for opt variables.
%   [V0, VL, VU] = OM.PARAMS_VAR()
%   [V0, VL, VU] = OM.PARAMS_VAR(NAME)
%   [V0, VL, VU] = OM.PARAMS_VAR(NAME, IDX_LIST)
%   [V0, VL, VU, VT] = PARAMS_VAR(...)
%   Returns the initial value V0, lower bound VL and upper bound VU for
%   the full optimization variable vector, or for a specific named or named
%   and indexed variable set. Optionally also returns a corresponding char
%   vector VT of variable types, where 'C', 'I' and 'B' represent continuous
%   integer and binary variables, respectively.
%
%   Examples:
%       [x0, xmin, xmax] = om.params_var();
%       [Pg0, Pmin, Pmax] = om.params_var('Pg');
%       [zij0, zijmin, zijmax, ztype] = om.params_var('z', {i, j});
%
%   See also OPT_MODEL.

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

if nargout > 3
    have_vt = 1;
else
    have_vt = 0;
end
if nargin < 2
    v0 = []; vl = []; vu = []; vt = char([]);
    %% calls to substruct() are relatively expensive, so we pre-build the
    %% structs for addressing cell and numeric array fields, updating only
    %% the subscripts before use
    sc = struct('type', {'.', '{}'}, 'subs', {'', 1});  %% cell array field
    for k = 1:om.var.NS
        name = om.var.order(k).name;
        idx = om.var.order(k).idx;
        if isempty(idx)
            v0 = [ v0; om.var.data.v0.(name) ];
            vl = [ vl; om.var.data.vl.(name) ];
            vu = [ vu; om.var.data.vu.(name) ];
            if have_vt
                N = om.var.idx.N.(name);
                vt0 = om.var.data.vt.(name);
                if isscalar(vt0) && N > 1
                    vt = [ vt char(vt0 * ones(1, N)) ];
                else
                    vt = [ vt vt0 ];
                end
            end
        else
            % (calls to substruct() are relatively expensive ...
            % sc = substruct('.', name, '{}', idx);
            % ... so replace it with these more efficient lines)
            sc(1).subs = name;
            sc(2).subs = idx;
            v0 = [ v0; subsref(om.var.data.v0, sc) ];
            vl = [ vl; subsref(om.var.data.vl, sc) ];
            vu = [ vu; subsref(om.var.data.vu, sc) ];
            if have_vt
                % (calls to substruct() are relatively expensive ...
                % sn = substruct('.', name, '()', idx);
                % ... so replace it with these more efficient lines)
                sn = sc; sn(2).type = '()';
                N = subsref(om.var.idx.N, sn);
                vt0 = subsref(om.var.data.vt, sc);
                if isscalar(vt0) && N > 1
                    vt = [ vt char(vt0 * ones(1, N)) ];
                else
                    if ~isempty(vt0)
                        vt = [ vt vt0 ];
                    end
                end
            end
        end
    end
else
    if isfield(om.var.idx.N, name)
        if nargin < 3 || isempty(idx)
            v0 = om.var.data.v0.(name);
            vl = om.var.data.vl.(name);
            vu = om.var.data.vu.(name);
            if have_vt
                N = om.var.idx.N.(name);
                vt0 = om.var.data.vt.(name);
                if isscalar(vt0) && N > 1
                    vt = char(vt0 * ones(1, N));
                else
                    vt = vt0;
                end
            end
        else
            % (calls to substruct() are relatively expensive ...
            % sc = substruct('.', name, '{}', idx);
            % ... so replace it with these more efficient lines)
            sc = struct('type', {'.', '{}'}, 'subs', {name, idx});
            v0 = subsref(om.var.data.v0, sc);
            vl = subsref(om.var.data.vl, sc);
            vu = subsref(om.var.data.vu, sc);
            if have_vt
                % (calls to substruct() are relatively expensive ...
                % sn = substruct('.', name, '()', idx);
                % ... so replace it with these more efficient lines)
                sn = sc; sn(2).type = '()';
                N = subsref(om.var.idx.N, sn);
                vt0 = subsref(om.var.data.vt, sc);
                if isscalar(vt0) && N > 1
                    vt = char(vt0 * ones(1, N));
                else
                    vt = vt0;
                end
            end
        end
    else
        v0 = [];
        vl = [];
        vu = [];
        if have_vt
            vt = [];
        end
    end
end


function result = TS_GetFromData(dataSource,dataField)
% TS_GetFromData   Load a given field from either a data file, or data structure
%                   (loaded from file).
%
%---INPUTS:
% dataSource: either a .mat filename or a structure generated from loading an
%               HCTSA file, e.g.,
%               dataSource = load('HCTSA.mat');
% dataField: the variable to extract
%
%---OUTPUTS:
% result: the variable extracted from either the file or structure (depending
%           on the type of dataSource)
%
%---EXAMPLE USAGE:
% fromDatabase = TS_GetFromData('HCTSA_EEGDataset.mat','fromDatabase');
% MasterOperations = TS_GetFromData('HCTSA_EEGDataset.mat','MasterOperations');

% ------------------------------------------------------------------------------
% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite the following two papers:
%
% (1) B.D. Fulcher and N.S. Jones, "hctsa: A Computational Framework for Automated
% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).
% DOI: 10.1016/j.cels.2017.10.001
%
% (2) B.D. Fulcher, M.A. Little, N.S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2013).
% DOI: 10.1098/rsif.2013.0048
%
% This work is licensed under the Creative Commons
% Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of
% this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/ or send
% a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View,
% California, 94041, USA.
% ------------------------------------------------------------------------------

%-------------------------------------------------------------------------------
% In some cases, you provide a structure with the pre-loaded data already in it
% e.g., as a whatDataFile = load('HCTSA.mat');
%-------------------------------------------------------------------------------
if isstruct(dataSource)
    if isfield(dataSource,dataField)
        result = dataSource.(dataField);
    else
        result = [];
    end

%-------------------------------------------------------------------------------
% Often you provide a .mat file name: load in from file
%-------------------------------------------------------------------------------
elseif ischar(dataSource)

    % Decode shorthands for default filenames 'raw', 'loc', 'norm', and 'cl':
    switch dataSource
    case {'raw','loc'} % the raw, un-normalized data:
        dataSource = 'HCTSA.mat';
    case 'norm' % the normalized data:
        dataSource = 'HCTSA_N.mat';
    case 'cl' % the clustered data:
        dataSource = 'HCTSA_N.mat';
    end

    try
        loadAgain = load(dataSource,dataField);
        result = loadAgain.(dataField);
    catch
        result = [];
    end
    % fileVarsStruct = whos('-file',dataSource);
    % fileVars = {fileVarsStruct.name};
    % if ismember(dataField,fileVars)
    %     loadAgain = load(dataSource,dataField);
    %     result = loadAgain.(dataField);
    % else
    %     result = [];
    % end
else
    error('Unknown data source type: %s',class(dataSource));
end

% Check for legacy structure array format and convert to table:
if ismember(dataField,{'TimeSeries','Operations','MasterOperations'}) && isstruct(result)
    warning('Loaded metadata, %s, is still in the old structure-array format; converted to table',dataField)
    result = struct2table(result);
end

end


function A = cs_sparse2 (i,j,x)                                             %#ok
%CS_SPARSE2 same as cs_sparse, to test cs_entry function
% A = cs_sparse2 (i,j,x), removing duplicates and numerically zero entries,
% and returning A sorted (test cs_entry)
%
% Example:
%   A = cs_sparse2 (i,j,x)
% See also: cs_demo

%   Copyright 2006-2007, Timothy A. Davis.
%   http://www.cise.ufl.edu/research/sparse

error ('cs_sparse2 mexFunction not found') ;


function percent = parfor_progress(N)
%PARFOR_PROGRESS Progress monitor (progress bar) that works with parfor.
%   PARFOR_PROGRESS works by creating a file called parfor_progress.txt in
%   your working directory, and then keeping track of the parfor loop's
%   progress within that file. This workaround is necessary because parfor
%   workers cannot communicate with one another so there is no simple way
%   to know which iterations have finished and which haven't.
%
%   PARFOR_PROGRESS(N) initializes the progress monitor for a set of N
%   upcoming calculations.
%
%   PARFOR_PROGRESS updates the progress inside your parfor loop and
%   displays an updated progress bar.
%
%   PARFOR_PROGRESS(0) deletes parfor_progress.txt and finalizes progress
%   bar.
%
%   To suppress output from any of these functions, just ask for a return
%   variable from the function calls, like PERCENT = PARFOR_PROGRESS which
%   returns the percentage of completion.
%
%   Example:
%
%      N = 100;
%      parfor_progress(N);
%      parfor i=1:N
%         pause(rand); % Replace with real code
%         parfor_progress;
%      end
%      parfor_progress(0);
%
%   See also PARFOR.

% By Jeremy Scheff - jdscheff@gmail.com - http://www.jeremyscheff.com/

%error(nargchk(0, 1, nargin, 'struct'));
narginchk(0, 1); %because nargchk is depreciated

if nargin < 1
    N = -1;
end

percent = 0;
w = 50; % Width of progress bar

if N > 0
    f = fopen('parfor_progress.txt', 'w');
    if f<0
        error('Do you have write permissions for %s?', pwd);
    end
    fprintf(f, '%d\n', N); % Save N at the top of progress.txt
    fclose(f);

    if nargout == 0
        disp(['  0%[>', repmat(' ', 1, w), ']']);
    end
elseif N == 0
    delete('parfor_progress.txt');
    percent = 100;

    if nargout == 0
        disp([repmat(char(8), 1, (w+9)), char(10), '100%[', repmat('=', 1, w+1), ']']);
    end
else
    if ~exist('parfor_progress.txt', 'file')
        error('parfor_progress.txt not found. Run PARFOR_PROGRESS(N) before PARFOR_PROGRESS to initialize parfor_progress.txt.');
    end

    f = fopen('parfor_progress.txt', 'a');
    fprintf(f, '1\n');
    fclose(f);

    f = fopen('parfor_progress.txt', 'r');
    progress = fscanf(f, '%d');
    fclose(f);
    percent = (length(progress)-1)/progress(1)*100;

    if nargout == 0
        perc = sprintf('%3.0f%%', percent); % 4 characters wide, percentage
        disp([repmat(char(8), 1, (w+9)), char(10), perc, '[', repmat('=', 1, round(percent*w/100)), '>', repmat(' ', 1, w - round(percent*w/100)), ']']);
    end
end


function serialized_mat = serialize(mat)
% SYNTAX:
%   serialized_mat = serialize(mat)
% DESCRIPTION:
%   return the array of the serialized matrix

%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:       Andrea Gatti
%  Contributors:     Andrea Gatti ...
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   This program is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License
%   along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

    serialized_mat = mat(:);
end


function bboxeso = bbox_remove_duplicates(bboxes, minSize, maxNum)
% Copyright (C) 2016 Hakan Bilen.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
bboxeso = cell(size(bboxes));
for i=1:numel(bboxes)
  bbox = bboxes{i};
  % remove small bbox
  isGood = (bbox(:,3)>=bbox(:,1)-1+minSize) & (bbox(:,4)>=bbox(:,2)-1+minSize);
  bbox = bbox(isGood,:);
  % remove duplicate ones
  [dummy, uniqueIdx] = unique(bbox, 'rows', 'first');
  uniqueIdx = sort(uniqueIdx);
  bbox = bbox(uniqueIdx,:);
  % limit number for training
  nB = min(size(bbox,1),maxNum);

  bboxeso{i} = bbox(1:nB,:);
end


function varargout = lzmadecode(varargin)
%
% output = lzmadecode(input)
%    or
% output = lzmadecode(input,info)
%
% Decompressing an LZMA-compressed byte-stream to recover the original data
% This function depends on the ZMat toolbox (http://github.com/fangq/zmat)
%
% authors:Qianqian Fang (q.fang <at> neu.edu)
%
% input:
%      input: a string, int8/uint8 vector or numerical array to store LZMA-compressed data
%      info (optional): a struct produced by the zmat/lzmaencode function during
%            compression; if not given, the inputs/outputs will be treated as a
%            1-D vector
%
% output:
%      output: the decompressed byte stream stored in a uint8 vector; if info is
%            given, output will restore the original data's type and dimensions
%
% examples:
%      [bytes, info]=lzmaencode(eye(10));
%      orig=lzmadecode(bytes,info);
%
% license:
%     BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%

if(nargin==0)
    error('you must provide at least 1 input');
end
if(exist('zmat','file')==2 || exist('zmat','file')==3)
    if(nargin>1)
        [varargout{1:nargout}]=zmat(varargin{1},varargin{2:end});
    else
        [varargout{1:nargout}]=zmat(varargin{1},0,'lzma',varargin{2:end});
    end
else
    error('you must install ZMat toolbox to use this feature: http://github.com/fangq/zmat')
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D
% shape modeling and analysis toolkit.
% It is a software package developed at Shenlab in Center for Neuroimaging,
% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)
% It is available to the scientific community as copyright freeware
% under the terms of the GNU General Public Licence.
%
% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University
%
% This file is part of SPHARM-MAT.
%
% SPHARM-MAT 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.
%
% SPHARM-MAT 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 SPHARM-MAT. If not, see <http://www.gnu.org/licenses/>.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% ============================================
% write_gipl_volume.m
% Function for writing Guys Image Processing Lab (Gipl) files with given
% volumn, file name of the output, and voxel size.
%
% for example,
% I=uint8(rand(64,64,64)*256);
% 1: gipl_write_volume(I);
% 2: gipl_write_volume(I,'random.gipl',[2 2 2];

% Wan Jing
% 11/06/2008 - create
%============================================

function gipl_write_volume(I,fname,scales,origin)

% define supported image types and bit length.
image_types=struct('double',65,'float',65,'single',64,'logical',1,'int8',7,'uint8',8,'int16',15,'uint16',16,'int32',32,'uint32',31);
bit_lengths=struct('double',64,'float',64,'single',32,'logical',1,'int8',8,'uint8',8,'int16',16,'uint16',16,'int32',32,'uint32',32);

% Sizes
    sizes=size(I);
    while(length(sizes)<4), sizes=[sizes 1]; end
% Scales
    if(exist('scales','var')==0), scales=ones(1,length(sizes)); end;
    while(length(scales)<4), scales=[scales 0]; end
% Offset
    offset=256;
% Image Type
    image_type=getfield(image_types,class(I));
% File size
    fsize=offset+prod(sizes)*getfield(bit_lengths,class(I))/8;
% Patient
    patient='Generated by Matlab';
    while(length(patient)<80), patient=[patient ' ']; end
% Matrix
    matrix=[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0];
% orientation
    orientation=0;
% voxel_min
    voxmin=min(I(:));
% voxel_max
    voxmax=max(I(:));
% origin
 %   origin=[0 0 0 0];
% pixval_offset
    pixval_offset=0;
% pixval_cal
    pixval_cal=0;
% interslicegap
    interslicegap=0;
% user_def2
    user_def2=0;
% par2
    par2=0;
% magic_number
    magic_number=4026526128;

trans_type{1}='binary'; trans_type{7}='char'; trans_type{8}='uchar'; trans_type{15}='short';
trans_type{16}='ushort'; trans_type{31}='uint'; trans_type{32}='int'; trans_type{64}='float';
trans_type{65}='double'; trans_type{144}='C_short'; trans_type{160}='C_int'; trans_type{192}='C_float';
trans_type{193}='C_double'; trans_type{200}='surface'; trans_type{201}='polygon';

trans_orien{0+1}='UNDEFINED'; trans_orien{1+1}='UNDEFINED_PROJECTION'; trans_orien{2+1}='AP_PROJECTION';
trans_orien{3+1}='LATERAL_PROJECTION'; trans_orien{4+1}='OBLIQUE_PROJECTION';  trans_orien{8+1}='UNDEFINED_TOMO';
trans_orien{9+1}='AXIAL'; trans_orien{10+1}='CORONAL'; trans_orien{11+1}='SAGITTAL'; trans_orien{12+1}='OBLIQUE_TOMO';

% display information about the volumn
disp(['filename : ' num2str(fname)]);
disp(['filesize : ' num2str(fsize)]);
disp(['sizes : ' num2str(sizes)]);
disp(['scales : ' num2str(scales)]);
disp(['image_type : ' num2str(image_type) ' - ' trans_type{image_type}]);
disp(['patient : ' patient]);
disp(['matrix : ' num2str(matrix)]);
disp(['orientation : ' num2str(orientation) ' - ' trans_orien{orientation+1}]);
disp(['voxel min : ' num2str(voxmin)]);
disp(['voxel max : ' num2str(voxmax)]);
disp(['origin : ' num2str(origin)]);
disp(['pixval_offset : ' num2str(pixval_offset)]);
disp(['pixval_cal : ' num2str(pixval_cal)]);
disp(['interslicegap : ' num2str(interslicegap)]);
disp(['user_def2 : ' num2str(user_def2)]);
disp(['par2 : ' num2str(par2)]);
disp(['offset : ' num2str(offset)]);

% save volumn to *.gipl file
fout=fopen(fname,'wb','ieee-be');
fwrite(fout,uint16(sizes),'ushort'); % 4
fwrite(fout,uint16(image_type),'ushort'); % 1
fwrite(fout,single(scales),'float'); % 4
fwrite(fout,patient,'char'); % 80
fwrite(fout,single(matrix),'float'); % 20
fwrite(fout,uint8(orientation),'uint8'); % 1
fwrite(fout,uint8(par2),'uint8'); % 1
fwrite(fout,double(voxmin),'double'); % 1
fwrite(fout,double(voxmax),'double'); % 1
fwrite(fout,double(origin),'double'); % 4
fwrite(fout,single(pixval_offset),'float'); % 1
fwrite(fout,single(pixval_cal),'float'); % 1
fwrite(fout,single(interslicegap),'float'); % 1
fwrite(fout,single(user_def2),'float'); % 1
fwrite(fout,uint32(magic_number),'uint'); % 1
fwrite(fout,I, trans_type{image_type});
fclose('all');


function[u] = DxT(v)

  u = DyT(v')';

return


function model = gpReconstruct(kern, noise, gpInfo, X, y)

% GPRECONSTRUCT Reconstruct an GP form component parts.
% FORMAT
% DESC takes component parts of an GP model and reconstructs the
% GP model. The component parts are normally retrieved from a
% saved file.
% ARG kern : a kernel structure for the GP.
% ARG noise : a noise structure for the GP (currently ignored).
% ARG gpInfo : the active set and other information stored in a structure.
% ARG X : the input training data for the GP.
% ARG y : the output target training data for the GP.
% RETURN model : an GP model structure that combines the component
% parts.
%
% SEEALSO : gpDeconstruct, gpCreate
%
% COPYRIGHT : Neil D. Lawrence, 2007, 2009

% GP

  model = gpInfo;
  model.X = X;
  model.y = y;
  model.kern = kern;
  if ~isempty(noise)
    model.noise = noise;
  end
  model.m = gpComputeM(model);

  if isfield(model, 'computeS') && model.computeS
    model.S = model.m*model.m';
  end
  params = gpExtractParam(model);
  model = gpExpandParam(model, params);

end


%%*****************************************************************
%% validate: validate data
%%*****************************************************************
%% SDPT3: version 4.0
%% Copyright (c) 1997 by
%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************

   function  [blk,At,C,b,dim,nnblk,parbarrier] = ...
              validate(blk,At,C,b,par,parbarrier)

   if (nargin >= 5)
      spdensity = par.spdensity;
   else
      spdensity = 0.4;
   end
%%
   if ~iscell(blk);
      error('validate: blk must be a cell array'); end;
   if (size(blk,2) < 2)
      error('validate: blk must be a cell array with at least 2 columns');
   end
   if ~iscell(At) | ~iscell(C);
      error('validate: At, C must be cell arrays');
   end
   if (size(At,1) ~= size(blk,1))
      if (size(At,2) == size(blk,1));
         At = At';
      else
         error('validate: size of At is not compatible with blk');
      end
   end
   if (size(C,1) ~= size(blk,1))
      if (size(C,2) == size(blk,1))
         C = C';
      else
         error('validate: size of C is not compatible with blk');
      end
   end
   if (min(size(b)) > 1); error('validate: b must be a vector'); end
   if (size(b,1) < size(b,2)); b = b'; end
   m = length(b);
%%
%%-----------------------------------------
%% validate blk, At, C
%%-----------------------------------------
   ntotal = zeros(size(blk,1),1);
   for p = 1:size(blk,1)
      if (size(blk{p,2},1) > size(blk{p,2},2))
         blk{p,2} = blk{p,2}';
      end
      pblk = blk(p,:);
      n = sum(pblk{2});
      numblk = length(pblk{2});
      if strcmp(pblk{1},'s');
         m1 = size(At{p,1},2);
         n2 = sum(pblk{2}.*pblk{2});  n22 = sum(pblk{2}.*(pblk{2}+1))/2;
         ntotal(p) = n22;
         if ~all(size(C{p}) == n)
            error('validate: blk and C are not compatible');
         end
         if (norm(C{p}-C{p}',inf) > 1e-13*norm(C{p},inf));
            error('validate: C is not symmetric');
         end
         if (size(At{p,1}) == [m1, n22] & m1~=n22);
            At{p,1} = At{p,1}';
         end
         if (~isempty(At{p,1})) & (size(At{p,1},1) ~= n22)
            error('validate: blk and At not compatible');
         end
         if (nnz(At{p,1}) < spdensity*n22*m1) || (n <= 20) %%2nd condition: 2017-May-08
            if ~issparse(At{p,1}); At{p,1} = sparse(At{p,1}); end
         else
            if issparse(At{p,1}); At{p,1} = full(At{p,1}); end
         end
         if (length(pblk) > 2) %% for low rank constraints
            len = sum(pblk{3});
            if (size(pblk{1,3},2) < size(pblk{1,3},1))
                blk{p,3} = blk{p,3}';
            end
            if any(size(At{p,2})- [n,len])
               error(' low rank structure specified in blk and At not compatible')
            end
            if (length(At(p,:)) > 2)  & ~isempty(At{p,3})
               if all(size(At{p,3},2)-[1,4])
                  error(' low rank structure in At{p,3} not specified correctly')
               end
               if (size(At{p,3},2) == 1)
                  if (size(At{p,3},1) < size(At{p,3},2)); At{p,3} = At{p,3}'; end
                  lenn = length(At{p,3});
                  constrnum = mexexpand(pblk{3},[1:length(pblk{3})]');
                  At{p,3} = [constrnum, [1:lenn]', [1:lenn]', At{p,3}];
               elseif (size(At{p,3},2) == 4)
                  dd = At{p,3};
                  [dummy,idxsort] = sort(dd(:,1));
                  dd = dd(idxsort,:);
                  lenn = size(dd,1);
                  idxD = [0; find(diff(dd(:,1))); lenn];
                  ii = zeros(lenn,1); jj = zeros(lenn,1);
                  ss = [0,cumsum(pblk{3})];
                  for k = 1:length(pblk{3})
                     idx = [idxD(k)+1 : idxD(k+1)];
                     ii(idx) = dd(idx,2)+ss(k); %% convert to cumulative indexing
                     jj(idx) = dd(idx,3)+ss(k);
                  end
                  At{p,3} = [dd(:,1),ii,jj,dd(:,4)];
               end
            else
               constrnum = mexexpand(pblk{3},[1:length(pblk{3})]');
               At{p,3} = [constrnum,  [1:len]', [1:len]', ones(len,1)];
            end
         end
         if (nnz(C{p}) < spdensity*n2) | (numblk > 1);
            if ~issparse(C{p}); C{p} = sparse(C{p}); end;
         else
            if issparse(C{p}); C{p} = full(C{p}); end; %%added: 2017-May-08
         end
      elseif strcmp(pblk{1},'q') | strcmp(pblk{1},'l') ...
             | strcmp(pblk{1},'u');
         ntotal(p) = n;
         if (min(size(C{p})) ~= 1 | max(size(C{p})) ~= n);
            error(['validate: blk and C are not compatible']);
         end;
         if (size(C{p},1) < size(C{p},2)); C{p} = C{p}'; end
         if (size(At{p,1}) == [m, n] & m~=n);
            At{p,1} = At{p,1}';
         end
         if ~all(size(At{p,1}) == [n,m]);
            error('validate: blk and At not compatible');
         end
         if ~issparse(At{p,1});
            At{p,1} = sparse(At{p,1});
         end
         if (nnz(C{p}) < spdensity*n);
            if ~issparse(C{p}); C{p} = sparse(C{p}); end;
         else
            if issparse(C{p}); C{p} = full(C{p}); end;
         end;
      else
         error(' blk: some fields are not specified correctly');
      end
   end
   if (sum(ntotal) < m)
      error(' total dimension of C should be > length(b)');
   end
%%
%%-----------------------------------------
%% problem dimension
%%-----------------------------------------
%%
   dim = zeros(1,4);  nnblk = zeros(1,2);
   for p = 1:size(blk,1)
      pblk = blk(p,:);
      if strcmp(pblk{1},'s')
         dim(1) = dim(1) + sum(pblk{2});
         nnblk(1) = nnblk(1) + length(pblk{2});
         nn(p) = sum(pblk{2});
      elseif strcmp(pblk{1},'q')
         dim(2) = dim(2) + sum(pblk{2});
         nnblk(2) = nnblk(2) + length(pblk{2});
         nn(p) = length(pblk{2});
      elseif strcmp(pblk{1},'l')
         dim(3) = dim(3) + sum(pblk{2});
         nn(p) = sum(pblk{2});
      elseif strcmp(pblk{1},'u')
         dim(4) = dim(4) + sum(pblk{2});
         nn(p) = sum(pblk{2});
      end
   end
%%
%%-----------------------------------------
%% validate parbarrier
%%-----------------------------------------
%%
    if (nargin == 6)
       if ~iscell(parbarrier);
	  if (length(parbarrier) == size(blk,1))
	     tmp = parbarrier;
             clear parbarrier;
	     parbarrier = cell(size(blk,1),1);
	     for p = 1:size(blk,1)
		parbarrier{p} = tmp(p);
             end
          end
       end
       if (size(parbarrier,2) > size(parbarrier,1))
          parbarrier = parbarrier';
       end
       for p = 1:size(blk,1)
          pblk = blk(p,:);
          if (size(parbarrier{p},1) > size(parbarrier{p},2))
             parbarrier{p} = parbarrier{p}';
          end
          len = length(parbarrier{p});
          if strcmp(pblk{1},'s') | strcmp(pblk{1},'q')
             if (len == 1)
                parbarrier{p} = parbarrier{p}*ones(1,length(pblk{2}));
	     elseif (len == 0)
                parbarrier{p} = zeros(1,length(pblk{2}));
	     elseif (len ~= length(pblk{2}))
                error('blk and parbarrier not compatible');
             end
          elseif strcmp(pblk{1},'l')
             if (len == 1)
                parbarrier{p} = parbarrier{p}*ones(1,sum(pblk{2}));
	     elseif (len == 0)
		parbarrier{p} = zeros(1,sum(pblk{2}));
             elseif (len ~= sum(pblk{2}))
                error('blk and parbarrier not compatible');
             end
          elseif strcmp(pblk{1},'u')
             parbarrier{p}= zeros(1,sum(pblk{2}));
          end
       end
    end
%%***********************************************************************


%  thetaj : switching parameter
%  thetaj_bar: steady state value
%  pj : 1 if the parameter is "partitioned"
%  iota1 : 0 if FRWZ perturbation
%  sig : perturbation parameter
%


function h = assignColumns(f, colIdx, g)
%ASSIGNCOLUMNS   Extract columns (or rows) of an array-valued CHEBTECH.
%   G = ASSIGNCOLUMNS(F, COLIDX, G) assigns the columns specified by the row
%   vector COLIDX from the FUN F so that F(:, COLIDX) = G. COLIDX need not be
%   increasing in order or unique, but must contain only integers in the range
%   [1, M] (where F has M columns) and satisfy LENGTH(COLIDX) = SIZE(G, 2) or
%   ISEMPTY(G);
%
% See also EXTRACTCOLUMNS, MAT2CELL.

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

% g is empty - remove columns:
if ( isempty(g) )
    h = f;
    h.coeffs(:,colIdx) = [];
    return
end

% Prolong so that f and g have the same length:
if ( length(f) > length(g) )
    g = prolong(g, length(f));
elseif ( length(g) > length(f) )
    f = prolong(f, length(g));
end

% Assign the columns of h.coeffs:
h = f;
h.coeffs(:, colIdx) = g.coeffs;

% Update ishappy:
h.ishappy = f.ishappy && g.ishappy;

end


function [fval,optimState,idx] = funlogger_vbmc(fun,x,optimState,state,varargin)
%FUNLOGGER_VBMC Call objective function and do some bookkeeping.
%   [~,OPTIMSTATE] = FUNLOGGER_VBMC(FUN,NVARS,OPTIMSTATE,'init') starts logging
%   function FUN with starting point X and optimization struct OPTIMSTATE.
%
%   [~,OPTIMSTATE] = FUNLOGGER_VBMC(FUN,NVARS,OPTIMSTATE,'init',NMAX) stores up
%   to NMAX function values (default NMAX=1e4).
%
%   [FVAL,OPTIMSTATE] = FUNLOGGER_VBMC(FUN,X,OPTIMSTATE,'iter') evaluates
%   function FUN at X with optimization struct OPTIMSTATE, returns function
%   value FVAL. FUN must take a vector input and return a scalar value and,
%   optionally, the (estimated) SD of the returned value (if heteroskedastic
%   noise handling is on).
%
%   [FVAL,OPTIMSTATE] = FUNLOGGER_VBMC(FUN,X,OPTIMSTATE,'single') as 'iter'
%   but does not store function values in the cache.
%
%   [~,OPTIMSTATE] = FUNLOGGER_VBMC(FUN,X,OPTIMSTATE,'done') finalizes
%   stored function values.

%   Luigi Acerbi 2019

fval = [];

% Switch warnings on
for ff = fields(optimState.DefaultWarnings)'
    warning(optimState.DefaultWarnings.(ff{:}).state,optimState.DefaultWarnings.(ff{:}).identifier);
end

switch lower(state)
    case 'init' % Start new function logging session

        nvars = x;

        % Number of stored function values
        if nargin > 4; nmax = varargin{1}; else; nmax = []; end
        if isempty(nmax); nmax = 500; end

        % Read noise level
        noise_flag = optimState.UncertaintyHandlingLevel > 0;

        optimState.funccount = 0;
        optimState.cachecount = 0;

        % Passing empty or new OPTIMSTATE
        if ~isfield(optimState,'X_orig') || isempty(optimState.X_orig)
            optimState.X_orig = NaN(nmax,nvars);
            optimState.y_orig = NaN(nmax,1);
            optimState.X = NaN(nmax,nvars);
            optimState.y = NaN(nmax,1);
            if noise_flag; optimState.S = NaN(nmax,1); end
            optimState.nevals = zeros(nmax,1);
            optimState.Xn = 0;                    % Last filled entry
            optimState.Xmax = nmax;               % Maximum entry index
            optimState.X_flag = false(nmax,1);
            optimState.ymax = -Inf;

        else % Receiving previous evaluations (e.g. from previous run)

            error('Previous function evaluations not supported yet.');

            % Find last evaluated point
            optimState.Xmax = find(~isnan(optimState.Y),1,'last');
            if ~isfield(optimState,'Xn') || isempty(optimState.Xn)
                optimState.Xn = optimState.Xmax;
            end

            % Current cache is smaller than previous one, keep most recent
            % evaluated points
            if optimState.Xmax > nmax
                optimState.X_orig = circshift(optimState.X_orig,-optimState.Xn);
                optimState.X_orig = optimState.X_orig(end-nmax+1:end,:);
                optimState.y_orig = circshift(optimState.y_orig,-optimState.Xn);
                optimState.y_orig = optimState.y_orig(end-nmax+1:nmax,:);
                if noise_flag
                    optimState.S = circshift(optimState.S,-optimState.Xn);
                    optimState.S = optimState.S(end-nmax+1:nmax,:);
                end
                optimState.Xn = 0;
                optimState.Xmax = nmax;
            else
                offset = nmax - size(optimState.X_orig,1);
                optimState.X_orig = [optimState.X_orig; NaN(offset,nvars)];
                optimState.y_orig = [optimState.y_orig; NaN(offset,1)];
                if noise_flag
                    optimState.S = [optimState.S; NaN(offset,1)];
                end
            end
            optimState.X = warpvars_vbmc(optimState.X_orig,'d',optimState.trinfo);
        end
        optimState.funevaltime = NaN(nmax,1);
        optimState.totalfunevaltime = 0;

    case {'iter','single'} % Evaluate function (and store output for 'iter')

        x_orig = warpvars_vbmc(x,'inv',optimState.trinfo);    % Convert back to original space
        % Heteroscedastic noise?
        noise_flag = optimState.UncertaintyHandlingLevel > 0;

        try
            funtime = tic;
            if noise_flag && optimState.UncertaintyHandlingLevel == 2
                [fval_orig,fsd] = fun(x_orig);
            else
                fval_orig = fun(x_orig);
                if noise_flag
                    fsd = 1;
                else
                    fsd = [];
                end
            end
            t = toc(funtime);

            % Check returned function value
            %if isscalar(fval_orig) && isreal(fval_orig) && fval_orig == -Inf
            %    warning(['funlogger_vbmc:InfiniteFuncValue',...
            %        'The function returned -Inf as function value, which should not be allowed. Trying to continue, but results might be affected.'])
            %    fval_orig = log(realmin);
            if ~isscalar(fval_orig) || ~isfinite(fval_orig) || ~isreal(fval_orig)
                error(['funlogger_vbmc:InvalidFuncValue',...
                    'The returned function value must be a finite real-valued scalar (returned value: ' mat2str(fval_orig) ').']);
            end

            % Check returned function SD
            if noise_flag && ...
                    (~isscalar(fsd) || ~isfinite(fsd) || ~isreal(fsd) || fsd <= 0.0)
                error(['funlogger_vbmc:InvalidNoiseValue',...
                    'The returned estimated SD (second function output) must be a finite, positive real-valued scalar (returned SD: ' mat2str(fsd) ').']);
            end

            % Tempered posterior
            if isfield(optimState,'temperature') && ~isempty(optimState.temperature)
                fval_orig = fval_orig / optimState.temperature;
                fsd = fsd / optimState.temperature;
            end

        catch fun_error
            warning(['funlogger_vbmc:FuncError',...
                'Error in executing the logged function ''' func2str(fun) ''' with input: ' mat2str(x)]);
            fprintf('Error identifier: %s\nMessage: %s\n',fun_error.identifier,fun_error.message);
            fprintf('File: %s\n',fun_error.stack(1).file);
            fprintf('Function: %s, line %d.\n',fun_error.stack(1).name,fun_error.stack(1).line);
            rethrow(fun_error);
        end

        % Update function records
        optimState.funccount = optimState.funccount + 1;
        if strcmpi(state, 'iter')
            [optimState,fval,idx] = record(optimState,x_orig,x,fval_orig,t,fsd);
        end
        optimState.totalfunevaltime = optimState.totalfunevaltime + t;

    case {'add'} % Add previously evaluated function

        fval_orig = varargin{1};
        x_orig = warpvars_vbmc(x,'inv',optimState.trinfo);    % Convert back to original space
        % Heteroscedastic noise?
        noise_flag = isfield(optimState,'S');
        if noise_flag
            fsd = varargin{2};
            if isempty(fsd); fsd = 1; end
        else
            fsd = [];
        end

        % Check function value
        if ~isscalar(fval_orig) || ~isfinite(fval_orig) || ~isreal(fval_orig)
            error(['funlogger_vbmc:InvalidFuncValue',...
                'The provided function value must be a finite real-valued scalar (provided value: ' mat2str(fval_orig) ').']);
        end

        % Check returned function SD
        if noise_flag && (~isscalar(fsd) || ~isfinite(fsd) || ~isreal(fsd) || fsd <= 0.0)
            error(['funlogger_vbmc:InvalidNoiseValue',...
                'The provided estimated SD (second function output) must be a finite, positive real-valued scalar (provided SD: ' mat2str(fsd) ').']);
        end

        % Tempered posterior
        if isfield(optimState,'temperature') && ~isempty(optimState.temperature)
            fval_orig = fval_orig / optimState.temperature;
            fsd = fsd / optimState.temperature;
        end

        % Update function records
        optimState.cachecount = optimState.cachecount + 1;
        [optimState,fval,idx] = record(optimState,x_orig,x,fval_orig,0,fsd);

    case 'done' % Finalize stored table

        noise_flag = isfield(optimState,'S');

        optimState.X_orig = optimState.X_orig(1:optimState.Xn,:);
        optimState.y_orig = optimState.y_orig(1:optimState.Xn);
        optimState.X_flag = optimState.X_flag(1:optimState.Xn);
        if noise_flag; optimState.S = optimState.S(1:optimState.Xn); end
        optimState.funevaltime = optimState.funevaltime(1:optimState.Xn);
        optimState.nevals = optimState.nevals(1:optimState.Xn);

        optimState = rmfield(optimState,'X');
        optimState = rmfield(optimState,'y');

    otherwise
        error('funlogger_vbmc:UnknownAction','Unknown FUNLOGGER action.');
end

% Switch warnings off again
for ff = fields(optimState.DefaultWarnings)'
    warning('off',optimState.DefaultWarnings.(ff{:}).identifier);
end

end

%--------------------------------------------------------------------------
function [optimState,fval,idx] = record(optimState,x_orig,x,fval_orig,t,fsd)
%RECORD Record function evaluation.

if nargin < 6; fsd = []; end

duplicate_flag = all(bsxfun(@eq,x,optimState.X),2);

% Tempered posterior
if isfield(optimState,'temperature') && ~isempty(optimState.temperature)
    T = optimState.temperature;
else
    T = 1;
end

if any(duplicate_flag)
    if sum(duplicate_flag) > 1; error('More than one match.'); end
    idx = find(duplicate_flag);
    N = optimState.nevals(idx);

    if ~isempty(fsd)
        tau_n = 1/optimState.S(idx)^2;
        tau_1 = 1/fsd^2;
        optimState.y_orig(idx) = (tau_n*optimState.y_orig(idx) + tau_1*fval_orig)/(tau_n + tau_1);
        optimState.S(idx) = 1/sqrt(tau_n + tau_1);
    else
        optimState.y_orig(idx) = (N*optimState.y_orig(idx) + fval_orig)/(N+1);
    end

    fval = optimState.y_orig(idx) + warpvars_vbmc(x,'logp',optimState.trinfo)/T;
    optimState.y(optimState.Xn) = fval;
    % if ~isempty(fsd); optimState.S(idx) = sqrt((N^2*optimState.S(idx)^2 + fsd^2)/(N+1)^2); end
    optimState.funevaltime(idx) = (N*optimState.funevaltime(idx) + t)/(N+1);
    optimState.nevals(idx) = optimState.nevals(idx) + 1;

else
    optimState.Xn = optimState.Xn+1;
    idx = optimState.Xn;

    % Expand storage by 50% at a time
    if optimState.Xn > optimState.Xmax
        optimState.Xmax = ceil(optimState.Xmax*1.5);
        optimState.X_orig = expand(optimState.X_orig,optimState.Xmax);
        optimState.X = expand(optimState.X,optimState.Xmax);
        optimState.y_orig = expand(optimState.y_orig,optimState.Xmax);
        optimState.y = expand(optimState.y,optimState.Xmax);
        if ~isempty(fsd); optimState.S = expand(optimState.S,optimState.Xmax); end
        optimState.X_flag = expand(optimState.X_flag,optimState.Xmax,false);
        optimState.funevaltime = expand(optimState.funevaltime,optimState.Xmax);
        optimState.nevals = expand(optimState.nevals,optimState.Xmax);
    end

    optimState.X_orig(optimState.Xn,:) = x_orig;
    optimState.X(optimState.Xn,:) = x;
    optimState.y_orig(optimState.Xn) = fval_orig;
    fval = fval_orig + warpvars_vbmc(x,'logp',optimState.trinfo)/T;
    optimState.y(optimState.Xn) = fval;
    if ~isempty(fsd); optimState.S(optimState.Xn) = fsd; end
    optimState.X_flag(optimState.Xn) = true;
    optimState.funevaltime(optimState.Xn) = t;
    optimState.nevals(optimState.Xn) = max(1,optimState.nevals(optimState.Xn) + 1);
end

optimState.ymax = max(optimState.y(optimState.X_flag));
optimState.N = optimState.Xn;  % Number of training inputs
optimState.Neff = sum(optimState.nevals(optimState.X_flag));

end

%--------------------------------------------------------------------------
function x = expand(x,nmax,fill)
%EXPAND Expand storage for given matrix
if nargin < 3 || isempty(fill); fill = NaN; end

if isnan(fill)
    x = [x; NaN(nmax-size(x,1),size(x,2))];
elseif islogical(fill) && fill
    x = [x; true(nmax-size(x,1),size(x,2))];
elseif islogical(fill) && ~fill
    x = [x; false(nmax-size(x,1),size(x,2))];
else
    x = [x; fill*ones(nmax-size(x,1),size(x,2))];
end

end


function varargout = process_spgranger1( varargin )
% PROCESS_SPGRANGER1: Compute the spectral Granger causality between one signal and all the others, in one file.
%
% USAGE:   OutputFiles = process_spgranger1('Run', sProcess, sInputA)

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2014-2020

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % Description the process
    sProcess.Comment     = 'Bivariate Granger causality (spectral) 1xN';
    sProcess.Category    = 'Custom';
    sProcess.SubGroup    = 'Connectivity';
    sProcess.Index       = 665;
    sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/Connectivity';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'data',     'results',  'matrix'};
    sProcess.OutputTypes = {'timefreq', 'timefreq', 'timefreq'};
    sProcess.nInputs     = 1;
    sProcess.nMinFiles   = 1;

    % === CONNECT INPUT
    sProcess = process_corr1n('DefineConnectOptions', sProcess, 0);
    % === REMOVE EVOKED REPONSE
    sProcess.options.removeevoked.Comment = 'Remove evoked response from each trial';
    sProcess.options.removeevoked.Type    = 'checkbox';
    sProcess.options.removeevoked.Value   = 0;
    sProcess.options.removeevoked.Group   = 'input';
    % === DIRECTION
    sProcess.options.dirlabel.Comment  = 'Direction of the causality:';
    sProcess.options.dirlabel.Type     = 'label';
    sProcess.options.direction.Comment = {'From the selected node (out)', 'To the selected node (in)', 'Both (generates two files)'};
    sProcess.options.direction.Type    = 'radio';
    sProcess.options.direction.Value   = 3;
    % === GRANGER ORDER
    sProcess.options.grangerorder.Comment = 'Maximum Granger model order (default=10):';
    sProcess.options.grangerorder.Type    = 'value';
    sProcess.options.grangerorder.Value   = {10, '', 0};
    % === MAX FREQUENCY RESOLUTION
    sProcess.options.maxfreqres.Comment = 'Maximum frequency resolution:';
    sProcess.options.maxfreqres.Type    = 'value';
    sProcess.options.maxfreqres.Value   = {2,'Hz',2};
    % === HIGHEST FREQUENCY OF INTEREST
    sProcess.options.maxfreq.Comment = 'Highest frequency of interest:';
    sProcess.options.maxfreq.Type    = 'value';
    sProcess.options.maxfreq.Value   = {100,'Hz',2};
    % === OUTPUT MODE
    sProcess.options.outputmode.Comment = {'Save individual results (one file per input file)', 'Concatenate input files before processing (one file)', 'Save average connectivity matrix (one file)'};
    sProcess.options.outputmode.Type    = 'radio';
    sProcess.options.outputmode.Value   = 1;
    sProcess.options.outputmode.Group   = 'output';
end

%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess) %#ok<DEFNU>
    Comment = sProcess.Comment;
end

%% ===== RUN =====
function OutputFiles = Run(sProcess, sInputA) %#ok<DEFNU>
    % Input options
    OPTIONS = process_corr1n('GetConnectOptions', sProcess, sInputA);
    if isempty(OPTIONS)
        OutputFiles = {};
        return
    end

    % Metric options
    OPTIONS.Method = 'spgranger';
    OPTIONS.RemoveEvoked = sProcess.options.removeevoked.Value;
    OPTIONS.GrangerOrder = sProcess.options.grangerorder.Value{1};
    OPTIONS.MaxFreqRes   = sProcess.options.maxfreqres.Value{1};
    OPTIONS.MaxFreq      = sProcess.options.maxfreq.Value{1};

    % Computation depends on the direction
    OutputFiles = {};
    if ismember(sProcess.options.direction.Value, [1 3])
        OPTIONS.GrangerDir = 'out';
        OutputFiles = cat(2, OutputFiles, bst_connectivity({sInputA.FileName}, {sInputA.FileName}, OPTIONS));
    end
    if ismember(sProcess.options.direction.Value, [2 3])
        OPTIONS.GrangerDir = 'in';
        OutputFiles = cat(2, OutputFiles, bst_connectivity({sInputA.FileName}, {sInputA.FileName}, OPTIONS));
    end
end


% op_takecoils.m
% Jamie Near, McGill University 2014.
%
% USAGE:
% out=op_takecoils(in,index);
%
% DESCRIPTION:
% Extract the rf coil channels with indices corresponding to the 'index' input
% array.
%
% INPUTS:
% in     = input data in matlab structure format.
% index  = vector indicating the indices of the rf channels you would like to extract.
%
% OUTPUTS:
% out    = Output dataset consisting of averages extracted from the input.

function out=op_takecoils(in,index);

if in.dims.coils==0
    %Can't take average because there are none:
    error('ERROR:  There aren''t multiple coils in this dataset!  Aborting!');
elseif in.dims.coils==1
    %SHOULD NEVER HAPPEN (Time dimension should always be dim=1)
    error('ERROR:  dims.coils==1.  This should never happen!  Aborting!');
elseif in.dims.coils==2
    fids=in.fids(:,index,:,:,:);
elseif in.dims.coils==3;
    fids=in.fids(:,:,index,:,:);
elseif in.dims.coils==4;
    fids=in.fids(:,:,:,index,:);
elseif in.dims.coils==5
    fids=in.fids(:,:,:,:,index);
end

fids=squeeze(fids);

%re-calculate Specs using fft
specs=fftshift(ifft(fids,[],in.dims.t),in.dims.t);

%change the dims variables
dims.t=in.dims.t;
if length(index)==1
    dims.coils=0;
    if in.dims.averages > in.dims.coils
        dims.averages=in.dims.averages-1;
    else
        dims.averages=in.dims.averages;
    end
    if in.dims.subSpecs > in.dims.coils
        dims.subSpecs=in.dims.subSpecs-1;
    else
        dims.subSpecs=in.dims.subSpecs;
    end
    if in.dims.extras > in.dims.coils
        dims.extras=in.dims.extras-1
    else
        dims.extras=in.dims.extras;
    end
elseif length(index)>1
    dims.coils=in.dims.coils;
    dims.averages=in.dims.averages;
    dims.subSpecs=in.dims.subSpecs;
    dims.extras=in.dims.extras;
end

%re-calculate the sz variable
sz=size(fids);

%FILLING IN DATA STRUCTURE
out=in;
out.fids=fids;
out.specs=specs;
out.sz=sz;
out.dims=dims;

%FILLING IN THE FLAGS
out.flags=in.flags;
out.flags.writtentostruct=1;
if length(index)<2
    out.flags.addedrcvrs=1;
end


classdef KTUEAMapFile

% UEAMAPFILE -- Defines a class that contains information on a UEA
% electrode array using CMP files provided by Blackrock Microsystems.
%
% To load a CMP file type 'MapName = UEAMapFile' where MapName is the name
% of the variable that will be created and will contain the map class.
%
% Example: myArrayMap = UEAMapFile;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% METHODS:
%
% There are several available methods for mapfiles. Here's a list and a
% description of what they perform.
%
% Electrode2Channel(Electrode):
%   Will return the Channel number corresponding to a passed Electrode.
%
% Channel2Electrode(Channel):
%   Will return the Electrode number corresponding to a passed Channel.
%
% GetChannelBankID(Channel):
%   Returns the BankID for a passed Channel.
%
% GetChannelPin(Channel):
%   Returns the Pin for a passed Channel.
%
% GetChannelLabel(Channel):
%   Returns the Label for a passed Channel.
%
% GenerateChannelSubplot(Channel):
%   Returns a subplot handle for the passed Channel to be used in plotting
%   UEA-like maps.
%
% GenerateChannelSubplotNames(Channel):
%   Plots the names of channels and electrodes on the subplot corresponding
%   to the passed Channel.
%
% GetChannelColumnRow(Channel):
%   Returns the Column and Row positions of the passed number that is used
%   to plot UEA-like maps.
%
% PlotCMP:
%   Will plot a map of the CMP Map with all the electrode and channel
%   names.
%
%   Kian Torab
%   Blackrock Microsystems
%   ktorab@blackrockmicro.com
%
%   Version 1.6.1.0

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Version History
%
% 1.0.0.0:
%   - Initial release.
%
% 1.6.1.0:
%   - Minor bug fix.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%
    properties (SetAccess = private)
        ElecNum
        ChanNum
        Column
        Row
        Bank
        Pin
        Label
        pathHandle
        fileHandle
    end
    methods (Hidden)
        function obj = KTUEAMapFile(fileName)
            if ~exist('fileName', 'var')
                if exist('getFile.m', 'file') == 2
                    [obj.fileHandle obj.pathHandle] = getFile('*.cmp', 'Open a CMP Mapfile...');
                else
                    [obj.fileHandle obj.pathHandle] = uigetfile('*.cmp', 'Open a CMP Mapfile...');
                end
                if ~obj.fileHandle
                    disp('No file was selected.');
                    return;
                end
                mapfileDataCell = importdata([obj.pathHandle obj.fileHandle], ' ', 200);
            else
                mapfileDataCell = importdata(fileName, ' ', 200);
            end
            mapfileDataCellParsed = regexp(mapfileDataCell, '\t', 'split');
            if size(mapfileDataCellParsed, 2) == 1
                mapfileDataCellParsed = regexp(mapfileDataCell, '\s+', 'split');
            end
            lastJunkIDX = 1;
            while 1
                if size(mapfileDataCellParsed{lastJunkIDX}, 2) == 6 || size(mapfileDataCellParsed{lastJunkIDX}, 2) == 5
                    if ~isempty(str2num(mapfileDataCellParsed{lastJunkIDX}{1})) && ...
                    ~isempty(str2num(mapfileDataCellParsed{lastJunkIDX}{2})) && ...
                    ~isempty(str2num(mapfileDataCellParsed{lastJunkIDX}{4}))
                    lastJunkIDX = lastJunkIDX - 1;
                        break;
                    end
                end
                lastJunkIDX = lastJunkIDX + 1;
            end
            mapfileDataCellParsed(1:lastJunkIDX) = [];
            for i = 1:size(mapfileDataCellParsed, 1)
                if ~all(isspace(mapfileDataCellParsed{i}))
                    obj.Column(i) = str2num(mapfileDataCellParsed{i,:}{1});
                    obj.Row(i)    = str2num(mapfileDataCellParsed{i,:}{2});
                    obj.Bank(i)   = mapfileDataCellParsed{i,:}{3}-'@';
                    obj.Pin(i)    = str2num(mapfileDataCellParsed{i,:}{4});
                    ElectNum      = str2num(mapfileDataCellParsed{i,:}{5}(5:end));
                    if isempty(ElectNum)
                        obj.ElecNum(i) = str2num(mapfileDataCellParsed{i,:}{5}(2:end-4));
                    else
                        obj.ElecNum(i) = ElectNum;
                    end
                    obj.ChanNum(i)  = (obj.Bank(i) - 1) * 32 + obj.Pin(i);
                    obj.Label{i}    = mapfileDataCellParsed{i,:}{5};
                end
            end
        end
    end
    methods
        function validFlag = isValid(obj)
            if ~obj.getFilename
                validFlag = 0;
            else
                validFlag = 1;
            end
        end
        function FilePath = getPathName(obj)
            FilePath = obj.pathHandle;
        end
        function FileName = getFilename(obj)
            FileName = obj.fileHandle;
        end
        function Channel = Electrode2Channel(obj, Electrode)
            if ~exist('Electrode', 'var'); disp('Electrode is a required input. Refer to help for more information.'); return; end;
            if isempty(obj.ChanNum(obj.ElecNum == Electrode(1)))
                disp('Electrode number is invalid.');
                Channel = [];
                return;
            end
            for ElecIDX = 1:length(Electrode)
                Channel(ElecIDX) = obj.ChanNum(obj.ElecNum == Electrode(ElecIDX));
            end
        end
        function Electrode = Channel2Electrode(obj, Channel)
            if isempty(obj.ElecNum(obj.ChanNum == Channel(1)))
                disp('Channel number is invalid.');
                Electrode = [];
                return;
            end
            if ~exist('Channel', 'var'); disp('Channel is a required input. Refer to help for more information.'); return; end;
            for ChanIDX = 1:length(Channel)
                Electrode(ChanIDX) = obj.ElecNum(obj.ChanNum == Channel(ChanIDX));
            end
        end
        function BankID = getChannelBankID(obj, Channel)
            BankID = obj.Bank(obj.ChanNum == Channel);
        end
        function Label = getChannelLabel(obj, Channel)
            Label = char(obj.Label{obj.ChanNum == Channel});
        end
        function Pin = getChannelPin(obj, Channel)
            Pin = obj.Pin(obj.ChanNum == Channel);
        end
        function spHandle = GenerateChannelSubplot(obj, Channel)
            if ~exist('Channel', 'var'); disp('Channel is a required input. Refer to help for more information.'); return; end;
            [x, y] = getChannelColumnRow(obj, Channel);
            spHandle=subplot('position', [x/10+0.004, y/10+0.004, 1/10-0.004, 1/10-0.004]);
            axis off;
            box on;
            set(spHandle,'XTickLabel', []);
            set(spHandle,'YTickLabel', []);
            %%
        end
        function GenerateChannelSubplotNames(obj, Channel, fColor)
            if ~exist('Channel', 'var'); disp('Channel is a required input. Refer to help for more information.'); return; end;
            if ~exist('fColor', 'var'); fColor  = [1,1,1]; end
            Electrode = Channel2Electrode(obj, Channel);
            text(0.13, 0.23, ['elec ', num2str(Electrode)], 'Color', fColor, 'FontSize', 8);
            text(0.13, 0.10, ['chan ', num2str(Channel)], 'Color', fColor, 'FontSize', 8);
        end
        function [x, y] = getChannelColumnRow(obj, Channel)
            if ~exist('Channel', 'var'); disp('Channel is a required input. Refer to help for more information.'); return; end;
            x = obj.Column(obj.ChanNum == Channel);
            y = obj.Row(obj.ChanNum == Channel);
        end
        function PlotCMP(obj)
            figure;
            for Channel = 1:96
                GenerateChannelSubplot(obj, Channel);
                GenerateChannelSubplotNames(obj, Channel, [0,0,0]);
            end
        end
        function setAxisBackgroundColor(~, curColor)
            if isa(curColor, 'double') && (length(curColor) == 3)
                if all(curColor <= 1) && all(curColor >= 0)
                    set(gca, 'Color', curColor);
                else
                    disp('The color values have to be between 0 and 1.');
                end
            elseif isa(curColor, 'char')
                try
                	set(gca, 'Color', curColor);
                catch
                    disp('Color is not valid. Type ''doc color'' for more information.');
                end
            else
                disp('The input needs to be a valid color input.');
                disp('A valid color input is a vector of length 3 of values between 0 and 1.');
            end
        end
        function setXAxisColor(~, curColor)
            if isa(curColor, 'double') && (length(curColor) == 3)
                if all(curColor <= 1) && all(curColor >= 0)
                    set(gca, 'XColor', curColor);
                else
                    disp('The color values have to be between 0 and 1.');
                end
            elseif isa(curColor, 'char')
                try
                    set(gca, 'XColor', curColor);
                catch
                    disp('Color is not valid. Type ''doc color'' for more information.');
                end
            else
                disp('The input needs to be a valid color input.');
                disp('A valid color input is a vector of length 3 of values between 0 and 1.');
            end
        end
        function setYAxisColor(~, curColor)
            if isa(curColor, 'double') && (length(curColor) == 3)
                if all(curColor <= 1) && all(curColor >= 0)
                    set(gca, 'YColor', curColor);
                else
                    disp('The color values have to be between 0 and 1.');
                end
            elseif isa(curColor, 'char')
                try
                    set(gca, 'YColor', curColor);
                catch
                    disp('Color is not valid. Type ''doc color'' for more information.');
                end
            else
                disp('The input needs to be a valid color input.');
                disp('A valid color input is a vector of length 3 of values between 0 and 1.');
            end
        end
        function setAxesColor(~, curColor)
            if isa(curColor, 'double') && (length(curColor) == 3)
                if all(curColor <= 1) && all(curColor >= 0)
                    set(gca, 'YColor', curColor);
                    set(gca, 'XColor', curColor);
                else
                    disp('The color values have to be between 0 and 1.');
                end
            elseif isa(curColor, 'char')
                try
                    set(gca, 'YColor', curColor);
                    set(gca, 'XColor', curColor);
                catch
                    disp('Color is not valid. Type ''doc color'' for more information.');
                end
            else
                disp('The input needs to be a valid color input.');
                disp('A valid color input is a vector of length 3 of values between 0 and 1.');
            end
        end
    end
end


classdef TestLinearPolar
    %TestLinearPolar

    methods (Static)
        function test_1
            img = imread(fullfile(mexopencv.root(),'test','fruits.jpg'));
            dst = cv.linearPolar(img, [100 100], 500);
            validateattributes(dst, {class(img)}, {'size',size(img)});
        end

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

end


function importfile(fileToRead1)
%IMPORTFILE(FILETOREAD1)
%  Imports data from the specified file
%  FILETOREAD1:  file to read

%  Auto-generated by MATLAB on 08-Mar-2011 12:24:52
%  Copyright 2011 The MathWorks, Inc.

% Import the file
sheetName='Sheet1';
[numbers, strings, raw] = xlsread(fileToRead1, sheetName);
if ~isempty(numbers)
    newData1.data =  numbers;
end

if ~isempty(strings) && ~isempty(numbers)
    [strRows, strCols] = size(strings);
    [numRows, numCols] = size(numbers);
    likelyRow = size(raw,1) - numRows;
    % Break the data up into a new structure with one field per column.
    if strCols == numCols && likelyRow > 0 && strRows >= likelyRow
        newData1.colheaders = strings(likelyRow, :);
    end
end

% Create new variables in the base workspace from those fields.
for i = 1:size(newData1.colheaders, 2)
    assignin('base', genvarname(newData1.colheaders{i}), newData1.data(:,i));
end