function [M,padpre] = padImage(MData, pof2, padval)
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR 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.
%
% CERR 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 CERR.  If not, see <http://www.gnu.org/licenses/>.

if ~exist('padval','var')
    padval = 0;
end

dim = size(MData);
s = 2^pof2;
newdim = ceil(dim/s)*s;

paddim = newdim-dim;
padpre = floor(paddim/2);
padpost = paddim-padpre;

if exist('padarray.m','file')
    M = padarray(MData,padpre,padval,'pre');
    M = padarray(M,padpost,padval,'post');
else
    M = padarray_oct(MData,padpre,padval,'pre');
    M = padarray_oct(M,padpost,padval,'post');
end


%FILLCONVEXPOLY  Fills a convex polygon
%
%     img = cv.fillConvexPoly(img, pts)
%     [...] = cv.fillConvexPoly(..., 'OptionName', optionValue, ...)
%
% ## Input
% * __img__ Image.
% * __pts__ Polygon vertices, stored in numeric array (Nx2/Nx1x2/1xNx2) or
%   cell-array of 2-element vectors `{[x,y], [x,y], ...}`. Supports integer
%   `int32` 2D points.
%
% ## Output
% * __img__ Output image, same size and type as input `img`.
%
% ## Options
% * __Color__ 3-element floating-point vector specifying polygon color.
%   default zeros
% * __LineType__ Type of the polygon boundaries. One of:
%   * __4__ 4-connected line
%   * __8__ 8-connected line (default)
%   * __AA__ anti-aliased line
% * __Shift__ Number of fractional bits in the vertex coordinates. default 0
%
% The function cv.fillConvexPoly draws a filled convex polygon. This function
% is much faster than the function cv.fillPoly. It can fill not only convex
% polygons but any monotonic polygon without self-intersections, that is, a
% polygon whose contour intersects every horizontal line (scan line) twice at
% the most (though, its top-most and/or the bottom edge could be horizontal).
%
% See also: cv.line, cv.fillPoly
%


function bc = specific_bc(xbd,ybd)
%hotwall_bc   Reference problem 3.4  boundary condition
%   bc = specific_bc(xbd,ybd);
%   input
%          xbd          x boundary coordinate vector
%          ybd          y boundary coordinate vector
%
%   specifies hot wall /Morton pp.10/
%   IFISS function: DJS; 5 March 2005.
% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage
nobd=length(xbd);
bc=zeros(size(xbd));
k=find(xbd==1);
bc(k)=1;
return


function lebesgue_test ( )

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

  lebesgue_test01 ( );
  lebesgue_test02 ( );
  lebesgue_test03 ( );
  lebesgue_test04 ( );
  lebesgue_test05 ( );
  lebesgue_test06 ( );
  lebesgue_test07 ( );
  lebesgue_test08 ( );
  lebesgue_test09 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'LEBESGUE_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function timestamp ( )

%% TIMESTAMP prints the current YMDHMS date as a timestamp.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  t = now;
  c = datevec ( t );
  s = datestr ( c, 0 );
  fprintf ( 1, '%s\n', s );

  return
end


function Hp = essential_flat(H)
    %Reshape a [3x6xk] matrix to a [3x3x2k] matrix
    Hp = reshape(H,3,3,[]);
end


% Copyright (C) 2010 Joao Carreira
%
% This code is part of the extended implementation of the paper:
%
% J. Carreira, C. Sminchisescu, Constrained Parametric Min-Cuts for Automatic Object Segmentation, IEEE CVPR 2010
%
% Modified:
%   @authors:     Ahmad Humayun
%   @contact:     ahumayun@cc.gatech.edu
%   @affiliation: Georgia Institute of Technology
%   @date:        Fall 2013 - Summer 2014

%function pixel_ids = frame_pixel_ids(nrows, ncols, width, custom)
% creates a frame whose external border has nrows and ncols, and width = 'width'
function seeds = frame_pixel_ids(nrows, ncols, width, custom)
    assert(width>=1);

    boundary_pixels_horiz_top = false(nrows, ncols);
    boundary_pixels_horiz_top(1:width, 1:end) = true;
    boundary_pixels_horiz_bottom = false(nrows, ncols);
    boundary_pixels_horiz_bottom(end-width+1:end, 1:end) = true;
    boundary_pixels_vert_left = false(nrows, ncols);
    boundary_pixels_vert_left(1:end, 1:width) = true;
    boundary_pixels_vert_right = false(nrows, ncols);
    boundary_pixels_vert_right(1:end, end-width+1:end) = true;

    if(strcmp(custom, 'horiz'))
        seeds = boundary_pixels_horiz_bottom | boundary_pixels_horiz_top;
    elseif(strcmp(custom, 'down'))
        seeds = boundary_pixels_horiz_bottom;
    elseif(strcmp(custom, 'up'))
        seeds = boundary_pixels_horiz_top;
    elseif(strcmp(custom, 'vert'))
        seeds = boundary_pixels_vert_left | boundary_pixels_vert_right;
    elseif(strcmp(custom, 'all_but_down'))
        seeds = boundary_pixels_horiz_top | boundary_pixels_vert_left | ...
                boundary_pixels_vert_right;
    elseif(strcmp(custom, 'all')) % whole frame
        seeds = boundary_pixels_horiz_top | ...
                boundary_pixels_horiz_bottom | ...
                boundary_pixels_vert_left | boundary_pixels_vert_right;
    else
        error('no such option');
    end

    seeds = seeds(:);
end


function varargout = circleArcAsCurve(arc, N)
%CIRCLEARCASCURVE Convert a circle arc into a series of points
%
%   deprecated: replaced by circleArcToPolyline
%
%
% ---------
% author : David Legland
% created the 22/05/2006.
% Copyright 2010 INRA - Cepia Software Platform.
%

% HISTORY
% 2011-03-30 use angles in degrees, add default value for N
% 2011-12-09 deprecate

warning('matGeom:deprecated', ...
    'function "circleArcAsCurve" is deprecated, use "circleArcToPolygon" instead');

% format output
if nargout <= 1
    varargout = {circleArcToPolyline(arc, N)};
else
    [x, y] = circleArcToPolyline(arc, N);
    varargout = {x, y};
end


function sparse_grid_total_poly_test ( )

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

  rules_test ( );
  point_quality_test ( );
  weight_quality_test ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SPARSE_GRID_TOTAL_POLY_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


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


%% Copyright (C) 2016, 2018-2019 Colin B. Macdonald
%% Copyright (C) 2016 Abhinav Tripathi
%% Copyright (C) 2021 Johannes Maria Frank
%% Copyright (C) 2022 Chris Gorman
%% Copyright (C) 2022 Alex Vong
%%
%% 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/>.

%% -*- texinfo -*-
%% @deftypefn  {Function File}  {[@var{A}, @var{info}] =} python_ipc_native (@dots{})
%% Private helper function for Python IPC.
%%
%% @var{A} is the resulting object, which might be an error code.
%%
%% @var{info} usually contains diagnostics to help with debugging
%% or error reporting.
%%
%% @code{@var{info}.prelines}: the number of lines of header code
%% before the command starts.
%%
%% @end deftypefn

function [A, info] = python_ipc_native(what, cmd, varargin)

  persistent show_msg
  persistent have_headers

  info.prelines = 0;

  if (strcmp(what, 'reset'))
    A = true;
    have_headers = [];
    return
  end

  if ~(strcmp(what, 'run'))
    error('unsupported command')
  end

  verbose = ~sympref('quiet');

  if (verbose && isempty(show_msg))
    assert_pythonic_and_sympy ()
    fprintf ('Symbolic pkg v%s: ', sympref ('version'))
  end

  newl = sprintf('\n');

  if isempty(have_headers)
    pyexec(strjoin({'import sys'
                    'import sympy'
                    'import mpmath'
                    'import sympy as sp'
                    'from sympy import __version__ as spver'
                    'from sympy import *'
                    'from sympy.logic.boolalg import Boolean, BooleanFunction'
                    'from sympy.core.relational import Relational'
                    '# temporary? for piecewise support'
                    'from sympy.functions.elementary.piecewise import ExprCondPair'
                    'from sympy.integrals.risch import NonElementaryIntegral'
                    'from sympy.matrices.expressions.matexpr import MatrixElement'
                    '# for hypergeometric'
                    'from sympy.functions.special.hyper import TupleArg'
                    '# for sets'
                    'from sympy.utilities.iterables import uniq'
                    'try:'
                    '    # quick fix for https://github.com/cbm755/octsympy/issues/1053'
                    '    # TODO: investigate the sym ctor in this case, likely a better fix in there'
                    '    from sympy.core.symbol import Str'
                    'except ImportError:'
                    '    pass'
                    'import copy'
                    'import struct'
                    'import codecs'
                    'try:'
                    '    from packaging.version import Version'
                    'except ImportError:'
		    '    try:'
		    '        from sympy.external.importtools import version_tuple as Version'
		    '    except ImportError:'
                    '        from distutils.version import LooseVersion'
                    '        def Version(v):'
                    '            return LooseVersion(v.replace(".dev", ""))'
                    'import itertools'
                    'import collections'
                    'from re import split'
                    '# patch pretty printer, issue #952'
                    'from sympy.printing.pretty.pretty import PrettyPrinter'
                    '_mypp = PrettyPrinter'
                    'def _my_rev_print(cls, f, **kwargs):'
                    '    g = f.func(*reversed(f.args), evaluate=False)'
                    '    return cls._print_Function(g, **kwargs)'
                    '_mypp._print_LambertW = lambda cls, f: _my_rev_print(cls, f, func_name="lambertw")'
                    '_mypp._print_sinc = lambda cls, f: cls._print_Function(f.func(f.args[0]/sp.pi, evaluate=False))'
                    'del _mypp'
                    'def dbout(l):'
                    '    # should be kept in sync with the same function'
                    '    # defined in inst/private/python_header.py'
                    '    sys.stderr.write("pydebug: " + str(l) + "\n")'
                  }, newl))
    have_headers = true;
  end

  if (verbose && isempty (show_msg))
    fprintf ('using Pythonic interface, SymPy v%s.\n', ...
             char (py.sympy.__version__))
    show_msg = true;
  end

  ins = store_vars_in_python(varargin);
  pyexec (strjoin (cmd, newl));
  outs = pycall ('_fcn', ins);
  A = check_and_convert(outs);
end


function [] = rotation(st);

if nargin < 1,
   st= 1;
end;

fig = gcf;

ax = gca;

vv = get(ax,'view');

az = vv(1);
el = vv(2);

for azi = az:-abs(st):az-360,

   set(ax,'view',[azi el]);
   figure(fig);
   drawnow;

end;


function test_tutorial_plotting

% WALLTIME 00:15:00
% MEM 4gb
% DEPENDENCY ft_multiplotER ft_singleplotER ft_topoplotER ft_singleplotTFR ft_multiplotTRF ft_megplanar ft_combineplanar ft_volumereslice

%%
% *Plotting data at the channel and source level*
%
% _*Introduction*_
%
% To visualize your data you can use FieldTrip's high-level plotting functions,
% which are optimised for the FT data structures. Like other high-level functions
% they take a cfg as first input argument, followed by the data. These functions
% take care of all bookkeeping and some of the functions allow you to interact
% with the data by clicking in the figure.
%
% Alternatively, you can use the low-level FieldTrip plotting functions.
% These are located in the plotting sub-directory and are named ft_plot_xxx. You
% can find them by typing in the command window ?help ft_plot_? and then press
% the Tab key.
%
% Of course you can use the standard MATLAB functions ('plot, 'image', 'images',
% 'patch').
%
% _*Background*_
%
% The goal of the plotting functions in FieldTrip is to ease the visualization
% of complex data structures with multiple dimensions and with data that is not
% trivial to interpret spatially. This is accomplished with high-level functions
% (e.g. ft_topoplotER or ft_multiplotTFR) and low-level functions (with prefixes
% 'ft_plot_' and 'ft_select_', e.g. ft_plot_matrix or ft_select_box). For more
% simple data, such as a set of reaction times of the subject, we expect you to
% use the standard MATLAB plotting functions.
%
% The high-level functions take care of the data bookkeeping and call the
% low-level function. If you want to make more complex figures or tweak all options,
% you can bypass the high-level functions and call the low-level functions instead.
% This is especially useful if there is no data selection and bookkeeping involved,
% e.g. when you want to plot multiple geometrical objects (like sensors, source
% model, head surface, etc).
%
% To determine which high-level functions are suitable for you depends on
% the type of data you have: sensor or source space data. In this tutorial we
% assume that you already have the data from the event related averaging tutorial,
% the time-frequency representations of power tutorial and the applying beamforming
% techniques in the frequency domain tutorial, and we will demonstrate plotting
% at both the sensor and source level.
%
% Let us start by loading some data.

cd(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/plotting'))

load avgFC.mat
load GA_FC.mat
load TFRhann.mat
load statERF.mat
load statTFR.mat
load sourceDiff.mat

%%
% _*Plotting data at the channel level*_
%
% Data at the channel level has a value for each sensor (MEG) or electrode
% (EEG). Those values can change over time and/or over frequency.
%
% *Singleplot functions*
%
% With ft_singleplotER you can make a plot using the avgFC data from the
% ERF tutorial by the following code:
%
% The ft_singleplotER function first selects the data to be plotted, in this
% case channel MLC24, from -0.2 to 1.0 seconds. Subsequently this selected data
% is plotted with the MATLAB plot function.

cfg = [];
cfg.xlim = [-0.2 1.0];
cfg.ylim = [-1e-13 3e-13];
cfg.channel = 'MLC24';
figure; ft_singleplotER(cfg,avgFC);
%%
% You could make the same plot by the following code:

selected_data = avgFC.avg(9,241:601); % MLC24 is the 9th channel, -0.2 to 1.0 is sample 241 to 601
selected_time = avgFC.time(241:601);
figure;
plot(selected_time, selected_data)
xlim([-0.2 1.0])
ylim([-1e-13 3e-13])
%%
% The advantage of ft_singleplotER is that it does the bookeeping for you.
% E.g. you can plot the mean over all MLC channels, which are MEG channels over
% left-central regions:

cfg = [];
cfg.xlim = [-0.2 1.0];
cfg.ylim = [-1e-13 3e-13];
cfg.channel = 'MLC*';
figure; ft_singleplotER(cfg,avgFC);

%%
% and change the line width or color:

cfg = [];
cfg.xlim = [-0.2 1.0];
cfg.ylim = [-1e-13 3e-13];
cfg.channel = 'MLC24';
cfg.linewidth = 10;
cfg.graphcolor = 'g';
figure; ft_singleplotER(cfg,avgFC);

%%
% The ft_singleplotER function might not look so impressive compared to
% standard plot; that is because the ERF data representation is quite simple.
%
% The advantage of using the standard MATLAB plot function is that you can
% easily find all documentation for it ("doc plot") and tweak the low level figure
% characteristics.
%
% The FieldTrip plotting functions have a lot of built-in intelligence to
% make plotting of multidimensional data easier. It is for instance possible to
% do baseline correction before plotting, by specifying the baseline type and
% time limits. In the plotting functions either the FieldTrip function ft_timelockbaseline
% or ft_freqbaseline is called. If you specify multiple channels in cfg.channel
% both singleplot functions will plot the mean over these channels. In the plotting
% functions the FieldTrip function ft_channelselection is called, which makes
% it straightforward to plot for instance the mean TFR (download here, see time-frequency
% analysis tutorial)of the left central channels.

cfg = [];
cfg.baseline = [-0.5 -0.1];
cfg.baselinetype = 'absolute';
cfg.zlim = [-1.5e-27 1.5e-27];
cfg.channel = 'MLC24'; % top figure
figure; ft_singleplotTFR(cfg, TFRhann);

%%
% or wiht the average over a group of channels:

cfg.channel  = 'MLC*' % bottom figure
figure; ft_singleplotTFR(cfg,TFRhann);
%%
% You can again make very similar figures using standard MATLAB plotting
% functions.

chanindx = find(strcmp(TFRhann.label, 'MLC24'));
figure; imagesc(squeeze(TFRhann.powspctrm(chanindx,:,:)));
%%
% The default MATLAB image is shown upside down compared to usual MEG/EEG
% conventions. Along the axes you can see the number of time and frequency bins,
% but not the acqual time and frequency. This can be fixed of course.

figure; imagesc(TFRhann.time, TFRhann. freq, squeeze(TFRhann.powspctrm(chanindx,:,:)));
axis xy % flip vertically
colorbar
%%
% Still, the power is more difficult to interpret due to it being larger
% for low frequencies and smaller for high frequencies. This 1/f characteristic
% is removed from the figure by baseline correction. See also ft_freqbaseline.
%
% *Multiplot functions*
%
% The multiplot functions work similarly to the singleplot functions, again
% first by selecting the data and subsequently using the MATLAB functions plot
% and imagesc. But instead of one plot, multiple plots are made; one for each
% channel. These plots are arranged according to a specified layout in one pair
% of axes. In the subsequent figures you can see these axes that are normally
% set to ?off?.

cfg = [];
cfg.layout = 'CTF151.lay';
figure; ft_multiplotER(cfg, avgFC);
axis on % this shows the actual MATLAB axes
%%
% Normally the axes of the figure are not visible, only the ?axis? of each
% channel, but remember these are not real axes on which you can use MATLAB axis
% commands, the are just lines drawn by the function. Of course you can set the
% limits of the channel ?axis? by the cfg structure (cfg.xlim, cfg.ylim).

cfg = [];
cfg.baseline = [-0.5 -0.1];
cfg.zlim = [-3e-27 3e-27];
cfg.baselinetype = 'absolute';
cfg.layout = 'CTF151.lay';
figure; ft_multiplotTFR(cfg,TFRhann);
%%
% In the upper left corner you see the "COMMENT" element and in the upper
% right cornier you see the "SCALE" element. The scale contains the average of
% all channels.
%
% The location of all channels and the COMMENT and SCALE placeholder can
% be visualized with

cfg = [];
cfg.layout = 'CTF151.lay';
cfg.layout = ft_prepare_layout(cfg);
figure; ft_plot_layout(cfg.layout);
%%
% Note that the layout contains all 151 MEG channels; the one channel missing
% in the data is automatically excluded from the plots.
%
% All channels are squeezed in a circle and the nose and ears are indicated
% at the top and sides. The actual 3-D layout of the MEG channels in the CTF system
% is more complex than the circular arrangement suggested by the flat 2-D layout.
% This is a generic challenge for projections onto a 2-D plane and also applies
% to cartography. We can plot the bottom coil of the CTF gradiometer channels
% with

figure;
ft_plot_sens(avgFC.grad, 'chantype', 'meggrad')
ft_plot_axes(avgFC.grad)
view(-90, 90) % you should rotate the figure to get a good 3-D feel of the channel locations.
%%
% Although many tutorials elsewhere on the Fieldtrip wiki are using the
% standard CTF151 layout, we do have another one that better reflects the helmet
% shape:

cfg = [];
cfg.layout = 'CTF151_helmet.mat'; % note that it is a binary *.mat file, not an ascii *.lay file
cfg.layout = ft_prepare_layout(cfg);
figure; ft_plot_layout(cfg.layout);
%%
% The layout is determined by the layout file. Read more on layout files
% [[tutorial:layout|here]], and in the [[faq:what_is_the_format_of_the_layout_file_which_is_used_for_plotting|frequently
% asked questions]].

%%
% For multiplotting planar gradient data from the Elekta Neuromag system
% it is especially relevant to understand the layout files. The Neuromag system
% has two planar gradiometers and one axial magnetometer at each sensor location.
% You do not want to plot those on top of each other. Hence the Neuromag layout
% files contain two (for the old 122 channel system) or three (for the recent
% 306 channel systems) separate subplots for each channel location. Those two
% (or three) subplots hold the data for the two planar gradients and for the magnetometer
% signal.

cfg = [];
cfg.layout = 'neuromag306all.lay';
cfg.layout = ft_prepare_layout(cfg);
figure; ft_plot_layout(cfg.layout);
%%
% You should zoom in on the figure to see the triplets for the three channels
% ar each sensor locations. There are also template layouts available that only
% contain the magnetometer channels at the correct location (i.e. not shifted)
% and that contain the combined planar channels. The latter one can be used after
% applying ft_combineplanar on your data.
%
% *==== Topoplot functions ====*
%
%
%
% Ft_topoplotER and ft_topoplotTFR plot the topographic distribution of 2-Dimensional
% or 3-Dimensional datatypes as a 2-D circular view (looking down at the top of
% the head). The arrangement of the channels is again specified in the layout
% (see above in multiplot functions). The ft_topoplotER and ft_topoplotTFR functions
% first again select the data to be plotted from the 2D or 3D input data and subsequently
% plot the selected data using low-level Fieldtrip functions. Using one value
% for each channel and the x and y coordinates, the values between points are
% interpolated and plotted.

cfg = [];
cfg.xlim = [0.3 0.5];
cfg.zlim = [0 6e-14];
cfg.layout = 'CTF151.lay';
cfg.parameter = 'individual'; % the default (avg) is not present
figure; ft_topoplotER(cfg,GA_FC); colorbar
%%
%

cfg = [];
cfg.xlim = [0.9 1.3];
cfg.ylim = [15 20];
cfg.zlim = [-1e-27 1e-27];
cfg.baseline = [-0.5 -0.1];
cfg.baselinetype = 'absolute';
cfg.layout = 'CTF151.lay';
figure; ft_topoplotTFR(cfg,TFRhann); colorbar

%%
% You can compare this to the more realistic helmet-style layout, which
% better acknowledges the fact that the MEG channels extend below the ears and
% that the helmet has sort of an opening at the face.

cfg = [];
cfg.xlim = [0.9 1.3];
cfg.ylim = [15 20];
cfg.zlim = [-1e-27 1e-27]; % this is in T^2
cfg.baseline = [-0.5 -0.1];
cfg.baselinetype = 'absolute';
cfg.layout = 'CTF151_helmet';
figure; ft_topoplotTFR(cfg,TFRhann); colorbar
%%
%   The baseline correction computes the power difference compared to the
% pre-stimuls baseline. We can also look at the power ratio

cfg = [];
cfg.xlim = [0.9 1.3];
cfg.ylim = [15 20];
cfg.zlim = [0.6 1.4]; % the value 1 means 100%, so this ranges from 60% to 140% of the baseline power
cfg.baseline = [-0.5 -0.1];
cfg.baselinetype = 'relative';
cfg.layout = 'CTF151_helmet';
figure; ft_topoplotTFR(cfg,TFRhann); colorbar
%%
% The interpretation becomes more clear with

cfg = [];
cfg.xlim = [0.9 1.3];
cfg.ylim = [15 20];
cfg.zlim = [0.6 1.4]; % the value 1 means 100%, so this ranges from 60% to 140% of the baseline power
cfg.baseline = [-0.5 -0.1];
cfg.baselinetype = 'relative';
cfg.layout = 'CTF151_helmet';
figure; ft_topoplotTFR(cfg,TFRhann); colorbar

% so far it was the same as above, now change the colormap
ft_hastoolbox('brewermap', 1);         % ensure this toolbox is on the path
colormap(flipud(brewermap(64,'RdBu'))) % change the colormap
%%
% See <http://colorbrewer2.org http://colorbrewer2.org> for more details.
%
% In the help of ft_topoplotER and ft_topoplotTFR you can find many cfg options.
% For instance by specifying the cfg.xlim as a vector the functions makes selections
% of multiple time-windows and plots them as a series of subplots.

% for the multiple plots also
cfg = [];
cfg.xlim = [-0.4:0.2:1.4];
cfg.ylim = [15 20];
cfg.zlim = [-1e-27 1e-27];
cfg.baseline = [-0.5 -0.1];
cfg.baselinetype = 'absolute';
cfg.layout = 'CTF151_helmet.mat';
cfg.comment = 'xlim';
cfg.commentpos = 'title';
figure; ft_topoplotTFR(cfg,TFRhann);
%%
% In ft_topoplotER and ft_topoplotTFR, you can specify many options to fully
% control the appearance of the picture. Subsequently you can use the MATLAB print
% function to write the figure to a file. Preferred file formats are EPS for vector
% drawings that can be edited in Adobe Illustrator or in Canvas (using ?print
% -depsc?) or PNG for bitmaps (using ?print -dpng?).
%
% To make the EPS-files optimally suitable for Adobe Illustrator, use the
% command ?print -depsc -adobecs -painter?.
%
% Since MATLAB uses the 'painter' renderer to export in Illustrator format,
% this method allows one to export quite complex figures that otherwise would
% be exported as bitmaps. Note, however, that the 'painter' renderer also has
% certain limitations compared to the z-buffer and openGL renderers. (See also
% MATLAB help on selecting a renderer).
%
% Some examples of what you can do:

% options for data selection (used with any plotting function):
cfg = [];
cfg.xlim = [0.9 1.3];
cfg.ylim = [15 20];
cfg.zlim = [-1e-27 1e-27];
cfg.baseline = [-0.5 -0.1];
cfg.baselinetype = 'absolute';
cfg.layout = 'CTF151.lay';
%%
% Options specific to the topoplot

cfg.gridscale = 300;
cfg.style = 'straight';
cfg.marker = 'labels';
figure; ft_topoplotTFR(cfg,TFRhann);
%%
%

cfg.gridscale = 300;
cfg.contournum = 10;
cfg.colormap = gray(10);
figure; ft_topoplotTFR(cfg,TFRhann);
%%
%

cfg.gridscale = 300;
cfg.contournum = 4;
cfg.colormap = spring(4);
cfg.markersymbol  = '.';
cfg.markersize = 12;
cfg.markercolor = [0 0.69 0.94];
figure; ft_topoplotTFR(cfg,TFRhann);
%%
%
%
% *==== Interactive mode ====*
%
% During the phase of the analysis in which you do a lot of data inspection,
% you can use the interactive modus to go from one plot to the other. You can
% for instance select a certain frequency and time range in a singleplot, to get
% the average over that range plotted in a topoplot. Or select a group of channels
% in a topoplot or a multiplot and get the average over those channels for the
% whole time and frequency range in a single plot.
%
%

%interactive
cfg = [];
cfg.baseline = [-0.5 -0.1];
cfg.zlim = [-3e-27 3e-27];
cfg.baselinetype = 'absolute';
cfg.layout = 'CTF151.lay';
cfg.interactive = 'yes';
figure; ft_multiplotTFR(cfg,TFRhann);
%%
%
%
% You should select channels using the mouse and click, then you get singleplot
% average over those channels. You should select a time-frequency window and click,
% then you get topoplot average over that time-frequency window.
%
%
%
% *==== Plotting clusters ====*
%
% Ft_clusterplot plots a series of topoplots that highlight the clusters
% from cluster-based permutation testing. The output "stat" is 2D data from **[[reference:ft_timelockstatistics]]**
% or **[[reference:ft_freqstatistics]]** with cfg.correctm='cluster'.
%
% The function automatically finds the clusters in the data which are smaller
% than the pre-specified threshold (cfg.alpha) and plots a series of topoplots
% with the data in "stat" field (are for instance t-values) and the sensors which
% are part of the cluster highlighted.
%
% Stat should be 2D, i.e. channels-by-time, or channels-by frequency. You
% cannot visualize channels-by-frequency-by-time, that case requires either averaging
% over time, or averaging over frequency.
%
% *== Clusters in timelocked data ==*

% clusterplot
cfg = [];
cfg.zlim = [-6 6]; % T-values
cfg.alpha = 0.05;
cfg.layout = 'CTF151.lay';
ft_clusterplot(cfg,statERF);
%%
%
%
% *== Clusters in time-frequency data ==*

% clusterplot
cfg = [];
cfg.zlim = [-5 5];
cfg.alpha = 0.05;
cfg.layout = 'CTF151.lay';
ft_clusterplot(cfg,statTFR);
%%
%
%
% *==== Plotting channel-level connectivity ====*
%
% This is possible using ft_connectivityplot,  ft_multiplotCC and ft_topoplotCC.
%
%
%
% *==== Plotting Principal or Independent Components (PCA/ICA)====*
%
% To plot PCA, ICA or other decompositions that result from ft_componentanalysis
% you can use ft_topoplotIC for the topographies and ft_databrowser for the topographies
% combined with the time series. For a viewer that displays the power spectrum,
% topography and variance over time of each component, see [[https://github.com/fieldtrip/fieldtrip/blob/master/contrib/misc/ft_icabrowser.m]].
%
%
%
% *===== Plotting data at the source level =====*
%
% With the ft_sourceplot function you can plot functional source reconstructed
% data. Data structures can be source estimates from ft_sourceanalysis or ft_sourcegrandaverage
% or statistical values from ft_sourcestatistics. The following sections will
% present the available options for source-level plotting, following the same
% structure as previous sections.
%
% In visualising source reconstructed data, you should consider that  there
% are two principled ways of representing the spatial dimension of source reconstructed
% data:
%
%   - On a regular, 3-dimensional grid, i.e. volumetric data like an MRI
% scan
%
%   - On a surface geometry, i.e. a cortical sheet.
%
% Besides the three dimensions that describe the spatial or geometrical aspect
% of source reconstructed brain activity, the data can have additional dimensions
% for time and/or frequency.
%
%
%
% *==== Volumetric data  ====*
%
% Source level data is considered volumetric if the locations at which activity
% is estimated are spaced in a regular 3-dimensional grid, like voxels in an MRI.
% FieldTrip offers multiple plotting options for volumetric data that can be specified
% in the cfg for ft_sourceplot|ft_sourceplot.
%
% You can (1) make multiple 2D axials slices throughout the brain on which
% the functional data is plotted, (2) create three slices in each of the three
% orthorgonal directions (axial, sagittal and coronal) on which you can click
% around to navigate the whole the brain (3) project the functional data onto
% a surface and make a 3-D rendering of that.
%
% Let us first provide the basic code to use one of these plotting methods,
% using the data from Subject01 from the beamformer tutorial.  Later on, we will
% give more details on the configuration options for ft_sourceplot.
%
% *=== Individual anatomical MRI (prior to spatial normalization) ===*
%
%

% load MRI, reslice it and interpolate the low-res functional data onto the high-res anatomy
mri = ft_read_mri('Subject01.mri');
mri = ft_volumereslice([], mri);

cfg            = [];
cfg.downsample = 2;
cfg.parameter  = 'pow';
sourceDiffInt  = ft_sourceinterpolate(cfg, sourceDiff , mri);
%%
%

% spatially normalize the anatomy and functional data to MNI coordinates
cfg = [];
cfg.nonlinear = 'no';
sourceDiffIntNorm = ft_volumenormalise(cfg, sourceDiffInt);
%%
%

% plot multiple 2D axial slices
cfg = [];
cfg.method        = 'slice';
cfg.funparameter  = 'pow';
cfg.maskparameter = cfg.funparameter;
cfg.funcolorlim   = [0.0 1.2];
cfg.opacitylim    = [0.0 1.2];
cfg.opacitymap    = 'rampup';
ft_sourceplot(cfg, sourceDiffInt);

% idem, in MNI (or SPM) coordinates
ft_sourceplot(cfg, sourceDiffIntNorm);
%%
%

% plot 3 orthogonal slices
cfg = [];
cfg.method        = 'ortho';
cfg.funparameter  = 'pow';
cfg.maskparameter = cfg.funparameter;
cfg.funcolorlim   = [0.0 1.2];
cfg.opacitylim    = [0.0 1.2];
cfg.opacitymap    = 'rampup';
ft_sourceplot(cfg, sourceDiffInt);

% idem, in MNI (or SPM) coordinates
ft_sourceplot(cfg, sourceDiffIntNorm);
%%
%
%
% The three essential cfg parameters are:
%
%   * cfg.anaparameter the anatomy parameter, specifying the anatomy to be
% plotted
%
%   * cfg.funparameter the functional parameter, specifying the functional
% data to be plotted
%
%   * cfg.maskparameter the mask parameter, specifying the parameter to be
% used to mask the functional data
%
% All data that is used in the figure (anatomical, functional, mask) must
% be interpolated and represented onto the same grid. See ft_sourceinterpolate
% and ft_volumenormalise.
%
% *=== the anatomical parameter ===*
%
% The anatomy can be read with **[[:reference:ft_read_mri]]**. The functional
% data can be interpolated onto the anatomy by **[[reference:ft_sourceinterpolate]]**.
% The anatomy is scaled between 0 and 1 and plotted in gray scale.
%
% *=== the functional parameter ===*
%
% The functional data is plotted in color optionally on top of the anatomy.
% The colors used can be determined by cfg.colormap (see MATLAB function COLORMAP).
% How the functional values are assigned to the colormap is determined by cfg.colorlim.
% It makes sense to plot for instance source data as functional parameter, but
% also statistical values (for instance T-values).
%
% *=== the masking parameter ===*
%
% You can control the opacity of the functional data by the mask parameter.
% Which values are plotted opaque and which transparent is determined by cfg.opacitymap
% and cfg.opacitylim (see MATLAB function ALPHA and ALPHAMAP). The opacity map
% determines the degree of opacity of the functional data going from opaque to
% transparent.  There are multiple ways to determine your opacity scale, as a
% user you can determine the opacity values for each and every single voxel (and
% as such, region of interest).  As such, the opacity limits determine how the
% opacity map is assigned to the values of the mask parameter.
%
% === Example 1: Plotting only positive values ===
%
% Imagine that your functional data has values ranging from -3 to 3. Here
% we plot only the positive values  (zeromax), using the scale whereby the strongest
% values are opaque, and the values close to zero are transparent:
%
% |  cfg.maskparameter = cfg.funparameter|
%
% |  cfg.colorlim      = [0 3] (or'zeromax')|
%
% |  cfg.opacitymap    = 'rampup'|
%
% |  cfg.opacitylim    = [0 3] (or 'zeromax')|
%
%
%
% === Example 2: Plotting high absolute values ===
%
% Suppose the functional data is the same as in example 1, but now we only
% wants to plot the high negative values and high positive values (use "maxabs"
% setting). We set these high absolute values to opaque, and the values around
% zero to transparent:
%
% |  cfg.maskparameter = cfg.funparameter|
%
% |  cfg.colorlim      = [-3 3] (or'maxabs')|
%
% |  cfg.opacitymap    = 'vdown'|
%
% |  cfg.opacitylim    = [-3 3] (or'maxabs')|
%
%
%
% === Example 3: Masking voxels outside values of interest ===
%
% Here, we make a field in the data with an opacity value for each voxel,
% and apply that as your mask. For instance if you only want to plot the values
% between 2 and 2.5 you can specify:
%
% |  data.mask         = (data.fun>2 & data.fun<2.5)|
%
% |  cfg.maskparameter = 'mask'|
%
%
%
% ==== Plotting on a brain surface ====
%
% === Scalar data per vertex ===
%
% The representation of source activity on a surface results from source
% estimation using a cortical sheet as the source model. The cortical sheet is
% represented as a triangulated surface and the activity is assigned to each of
% the vertices, i.e. corner points of the triangles. Besides doing the source
% estimation on a cortical sheet, it is also possible to interpolate the volumetric
% data (i.e. estimated on a regular 3-D grid) onto a cortical sheet for visualization.
%
% Scalar data (e.g., time-averaged activity, frequency-specific power estimates,
% statistics, etc.) can be plotted using the ft_plot_mesh function. Alternatively,
% volumetric data can also be rendered on a surface by projecting it to a surface
% geometry, using ft_sourceplot. An example of the latter is given below, where
% we use the same data as in the preceding section.
%
%
%
% === Project volumetric data to an MNI white-matter surface surface ===
%
%

cfg = [];
cfg.method         = 'surface';
cfg.funparameter   = 'pow';
cfg.maskparameter  = cfg.funparameter;
cfg.funcolorlim    = [0.0 1.2];
cfg.funcolormap    = 'jet';
cfg.opacitylim     = [0.0 1.2];
cfg.opacitymap     = 'rampup';
cfg.projmethod     = 'nearest';
cfg.surffile       = 'surface_white_both.mat'; % Cortical sheet from canonical MNI brain
cfg.surfdownsample = 10;  % downsample to speed up processing
ft_sourceplot(cfg, sourceDiffIntNorm);

view ([90 0])             % rotate the object in the view
%%
% If you enable the camera toolbar (menu option "view", "camera toolbar")
% you have more options for controlling the 3-dimensional rendering, e.g. change
% perspective, change the position of the light (used for relection and shadows).
%
%
%
% As with the channel-level multiplots, you can change the colormap that
% maps the functional values on the colors.

ft_sourceplot(cfg, sourceDiffIntNorm);
colormap jet

ft_sourceplot(cfg, sourceDiffIntNorm);
colormap hot

ft_sourceplot(cfg, sourceDiffIntNorm);
colormap cool

%%
% If you right-click with the mouse on the colobar in the figure, you can
% also also do this interactively.
%
% To  interactively explore higher-dimensional data (such as TFR data) on
% the surface, ft_sourceplot cannot be used. You can make selections of a specific
% time and/or frequency and make a series of sublplots.
%
% *=== Higher dimensional source-level data ===*
%
%
%
% Since source-level function data requires three dimensions for "space"
% and uses the color dimension for "strength", there is no graphical dimension
% in which the temporal evolution or the spectral distribution can be visualized
% in full detail. The ft_sourceplot function allows you with method=ortho to use
% teh lower right corner of the figure to show the timecourse or spectrum of the
% functional activity at a specific location (the one you click). The ft_sourcemovie
% function allows you to use time (as in a movie) to explore the changes of cortical
% activity over time and/or frequency.
%
%
%
% *==== Using external tools ====*
%
%
%
% Although MATLAB is a very flexible development and analysis environment,
% it is not super-fast in visualisation. Hence external visualisation tools are
% sometimes more useful for exploring your data. Volumetric and surface based
% data can be exported to standard file formats using **[[:reference:ft_sourcewrite]]**.
% Subsequently, you can use external tools such as
%
%
%
%   * [[http://www.mccauslandcenter.sc.edu/mricro/mricron/index.html|MRIcron]]
%
%   * [[http://www.openwalnut.org|OpenWallnut]]
%
%   * [[http://www.humanconnectome.org/software/connectome-workbench.html|Connectome
% Workbench]]
%
%   * https://github.com/piermorel/gramm
%
%
%
% *=====Suggested further reading=====*
%
% Plotting channel-level data in a 2-dimensional representation on your flat
% computer screen or on paper requires that the 3-dimensional channel positions
% are mapped or projected onto the 2-dimensional plane. The tutorial on [[layout|specifying
% the channel layout for plotting]] explains how this mapping is constructed.
%
%


function compute_movie_file(A, filename, options)

% compute_movie_file - create an avi or gif file
%
%   compute_movie_file(A, filename, options);
%
%   A can be a 3D array or a cell array of 2D matrices.
%   Each A{k} or A(:,:,k) is one frame in the animation.
%
%   Output avi or gif file depending on the extension of the filename.
%   (you can also use options.format='avi' or 'gif')
%
%   Copyright (c) 2007 Gabriel Peyre

options.null = 0;
fps = getoptions(options, 'fps', 10);
format = getoptions(options, 'format', []);

if isempty(format)
    % find extension
    i = strfind(filename,'.');
    if isempty(i)
        error('Does not recognize extension, you should specify options.format.');
    end
    format = filename(i+1:end);
end

if not(iscell(A)) && not(isstr(A))
    B = A; A = {};
    for i=1:size(B,3)
        A{end+1} = B(:,:,i);
    end
    clear B;
end

% close all;
% figure;

if iscell(A)
    nb = length(A);
else
    nb = length( dir([A '*.png']) );
end

if strcmp(format, 'avi')
    % 'Indeo3', 'Indeo5', 'Cinepak', 'MSVC', 'RLE' or 'None'
    compressor = 'Cinepak';
    compressor = 'none';
    qual = 50;
    aviobj = avifile(filename, 'compression', compressor, 'quality', qual, 'fps', fps );
    % aviobj = avifile(filename, 'fps', fps );
end

imap = getoptions(options, 'colormap', jet(256));
loopCount = getoptions(options, 'loopcount', 1);

for j=1:nb
    progressbar(j,nb);
    if iscell(A)
        B = A{j};
    else
        % A is a filename
        B = load_image( [A '-' num2string_fixeddigit(j-1,3)] );
    end
    B = round(rescale( B, 1,256));
    switch format
        case 'avi'
            if size(B,3)==3
                frame = im2frame( rescale(B) );
            else
                frame = im2frame(B,gray(256));
            end
            % imageplot(A{j});
            % frame = getframe ( gca );
            aviobj = addframe( aviobj, frame );
        case 'gif'
            warning off;
            if j==1
                imwrite(B,imap,filename,'gif',...
                    'DelayTime',1/fps, 'LoopCount',loopCount,...
                    'WriteMode','overwrite')
            else
                imwrite(B,imap,filename,'gif','WriteMode','append',...
                    'DelayTime',1/fps);
            end
            warning on;
        otherwise
            error('Unknown format');
    end
end

if strcmp(format, 'avi')
    warning off;
    aviobj = close( aviobj );
    warning on;
end


%ISSTACKED Test on stacked mapping
%
%   N = ISSTACKED(W)
%   ISSTACKED(W)
%
% INPUT
%   W  Mapping
%
% OUTPUT
%   N  Scalar, 1 if W is a stacked mapping, 0 otherwise
%
% DESCRIPTION
% Returns 1 for stacked mappings. If no output is requested, false outputs
% are turned into errors. This may be used for assertion.
%
% SEE ALSO (PRTools Guide)
% ISMAPPING, ISPARALLEL

% $Id: isstacked.m,v 1.2 2006/03/08 22:06:58 duin Exp $

function n = isstacked(w)

		if (isa(w,'prmapping')) & (strcmp(w.mapping_file,'stacked'))
%			strcmp(w.mapping_file,'dyadicm')
		n = 1;
	else
		n = 0;
	end

	% Generate an error if the input is not a stacked mapping and no output
	% is requested (assertion).

	if (nargout == 0) & (n == 0)
		error([newline '---- Stacked mapping expected -----'])
	end

return


function xy_io_test05 ( )

%*****************************************************************************80
%
%% XY_IO_TEST05 tests XYF_EXAMPLE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 January 2009
%
%  Author:
%
%    John Burkardt
%
  xy_filename = 'annulus.xy';
  xyf_filename = 'annulus.xyf';

  fprintf ( 1, '\n' );
  fprintf ( 1, 'XY_IO_TEST05\n' );
  fprintf ( 1, '  XYF_EXAMPLE sets up XY and XYF data.\n' );

  [ point_num, face_num, face_data_num ] = xyf_example_size ( );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Example has:\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of points     = %d\n', point_num );
  fprintf ( 1, '  Number of faces      = %d\n', face_num );
  fprintf ( 1, '  Number of face items = %d\n', face_data_num );

  [ xy, face_pointer, face_data ] = xyf_example ( point_num, face_num, ...
    face_data_num );

  xy_write ( xy_filename, point_num, xy );

  xyf_write ( xyf_filename, point_num, face_num, face_data_num, ...
    face_pointer, face_data );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Wrote the XY file "%s".\n', xy_filename );
  fprintf ( 1, '  and the XYF file "%s"\n', xyf_filename ) ;

  return
end


%% Copyright (C) 2017, 2022 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/>.

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @deffn  Command assume {@var{x} @var{cond}}
%% @deffnx Command assume {@var{x} @var{cond} @var{cond2} @dots{}}
%% @deffnx Command assume {@var{x} @var{y} @dots{} @var{cond} @var{cond2} @dots{}}
%% Specify assumptions for a symbolic variable (replace existing).
%%
%% Example:
%% @example
%% @group
%% syms n x y
%% assume n integer
%% assume x y real
%% assumptions
%%   @result{} ans =
%%     @{
%%       [1,1] = n: integer
%%       [1,2] = x: real
%%       [1,3] = y: real
%%     @}
%% @end group
%% @end example
%%
%% To clear assumptions on a variable, use @code{assume x clear}, for example:
%% @example
%% @group
%% assume x y clear
%% assumptions
%%   @result{} ans =
%%     @{
%%       [1,1] = n: integer
%%     @}
%% @end group
%% @end example
%%
%% For more precise control over assumptions, @pxref{@@sym/assume}
%% and @pxref{@@sym/assumeAlso}.
%%
%% @seealso{@@sym/assume, @@sym/assumeAlso, assumptions, sym, syms}
%% @end deffn

function varargout = assume(varargin)

  assert (nargout == 0, 'assume: use functional form if you want output');

  assert (nargin > 1, 'assume: general algebraic assumptions are not supported');

  %% Find symbol/assumptions boundary and verify input
  valid_asm = assumptions ('possible');
  lastvar = -1;
  for n = 1:nargin
    assert (ischar (varargin{n}), 'assume: command form expects string inputs only')
    if (ismember (varargin{n}, valid_asm))
      if (lastvar < 0)
        lastvar = n - 1;
      end
    elseif (strcmp (varargin{n}, 'clear'))
      assert (n == nargin, 'assume: "clear" should be the final argument')
      assert (lastvar < 0, 'assume: should not combine "clear" with other assumptions')
      lastvar = n - 1;
    elseif (lastvar > 0)
      error('assume: cannot have symbols after assumptions')
    else
      assert (isvarname (varargin{n}), 'assume: only symbols can have assumptions')
    end
  end

  if (lastvar < 0)
    error ('assume: no assumptions were given')
  end
  if (lastvar == 0)
    error ('assume: cannot have only assumptions w/o symbols')
  end

  asm = varargin((lastvar+1):end);
  vars = varargin(1:lastvar);

  %% loop over each variable
  for n = 1:length (vars)
    vals = evalin ('caller', vars{n});
    newvals = cell(1, numel (vals));
    [newvals{:}] = assume (vals, asm{:});

    for i = 1:length (newvals)
      newx = newvals{i};
      xstr = newx.flat;

      % ---------------------------------------------
      % Muck around in the caller's namespace, replacing syms
      % that match 'xstr' (a string) with the 'newx' sym.
      context = 'caller';
      % ---------------------------------------------
      S = evalin(context, 'whos');
      evalin(context, '[];');  % clear 'ans'
      for i = 1:numel(S)
        obj = evalin(context, S(i).name);
        [newobj, flag] = symreplace(obj, xstr, newx);
        if flag, assignin(context, S(i).name, newobj); end
      end
      % ---------------------------------------------

    end
  end
end

%!error <if you want output>
%! a = assume('a', 'real')

%!error <cannot have only assumptions>
%! assume positive integer

%!error <no assumptions>
%! assume x y

%!error <should be the final>
%! assume x clear real

%!error <algebraic assumptions are not supported>
%! assume a>0

%!error <only symbols>
%! assume 'x/pi' integer

%!test
%! syms x
%! assume x positive
%! a = assumptions(x);
%! assert(strcmp(a, 'x: positive'))
%! assume x even
%! a = assumptions(x);
%! assert(strcmp(a, 'x: even'))

%!test
%! % multiple assumptions
%! syms x
%! assume x positive integer
%! [tilde, a] = assumptions(x, 'dict');
%! assert(a{1}.integer)
%! assert(a{1}.positive)

%!test
%! % does workspace
%! syms x positive
%! x2 = x;
%! f = sin(x);
%! assume x negative
%! a = assumptions(x);
%! assert(strcmp(a, 'x: negative'))
%! a = assumptions(x2);
%! assert(strcmp(a, 'x: negative'))
%! a = assumptions(f);
%! assert(strcmp(a, 'x: negative'))

%!error <undefined>
%! % does not create new variable x
%! clear x
%! assume x real

%!error <undefined>
%! % no explicit variable named x
%! clear x
%! f = 2*sym('x');
%! assume x real

%!test
%! % clear does workspace
%! syms x positive
%! f = 2*x;
%! assume x clear
%! assert (isempty (assumptions (f)));
%! assert (isempty (assumptions ()));

%!test
%! syms x y
%! f = sin (2*x);
%! assume x y real
%! assert (strcmp (assumptions (x), 'x: real'))
%! assert (strcmp (assumptions (y), 'y: real'))
%! assert (strcmp (assumptions (f), 'x: real'))

%!test
%! syms x y
%! f = sin (2*x);
%! assume x y positive even
%! assert (strcmp (assumptions (x), 'x: positive, even') || strcmp (assumptions (x), 'x: even, positive'))
%! assert (strcmp (assumptions (y), 'y: positive, even') || strcmp (assumptions (y), 'y: even, positive'))
%! assert (strcmp (assumptions (f), 'x: positive, even') || strcmp (assumptions (f), 'x: even, positive'))

%!test
%! % works from variable names not symbols
%! syms x y
%! a = [x y];
%! assume a real
%! assert (strcmp (assumptions (x), 'x: real'))
%! assert (strcmp (assumptions (y), 'y: real'))

%!test
%! % works from variable names not symbols
%! y = sym('x');
%! f = 2*y;
%! assume y real
%! assert (strcmp (assumptions (f), 'x: real'))

%!test
%! % matrix of symbols
%! syms a b c d
%! A = [a b; c d];
%! assume A real
%! assert (strcmp (assumptions (a), 'a: real'))
%! assert (strcmp (assumptions (b), 'b: real'))
%! assert (strcmp (assumptions (c), 'c: real'))
%! assert (strcmp (assumptions (d), 'd: real'))

%!test
%! % assume after symfun
%! clear x
%! syms f(x)
%! assume x real
%! assert (~ isempty (assumptions (formula (f))))
%! assert (~ isempty (assumptions (argnames (f))))


function displaytable(colname,varargin)
%% DISPLAYTABLE display data in table
%
% Example
%
%	load dispdata
%   colname = {'#nodes'     '|u_I-u_h|_1'      '||p-p_h||'};
%   displaytable(colname,err.N,[],err.uH1,'%0.5e',err.pL2,'%0.5e');
%
% Note that all data are column arrays.
%
% See also disptable
%
% Copyright (C)  Long Chen. See COPYRIGHT.txt for details.

col = varargin{1};
rownum = size(col,1);
colnum = size(colname,2);
colwidth = zeros(1,colnum);
dispresult = char(zeros(rownum,6*colnum));
idx = 1;
for c = 1:nargin/2
    if isempty(varargin{2*c})
        currentstr = num2str(varargin{2*c-1});
    else
        currentstr = num2str(varargin{2*c-1},varargin{2*c});
    end
    colwidth(c) = size(currentstr,2);
    dispresult(:,idx:idx+colwidth(c)-1) = currentstr;
    idx = idx+colwidth(c)+3;
end
for c = 1:colnum
    spnum = colwidth(c) - length(colname{c})+3;
    if spnum >0
        if c>1
            colname{c} = [char(zeros(1,floor(spnum/2))) colname{c} ...
                          char(zeros(1,ceil(spnum/2)))];
        else
            colname{c} = [char(zeros(1,floor(spnum/3))) colname{c} ...
                          char(zeros(1,ceil(spnum/2)))];
        end
    end
end
% fprintf('\n');
disp(cell2mat(colname));
fprintf('\n');
disp(dispresult);
fprintf('\n');


function BC = createBC1D(meshvar)
% function BC = createBC1D(meshvar)
% Creates a boundary condition structure from a mesh structure
%
% SYNOPSIS:
%   BC = createBC1D(meshvar)
%
% PARAMETERS:
%
%
% RETURNS:
%
%
% EXAMPLE:
%
% SEE ALSO:
%

% Define the right, and left boundary conditions
% (default = Neumann, i.e., a = 1, b = 0, c = 0)

right.a = 1;
right.b = 0;
right.c = 0;
right.periodic = 0;

left.a = 1;
left.b = 0;
left.c = 0;
left.periodic = 0;

bottom=[];
top=[];
back=[];
front=[];

BC= BoundaryCondition(meshvar, left, right, bottom, top, back, front);


function chanind = selectchannels(this, channels)
% Method for getting channel indices based on labels and/or types
% FORMAT  res = selectchannels(this, label)
% this       - MEEG object
% channels   - string or cell array of labels that may also include
%              'all', or types ('EEG', 'MEG' etc.)
%
% res        - vector of channel indices matching labels
%__________________________________________________________________________
% Copyright (C) 2010-2012 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: selectchannels.m 7253 2018-02-04 17:20:57Z vladimir $

if ischar(channels)
    channels = {channels};
end

chanind = [];

for i = 1:numel(channels)
    if strncmpi('regexp_', channels{i}, 7)
        re        = channels{i}(8:end);
        match     = regexp(chanlabels(this), re);
        chanind   = [chanind find(~cellfun('isempty', match))];
    else
        cind    = indchannel(this, channels{i});
        if ~isempty(cind)
            chanind = [chanind cind];
        elseif ismember(upper(channels{i}), ...
                {'ALL','MEG', 'MEGPLANAR', 'MEGMAG', 'MEGGRAD', 'MEGCOMB','EEG',...
                'EOG', 'ECG', 'EMG', 'LFP', 'SRC', 'PHYS', 'ILAM', 'OTHER', 'REF', 'REFMAG', 'REFGRAD'})
            chanind = [chanind indchantype(this, upper(channels{i}))];
        end
    end

    if any(size(chanind) == 0)
        chanind = [];
    end
end

chanind = unique(chanind);


function tal = mrAnatGetTalairachDists
%
% tal = mrAnatGetTalairachDists
%
% Simple function to return the measured distances (in mm) from
% the original Talairach and Tournoux brain. The origin is assumed
% to be the ac. However, note that the ppc point is the distance
% from the pc- to get the most posterior distance from the ac, use
% ppc+acpc.
%
% HISTORY:
% 2005.04.29 RFD:wrote it.

tal.sac = 72;
tal.iac = -42;
tal.lac = -62;
tal.rac = 62;
tal.aac = 68;
tal.acpc = -24;
tal.ppc = -78;
return;


function transportRxns=getTransportRxns(model)
% getTransportRxns
%   Retrieves the transport reactions from a model
%
%   model           a model structure
%
%   transportRxns   logical array with true if the corresponding
%                   reaction is a transport reaction
%
%   Transport reactions are defined as reactions involving (at least) one
%   metabolite name in more than one compartment.
%
%   Usage: transportRxns=getTransportRxns(model)

transportRxns=false(numel(model.rxns),1);

for i=1:numel(model.rxns)
    %Get the involved metabolites in each reaction
    mets=model.metNames(model.S(:,i)~=0);
    transportRxns(i)=numel(mets)~=numel(unique(mets));
end
end


function obj = Calc_Mannings_Landcover(obj,data,type,varargin)
% obj = Calc_Mannings_Landcover(obj,data,type,varargin)
% Input a msh class object and interpolates a land-cover database file
% (netcdf format) onto the msh while converting to mannings values through
% a look-up table
%
% type:
%  - 'nlcd':
%    NLCD 2006 Land Cover (2011 Edition) (1.1Gb) from
%    https://www.mrlc.gov/nlcd06_data.php
%  - 'ccap':
%    CCAP NOAA land cover:
%    https://coast.noaa.gov/data/digitalcoast/pdf/ccap-class-scheme-regional.pdf
%
% varargin: Accepts the same options as for msh.interp to control how
%           data is interpolated; see 'help msh.interp'
%
%  Author:            KR & WP July 19, 2018
%  Update for CCAP:   WP May 5, 2021
%  Update for storing incremental interpolation results: KJ & OK July 9, 2021
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin < 3 || isempty(type)
   type = 'nlcd';
end

if strcmp(type,'nlcd')
    disp('Info: Using NLCD table')
    % NLCD table
    load nlcd
    nlcd_mannings(end+1)=nlcd_mannings(11); % <--make NaN = default value
    varargin{end+1}='lut';
    varargin{end+1}=nlcd_mannings;
elseif strcmp(type,'ccap')
    disp('Info: Using CCAP table')
    % CCAP table
    load ccap
    ccap_mannings(end+1)=ccap_mannings(21); % <-- make NaN = default value
    varargin{end+1}='lut';
    varargin{end+1}=ccap_mannings;
else
    error('Land-cover database not supported')
end
% The mannings name and default value
attrname = 'mannings_n_at_sea_floor';
default_val = varargin{end}(end); %end of the lut is default
dmy = msh();  dmy.p = obj.p; dmy.t = obj.t;
% Convert to Mannings and interpolate how the user wants
dmy = interp(dmy,data,varargin{:});
Man = dmy.b';
Man( isnan(Man) | Man==0 ) = default_val; %points outside of lut can still be NaN
%% Make into f13 struct
if isempty(obj.f13)
    % Add add mannings as first entry in f13 struct
    obj.f13.AGRID = obj.title;
    obj.f13.NumOfNodes = length(obj.p);
    obj.f13.nAttr = 1;
    NA = 1;
else
    broken = 0;
    for NA = 1:obj.f13.nAttr
        if strcmp(attrname,obj.f13.defval.Atr(NA).AttrName)
            broken = 1;
            % overwrite existing tau0
            break
        end
    end
    if ~broken
        % add mannings to list
        obj.f13.nAttr = obj.f13.nAttr + 1;
        NA = obj.f13.nAttr;
    end
end

% Default Values
obj.f13.defval.Atr(NA).AttrName = attrname;
% We can just put in the options here
obj.f13.defval.Atr(NA).Unit = 'unitless';
valpernode = 1;
obj.f13.defval.Atr(NA).ValuesPerNode = valpernode ;
obj.f13.defval.Atr(NA).Val = default_val ;

% User Values
obj.f13.userval.Atr(NA).AttrName = attrname ;
numnodes = length(find(Man ~= default_val));
obj.f13.userval.Atr(NA).usernumnodes = numnodes ;
% Print out list of nodes for each
K = find(Man ~= default_val);
if isfield(obj.f13.userval.Atr(NA),'Val')
    obj.f13.userval.Atr(NA).Val = [obj.f13.userval.Atr(NA).Val'; K' , Man(K)']';
else
    obj.f13.userval.Atr(NA).Val = [K ; Man(K)];
end
%EOF
end


function [imgs, TR, scanspersess, names, onsets, durations] = spm_mat2batchinput(SPM)
% Extract info from SPM structure and format in batch input mode
%
% :Usage:
% ::
%
%     [imgs, TR, scanspersess, names, onsets, durations] = spm_mat2batchinput(SPM)
%
% :Input into SPM8::
%
%   tmod = time modulator (number per cell, order, linear = 1)
%
% For parametric modulation include a structure array, which is up to 1 x n in size, called pmod. n must be less
% than  or  equal  to  the  number  of  cells in the names/onsets/durations cell arrays. The structure array pmod
% must  have the fields: name, param and poly.  Each of these fields is in turn a cell array to allow the inclusion
% R for regressors of no interest
%
% NOTES:
% This is a preliminary version of this function and does not extract
% covariates, parametric modulators, etc.
%
% Returns output in the format you would use to enter into the SPM GUI to
% set up a model. Same format is used by canlab_spm_fmri_model_job.m
%
% ..
%    Tor Wager, Feb 2011
%    Could be extended to include nuisance covs, parametric modulators, etc.
%    Right now this is very basic.
% ..
%
% CANlab SPM 1st-level model helper tools:
% scn_spm_design_check, spm2canlab_dataset, spm_mat2batchinput, scn_spm_get_events_of_interest

if iscell(SPM.xY.P) % check input image names
    imgs = char(SPM.xY.P{:});
else
    imgs = SPM.xY.P;
end

TR = SPM.xY.RT;
scanspersess = SPM.nscan;

[names, onsets, durations, covs] = deal({});

% list regressor names
for sess = 1:length(SPM.Sess)

    names = [names cat(1, SPM.Sess(sess).U(:).name)'];
    %disp(sprintf('Session %3.0f', sess));

end

% check onsets
% 0 should be the start of the first image acquisition

for sess = 1:length(SPM.Sess)

    %disp(sprintf('Session %3.0f', sess));

    for evt = 1:length(SPM.Sess(sess).U)
        %         disp(['Session ' num2str(sess) ' event type: ' SPM.Sess(sess).U(evt).name])
        %         [SPM.Sess(sess).U(evt).ons  SPM.Sess(sess).U(evt).durations]

        onsets = [onsets {SPM.Sess(sess).U(evt).ons}];
        durations = [durations {SPM.Sess(sess).U(evt).dur}];

    end

end


function Abar = computeAbar(A, ny)
    Abar_tmp = cell(ny,1);
    tmp = A;

    for i=1:ny
        Abar_tmp{i,1} = tmp;
        tmp = tmp*A;
    end

    Abar = cell2mat(Abar_tmp);

end


function [I] = imgread(img, c)
%
% Copyright Aditya Khosla http://mit.edu/khosla
%
% Please cite this paper if you use this code in your publication:
%   A. Khosla, J. Xiao, A. Torralba, A. Oliva
%   Memorability of Image Regions
%   Advances in Neural Information Processing Systems (NIPS) 2012
%

if(ischar(img))
    I = imread(img);
else
    I=img;
end

scale = min(min(c.maxsize/size(I, 1), c.maxsize/size(I, 2)), 1);
if(scale~=1)
	I = imresize(I, scale);
end

if(size(I,3)==1)
	I=cat(3, I, I, I);
end


function sendJointsPositionsf( t_Kuka ,jPos)
%% Syntax:
% sendJointsPositionsf( t_Kuka ,jPos)

%% About
% This function is used to send the target positions of the joints for the
% direct servo motion
% this function is for direct-servoing in joint space

%% Arreguments
% jPos: is 7 cells array of doubles
% t: is the TCP/IP connection object

% Copy right, Mohammad SAFEEA, 3rd of May 2017

theCommand='jf_';
for i=1:7
    x=jPos{i};
    theCommand=[theCommand,sprintf('%0.5f',x),'_'];
end
fprintf(t_Kuka, theCommand);
end


function [cplx_str,cplx_inc,cplx_lib,cplx_libname,cplx_ver] = opti_FindCplex()
%Finds IBM ILOG CPLEX Libraries and returns path and version

%Known CPLEX path locations (Modify to suit your system by adding to cell arrays, or create a new structure for other versions)
CPLX125.x64 = {'C:\Program Files\IBM\ILOG\CPLEX_Studio125\cplex\'};
CPLX125.x86 = {'C:\Program Files (x86)\IBM\ILOG\CPLEX_Studio125\cplex\'};
CPLX125.ver = '12.5';
CPLX125.lib = 'cplex125';

CPLX124.x64 = {'C:\Program Files\IBM\ILOG\CPLEX_Studio_Academic124\cplex\'};
CPLX124.x86 = {'C:\Program Files (x86)\IBM\ILOG\CPLEX_Studio_Academic124\cplex\'};
CPLX124.ver = '12.4';
CPLX124.lib = 'cplex124';

%Add any new structures to below
CPLXLIB = {CPLX125,CPLX124};

%DO NOT MODIFY BELOW HERE
for i = 1:length(CPLXLIB)
    %Check for CPLEX
    [ok,cplx_str,cplx_inc,cplx_lib,cplx_libname,cplx_ver] = checkCPLXVer(CPLXLIB{i});
    if(ok), return; end
end

%Still no Luck - user must locate
error('Could not find the IBM ILOG CPLEX Location on your computer. Please modify this file to locate it');

function [ok,cplx_str,cplx_inc,cplx_lib,cplx_libname,cplx_ver] = checkCPLXVer(cplxstr)
%Local check function
ok = false;
%Defaults
cplx_str = []; cplx_inc = []; cplx_lib = []; cplx_libname = []; cplx_ver = [];
%Find local config paths
switch(computer)
    case 'PCWIN'
        if(~isfield(cplxstr,'x86') || isempty(cplxstr.x86))
            error('No x86 CPLEX directories specified to check');
        end
        paths = cplxstr.x86;
    case 'PCWIN64'
        if(~isfield(cplxstr,'x64') || isempty(cplxstr.x86))
            error('No x64 CPLEX directories specified to check');
        end
        paths = cplxstr.x64;
    otherwise
        error('This function is only setup for Windows PCs');
end
for i = 1:length(paths)
    if(exist(paths{i},'dir'))
        dir_cplx = paths{i};
        %Get Include Directory
        cplx_inc = [dir_cplx 'include\ilcplex'];
        if(~exist(cplx_inc,'dir'))
            error('Could not find Cplex include directory. Checked:\n %s',cplx_inc);
        end
        %Get Library Directory
        switch(computer)
            case 'PCWIN'
                cplx_lib = [dir_cplx 'lib\x86_windows_vs2010\stat_mda\'];
            case 'PCWIN64'
                cplx_lib = [dir_cplx 'lib\x64_windows_vs2010\stat_mda\'];
        end
        if(~exist(cplx_lib,'dir'))
            error('Could not find Cplex lib directory. Checked:\n %s\n',cplx_lib);
        end
        %Build complete linker line
        cplx_str = [' -I"' cplx_inc '" -L"' cplx_lib '" -l' cplxstr.lib ' '];
        cplx_libname = cplxstr.lib;
        cplx_ver = cplxstr.ver;
        ok = true;
        return;
    end
end


%kmgident 'Generate identity or unit matrix '
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros mgident.pane file
%
% Parameters:
% Integer: r 'Rows', default: 0: 'rows'
% Integer: c 'Cols', default: 0: 'cols'
% OutputFile: o 'Output Matrix', required: 'Output matrix'
%
% Example: o = kmgident( {'r',0;'c',0;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% mgident - Generate Identity or Unit Matrix
%
%  DESCRIPTION
% .I mgident
% is used to generate a matrix with all diagonal elements equal to one (unity).
% The output is of type DOUBLE.
%
% "mgident\fR is a pane object pointing to \fImgdiag\fR in the MATRIX
% toolbox.
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
% mgdiag(1)
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kmgident(varargin)
Inputs={};
if nargin ==0
  arglist={'',''};
elseif nargin ==1
  arglist=varargin{1};
else error('Usage: [out1,..] = kmgident(arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'r', 0;'c', 0;'o', '__output'};
maxval={1,1,0};
minval={1,1,0};
istoggle=[1,1,0];
was_set=istoggle * 0;
paramtype={'Integer','Integer','OutputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; 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 'mgdiag"  -cr'],Inputs,narglist);


function cyclic_reduction_test ( )

%*****************************************************************************80
%
%% CYCLIC_REDUCTION_TEST tests the CYCLIC_REDUCTION library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 May 2010
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CYCLIC_REDUCTION_TEST\n' );
  fprintf ( 1, '  MATLAB version.\n' );
  fprintf ( 1, '  Test the CYCLIC_REDUCTION library.\n' );

  cyclic_reduction_test01 ( );
  cyclic_reduction_test02 ( );
  cyclic_reduction_test03 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CYCLIC_REDUCTION_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function bc = specific_bc(xbd,ybd)
%zero_bc   Reference problems 5.3 and 5.4 boundary condition
%   bc = specific_bc(xbd,ybd);
%   input
%          xbd          x boundary coordinate vector
%          ybd          y boundary coordinate vector
%
%   specifies streamfunction associated with enclosed flow
%   IFISS function: DJS; 6 March 2005.
% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage
bc=0*xbd;
return


function [ net,opts ] = selective_sgd( net,opts )
%NET_APPLY_SELECTIVE_SGD Summary of this function goes here
%   Detailed explanation goes here

    if (mod(opts.parameters.current_ep,opts.parameters.ssgd_search_freq)==1||opts.parameters.ssgd_search_freq==1)

        if ~isfield(opts.parameters,'selection_count')
            opts.parameters.selection_count=0;
        end

        [lr_best]=select_learning_rate(net,opts);
        opts.parameters.lr=lr_best;

        if ~isfield(opts.parameters,'selected_lr')
            opts.parameters.selected_lr(1)=lr_best;
        else
            opts.parameters.selected_lr(end+1)=lr_best;
        end

        opts.parameters.selection_count=opts.parameters.selection_count+1;

        disp(['Selected learning rate: ',num2str(opts.parameters.lr)]);

    end

end


function [nodes, edges, ages, error] = removeUnconnected(nodes, edges,ages,error) %#codegen

NumOfNodes = size(nodes,2);

i = 1;
while NumOfNodes >= i
    if any(edges(i,:)) == 0

        edges = [edges(1:i-1,:); edges(i+1:NumOfNodes,:);];
        edges = [edges(:,1:i-1)  edges(:,i+1:NumOfNodes);];

        ages = [ages(1:i-1,:); ages(i+1:NumOfNodes,:);];
        ages = [ages(:,1:i-1)  ages(:,i+1:NumOfNodes);];

        nodes = [nodes(:,1:i-1) nodes(:,i+1:NumOfNodes);];
        error = [error(1,1:i-1) error(1,i+1:NumOfNodes);];

        NumOfNodes = NumOfNodes - 1;

        i = i -1;
    end
    i = i+1;
end

% MEX-code generation

% mexcfg = coder.config('mex');
% mexcfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';
% codegen -config mexcfg removeUnconnected -args {coder.typeof(nodes,[Inf Inf]),coder.typeof(edges,[Inf Inf]),coder.typeof(ages,[Inf Inf]),coder.typeof(error,[1 Inf])}


%==============================================================================
% This code is part of the Matlab-based toolbox
% FAIR - Flexible Algorithms for Image Registration.
% For details see
% - https://github.com/C4IR and
% - http://www.siam.org/books/fa06/
%==============================================================================
% This scripts checks whether the required data is already available.
% If if so and possible, it also initializes the modules
% viewimage, imgModel, trafo, distance, regularizer for later use;
% see setup2DhandsData.m for an example
%==============================================================================
caller          = dbstack;        % identify the name of the calling function
caller          = caller(min(length(caller),2)).name;
expfile         = fullfile(FAIRpath,'temp',[caller,'.mat']);
expfileExists   = (exist(expfile,'file') == 2);

if ~expfileExists,
  return;         % matfile has to be generated
end;

fprintf('%s: load(%s); and initialize modules\n',...
  caller,expfile(length(FAIRpath)+1:end));
clear caller
load(expfile);

% initialize toolbox
if ~isempty(who(expfile,'viewPara')),    viewImage('reset',viewPara{:});  end;
if ~isempty(who(expfile,'imgPara')),     imgModel('reset',imgPara{:});    end;
if ~isempty(who(expfile,'traPara')),     trafo('reset',traPara{:});       end;
if ~isempty(who(expfile,'disPara')),     distance('reset',disPara{:});    end;
if ~isempty(who(expfile,'regPara')),     regularizer('reset',regPara{:}); end;
%==============================================================================


function [CnoHelp] = SkipMatlabHelp (C)
%
%   [CnoHelp] = SkipMatlabHelp (C)
%
%Purpose:
%   removes the first set of comments from a character array
%   that would normally consiture matlab's help text (see example)
%
%
%Input Parameters:
%   C : a character array
%
%
%Output Parameters:
%   CnoHelp : C without the help comments
%
%
%
%More Info :
%   C = sprintf ('%%Hello Baby\n%%Couci Couci Cooo\nAbc = 100\n%%Waldo\njon=6')
%   [CnoHelp] = SkipMatlabHelp (C)
%
%  PurgeComments
%	NextString
%	FindChar
%
%     Author : Ziad Saad
%     Date : Sat Mar 27 14:27:36 CST 1999

%Define the function name for easy referencing
FuncName = 'SkipMatlabHelp';

%Debug Flag
DBG = 1;

%initailize return variables
err = 1;
CnoHelp = [];

if (C(1) == '%'),
	cpos = 1;
	Loc = 1;
	while (~isempty(Loc) & Loc(1) == 1 & ~isempty(C)),
		%get the 1st line
			[err, Cnext, cend] = NextString (C, 'NewLine', 1);
		%get ridd of 1st line
			nC = length(C);
			C = C(cend+1:nC);
		%search for first %
			[err, Loc] = FindChar (C, '%');
	end
	CnoHelp = C;
else
	CnoHelp = C;
end

err = 0;
return;


function value = year_length_months_common ( y )

%*****************************************************************************80
%
%% YEAR_LENGTH_MONTHS_COMMON returns the number of months in a Common year.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 July 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, the year to be checked.
%
%    Output, integer VALUE, the number of months in the year.
%
  value = 12;

  return
end


function varargout = imdown(varargin)
% VL_IMDOWN  Downsample an image by two
%   J = VL_IMDOWN(I) downsamples the image I by half by discarding
%   each other pixel.
%
%   VL_IMDOWN() accepts the following options:
%
%   Method:: Sample
%     'Sample' downsamples the image by discarding
%     pixels. 'Average' instead averages groups of 2x2 pixels.
%
%   See also: VL_IMUP(), VL_HELP().
[varargout{1:nargout}] = vl_imdown(varargin{:});


function pointLocations = markImagePoints(imgax,varname,clr)
% Pass in a handle to an image-containing axes
% (optional; default is returned by imgca);
%
% Brett Shoelson, PhD
% brett.shoelson@mathworks.com
% 3/25/2011
%
% Copyright 2011 MathWorks, Inc.

if nargin == 0 || isempty(imgax)
    imgax = imgca;
end
axes(imgax);%#ok
imghandle = imhandles(imgax);
if isempty(imghandle)
    error('MarkImagePoints: specified axes does not contain an image!')
end
imghandle = imghandle(1); % Just in case there are multiple images in the axes
parentfig = ancestor(imgax,'figure');
pointLocationsRequested = nargin > 1;
pointLocations = [];
if pointLocationsRequested
    requestedvar = varname;
    if isempty(requestedvar)
        requestedvar = 'MarkedPoints';
    end
end
if nargin < 3
    clr = [1 0 0]; %default = red
end
oldTitleProps = get(get(imgax,'title'));
tmp       = title(imgax,'Click to define object(s). Press <ENTER> to finish selection.');
set(tmp,'color',clr,'fontsize',12, 'fontweight','b','tag','markImagePoints', 'Visible', 'on');
currBDF   = get(imgax,'ButtonDownFcn');
currKPF   = get(parentfig,'KeyPressFcn');
set(imgax,'ButtonDownFcn','');
set(imghandle,'ButtonDownFcn',@placePoint);
set(parentfig,'KeyPressFcn',  @noMorePoints);

    function roi = impoint2(varargin)
        % impoint2: improved impoint object
        roi      = impoint(varargin{:});
        % Add a context menu for adding points
        l        = findobj(roi,'type','hggroup');
        uic      = unique( get(l,'UIContextMenu') );
        for u = 1:numel(uic)
            uimenu( uic(u), 'Label', 'Delete', 'Callback', @deleteROI )
        end

        function deleteROI(src,evt) %#ok
            delete(roi);
        end

    end

    function pointLocations = noMorePoints(~,evt)
        finished  = strcmpi(evt.Key,'return');
        if finished
            % Delete title, reset original functionality
            %delete(findall(parentfig,'tag','markImagePoints'));
            set(findall(parentfig,'tag','markImagePoints'),...
                'string',oldTitleProps.String,...
                'color',oldTitleProps.Color,...
                'tag',oldTitleProps.Tag,...
                'fontsize',oldTitleProps.FontSize,...
                'fontweight',oldTitleProps.FontWeight,...
                'visible',oldTitleProps.Visible);
            set(imghandle,'ButtonDownFcn','');
            set(parentfig,'KeyPressFcn','');
            set(imgax,'ButtonDownFcn',currBDF);
            set(parentfig,'KeyPressFcn',currKPF);
            if pointLocationsRequested
                roi = findall(imgax,'type','hggroup');
                pointLocations = NaN(numel(roi),2);
                for ii = 1:numel(roi)
                    tmp = get(roi(ii),'children');
                    pointLocations(ii,1) = get(tmp(1),'xdata');
                    pointLocations(ii,2) = get(tmp(1),'ydata');
                end
                assignin('base',requestedvar,pointLocations);
            end
        end

    end

    function placePoint(varargin)
        point_loc = get(imgax,'CurrentPoint');
        point_loc = point_loc(1,1:2);
        impoint2(imgax,point_loc);
    end

end


function loc = match_sorted_rows(a,s)
%MATCH_SORTED_ROWS   Location of matches in sorted rows.
% MATCH_SORTED_ROWS(A,S) returns LOC such that S(LOC(i),:) = A(i,:).
% If A(i,:) is not in S, LOC(i) = 0.
% S must be sorted and unique.
%
% This function is a special case of ISMEMBER_SORTED_ROWS.

% Written by Tom Minka
% (c) Microsoft Corporation. All rights reserved.

[tf,loc] = ismember_sorted_rows(a,s);


%MTIT		creates a major title in a figure with many axes
%
%		MTIT
%		- creates a major title above all
%		  axes in a figure
%		- preserves the stack order of
%		  the axis handles
%
%SYNTAX
%-------------------------------------------------------------------------------
%		P = MTIT(TXT,[OPT1,...,OPTn])
%		P = MTIT(FH,TXT,[OPT1,...,OPTn])
%
%INPUT
%-------------------------------------------------------------------------------
%    FH	:	a valid figure handle		[def: gcf]
%   TXT	:	title string
%
% OPT	:	argument
% -------------------------------------------
%  xoff	:	+/- displacement along X axis
%  yoff	:	+/- displacement along Y axis
%  zoff	:	+/- displacement along Z axis
%
%		title modifier pair(s)
% -------------------------------------------
%   TPx	:	TVx
%		see: get(text) for possible
%		     parameters/values
%
%OUTPUT
%-------------------------------------------------------------------------------
% par	:	parameter structure
%  .pos :	position of surrounding axis
%   .oh	:	handle of last used axis
%   .ah :	handle of invisible surrounding axis
%   .th :	handle of main title
%
%EXAMPLE
%-------------------------------------------------------------------------------
%	subplot(2,3,[1 3]);		title('PLOT 1');
%	subplot(2,3,4); 		title('PLOT 2');
%	subplot(2,3,5); 		title('PLOT 3');
%	axes('units','inches',...
%	     'color',[0 1 .5],...
%	     'position',[.5 .5 2 2]);	title('PLOT 41');
%	axes('units','inches',...
%	     'color',[0 .5 1],...
%	     'position',[3.5 .5 2 2]);	title('PLOT 42');
%	shg;
%	p=mtit('the BIG title',...
%	     'fontsize',14,'color',[1 0 0],...
%	     'xoff',-.1,'yoff',.025);
% % refine title using its handle <p.th>
%	set(p.th,'edgecolor',.5*[1 1 1]);

% created:
%	us	24-Feb-2003		/ R13
% modified:
%	us	24-Feb-2003		/ CSSM
%	us	06-Apr-2003		/ TMW
%	us	13-Nov-2009 17:38:17

%-------------------------------------------------------------------------------
function	par=mtit(varargin)

		defunit='normalized';
	if	nargout
		par=[];
	end

% check input
	if	nargin < 1
		help(mfilename);
		return;
	end
	if	isempty(get(0,'currentfigure'))
		disp('MTIT> no figure');
		return;
	end

		vl=true(size(varargin));
	if	ischar(varargin{1})
		vl(1)=false;
		figh=gcf;
		txt=varargin{1};
	elseif	any(ishandle(varargin{1}(:)))		&&...
		ischar(varargin{2})
		vl(1:2)=false;
		figh=varargin{1};
		txt=varargin{2};
	else
		error('MTIT> invalid input');
	end
		vin=varargin(vl);
		[off,vout]=get_off(vin{:});

% find surrounding box
		ah=findall(figh,'type','axes');
	if	isempty(ah)
		disp('MTIT> no axis');
		return;
	end
		oah=ah(1);

		ou=get(ah,'units');
		set(ah,'units',defunit);
		ap=get(ah,'position');
	if	iscell(ap)
		ap=cell2mat(get(ah,'position'));
	end
		ap=[	min(ap(:,1)),max(ap(:,1)+ap(:,3)),...
			min(ap(:,2)),max(ap(:,2)+ap(:,4))];
		ap=[	ap(1),ap(3),...
			ap(2)-ap(1),ap(4)-ap(3)];

% create axis...
		xh=axes('position',ap);
% ...and title
		th=title(txt,vout{:});
		tp=get(th,'position');
		set(th,'position',tp+off);
		set(xh,'visible','off','hittest','on');
		set(th,'visible','on');

% reset original units
		ix=find(~strcmpi(ou,defunit));
	if	~isempty(ix)
	for	i=ix(:).'
		set(ah(i),'units',ou{i});
	end
	end

% ...and axis' order
		uistack(xh,'bottom');
		axes(oah);				%#ok

	if	nargout
		par.pos=ap;
		par.oh=oah;
		par.ah=xh;
		par.th=th;
	end
end
%-------------------------------------------------------------------------------
function	[off,vout]=get_off(varargin)

% search for pairs <.off>/<value>

		off=zeros(1,3);
		io=0;
	for	mode={'xoff','yoff','zoff'};
		ix=strcmpi(varargin,mode);
	if	any(ix)
		io=io+1;
		yx=find(ix);
		ix(yx+1)=1;
		off(1,io)=varargin{yx(end)+1};
		varargin=varargin(xor(ix,1));
	end
	end
		vout=varargin;
end
%-------------------------------------------------------------------------------


function [conn,connnum,count]=neighborelem(elem,nn);
%
% [conn,connnum,count]=neighborelem(elem,nn)
%
% create node neighbor list from a mesh
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% date: 2007/11/21
%
% input:
%    elem:  element table of a mesh
%    nn  :  total node number of the mesh
%
% output:
%    conn:  output, a cell structure of length nn, conn{n}
%           contains a list of all neighboring elem ID for node n
%    connnum: vector of length nn, denotes the neighbor number of each node
%    count: total neighbor numbers
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

conn=cell(nn,1);
dim=size(elem);
for i=1:dim(1)
  for j=1:dim(2)
    conn{elem(i,j)}=[conn{elem(i,j)},i];
  end
end
count=0;
connnum=zeros(1,nn);
for i=1:nn
    conn{i}=sort(conn{i});
    connnum(i)=length(conn{i});
    count=count+connnum(i);
end


function tests = test_gifti
% Unit Tests for gifti
%__________________________________________________________________________
% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging

% $Id: test_gifti.m 6516 2015-08-07 17:28:33Z guillaume $

tests = functiontests(localfunctions);

function test_gifti_constructor(testCase)
import matlab.unittest.constraints.*
g1 = gifti;
g2 = gifti(fullfile(spm('Dir'),'canonical','cortex_20484.surf.gii'));
g3 = gifti(g2);
s  = struct(g3);
g4 = gifti(s);
g5 = gifti(rand(16,1));

testCase.verifyThat(g1, IsOfClass('gifti'));
testCase.verifyThat(fieldnames(g1), IsEmpty);

testCase.verifyThat(g2, IsOfClass('gifti'));
testCase.verifyThat(s, HasField('faces'));
testCase.verifyThat(s, HasField('vertices'));
testCase.verifyThat(s, HasField('mat'));

testCase.verifyThat(g3, IsOfClass('gifti'));
testCase.verifyThat(g3, IsEqualTo(g2));

testCase.verifyThat(s, IsOfClass('struct'));
testCase.verifyThat(s, HasField('faces'));
testCase.verifyThat(s, HasField('vertices'));
testCase.verifyThat(s, HasField('mat'));

testCase.verifyThat(g4, IsOfClass('gifti'));
testCase.verifyThat(struct(g4), IsEqualTo(s));

testCase.verifyThat(g5, IsOfClass('gifti'));
testCase.verifyThat(g5, HasField('cdata'));

function test_gifti_accessor(testCase)
import matlab.unittest.constraints.*
g1 = gifti(fullfile(spm('Dir'),'canonical','cortex_8196.surf.gii'));
s.faces    = g1.faces;
s.vertices = g1.vertices;
s.mat      = g1.mat;
testCase.verifyEqual(s.faces(1000,:), g1.faces(1000,:));
testCase.verifyEqual(s.vertices(1000,:), g1.vertices(1000,:));
testCase.verifyEqual(s.mat(:,4), g1.mat(:,4));

cdata = single(rand(16,1));
g2 = gifti(cdata);
testCase.verifyEqual(cdata,g2.cdata);
testCase.verifyEqual(cdata(8),g2.cdata(8));
testCase.verifyEqual(cdata(8,1),g2.cdata(8,1));

function test_gifti_mutator(testCase)
import matlab.unittest.constraints.*
g = gifti(fullfile(spm('Dir'),'canonical','cortex_5124.surf.gii'));
g.mat = eye(4);
g.mat(logical(eye(4))) = 2;
g.mat(4,4) = 1;
testCase.verifyEqual(g.mat, diag([2 2 2 1]));

faces = g.faces;
faces = faces(:,[2 1 3]);
g.faces = faces;
g.faces(64,:) = [1 2 3];
g.faces(:,1) = faces(:,1);
testCase.verifyEqual(g.faces(64,:), [faces(64,1) 2 3]);

vertices = g.vertices;
vertices = vertices(:,[2 1 3]);
g.vertices = vertices;
g.vertices(64,:) = zeros(1,3);
g.vertices(:,2:3) = ones(size(vertices,1),2);
testCase.verifyEqual(g.vertices(64,:), single([0 1 1]));

g.cdata = rand(size(g.vertices,1),1);
g.cdata(1) = pi;
g.cdata(2:end) = exp(1);
testCase.verifyEqual(g.cdata(1), single(pi));

function test_gifti_export(testCase)
import matlab.unittest.constraints.*
mri = load('mri');
g = gifti(isosurface(smooth3(squeeze(mri.D)),5));
s = export(g);
testCase.verifyThat(s, HasField('vertices'));
testCase.verifyThat(s, HasField('faces'));
s = export(g,'matlab');
testCase.verifyThat(s, HasField('vertices'));
testCase.verifyThat(s, HasField('faces'));
s = export(g,'patch');
testCase.verifyThat(s, HasField('vertices'));
testCase.verifyThat(s, HasField('faces'));
testCase.verifyThat(s, ~HasField('mat'));
s = export(g,'fieldtrip');
testCase.verifyThat(s, HasField('pnt'));
testCase.verifyThat(s, HasField('tri'));
s = export(g,'spm');
testCase.verifyThat(s, HasField('vert'));
testCase.verifyThat(s, HasField('face'));

function test_gifti_load(testCase)
import matlab.unittest.constraints.*
d = fullfile(spm('Dir'),'canonical');
files = dir(fullfile(d,'*.gii'));
for i=1:numel(files)
    g = gifti(fullfile(d,files(i).name));
    testCase.verifyThat(evalc('g'), ~IsEmpty); % check display()
end

function test_gifti_save(testCase)
mri = load('mri');
g = gifti(isosurface(smooth3(squeeze(mri.D)),5));
g.cdata = rand(size(g.vertices,1),1);
basename = tempname;
file = [basename '.gii'];
save(g,file,'ASCII');
g = gifti(file);
delete(file);
save(g,file,'Base64Binary');
g = gifti(file);
delete(file);
save(g,file,'GZipBase64Binary');
g = gifti(file);
delete(file);
save(g,file,'ExternalFileBinary');
g = gifti(file);
delete(file);
delete([basename '.dat']);


function mesh_write_emse(p)

% mesh_write_emse - Save mesh to EMSE (.wfr) file
%
% USEAGE: mesh_write_emse(p)
%
% Write a .wfr file, in minor revision 3 format (ascii),
% for each mesh in p.mesh.data.  If any cells of
% p.mesh.data.meshtype are empty, these cells will
% be skipped.
%
% See the EMSE website at http://www.sourcesignal.com
% for more information on file formats.
%

% $Revision: 1.1 $ $Date: 2009-04-28 22:13:58 $

% Licence:  GNU GPL, no implied or express warranties
% History:  06/2002 Darren.Weber_at_radiology.ucsf.edu
%                 - created function from mesh_emse2matlab
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

fprintf('\nMESH_WRITE_EMSE...\n');

if ~exist('p','var'),
  error('...no input p struct.\n');
elseif isempty(p),
  error('...input p struct is empty.\n');
elseif isempty(p.mesh.data),
  error('...input p struct has no mesh data.\n');
end

[path,name,ext] = fileparts(strcat(p.mesh.path,filesep,p.mesh.file));
file = fullfile(path,[name ext]);

fprintf('...writing EMSE meshes to:\n\t%s\n',fullfile(path,name));

tic;

Meshes = p.mesh.data.meshtype;

for i=1:size(Meshes,2),

  if Meshes{i},
    write_emse(file,p.mesh.data.vertices{i},p.mesh.data.faces{i},Meshes{i});
  end

end

t=toc; fprintf('...done (%5.2f sec).\n\n',t);

return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function write_emse(file,vertex,face,meshtype)

[path,name,ext] = fileparts(file);
ext = '.wfr';

name = strcat(name,'_',meshtype);

file = fullfile(path,[name ext]);

fid = fopen(file,'w','ieee-le');

if(fid == -1),
  fprintf('...could not open file: %s',file);
  return;
else

  fprintf('...writing tesselation: %s\n',[name ext]);

  % Write prolog
  fprintf(fid,'3\t4000\n');
  fprintf(fid,'3\n');

  % Write mesh type
  type = lower(meshtype);
  switch type,
    case 'unknown',     fprintf(fid,  '0\n');
    case 'scalp',       fprintf(fid, '40\n');
    case 'outer skull', fprintf(fid, '80\n');
    case 'outer_skull', fprintf(fid, '80\n');
    case 'inner skull', fprintf(fid,'100\n');
    case 'inner_skull', fprintf(fid,'100\n');
    case 'cortex',      fprintf(fid,'200\n');
    case 'pial',        fprintf(fid,'200\n'); % cortex variant
    case 'white',       fprintf(fid,'200\n'); % cortex variant
    case 'smoothwm',    fprintf(fid,'200\n'); % cortex variant
    otherwise,          fprintf(fid,  '0\n');
      fprintf('\n...WARNING, unknown meshtype!\n\n');
  end

  % EMSE Voxel Coordinates
  % Voxel coordinates measure location in terms of the voxels inherent in
  % the given volumetric set. The origin is the bottom (inferior) axial
  % slice, the posterior row and in the rightmost column. This coordinate
  % system is right-handed (although, internally, the origin is in the
  % anterior row, and thus is left-handed; this representation is not
  % available to the user). The order of the displayed coordinates is
  % (slice#, row#, column#).
  %
  % EMSE MRI Coordinates
  % MRI coordinates share the same origin as internal voxel coordinates,
  % but differ from the latter in two ways: first, the coordinates
  % are measured in millimeters, not voxels. Secondly, the origin is that
  % of the internal representation; that is, the inferior slice, anterior
  % row and rightmost column. As mentioned above, this internal representation
  % is left-handed. To correct for this, the row axis is numbered in the
  % opposite direction, making the displayed coordinate system right-handed.
  % The order of the displayed coordinates is (x, y, z).

  % Given a point P(x,y,z) in head frame (the activation point on the
  % cortical mesh) and you want to find the corresponding voxel in the
  % vmi file.  Symbolically you have P(head) and you want to find P(voxel).
  %
  % 1.  The registration file contains the matrix HeadToImage,
  %     so P(MRI-mm) = HeadToImage*P(head), where P(MRI-mm) is the
  %     point in MRI coordinates.
  % 2.  From the voxel size, you can find P(MRI-voxel), which
  %     is the MRI coordinates expressed in voxels
  % 3.  Use the offset between the MRI coordinate frame and
  %     the Image coordinate frame to find P(voxel).
  %
  %Demetrios Voreades, Ph.D.
  %Applications Engineer, Source Signal Imaging
  %

  % Rotate -90 degrees around Z, given that emse coordinates
  % have +X through Nasion and +Y through left ear.
  fprintf('...rotating coordinate axes so +X anterior, +Y left, +Z superior\n');
  vertex = rz(vertex,-90,'degrees');

  % Write vertex data
  for v = 1:size(vertex,1),
    fprintf(fid,'v\t%12.8f\t%12.8f\t%12.8f\n',vertex(v,1),vertex(v,2),vertex(v,3));
  end

  % matlab vertex indices start at one,
  % not zero, so we subtract one from matlab values
  face = face - 1;
  for t = 1:size(face,1),
    fprintf(fid,'t\t%d\t%d\t%d\t\n',face(t,1),face(t,2),face(t,3));
  end

  fclose(fid);

end

return


function neqn = p03_neqn ( )

%*****************************************************************************80
%
%% P03_NEQN returns the number of equations for problem P03.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer NEQN, the number of equations.
%
  neqn = 1;

  return
end


function test_suite = test_mergeBoxes
%testMergeBoxes  One-line description here, please.
%
%   output = testMergeBoxes(input)
%
%   Example
%   testMergeBoxes
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2010-08-06,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2010 INRA - Cepia Software Platform.

test_suite = functiontests(localfunctions);

function testBasic(testCase) %#ok<*DEFNU>
box1 = [5 20 10 25];
box2 = [0 15 15 20];
exp  = [0 20 10 25];
box = mergeBoxes(box1, box2);
testCase.assertEqual(exp, box, 'AbsTol', .01);


function tests = test_imEuler1d(varargin)
%TEST_IMEULER1D  One-line description here, please.
%
%   output = test_imEuler1d(input)
%
%   Example
%   test_imEuler1d
%
%   See also
%

% ------
% Author: David Legland
% e-mail: david.legland@inra.fr
% Created: 2010-10-08,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2010 INRA - Cepia Software Platform.

tests = functiontests(localfunctions);

function testBasic(testCase)

img = [0 0 1 1 1 0 1 0];

len = imEuler1d(img);

exp = 2;
assertEqual(testCase, exp, len);

function testAddBorder(testCase)

img = ones(1, 5);
imgb = padarray(img, [0 1]);

len = imEuler1d(img);
len2 = imEuler1d(imgb);

assertEqual(testCase, len, len2);

function testCalib(testCase)

img = [0 0 1 1 1 0 1 0];

len = imEuler1d(img, .4);

exp = 2;
assertEqual(testCase, exp, len);


function value = p08_autonomous ( )

%*****************************************************************************80
%
%% P08_AUTONOMOUS reports whether problem P08 is autonomous.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer VALUE, is 1 if the equation is autonomous.
%
  value = 1;

  return
end


function varargout = chebfuneps(val)
%CHEBFUNEPS   Set the default value of the chebfuneps preference.
%   CHEBFUNEPS VAL, or CHEBFUNEPS(VAL) sets the default value of the
%   chebfuneps preference to the specified value VAL. CHEBFUNEPS(VAL) is
%   equivalent to CHEBFUNPREF.SETDEFAULTS('chebfuneps', VAL).
%
%   CHEBFUNEPS factory, or CHEBFUNEPS('factory') sets the default
%   chebfuneps preference to the factory value. This is equivalent to
%   chebfunpref.setDefaults('chebfuneps', 'factory').
%
%   CHEBFUNEPS prints the current default value of the chebfuneps
%   preference.
%
%   If changing the preference is needed only for a single construction,
%   calling constructor with the 'eps' flag is a better option.
%
% See also CHEBFUN2EPS and CHEBFUN3EPS.

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

if ( nargin == 0 )
    % Return current chebfuneps:
    varargout{1} = chebfunpref().techPrefs.chebfuneps;
else
    if ( strcmpi(val, 'factory') )
        chebfunpref.setDefaults('chebfuneps', 'factory');
    else
        eval(['val=',val,';'])
        if ( isnumeric(val) )
            chebfunpref.setDefaults('chebfuneps', val);
        else
            error('CHEBFUN:chebfuneps:unknownOption',...
                'Unknown CHEBFUNEPS option.')
        end
    end
end

end