% setup.m
% run this file to set up matlab path etc.
% you may need to modify this depending on how you installed the toolbox
% so this should be considered simply a "guide" not a robust script.

if ~exist('irtdir', 'var')
	disp('The variable "irtdir" is not set, so trying default, assuming')
	disp('that you launched matlab from the irt install directory.')
	disp('You may need to edit setup.m or adjust your path otherwise.')

%	irtdir = pwd; % the default is to assume launch from irt directory

	% default is to look for directory where this setup.m is installed!
	irtdir = which('setup'); % find setup.m
	[irtdir, ~] = fileparts(irtdir);

	disp(['Assuming you installed irt in directory "' irtdir '".'])

%	irtdir = '~fessler/l/src/matlab/alg/'; % where you install this package
%	irtdir = '~fessler/l/web/irt/'; % where you install this package
end

if ~exist(irtdir, 'dir')
	disp(sprintf('The directory "%s" does not exist', irtdir))
	error(sprintf('you need to edit %s to change default path', mfilename))
end

if irtdir(end) ~= filesep % make sure there is a '/' at end of directory
	irtdir = [irtdir filesep];
end

list = {...
'align', ...		% image registration
'align/mex', ...	% image registration mex files
'blob', ...		% blob (KB) basis
'ct', ...		% x-ray CT (polyenergetic) recon
'data', ...		% example data
'data/downloads', ...		% example data
'emission', ...		% emission image reconstruction
'example', ...		% example applications
'fbp', ...		% FBP (filtered backprojection) code
'general', ...		% generic image reconstruction
'graph', ...		% graphics routines
'mri', ...		% MRI reconstruction
'mri/fieldmap', ...	% MRI B0 field map estimation
'mri-rf/yip-spsp', ...	% MRI RF pulse design
'mri/arch',... % MRI examples
'nufft', ...		% nonuniform FFT (for a fast projector)
'nufft/table', ...	% mex files for NUFFT
'penalty', ...		% regularizing penalty functions
'systems', ...		% system "matrices"
'systems/tests', ...	% tests of systems
'transmission', ...	% transmission image reconstruction
'utilities', ...	% various utility functions
'wls', ...		% weighted least-squares (WLS) estimates
'um', ...		% extra directories for UM users only
'um/lustig-poisson-disk'
};
%'mri/recon', ...	% MRI reconstruction - old

for ii=1:numel(list)
	tmp = [irtdir list{ii}];
	if exist(tmp, 'dir'), addpath(tmp), end
end

% Set up path to mex files, possibly depending on matlab version.
% Fortunately it seems that the v6 files also run on v7.
% Unfortunately, it seems that sometimes compiling on one version
% e.g., 7.3 and running on earlier 7.0 won't work.
% If you have mex problems, comment out the following line.
% Much of the toolbox will work without mex, just slower.
addpath([irtdir 'mex/v7']);

% do not add the paths below if you are using Matlab!
if ir_is_octave
	addpath([irtdir 'octave']); % extra stuff for octave only!
elseif isempty(which('dbstack')) % for freemat only!
	addpath([irtdir 'freemat']); % extra stuff for freemat only!
end

% check to see if path setup worked by looking for im() routine.
if strcmp([irtdir 'graph' filesep 'im.m'], which('im'))
	disp('Path setup for irt appears to have succeeded.')
	clear list ii irtdir tmp
else
	disp('Path setup for irt may have failed.')
end


function bytesize(in, fid)
% BYTESIZE writes the memory usage of the provide variable to the given file
% identifier. Output is written to screen if fid is 1, empty or not provided.

if nargin == 1 || isempty(fid)
    fid = 1;
end

s = whos('in');
fprintf(fid,[Bytes2str(s.bytes) '\n']);
end

function str = Bytes2str(NumBytes)
% BYTES2STR Private function to take integer bytes and convert it to
% scale-appropriate size.

scale = floor(log(NumBytes)/log(1024));
switch scale
    case 0
        str = [sprintf('%.0f',NumBytes) ' b'];
    case 1
        str = [sprintf('%.2f',NumBytes/(1024)) ' kb'];
    case 2
        str = [sprintf('%.2f',NumBytes/(1024^2)) ' Mb'];
    case 3
        str = [sprintf('%.2f',NumBytes/(1024^3)) ' Gb'];
    case 4
        str = [sprintf('%.2f',NumBytes/(1024^4)) ' Tb'];
    case -inf
        % Size occasionally returned as zero (eg some Java objects).
        str = 'Not Available';
    otherwise
       str = 'Over a petabyte!!!';
end
end


%kcmindist_printsig 'Print a Minimum Distance Signature '
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros cmindist_printsig.pane file
%
% Parameters:
% InputFile: isig 'Input Signature', required: 'input signature file'
% MultiChoice: omode 'Output Mode', default: 1: 'output mode toggle'
%    Choices are:
%   1: 'Text'
%   2: 'LaTeX'
%   3: 'HTML'
%   4: 'CSV'
% OutputFile: o 'Output', optional: 'output signature info'
%
% Example: o = kcmindist_printsig(isig, {'isig','';'omode',1;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% cmindist_printsig - Print a Minimum Distance Signature
%
%  DESCRIPTION
% This operator prints out the contents of a Minimum Distance Signature file created with "cmindist_signature". It expects a valid Minimum Distance signature file in the parameter [-isig], so its input must be either the output of a \fIcmindist_signature\fP or the output of \fIkappend\fP which appended several signatures together in the time dimension. Its output can be formatted so it can be used in reports, etc. and will be redirected to kstdout unless a file name is passed with the parameter [-o].
% The output of this program can be in four formats, depending on the value of the parameter [-omode] :
% The Text (ASCII) format option ([-omode 1]) formats the output so it can be viewed with simple text editors or in kstdout.
% The LaTeX format option ([-omode 2]) formats the output so it can be included in a LaTeX file with the \\input command.
% The HTML format option ([-omode 3]) formats the output in a HTML table so it can be read into a HTML file.
% The CSV format option ([-omode 4]) formats the output in a Comma-delimited format so it can be read by spreadsheets, etc.
%
%
%
%  EXAMPLES
% All examples for the Classify toolbox are listed on the Classify Toolbox Manual. For an example of this routine, please see the example workspace Classify:workspaces:MINDIST-Signatures.
%
%  "SEE ALSO"
% cmindist_signature
%
%  RESTRICTIONS
% Expect the input file to be a valid signature file for the Minimum Distance classifier.
%
%  REFERENCES
% All references for the Classify toolbox are listed on the Classify Toolbox Manual.
%
%  COPYRIGHT
% Copyright (C) 1997 Rafael Santos. Khoros (C) Khoral Research, Inc.
%

function varargout = kcmindist_printsig(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kcmindist_printsig(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'isig', '__input';'omode', 1;'o', '__output'};
maxval={0,0,1};
minval={0,0,1};
istoggle=[0,0,1];
was_set=istoggle * 0;
paramtype={'InputFile','MultiChoice','OutputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=0; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(1,1);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
[varargout{:}]=callKhoros([w 'cmindist_printsig"  '],Inputs,narglist);


function tests = test_checkcode
% Test for possible problems in all of MATLAB code files
%__________________________________________________________________________
% Copyright (C) 2017 Wellcome Trust Centre for Neuroimaging

% $Id: test_checkcode.m 7111 2017-06-16 09:01:09Z guillaume $

tests = functiontests(localfunctions);

function test_checkcode_all(testCase)
testCase.assumeTrue(strcmp(spm_check_version,'matlab'));

f = cellstr(spm_select('FPlistRec',spm('Dir'),'\.m$')); % discard external?
s = checkcode(f,'-id');
checked = false(size(s));
for i=1:numel(s)
    for j=1:numel(s{i})
        if isequal(s{i}(j).id,'SYNER') % Syntax error
            checked(i) = true;
        end
    end
end
testCase.verifyFalse(any(checked));
if any(checked)
    fprintf('Problematic files are:\n');
    disp(f(checked));
end

function t_e_s_t_analyzeCodeCompatibility(testCase) % disabled for now
testCase.assumeFalse(~strcmp(spm_check_version,'matlab') | ...
    spm_check_version('matlab','9.3') < 0);

import matlab.unittest.constraints.*
r = analyzeCodeCompatibility(spm('Dir'),'IncludeSubfolders',true); % discard external?
idx = find(r.Recommendations.Severity == 'Error');
testCase.verifyThat(numel(idx), IsEqualTo(0));
for i=1:numel(idx)
    fprintf('%s:\n',r.Recommendations.File(idx(i)));
    fprintf('  %s\n',r.Recommendations.Description(idx(i)));
end


function [new_clu log] =renumberclu(clu,log)
% re-orders clu to start from index 1 and iterate through the number of
% clusters

% rewritten by David Tingley, 2017
new_clu = zeros(length(clu),1);

cluster_names = unique(clu);
for i=1:length(cluster_names)
    if cluster_names(i) ~= 0  % keep cluster 0 (noise) as 0
    new_clu(find(clu==cluster_names(i))) = i+2;
     log = [log sprintf('%d -> %d; reordering clusters\n',cluster_names(i),i+2)];
    end
end


function grf_io_test02 ( )

%*****************************************************************************80
%
%% GRF_IO_TEST02 tests GRF_HEADER_READ and GRF_DATA_READ.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 January 2009
%
%  Author:
%
%    John Burkardt
%
  input_filename = 'coxeter.grf';

  fprintf ( 1, '\n' );
  fprintf ( 1, 'GRF_IO_TEST02\n' );
  fprintf ( 1, '  GRF_HEADER_READ reads the header of a GRF file.\n' );
  fprintf ( 1, '  GRF_DATA_READ reads the data of a GRF file.\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Reading the GRF file "%s".\n', input_filename );

  [ node_num, edge_num ] = grf_header_read ( input_filename );

  grf_header_print ( node_num, edge_num );

  [ edge_pointer, edge_data, xy ] = grf_data_read ( input_filename, ...
    node_num, edge_num );

  grf_data_print ( node_num, edge_num, edge_pointer, edge_data, xy );

  return
end


function plot(obj, varargin)
% PLOT Plot of point cloud.
% ------------------------------------------------------------------------------
% DESCRIPTION/NOTES
% * Only active points are visualized.
% ------------------------------------------------------------------------------
% INPUT
% 1 ['Color', color]
%   Color of the points. The following choices are possible:
%
%     * Unicolor (format = 'ColorName'):
%       A single color is used for all points, e.g. 'yellow'. For possible
%       values, look for 'ColorSpec' in the documentation.
%
%     * Attribute (format = 'A.AttributeName'):
%       Coloring according to an attribute, e.g. 'A.roughness'.
%       Additionally, the following choices are possible:
%         * 'A.x'  : coloring according to x coordinate
%         * 'A.y'  : coloring according to y coordinate
%         * 'A.z'  : coloring according to z coordinate
%         * 'A.rgb': true color plot using the attributes r, g and b.
%
% 2 ['MarkerSize', markerSize]
%   Marker size of points.
%
% 3 ['MaxPoints', maxPoints]
%   Maximum number of points to plot. If the point cloud contains more than
%   maxPoi points, the points for plotting are randomly sampled among all
%   points.
%
% 4 ['ColormapName', colormapName]
%   Name of colormap defined as char (e.g. 'jet'). For possible values, look for
%   'colormap' in the documentation. Additionally, for visualization of classes,
%   the colormap 'classpal' can be used.
%   (This parameter is only considered for attribute dependent plots.)
%
% 5 ['CAxisLim', cAxisLim]
%   Limits of colorbar defined as vector with 2 elements.
%   (This parameter is only considered for attribute dependent plots.)
% ------------------------------------------------------------------------------
% EXAMPLES
% 1 Import a point cloud and plot points according to z coordinate (default).
%   pc = pointCloud('Lion.xyz');
%   pc.plot;
%
% 2 Unicolor plot.
%   pc = pointCloud('Lion.xyz');
%   pc.plot('Color', 'red');
%
% 3 Plot all points of a point cloud.
%   pc = pointCloud('Lion.xyz');
%   pc.plot('MaxPoints', Inf);
%
% 4 Plot only 1000 points of a point cloud with increased point size.
%   pc = pointCloud('Lion.xyz');
%   pc.plot('MaxPoints', 1000, 'MarkerSize', 10);
%
% 5 Plot points according to true color attributes r, g and b.
%   pc = pointCloud('Gieszkanne.xyz', 'Attributes', {'r' 'g' 'b'});
%   pc.plot('Color', 'A.rgb', 'MarkerSize', 5);
%
% 6 Plot points colored by an imported attribute.
%   pc = pointCloud('Lion.xyz', 'Attributes', {'nx' 'ny' 'nz' 'roughness'});
%   % Note: the imported attributes are saved as fields in the structure pc.A,
%   % e.g. the roughness is saved in pc.A.roughness.
%   pc.plot('Color', 'A.roughness');
% ------------------------------------------------------------------------------
% philipp.glira@gmail.com
% ------------------------------------------------------------------------------

% Start
[hFig, idxPC, firstCall] = plot_start;

if firstCall

    % Save colors to figure
    plot_saveColors(hFig)

    % Save default options to figure
    plot_saveOptions(hFig)

    % Create toolbar
    plot_createToolbar(hFig)

    % Set properties of figure
    plot_setFigureProperties(hFig)

end

% Save PC data to figure
plot_savePC(hFig, obj, idxPC); clear obj

% Create menu
plot_createMenu(hFig, firstCall, idxPC)

% Set parameters and plot
plot_setPrmAndPlot(hFig, idxPC, varargin{:})

% Temporary solution
if firstCall, set(gca, 'Visible', 'on'); end

end


function F = times(F, G)
%.*   Pointwise multiplication of two CHEBFUN3V objects.
%   F.*G computes pointwise, componentwise multiplication of two
%   CHEBFUN3V objects, a CHEBFUN3V and a CHEBFUN3, or a CHEBFUN3V
%   and a double.

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

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

if ( ~isa(F, 'chebfun3v') )
    F = times(G, F);
    return
end

nF = F.nComponents;

if ( isa(G, 'double') )             % CHEBFUN3V .* double
    if ( numel(G) == 1 )            % CHEBFUN3V .* scalar
        scalar = G;
        for jj = 1:nF
            F.components{jj} = times(F.components{jj}, scalar);
        end
    elseif ( (size(G, 1) == nF) || ( F.isTransposed && (size(G, 2) == nF) ) )
                                    % CHEBFUN3V .* vector
        for jj = 1 : nF
            F.components{jj} = times(F.components{jj}, G(jj));
        end
    else
        error('CHEBFUN:CHEBFUN3V:times:double', ...
            'CHEBFUN3V and double size mismatch.');
    end

elseif ( isa(G, 'chebfun3v') )      % CHEBFUN3V .* CHEBFUN3V
    nG = G.nComponents;
    if ( nF ~= nG )
         error('CHEBFUN:CHEBFUN3V:times:numel', ...
             'CHEBFUN3V components mismatch.');
    end
    for jj = 1:nF
        F.components{jj} = times(F.components{jj}, G.components{jj});
    end

elseif ( isa(G, 'chebfun3') )       % CHEBFUN3V .* CHEBFUN3
    for jj = 1 : nF
        F.components{jj} = times(F.components{jj}, G);
    end

else  % error
    error('CHEBFUN:CHEBFUN3V:times:inputs', 'Unrecognized input arguments.');
end

end


classdef TestEMDL1
    %TestEMDL1

    methods (Static)
        function test_1
            sig1 = randn(20,1);
            sig2 = randn(20,1);
            d = cv.EMDL1(sig1, sig2);
            validateattributes(d, {'numeric'}, {'scalar', 'real'});
        end

        function test_2
            sig1 = randn(20,1);
            d = cv.EMDL1(sig1, sig1);
            validateattributes(d, {'numeric'}, {'scalar', 'real'});
        end

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

end


function ht= axis_yTickLabel(label_list, varargin)
%AXIS_YTICKLABEL - Add y-ticklabels to the current axis
%
%Synopsis:
% H= axis_yTickLabel(LABEL_LIST, <OPT>)
%
%Input:
% LABEL_LIST: string (labels separated by '|') or cell array of strings
% OPT: struct or property/value list of optional properties:
%  .HPos  - horizontal position
%  .YTick - position of yticks. If not provided, get(gca,'YTick') is used.
%  .Color - font color in RGB format. Maybe an [nLabels 3] matrix of color
%           codes
%  .HorizontalAlignment, .VerticalAlignment
%
%Output:
% H: handle to the text object(s)
%
%Note:
% The position of the text object is defined *within* the axis. So you should
% set XLimMode and YLimMode to 'manual' before calling AXIS_TITLE.

% Author(s): Benjamin Blankertz

props= {'YTick'                []       'DOUBLE[-]'
        'HPos'                 -0.03    'DOUBLE[1]'
        'Color'                [0 0 0]  'DOUBLE[- 3]'
        'HorizontalAlignment' 'right'   'CHAR(left center right)'
        'VerticalAlignment'   'middle'  'CHAR(top cap middle baseline bottom)'};

opt= opt_proplistToStruct(varargin{:});
[opt, isdefault]= opt_setDefaults(opt, props);

if ~iscell(label_list),
  if ismember('|',label_list,'legacy'),
    label_str= label_list;
    idx= find(label_str=='|');
    idx= [0, idx, length(label_str)+1];
    nLab= length(idx)-1;
    label_list= cell(1,nLab);
    for ii= 1:nLab,
      label_list{ii}= label_str(idx(ii)+1:idx(ii+1)-1);
    end
  else
    label_list= {label_list};
  end
end
nLab= length(label_list);
if isdefault.YTick,
  opt.YTick= get(gca, 'YTick');
end
if length(opt.YTick)~=nLab,
  error('number of labels must match number of xticks');
end
if nLab>1 && size(opt.Color,1)==1,
  opt.Color= repmat(opt.Color, [nLab 1]);
end

opt_fn= fieldnames(opt);
ifp= find(ismember(opt_fn, {'HorizontalAlignment','VerticalAlignment'},'legacy'));
ifp= cat(1, ifp, strmatch('Font', opt_fn));
font_opt= struct_copyFields(opt, opt_fn(ifp));
font_pl= opt_structToProplist(font_opt);

XLim= get(gca, 'XLim');
xx= XLim(1) + opt.HPos*diff(XLim);
yy= opt.YTick;

for tt= 1:nLab,
  ht(tt)= text(xx, yy(tt), label_list{tt});
  set(ht(tt), font_pl{:}, 'Color',opt.Color(tt,:));
end


function varargout = inviscidChannelGUI(varargin)
% INVISCIDCHANNELGUI MATLAB code for inviscidChannelGUI.fig
%      INVISCIDCHANNELGUI, by itself, creates a new INVISCIDCHANNELGUI or raises the existing
%      singleton*.
%
%      H = INVISCIDCHANNELGUI returns the handle to a new INVISCIDCHANNELGUI or the handle to
%      the existing singleton*.
%
%      INVISCIDCHANNELGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in INVISCIDCHANNELGUI.M with the given input arguments.
%
%      INVISCIDCHANNELGUI('Property','Value',...) creates a new INVISCIDCHANNELGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before inviscidChannelGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to inviscidChannelGUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help inviscidChannelGUI

% Last Modified by GUIDE v2.5 20-Feb-2013 10:37:02

% Copyright 2013 The MathWorks, Inc.

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @inviscidChannelGUI_OpeningFcn, ...
    'gui_OutputFcn',  @inviscidChannelGUI_OutputFcn, ...
    'gui_LayoutFcn',  [] , ...
    'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before inviscidChannelGUI is made visible.
function inviscidChannelGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to inviscidChannelGUI (see VARARGIN)

% Initialize the GUI layout
sketchplot(gcf);
set(get(handles.plotstreamline,'XLabel'),'String','x (m)')
set(get(handles.plotstreamline,'YLabel'),'String','y (m)')
set(get(handles.plotstreamline,'Title'),'String','Normalized Stream Function \Psi')
set(get(handles.plotvector,'XLabel'),'String','x (m)')
set(get(handles.plotvector,'YLabel'),'String','y (m)')
set(get(handles.plotvector,'Title'),'String','Velocity Profile')
% Create the help button on toolbar
[X, map] = imread(fullfile(...
    matlabroot,'toolbox','matlab','icons','csh_icon.gif'));
icon = ind2rgb(X,map);
uipushtool(handles.uitoolbar1,'CData',icon,...
    'TooltipString','Help',...
    'ClickedCallback',@AppHelp);

% Choose default command line output for inviscidChannelGUI
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes inviscidChannelGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = inviscidChannelGUI_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in start.
function start_Callback(hObject, eventdata, handles)
% hObject    handle to start (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
inviscidchannel(handles);

function handles = getpara(handles)
% Get user input parameters from the GUI
handles.para.D1 = str2double(get(handles.D1,'String'));
handles.para.D2 = str2double(get(handles.D2,'String'));
handles.para.L1 = str2double(get(handles.L1,'String'));
handles.para.L2 = str2double(get(handles.L2,'String'));
handles.para.U1 = str2double(get(handles.U1,'String'));
handles.para.nx = str2double(get(handles.nx,'String'));
handles.para.ny = str2double(get(handles.ny,'String'));
handles.para.nmax = str2double(get(handles.nmax,'String'));
cla(handles.plotstreamline),cla(handles.plotvector),
axis([handles.plotstreamline handles.plotvector], [0 handles.para.L1+handles.para.L2 0 max(handles.para.D1,handles.para.D2)]),
% Draw the channel shape according to input
if handles.para.D1 < handles.para.D2 % converging channel
    cornerposition = [0 handles.para.D1 handles.para.L1 handles.para.D2-handles.para.D1];
elseif handles.para.D1 > handles.para.D2 % diverging channel
    cornerposition = [handles.para.L1 handles.para.D2 handles.para.L2 handles.para.D1-handles.para.D2];
else
    cornerposition = [0 handles.para.D1 1 1]; % straight channel
end
rectangle('Parent',handles.plotstreamline,'Position',cornerposition,'FaceColor',[0.94 0.94 0.94])
rectangle('Parent',handles.plotvector,'Position',cornerposition,'FaceColor',[0.94 0.94 0.94])

function inviscidchannel(handles)
%% Initialization
% get input parameters
handles = getpara(handles);
% store input parameters with shorter names
D1 = handles.para.D1;
D2 = handles.para.D2;
L1 = handles.para.L1;
L2 = handles.para.L2;
U1 = handles.para.U1;
nx = handles.para.nx;
ny = handles.para.ny;
nmax = handles.para.nmax;
% compute grid length
dx = (L1+L2)/(nx-1);
dy = max(D1,D2)/(ny-1);
% nondimensionalization
dX = dx/D1;
dY = dy/D1;
PSI = ones(ny,nx);
%% Boundary conditions
PSI(1,:) = 0; % bottom
PSI(floor(D1/dy+1),1:floor(L1/dx+1)) = 1; % left part of top
PSI(floor(D2/dy+1),floor(L1/dx+1):nx) = 1; % right part of top
for j = 1:floor(D1/dy+1)
    PSI(j,1) = (j-1)*dY; % inlet
end
for j = 1:floor(D2/dy+1)
    PSI(j,nx) = D1/D2*(j-1)*dY; % outlet
end
%% Iteration to solve for stream function PSI
err = 1e-6; % convergence criteria
n = 0;
while n < nmax
    n = n + 1;
    tempPSI = PSI;
    % left part of the channel
    for i = 2:floor(L1/dx+1)
        for j = 2:(floor(D1/dy+1)-1)
            PSI(j,i) = 1/(2/dX^2+2/dY^2)*((tempPSI(j,i+1)+PSI(j,i-1))/dX^2+(tempPSI(j+1,i)+PSI(j-1,i))/dY^2);
        end
    end
    % right part of the channel
    for i = floor(L1/dx+1):nx-1
        for j = 2:(floor(D2/dy+1)-1)
            PSI(j,i) = 1/(2/dX^2+2/dY^2)*((tempPSI(j,i+1)+PSI(j,i-1))/dX^2+(tempPSI(j+1,i)+PSI(j-1,i))/dY^2);
        end
    end
    % checking for convergence
    if max(max(abs(PSI-tempPSI))) <= err
        break
    end
end
%% Prompt convergence result in a message box
if n < nmax
    helpdlg({'Converged.';sprintf('Total number of iterations: %g\n',n)},...
        'Converged');
else
    warndlg({'NOT Converged!';sprintf('Change n_x, n_y, n_max or convergence criteria.\n')},...
        'NOT Converged');
end
%% Solve for velocity u and v from stream function
u = zeros(ny,nx);
v = zeros(ny,nx);
psi = PSI*U1*D1; % dimentionalization
for j = 2:ny-1
    u(j,:) = (psi(j+1,:)-psi(j-1,:))/2/dy;
end
for i = 2:nx-1
    v(:,i) = -(psi(:,i+1)-psi(:,i-1))/2/dx;
end
% velocity at boundaries (inviscid, so slip occurs)
u(1,:) = u(2,:);
u(ny,:) = u(ny-1,:);
v(:,1) = v(:,2);
v(:,nx) = v(:,nx-1);
%% Plot results
[X, Y] = meshgrid(0:dx:(L1+L2),0:dy:max(D1,D2));
% contour plot of stream function
contourf(handles.plotstreamline,X,Y,PSI),colormap(handles.plotstreamline,'jet')
% vector plot of velocity u and v
quiver(handles.plotvector,X,Y,u,v),
axis([handles.plotstreamline handles.plotvector],[0 L1+L2 0 max(D1,D2)]),
% plot the shape of the channel based on input parameters
if D1 < D2
    cornerposition = [0 D1 L1 D2-D1];
elseif D1 > D2
    cornerposition = [L1 D2 L2 D1-D2];
else
    cornerposition = [0 D1 1 1];
end
rectangle('Parent',handles.plotstreamline,'Position',cornerposition,'FaceColor',[0.94 0.94 0.94])
rectangle('Parent',handles.plotvector,'Position',cornerposition,'FaceColor',[0.94 0.94 0.94])
set(get(handles.plotstreamline,'XLabel'),'String','x (m)')
set(get(handles.plotstreamline,'YLabel'),'String','y (m)')
set(get(handles.plotstreamline,'Title'),'String','Normalized Stream Function \Psi')
set(get(handles.plotvector,'XLabel'),'String','x (m)')
set(get(handles.plotvector,'YLabel'),'String','y (m)')
set(get(handles.plotvector,'Title'),'String','Velocity Profile')

function sketchplot(h)
%Sketch the plot of the channel to show geometric parameters
% and governing equations. You can learn how to draw sketches
% programmatically and write LaTeX. Don't worry about it otherwise,
% since it has nothing to do with computation.

% Create doublearrow
d1 = annotation(h,'doublearrow',[0.06 0.06],...
    [0.6 0.8]);

% Create doublearrow
l1 = annotation(h,'doublearrow',[0.06 0.15],...
    [0.6 0.6]);

% Create doublearrow
l2 = annotation(h,'doublearrow',[0.15 0.3],...
    [0.6 0.6]);

% Create doublearrow
d2 = annotation(h,'doublearrow',[0.3 0.3],...
    [0.7 0.6]);

% Create arrow U
annotation(h,'arrow',[0.02 0.06],...
    [0.7 0.7],...
    'HeadStyle','Plain',...
    'HeadWidth',5);

% Create textbox U
annotation(h,'textbox',...
    [0.02 0.67 0.03 0.07],...
    'String',{'U'},...
    'FitBoxToText','off',...
    'LineStyle','none');

% Create textbox
annotation(h,'textbox',...
    [0.06 0.65 0.03 0.07],...
    'String',{'D1'},...
    'FitBoxToText','off',...
    'LineStyle','none');

% Create textbox
annotation(h,'textbox',...
    [0.1 0.58 0.03 0.07],...
    'String',{'L1'},...
    'FitBoxToText','off',...
    'LineStyle','none');

% Create textbox
annotation(h,'textbox',...
    [0.22 0.58 0.03 0.07],...
    'String',{'L2'},...
    'FitBoxToText','off',...
    'LineStyle','none');

% Create textbox
annotation(h,'textbox',...
    [0.25 0.61 0.03 0.07],...
    'String',{'D2'},...
    'FitBoxToText','off',...
    'LineStyle','none');

% Create channel
annotation(h,'line',...
    [0.05 0.15],[0.8 0.8],...
    'LineWidth',2);

% Create channel
annotation(h,'line',...
    [0.15 0.31],[0.7 0.7],...
    'LineWidth',2);

% Create channel
annotation(h,'line',...
    [0.15 0.15],[0.7 0.8],...
    'LineWidth',2);

% Create channel
annotation(h,'line',...
    [0.05 0.31],[0.58 0.58],...
    'LineWidth',2);

% Create textbox equations
annotation(h,'textbox',[0.32 0.73 0.03 0.07],...
    'String',{'\partial^2\psi/\partialx^2 + \partial^2\psi/\partialy^2 = 0','','u = \partial\psi/\partialy','', 'v = -\partial\psi/\partialx'},...
    'FitBoxToText','on',...
    'LineStyle','none');

function AppHelp(varargin)
% Create help message
dlgname = 'About Inviscid Channel App';
txt = {'Inviscid flow in a channel (Laplace equation of stream function)';
    'solved with explicit method';
    '';
    'Start - Start the simulation';
    'Solution Code - Open a pre-written script to show the solution code';
    '';
    '* Try D1 > D2, D1 < D2 or D1 = D2.';
    '* Use zoom, pan and data curser in the toolbar to interact with the';
    '  plots as usual';
    '* If result does not  converge, try:';
    '       a) increasing n_max (total number of iterations)';
    '       b) decreasing n_x, n_y (number of grids in each direction)';
    '';
    'Copyright 2013 The MathWorks, Inc.'};
helpdlg(txt,dlgname);

function D1_Callback(hObject, eventdata, handles)
% hObject    handle to D1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
getpara(handles);
% Hints: get(hObject,'String') returns contents of D1 as text
%        str2double(get(hObject,'String')) returns contents of D1 as a double

function D2_Callback(hObject, eventdata, handles)
% hObject    handle to D2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
getpara(handles);
% Hints: get(hObject,'String') returns contents of D2 as text
%        str2double(get(hObject,'String')) returns contents of D2 as a double

function L1_Callback(hObject, eventdata, handles)
% hObject    handle to L1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
getpara(handles);
% Hints: get(hObject,'String') returns contents of L1 as text
%        str2double(get(hObject,'String')) returns contents of L1 as a double

function L2_Callback(hObject, eventdata, handles)
% hObject    handle to L2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
getpara(handles);
% Hints: get(hObject,'String') returns contents of L2 as text
%        str2double(get(hObject,'String')) returns contents of L2 as a double

% --- Executes on button press in solution.
function solution_Callback(hObject, eventdata, handles)
% hObject    handle to solution (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
open('inviscidChannelScript.m');


function interleaved_vec = interleave_vectors(vectors)
    % Interleave multiple vectors element-by-element
    num_vectors = length(vectors);
    element_count = zeros(1, num_vectors);
    for i = 1:num_vectors
        element_count(i) = numel(vectors{i});
    end

    temp = cell(num_vectors, max(element_count));
    for i = 1:num_vectors
        temp(i, 1:element_count(i)) = num2cell(vectors{i});
    end

    interleaved_vec = [temp{:}];
end


function SHOWELEMENTS(ShowElements,ShowNodes,coordinates,X,Y,nel,nodes,nnode)
%--------------------------------------------------------------------------
%   Purpose:
%           To display and undisplay the Element numbers
%--------------------------------------------------------------------------
ShowElements = get(ShowElements,'Value') ;
ShowNodes = get(ShowNodes,'Value') ;
% Diaply only Element Numbers
if ShowElements==1 && ShowNodes==0
    cla(gcf) ;
    patch(X,Y,'w') ;
    for i = 1:nel
        EX = coordinates(nodes(i,:),1) ;EY = coordinates(nodes(i,:),2) ;
        pos = [sum(EX)/4,sum(EY)/4] ;
        text(pos(1),pos(2),int2str(i),'fontsize',8, 'fontweight','bold','color','b');
    end
end
% Display only Node Numbers
if ShowElements==0 && ShowNodes==1
    cla(gcf) ;
    patch(X,Y,'w')
    for i = 1:nnode
        text(coordinates(i,1),coordinates(i,2),int2str(i),'fontsize',8,....
            'fontweight','bold','Color','r');
    end
end
% Display both Element Numbers and Node Numbers
if ShowElements==1 && ShowNodes==1
    cla(gcf) ;
    patch(X,Y,'w') ;
    for i = 1:nel
        EX = coordinates(nodes(i,:),1) ;EY = coordinates(nodes(i,:),2) ;
        pos = [sum(EX)/4,sum(EY)/4] ;
        text(pos(1),pos(2),int2str(i),'fontsize',8, 'fontweight','bold','color','b');
    end
    for i = 1:nnode
        text(coordinates(i,1),coordinates(i,2),int2str(i),'fontsize',8,....
            'fontweight','bold','Color','r');
    end
end
% Display None
if ShowElements==0 && ShowNodes==0
    cla(gcf) ;
    patch(X,Y,'w')
end
return


function a = double(t)
%DOUBLE Convert tenmat to double array.
%
%   See also TENMAT.
%
%MATLAB Tensor Toolbox.
%Copyright 2012, Sandia Corporation.

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

a = t.data;


classdef dmce_shunt_mpc2 < mp.dmc_element % & mp.dmce_shunt
%MP.DMCE_SHUNT_MPC2  Data model converter for shunt elements for MATPOWER case v2.

%   MATPOWER
%   Copyright (c) 2021-2022, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

    properties
        bus
    end     %% properties

    methods
        function name = name(obj)
            name = 'shunt';
        end

        function df = data_field(obj)
            df = 'bus';
        end

        function [nr, nc, r] = get_import_size(obj, mpc)
            %% define named indices into data matrices
            [PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...
               VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;

            if isfield(mpc, obj.data_field())
                tab = mpc.(obj.data_field());
            else
                tab = [];
            end
            if isempty(tab)
                nr = 0;
                nc = 0;
                r = [];
            else
                r = find(tab(:, GS) | tab(:, BS));
                obj.bus = r;
                nr = size(r, 1);
                nc = size(tab, 2);          %% use nc of default table
            end
        end

        function [nr, nc, r] = get_export_size(obj, dme)
            [nr, nc] = size(dme.tab);   %% use size of default table
            r = dme.tab.source_uid;     %% rows in bus matrix
        end

        function vmap = table_var_map(obj, dme, mpc)
            vmap = table_var_map@mp.dmc_element(obj, dme, mpc);

            %% define named indices into data matrices
            [PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...
               VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;

            %% mapping for each name, default is {'col', []}
            vmap.uid        = {'IDs'};      %% consecutive IDs, starting at 1
            vmap.name       = {'cell', ''}; %% empty char
            vmap.status     = {'num', 1};   %% ones
            vmap.source_uid = {'r'};        %% row index in mpc.bus
            vmap.bus{2}     = BUS_I;
            vmap.gs{2}      = GS;
            vmap.bs{2}      = BS;
            vmap.p          = {'num', 0};   %% zeros
            vmap.q          = {'num', 0};   %% zeros
        end
    end     %% methods
end         %% classdef


% SPGL1: A solver for large-scale sparse reconstruction
% Version 1.7 (May 20, 2009)
%
% Files
%   spg_bp           - Solve the basis pursuit (BP) problem
%   spg_bpdn         - Solve the basis pursuit denoise (BPDN) problem
%   spg_lasso        - Solve the LASSO problem
%   spg_mmv          - Solve the multiple measurement vector (MMV) problem
%   spg_group        - Solve the group-sparse BPDN problem
%   spgdemo          - Demonstrates the use of the SPGL1 solver
%   spgl1            - Expert driver for BP, BPDN, and LASSO problems
%   spgSetParms      - Set options for SPGL1
%   spgsetup         - Compile the SPGL1 MEX interfaces
%
% $Id: Contents.m 1384 2009-05-20 19:09:37Z ewout78 $


% floatwrite() - Write data matrix to float file.
%
% Usage: >> floatwrite(data,filename, 'format')
%
% Inputs:
%   data     - write matrix data to specified file as four-byte floating point numbers.
%   filename - name of the file
%   'format' - The option FORMAT argument specifies the storage format as
%              defined by fopen. Default format is 'native'.
%   'transp|normal' - save the data transposed (.dat files) or not.
%
% Author: Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998
%
% See also: floatread(), fopen()

% Copyright (C) Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998
%
% 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

% 07-08-99  FORMAT argument added -se
% 02-08-00  new version included in toolbox -sm
% 01-25-02 reformated help & license, added links -ad

function A = floatwrite(A, fname, fform, transp)

if ~exist('fform')
	fform = 'native';
end
if nargin < 4
    transp = 'normal';
end;

if strcmpi(transp,'normal')
    if strcmpi(class(A), 'mmo')
        A = changefile(A, fname);
        return;
    elseif strcmpi(class(A), 'memmapdata')
        % check file to overwrite
        % -----------------------
        [fpath1 fname1 ext1] = fileparts(fname);
        [fpath2 fname2 ext2] = fileparts(A.data.Filename);
        if isempty(fpath1), fpath1 = pwd; end;

        fname1 = fullfile(fpath1, [fname1 ext1]);
        fname2 = fullfile(fpath2, [fname2 ext2]);
        if ~isempty(findstr(fname1, fname2))
            disp('Warning: raw data already saved in memory mapped file (no need to resave it)');
            return;
        end;

        fid = fopen(fname,'wb',fform);
        if fid == -1, error('Cannot write output file, check permission and space'); end;
        if size(A,3) > 1
            for ind = 1:size(A,3)
                tmpdata = A(:,:,ind);
                fwrite(fid,tmpdata,'float');
            end;
        else
            blocks = [ 1:round(size(A,2)/10):size(A,2)];
            if blocks(end) ~= size(A,2), blocks = [blocks size(A,2)]; end;
            for ind = 1:length(blocks)-1
                tmpdata = A(:, blocks(ind):blocks(ind+1));
                fwrite(fid,tmpdata,'float');
            end;
        end;
    else
        fid = fopen(fname,'wb',fform);
        if fid == -1, error('Cannot write output file, check permission and space'); end;
        fwrite(fid,A,'float');
    end;
else
    % save transposed
    for ind = 1:size(A,1)
        fwrite(fid,A(ind,:),'float');
    end;
end;
fclose(fid);


function a = i4cvv_nset ( mn, a, m, roff, nn, in, jn, vn )

%*****************************************************************************80
%
%% I4CVV_NSET sets items JN(*) from row IN(*) in an I4CVV.
%
%  Discussion:
%
%    An I4CVV is a "vector of vectors" of I4's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 December 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer MN, the size of the cell array.
%
%    Input, integer A(MN), the cell array.
%
%    Input, integer M, the number of rows in the array.
%
%    Input, integer ROFF(M+1), the row offsets.
%
%    Input, integer NN, the number of items.
%
%    Input, integer IN(NN), the rows of the items.
%    1 <= IN(*) <= M.
%
%    Input, integer JN(NN), the columns of the items.
%    1 <= JN(*) <= NR(IN(*)).
%
%    Input, integer VN(NN), the new value of items A(IN(*),JN(*)).
%
%    Output, integer A(MN), the cell array.
%
  k = roff(in(1:nn)) + jn(1:nn);
  a(k) = vn(1:nn);

  return
end


% Copyright (C) 2014-2017 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 extract_tests_for_matlab()

  dirs = {'.', '@sym', '@symfun', '@double', '@logical'};
  dirstr = {'', 'sym', 'symfun', 'double', 'logical'};

  outdir = 'tests_matlab';

  for j=1:length(dirs)
    files = dir(dirs{j});

    for i=1:length(files)
      mfile = files(i).name;
      if ( (~files(i).isdir) && strcmp(mfile(end-1:end), '.m') )
        %str = mfile(1:end-2);
        fprintf('>>> Looking for tests in: %s', mfile);
        tf = proc_file(dirs{j}, dirstr{j}, mfile, outdir);
        if tf
          fprintf('\t[done]\n');
        else
          fprintf('\t[no tests]\n');
        end
      end
    end
  end
endfunction

function r = proc_file(base, basestr, nm, outdir)

  %nm = 'symfun.m';
  %base = '@symfun';

  name_no_m = nm(1:end-2);
  in_name = [base '/' nm];
  body = __extract_test_code(in_name);

  r = true;
  if isempty(body)
    r = false;
    return
  end

  %% process it a bit
  % Chop it up into blocks for evaluation.
  %__lineidx = find (__body == "\n");
  %__blockidx = __lineidx(find (! isspace (__body(__lineidx+1))))+1;

  nl = sprintf('\n');

  % add an extra newline to ensure final line has one
  body = [body nl];

  ddot = 'fprintf(''.'')';
  dskip = 'fprintf(''s'')';
  body = regexprep(body, '^test\n', [nl ddot nl '%test' nl], 'lineanchors');
  body = regexprep(body, '^test ', [nl ddot nl '%test' nl], 'lineanchors');
  body = regexprep(body, '^assert', [nl ddot nl 'assert'], 'lineanchors');
  body = regexprep(body, 'assert', 'octassert');
  body = regexprep(body, '^(shared.*)\n', ['%$1' nl], 'lineanchors', 'dotexceptnewline');
  % FIXME: better to put these inside appropriate try catch end"
  body = regexprep(body, '^xtest\n( [^\n]*\n)*', [nl dskip nl '%xtest' ...
                      ' (**TEST EXPECTED TO FAIL: REMOVE**)' nl], 'lineanchors');
  body = regexprep(body, '^error [^\n]+\n( [^\n]*\n)*', [nl dskip nl '%error' ...
                      ' (**ERROR TEST: NOT SUPPORTED, REMOVED**)' nl], 'lineanchors');
  body = regexprep(body, '^error\n( [^\n]*\n)*', [nl dskip nl '%error' ...
                      ' (**ERROR TEST: NOT SUPPORTED, REMOVED**)' nl], 'lineanchors');
  body = regexprep(body, '^warning [^\n]+\n( [^\n]*\n)*', [nl dskip nl '%warning' ...
                      ' (**WARNING TEST: NOT SUPPORTED, REMOVED**)' nl], 'lineanchors');

  % output it
  out_name = ['tests_' basestr '_' name_no_m];
  full_out_name = [outdir '/' out_name '.m'];
  fid = fopen (full_out_name, 'w');
  fprintf(fid, 'function %s()\n', out_name);
  fprintf(fid, '%%%% Auto extracted tests from %s\n', in_name);
  fprintf(fid, '%% This file autogenerated from the inline Octave tests\n');
  fprintf(fid, '%% in the above file.  Don''t modify directly.\n');
  % FIXME: fprintf better than this schar thing?  its for utf8
  fwrite(fid, body, "schar");
  fprintf(fid, '\n\n\n%%%% End of tests\n');
  fprintf(fid, 'disp(''  Passed'')\n');
  fclose(fid);
endfunction

% This code from Octave source: /scripts/testfun/test.m
% Copyright (C) 2005-2013 Paul Kienzle
% GPL
function body = __extract_test_code (nm)
  fid = fopen (nm, "rt");
  body = '';
  if (fid >= 0)
    while (! feof (fid))
      ln = fgetl (fid);
      if (length (ln) >= 2 && strcmp (ln(1:2), "%!"))
        body = [body, "\n"];
        if (length (ln) > 2)
          body = [body, ln(3:end)];
        endif
      endif
    endwhile
    fclose (fid);
  endif
endfunction


classdef SparsePyrLKOpticalFlow < handle
    %SPARSEPYRLKOPTICALFLOW  Class used for calculating a sparse optical flow
    %
    % The class can calculate an optical flow for a sparse feature set using
    % the iterative Lucas-Kanade method with pyramids.
    %
    % See also: cv.SparsePyrLKOpticalFlow.calc, cv.calcOpticalFlowPyrLK
    %

    properties (SetAccess = private)
        % Object ID
        id
    end

    properties (Dependent)
        % default [21,21]
        WinSize
        % default 3
        MaxLevel
        % default `struct('type','Count+EPS', 'maxCount',30, 'epsilon',0.01)`
        TermCriteria
        % default 0
        Flags
        % default 1e-4
        MinEigThreshold
    end

    %% Constructor/destructor
    methods
        function this = SparsePyrLKOpticalFlow()
            %SPARSEPYRLKOPTICALFLOW  Creates instance of SparsePyrLKOpticalFlow
            %
            %     obj = cv.SparsePyrLKOpticalFlow()
            %
            % See also: cv.SparsePyrLKOpticalFlow.calc
            %
            this.id = SparsePyrLKOpticalFlow_(0, 'new');
        end

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

    %% SparseOpticalFlow
    methods
        function varargout = calc(this, prevImg, nextImg, prevPts, varargin)
            %CALC  Calculates a sparse optical flow
            %
            %     nextPts = obj.calc(prevImg, nextImg, prevPts)
            %     [nextPts, status, err] = obj.calc(...)
            %     [...] = obj.calc(..., 'OptionName', optionValue, ...)
            %
            % ## Input
            % * __prevImg__ First input image.
            % * __nextImg__ Second input image of the same size and the same
            %   type as `prevImg`.
            % * __prevPts__ Vector of 2D points for which the flow needs to be
            %   found.
            %
            % ## Output
            % * __nextPts__ Output vector of 2D points containing the
            %   calculated new positions of input features in the second image.
            % * __status__ Output status vector. Each element of the vector is
            %   set to 1 if the flow for the corresponding features has been
            %   found. Otherwise, it is set to 0.
            % * __err__ Optional output vector that contains error response
            %   for each point (inverse confidence).
            %
            % ## Options
            % * __InitialFlow__ Vector of 2D points to be used for the initial
            %   estimate of `nextPts`. Not set by default.
            %
            % See also: cv.SparsePyrLKOpticalFlow, cv.calcOpticalFlowPyrLK
            %
            [varargout{1:nargout}] = SparsePyrLKOpticalFlow_(this.id, 'calc', prevImg, nextImg, prevPts, varargin{:});
        end
    end

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

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

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

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

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

    %% Getters/Setters
    methods
        function value = get.WinSize(this)
            value = SparsePyrLKOpticalFlow_(this.id, 'get', 'WinSize');
        end
        function set.WinSize(this)
            SparsePyrLKOpticalFlow_(this.id, 'set', 'WinSize', value);
        end

        function value = get.MaxLevel(this)
            value = SparsePyrLKOpticalFlow_(this.id, 'get', 'MaxLevel');
        end
        function set.MaxLevel(this)
            SparsePyrLKOpticalFlow_(this.id, 'set', 'MaxLevel', value);
        end

        function value = get.TermCriteria(this)
            value = SparsePyrLKOpticalFlow_(this.id, 'get', 'TermCriteria');
        end
        function set.TermCriteria(this)
            SparsePyrLKOpticalFlow_(this.id, 'set', 'TermCriteria', value);
        end

        function value = get.Flags(this)
            value = SparsePyrLKOpticalFlow_(this.id, 'get', 'Flags');
        end
        function set.Flags(this)
            SparsePyrLKOpticalFlow_(this.id, 'set', 'Flags', value);
        end

        function value = get.MinEigThreshold(this)
            value = SparsePyrLKOpticalFlow_(this.id, 'get', 'MinEigThreshold');
        end
        function set.MinEigThreshold(this)
            SparsePyrLKOpticalFlow_(this.id, 'set', 'MinEigThreshold', value);
        end
    end

end


function  [bnde,bnd] = extdom_edges2( t , p )
% bnde -- boundary edges
% bnd  -- boundary points
% Given an element table, extract boundary edges in no order.
edge = [t(:,[1,2]); t(:,[1,3]); t(:,[2,3])];                               % Non-unique edges
edge = sortrows(sort(edge,2));                                             % Put shared edges next to each other
idx = all(diff(edge)==0,2);                                                % Find shared edges
idx = [idx;false]|[false;idx];                                             % True for all shared edges
bnde = edge(~idx,:);                                                       % Boundary edges
bnde  = unique(bnde,'rows');                                               % Boundary nodes
bnd=p(unique(bnde(:)),:);
end


function [ magic, offset, msg ] = pnmmagic( fid, fmt )
%PNMMAGIC Find and identify magic number in PBM/PGM/PPM file.
%
%   [ MAGIC, OFFSET, MSG ] = PNMMAGIC( FID ) scans the file with
%   filehandle FID for a PNM file magic number.
%
%   [ ... ] = PNMMAGIC( FID, FMT ) allows a restriction on the image
%   formats to look for. FMT must be one of 'pbm', 'pgm', 'ppm' or any
%   combination if put in a list (cell array). The special string 'pnm'
%   indicates any of 'pbm', 'pgm' and 'ppm'. If FMT is omitted, 'pnm' is
%   used.
%
%   MAGIC is the magic number found and OFFSET is the offset of the
%   magic number within the file. MSG contains an error message if the
%   search for the magic number failed, otherwise MSG is empty.
%
%   If PNMMAGIC succeeds, the file position indicator will be right
%   after the magic number so there is no need to call FSEEK when the
%   rest of the image is to be read. If PNMMAGIC fails, the file
%   position indicator will be at the end of the file.
%
%   PNM is not an image format by itself but means any of PBM, PGM, PPM.

%   Don't call error() if there is something wrong with the image file,
%   only if there is something wrong with the way this program is
%   called.

%   Author:      Peter J. Acklam
%   Time-stamp:  1998-05-10 19:03:42
%   E-mail:      jacklam@math.uio.no (Internet)
%   URL:         http://www.math.uio.no/~jacklam

%
% Checks input arguments and assign default value to omitted argument.
%
error( nargchk( 1, 2, nargin ) );
if nargin < 2
   fmt = 'pnm';
end
if all( fid ~= fopen( 'all' ) )
   error( 'Invalid file identifier.' );
end

% Make sure the format variable is a list (cell array).
if ischar( fmt )
   fmt = { fmt };
end

% From the list of formats create a list of magic numbers to look for.
magics = {};
for i = 1:length(fmt)
   switch lower( fmt{i} )
      case 'pbm'                                % Portable bitmap.
         magics = { magics{:}, 'P1', 'P4' };
      case 'pgm'                                % Portable graymap.
         magics = { magics{:}, 'P2', 'P5' };
      case 'ppm'                                % Portable pixmap.
         magics = { magics{:}, 'P3', 'P6' };
      case 'pnm'                                % Portable anymap.
         magics = { 'P1', 'P2', 'P3', 'P4', 'P5', 'P6' };
      otherwise
         error( [ 'Invalid format string: ' fmt ] );
   end
end

% Initialize output arguments.
magic  = '';                    % Magic number string.
offset = [];                    % Offset of magic number within file.
msg    = '';                    % Error message string.

while 1

   % The magic number should be followed by whitespace, so we can use
   % FSCANF to get the magic number.
   [ str, count ] = fscanf( fid, '%s', 1 );

   % Look for magic number.
   if any( strcmp( str, magics ) )
      magic = str;
      offset = ftell( fid ) - 2;   % Subtract length of magic number.
      return
   end

   %
   % If a magic number was not found, start scanning from the beginning
   % of the next line of the file. We don't use FGETL to get the next
   % line since the file might be enormous and contain only one line.
   %
   blocksize = 8192;            % Number of bytes read at a time.
   while 1

      % Read a chunk of data from the file.
      [ data, count ] = fread( fid, blocksize );
      if count == 0
         msg = 'File ended while scanning for magic number.';
         return
      end

      % Look for newline characters.
      nlchars = ( data == 10 ) | ( data == 13 );
      if any( nlchars )
         nlpos = find( nlchars );       % Position of newline chars.
         nlpos = nlpos(1);              % In case there are several.
         fseek( fid, nlpos - count, 0 );        % Put FPS at newline.
         break
      end

   end

end


function p02_default ( dim_num )

%*****************************************************************************80
%
%% P02_DEFAULT sets default values for problem 02.
%
%  Discussion:
%
%    If a problem uses vector parameters, then the spatial dimension
%    DIM_NUM is needed as input, so that the vector parameters can be
%    properly dimensioned.
%
%    Every problem keeps a count of the number of function calls.  Calling
%    this routine causes that count to be reset to 0.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DIM_NUM, the dimension of the problem.
%
  i4 = 0;
  p02_i4 ( 'D', '*', i4 );

  return
end


function line_cvt_lloyd_test ( )

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

  line_cvt_lloyd_test01 ( );
  line_cvt_lloyd_test02 ( );
%
%  Repeat, using sorted initial points.
%
  line_cvt_lloyd_test03 ( );
  line_cvt_lloyd_test04 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'LINE_CVT_LLOYD_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


classdef LvdOptimizerAlgoEnum < matlab.mixin.SetGet
    %LvdOptimizerAlgoEnum Summary of this class goes here
    %   Detailed explanation goes here

    enumeration
        Fmincon('FMINCON', ...
                'The standard gradient-based nonlinear programming solver in MATLAB.  Supports a variety of subroutines.  Try this algorithm first.', ...
                true);

        PatternSearch('Pattern Search', ...
                      'Uses a "direct search" algorithm to solve NLP problems.  Direct search is a method for solving optimization problems that does not require any information about the gradient of the objective function.  Use this function to find a reasonable guess for a solution and then switch to a gradient-based method.', ...
                      false);

        Nomad('NOMAD', ...
              'NOMAD is a C++ implementation of the Mesh Adaptive Direct Search (MADS) algorithm designed for constrained optimization of blackbox functions.  At the core of NOMAD resides the Mesh Adaptive Direct Search (MADS) algorithm.', ...
              false);

        Ipopt('IPOPT', ...
              'IPOPT is a software library for large scale nonlinear optimization of continuous systems.', ...
              true);

        Surrogate('Surrogate Optimizer', ...
              'Surrogate optimization for global minimization of time-consuming objective functions.  This optimizer does not necessarily handle equality constraints well.', ...
              false);
    end

    properties
        name(1,:) char
        desc(1,:) char
        reqGrad(1,1) logical = true
    end

    methods
        function obj = LvdOptimizerAlgoEnum(name, desc, reqGrad)
            obj.name = name;
            obj.desc = desc;
            obj.reqGrad = reqGrad;
        end
    end

    methods(Static)
        function listBoxStr = getListBoxStr()
            m = enumeration('LvdOptimizerAlgoEnum');
            [~,I] = sort({m.name});
            listBoxStr = {m(I).name};
        end

        function [ind, enum] = getIndForName(name)
            m = enumeration('LvdOptimizerAlgoEnum');
            [~,I] = sort({m.name});
            m = m(I);
            ind = find(ismember({m.name},name),1,'first');
            enum = m(ind);
        end

        function [enum, ind] = getEnumForListboxStr(nameStr)
            m = enumeration('LvdOptimizerAlgoEnum');
            ind = find(ismember({m.name},nameStr),1,'first');
            enum = m(ind);
        end
    end
end


function check13Color(img)
%
%
%        check13Color(img)
%
%
%        Input:
%           -img: an image to be tested if it is an one or three color
%                 channels image
%
%     Copyright (C) 2013  Francesco Banterle
%
%     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/>.
%

col = size(img, 3);
if(col ~= 3 && col ~= 1)
    error('The image has to be an RGB or luminance image.');
end


function colorMap = diffMap(cMapSize)
% matRad difference colormap
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright 2015 the matRad development team.
%
% This file is part of the matRad project. It is subject to the license
% terms in the LICENSE file found in the top-level directory of this
% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part
% of the matRad project, including this file, may be copied, modified,
% propagated, or distributed except according to the terms contained in the
% LICENSE file.
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

colorMapData = ...
    [0         0    1.0000
    0.0323    0.0323    1.0000
    0.0645    0.0645    1.0000
    0.0968    0.0968    1.0000
    0.1290    0.1290    1.0000
    0.1613    0.1613    1.0000
    0.1935    0.1935    1.0000
    0.2258    0.2258    1.0000
    0.2581    0.2581    1.0000
    0.2903    0.2903    1.0000
    0.3226    0.3226    1.0000
    0.3548    0.3548    1.0000
    0.3871    0.3871    1.0000
    0.4194    0.4194    1.0000
    0.4516    0.4516    1.0000
    0.4839    0.4839    1.0000
    0.5161    0.5161    1.0000
    0.5484    0.5484    1.0000
    0.5806    0.5806    1.0000
    0.6129    0.6129    1.0000
    0.6452    0.6452    1.0000
    0.6774    0.6774    1.0000
    0.7097    0.7097    1.0000
    0.7419    0.7419    1.0000
    0.7742    0.7742    1.0000
    0.8065    0.8065    1.0000
    0.8387    0.8387    1.0000
    0.8710    0.8710    1.0000
    0.9032    0.9032    1.0000
    0.9355    0.9355    1.0000
    0.9677    0.9677    1.0000
    1.0000    1.0000    1.0000
    1.0000    1.0000    1.0000
    1.0000    0.9677    0.9677
    1.0000    0.9355    0.9355
    1.0000    0.9032    0.9032
    1.0000    0.8710    0.8710
    1.0000    0.8387    0.8387
    1.0000    0.8065    0.8065
    1.0000    0.7742    0.7742
    1.0000    0.7419    0.7419
    1.0000    0.7097    0.7097
    1.0000    0.6774    0.6774
    1.0000    0.6452    0.6452
    1.0000    0.6129    0.6129
    1.0000    0.5806    0.5806
    1.0000    0.5484    0.5484
    1.0000    0.5161    0.5161
    1.0000    0.4839    0.4839
    1.0000    0.4516    0.4516
    1.0000    0.4194    0.4194
    1.0000    0.3871    0.3871
    1.0000    0.3548    0.3548
    1.0000    0.3226    0.3226
    1.0000    0.2903    0.2903
    1.0000    0.2581    0.2581
    1.0000    0.2258    0.2258
    1.0000    0.1935    0.1935
    1.0000    0.1613    0.1613
    1.0000    0.1290    0.1290
    1.0000    0.0968    0.0968
    1.0000    0.0645    0.0645
    1.0000    0.0323    0.0323
    1.0000         0         0];

if nargin < 1
    colorMap = colorMapData;
elseif size(colorMapData,1) == cMapSize
    colorMap = colorMapData;
else
    %We have to interpolate the colormap
    newX = linspace(1,64,cMapSize);
    oldX = 1:64;
    colorMap = interp1(oldX,colorMapData,newX);
    %{
    %resample via HSV.. more color-true than above, but doesn't work with
    %every colormap
    hsv                        = rgb2hsv(cm);
    hsv(144:end,1)             = hsv(144:end,1)+1;
    ColorMap                   = interp1(linspace(0,1,size(cm,1)),hsv,linspace(0,1,cMapSize));
    ColorMap(cm(:,1)>1,1) = ColorMap(cm(:,1)>1,1)-1;
    ColorMap                   = hsv2rgb(cm);
    %}
end

end


% Copyright 2011 Zdenek Kalal
%
% This file is part of TLD.
%
% TLD 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.
%
% TLD 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 TLD.  If not, see <http://www.gnu.org/licenses/>.

function [nX1,nX2,nEx1,nEx2] = tldSplitNegativeData(nX,nEx)
% Splits negative data to training and validation set

N    = size(nX,2);
idx  = randperm(N);
nX   = nX(:,idx);
nX1  = nX(:,1:N/2);
nX2  = nX(:,N/2+1:end);

N    = size(nEx,2);
idx  = randperm(N);
nEx  = nEx(:,idx);
nEx1 = nEx(:,1:N/2);
nEx2 = nEx(:,N/2+1:end);


function [varargout]=mergeVertices(varargin)

% function [F,V,ind1,ind2]=mergeVertices(F,V,numDigitsMerge)

%% Parse input

switch nargin
    case 2
        F=varargin{1};
        V=varargin{2};
        numDigitsMerge=[];
    case 3
        F=varargin{1};
        V=varargin{2};
        numDigitsMerge=varargin{3};
    otherwise
        error('Wrong number of input arguments');
end

cellMode=isa(F,'cell');

if isempty(numDigitsMerge)
    D=patchEdgeLengths(F,V);
    if cellMode
        mean_D=mean(cellfun(@mean,D)); %Take mean across cell entries
    else
        mean_D=mean(D); %Mean across array
    end
    numDigitsMerge=6-numOrder(mean_D); %base number of digits on mean
end

%% Merge nodes

[~,indKeep,indFix]=unique(pround(V,numDigitsMerge),'rows');
V=V(indKeep,:);

%% Fix indices in face array
if isa(F,'cell')
    for q=1:1:numel(F)
        F{q}=fixFaces(F{q},indFix);
    end
else
    F=fixFaces(F,indFix);
end

%% Collect output

varargout{1}=F;
varargout{2}=V;
varargout{3}=indKeep;
varargout{4}=indFix;

end

%% Fix indices in face array
function F=fixFaces(F,indFix)
    if size(F,1)==1
        F=indFix(F)'; %Fix indices in F
    else
        F=indFix(F); %Fix indices in F
    end
end

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


%DOUBLEM Datafile mapping for conversion to double
%
%	B = DOUBLEM(A)
%	B = A*DOUBLEM
%
% For datasets B = A, but the data inside A is converted to double.
% For datafiles B = A, but the command makes sure that the data in B is
% first converted to double when B is converted to a dataset.
% In all other cases A itself is converted to double.
% This is useful to convert INT8 and other formats inside a dataset.

function a = doublem(a)

	if nargin < 1 || isempty(a)
		a = prmapping(mfilename,'fixed');
		a = setname(a,'double');
	elseif isdataset(a)
		a = setdat(a,double(+a));
	elseif isdatafile(a)
		a = a*filtm([],'double');
	else
		a = double(a);
	end

return


function s = s_to_rot13 ( s )

%*****************************************************************************80
%
%% S_TO_ROT13 "rotates" the alphabetical characters in a string by 13 positions.
%
%  Discussion:
%
%    Two applications of the routine will return the original string.
%
%  Examples:
%
%    Input:                      Output:
%
%    abcdefghijklmnopqrstuvwxyz  nopqrstuvwxyzabcdefghijklm
%    Cher                        Pure
%    James Thurston Howell       Wnzrf Guhefgba Ubjryy
%    0123456789                  56789012345
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%   24 March 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string S, a string to be "rotated".
%
%    Output, string S, the rotated string.
%
  s_length = length ( s );

  for i = 1 : s_length
    s(i) = ch_to_rot13 ( s(i) );
  end

  return
end


if ~exist('n_ima')|~exist('fc'),
   fprintf(1,'No calibration data available.\n');
   return;
end;

if ~exist('no_image'),
    no_image = 0;
end;

if ~exist('est_alpha'),
    est_alpha = 0;
end;

if ~exist('center_optim'),
    center_optim = 1;
end;

if ~exist('est_aspect_ratio'),
    est_aspect_ratio = 1;
end;

if ~exist('est_fc');
    est_fc = [1;1]; % Set to zero if you do not want to estimate the focal length (it may be useful! believe it or not!)
end;

if exist('est_dist'),
   if length(est_dist) == 4,
      est_dist = [est_dist ; 0];
   end;
end;

if exist('kc'),
   if length(kc) == 4;
      kc = [kc;0];
   end;
end;

if ~exist('fc_error'),
   fc_error = NaN*ones(2,1);
end;

if ~exist('kc_error'),
   kc_error = NaN*ones(5,1);
end;

if ~exist('cc_error'),
   cc_error = NaN*ones(2,1);
end;

if ~exist('alpha_c_error'),
   alpha_c_error = NaN;
end;

check_active_images;

if ~exist('solution_init'), solution_init = []; end;

for kk = 1:n_ima,
   if ~exist(['dX_' num2str(kk)]), eval(['dX_' num2str(kk) '= dX;']); end;
   if ~exist(['dY_' num2str(kk)]), eval(['dY_' num2str(kk) '= dY;']); end;
end;

if ~exist('solution'),
    solution = [];
end;

if ~exist('param_list'),
   param_list = solution;
end;

if ~exist('wintx'),
   wintx = [];
   winty = [];
end;

if ~exist('dX_default'),
   dX_default = [];
   dY_default = [];
end;

if ~exist('dX'),
    dX = [];
end;
if ~exist('dY'),
    dY = dX;
end;

if ~exist('Hcal'),
    Hcal = [];
end;
if ~exist('Wcal'),
    Wcal = [];
end;
if ~exist('map'),
    map = [];
end;

if ~exist('wintx_default')|~exist('winty_default'),
    wintx_default = max(round(nx/128),round(ny/96));
    winty_default = wintx_default;
end;

if ~exist('alpha_c'),
   alpha_c = 0;
end;

if ~exist('err_std'),
    err_std = [NaN;NaN];
end;

for kk = 1:n_ima,
   if ~exist(['y_' num2str(kk)]),
   	eval(['y_' num2str(kk) ' = NaN*ones(2,1);']);
   end;
   if ~exist(['n_sq_x_' num2str(kk)]),
   	eval(['n_sq_x_' num2str(kk) ' = NaN;']);
   	eval(['n_sq_y_' num2str(kk) ' = NaN;']);
   end;
   if ~exist(['wintx_' num2str(kk)]),
   	eval(['wintx_' num2str(kk) ' = NaN;']);
   	eval(['winty_' num2str(kk) ' = NaN;']);
   end;
   if ~exist(['Tc_' num2str(kk)]),
    eval(['Tc_' num2str(kk) ' = [NaN;NaN;NaN];']);
   end;
   if ~exist(['omc_' num2str(kk)]),
    eval(['omc_' num2str(kk) ' = [NaN;NaN;NaN];']);
    eval(['Rc_' num2str(kk) ' = NaN * ones(3,3);']);
   end;
   if ~exist(['omc_error_' num2str(kk)]),
      eval(['omc_error_' num2str(kk) ' = NaN*ones(3,1);']);
   end;
   if ~exist(['Tc_error_' num2str(kk)]),
      eval(['Tc_error_' num2str(kk) ' = NaN*ones(3,1);']);
   end;
   if ~exist(['Rc_' num2str(kk)]),
    eval(['Rc_' num2str(kk) ' = rodrigues(omc_' num2str(kk) ');']);
   end;
end;

if ~exist('small_calib_image'),
    small_calib_image = 0;
end;

if ~exist('check_cond'),
    check_cond = 1;
end;

if ~exist('MaxIter'),
    MaxIter = 30;
end;

save_name = 'Calib_Results';

if exist([ save_name '.mat'])==2,
    disp('WARNING: File Calib_Results.mat already exists');
    if exist('copyfile'),
        pfn = -1;
        cont = 1;
        while cont,
            pfn = pfn + 1;
            postfix = ['_old' num2str(pfn)];
            save_name = [ 'Calib_Results' postfix];
            cont = (exist([ save_name '.mat'])==2);
        end;
        copyfile('Calib_Results.mat',[save_name '.mat']);
        disp(['Copying the current Calib_Results.mat file to ' save_name '.mat']);
        if exist('Calib_Results.m')==2,
            copyfile('Calib_Results.m',[save_name '.m']);
            disp(['Copying the current Calib_Results.m file to ' save_name '.m']);
        end;
        cont_save = 1;
    else
        disp('The file Calib_Results.mat is about to be changed.');
        cont_save = input('Do you want to continue? ([]=no,other=yes) ','s');
        cont_save = ~isempty(cont_save);
    end;
else
    cont_save = 1;
end;

if cont_save,

    save_name = 'Calib_Results';

    if exist('calib_name'),

        fprintf(1,['\nSaving calibration results under ' save_name '.mat\n']);

        string_save = ['save ' save_name ' center_optim param_list active_images ind_active est_alpha est_dist est_aspect_ratio est_fc fc kc cc alpha_c fc_error kc_error cc_error alpha_c_error  err_std ex x y solution solution_init wintx winty n_ima type_numbering N_slots small_calib_image first_num image_numbers format_image calib_name Hcal Wcal nx ny map dX_default dY_default KK inv_KK dX dY wintx_default winty_default no_image check_cond MaxIter'];

        for kk = 1:n_ima,
            string_save = [string_save ' X_' num2str(kk) ' x_' num2str(kk) ' y_' num2str(kk) ' ex_' num2str(kk) ' omc_' num2str(kk) ' Rc_' num2str(kk) ' Tc_' num2str(kk) ' omc_error_' num2str(kk) ' Tc_error_' num2str(kk) ' H_' num2str(kk) ' n_sq_x_' num2str(kk) ' n_sq_y_' num2str(kk) ' wintx_' num2str(kk) ' winty_' num2str(kk) ' dX_' num2str(kk) ' dY_' num2str(kk)];
        end;

    else

        fprintf(1,['\nSaving calibration results under ' save_name '.mat (no image version)\n']);

        string_save = ['save ' save_name ' center_optim param_list active_images ind_active est_alpha est_dist est_aspect_ratio est_fc fc kc cc alpha_c fc_error kc_error cc_error alpha_c_error err_std ex x y solution solution_init wintx winty n_ima nx ny dX_default dY_default KK inv_KK dX dY wintx_default winty_default no_image check_cond MaxIter'];

        for kk = 1:n_ima,
            string_save = [string_save ' X_' num2str(kk) ' x_' num2str(kk) ' y_' num2str(kk) ' ex_' num2str(kk) ' omc_' num2str(kk) ' Rc_' num2str(kk) ' Tc_' num2str(kk) ' omc_error_' num2str(kk) ' Tc_error_' num2str(kk) ' H_' num2str(kk) ' n_sq_x_' num2str(kk) ' n_sq_y_' num2str(kk) ' wintx_' num2str(kk) ' winty_' num2str(kk) ' dX_' num2str(kk) ' dY_' num2str(kk)];
        end;

    end;

    %fprintf(1,'To load later click on Load\n');

    eval(string_save);

    saving_calib_ascii;

    fprintf(1,'done\n');

end;


function [boxes] = detect_face( im, options )

% Load a face detector and an image
detector = CascadeClassifier(options.haarFaceCascadeXml);

% Preprocess
if size(im,3) > 1
    gr = rgb2gray(im);
else
    gr = im;
end
gr = equalizeHist(gr);

% Detect
boxes = detector.detect(gr, 'ScaleFactor',  1.3, ...
                            'MinNeighbors', 2, ...
                            'MinSize',      [30, 30]);
% Draw results
% imshow(im);
% for i = 1:numel(boxes)
%     rectangle('Position',  boxes{i}, ...
%               'EdgeColor', 'g');
% end
%
% end


function writetoPAJ(CIJ, fname, arcs)
%WRITETOPAJ         Write to Pajek
%
%   writetoPAJ(CIJ, fname, arcs);
%
%   This function writes a Pajek .net file from a MATLAB matrix
%
%   Inputs:     CIJ,        adjacency matrix
%               fname,      filename minus .net extension
%               arcs,       1 for directed network
%                           0 for an undirected network
%
%   Chris Honey, Indiana University, 2007

N = size(CIJ,1);
fid = fopen(cat(2,fname,'.net'), 'w');

%%%VERTICES
fprintf(fid, '*vertices %6i \r', N);
for i = 1:N
    fprintf(fid, '%6i "%6i" \r', [i i]);
end

%%%ARCS/EDGES
if arcs
    fprintf(fid, '*arcs \r');
else
    fprintf(fid, '*edges \r');
end

for i = 1:N
    for j = 1:N
        if CIJ(i,j) ~= 0
            fprintf(fid, '%6i %6i %6f \r', [i j CIJ(i,j)]);
        end
    end
end

fclose(fid);


% feat is a cell array of matrix, each with TxD size. T is the number of
% frames and D is the number of dimensions.

function writeKaldiArchiveText(file_name, uttID, feat)

FID = fopen(file_name, 'W');

for i=1:length(uttID)
    PrintProgress(i, length(uttID), 500, 'Writing Kaldi archive');
    fprintf(FID, '%s [ ', uttID{i});
    write_matrix(FID, feat{i}, 1);
    fprintf(FID, ' ]\n');
end

fclose(FID);


function resu = ismemberclique(v,cliques)
% b = ismemberclique(v,cliques)
%

finiclique = 0 ; resu=0 ;
cl=1;  ncl=length(cliques) ;

while (~finiclique) & (cl<=ncl);
    if ismember(v,cliques{cl})
        resu=1;
        finiclique=1 ;
    end
    cl=cl+1;
end


function test_mrvConvertVAnat
%Validate that mrVista conversopm of vAanatomy.data to nifti works
%
%  test_mrvConvertVAnat()
%
% Tests: mrAnatConvertVAnatToT1Nifti
%
% INPUTS
%  No inputs
%
% RETURNS
%  No returns
%
% Example: test_mrvConvertVAnat()
%
% See also MRVTEST
%
% Copyright NYU team, mrVista, 2017

%% Convert vAnatomy.dat to nifti

% Get the vAnatomy.dat sample data file
vAnatFileName = mrtInstallSampleData('anatomy/anatomyV','vAnatomy',  [], [], 'filetype', 'dat');

% Convert it to nifti
newNiftiFileName = fullfile(tempdir,'vAnatomy.nii.gz');
mrAnatConvertVAnatToT1Nifti(vAnatFileName,newNiftiFileName);

% Get a stored nifti file that corresponds to the vAnatomy
oldNifitFileName = mrtInstallSampleData('anatomy/anatomyV','t1.nii', [], [], 'filetype', 'gz');

%% Compare the nifti to some stored values
n0  = niftiRead(oldNifitFileName);
n1 = niftiRead(newNiftiFileName);

n0  = niftiApplyCannonicalXform(n0);
n1 = niftiApplyCannonicalXform(n1);

assertEqual(niftiGet(n0, 'qto_xyz'), niftiGet(n1, 'qto_xyz'));
assertEqual(niftiGet(n0, 'data'), niftiGet(n1, 'data'));
assertEqual(niftiGet(n0, 'dim'), niftiGet(n1, 'dim'));


function [fitresult, gof,stats] = evaluate_spatial_scale(data_obj,parcel_obj,varargin)
% Evaluate information coding at multiple spatial scales, using a prespecified parcellation
% and the predict function (and associated optional inputs). This function evaluates the
% spatial scale of information coding by constructing predictive models using random draws
% of features from different parcels to test whether information is contained 1) at the
% whole-brain scale, 2) within individual parcels, or 3) across all parcels (may be similar
% to whole-brain if parcels cover most cortical and subcortical areas)
% Usage:
% ::
%
%    [fitresult, gof,stats] = evaluate_spatial_scale(obj, parcel_obj, varargin);
%
%
% ..
%     Author and copyright information:
%
%     Copyright (C) 2018 Philip Kragel
%
%     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/>.
% ..
%
% :Inputs:
%
%   **data_obj:**
%   **parcel_obj:**
%
% :Optional inputs:
%
%   **colors:**
%       Cell array of RGB values that indicate colors for each parcel
%
%   **labels:**
%       Cell array of strings that indicate names for each parcel
%
%   **num_voxels:**
%      Vector of integers that indicate how many voxels to randomly sample
%      these should be smaller than the total number of voxels in the
%      smallest parcel
%
%
%   **do_plot:**
%      Automatically make plot of sampling curves
%
%   **render_brain**
%      Make a brain rendering of parcels on plot
%
%
% :Outputs:
%
%   **fitresult:**
%        cell array of fit objects for each parcel
%
%   **gof:**
%        cell array of with performance metrics for each parcel
%
%   **stats:**
%        structure with normal approximation Z-stats and P-values for
%        pairwise comparisons of effect size at the second largest spatial
%        scale
%
% :Examples:
% ::
%
%  % Example 1: Load bmrk3 data and predict pain intensity sampling
%  within/across different resting-state networks
% % -------------------------------------------------------------------------
%   canlab_help_set_up_pain_prediction_walkthrough;
%   [mask_obj, networknames, imagenames] = load_image_set('bucknerlab');
%   mycolors={[120 18 134]/255 [70 130 180]/255  [0 118 14]/255  [196 58 250]/255  [220 248 164]/255  [230 148 34]/255  [205 62 78]/255 };
%   [fitresult, gof] = evaluate_spatial_scale(image_obj,mask_obj,'cv_lassopcr', 'nfolds',[rem(subject_id,2)+1],'verbose',0,'labels',networknames,'colors',mycolors);
%
%
%  % Example 1: Load bmrk3 data and predict pain intensity sampling
%  within/across different brainstem/thalamus regions
% % -------------------------------------------------------------------------
%   canlab_help_set_up_pain_prediction_walkthrough;
%   [mask_obj, networknames, imagenames] = load_atlas('brainstem');
%   [fitresult, gof] = evaluate_spatial_scale(image_obj,mask_obj,'cv_lassopcr', 'nfolds',[rem(subject_id,2)+1],'verbose',0,'labels',networknames,'colors',mycolors);
%
%
% :References:
%   Kragel, P. A., Koban, L., Barrett, L. F., & Wager, T. D. (2018). Representation, pattern information, and brain signatures: from neurons to neuroimaging. Neuron, 99(2), 257-273.
%   Kragel, P. A., Reddan, M., LaBar, K. S., & Wager, T. D. (2018). Emotion Schemas are Embedded in the Human Visual System. bioRxiv, 470237.
%
% :See also:
%
% predict, load_atlas

% ..
%    Programmers' notes:
%    List dates and changes here, and author of changes
%
%   Phil: created, Dec 2018
%
%   TODOs: - change outcome metric to optionally incude accuracy/AUC/etc.
%          - change outcome to optionally reflect % of noise ceiling
%          - account for regions that have small number of voxels
% ..

%if we have a 1d atlas object convert to matrix for
parcel_obj=resample_space(parcel_obj,data_obj,'nearest');

if size(parcel_obj.dat,2)==1
    parcel_obj.dat=condf2indic(parcel_obj.dat);
    parcel_obj.dat=parcel_obj.dat(:,2:end);

end

% defaults
num_iterations = 1000;
num_parcels = size(parcel_obj.dat,2);
num_vox = [ 50 150 250 500 750 1000 1500 5000 10000];

do_plot=true;
render_brain=false;

mycolors=scn_standard_colors(num_parcels);

atlas_labels=cell(num_parcels,1);
for i=1:length(atlas_labels)
    atlas_labels{i}='';
end

% optional inputs
if any(strcmp(varargin,'colors'))
    mycolors=varargin{find(strcmp(varargin,'colors'))+1};
end

if any(strcmp(varargin,'labels'))
    atlas_labels=varargin{find(strcmp(varargin,'labels'))+1};
end

if any(strcmp(varargin,'num_voxels'))
    num_vox=varargin{find(strcmp(varargin,'num_voxels'))+1};
end

if any(strcmp(varargin,'iterations'))
    num_iterations=varargin{find(strcmp(varargin,'iterations'))+1};
end

%% adjust number of voxels to sample based on size of parcels

for n=1:num_parcels %for each parcel
    mask=parcel_obj;
    mask.dat=mask.dat(:,n);
    nf(n)=length(find(mask.dat>0));
end

num_vox(num_vox>(min(nf)))=[];
%% test with increasing number of features randomly sampled from each parcel
num_feats_within = nan(num_parcels,length(num_vox)+1);
pred_outcome_r=nan(num_iterations,num_parcels,length(num_vox)+1);
for n=1:num_parcels %for each parcel
    mask=parcel_obj;
    mask.dat=mask.dat(:,n);
    masked_data=apply_mask(data_obj,mask);

    num_feats_within(n,:)=[num_vox size(masked_data.dat,1)];

    for it=1:num_iterations
        temp_inds=randperm(size(masked_data.dat,1));
        cs=1;
        for nf=num_feats_within(n,:)
            try
                subsampled_masked_data=masked_data;

                if nf==size(subsampled_masked_data.dat,1) %if subsampling all data, do nothing
                else
                    subsampled_masked_data.dat=subsampled_masked_data.dat(temp_inds(1:nf),:); %otherwise grab first 1:nf reordered features
                end

                if ~any(strcmp(varargin,'nfolds')) %if cv not specified do 10-fold
                    [~, stats]=predict(subsampled_masked_data,varargin{:},'nfolds',10);
                else
                    [~, stats]=predict(subsampled_masked_data,varargin{:});
                end

                try
                    pred_outcome_r(it,n,cs)=stats.pred_outcome_r;

                catch
                    pred_outcome_r(it,n,cs)=1-stats.cverr;

                end
                cs=cs+1;
            catch
            end

        end
    end
end

%% random samples from entire brain

num_feats_full=[num_vox size(data_obj.dat,1)];
pred_outcome_r_full=nan(num_iterations,length(num_vox)+1);

for it=1:num_iterations
    temp_inds=randperm(size(data_obj.dat,1));
    cs=1;
    for nf=num_feats_full
        try
            subsampled_masked_data=data_obj;

            if nf==size(subsampled_masked_data.dat,1) %if subsampling all data, do nothing
            else
                subsampled_masked_data.dat=subsampled_masked_data.dat(temp_inds(1:nf),:); %otherwise grab first 1:nf reordered features
            end

            if ~any(strcmp(varargin,'nfolds')) %if cv not specified do 10-fold
                [~, stats]=predict(subsampled_masked_data,varargin{:},'nfolds',10);
            else
                [~, stats]=predict(subsampled_masked_data,varargin{:});
            end

            try
                pred_outcome_r_full(it,cs)=stats.pred_outcome_r;

            catch
                pred_outcome_r_full(it,cs)=1-stats.cverr;

            end

            cs=cs+1;
        catch
        end

    end
end

%% random samples across all parcels

mask=parcel_obj;

mask.dat=double(any(mask.dat')');

masked_data=apply_mask(data_obj,mask);
num_feats_all_parcels=[num_vox size(masked_data.dat,1)];
pred_outcome_r_all_parcels=nan(num_iterations,length(nf));

for it=1:num_iterations
    temp_inds=randperm(size(masked_data.dat,1));
    cs=1;
    for nf=num_feats_all_parcels
        try
            subsampled_masked_data=masked_data;

            if nf==size(subsampled_masked_data.dat,1) %if subsampling all data, do nothing
            else
                subsampled_masked_data.dat=subsampled_masked_data.dat(temp_inds(1:nf),:); %otherwise grab first 1:nf reordered features
            end

            if ~any(strcmp(varargin,'nfolds')) %if cv not specified do 10-fold
                [~, stats]=predict(subsampled_masked_data,varargin{:},'nfolds',10);
            else
                [~, stats]=predict(subsampled_masked_data,varargin{:});
            end

            try
                pred_outcome_r_all_parcels(it,cs)=stats.pred_outcome_r;

            catch
                pred_outcome_r_all_parcels(it,cs)=1-stats.cverr;

            end

            cs=cs+1;
        catch
        end

    end
end

%% do curve fitting and make plots

if do_plot

    [fitresult{1}, gof{1},x_mean_wb,y_mean_wb] = createFit(num_feats_full(:)', mean(pred_outcome_r_full),'color',[.5 .5 .5],'linewidth',2);
    [fitresult{2}, gof{2},x_mean_parcels,y_mean_parcels] = createFit(num_feats_all_parcels(:)', mean(pred_outcome_r_all_parcels),'color',[.1 .1 .1],'linewidth',2);

    for r=1:num_parcels

        mean_r_within=squeeze(mean(pred_outcome_r(:,r,1:size(pred_outcome_r_all_parcels,2))));
        [fitresult{2+r}, gof{2+r},x_mean_parcel{r},y_mean_parcel{r}] = createFit(num_feats_within(r,:)', mean_r_within(:),'color',mycolors{r},'linewidth',2);

    end

    for it=1:num_iterations
        [~, ~,x_wb(it,:),y_wb(it,:)] = createFit(num_feats_full(:)', pred_outcome_r_full(it,:),'color',[.5 .5 .5],'linewidth',2);
        [~, ~,x_all_parcels(it,:),y_all_parcels(it,:)] = createFit(num_feats_all_parcels(:)', pred_outcome_r_all_parcels(it,:),'color',[.1 .1 .1],'linewidth',2);

        for r=1:num_parcels

            r_within=squeeze((pred_outcome_r(it,r,1:size(pred_outcome_r_all_parcels,2))));
            [~, ~,x{it,r},y{it,r}] = createFit(num_feats_within(r,:)', r_within(:),'color',mycolors{r},'linewidth',2);

        end
    end

    figure;
    hold on;
    boundedline(mean(x_wb),mean(y_wb), std(y_wb),'alpha', 'cmap',[.5 .5 .5]);
    boundedline(mean(x_all_parcels), mean(y_all_parcels), std(y_all_parcels),'alpha', 'cmap',[.1 .1 .1]);

    for r=1:num_parcels
        clear to_plot_x to_plot_y
        for i=1:size(x,1)
            to_plot_x(i,:)=x{i,r};
            to_plot_y(i,:)=y{i,r};
        end
        boundedline(mean(to_plot_x), mean(to_plot_y), std(to_plot_y),'alpha', 'cmap',mycolors{r});

    end
    h=findobj(gca,'type','line');
    set(h,'linewidth',2);
    set(gca,'XScale','log')
    grid on
    legend(h(1:end),{atlas_labels{:} 'All Parcels' 'Whole-brain'});

    xlabel 'Number of voxels'
    ylabel 'Model performance'

    % add brain render to plot

    axis tight;
    if render_brain

        clear o2
        o2=fmridisplay();
        o2 = surface(o2, 'axes', [0.5 0 .5 .5], 'direction', 'surface left', 'orientation', 'lateral','trans');
        o2 = surface(o2, 'axes', [0.5 .5 .4 .4], 'direction', 'surface right', 'orientation', 'lateral');

        pname = 'R.pial_MSMAll_2_d41_WRN_DeDrift.32k.mat'; % from Glasser_et_al_2016_HCP

        try
            load(which(pname))
        catch
            error('Unable to find ''R.pial_MSMAll_2_d41_WRN_DeDrift.32k.mat'' please check your path');
        end

        set(o2.surface{1}.object_handle(1),'FaceVertexCData',cdata)
        set(o2.surface{2}.object_handle(1),'FaceVertexCData',cdata)
        colormap gray

        %add mask regions
        for i=1:size(parcel_obj.dat,2)
            tv=parcel_obj;
            tv.dat=tv.dat(:,i);

            o2=addblobs(o2,region(tv),'splitcolor',{mycolors{i} mycolors{i} mycolors{i} mycolors{i}});

        end

        %clear brainstem
        delete(o2.surface{1}.object_handle(2))
        delete(o2.surface{2}.object_handle(2))

        %position axes
        ha=findobj(gcf,'type','axes');
        newpos=[[.315 .1 .3 .3];[.61 .1 .3 .3]];
        for i=1:2
            set(ha(i),'Position',newpos(i,:))
        end
        set(ha([1]),'view',[-90 0]);
        set(ha([2]),'view',[90 0]);

    end
end

%%  stats across regions
random_subsampled_outcomes=cat(2,permute(cat(3,pred_outcome_r_full,pred_outcome_r_all_parcels),[1,3,2]),pred_outcome_r);

for i=1:size(random_subsampled_outcomes,2)
    for j=1:size(random_subsampled_outcomes,2)

        if i<j

            b_mean = squeeze(nanmean(random_subsampled_outcomes(:,i,size(random_subsampled_outcomes,3)-1)- random_subsampled_outcomes(:,j,size(random_subsampled_outcomes,3)-1)));
            b_ste = squeeze(nanstd(random_subsampled_outcomes(:,i,size(random_subsampled_outcomes,3)-1) - random_subsampled_outcomes(:,j,size(random_subsampled_outcomes,3)-1)));
            b_ste(b_ste == 0) = Inf;
            b_Z(i,j) = b_mean ./ b_ste;
            b_P(i,j) = 2*normcdf(-1*abs(b_Z(i,j)),0,1);

        end
    end
end

stats.pairwise_comparisons.Z = b_Z;
stats.pairwise_comparisons.P = b_P;


function Retorno_Puntero()
    global Puntero
        vect_Punt = getfield(Puntero, 'translation');
        Pos_actual = vect_Punt(1,2);
            despl_retor = Pos_actual:0.01:2.5;
        for r=1:length(despl_retor)
            Puntero.translation = [ 0 despl_retor(r) vect_Punt(1,3)];
            pause(0.01);
        end
end


function varargout = area(f, varargin)
%AREA   Filled CHEBFUN area plot.
%   AREA(X, F) or AREA(F) is the same as PLOT(X, F) or PLOT(F) except that the
%   area between 0 and F is filled. When F is array-valued, AREA(F) plots the
%   columns of Y as filled areas.
%
%   AREA(F, LEVEL) specifies the base level for the area plot to be at the value
%   y = LEVEL. The default value is LEVEL = 0.
%
%   AREA(..., 'Prop1', VALUE1, 'Prop2', VALUE2,...) sets the specified
%   properties of the underlying areaseries objects.
%
%   AREA(AX, ...) plots into axes with handle AX. Use GCA to get the handle to
%   the current axes or to create one if none exist.
%
%   H = AREA(...) returns a vector of handles to areaseries objects.
%
% See also PLOT.

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

% TODO: Quasimatrix support?

% Deal with empty case:
if ( isempty(f) )
    varargout{1} = plot(); %#ok<LTARG>
    return
end

if ( numel(f) > 1 )
    try
        f = quasi2cheb(f);
    catch ME
        error('CHEBFUN:CHEBFUN:area:quasi', ...
            'AREA() does not support quasimatrices.');
    end
end

% Get the (x, y) data from PLOTDATA():
if ( (nargin > 1) && isa(varargin{1}, 'chebfun') )
    g = varargin{1};
    if ( numel(g) > 1 )
        try
            g = quasi2cheb(g);
        catch ME
            error('CHEBFUN:CHEBFUN:area:quasi', ...
                'AREA() does not support quasimatrices.');
        end
    end
    varargin(1) = [];
    data = plotData(f, g);
else
    data = plotData(f);
end

x = data.xLine;
y = data.yLine;

% Remove NaNs from jumps:
if ( isnan(x(1)) )
    x(1) = x(2);
    y(1,:) = y(2,:);
end
if ( isnan(x(end)) )
    x(end) = x(end-1);
    y(end,:) = y(end-1,:);
end
mask = find(isnan(x));
% Take average of left/right for y:
y(mask,:) = (y(mask+1,:) + y(mask-1,:))/2;
% Take subsequent point for x:
x(mask) = x(mask+1);

% Call built-in AREA():
h = area(x, y, 'LineStyle', 'None', varargin{:});

% Output handle to plot window:
if ( nargout == 1 )
    varargout{1} = h;
end

end