text:
function [pipeline] = ft_analysispipeline(cfg, data)

% FT_ANALYSIPIPELINE reconstructs the complete analysis pipeline that was used to create
% the input FieldTrip data structure. The pipeline will be visualized as a flowchart.
% In the future it will be possible to output the complete pipeline as a MATLAB script
% or in a specialized pipeline format (e.g. PSOM, JIST, LONI, Taverna).
%
% Use as
%   output = ft_analysispipeline(cfg, data)
%
% The first cfg input contains the settings that apply to the behavior of this
% particular function and the second data input argument can be the output of any
% FieldTrip function, e.g. FT_PREPROCESSING, FT_TIMELOCKANALYSIS, FT_SOURCEANALYSIS,
% FT_FREQSTATISTICS or whatever you like.
%
% Alternatively, for the second input argument you can also only give the configuration
% of the processed data (i.e. "data.cfg") instead of the full data.
%
% The configuration options that apply to the behavior of this function are
%   cfg.filename   = string, filename without the extension
%   cfg.filetype   = string, can be 'matlab', 'html' or 'dot'
%   cfg.feedback   = string, 'no', 'text', 'gui' or 'yes', whether text and/or
%                    graphical feedback should be presented (default = 'yes')
%   cfg.showinfo   = string or cell-array of strings, information to display
%                    in the gui boxes, can be any combination of
%                    'functionname', 'revision', 'matlabversion',
%                    'computername', 'username', 'calltime', 'timeused',
%                    'memused', 'workingdir', 'scriptpath' (default =
%                    'functionname', only display function name). Can also
%                    be 'all', show all pipeline. Please note that if you want
%                    to show a lot of information, this will require a lot
%                    of screen real estate.
%   cfg.remove     = cell-array with strings, determines which objects will
%                    be removed from the configuration prior to writing it to
%                    file. For readibility of the script, you may want to
%                    remove the large objectssuch as event structure, trial
%                    definition, source positions
%  cfg.keepremoved = 'yes' or 'no', determines whether removed fields are
%                    completely removed, or only replaced by a short textual
%                    description (default = 'no')
%
% This function uses the nested cfg and cfg.previous that are present in
% the data structure. It will use the configuration and the nested previous
% configurations to climb all the way back into the tree. This funtction
% will print a complete MATLAB script to screen (and optionally to file).
% Furthermore, it will show an interactive graphical flowchart
% representation of the steps taken during the pipeline(i). In the flowchart
% you can click on one of the steps to see the configuration details of
% that pipeline(i).
%
% Note that the nested cfg and cfg.previous in your data might not contain
% all details that are required to reconstruct a complete and valid
% analysis script.
%
% To facilitate data-handling and distributed computing you can use
%   cfg.inputfile   =  ...
% If you specify this, the input data will be read from a *.mat file on disk. The
% file should contain only a single variable, corresponding with the input structure.
%
% See also FT_PREPROCESSING, FT_TIMELOCKANALYSIS, FT_FREQANALYSIS, FT_SOURCEANALYSIS,
% FT_CONNECTIVITYANALYSIS, FT_NETWORKANALYSIS

% Copyright (C) 2014-2015, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% these are used by the ft_preamble/ft_postamble function and scripts
ft_revision = '$Id$';
ft_nargin   = nargin;
ft_nargout  = nargout;

% callinfo feedback is highly annoying in this recursive function
% do this here, otherwise ft_defaults will override our setting
if ~isfield(cfg, 'showcallinfo'), cfg.showcallinfo = 'no';   end

% do the general setup of the function
ft_defaults
ft_preamble init
ft_preamble debug
ft_preamble loadvar    data
ft_preamble provenance data
ft_preamble trackconfig

% the ft_abort variable is set to true or false in ft_preamble_init
if ft_abort
  return
end

% set the defaults
cfg.filename    = ft_getopt(cfg, 'filename');
cfg.showinfo    = ft_getopt(cfg, 'showinfo', {'functionname'});
cfg.keepremoved = ft_getopt(cfg, 'keepremoved', 'no');
cfg.feedback    = ft_getopt(cfg, 'feedback', 'text');
cfg.prune       = ft_getopt(cfg, 'prune', 'yes');
cfg.filetype    = ft_getopt(cfg, 'filetype');
cfg.fontsize    = ft_getopt(cfg, 'fontsize', 10);

if isempty(cfg.filetype) && ~isempty(cfg.filename)
  [p, f, x] = fileparts(cfg.filename);
  switch x
    case '.m'
      cfg.filetype = 'matlab';
    case '.html'
      cfg.filetype = 'html';
    case '.dot'
      cfg.filetype = 'dot';
    otherwise
      ft_error('cannot determine filetype');
  end
end

if ~isfield(cfg, 'remove')
  % this is the default list of configuration elements to be removed. These
  % elements would be very large to print and make the script difficult to
  % read. To get a correctly behaving script, you may have to change this.
  cfg.remove = {
    'sgncmb'
    'channelcmb'
    'event'
    'trl'
    'trlold'
    'artfctdef.eog.trl'
    'artfctdef.jump.trl'
    'artfctdef.muscle.trl'
    'pos'
    'inside'
    'outside'
    'sourcemodel.pos'
    'sourcemodel.inside'
    'sourcemodel.outside'
    'vol.bnd.pos'
    'vol.bnd.tri'
    'headmodel.bnd.pos'
    'headmodel.bnd.tri'
    };
elseif ~iscell(cfg.remove)
  cfg.remove = {cfg.remove};
end

if strcmp(cfg.showinfo, 'all')
  cfg.showinfo = {
    'functionname'
    'revision'
    'matlabversion'
    'computername'
    'architecture'
    'username'
    'calltime'
    'timeused'
    'memused'
    'workingdir'
    'scriptpath'
    };
end

if ~isfield(cfg, 'showinfo')
  cfg.showinfo = {'functionname'};
elseif ~iscell(cfg.showinfo)
  cfg.showinfo = {cfg.showinfo};
end

% we are only interested in the cfg-part of the data
if isfield(data, 'cfg')
  datacfg = data.cfg;
else
  datacfg = data;
end
clear data

% walk the tree, gather information about each node
ft_progress('init', cfg.feedback, 'parsing provenance...');
pipeline = walktree(datacfg);
ft_progress('close');

% convert the cell-array into a structure array
for i=1:length(pipeline)
  tmp(i) = pipeline{i};
end
pipeline = tmp;

if istrue(cfg.prune)
  % prune the double occurences
  [dummy, indx] = unique({pipeline.this});
  pipeline = pipeline(sort(indx));
end

% start at the end of the tree and determine the level of each of the parents
hasparent = false(size(pipeline));
haschild  = false(size(pipeline));
for i=1:length(pipeline)
  hasparent(i) = ~isempty(pipeline(i).parent);
  haschild(i)  = any(strcmp(pipeline(i).this, [pipeline.parent]));
end

% construct a matrix with all pipeline steps
width  = zeros(size(pipeline));
height = zeros(size(pipeline));
level  = 1;
% the items without children start at height 1
sel = find(~haschild);
while ~isempty(sel)
  height(sel) = level;
  % find the parents of the items at this level
  sel = match_str({pipeline.this}, [pipeline(sel).parent]);
  % the parents should be at least one level higher
  height(sel) = level + 1;
  % continue with the next level
  level = level + 1;
end
for i=1:max(height)
  sel = find(height==i);
  width(sel) = 1:length(sel);
end
for i=1:length(pipeline)
  pipeline(i).position = [height(i) width(i)];
end

% sort according to a decreasing level, i.e. the last pipeline(i) at the end
[dummy, indx] = sortrows(-[height(:) width(:)]);
pipeline = pipeline(indx);

if isempty(cfg.filename)
  pipeline2matlabfigure(cfg, pipeline);
else
  switch cfg.filetype
    case 'matlab'
      pipeline2matlabscript(cfg, pipeline);
    case 'dot'
      pipeline2dotfile(cfg, pipeline);
    case 'html'
      pipeline2htmlfile(cfg, pipeline);
    otherwise
      ft_error('unsupported filetype');
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for recursive walking along the cfg.previous.previous info
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function info = walktree(cfg)

if isempty(cfg) || (isstruct(cfg) && numel(fieldnames(cfg))==0)
  info = [];
  return
end

this = getnode(cfg);

% parse all previous steps
if isfield(cfg, 'previous') && ~isempty(cfg.previous) && iscell(cfg.previous)
  previous = cellfun(@walktree, cfg.previous, 'UniformOutput', false);
  if iscell(previous{1})
    previous = cat(2, previous{:});
  end
elseif isfield(cfg, 'previous') && ~isempty(cfg.previous) && isstruct(cfg.previous)
  previous = walktree(cfg.previous);
elseif isfield(cfg, 'previous') && ~isempty(cfg.previous)
  ft_error('unexpected content in cfg.previous');
else
  previous = {};
end

% parse the side branches, such as cfg.headmodel and cfg.layout
fn = fieldnames(cfg);
branch = {};
for i=1:numel(fn)
  if isstruct(cfg.(fn{i})) && isfield(cfg.(fn{i}), 'cfg')
    branch = [walktree(cfg.(fn{i}).cfg) branch];
    this.parent{end+1} = branch{1}.this; % the start of the branch is a parent to this element
  end
end

ft_progress(rand(1), 'parsing provenance for %s\n', this.name); % FIXME no percentage complete known
drawnow

% the order of the output elements matters for the recursion
info = [{this} branch previous];

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for gathering the information about each pipeline
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function node = getnode(cfg)
[p, f, x]      = myfileparts(getvalue(cfg, 'version.name'));
node.cfg       = cfg;
node.name      = f;
node.id        = getvalue(cfg, 'version.id');
node.this      = ft_hash(cfg);
if isfield(cfg, 'previous') && ~isempty(cfg.previous) && iscell(cfg.previous)
  % skip the entries that are empty
  cfg.previous = cfg.previous(~cellfun(@isempty, cfg.previous));
  node.parent   = cellfun(@ft_hash, cfg.previous, 'UniformOutput', false);
elseif isfield(cfg, 'previous') && ~isempty(cfg.previous) && isstruct(cfg.previous)
  node.parent   = {ft_hash(cfg.previous)};
elseif isfield(cfg, 'previous') && ~isempty(cfg.previous)
  ft_error('unexpected content in cfg.previous');
else
  node.parent   = {};
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function v = getvalue(s, f)
if issubfield(s, f)
  v = getsubfield(s, f);
else
  v = 'unknown';
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [p, f, x] = myfileparts(filename)
if ispc
  filename(filename=='/') = filesep;
else
  filename(filename=='\') = filesep;
end
[p, f, x] = fileparts(filename);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = button(h, eventdata, handles, varargin)
pos = get(get(gcbo, 'CurrentAxes'), 'CurrentPoint');
x = pos(1,1);
y = pos(1,2);
pipeline = guidata(h);

for i=1:numel(pipeline)
  if (x >= pipeline(i).x(1) && x <= pipeline(i).x(2) && y >= pipeline(i).y(1) && y <= pipeline(i).y(3))
    cfg = pipeline(i).cfg;
    if isfield(cfg, 'previous')
      cfg = rmfield(cfg, 'previous');
    end
    % use a helper function to remove uninteresting fields
    cfg = removefields(cfg, ignorefields('pipeline'), 'recursive', true);
    % use a helper function to remove too large fields
    cfg.checksize = 3000;
    cfg = ft_checkconfig(cfg, 'checksize', 'yes');
    cfg = rmfield(cfg, 'checksize');
    script = printstruct('cfg', cfg);
    uidisplaytext(script, pipeline(i).name);
    break;
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function pipeline2matlabfigure(cfg, pipeline)

fprintf('plotting pipeline as MATLAB figure\n');

layout = cell(numel(pipeline));
for i=1:length(pipeline)
  % get the vertical and horizontal position in integer values
  % high numbers are towards the begin, low numbers are towards the end of the pipeline
  v = pipeline(i).position(1);
  h = pipeline(i).position(2);
  layout{v,h} = pipeline(i).this;
end

% remove the empty columns
maxheight = max(sum(~cellfun(@isempty, layout),1));
maxwidth  = max(sum(~cellfun(@isempty, layout),2));
layout    = layout(1:maxheight,1:maxwidth);

fig = figure;
hold on
axis manual; % the axis should not change during the contruction of the arrows, otherwise the arrowheads will be distorted
set(gca, 'Units', 'normalized'); % use normalized units
set(gcf, 'ToolBar', 'none');
axis([0 1 0 1])
axis off;
axis tight;

for i=1:numel(pipeline)

  label = makelabel(pipeline(i), cfg.showinfo);

  % dublicate backslashes to escape tex interpreter (in case of windows filenames)
  label = strrep(label, '\', '\\');
  label = strrep(label, '{\\bf', '{\bf'); % undo for bold formatting

  % escape underscores
  label = strrep(label, '_', '\_');

  % strip blank line if present and not needed
  if strcmp(label{end}, '')
    label(end) = [];
  end

  % compute width and height of each box, note that axis Units are set to Normalized
  boxsize = 1./[maxwidth+1 maxheight+3];

  % create the 4 corners for our patch, close the patch by returning to the start point
  x = ([0 1 1 0 0]-0.5) .* boxsize(1);
  y = ([0 0 1 1 0]-0.5) .* boxsize(2);

  % position the patch
  location    = pipeline(i).position([2 1]);
  location(1) = (location(1)-0.5)/maxwidth;
  location(2) = (location(2)-0.5)/maxheight;

  % the location specifies the center of the patch
  x = x + location(1);
  y = y + location(2);

  p = patch(x', y', 0);
  set(p, 'Facecolor', [1 1 0.6])

  pipeline(i).x = x;
  pipeline(i).y = y;
  guidata(fig, pipeline);

  if length(label)==1
    textloc = location;
    l = text(textloc(1), textloc(2), label);
    set(l, 'HorizontalAlignment', 'center');
    set(l, 'VerticalAlignment', 'middle');
    set(l, 'fontUnits', 'points');
    set(l, 'fontSize', cfg.fontsize);
    set(l, 'interpreter', 'tex');
  else
    textloc = location;
    textloc(1) = textloc(1)-boxsize(1)/2;
    textloc(2) = textloc(2)+boxsize(2)/2;

    l = text(textloc(1), textloc(2), label);
    set(l, 'HorizontalAlignment', 'left');
    set(l, 'VerticalAlignment', 'top');
    set(l, 'fontUnits', 'points');
    set(l, 'fontSize', cfg.fontsize);
    set(l, 'interpreter', 'tex');
  end

  % draw an arrow if appropriate
  n = length(pipeline(i).parent);

  for j=1:n
    [parentlocation(2), parentlocation(1)] = ind2sub([maxheight, maxwidth], find(strcmp(layout(:), pipeline(i).parent{j}), 1, 'first'));
    % parentlocation = info(find(strcmp({pipeline.this}, analysis.parent{j}), 1, 'first')).position;
    parentlocation(1) = (parentlocation(1)-0.5)/maxwidth;
    parentlocation(2) = (parentlocation(2)-0.5)/maxheight;
    base = parentlocation + [0 -0.5].*boxsize;
    if false % n>1
      % distribute the inputs evenly over the box
      rel = 2*(j+n-1)/(n-1)-1; % relative location between -1.0 and 1.0
      rel = rel*(n-1)/(n+3);   % compress the relative location
      tip = location + [0 0.5].*boxsize + [rel 0].*boxsize/2;
    else
      % put it in the centre
      tip  = location + [0 0.5].*boxsize;
    end
    arrow(base, tip, 'length', 8, 'lineWidth', 1);
  end

end % for numel(info)

set(fig, 'WindowButtonUpFcn', @button);
% set(fig, 'KeyPressFcn', @key);

% add a context menu to the figure
% ftmenu = uicontextmenu; set(gcf, 'uicontextmenu', ftmenu)

% add a regular menu item to the figure
ftmenu  = uimenu(fig, 'Label', 'FieldTrip');
% ftmenu1 = uimenu(ftmenu, 'Label', 'Save pipeline');
% ftmenu2 = uimenu(ftmenu, 'Label', 'Share pipeline');
uimenu(ftmenu, 'Label', 'About',  'Separator', 'on', 'Callback', @menu_about);
% uimenu(ftmenu1, 'Label', 'Save as MATLAB script');
% uimenu(ftmenu1, 'Label', 'Save as PSOM pipeline');
% uimenu(ftmenu1, 'Label', 'Save as HTML page');
% uimenu(ftmenu2, 'Label', 'Share within DCCN');
% uimenu(ftmenu2, 'Label', 'Share on PasteBin.com');
% uimenu(ftmenu2, 'Label', 'Share on MyExperiment.org');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function label = makelabel(pipeline, showinfo)
% create the text information to display
label = {};
for k = 1:numel(showinfo)
  switch showinfo{k}

    case 'functionname'
      % label{end+1} = ['{\bf ' pipeline(i).name '}'];
      label{end+1} = pipeline.name;
      if k == 1 % add blank line if function name is on top, looks nice
        label{end+1} = '';
      end

    case 'revision'
      if isfield(pipeline.cfg, 'version') && isfield(pipeline.cfg.version, 'id')
        label{end+1} = pipeline.cfg.version.id;
      else
        label{end+1} = '<revision unknown>';
      end

    case 'matlabversion'
      if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'matlab')
        label{end+1} = ['MATLAB ' pipeline.cfg.callinfo.matlab];
      else
        label{end+1} = '<MATLAB version unknown>';
      end

    case 'computername'
      if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'hostname')
        label{end+1} = ['Hostname: ' pipeline.cfg.callinfo.hostname];
      else
        label{end+1} = '<hostname unknown>';
      end

    case 'architecture'
      if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'hostname')
        label{end+1} = ['Architecture: ' pipeline.cfg.callinfo.computer];
      else
        label{end+1} = '<architecture unknown>';
      end

    case 'username'
      if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'user')
        label{end+1} = ['Username: ' pipeline.cfg.callinfo.user];
      else
        label{end+1} = '<username unknown>';
      end

    case 'calltime'
      if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'calltime')
        label{end+1} = ['Function called at ' datestr(pipeline.cfg.callinfo.calltime)];
      else
        label{end+1} = '<function call time unknown>';
      end

    case 'timeused'
      if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'proctime')
        label{end+1} = sprintf('Function call required %d seconds', round(pipeline.cfg.callinfo.proctime));
      else
        label{end+1} = '<processing time unknown>';
      end

    case 'memused'
      if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'procmem')
        label{end+1} = sprintf('Function call required %d MB', round(pipeline.cfg.callinfo.procmem/1024/1024));
      else
        label{end+1} = '<memory requirement unknown>';
      end

    case 'workingdir'
      if isfield(pipeline.cfg, 'callinfo') && isfield(pipeline.cfg.callinfo, 'pwd')
        label{end+1} = sprintf('Working directory was %s', pipeline.cfg.callinfo.pwd);
      else
        label{end+1} = '<working directory unknown>';
      end

    case 'scriptpath'
      if isfield(pipeline.cfg, 'version') && isfield(pipeline.cfg.version, 'name')
        label{end+1} = sprintf('Full path to script was %s', pipeline.cfg.version.name);
      else
        label{end+1} = '<script path unknown>';
      end
  end
end % for numel(showinfo)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function pipeline2matlabscript(cfg, pipeline)

[p, f, x] = fileparts(cfg.filename);
filename = fullfile(p, [f '.m']);

fprintf('exporting MATLAB script to file ''%s''\n', filename);

varname = {};
varhash = {};

for i=1:length(pipeline)
  varname{end+1} = sprintf('variable_%d_%d', pipeline(i).position(1), pipeline(i).position(2));
  varhash{end+1} = pipeline(i).this;
end

for i=1:length(pipeline)
  pipeline(i).inputvar  = {};
  pipeline(i).outputvar = varname{strcmp(varhash, pipeline(i).this)};
  for j=1:length(pipeline(i).parent)
    pipeline(i).inputvar{j} = varname{strcmp(varhash, pipeline(i).parent{j})};
  end
end

sep    = sprintf('\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n');
script = sep;
for i=1:length(pipeline)
  thiscfg = pipeline(i).cfg;
  if isfield(thiscfg, 'previous')
    thiscfg = rmfield(thiscfg, 'previous');
  end
  cfgstr    = printstruct('cfg', thiscfg);
  if ~isempty(pipeline(i).inputvar)
    inputvar = sprintf(', %s', pipeline(i).inputvar{:});
  else
    inputvar = '';
  end
  cmd       = sprintf('\n%s = %s(cfg%s);', pipeline(i).outputvar, pipeline(i).name, inputvar);
  script    = cat(2, script, cfgstr, cmd, sep);
end

% write the complete script to file
fid = fopen(filename, 'wb');
fprintf(fid, '%s', script);
fclose(fid);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function pipeline2dotfile(cfg, pipeline)

[p, f, x] = fileparts(cfg.filename);
filename = fullfile(p, [f '.dot']);

fprintf('exporting DOT file to ''%s''\n', filename);

% write the complete script to file
fid = fopen(filename, 'wb');

fprintf(fid, 'digraph {\n');

varhash = {pipeline.this};

for i=1:length(pipeline)
  for j=1:length(pipeline(i).parent)
    fprintf(fid, '%d -> %d\n', find(strcmp(varhash, pipeline(i).parent{j})), i);
  end
end

for i=1:length(pipeline)
  label = makelabel(pipeline(i), cfg.showinfo);
  if numel(label)>2
    % left justified
    label = sprintf('%s\\l', label{:});
    label = label(1:end-2);
  else
    % centered
    label = sprintf('%s\\n', label{:});
    label = label(1:end-2);
  end
  fprintf(fid, '%d [label="%s",shape=box,fontsize=%d,URL="http://www.fieldtriptoolbox.org/reference/%s"]\n', i, label, cfg.fontsize, pipeline(i).name);
end

fprintf(fid, '}\n');

fclose(fid);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function pipeline2htmlfile(cfg, pipeline)

[p, f, x] = fileparts(cfg.filename);
filename = fullfile(p, [f '.html']);

fprintf('exporting HTML file to ''%s''\n', filename);

html = '';
totalproctime = 0;

ft_progress('init', cfg.feedback, 'serialising cfg-structures...');

for k = 1:numel(pipeline)
  ft_progress(k/numel(pipeline), 'serialising cfg-structure %d from %d', k, numel(pipeline));

  % strip away the cfg.previous fields, and all data-like fields
  tmpcfg = removefields(pipeline(k).cfg, ignorefields('html'));

  usercfg = [];

  % record the usercfg and proctime if present
  if isfield(tmpcfg, 'callinfo')
    if isfield(tmpcfg.callinfo, 'usercfg')
      usercfg = removefields(tmpcfg.callinfo.usercfg, ignorefields('html'));

      % avoid processing usercfg twice
      tmpcfg.callinfo = rmfield(tmpcfg.callinfo, 'usercfg');
    end

    if isfield(tmpcfg.callinfo, 'proctime')
      totalproctime = totalproctime + tmpcfg.callinfo.proctime;
    end
  end

  html = [html sprintf('nodes["%s"] = {"id": "%s", "name": "%s", "cfg": "%s", "usercfg": "%s", "parentIds": [',...
    pipeline(k).this, pipeline(k).this, pipeline(k).name, escapestruct(tmpcfg), escapestruct(usercfg))];

  if ~isempty(pipeline(k).parent)
    for j = 1:numel(pipeline(k).parent)
      html = [html '"' pipeline(k).parent{j} '"'];
      if j < numel(pipeline(k).parent)
        html = [html ','];
      end
    end
  end

  html = [html sprintf(']};\n')];

  if k == numel(pipeline)
    % we are at the single leaf node
    html = [html sprintf('var leafId = "%s";\n', pipeline(k).this)];
  end

end
ft_progress('close');

html = [html(1:end-2) sprintf('\n')];

% load the skeleton and put in the html code
thispath = fileparts(mfilename('fullpath'));
htmlfile = fileread([thispath '/private/pipeline-skeleton.html']);

timestamp = [datestr(now(), 'ddd') ' ' datestr(now())];
proctimestr = print_tim(totalproctime);
htmlfile = strrep(htmlfile, '${TIMESTAMP}', timestamp);
htmlfile = strrep(htmlfile, '${PIPELINE}', html);
htmlfile = strrep(htmlfile, '${USER}', getusername());
htmlfile = strrep(htmlfile, '${PROCTIME}', proctimestr);

% write the file
fid = fopen(filename, 'w');
fwrite(fid, htmlfile, 'uchar');
fclose(fid);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cfghtml = escapestruct(tmpcfg)
% convert the cfg structure to a suitable string (escape newlines and
% quotes)

% strip away big numeric fields
if isstruct(tmpcfg)
  fields = fieldnames(tmpcfg);
  for k = 1:numel(fields)
    if isnumeric(tmpcfg.(fields{k})) && numel(tmpcfg.(fields{k})) > 400
      tmpcfg.(fields{k}) = '[numeric data of >400 elements stripped]';
    end
  end
end
cfghtml = strrep(printstruct('cfg', tmpcfg), '\', '\\');
cfghtml = strrep(cfghtml, sprintf('\r'), '\r');
cfghtml = strrep(cfghtml, sprintf('\n'), '\n');
cfghtml = strrep(cfghtml, sprintf('\t'), '\t');
cfghtml = strrep(cfghtml, '"', '\"');


text:
function L = probitNoiseLogLikelihood(noise, mu, varsigma, y)

% PROBITNOISELOGLIKELIHOOD Log likelihood of the data under the PROBIT noise model.
% FORMAT
% DESC returns the log likelihood of a data set under the  probit based classification noise model.
% ARG noise : the noise structure for which the log likelihood is required.
% ARG mu : input mean locations for the log likelihood.
% ARG varSigma : input variance locations for the log likelihood.
% ARG y : target locations for the log likelihood.
%
% SEEALSO : probitNoiseParamInit, probitNoiseLikelihood, noiseLogLikelihood
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005

% NOISE

D = size(y, 2);
for i = 1:D
  mu(:, i) = mu(:, i) + noise.bias(i);
end

L = sum(sum(lnCumGaussian((y.*mu)./(sqrt(noise.sigma2+varsigma)))));

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
% Focussed Detector Example in 2D
%
% This example shows how k-Wave can be used to model the output of a
% focussed semicircular detector where the directionality arises from
% spatially averaging across the detector surface. It builds on the
% Homogeneous Propagation Medium and Using A Binary Sensor Mask examples.
%
% author: Ben Cox
% date: 20th January 2010
% last update: 16th December 2011
%
% This function is part of the k-Wave Toolbox (http://www.k-wave.org)
% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox

% This file is part of k-Wave. k-Wave is free software: you can
% redistribute it and/or modify it under the terms of the GNU Lesser
% General Public License as published by the Free Software Foundation,
% either version 3 of the License, or (at your option) any later version.
%
% k-Wave 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 Lesser General Public License for
% more details.
%
% You should have received a copy of the GNU Lesser General Public License
% along with k-Wave. If not, see <http://www.gnu.org/licenses/>.
clear all;

% =========================================================================
% SIMULATION
% =========================================================================

% create the computational grid
Nx = 180;           % number of grid points in the x (row) direction
Ny = 180;           % number of grid points in the y (column) direction
dx = 0.1e-3;        % grid point spacing in the x direction [m]
dy = 0.1e-3;        % grid point spacing in the y direction [m]
kgrid = makeGrid(Nx, dx, Ny, dy);

% define the properties of the propagation medium
medium.sound_speed = 1500;    % [m/s]

% define a sensor as part of a circle centred on the grid
sensor_radius = 65; % [grid points]
arc_angle = pi;     % [rad]
sensor.mask = makeCircle(Nx, Ny, Nx/2, Ny/2, sensor_radius, arc_angle);

% define the array of temporal points [s] and shorten it to make the
% example finish sooner
[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed);
kgrid.t_array = (0:round(length(kgrid.t_array)*0.75))*dt;

% place a disc-shaped source near the focus of the detector
source.p0 = makeDisc(Nx, Ny, Nx/2, Ny/2, 4)*2;

% run the first simulation
sensor_data1 = kspaceFirstOrder2D(kgrid, medium, source, sensor);

% place a disc-shaped source away from the focus of the detector
source.p0 = makeDisc(Nx, Ny, Nx/2, Ny/2+20, 4)*2;

% run the second simulation
sensor_data2 = kspaceFirstOrder2D(kgrid, medium, source, sensor);

% average the outputs of the simulations over the points making up the sensor
sensor_output1 = sum(sensor_data1,1)/sum(sensor.mask(:));
sensor_output2 = sum(sensor_data2,1)/sum(sensor.mask(:));

% =========================================================================
% VISUALISATION
% =========================================================================

% plot the recorded time signals
figure
[t_sc, t_scale, t_prefix] = scaleSI(kgrid.t_array(end));
plot(kgrid.t_array*t_scale, sensor_output1, 'k', kgrid.t_array*t_scale, sensor_output2, 'r');
xlabel(['Time [' t_prefix 's]']);
ylabel('Average Pressure Measured Over Detector [au]') ;
legend(['Source on focus, sum(output^2) = ' num2str(round(sum(sensor_output1.^2)*100)/100)], ['Source off focus, sum(output^2) = ' num2str(round(sum(sensor_output2.^2)*100)/100)]);

repo: Aero-matlab


text:
function varargout = LinTestPJ(varargin)
%GUI made by Paulo Silva to solve Catalin Eberhardt problem at
%http://www.mathworks.com/matlabcentral/newsreader/view_thread/300770
%psychology experiment that measures how people map numbers to space.
%The task would is as follows: two numbers (e.g. -10 and 10) mark the
%extremities of a line, which is constant from trial to trial; a series of
%numbers appear one by one in the upper part of the screen, and the
%participant has to click on the line where they think that number should
%be (so, for instance, the number 1 would require a click a little to the
%right of the line's midpoint, if the line goes from -10 to 10).
%
%When the GUI starts 10 diferent values are selected and each user will be
%asked to click on the line where he or she thinks the value is located
%
%This GUI will log each participant results and gives the option to save
%the results to a text file
%
% LINTESTPJ M-file for LinTestPJ.fig
%      LINTESTPJ, by itself, creates a new LINTESTPJ or raises the existing
%      singleton*.
%
%      H = LINTESTPJ returns the handle to a new LINTESTPJ or the handle to
%      the existing singleton*.
%
%      LINTESTPJ('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in LINTESTPJ.M with the given input arguments.
%
%      LINTESTPJ('Property','Value',...) creates a new LINTESTPJ or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before LinTestPJ_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to LinTestPJ_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 LinTestPJ

% Last Modified by GUIDE v2.5 12-Jan-2011 19:37:20

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @LinTestPJ_OpeningFcn, ...
                   'gui_OutputFcn',  @LinTestPJ_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 LinTestPJ is made visible.
function LinTestPJ_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 LinTestPJ (see VARARGIN)

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

while (1)
TestValues=ceil(10*rand(1,10));
for a=1:length(TestValues)
Sig=rand;
if (Sig>=0.5)
    Signal=1;
else
    Signal=-1;
end
TestValues(a)=TestValues(a)*Signal;
end

if ((length(unique(TestValues))==length(TestValues(:)))~=0)
    break
end

end

handles.TestValues=TestValues;

% Update handles structure
guidata(hObject, handles);

global Stop

line([0 1],[0.5 0.5]);
box off;
Stop=1;

set(handles.listbox1,'Visible','off');

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

% --- Outputs from this function are returned to the command line.
function varargout = LinTestPJ_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;

function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double

% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

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

User = inputdlg('Please write your name');

global Stop
Stop=0;
hold on;

TestValues=handles.TestValues;

Test=0;

VAL_X=[];
VAL_Y=[];
        but = 1;
        while ((but == 1) & (Stop==0) & (Test<10))
            Test=Test+1;
            set(handles.edit1,'String',TestValues(Test))
            [xi,yi,but] = ginput(1);
            %plot(xi,yi,'r*');
            VAL_X=[VAL_X xi];
            VAL_Y=[VAL_Y yi];

        end

error=TestValues-VAL_X;
str_part = sprintf('User: %s Test Values: %s Selected: %s P.Error %s S.Error: %s ',...
    User{:},mat2str(TestValues),mat2str(error,2),mat2str(VAL_X,2),...
    num2str(abs(sum(error)/10))); %'something'
old_str = get(handles.listbox1, 'String' );
new_str = strvcat(old_str, str_part); %
set(handles.listbox1, 'String', new_str);

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global Stop
Stop=1;

% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns listbox1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listbox1

% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

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

if (strcmp(get(handles.listbox1,'Visible'),'off'));
    set(handles.listbox1,'Visible','on');
    set(handles.pushbutton3,'String','Hide Results');
else
    set(handles.pushbutton3,'String','Show Results');
    set(handles.listbox1,'Visible','off');
end

% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ListBoxValues = get(handles.listbox1, 'String');
fid = fopen('LinTestPJ.txt', 'a+');
% print a title, followed by a blank line
%sprintf(fid, '%s', ListBoxValues);

sizelist=size(ListBoxValues)

lines=sizelist(1);
col=sizelist(2);

for b=1:lines
for a=1:col
%set(handles.listbox1,'Value',a);
str=sprintf('%s',ListBoxValues(b,a)); % the most versatile
fprintf(fid,'%s',str);
end
fprintf(fid,'\n');
end

% print a title, followed by a blank line
fclose(fid);

disp('Results saved to LinTestPJ.txt on the Current Directory');
msgbox('Results saved to LinTestPJ.txt on the Current Directory');

author: Sable

repo: mcbench-benchmarks


text:
function [lmval,indd]=lmin_pw(xx, dx)
%   Find  piece-wise local minima in vector XX,where
%	LMVAL is the output vector with minima values, INDD  is the
%	corresponding indexes, DX is scalar length of piece where minima is searched,
%   IMPORTANT:      FIRST and LAST point in vector are excluded
%   IMPORTANT:      XX must be single column vector
%   IMPORTANT:      Length of DX must be very carefully selected
%	For example compare dx=10; and dx=1000;
%
%   dx=150; xx=[0:0.01:35]'; y=sin(xx .* cos(xx /4.5)) + cos(xx);
%   y(length(y))=-2; plot(xx,y); grid; hold on;
%   %   Excluding first and last points
%   [b,a]=lmin_pw(y,dx); plot(xx(a),y(a),'r+')
%   % Way to include first and last points can be as:
%   yy=[1.5; y; 0];         % padd with values higher than end values
%   [b,a]=lmin_pw(yy,dx); a=a-1; plot(xx(a),y(a),'go')
%
%	see also LMIN,LMAX, LMAX_PW, MATCH

% 	Sergei Koptenko, Applied Acoustic Technologies, Toronto, Canada
%   sergei.koptenko@sympatico.ca,  March/11/2003

if nargin <2,
	disp('Not enough arguments'); return
end

len_x = length(xx);
xx = [xx; xx(end)];
nn=floor(len_x/dx);
ncount=1; lmval=[]; indd=[];
for ii=1:nn,
    [lm,ind] = min(xx(ncount: ii*dx+1)) ;
        ind=ind+(ii-1)*dx;
         if (ind ~=ncount) & (ind~=ii*dx+1),
         lmval=[lmval, lm]; indd=[indd, ind];
end
ncount=ncount +dx;
end
[lm,ind] = min(xx(ii*dx:len_x));
    if (ind ~=len_x) & (ind~=ii*dx),
    lmval=[lmval, lm]; indd=[indd, (ind+ii*dx-1)];
    end

     if indd(end)==len_x,
    indd=indd(1:end-1); lmval=lmval(1:end-1);
    end
return


text:
function testPCA
%%
clc
clear
close all
%%

filename = 'testSet.txt';
K = 1;
data = load(filename);
[lowData,reconMat] = PCA(data,K);
figure
scatter(data(:,1),data(:,2),5,'r')
hold on
scatter(reconMat(:,1),reconMat(:,2),5)
hold off

end

repo: MachineLearning


text:
function X = fruchterman_reingold_force_directed_layout(A,varargin)
% FRUCHTERMAN_REINGOLD_FORCE_DIRECTED_LAYOUT A force directed graph layout
%
% Compute the layout for an unweighted, undirected graph.
% See
% http://www.boost.org/doc/libs/1_36_0/libs/graph/doc/fruchterman_reingold.html
% for information about the layout function and the parameters
%
% The temperature of the layout begins at the value initial_temp and
% decreases to 0 over the number of iterations given.
%
% ... = fruchterman_reingold_force_directed_layout(A,...) takes a set of
% key-value pairs or an options structure.  See set_matlab_bgl_options
% for the standard options.
%   options.iterations: number of layout iterations [int > 0 | {100}]
%   options.initial_temp: starting temperature [double > 0 | {10}]
%   options.force_pairs: computation of forces between pairs of vertices can
%     either be approximated on a grid or computed between all pairs
%     [{'grid'} | 'all']
%   options.width: width of layout area [double | {num_vertices(G)}]
%   options.height: height of layout area [double | {num_vertices(G)}]
%   options.progressive: whether to start from an old layout
%     [{0} | position matrix X]
%
% Note: this function does not depend on the non-zero values of A,
% but only uses the non-zero structure of A
%
% Example:
%   G = grid_graph(6,5);
%   X = fruchterman_reingold_force_directed_layout(G);
%   gplot(G,X);
%   X = fruchterman_reingold_force_directed_layout(G,'initial_temp',100);
%
% See also KAMADA_KAWAI_SPRING_LAYOUT, GURSOY_ATUN_LAYOUT, LAYOUT

% David F. Gleich
% Copyright, Stanford University, 2008

%% History
%  2008-09-25: Initial coding
%%

[trans check full2sparse] = get_matlab_bgl_options(varargin{:});
if full2sparse && ~issparse(A), A = sparse(A); end

n = num_vertices(A);
options = struct('iterations',100,'initial_temp',10,'force_pairs','grid',...
    'width',n,'height',n,'progressive',0);
options = merge_options(options,varargin{:});

if check, check_matlab_bgl(A,struct('sym',1)); end

progressive_opt = [];
if ~isscalar(options.progressive), progressive_opt = options.progressive; end

force_pair_type = 0;
switch options.force_pairs
    case 'grid', force_pair_type = 1;
    case 'all', force_pair_type = 0;
    otherwise, error('matlab_bgl:invalidParameter',...
            'force_pair = %s isn''t a recognized option',options.force_pair);
end

X = fruchterman_reingold_mex(A,options.iterations,options.initial_temp,...
    force_pair_type, options.width, options.height, progressive_opt);

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function [xi,w]=thirdOrderPrismCubPoints()
%%THIRDORDERPRISMCUBPOINTS Generate third-order cubature points for
%  integration over a standard prism in 3D. This is a triangle that has
%  been extruded upward. The vertices are (1,-1,-1), (-1,-1,-1), (-1,1,-1),
%  (1,-1,1), (-1,-1,1), and (-1,1,1).
%
%INPUTS: None
%
%OUTPUTS: xi This is a 3XnumCubPoints set of points for the standard prism.
%          w A 1XnumCubPoints set of cubature weights. This sums to the
%            volume of the standard prism (4).
%
%This function implements the points given in [1] (8 points).
%
%EXAMPLE:
%We compare a 3rd-order moment computed using these cubature points
%to one computed using monomialIntPrism. The results are the same within
%typical finite precision limits.
% [xi,w]=thirdOrderPrismCubPoints();
% alpha=[1;2;0];
% theMoment=findMomentFromSamp(alpha,xi,w);
% intVal=monomialIntPrism(alpha);
% RelErr=(theMoment-intVal)/intVal
%
%REFERENCES:
%[1] F. D. Witherden and P. E. Vincent, "On the identification of symmetric
%    quadrature rules for finite element methods," Computer and Mathematics
%    with Applications, vol. 69, no. 10, pp. 1232-1241, May 2015.
%
%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

M=[-0.33333333333333333333333333333333333333,  -0.33333333333333333333333333333333333333,  -0.86066920446477793249332885107223920359,   0.89998695257960196814387903509173005101;
-0.33333333333333333333333333333333333333,  -0.33333333333333333333333333333333333333,   0.86066920446477793249332885107223920359,   0.89998695257960196814387903509173005101;
-0.52223312808684327863699399822724711768,   0.52222829574978345631488370728601281383,                                          0,     0.366671015806799343952040321636089983;
 0.52222829574978345631488370728601281383,  -0.52223312808684327863699399822724711768,                                          0,     0.366671015806799343952040321636089983;
-0.99999516766294017767788970905876569615,   0.52222829574978345631488370728601281383,                                          0,     0.366671015806799343952040321636089983;
 0.52222829574978345631488370728601281383,  -0.99999516766294017767788970905876569615,                                          0,     0.366671015806799343952040321636089983;
-0.99999516766294017767788970905876569615,  -0.52223312808684327863699399822724711768,                                          0,     0.366671015806799343952040321636089983;
-0.52223312808684327863699399822724711768,  -0.99999516766294017767788970905876569615,                                          0,     0.366671015806799343952040321636089983];

w=M(:,4);
xi=M(:,1:3)';

end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
%-----------------------------------------------------------------------
% This demo use a nailfold video (demo1.avi) to show that blood cells
% tracking and velocity measurement by using one trackpath.
% Written by Yuan Chen,Nanjing university of aeronautic and astronautic(2010)
%-----------------------------------------------------------------------
clear all;
% read the nailfold avi file;
video = aviread('demo1.avi');
video = {video.cdata};
% change 'color' video to gray;
for i=1:length(video);
    video{i}=rgb2gray(video{i});
end

% read the trackpath image;
I = imread('trackpath.bmp');

% finding the start point of the trackpath;
[x,y] = startpoint(I);

% order the trackpath's points;
ind = ord_line_indx(I,x,y);

% generate the spatiotemporal image;
for i = 1:length(video)
    for j = 1:length(ind)
        line = video{i}(ind);
        map(j,i) = line(j);
    end
end
figure,subplot(3,2,1);imshow(map,[]),title('raw spatiotemporal image');

% Jacob filter enhancement;
[F,Theta,angle] = J4(map,2);
subplot(3,2,2);imshow(F,[]),title('Jacob enhancement result');

% applying the noise supression function(nsf);
Idenoised = nsf(F);
subplot(3,2,3);imshow(Idenoised,[]),title('noise supression result');

% applying the orientation filtering function;
h = fspecial('gaussian');
sTheta  = round(imfilter(Theta,h));
K = angfilter(Idenoised,sTheta,angle,20);
sK = imfilter(K,h);
subplot(3,2,4);imshow(sK,[]),title('orientation filter result');

% binary the filtered image;
th = graythresh(sK);    % threshold calculation;
if th < 0.003
    th = 0.003;
end

% [cont,Th] = hist(sK(:));
% th = Th(2);           % threshold calculation;

bw = im2bw(sK,th);
subplot(3,2,5);imshow(bw);title('binary result');

% thinning the image and remove small traces;
thin = bwmorph(bw,'thin',inf);
thin = bwareaopen(thin,size(map,1));
subplot(3,2,6);imshow(thin);title('extracted trace i(i=1,2...)from left to right');

%% velocity measurement;
figure;
[L,num] = bwlabel(thin);
[m,n] = size(thin);
for i = 1:num
    % method1: velocity calculated by orientations;
    indx = find(L==i);
    traceTheta = Theta(indx);                       % finding the orientation of the trace;
    V_trace = abs(tan(pi/180*traceTheta));          % velocity calculation;
    t = 2;
    Velocity1 = V_trace(t:length(V_trace)-t);         % do not calculate boundary data;
    Velocity1 = smooth(Velocity1);                  % smoothing the velocity;
    subplot(num,1,i),plot(Velocity1);axis([0 100 0 3]);title(['trace',int2str(i),'Velocity']);
    % method2: velocity calculated by differential;
    [m1,n1] = ind2sub(size(L),indx);
    for j = 1:length(m1)
        [X(j),Y(j)] = ind2sub(size(I),ind(m1(j)));  % finding the position of the trace points in the trackpath;
    end
    del_x = diff(X);     % dx;
    del_y = diff(Y);     % dy;
    Velocity2 = sqrt(del_x.^2 + del_y.^2);          % velocity calculation;
    Velocity2 = Velocity2(t:length(Velocity2)-t);     % do not calculate boundary data;
    Velocity2 = smooth(Velocity2,10);               % smoothing the velocity;
    hold on;plot(Velocity2,'r');h = legend('Orientation Velocity','Differential Velocity',2);
    xlabel('trace points');ylabel('velocity pixels/s')
    clear X;clear Y;
end


text:
% CVX: Built-in operators and functions supported in CVX models.
%
%   The following operators and functions are included with MATLAB but
%   have either been verified to work properly within CVX models or have
%   been extended with additional code to do so. In many cases, typing
%      help cvx/<func>
%   where <func> is one of the names listed below will provide specific
%   help on the proper use of that item in CVX models---including any
%   restrictions imposed by the DCP and DGP rulesets.
%
%   For a list of new functions created specifically for CVX, type
%   "help cvx/functions".
%
%   The exponential and logarithm functions, along with the starred
%   functions listed in "help cvx/functions", are supported using a
%   "successive approximation" approach: the solver must be called
%   multiple times to achieve the required accuracy. Thus models using
%   these functions should be expected to run more slowly than models
%   of comparable size that do not. See the CVX user guide for details.
%
% Computational operators:
%    plus (+), uplus (unary +), minus (-), uminus (unary -), times (.*),
%    mtimes (*), ldivide (.\), mldivide (\), rdivide (./), mrdivide (/),
%    power (.^), mpower (^), subsref/subsasgn/end (subscripting),
%    transpose (.'), ctranspose (')
% Relational operators:
%    eq (==), ge (>=), gt (>), le (<=), lt(<), ne (~=).
% Linear/affine functions:
%    blkdiag, cat, conj, conv, cumsum, diag, dot, find, flipdim, fliplr,
%    flipud, hankel, horzcat, imag, ipermute, kron, permute, polyval, real,
%    repmat, reshape, rot90, sparse, sum, toeplitz, tril, triu, vertcat
% Nonlinear functions:
%    abs, exp(*), log (*), max, min, norm, prod, sqrt
% Query functions:
%    disp/display, end, isempty, isequal, length, isreal, ndims, nnz,
%    numel, size, spy

% Copyright 2005-2014 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.

author: yu-jiang

repo: radpbook

save_path: github-repos/MATLAB/yu-jiang-radpbook


text:
function tf = isVarInInitialState(var, lvdData)
    initStateModel = lvdData.initStateModel;
    initStateModelOptVars = initStateModel.getAllOptVars();

    tf = false;
    for(i=1:length(initStateModelOptVars))
        isVar = initStateModelOptVars(i);

        if(var == isVar)
            tf = true;
            break;
        end
    end
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function m = maskcircle2(I,type)
% auto pick a circular mask for image I
% built-in mask creation function
% Input: I   : input image
%        type: mask shape keywords
% Output: m  : mask image

% Copyright (c) 2009,
% Yue Wu @ ECE Department, Tufts University
% All Rights Reserved

if size(I,3)~=3
    temp = double(I(:,:,1));
else
    temp = double(rgb2gray(I));
end

h = [0 1 0; 1 -4 1; 0 1 0];
T = conv2(temp,h);
T(1,:) = 0;
T(end,:) = 0;
T(:,1) = 0;
T(:,end) = 0;

thre = max(max(abs(T)))*.5;
idx = find(abs(T) > thre);
[cx,cy] = ind2sub(size(T),idx);
cx = round(mean(cx));
cy = round(mean(cy));

[x,y] = meshgrid(1:min(size(temp,1),size(temp,2)));

m = zeros(size(temp));
[p,q] = size(temp);

switch lower (type)
    case 'small'
        r = 10;
        n = zeros(size(x));
        n((x-cx).^2+(y-cy).^2<r.^2) = 1;
        m(1:size(n,1),1:size(n,2)) = n;
        %m((x-cx).^2+(y-cy).^2<r.^2) = 1;
    case 'medium'
        r = min(min(cx,p-cx),min(cy,q-cy));
        r = max(2/3*r,25);
        n = zeros(size(x));
        n((x-cx).^2+(y-cy).^2<r.^2) = 1;
        m(1:size(n,1),1:size(n,2)) = n;
        %m((x-cx).^2+(y-cy).^2<r.^2) = 1;
    case 'large'
        r = min(min(cx,p-cx),min(cy,q-cy));
        r = max(2/3*r,60);
        n = zeros(size(x));
        n((x-cx).^2+(y-cy).^2<r.^2) = 1;
        m(1:size(n,1),1:size(n,2)) = n;
        %m((x-cx).^2+(y-cy).^2<r.^2) = 1;
    case 'whole'
        r = 5;
        m = zeros(round(ceil(max(p,q)/2/(r+1))*3*(r+1)));
        siz = size(m,1);
        sx = round(siz/2);
        i = 1:round(siz/2/(r+1));
        j = 1:round(0.9*siz/2/(r+1));
        j = j-round(median(j));
        m(sx+2*j*(r+1),(2*i-1)*(r+1)) = 1;
        se = strel('disk',r);
        m = imdilate(m,se);
        m = m(round(siz/2-p/2-6):round(siz/2-p/2-6)+p-1,round(siz/2-q/2-6):round(siz/2-q/2-6)+q-1);
end
        tem(:,:,1) = m;
        M = padarray(m,[floor(2/3*r),floor(2/3*r)],0,'post');
        tem(:,:,2) = M(floor(2/3*r)+1:end,floor(2/3*r)+1:end);
        m = tem;
return

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text:
function train_denoising_demo()
% Copyright (c) 2014-present University of Illinois at Urbana-Champaign
% All rights reserved.
%
% Developed by:     Po-Sen Huang, Paris Smaragdis
%                   Department of Electrical and Computer Engineering
%                   Department of Computer Science
%
%% Global parameters
rand('state',0)
randn('state',0)

addpath('drnn');
addpath(['Data',filesep,'noise']);
pg.nspkr = 10;
pg.spkrt = 'F';
pg.nf = {'babble.wav', 'drill.wav', 'airport.wav', 'train.wav', 'subway.wav'};
pg.g = 1;

% Parameter search space
pst = {
    {1024} % FFT size
    {1} % Power to raise spectra
    {1} % Emphasis
    {1} % Temporal stacking
    {[1000,1000]} % Hidden layers; 1000 optimal?
    {'poslin'} % Activations, poslin only is best
    {0} % Normalization flag
    {3} % Gain filtering (3 is no filtering)
    {'euc'} % Cost function
%         {'drnn'}
    {'drnn_mini'}
    {10000} % circular shift size 10000
    {20} % max_outer_iter
    {'spectra'}
    {1, 3} % isRNN
    {0}  % discriminative training gamma parameter
    {0}  % isclean only
    {100} %batchsize,
    {100} % lbfgs_iter 100
    {0} % gradient clipping
    {10} % weight norm
%         {5, 20, 30, 40} % weight norm
};

% Index of training leave-out speaker, noise, gain and utterance
los = [];
lon = [];
lor = [];
lou = [1 2];

[s,~] = nn4expr_wav( pg.nspkr, pg.spkrt, pg.nf, pg.g, pst, {los,lon,lor,lou});
save DRNN_wdecay10 s pst

load DRNN_wdecay10 s pst
figure(3)

[p,m,n] = nanstats2( s, [4 2 1]);
bare3( 1:4, p', m', n', .8, {{}}, 'Effect of Network Topology')
set( gcf, 'name', 'Layers', 'paperposition', [0.25 5.75 8 2.75])
legend({'RNN1', 'RNN3'}, 'fontsize', 8, 'location', 'northwest')

author: posenhuang

repo: deeplearningsourceseparation


text:
% Reconstruction of image from Laplacian pyramid
%
% Arguments:
%   pyramid 'pyr', as generated by function 'laplacian_pyramid'
%   subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional)
%
% tom.mertens@gmail.com, August 2007
% sam.hasinoff@gmail.com, March 2011  [modified to handle subwindows]
%
%
% More information:
%   'The Laplacian Pyramid as a Compact Image Code'
%   Burt, P., and Adelson, E. H.,
%   IEEE Transactions on Communication, COM-31:532-540 (1983).
%

function R = reconstruct_laplacian_pyramid(pyr,subwindow)

r = size(pyr{1},1);
c = size(pyr{1},2);
nlev = length(pyr);

subwindow_all = zeros(nlev,4);
if ~exist('subwindow','var')
    subwindow_all(1,:) = [1 r 1 c];
else
    subwindow_all(1,:) = subwindow;
end
for lev = 2:nlev
    subwindow_all(lev,:) = child_window(subwindow_all(lev-1,:));
end

% start with low pass residual
R = pyr{nlev};
filter = pyramid_filter;
for lev = nlev-1 : -1 : 1
    % upsample, and add to current level
    R = pyr{lev} + upsample(R,filter,subwindow_all(lev,:));
end

author: drakeguan


text:
function bounds= GetBounds(sys)
    %GET_BOUNDS Summary of this function goes here
    %   Detailed explanation goes here

    if isa(sys,'HybridSystem')
        is_hybrid = true;
        robot = sys.Gamma.Nodes.Domain{1};
    else
        is_hybrid = false;
        robot = sys;
    end

    bounds = robot.getLimits();

    bounds.time.t0.lb = 0; % starting time
    bounds.time.t0.ub = 0;
    bounds.time.t0.x0 = 0;
    bounds.time.tf.lb = 0; % terminating time
    bounds.time.tf.ub = 10;
    bounds.time.tf.x0 = 0.5;
    bounds.time.duration.lb = 0.5; % duration (optional)
    bounds.time.duration.ub = 0.5;

    %     bounds.states.x.terminal = zeros(6,1);
    %     bounds.states.dx.terminal = zeros(6,1);
    %     bounds.states.ddx.terminal = zeros(6,1);
    %     bounds.states.dx.ub = zeros(6,1);
    %     bounds.states.dx.x0 = zeros(6,1);

    bounds.gain.kp = 100;
    bounds.gain.kd = 20;

    bounds.params.ajoints.ub = reshape(ones(3,6)*pi,[],1);
    bounds.params.ajoints.lb = reshape(ones(3,6)*-pi,[],1);
    bounds.params.ajoints.x0 = reshape(ones(3,6)*0,[],1);

    bounds.params.pjoints.lb = [0,0];
    bounds.params.pjoints.ub = [2,2];
    bounds.params.pjoints.x0 = [0,0.5];

    bounds.params.pfoot.lb = [0,0,0];
    bounds.params.pfoot.ub = [0,0,0];
    bounds.params.pfoot.x0 = [0,0,0];

    bounds.inputs.ConstraintWrench.ffoot.x0 = [0,100,0];
    bounds.zmp.lb = -0.1;
    bounds.zmp.ub = -0.1;

    %     load('res/static_pose.mat','gait');
    load('res/gaits/static_r-0-7_th=84.mat', 'gait');
    bounds.restPos = [zeros(3,1);gait.states.x(4:end,end)];
    bounds.restVel = zeros(6,1);
    bounds.restAcc = zeros(6,1);
    %     load('res/gaits/static_r-0-7_th=84.mat', 'gait');
    bounds.initialPos = [zeros(3,1);gait.states.x(4:end,1)];
    bounds.initialVel = gait.states.dx(:,1);

    bounds.pos_weight = blkdiag(zeros(3),eye(3)*20000);
    bounds.vel_weight = blkdiag(zeros(3),eye(3)*5000);
    bounds.tor_weight = eye(3)*0.01;
    bounds.momentum_weight = 500;
    bounds.zmp_weight = 1000;

    bounds.push_force = [0;0];
    bounds.xcom.lb = -0.2;
    bounds.xcom.ub = -0.0;
    bounds.zcom.lb = 0.2;
    bounds.zcom.ub = 0.7;
    bounds.torso.lb = deg2rad(-50);
    bounds.torso.ub = deg2rad(50);

    bounds.rcom.lb = 0.3;
    bounds.rcom.ub = 0.7;
    bounds.thetacom.lb = deg2rad(72);
    bounds.thetacom.ub = deg2rad(96);

    %     bounds.rcom.initial = 0.7;
    %     bounds.rcom.terminal = 0.7;
    %     bounds.thetacom.initial = deg2rad(84);
    %     bounds.thetacom.terminal = deg2rad(84);

    if is_hybrid
        model_bounds = bounds;

        bounds = struct();
        for i=1:height(sys.Gamma.Nodes)
            if i>1
                model_bounds.time.t0.ub = 10;
            end

            bounds.(sys.Gamma.Nodes.Name{i}) = model_bounds;
        end

        for i=1:height(sys.Gamma.Edges)
            name = sys.Gamma.Edges.Guard{i}.Name;
            bounds.(name) = model_bounds;

            bounds.(name).states.xn = model_bounds.states.x;
            bounds.(name).states.dxn = model_bounds.states.dx;
        end
    end
end

author: ayonga

repo: frost-dev

save_path: github-repos/MATLAB/ayonga-frost-dev


text:
% Local Regression and Likelihood, Figure 2.3.
%
% Using different smoothing parameters.

load ethanol;

alp = [0.2 0.4 0.6 0.8];
f=['a','b','c','d'];
for (i=1:4)
  figure('Name', sprintf( 'figure2_3%c: Changing smoothing parameters', f(i) ) );
  fit = locfit(E,NOx,'alpha',alp(i));
  lfplot(fit);
  title(strcat('a = ',num2str(alp(i))));
end;

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
classdef KNearest < handle
    %KNEAREST  The class implements K-Nearest Neighbors model
    %
    % ## K-Nearest Neighbors
    %
    % The algorithm caches all training samples and predicts the response for
    % a new sample by analyzing a certain number (`K`) of the nearest
    % neighbors of the sample using voting, calculating weighted sum, and so
    % on. The method is sometimes referred to as "learning by example" because
    % for prediction it looks for the feature vector with a known response
    % that is closest to the given vector.
    %
    % ## Example
    %
    %     Xtrain = [randn(20,4)+1; randn(20,4)-1];    % training samples
    %     Ytrain = int32([ones(20,1); zeros(20,1)]);  % training labels
    %     knn = cv.KNearest(Xtrain, Ytrain);
    %     Xtest = randn(50,4);                        % testing samples
    %     Ytest = knn.predict(Xtest);                 % predictions
    %
    % ## References
    % [BEIS97]:
    % > J.S. Beis and D.G. Lowe. "Shape indexing using approximate
    % > nearest-neighbor search in highdimensional spaces". In Proc. IEEE
    % > Conf. Comp. Vision Patt. Recog., pp 1000-1006, 1997.
    % > [CiteSeerX](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.126.1046)
    %
    % See also: cv.KNearest.KNearest, cv.KNearest.train,
    %  cv.KNearest.findNearest, fitcknn
    %

    properties (SetAccess = private)
        % Object ID
        id
    end

    properties (Dependent)
        % Default number of neighbors to use in predict method.
        %
        % Default 10.
        %
        % See also: cv.KNearest.predict, cv.KNearest.findNearest
        DefaultK
        % Whether classification or regression model should be trained.
        %
        % Type of the problem: true for classification and false for
        % regression. Default true.
        IsClassifier
        % Parameter for 'KDTree' implementation.
        %
        % The user can balance between the speed and accuracy of the
        % cv.KNearest.findNearest search by varying `Emax` parameter, which is
        % the number of leaves that the algorithm checks.
        % The larger parameter values yield more accurate results at the
        % expense of lower processing speed.
        %
        % Default `intmax`.
        Emax
        % Algorithm type.
        %
        % Default 'BruteForce'. Possible nearest neighbors implementations:
        %
        % * __BruteForce__ brute-force search.
        % * __KDTree__ Fast Nearest Neighbor Search using KD-trees. This
        %   implements D. Lowe BBF (Best-Bin-First) algorithm for the last
        %   approximate (or accurate) nearest neighbor search in
        %   multi-dimensional spaces. See [BEIS97].
        AlgorithmType
    end

    %% Constructor/destructor
    methods
        function this = KNearest(varargin)
            %KNEAREST  Creates/trains a K-Nearest Neighbors model
            %
            %     model = cv.KNearest()
            %     model = cv.KNearest(...)
            %
            % The first variant creates an empty model. Use cv.KNearest.train
            % to train the model.
            %
            % The second variant accepts the same parameters as the train
            % method, in which case it forwards the call after construction.
            %
            % See also: cv.KNearest, cv.KNearest.train
            %
            this.id = KNearest_(0, 'new');
            if nargin > 0
                this.train(varargin{:});
            end
        end

        function delete(this)
            %DELETE  Destructor
            %
            %     model.delete()
            %
            % See also: cv.KNearest
            %
            if isempty(this.id), return; end
            KNearest_(this.id, 'delete');
        end
    end

    %% Algorithm
    methods
        function clear(this)
            %CLEAR  Clears the algorithm state
            %
            %     model.clear()
            %
            % The method clear does the same job as the destructor: it
            % deallocates all the memory occupied by the class members. But
            % the object itself is not destructed and can be reused further.
            % This method is called from the destructor, from the `train` and
            % `load` methods, or even explicitly by the user.
            %
            % See also: cv.KNearest.empty, cv.KNearest.load
            %
            KNearest_(this.id, 'clear');
        end

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

        function varargout = save(this, filename)
            %SAVE  Saves the algorithm parameters to a file or a string
            %
            %     model.save(filename)
            %     str = model.save(filename)
            %
            % ## Input
            % * __filename__ Name of the file to save to. In case of string
            %   output, only the filename extension is used to determine the
            %   output format (XML or YAML).
            %
            % ## Output
            % * __str__ optional output. If requested, the model is persisted
            %   to a string in memory instead of writing to disk.
            %
            % This method stores the complete model state to the specified
            % XML or YAML file (or to a string in memory, based on the number
            % of output arguments).
            %
            % See also: cv.KNearest.load
            %
            [varargout{1:nargout}] = KNearest_(this.id, 'save', filename);
        end

        function load(this, fname_or_str, varargin)
            %LOAD  Loads algorithm from a file or a string
            %
            %     model.load(filename)
            %     model.load(str, 'FromString',true)
            %     model.load(..., 'OptionName',optionValue, ...)
            %
            % ## Input
            % * __filename__ 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 (switches
            %   between `Algorithm<T>::load()` and
            %   `Algorithm<T>::loadFromString()` C++ methods). default false
            %
            % This method loads the complete model state from the specified
            % XML or YAML file (either from disk or serialized string). The
            % previous model state is cleared.
            %
            % See also: cv.KNearest.save
            %
            KNearest_(this.id, 'load', fname_or_str, varargin{:});
        end

        function name = getDefaultName(this)
            %GETDEFAULTNAME  Returns the algorithm string identifier
            %
            %     name = model.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.KNearest.save, cv.KNearest.load
            %
            name = KNearest_(this.id, 'getDefaultName');
        end
    end

    %% StatModel
    methods
        function count = getVarCount(this)
            %GETVARCOUNT  Returns the number of variables in training samples
            %
            %     count = model.getVarCount()
            %
            % ## Output
            % * __count__ number of variables in training samples.
            %
            % See also: cv.KNearest.train
            %
            count = KNearest_(this.id, 'getVarCount');
        end

        function b = isTrained(this)
            %ISTRAINED  Returns true if the model is trained
            %
            %     b = model.isTrained()
            %
            % ## Output
            % * __b__ Returns true if the model is trained, false otherwise.
            %
            % See also: cv.KNearest.empty, cv.KNearest.train
            %
            b = KNearest_(this.id, 'isTrained');
        end

        function b = isClassifier(this)
            %ISCLASSIFIER  Returns true if the model is a classifier
            %
            %     b = model.isClassifier()
            %
            % ## Output
            % * __b__ Returns true if the model is a classifier, false if the
            %   model is a regressor.
            %
            % See also: cv.KNearest.isTrained, cv.KNearest.IsClassifier
            %
            b = KNearest_(this.id, 'isClassifier');
        end

        function status = train(this, samples, responses, varargin)
            %TRAIN  Trains the model
            %
            %     status = model.train(samples, responses)
            %     status = model.train(csvFilename, [])
            %     [...] = model.train(..., 'OptionName', optionValue, ...)
            %
            % ## Input
            % * __samples__ matrix of training samples. It should have
            %   `single` type. By default, each row represents a sample (see
            %   the `Layout` option).
            % * __responses__ matrix of associated responses, with training
            %   labels in case of classification and response values for
            %   regression. If the responses are scalar, they should be stored
            %   as a vector (as a single row or a single column matrix). The
            %   matrix should have type `single` or `int32` (in the former
            %   case the responses are considered as ordered (numerical) by
            %   default; in the latter case as categorical). You can override
            %   the defaults using the `VarType` option.
            % * __csvFilename__ The input CSV file name from which to load
            %   dataset. In this variant, you should set the second argument
            %   to an empty array.
            %
            % ## Output
            % * __status__ Success flag.
            %
            % ## Options
            % * __Data__ Training data options, specified as a cell array of
            %   key/value pairs of the form `{'key',val, ...}`. See below.
            % * __Flags__ The optional training flags, model-dependent. For
            %   convenience, you can set the individual flag options below,
            %   instead of directly setting bits here. default 0
            % * __UpdateModel__ Specifies whether the model should be trained
            %   from scratch (`UpdateModel=false`), or should be updated
            %   using the new training data (`UpdateModel=true`) instead of
            %   being completely overwritten. default false
            %
            % ### Options for `Data` (first variant with samples and reponses)
            % * __Layout__ Sample types. Default 'Row'. One of:
            %   * __Row__ each training sample is a row of samples.
            %   * __Col__ each training sample occupies a column of samples.
            % * __VarIdx__ vector specifying which variables to use for
            %   training. It can be an integer vector (`int32`) containing
            %   0-based variable indices or logical vector (`uint8` or
            %   `logical`) containing a mask of active variables. Not set by
            %   default, which uses all variables in the input data.
            % * __SampleIdx__ vector specifying which samples to use for
            %   training. It can be an integer vector (`int32`) containing
            %   0-based sample indices or logical vector (`uint8` or
            %   `logical`) containing a mask of training samples of interest.
            %   Not set by default, which uses all samples in the input data.
            % * __SampleWeights__ optional floating-point vector with weights
            %   for each sample. Some samples may be more important than
            %   others for training. You may want to raise the weight of
            %   certain classes to find the right balance between hit-rate and
            %   false-alarm rate, and so on. Not set by default, which
            %   effectively assigns an equal weight of 1 for all samples.
            % * __VarType__ optional vector of type `uint8` and size
            %   `<num_of_vars_in_samples> + <num_of_vars_in_responses>`,
            %   containing types of each input and output variable. By default
            %   considers all variables as numerical (both input and output
            %   variables). In case there is only one output variable of
            %   integer type, it is considered categorical. You can also
            %   specify a cell-array of strings (or as one string of single
            %   characters, e.g 'NNNC'). Possible values:
            %   * __Numerical__, __N__ same as 'Ordered'
            %   * __Ordered__, __O__ ordered variables
            %   * __Categorical__, __C__ categorical variables
            % * __MissingMask__ Indicator mask for missing observation (not
            %   currently implemented). Not set by default
            % * __TrainTestSplitCount__ divides the dataset into train/test
            %   sets, by specifying number of samples to use for the test set.
            %   By default all samples are used for the training set.
            % * __TrainTestSplitRatio__ divides the dataset into train/test
            %   sets, by specifying ratio of samples to use for the test set.
            %   By default all samples are used for the training set.
            % * __TrainTestSplitShuffle__ when splitting dataset into
            %   train/test sets, specify whether to shuffle the samples.
            %   Otherwise samples are assigned sequentially (first train then
            %   test). default true
            %
            % ### Options for `Data` (second variant for loading CSV file)
            % * __HeaderLineCount__ The number of lines in the beginning to
            %   skip; besides the header, the function also skips empty lines
            %   and lines staring with '#'. default 1
            % * __ResponseStartIdx__ Index of the first output variable. If
            %   -1, the function considers the last variable as the response.
            %   If the dataset only contains input variables and no responses,
            %   use `ResponseStartIdx = -2` and `ResponseEndIdx = 0`, then the
            %   output variables vector will just contain zeros. default -1
            % * __ResponseEndIdx__ Index of the last output variable + 1. If
            %   -1, then there is single response variable at
            %   `ResponseStartIdx`. default -1
            % * __VarTypeSpec__ The optional text string that specifies the
            %   variables' types. It has the format
            %   `ord[n1-n2,n3,n4-n5,...]cat[n6,n7-n8,...]`. That is, variables
            %   from `n1` to `n2` (inclusive range), `n3`, `n4` to `n5` ...
            %   are considered ordered and `n6`, `n7` to `n8` ... are
            %   considered as categorical. The range
            %   `[n1..n2] + [n3] + [n4..n5] + ... + [n6] + [n7..n8]` should
            %   cover all the variables. If `VarTypeSpec` is not specified,
            %   then algorithm uses the following rules:
            %   * all input variables are considered ordered by default. If
            %     some column contains has non- numerical values, e.g.
            %     'apple', 'pear', 'apple', 'apple', 'mango', the
            %     corresponding variable is considered categorical.
            %   * if there are several output variables, they are all
            %     considered as ordered. Errors are reported when
            %     non-numerical values are used.
            %   * if there is a single output variable, then if its values are
            %     non-numerical or are all integers, then it's considered
            %     categorical. Otherwise, it's considered ordered.
            % * __Delimiter__ The character used to separate values in each
            %   line. default ','
            % * __Missing__ The character used to specify missing
            %   measurements. It should not be a digit. Although it's a
            %   non-numerical value, it surely does not affect the decision of
            %   whether the variable ordered or categorical. default '?'
            % * __TrainTestSplitCount__ same as above.
            % * __TrainTestSplitRatio__ same as above.
            % * __TrainTestSplitShuffle__ same as above.
            %
            % The method trains the K-Nearest model. It follows the
            % conventions of the generic train approach with the following
            % limitations:
            %
            % * Input variables are all ordered.
            % * Output variables can be either categorical
            %   (`IsClassifier=true`) or ordered (`IsClassifier=false`).
            % * Variable subsets (`VarIdx`) and missing measurements are not
            %   supported.
            %
            % See also: cv.KNearest.predict, cv.KNearest.calcError
            %
            status = KNearest_(this.id, 'train', samples, responses, varargin{:});
        end

        function [err,resp] = calcError(this, samples, responses, varargin)
            %CALCERROR  Computes error on the training or test dataset
            %
            %     err = model.calcError(samples, responses)
            %     err = model.calcError(csvFilename, [])
            %     [err,resp] = model.calcError(...)
            %     [...] = model.calcError(..., 'OptionName', optionValue, ...)
            %
            % ## Input
            % * __samples__ See the train method.
            % * __responses__ See the train method.
            % * __csvFilename__ See the train method.
            %
            % ## Output
            % * __err__ computed error.
            % * __resp__ the optional output responses.
            %
            % ## Options
            % * __Data__ See the train method.
            % * __TestError__ if true, the error is computed over the test
            %   subset of the data, otherwise it's computed over the training
            %   subset of the data. Please note that if you loaded a
            %   completely different dataset to evaluate an already trained
            %   classifier, you will probably want not to set the test subset
            %   at all with `TrainTestSplitRatio` and specify
            %   `TestError=false`, so that the error is computed for the whole
            %   new set. Yes, this sounds a bit confusing. default false
            %
            % The method uses the predict method to compute the error. For
            % regression models the error is computed as RMS, for classifiers
            % as a percent of missclassified samples (0%-100%).
            %
            % See also: cv.KNearest.train, cv.KNearest.predict
            %
            [err,resp] = KNearest_(this.id, 'calcError', samples, responses, varargin{:});
        end

        function [results,f] = predict(this, samples, varargin)
            %PREDICT  Predicts response(s) for the provided sample(s)
            %
            %     [results,f] = model.predict(samples)
            %     [...] = model.predict(..., 'OptionName', optionValue, ...)
            %
            % ## Input
            % * __samples__ The input samples, floating-point matrix.
            %
            % ## Output
            % * __results__ See the cv.KNearest.findNearest method.
            % * __f__ See the cv.KNearest.findNearest method.
            %
            % ## Options
            % * __Flags__ The optional predict flags, model-dependent.
            %   Not used. default 0
            %
            % The method is an alias for cv.KNearest.findNearest, using
            % `DefaultK` as value for number of nearest neighbors.
            %
            % See also: cv.KNearest.findNearest, cv.KNearest.train,
            %  cv.KNearest.calcError
            %
            [results,f] = KNearest_(this.id, 'predict', samples, varargin{:});
        end
    end

    %% KNearest
    methods
        function [results,neiResp,dist,f] = findNearest(this, samples, K)
            %FINDNEAREST  Finds the neighbors and predicts responses for input vectors
            %
            %     results = classifier.findNearest(samples, K)
            %     [results,neiResp,dists,f] = classifier.findNearest(samples, K)
            %     [...] = classifier.findNearest(..., 'OptionName', optionValue, ...)
            %
            % ## Input
            % * __samples__ Input samples stored by rows. It is a
            %   single-precision floating-point matrix of size
            %   `nsamples-by-nfeatures`.
            % * __K__ Number of used nearest neighbors. Should be greater than
            %   or equal to 1.
            %
            % ## Output
            % * __results__ Vector with results of prediction (regression or
            %   classification) for each input sample. It is a
            %   single-precision floating-point vector with `nsamples`
            %   elements.
            % * __neiResp__ Optional output array for corresponding neighbor
            %   responses. It is a single-precision floating-point matrix of
            %   size `nsamples-by-K`.
            % * __dists__ Optional output distances from the input vectors to
            %   the corresponding neighbors. It is a single-precision
            %   floating-point matrix of size `nsamples-by-K`.
            % * __f__ If only a single input vector is passed, the predicted
            %   value is returned by the method. Otherwise it returns the
            %   prediction of the first sample.
            %
            % For each input vector (a row of the matrix samples), the method
            % finds the `K` nearest neighbors. In case of regression, the
            % predicted result is a mean value of the particular vector's
            % neighbor responses. In case of classification, the class is
            % determined by voting.
            %
            % For each input vector, the neighbors are sorted by their
            % distances to the vector.
            %
            % The function is parallelized with the TBB library.
            %
            % See also: cv.KNearest.predict, cv.KNearest.train
            %
            [results,neiResp,dist,f] = KNearest_(this.id, 'findNearest', samples, K);
        end
    end

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

        function value = get.DefaultK(this)
            value = KNearest_(this.id, 'get', 'DefaultK');
        end
        function set.DefaultK(this, value)
            KNearest_(this.id, 'set', 'DefaultK', value);
        end

        function value = get.Emax(this)
            value = KNearest_(this.id, 'get', 'Emax');
        end
        function set.Emax(this, value)
            KNearest_(this.id, 'set', 'Emax', value);
        end

        function value = get.IsClassifier(this)
            value = KNearest_(this.id, 'get', 'IsClassifier');
        end
        function set.IsClassifier(this, value)
            KNearest_(this.id, 'set', 'IsClassifier', value);
        end
    end

end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv