function [x,endPop,bPop,traceInfo] = ga(bounds,evalFN,evalOps,startPop,opts,...
termFN,termOps,selectFN,selectOps,xOverFNs,xOverOps,mutFNs,mutOps)
% GA run a genetic algorithm
% function [x,endPop,bPop,traceInfo]=ga(bounds,evalFN,evalOps,startPop,opts,
%                                       termFN,termOps,selectFN,selectOps,
%                                       xOverFNs,xOverOps,mutFNs,mutOps)
%
% Output Arguments:
%   x            - the best solution found during the course of the run
%   endPop       - the final population
%   bPop         - a trace of the best population
%   traceInfo    - a matrix of best and means of the ga for each generation
%
% Input Arguments:
%   bounds       - a matrix of upper and lower bounds on the variables
%   evalFN       - the name of the evaluation .m function
%   evalOps      - options to pass to the evaluation function ([NULL])
%   startPop     - a matrix of solutions that can be initialized
%                  from initialize.m
%   opts         - [epsilon prob_ops display] change required to consider two
%                  solutions different, prob_ops 0 if you want to apply the
%                  genetic operators probabilisticly to each solution, 1 if
%                  you are supplying a deterministic number of operator
%                  applications and display is 1 to output progress 0 for
%                  quiet. ([1e-6 1 0])
%   termFN       - name of the .m termination function (['maxGenTerm'])
%   termOps      - options string to be passed to the termination function
%                  ([100]).
%   selectFN     - name of the .m selection function (['normGeomSelect'])
%   selectOpts   - options string to be passed to select after
%                  select(pop,#,opts) ([0.08])
%   xOverFNS     - a string containing blank seperated names of Xover.m
%                  files (['arithXover heuristicXover simpleXover'])
%   xOverOps     - A matrix of options to pass to Xover.m files with the
%                  first column being the number of that xOver to perform
%                  similiarly for mutation ([2 0;2 3;2 0])
%   mutFNs       - a string containing blank seperated names of mutation.m
%                  files (['boundaryMutation multiNonUnifMutation ...
%                           nonUnifMutation unifMutation'])
%   mutOps       - A matrix of options to pass to Xover.m files with the
%                  first column being the number of that xOver to perform
%                  similiarly for mutation ([4 0 0;6 100 3;4 100 3;4 0 0])

% Binary and Real-Valued Simulation Evolution for Matlab
% Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay
%
% C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function
% optimization: A Matlab implementation. ACM Transactions on Mathmatical
% Software, Submitted 1996.
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 1, or (at your option)
% any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details. A copy of the GNU
% General Public License can be obtained from the
% Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

%%$Log: ga.m,v $
%Revision 1.10  1996/02/02  15:03:00  jjoine
% Fixed the ordering of imput arguments in the comments to match
% the actual order in the ga function.
%
%Revision 1.9  1995/08/28  20:01:07  chouck
% Updated initialization parameters, updated mutation parameters to reflect
% b being the third option to the nonuniform mutations
%
%Revision 1.8  1995/08/10  12:59:49  jjoine
%Started Logfile to keep track of revisions
%

n=nargin;
if n<2 | n==6 | n==10 | n==12
  disp('Insufficient arguements')
end
if n<3 %Default evalation opts.
  evalOps=[];
end
if n<5
  opts = [1e-6 1 0];
end
if isempty(opts)
  opts = [1e-6 1 0];
end

if any(evalFN<48) %Not using a .m file
  if opts(2)==1 %Float ga
    e1str=['x=c1; c1(xZomeLength)=', evalFN ';'];
    e2str=['x=c2; c2(xZomeLength)=', evalFN ';'];
  else %Binary ga
    e1str=['x=b2f(endPop(j,:),bounds,bits); endPop(j,xZomeLength)=',...
	evalFN ';'];
  end
else %Are using a .m file
  if opts(2)==1 %Float ga
    e1str=['[c1 c1(xZomeLength)]=' evalFN '(c1,[gen evalOps]);'];
    e2str=['[c2 c2(xZomeLength)]=' evalFN '(c2,[gen evalOps]);'];
  else %Binary ga
    e1str=['x=b2f(endPop(j,:),bounds,bits);[x v]=' evalFN ...
	'(x,[gen evalOps]); endPop(j,:)=[f2b(x,bounds,bits) v];'];
  end
end

if n<6 %Default termination information
  termOps=[100];
  termFN='maxGenTerm';
end
if n<12 %Default muatation information
  if opts(2)==1 %Float GA
  mutFNs=['boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation'];
    mutOps=[4 0 0;6 termOps(1) 3;4 termOps(1) 3;4 0 0];
  else %Binary GA
    mutFNs=['binaryMutation'];
    mutOps=[0.05];
  end
end
if n<10 %Default crossover information
  if opts(2)==1 %Float GA
    xOverFNs=['arithXover heuristicXover simpleXover'];
    xOverOps=[2 0;2 3;2 0];
  else %Binary GA
    xOverFNs=['simpleXover'];
    xOverOps=[0.6];
  end
end
if n<9 %Default select opts only i.e. roullete wheel.
  selectOps=[];
end
if n<8 %Default select info
  selectFN=['normGeomSelect'];
  selectOps=[0.08];
end
if n<6 %Default termination information
  termOps=[100];
  termFN='maxGenTerm';
end
if n<4 %No starting population passed given
  startPop=[];
end
if isempty(startPop) %Generate a population at random
  %startPop=zeros(80,size(bounds,1)+1);
  startPop=initializega(80,bounds,evalFN,evalOps,opts(1:2));
end

if opts(2)==0 %binary
  bits=calcbits(bounds,opts(1));
end

xOverFNs=parse(xOverFNs);
mutFNs=parse(mutFNs);

xZomeLength  = size(startPop,2); 	%Length of the xzome=numVars+fittness
numVar       = xZomeLength-1; 		%Number of variables
popSize      = size(startPop,1); 	%Number of individuals in the pop
endPop       = zeros(popSize,xZomeLength); %A secondary population matrix
c1           = zeros(1,xZomeLength); 	%An individual
c2           = zeros(1,xZomeLength); 	%An individual
numXOvers    = size(xOverFNs,1); 	%Number of Crossover operators
numMuts      = size(mutFNs,1); 		%Number of Mutation operators
epsilon      = opts(1);                 %Threshold for two fittness to differ
oval         = max(startPop(:,xZomeLength)); %Best value in start pop
bFoundIn     = 1; 			%Number of times best has changed
done         = 0;                       %Done with simulated evolution
gen          = 1; 			%Current Generation Number
collectTrace = (nargout>3); 		%Should we collect info every gen
floatGA      = opts(2)==1;              %Probabilistic application of ops
display      = opts(3);                 %Display progress

while(~done)
  %Elitist Model
  [bval,bindx] = max(startPop(:,xZomeLength)); %Best of current pop
  best =  startPop(bindx,:);

  if collectTrace
    traceInfo(gen,1)=gen; 		          %current generation
    traceInfo(gen,2)=startPop(bindx,xZomeLength);       %Best fittness
    traceInfo(gen,3)=mean(startPop(:,xZomeLength));     %Avg fittness
    traceInfo(gen,4)=std(startPop(:,xZomeLength));
  end

  if ( (abs(bval - oval)>epsilon) | (gen==1)) %If we have a new best sol
    if display
      fprintf(1,'\n%d %f\n',gen,bval);          %Update the display
    end
    if floatGA
      bPop(bFoundIn,:)=[gen startPop(bindx,:)]; %Update bPop Matrix
    else
      bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)...
	  startPop(bindx,xZomeLength)];
    end
    bFoundIn=bFoundIn+1;                      %Update number of changes
    oval=bval;                                %Update the best val
  else
    if display
      fprintf(1,'%d ',gen);	              %Otherwise just update num gen
    end
  end

  endPop = feval(selectFN,startPop,[gen selectOps]); %Select

  if floatGA %Running with the model where the parameters are numbers of ops
    for i=1:numXOvers,
      for j=1:xOverOps(i,1),
	a = round(rand*(popSize-1)+1); 	%Pick a parent
	b = round(rand*(popSize-1)+1); 	%Pick another parent
	xN=deblank(xOverFNs(i,:)); 	%Get the name of crossover function
	[c1 c2] = feval(xN,endPop(a,:),endPop(b,:),bounds,[gen xOverOps(i,:)]);

	if c1(1:numVar)==endPop(a,(1:numVar)) %Make sure we created a new
	  c1(xZomeLength)=endPop(a,xZomeLength); %solution before evaluating
	elseif c1(1:numVar)==endPop(b,(1:numVar))
	  c1(xZomeLength)=endPop(b,xZomeLength);
	else
	  %[c1(xZomeLength) c1] = feval(evalFN,c1,[gen evalOps]);
	  eval(e1str);
	end
	if c2(1:numVar)==endPop(a,(1:numVar))
	  c2(xZomeLength)=endPop(a,xZomeLength);
	elseif c2(1:numVar)==endPop(b,(1:numVar))
	  c2(xZomeLength)=endPop(b,xZomeLength);
	else
	  %[c2(xZomeLength) c2] = feval(evalFN,c2,[gen evalOps]);
	  eval(e2str);
	end

	endPop(a,:)=c1;
	endPop(b,:)=c2;
      end
    end

    for i=1:numMuts,
      for j=1:mutOps(i,1),
	a = round(rand*(popSize-1)+1);
	c1 = feval(deblank(mutFNs(i,:)),endPop(a,:),bounds,[gen mutOps(i,:)]);
	if c1(1:numVar)==endPop(a,(1:numVar))
	  c1(xZomeLength)=endPop(a,xZomeLength);
	else
	  %[c1(xZomeLength) c1] = feval(evalFN,c1,[gen evalOps]);
	  eval(e1str);
	end
	endPop(a,:)=c1;
      end
    end

  else %We are running a probabilistic model of genetic operators
    for i=1:numXOvers,
      xN=deblank(xOverFNs(i,:)); 	%Get the name of crossover function
      cp=find(rand(popSize,1)<xOverOps(i,1)==1);
      if rem(size(cp,1),2) cp=cp(1:(size(cp,1)-1)); end
      cp=reshape(cp,size(cp,1)/2,2);
      for j=1:size(cp,1)
	a=cp(j,1); b=cp(j,2);
	[endPop(a,:) endPop(b,:)] = feval(xN,endPop(a,:),endPop(b,:),...
	  bounds,[gen xOverOps(i,:)]);
      end
    end
    for i=1:numMuts
      mN=deblank(mutFNs(i,:));
      for j=1:popSize
	endPop(j,:) = feval(mN,endPop(j,:),bounds,[gen mutOps(i,:)]);
	eval(e1str);
      end
    end
  end

  gen=gen+1;
  done=feval(termFN,[gen termOps],bPop,endPop); %See if the ga is done
  startPop=endPop; 			%Swap the populations

  [bval,bindx] = min(startPop(:,xZomeLength)); %Keep the best solution
  startPop(bindx,:) = best; 		%replace it with the worst
end

[bval,bindx] = max(startPop(:,xZomeLength));
if display
  fprintf(1,'\n%d %f\n',gen,bval);
end

x=startPop(bindx,:);
if opts(2)==0 %binary
  x=b2f(x,bounds,bits);
  bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)...
      startPop(bindx,xZomeLength)];
else
  bPop(bFoundIn,:)=[gen startPop(bindx,:)];
end

if collectTrace
  traceInfo(gen,1)=gen; 		%current generation
  traceInfo(gen,2)=startPop(bindx,xZomeLength); %Best fittness
  traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %Avg fittness
end


function [ state ] = nonBlocking_movePTPHomeJointSpace( t , relVel)
%% This non-blocking function is used for performing point to point motion
%  in joint space to the home position of the robot, for the KUKA iiwa 7 R 800.

%% Syntax:
% [ state ] = movePTPHomeJointSpace( t , relVel)

%% About:
% This function is used to move the robot to home position, the motion is
% performed in joint space.

%% Arreguments:
% t: is the TCP/IP connection
% relVel: is a double, from zero to one, specifies the over-ride relative
% velocity.

% Copy right, Mohammad SAFEEA, 9th of May 2017

% check also the function: nonBlocking_isGoalReached()

    theCommand=['jRelVel_',num2str(relVel),'_']; % set over ride.
    fprintf(t, theCommand);
    message=fgets(t);

    jPos=[];
    for i=1:7
        jPos{i}=0;
    end

    global paramName;
    global paramVal;
    paramName='jpos';
    paramVal=jPos;

    sendJointsPositions( t ,jPos); % send destination joint positions.

    theCommand='doPTPinJS';
    fprintf(t, theCommand); % start the point to point motion.
    message=fgets(t);
    state=checkAcknowledgment(message);

end


classdef spinpreference
%SPINPREFERENCE   Abstract class for managing preferences for SPIN, SPIN2 and
%SPIN3.
%   SPINPREFERENCE is an abstract class for managing preferences when solving
%   a time-dependent PDE defined by a SPINOPERATOR. SPINPREF (for SPIN in 1D),
%   SPINPREF2 (for SPIN2 in 2D), SPINPREF3 (for SPIN3 in 3D) and SPINPREFSPHERE
%   (for SPINSPHERE on the sphere) are full implementations.
%
% See also SPINPREF, SPINPREF2, SPINPREF3, SPINPREFSPHERE.

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

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CLASS PROPERTIES:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    properties ( Access = public )
        dataplot             % Which data to plot when complex values (STRING)
        dealias              % To use dealiasing with 2/3-rule (STRING)
        iterplot             % Plot every ITERPLOT iterations (1x1 INT)
        Nplot                % Number of points for movie grid (1x1 INT)
        plot                 % Plot options (STRING)
        scheme               % Time-stepping scheme (STRING)
    end

end


function [cMap]=iwarmcold(varargin)

% function [cMap]=iwarmcold(n)
% ------------------------------------------------------------------------
% Creates the colormap data for n levels for the  inverse warm-cold
% colormap.
%
% Kevin Mattheus Moerman
% gibbon.toolbox@gmail.com
%
% 2018/03/21
%------------------------------------------------------------------------

switch nargin
    case 0
        n=250;
    case 1
        n=varargin{1};
end

cf=[213 15  37; 238 178 17;]./255;
c=rot90(cf,2);
h=cf;

h=resampleColormap(h,3);
c=resampleColormap(c,3);

cMap=[c; [0 0 0]; h];

[cMap]=resampleColormap(cMap,n);

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


function uudecode = i4_to_uudecode ( i )

%*****************************************************************************80
%
%% I4_TO_UUDECODE returns the I-th character in the UUDECODE encoding.
%
%  Example:
%
%    I  UUDECODE
%
%    1  '`'
%    2  '!'
%    3  '"'
%   ..
%   64  '_'
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 March 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer I, the index of the character.
%    1 <= I <= 64.
%
%    Output, character UUDECODE, the requested character.
%
  s = '`!"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_';

  if ( 1 <= i && i <= 64 )
    uudecode = s(i);
  else
    uudecode = ' ';
  end

  return
end


function value = ch_roman_to_i4 ( c )

%*****************************************************************************80
%
%% CH_ROMAN_TO_I4 returns the integer value of a single digit of a Roman numeral.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, character C, a Roman numeral.
%
%    Output, integer VALUE, the value of the Roman numeral.
%    If the Roman numeral was not recognized, 0 is returned.
%
  if ( s_eqi ( c, 'M' ) )
    value = 1000;
  elseif ( s_eqi ( c, 'D' ) )
    value = 500;
  elseif ( s_eqi ( c, 'C' ) )
    value = 100;
  elseif ( s_eqi ( c, 'L' ) )
    value = 50;
  elseif ( s_eqi ( c, 'X' ) )
    value = 10;
  elseif ( s_eqi ( c, 'V' ) )
    value = 5;
  elseif ( s_eqi ( c, 'I' ) || s_eqi ( c, 'J' ) )
    value = 1;
  else
    value = 0;
  end

  return
end


function y=fdb(x,a,b)
if x>b
    y=1;
elseif x<a
    y=-1;
elseif x=b
    y=1/2;
elseif x=a
    y=-1/2;
end


function [idxStart, idxEnd] = find_ts_idx(ts, tStart, tEnd)
    % find indices for starting and ending time points
    if(tStart > ts.Time(end))
      warning(['Start time is greater than last point in time for timeseries: ' ts.Name]);
      idxStart = -1;
      idxEnd = -1;
      return;
    else
      idxStart = find(ts.Time >= tStart, 1);
    end
    if(tEnd < ts.Time(1))
      warning(['End time is smaller than first point in time for timeseries: ' ts.Name]);
      idxStart = -1;
      idxEnd = -1;
    else
      idxEnd = find(ts.Time <= tEnd, 1, 'last');
    end
    if(tStart >= tEnd)
      warning(['Start time is larger than end time']);
      idxStart = -1;
      idxEnd = -1;
    end
end


function polygons = splitPolygons(polygon)
%SPLITPOLYGONS Convert a NaN separated polygon list to a cell array of polygons.
%
%   POLYGONS = splitPolygons(POLYGON);
%   POLYGON is a N-by-2 array of points, possibly with pairs of NaN values.
%   The functions separates each component separated by NaN values, and
%   returns a cell array of polygons.
%
%   See also:
%   polygons2d
%

% ------
% Author: David Legland
% e-mail: david.legland@inra.fr
% Created: 2007-10-12,    using Matlab 7.4.0.287 (R2007a)
% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.

if iscell(polygon)
    % case of a cell array
    polygons = polygon;

elseif sum(isnan(polygon(:))) == 0
    % single polygon -> no break
    polygons = {polygon};

else
    % find indices of NaN couples
    inds = find(sum(isnan(polygon), 2) > 0);

    % number of polygons
    N = length(inds) + 1;
    polygons = cell(N, 1);

    % iterate over NaN-separated regions to create new polygon
    inds = [0; inds; size(polygon, 1)+1];
    for i = 1:N
        polygons{i} = polygon((inds(i)+1):(inds(i+1)-1), :);
    end
end


function s = ymdf_to_s_islamic ( y, m, d, f )

%*****************************************************************************80
%
%% YMDF_TO_S_ISLAMIC writes an Islamic YMDF date into a string.
%
%  Format:
%
%    AH YYYY/MM/DD.FF
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 March 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, M, D, real F, the YMDF date.
%
%    Output, string S, a representation of the date.
%
  s = sprintf ( 'AH %d/%02d/%05.2f', y, m, d + f );

  return
end


function m = p06_m ( )

%*****************************************************************************80
%
%% P06_M returns the number of equations M for problem 6.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 April 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer M, the number of equations.
%
  m = 10;

  return
end


function x = p15_start ( option, nvar )

%*****************************************************************************80
%
%% P15_START returns a starting point for problem 15.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer OPTION, the option index.
%
%    Input, integer NVAR, the number of variables.
%
%    Output, real X(NVAR), the starting point.
%
  x = zeros ( nvar, 1 );

  return
end


function r8mat_write ( output_filename, m, n, table )

%*****************************************************************************80
%
%% R8MAT_WRITE writes an R8MAT file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 August 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string OUTPUT_FILENAME, the output filename.
%
%    Input, integer M, the spatial dimension.
%
%    Input, integer N, the number of points.
%
%    Input, real TABLE(M,N), the points.
%

%
%  Open the file.
%
  output_unit = fopen ( output_filename, 'wt' );

  if ( output_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8MAT_WRITE - Error!\n' );
    fprintf ( 1, '  Could not open the output file.\n' );
    error ( 'R8MAT_WRITE - Error!' );
    return;
  end
%
%  Write the data.
%
  for j = 1 : n
    for i = 1 : m
      fprintf ( output_unit, '  %24.16f', table(i,j) );
    end
    fprintf ( output_unit, '\n' );
  end
%
%  Close the file.
%
  fclose ( output_unit );

  return
end


function [ a, b ] = p49_lim ( )

%*****************************************************************************80
%
%% P49_LIM returns the integration limits for problem 49.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real A, B, the limits of integration.
%
  a = 0.0;
  b = 3.0;

  return
end


function [ t_stop, y_stop ] = p38_stop ( neqn )

%*****************************************************************************80
%
%% P38_STOP returns the stopping point for problem p38.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NEQN, the number of equations.
%
%    Output, real T_STOP, Y_STOP(NEQN), the final data.
%
  delta = p38_param ( 'GET', 'DELTA' );
  t_stop = 2.0 / delta;
  y_stop = zeros ( neqn, 1 );
  y_stop(1) = 1.0;

  return
end


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

%% -*- texinfo -*-
%% @defun valid_sym_assumptions ()
%% Return list of valid assumptions.
%%
%% @end defun

%% Reference: http://docs.sympy.org/dev/modules/core.html

%% FIXME: Maybe in the future remove this file and replace with something else.

function L = valid_sym_assumptions()

  persistent List

  if (isempty(List))

    cmd = {'from sympy.core.assumptions import _assume_defined'
           'return list(_assume_defined),'};
    List = pycall_sympy__ (cmd);

  end

  L = List;

end


function [stop, reason] = stoppingcriterion(problem, x, options, info, last)
% Checks for standard stopping criteria, as a helper to solvers.
%
% function [stop, reason] = stoppingcriterion(problem, x, options, info, last)
%
% Executes standard stopping criterion checks, based on what is defined in
% the info(last) stats structure and in the options structure.
%
% The returned number 'stop' is 0 if none of the stopping criteria
% triggered, and a (strictly) positive integer otherwise. The integer
% identifies which criterion triggered:
%  0 : Nothing triggered;
%  1 : Cost tolerance reached;
%  2 : Gradient norm tolerance reached;
%  3 : Max time exceeded;
%  4 : Max iteration count reached;
%  5 : Maximum number of cost evaluations reached;
%  6 : User defined stopfun criterion triggered.
%
% The output 'reason' is a string describing the triggered event.

% This file is part of Manopt: www.manopt.org.
% Original author: Nicolas Boumal, Dec. 30, 2012.
% Contributors:
% Change log:
%
%   April 2, 2015 (NB):
%       'reason' now contains the option (name and value) that triggered.

    stop = 0;
    reason = '';

    stats = info(last);

    % Target cost attained
    if isfield(stats, 'cost') && isfield(options, 'tolcost') && ...
       stats.cost <= options.tolcost
        reason = sprintf('Cost tolerance reached; options.tolcost = %g.', options.tolcost);
        stop = 1;
        return;
    end

    % Target gradient norm attained
    if isfield(stats, 'gradnorm') && isfield(options, 'tolgradnorm') && ...
       stats.gradnorm < options.tolgradnorm
        reason = sprintf('Gradient norm tolerance reached; options.tolgradnorm = %g.', options.tolgradnorm);
        stop = 2;
        return;
    end

    % Allotted time exceeded
    if isfield(stats, 'time') && isfield(options, 'maxtime') && ...
       stats.time >= options.maxtime
        reason = sprintf('Max time exceeded; options.maxtime = %g.', options.maxtime);
        stop = 3;
        return;
    end

    % Allotted iteration count exceeded
    if isfield(stats, 'iter') && isfield(options, 'maxiter') && ...
       stats.iter >= options.maxiter
        reason = sprintf('Max iteration count reached; options.maxiter = %g.', options.maxiter);
        stop = 4;
        return;
    end

    % Allotted function evaluation count exceeded
    if isfield(stats, 'costevals') && isfield(options, 'maxcostevals') && ...
       stats.costevals >= options.maxcostevals
        reason = sprintf('Maximum number of cost evaluations reached; options.maxcostevals = %g.', options.maxcostevals);
        stop = 5;
    end

    % Check whether the possibly user defined stopping criterion
    % triggers or not.
    if isfield(options, 'stopfun')
        userstop = options.stopfun(problem, x, info, last);
        if userstop
            reason = 'User defined stopfun criterion triggered; see options.stopfun.';
            stop = 6;
            return;
        end
    end

end


function y = isfinite(x)
    %ISFINITE True for finite elements of symbolic arrays.
    %   ISFINITE(X) returns an array that contains 1's where
    %   the elements of X are finite and 0's where they are not.
    %   For example, isfinite(sym([pi NaN Inf -Inf])) is [1 0 0 0].
    %
    %   For any X, exactly one of ISFINITE(X), ISINF(X), or ISNAN(X)
    %   is 1 for each element.
    %
    %   See also SYM/ISINF, SYM/ISNAN.

    y = ~isinf(x) & ~isnan(x);
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D
% shape modeling and analysis toolkit.
% It is a software package developed at Shenlab in Center for Neuroimaging,
% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)
% It is available to the scientific community as copyright freeware
% under the terms of the GNU General Public Licence.
%
% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University
%
% This file is part of SPHARM-MAT.
%
% SPHARM-MAT is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SPHARM-MAT is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SPHARM-MAT. If not, see <http://www.gnu.org/licenses/>.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

disp('Ex0201: Perform SPHARM-PDM topology fix')

SpharmMatDir = '../';
if ~ispc
    curP = pwd;
    cd(SpharmMatDir);
    SpharmMatDir = [pwd '/'];
    cd(curP);
end
CodeDir = [SpharmMatDir 'code'];
if exist([CodeDir '/sysConfig.mat'])
    load([CodeDir '/sysConfig.mat']);
else
    disp('PDM_path variable (sysConfig.mat) does not exist in SPHARM-MAT directory.')
    disp('Please set the path to SHARM-PDM for SPHARM-MAT and use this script.');
    return;
end
addpath(CodeDir);

DataFolder = 'data';

%% (1) Input data directory
InDataDir = [SpharmMatDir DataFolder '/Ex0202/hip01_bim'];

%% (2) List input file names
inFiles = dir([InDataDir '/*.mat']); inNames={};
for i=1:length(inFiles)
    inNames{end+1} = [InDataDir '/' inFiles(i).name];
end

%% (3) Display input objects (optional)
    %Available values for Space- 'object';'param';'both'
dispConfs.Space = 'object';
    % Available values for Mesh- 'orig';'quad32';'quad64';'quad128';'quad256';'quad512';'icosa1';'icosa2'; ...
    %    'icosa3';'icosa4';'icosa5';'icosa6'
dispConfs.Mesh = 'orig';
    % Available values for Shape- 'solid';'mesh';'both'
dispConfs.Shade = 'mesh';
    % Available values for Overlay- 'none';'adc_paramap'
dispConfs.Overlay = 'none';
    % Available values for Export- 'screen';'png';'both'
dispConfs.Export = 'png';
dispConfs.Degree = [];
dispConfs.Template = '';

SpharmMatUtilDisplayObjs(dispConfs, inNames, CodeDir);

%% (4) Format Conversion bim2gipl
confs.OutDirectory = [SpharmMatDir DataFolder '/Ex0202/hip02_gipl'];

if ~exist(confs.OutDirectory,'dir')
    mkdir(confs.OutDirectory);
end

SpharmMatUtilFormatConvert(confs, inNames, 'bim2gipl');

%% (5) Perform SPHRM-PDM topology fix
inFiles = dir([confs.OutDirectory '/*.gipl']); inNames={};
for i=1:length(inFiles)
    inNames{end+1} = [confs.OutDirectory '/' inFiles(i).name];
end

PDM_Fix.command = 'SegPostProcess';
if ispc
    PDM_path = PDM_path_pc;
elseif isunix
    PDM_path = PDM_path_unix;
end

com = [PDM_path '/' PDM_Fix.command];
PDM_Fix.exist = 0;
if ispc
    if exist([com '.exe'],'file')
        PDM_Fix.exist = 1;
    end
else
    if exist(com, 'file')
        PDM_Fix.exist = 1;
    end
end

confs.vars = {'space','OutDirectory', 'others'};
confs.args = [3 200 20];
confs.space = [0.75,0.75,0.75];
confs.OutDirectory = [SpharmMatDir DataFolder '/Ex0202/hip03_gipl_fix'];
confs.others = '';
confs.command = PDM_Fix.command;
confs.path = PDM_path;

if ~exist(confs.OutDirectory,'dir')
    mkdir(confs.OutDirectory);
end

if (PDM_Fix.exist == 0)
    errordlg(sprintf('%s function does not exist in the PDM directory, %s',PDM_Fix.command,PDM_path));
    rmpath(Codedir);
    return;
else
    outNames = SpharmMatUtilTopologyFix(confs, inNames, 'PDM_Fix');
end

%% (6) Format Conversion gipl2bim

confs.OutDirectory = [SpharmMatDir DataFolder '/Ex0202/hip04_fix'];

if ~exist(confs.OutDirectory,'dir')
    mkdir(confs.OutDirectory);
end

SpharmMatUtilFormatConvert(confs, outNames, 'gipl2bim');

%% (7) Display output objects (optional)
inFiles = dir([confs.OutDirectory '/*.mat']); inNames={};
for i=1:length(inFiles)
    inNames{end+1} = [confs.OutDirectory '/' inFiles(i).name];
end

    %Available values for Space- 'object';'param';'both'
dispConfs.Space = 'object';
    % Available values for Mesh- 'orig';'quad32';'quad64';'quad128';'quad256';'quad512';'icosa1';'icosa2'; ...
    %    'icosa3';'icosa4';'icosa5';'icosa6'
dispConfs.Mesh = 'orig';
    % Available values for Shape- 'solid';'mesh';'both'
dispConfs.Shade = 'mesh';
    % Available values for Overlay- 'none';'adc_paramap'
dispConfs.Overlay = 'none';
    % Available values for Export- 'screen';'png';'both'
dispConfs.Export = 'png';
dispConfs.Degree = [];
dispConfs.Template = '';

SpharmMatUtilDisplayObjs(dispConfs, inNames, CodeDir);

rmpath(CodeDir);

clear;


function root_num = p03_root_num ( )

%*****************************************************************************80
%
%% P03_ROOT_NUM returns the number of known roots for problem 3.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 May 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer ROOT_NUM, the number of known roots.
%
  root_num = 1;

  return
end


function [params, names] = mixturePriorExtractParam(prior)

% MIXTUREPRIOREXTRACTPARAM Extract params from mixture prior structure.

% COPYRIGHT : Antti Honkela, 2013

% SHEFFIELDML

params = zeros(1, prior.nParams);
if nargout > 1
  names = cell(1, prior.nParams);
end

begindex = 1;
for k=1:length(prior.comp),
  myindex = begindex:(begindex+prior.comp{k}.nParams-1);
  if nargout > 1,
    [params(myindex), names(myindex)] = priorExtractParam(prior.comp{k});
  else
    params(myindex) = priorExtractParam(prior.comp{k});
  end
  begindex = begindex + prior.comp{k}.nParams;
end


function plotlowerbound(lb,peval,savethis, xlow)
% plotlowerbound(lb,peval,savethis, xlow)
% xlow : (optional) lower bound on x axes (not to show first few pointss in
% lb...)
if ~exist('xlow', 'var') xlow = 1; end

figure
plot(lb(xlow:end))
xlabel('iteration');
ylabel('lower bound');
grid on
setfontsizefigure(12)
if savethis
    SaveImageFULL([peval.res_dir '/lowerbound'])
end


function m = cell2mat(c)
%CELL2MAT Convert the contents of a cell array into a single matrix.
%   M = CELL2MAT(C) converts a multidimensional cell array with contents of
%   the same data type into a single matrix. The contents of C must be able
%   to concatenate into a hyperrectangle. Moreover, for each pair of
%   neighboring cells, the dimensions of the cell's contents must match,
%   excluding the dimension in which the cells are neighbors. This constraint
%   must hold true for neighboring cells along all of the cell array's
%   dimensions.
%
%   The dimensionality of M, i.e. the number of dimensions of M, will match
%   the highest dimensionality contained in the cell array.
%
%   CELL2MAT is not supported for cell arrays containing cell arrays or
%   objects.
%
%	Example:
%	   C = {[1] [2 3 4]; [5; 9] [6 7 8; 10 11 12]};
%	   M = cell2mat(C)
%
%	See also MAT2CELL, NUM2CELL

% Copyright 1984-2006 The MathWorks, Inc.
% $Revision: 1.10.4.7 $  $Date: 2006/11/11 22:43:58 $

% Error out if there is no input argument
if nargin==0
    error('MATLAB:cell2mat:NoInputs',['No input argument specified. ' ...
        'There should be exactly one input argument.'])
end
% short circuit for simplest case
elements = numel(c);
if elements == 0
    m = [];
    return
end
if elements == 1
    if isnumeric(c{1}) || ischar(c{1}) || islogical(c{1}) || isstruct(c{1})
        m = c{1};
        return
    end
end
% Error out if cell array contains mixed data types
cellclass = class(c{1});
ciscellclass = cellfun('isclass',c,cellclass);
if ~all(ciscellclass(:))
    error('MATLAB:cell2mat:MixedDataTypes', ...
        'All contents of the input cell array must be of the same data type.');
end

% Error out if cell array contains any cell arrays or objects
ciscell = iscell(c{1});
cisobj = isobject(c{1});
if cisobj || ciscell
    error('MATLAB:cell2mat:UnsupportedCellContent',['Cannot support cell ' ...
        'arrays containing cell arrays or objects.']);
end

% If cell array of structures, make sure the field names are all the same
if isstruct(c{1})
    cfields = cell(elements,1);
    for n=1:elements
        cfields{n} = fieldnames(c{n});
    end
    % Perform the actual field name equality test
    if ~isequal(cfields{:})
        error('MATLAB:cell2mat:InconsistentFieldNames', ...
            ['The field names of each cell array element must be consistent ' ...
            'and in consistent order.'])
    end
end

% If cell array is 2-D, execute 2-D code for speed efficiency
if ndims(c) == 2
    rows = size(c,1);
    cols = size(c,2);
    if (rows < cols)
        m = cell(rows,1);
        % Concatenate one dim first
        for n=1:rows
            m{n} = cat(2,c{n,:});
        end
        % Now concatenate the single column of cells into a matrix
        m = cat(1,m{:});
    else
        m = cell(1, cols);
        % Concatenate one dim first
        for n=1:cols
            m{n} = cat(1,c{:,n});
        end
        % Now concatenate the single column of cells into a matrix
        m = cat(2,m{:});
    end
    return
end

csize = size(c);
% Treat 3+ dimension arrays

% Construct the matrix by concatenating each dimension of the cell array into
%   a temporary cell array, CT
% The exterior loop iterates one time less than the number of dimensions,
%   and the final dimension (dimension 1) concatenation occurs after the loops

% Loop through the cell array dimensions in reverse order to perform the
%   sequential concatenations
for cdim=(length(csize)-1):-1:1
    % Pre-calculated outside the next loop for efficiency
    ct = cell([csize(1:cdim) 1]);
    cts = size(ct);
    ctsl = length(cts);
    mref = {};

    % Concatenate the dimension, (CDIM+1), at each element in the temporary cell
    %   array, CT
    for mind=1:prod(cts)
        [mref{1:ctsl}] = ind2sub(cts,mind);
        % Treat a size [N 1] array as size [N], since this is how the indices
        %   are found to calculate CT
        if ctsl==2 && cts(2)==1
            mref = {mref{1}};
        end
        % Perform the concatenation along the (CDIM+1) dimension
        ct{mref{:}} = cat(cdim+1,c{mref{:},:});
    end
    % Replace M with the new temporarily concatenated cell array, CT
    c = ct;
end

% Finally, concatenate the final rows of cells into a matrix
m = cat(1,c{:});


classdef spinprefsphere < spinpreference
%SPINPRESPHERE   Class for managing preferences when solving a PDE on the
%sphere with SPINSPHERE.
%
% Available preferences ([] = defaults):
%
%   Clim                      * Limits of the colorbar when 'plot' is 'movie'.
%     []                        Default is empty, i.e., automatically chosen by
%                               the code.
%
%   colormap                  * Color look-up table. See HELP/COLORMAP.
%     ['parula']
%
%   dataplot                  * Plotting options when the solution is complex.
%     ['real']
%      'imag'
%      'abs'
%
%   dealias                   * If 'on', uses the 2/3-rule to zero out high
%     ['off']                   wavenumbers.
%      'on'
%
%   grid                      * If 'on', plots longitude and latitude circles.
%     ['off']
%      'on'
%
%   iterplot                  * Plots the solution every ITERPLOT iterations of
%     [1]                       the time-stepping loop if 'plot' is 'movie'.
%
%
%   Nplot                     * Number of grid points in each direction for
%     [256]                     the movie. If Nplot>N, the data are interpolated
%                               to a finer grid.
%
%   plot                      * Plot options: 'movie' to plot a movie of the
%     ['movie']                 the solution, 'off' otherwise.
%      'off'
%
%   scheme                    * Time-stepping scheme. HELP/IMEX for the list
%     []                        of available schemes. Default is empty, i.e.,
%                               automatically chosen by the code depending on
%                               the PDE.
%
%   view                      * Viewpoint specification when 'plot' is 'movie'.
%     [-37.5 30]
%
% Construction:
%
%   PREF = SPINPREFSPHERE() creates a SPINPREF2 object with the default values.
%
%   PREF = SPINPREFSPHERE(PROP1, VALUE1, PROP2, VALUE2, ...) creates a
%   SPINPREFSPHERE object with the properties PROP1 and PROP2 set to VALUE1 and
%   VALUE2.
%
% See also SPINSPHERE.

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

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CLASS PROPERTIES:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    properties ( Access = public )
        Clim                  % Limits of the colorbar (1x2*NVARS DOUBLE)
        colormap              % Color look-up table (STRING)
        grid                  % For longitude and latitude circles (STRING)
        view = [-37.5 30];    % Viewpoint of the plot (1x2 DOUBLE)
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CLASS CONSTRUCTOR:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods ( Access = public, Static = false )

        function pref = spinprefsphere(varargin)
            if ( nargin == 0 )
                pref.colormap = 'parula';
                pref.grid = 'off';
                pref.dataplot = 'real';
                pref.dealias = 'off';
                pref.iterplot = 1;
                pref.Nplot = 128;
                pref.plot = 'movie';
            else
                pref = spinprefsphere();
                for k = 1:nargin/2
                    pref.(varargin{2*(k-1)+1}) = varargin{2*k};
                end
            end
        end
    end

end


function [molStr,molTable] = getMolFormula(model,metabolite)
% getMolFormula takes a metabolite in a specified model and returns the
% molecular formula.

% USAGE:
%
%    [molStr,molTable] = getMolFormula(model,'glu[c]')
%
% INPUTS:
%    model:          COBRA model structure with minimal fields:
%                      * .mets
%                      * .metFormulas
%   metabolite:       a specified metabolite with in the model
%
% OUTPUT:
%   molStr:  the molecular formula for the specified metabolite
%
%   molTable: A cellular array containing the breakdown of the metabolite
%             by element
%
% .. Authors: - Bronson R. Weston   2022

%Get the molStr from metFormulas
ind=find(strcmp(model.mets,metabolite));
if isempty(ind)
    error('Invalid input metabolite!')
end

try
    molStr=model.metFormulas{ind};
catch
    error('A "metFormulas" field is necessary in the input model to use getMolFormula.')
end

%Keep track of each element in the molStr
uC=isstrprop(molStr,'upper');
tracker={};
ind=0;
for i=1:length(uC)
    if uC(i)==1
        ind=ind+1;
        tracker{ind}=molStr(i);

    else
        tracker{ind}=[tracker{ind},molStr(i)];
    end
end

%Create the molTable
molTable={};
for i=1:length(tracker)
    unit=tracker{i};
    num=isstrprop(unit,'digit');
    if ~any(num==1)
        molTable(i,:)={tracker{i} , 1};
    else
        molTable{i,1}=unit(num~=1);
        molTable{i,2}=str2num(unit(num==1));
    end
end
end


%stepx   outlines step domain
%   IFISS scriptfile: DJS; 28 February 2005.
% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage
if exist('x','var')==0,
   error('You need to set up a step-shaped domain first!'),
end
varsteplen = max(x);
hold on
plot([-1,0],[0,0],'-k');
plot([0,0],[0,-1],'-k');
plot([0,varsteplen],[-1,-1],'-k');
plot([varsteplen,varsteplen],[-1,1],'-k');
plot([varsteplen,-1],[1,1],'-k');
plot([-1,-1],[1,0],'-k');
hold off


%kvnthin 'N-1 compositions of Thinnings'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros vnthin.pane file
%
% Parameters:
% InputFile: i 'Input Image ', required: 'input image'
% InputFile: str1 'Struct Element 1', required: 'Structuring Element'
% InputFile: str2 'Struct Element 2', required: 'Structuring Element'
% Integer: n 'Number of Thinnings', default: 5: 'number of thinnings'
% MultiChoice: r 'Struct El. Rotation Step', default: 1: 'Rotation step'
%    Choices are:
%   1: '1 '
%   2: '2 '
%   3: '4 '
% OutputFile: o 'Output Image ', required: 'resulting output image'
%
% Example: o = kvnthin({i, str1, str2}, {'i','';'str1','';'str2','';'n',5;'r',1;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% vnthin - N-1 compositions of Thinnings
%
%  DESCRIPTION
% .I vnthin
% will do N successive thinnings of an image.
%
% The output image data type will be the same as that of the highest data type
% of the input image.
%
% Some useful pairs of structuring elements:
%
%                         0 0 0    1 1 1
%   Homotopic Skeleton    0 1 0    0 0 0
%                         1 1 1    0 0 0
%
%                         0 0 0    1 0 0
%   Homotopic Marking     0 1 1    1 0 0
%                         0 0 0    1 0 0
%
%                         0 0 0    0 0 0
%   Skeleton Pruning      0 1 0    1 0 1
%                         0 0 0    1 1 1
%
%                         1 1 1    0 0 0
%   Boundary              1 1 1    0 0 0
%                         1 1 1    0 0 0
%
%
%
%  EXAMPLES
% vnthin -i feath.xv -str1 b1.str -str2 b2.str -n 5 -r 1 -o outimage.xv
%
% Will do 5 successive thinnings (vnthin) of the input image "feath.xv" by the structuring element b1.str and b2.str, rotating the struct. els. 1 step after each thinning. The resulting image will be written to  "outimage.xv".
%
%  "SEE ALSO"
% vcast1(1)
%
%  RESTRICTIONS
% .I vnthin
% can be defined for all data types supported by Khoros, but at the moment it has been implemented just for the bit and unsigned char types.
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993-1997 Junior Barrera, Roberto Lotufo.  All rights reserved.
%

function varargout = kvnthin(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kvnthin(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'str1', '__input';'str2', '__input';'n', 5;'r', 1;'o', '__output'};
maxval={0,0,0,2,0,0};
minval={0,0,0,2,0,0};
istoggle=[0,0,0,0,0,0];
was_set=istoggle * 0;
paramtype={'InputFile','InputFile','InputFile','Integer','MultiChoice','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 'vnthin"  '],Inputs,narglist);


function wavelet_test ( )

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

  wavelet_test01 ( );
  wavelet_test02 ( );
  wavelet_test03 ( );
  wavelet_test04 ( );
  wavelet_test05 ( );
  wavelet_test06 ( );
  wavelet_test07 ( );
  wavelet_test08 ( );
  wavelet_test09 ( );

  wavelet_test10 ( );
  wavelet_test11 ( );
  wavelet_test12 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'WAVELET_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


% This file is part of the project NILM-Eval (https://github.com/beckel/nilm-eval).
% Licence: GPL 2.0 (http://www.gnu.org/licenses/gpl-2.0.html)
% Copyright: ETH Zurich, 2014
% Author: Romano Cicchetti

function [phase] = getPhase(household, applianceID, dataset)

    % returns the phase of the specified (house, appliance)-pair

    phase_matrix = getPhaseMatrix(dataset);
    phase = phase_matrix(applianceID, household);

end


function calpak_test616 ( )

%*****************************************************************************80
%
%% CALPAK_TEST616 tests YEAR_LENGTH_ROMAN.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 April 2013
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALPAK_TEST616\n' );
  fprintf ( 1, '  For the Roman calendar:\n' );
  fprintf ( 1, '  YEAR_LENGTH_ROMAN determines the length of a year.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Year  Length\n' );
  fprintf ( 1, '\n' );

  for y = 96 : 100
    sy = y_to_s_roman ( y );
    fprintf ( 1, '  %10s  %3d\n', sy, year_length_roman ( y ) );
  end

  return
end


classdef jsonParseTest < TestCase
    methods
        function this = jsonParseTest(name)
            this = this@TestCase(name);
        end

        function testChar(~)
            assertEqual('', parse('""'));
            assertEqual('a', parse('"a"'));
            assertEqual(sprintf('-\t-\n'), parse('"-\t-\n"'));
            assertEqual('-\t-\n', parse('"-\\t-\\n"'));
            assertEqual(reshape('',[0 1]), parse('[[0,1],""]'));
            assertEqual(reshape('',[3 1 0]), parse('[[3,1,0],""]'));
            assertEqual(['a1';'b2'], parse('[[2,2],"ab12"]'));
        end

        function testLogical(~)
            assertEqual(true, parse('true'));
            assertEqual(false, parse('false'));
            assertEqual(logical.empty, parse('[true,[0,0]]'));
            assertEqual(true(3,1,0), parse('[true,[3,1,0]]'));
            assertEqual(logical([1 0; 1 0]), parse('[true,[2,2],1,1,0,0]'));
        end

        function testDouble(~)
            assertEqual(0, parse('0.0'));
            assertEqual(1, parse('1.0'));
            assertEqual(pi, parse('3.141592653589793'));
            assertEqual(double.empty, parse('[]'));
            assertEqual([3 1 0], parse('[3.0,1.0,0.0]'));
            assertEqual(ones(3,1,0), parse('[[3,1,0]]'));
            assertEqual([-1 -realmax; 0 realmax],...
                parse('[[2,2],-1.0,0.0,-1.7976931348623157E308,1.7976931348623157E308]'));
            assertExceptionThrown(@() parse('NaN'), 'jsonParse:InvalidJSON');
            assertExceptionThrown(@() parse('[[2,2],0,0,NaN,0]'),...
                'jsonParse:InvalidJSON');
        end

        function testSingle(~)
            assertEqual(single(0), parse('[1,[1,1],0.0]'));
            assertEqual(single(pi), parse('[1,[1,1],3.1415927]'));
            assertEqual(single.empty, parse('[1,[0,0]]'));
            assertEqual(ones(3,1,0,'single'), parse('[1,[3,1,0]]'));
            assertEqual(single([-1 -realmax('single'); 0 realmax('single')]),...
                parse('[1,[2,2],-1.0,0.0,-3.4028235E38,3.4028235E38]'));
            assertExceptionThrown(@() parse('[1,[2,2],0,0,NaN,0]'),...
                'jsonParse:InvalidJSON');
        end

        function testInt8(~)
            assertEqual(intmin('int8'), parse('[7,[1,1],-128]'));
            assertEqual(intmax('int8'), parse('[7,[1,1],127]'));
            assertEqual(int8.empty, parse('[7,[0,0]]'));
            assertEqual(ones(3,1,0,'int8'), parse('[7,[3,1,0]]'));
            assertEqual(int8([2 23; -123 0]), parse('[7,[2,2],2,-123,23,0]'));
        end

        function testInt16(~)
            assertEqual(intmin('int16'), parse('[15,[1,1],-32768]'));
            assertEqual(intmax('int16'), parse('[15,[1,1],32767]'));
            assertEqual(int16.empty, parse('[15,[0,0]]'));
            assertEqual(zeros(3,1,0,'int16'), parse('[15,[3,1,0]]'));
            assertEqual(int16([2 23; -234 0]), parse('[15,[2,2],2,-234,23,0]'));
        end

        function testInt32(~)
            assertEqual(intmin('int32'), parse('[31,[1,1],-2147483648]'));
            assertEqual(intmax('int32'), parse('[31,[1,1],2147483647]'));
            assertEqual(int32.empty, parse('[31,[0,0]]'));
            assertEqual(zeros(3,1,0,'int32'), parse('[31,[3,1,0]]'));
            assertEqual(int32([2 23; -234 0]), parse('[31,[2,2],2,-234,23,0]'));
        end

        function testInt64(~)
            assertEqual(intmin('int64'), parse('[63,[1,1],-9223372036854775808]'));
            assertEqual(intmax('int64'), parse('[63,[1,1],9223372036854775807]'));
            assertEqual(int64.empty, parse('[63,[0,0]]'));
            assertEqual(zeros(3,1,0,'int64'), parse('[63,[3,1,0]]'));
            assertEqual(int64([2 23; -234 0]), parse('[63,[2,2],2,-234,23,0]'));
        end

        function testUint8(~)
            assertEqual(intmin('uint8'), parse('[8,[1,1],0]'));
            assertEqual(intmax('uint8'), parse('[8,[1,1],255]'));
            assertEqual(uint8.empty, parse('[8,[0,0]]'));
            assertEqual(zeros(3,1,0,'uint8'), parse('[8,[3,1,0]]'));
            assertEqual(uint8([2 23; 234 0]), parse('[8,[2,2],2,234,23,0]'));
        end

        function testUint16(~)
            assertEqual(intmin('uint16'), parse('[16,[1,1],0]'));
            assertEqual(intmax('uint16'), parse('[16,[1,1],65535]'));
            assertEqual(uint16.empty, parse('[16,[0,0]]'));
            assertEqual(zeros(3,1,0,'uint16'), parse('[16,[3,1,0]]'));
            assertEqual(uint16([2 23; 234 0]), parse('[16,[2,2],2,234,23,0]'));
        end

        function testUint32(~)
            assertEqual(intmin('uint32'), parse('[32,[1,1],0]'));
            assertEqual(intmax('uint32'), parse('[32,[1,1],4294967295]'));
            assertEqual(uint32.empty, parse('[32,[0,0]]'));
            assertEqual(zeros(3,1,0,'uint32'), parse('[32,[3,1,0]]'));
            assertEqual(uint32([2 23; 234 0]), parse('[32,[2,2],2,234,23,0]'));
        end

        function testUint64(~)
            assertEqual(intmin('uint64'), parse('[64,[1,1],0]'));
            assertEqual(intmax('uint64'), parse('[64,[1,1],18446744073709551615]'));
            assertEqual(uint64.empty, parse('[64,[0,0]]'));
            assertEqual(zeros(3,1,0,'uint64'), parse('[64,[3,1,0]]'));
            assertEqual(uint64([2 23; 234 0]), parse('[64,[2,2],2,234,23,0]'));
        end

        function testCellArray(~)
            assertEqual(cell.empty, parse('[[]]'));
            assertEqual(reshape({'jared',0;'jacobs',1}, [2 1 2]),...
                parse('[[2,1,2],["jared","jacobs",0.0,1.0]]'));
            assertEqual({'jane' [] struct('a',0); 432 false -1},...
                parse('[[2,3],["jane",432.0,[],false,{"a":0.0},-1.0]]'));
        end

        function testStruct(~)
            assertEqual(struct.empty, parse('[{},[0,0],[]]'));
            assertEqual(struct('jane', [], 'b', 432),...
                parse('{"b":432.0,"jane":[]}'));
            s = struct;
            s.p = cell(0);
            assertEqual([struct('p', 0) struct('p',true); s struct('p','')],...
                parse('[{},[2,2],["p"],0.0,[[]],true,""]'));
        end

        function testClass(~)
            import edu.stanford.covert.util.SparseMat;
            assertEqual(SparseMat(), parse([
                '["edu.stanford.covert.util.SparseMat",'...
                 '{"siz":[0.0,2.0],"subs":[[0,2]],"vals":[[0,1]]}]']));
            assertEqual(SparseMat([0 0 0; 0 0 0; 0 1 0; 0 0 -1]), parse([
                '["edu.stanford.covert.util.SparseMat",'...
                 '{"siz":[4.0,3.0],"subs":[[2,2],3.0,4.0,2.0,3.0],"vals":[[2,1],1.0,-1.0]}]']));
        end
    end
end

function result = parse(jsonString)
    result = edu.stanford.covert.io.jsonParse(jsonString);
end


function value = year_length_months_english ( y )

%*****************************************************************************80
%
%% YEAR_LENGTH_MONTHS_ENGLISH returns the number of months in an English year.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 September 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 calpak_test502 ( )

%*****************************************************************************80
%
%% CALPAK_TEST502 tests WEEKDAY_TO_NAME_HEBREW.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 April 2013
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALPAK_TEST502\n' );
  fprintf ( 1, '  For the Hebrew calendar,\n' );
  fprintf ( 1, '  WEEKDAY_TO_NAME_HEBREW names the days of the week.\n' );
  fprintf ( 1, '\n' );

  for i = 1 : 7
    s = weekday_to_name_hebrew ( i );
    fprintf ( 1, '  %2d  %s\n', i, s );
  end

  return
end


function x = p11_start ( option, nvar )

%*****************************************************************************80
%
%% P11_START returns a starting point for problem 11.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer OPTION, the option index.
%
%    Input, integer NVAR, the number of variables.
%
%    Output, real X(NVAR), the starting point.
%
  x = zeros ( nvar, 1 );

  return
end


function n = p01_n ( )

%*****************************************************************************80
%
%% P01_N returns the number of variables N for problem 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 April 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer N, the number of variables.
%
  n = 3;

  return
end


function [epoch, jd] = mydatemjdi (mjd)
    jd = mjd + 2400000.5;
    epoch = mydatejdi (jd);
end

%!test
%! num = mydatenum([1858 11 17  0 0 0]);
%! num2 = mydatemjdi(0);
%! myassert (num2, num)


% shortread() - Read matrix from short file.
%
% Usage:
%  >> A = shortread(filename,size,'format',offset)
%
% Inputs:
%  filename - Read matrix a from specified file while assuming four byte
%             short integers.
%  size     - The vector SIZE determine the number of short elements to be
%             read and the dimensions of the resulting matrix. If the last
%             element of SIZE is INF the size of the last dimension is determined
%             by the file length.
%
% Optional inputs:
% 'format'  - The option FORMAT argument specifies the storage format as
%             defined by fopen(). Default format ([]) is 'native'.
% offset    - The option OFFSET is offset in shorts from the beginning of file (=0)
%             to start reading (2-byte shorts assumed).
%             It uses fseek to read a portion of a large data file.
%
% Author: Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998
%
% See also: floatread(), floatwrite(), fopen()

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

% xx-07-98  written by Sigurd Enghoff, Salk Institute
% 04-26-99  modified by Sigurd Enghoff to handle variable-sized and
%           multi-dimensional data.
% 07-08-99  modified by Sigurd Enghoff, FORMAT argument added.
% 02-08-00  help updated for toolbox inclusion -sm
% 02-14-00  added segment arg -sm

function A = shortread(fname,Asize,fform,offset)

if ~exist('fform') | isempty(fform)|fform==0
	fform = 'native';
end

fid = fopen(fname,'rb',fform);
if fid>0
 if exist('offset')
   stts = fseek(fid,2*offset,'bof');
   if stts ~= 0
     error('shortread(): fseek() error.');
     return
   end
 end
 A = fread(fid,prod(Asize),'short');
else
 error('shortread(): fopen() error.');
 return
end
fprintf('   %d shorts read\n',prod(size(A)));

if Asize(end) == Inf
	Asize = Asize(1:end-1);
	A = reshape(A,[Asize length(A)/prod(Asize)]);
else
	A = reshape(A,Asize);
end

fclose(fid);


function b = transpose(a)
% function B=transpose(A)
%
% DESCRIPTION
%   Returns the non-conjugate transpose of a polynomial.
%
% INPUTS
%   A: polynomial
%
% OUTPUTS
%   B: transpose of A.
%
% SYNTAX
%   B= transpose(A);
%   B= A.';
%
% See also ctranspose

% 6/7/2002: PJS  Initial Coding

b=a;

% Get Dimensions
[nrb,ncb]=size(b);
bcoef = b.coefficient;

idx = [];
tempidx = 0:nrb:(ncb-1)*nrb;
for i1 = 1:nrb
    idx = [idx i1+tempidx];
end
bcoef = bcoef(:,idx);
b.coefficient = bcoef;
b.matdim = [ncb nrb];


function seed = van_der_corput_seed_get ( )

%*****************************************************************************80
%
%% VAN_DER_CORPUT_SEED_GET gets the seed of the van der Corput sequence.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 February 2003
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Johannes van der Corput,
%    Verteilungsfunktionen I & II,
%    Nederl. Akad. Wetensch. Proc.,
%    Volume 38, 1935, pages 813-820, pages 1058-1066.
%
%  Parameters:
%
%    Output, integer SEED, the current value for the seed.
%
%    Global, integer VAN_DER_CORPUT_SEED, the current seed.
%
  global van_der_corput_BASE
  global van_der_corput_SEED
%
 seed = van_der_corput_SEED;

  return
end


function p22_default ( dim_num )

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

  r8 = 0.0;
  p22_r8 ( 'D', '*', r8 );

  i4vec = [];
  p22_i4vec ( 'D', '*', dim_num, i4vec );

  return
end


function root_num = p12_root_num ( )

%*****************************************************************************80
%
%% P12_ROOT_NUM returns the number of known roots for problem 12.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 May 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer ROOT_NUM, the number of known roots.
%
  root_num = 1;

  return
end


function r8sto_print_some ( n, a, ilo, jlo, ihi, jhi, title )

%*****************************************************************************80
%
%% R8STO_PRINT_SOME prints some of a R8STO matrix.
%
%  Discussion:
%
%    The R8STO storage format is used for a symmetric Toeplitz matrix.
%    It stores the N elements of the first row.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 April 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.
%    N must be positive.
%
%    Input, real A(N), the R8STO matrix.
%
%    Input, integer ILO, JLO, IHI, JHI, the first row and
%    column, and the last row and column to be printed.
%
%    Input, string TITLE, a title.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );

  incx = 5;
%
%  Print the columns of the matrix, in strips of 5.
%
  for j2lo = jlo : incx : jhi

    j2hi = j2lo + incx - 1;
    j2hi = min ( j2hi, n );
    j2hi = min ( j2hi, jhi );

    inc = j2hi + 1 - j2lo;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Col: ' );

    for j = j2lo : j2hi
      fprintf ( 1, '%7d       ', j );
    end

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Row\n' );
    fprintf ( 1, '  ---\n' );
%
%  Determine the range of the rows in this strip.
%
    i2lo = max ( ilo, 1 );
    i2hi = min ( ihi, n );

    for i = i2lo : i2hi

      fprintf ( 1, '%4d  ', i );
%
%  Print out (up to) 5 entries in row I, that lie in the current strip.
%
      for j2 = 1 : inc

        j = j2lo - 1 + j2;

        if ( i <= j )
          aij = a(1+j-i);
        else
          aij = a(1+i-j);
        end

        fprintf ( 1, '%12g  ', aij );

      end

      fprintf ( 1, '\n' );

    end

  end

  return
end


% MAPTEXT   Text annotations on maps.
%
%    MAPTEXT(C, 'string') adds the text in the quotes to location
%    specified by the coordinates C. C(1,:) specifies the longitudes and
%    C(2,:) the latitudes.
%
%    MAPTEXT(C, S) adds the texts in the cell array S to locations specified
%    by the coordinates C. C(1,:) specifies the longitudes and C(2,:) the
%    latitudes.
%
%    MAPTEXT(..., property/value pairs) can be used to change, e.g.,
%    fontsize, weight, and color using the standard TEXT properties.
%
%    See also TEXT and M_TEXT.

% Copyright (c) 2010 Jaakko Luttinen

function maptext(C, str, varargin)

if iscell(str)
  for i=1:numel(str)
    m_text(C(1,i), C(2,i), str{i}, varargin{:});
  end
else
  m_text(C(1,:), C(2,:), str, varargin{:});
end


function c8mat_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )

%*****************************************************************************80
%
%% C8MAT_PRINT_SOME prints some of a C8MAT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 September 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns in the matrix.
%
%    Input, complex A(M,N), the matrix.
%
%    Input, integer ILO, JLO, IHI, JHI, the first row and
%    column, and the last row and column to be printed.
%
%    Input, string TITLE, a title.
%
  incx = 4;

  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );
%
%  Print the columns of the matrix, in strips of INCX.
%
  for j2lo = jlo : incx : jhi

    j2hi = j2lo + incx - 1;
    j2hi = min ( j2hi, n );
    j2hi = min ( j2hi, jhi );

    inc = j2hi + 1 - j2lo;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Col: ' );
    for j = j2lo : j2hi
      j2 = j + 1 - j2lo;
      fprintf ( 1, '%10d          ', j );
    end
    fprintf ( 1, '\n' );
    fprintf ( 1, '  Row\n' );
    fprintf ( 1, '  ---\n' );
%
%  Determine the range of the rows in this strip.
%
    i2lo = max ( ilo, 1 );
    i2hi = min ( ihi, m );

    for i = i2lo : i2hi
%
%  Print out (up to) INCX entries in row I, that lie in the current strip.
%
      for j2 = 1 : inc

        j = j2lo - 1 + j2;

        if ( a(i,j) == 0.0 )
          fprintf ( 1, '       0.0          ' );
        elseif ( imag ( a(i,j) ) == 0.0 )
          fprintf ( 1, ' %9g          ', real ( a(i,j) ) );
        else
          fprintf ( 1, ' %9g %9g', real ( a(i,j) ), imag ( a(i,j) ) );
       end

      end

      fprintf ( 1, '\n' );

    end

  end

  fprintf ( 1, '\n' );

  return
end


%%% [video_aux] = crop_4dvideo(video,r,s)
%
function [video_aux] = crop_4dvideo(video,r,s)
  if(s == -1)
    s = size(video,4);
  end

  k = 1;
  for i = r : s
    video_aux(:,:,:,k) = video(:,:,:,i);
    k = k + 1;
  end
end


function root_num = p15_root_num ( )

%*****************************************************************************80
%
%% P15_ROOT_NUM returns the number of known roots for problem 15.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 May 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer ROOT_NUM, the number of known roots.
%
  root_num = 1;

  return
end


% CXSparse MATLAB demos.
%
%   cs_demo  - run all CXSparse demos.
%   cs_demo1 - MATLAB version of the CSparse/Demo/cs_demo1.c program.
%   cs_demo2 - MATLAB version of the CSparse/Demo/cs_demo2.c program.
%   cs_demo3 - MATLAB version of the CSparse/Demo/cs_demo3.c program.

% Example:
%   help cs_demo

%   Copyright 2006-2007, Timothy A. Davis


% Example script how to use PIVlab from the commandline
% Just run this script to see what it does.
% You can adjust the settings in "s" and "p", specify a mask and a region of interest
clc; clear all

nr_of_cores = 1; % integer, 1 means single core, greater than 1 means parallel
if nr_of_cores > 1
	try
		local_cluster=parcluster('local'); % single node
		corenum =  local_cluster.NumWorkers ; % fix : get the number of cores available
	catch
		warning('on');
		warning('parallel local cluster can not be created, assigning number of cores to 1');
		nr_of_cores = 1;
	end
end
%% Create list of images inside user specified directory
directory= fullfile(fileparts(mfilename('fullpath')) , 'Examples') ; %directory containing the images you want to analyze
% default directory: PIVlab/Examples
addpath(fileparts(mfilename('fullpath')));
disp(fileparts(mfilename('fullpath')))

suffix='*.jpg'; %*.bmp or *.tif or *.jpg or *.tiff or *.jpeg
disp(['Looking for ' suffix ' files in the selected directory.']);
direc = dir([directory,filesep,suffix]); filenames={};
[filenames{1:length(direc),1}] = deal(direc.name);
filenames = sortrows(filenames); %sort all image files
amount = length(filenames);

%% Standard PIV Settings
s = cell(15,2); % To make it more readable, let's create a "settings table"
%Parameter                          %Setting           %Options
s{1,1}= 'Int. area 1';              s{1,2}=64;         % window size of first pass
s{2,1}= 'Step size 1';              s{2,2}=32;         % step of first pass
s{3,1}= 'Subpix. finder';           s{3,2}=1;          % 1 = 3point Gauss, 2 = 2D Gauss
s{4,1}= 'Mask';                     s{4,2}=[];         % If needed, generate via: imagesc(image); [temp,Mask{1,1},Mask{1,2}]=roipoly;
s{5,1}= 'ROI';                      s{5,2}=[];         % Region of interest: [x,y,width,height] in pixels, may be left empty
s{6,1}= 'Nr. of passes';            s{6,2}=2;          % 1-4 nr. of passes
s{7,1}= 'Int. area 2';              s{7,2}=32;         % second pass window size
s{8,1}= 'Int. area 3';              s{8,2}=16;         % third pass window size
s{9,1}= 'Int. area 4';              s{9,2}=16;         % fourth pass window size
s{10,1}='Window deformation';       s{10,2}='*linear'; % '*spline' is more accurate, but slower
s{11,1}='Repeated Correlation';     s{11,2}=0;         % 0 or 1 : Repeat the correlation four times and multiply the correlation matrices.
s{12,1}='Disable Autocorrelation';  s{12,2}=0;         % 0 or 1 : Disable Autocorrelation in the first pass.
s{13,1}='Correlation style';        s{13,2}=0;         % 0 or 1 : Use circular correlation (0) or linear correlation (1).
s{14,1}='Repeat last pass';   s{14,2}=0; % 0 or 1 : Repeat the last pass of a multipass analyis
s{15,1}='Last pass quality slope';   s{15,2}=0.025; % Repetitions of last pass will stop when the average difference to the previous pass is less than this number.

%% Standard image preprocessing settings
p = cell(10,1);
%Parameter                       %Setting           %Options
p{1,1}= 'ROI';                   p{1,2}=s{5,2};     % same as in PIV settings
p{2,1}= 'CLAHE';                 p{2,2}=1;          % 1 = enable CLAHE (contrast enhancement), 0 = disable
p{3,1}= 'CLAHE size';            p{3,2}=50;         % CLAHE window size
p{4,1}= 'Highpass';              p{4,2}=0;          % 1 = enable highpass, 0 = disable
p{5,1}= 'Highpass size';         p{5,2}=15;         % highpass size
p{6,1}= 'Clipping';              p{6,2}=0;          % 1 = enable clipping, 0 = disable
p{7,1}= 'Wiener';                p{7,2}=0;          % 1 = enable Wiener2 adaptive denoise filter, 0 = disable
p{8,1}= 'Wiener size';           p{8,2}=3;          % Wiener2 window size
p{9,1}= 'Minimum intensity';     p{9,2}=0.0;        % Minimum intensity of input image (0 = no change)
p{10,1}='Maximum intensity';     p{10,2}=1.0;       % Maximum intensity on input image (1 = no change)

%% other settings
pairwise = 1; % 0 for [A+B], [B+C], [C+D]... sequencing style, and 1 for [A+B], [C+D], [E+F]... sequencing style

%% PIV analysis loop
if pairwise == 1
	if mod(amount,2) == 1 %Uneven number of images?
		disp('Image folder should contain an even number of images.')
		%remove last image from list
		amount=amount-1;
		filenames(size(filenames,1))=[];
	end

	disp(['Found ' num2str(amount) ' images (' num2str(amount/2) ' image pairs).'])
	x=cell(amount/2,1);
	y=x;
	u=x;
	v=x;
else
	disp(['Found ' num2str(amount) ' images'])
	x=cell(amount-1,1);
	y=x;
	u=x;
	v=x;
end

typevector=x; %typevector will be 1 for regular vectors, 0 for masked areas
correlation_map=x; % correlation coefficient

%% Pre-load the image names out side of the parallelizable loop
slicedfilename1=cell(0);
slicedfilename2=cell(0);
j = 1;
for i=1:1+pairwise:amount-1
	slicedfilename1{j}=filenames{i}; % begin
	slicedfilename2{j}=filenames{i+1}; % end
	j = j+1;
end

%% Main PIV analysis loop:
% parallel
if nr_of_cores > 1

	if pivparpool('size')<nr_of_cores
		pivparpool('open',nr_of_cores);
	end

	parfor i=1:size(slicedfilename1,2)  % index must increment by 1

		[x{i}, y{i}, u{i}, v{i}, typevector{i},correlation_map{i}] = ...
			piv_analysis(directory, slicedfilename1{i}, slicedfilename2{i},p,s,nr_of_cores,false);
	end
else % sequential loop

	for i=1:size(slicedfilename1,2)  % index must increment by 1

		[x{i}, y{i}, u{i}, v{i}, typevector{i},correlation_map{i}] = ...
			piv_analysis(directory, slicedfilename1{i}, slicedfilename2{i},p,s,nr_of_cores,true);

		disp([int2str((i+1)/amount*100) ' %']);

	end
end

%% PIV postprocessing loop
% Standard image post processing settings

r = cell(6,1);
%Parameter     %Setting                                     %Options
r{1,1}= 'Calibration factor, 1 for uncalibrated data';      r{1,2}=1;                   % Calibration factor for u
r{2,1}= 'Calibration factor, 1 for uncalibrated data';      r{2,2}=1;                   % Calibration factor for v
r{3,1}= 'Valid velocities [u_min; u_max; v_min; v_max]';    r{3,2}=[-50; 50; -50; 50];  % Maximum allowed velocities, for uncalibrated data: maximum displacement in pixels
r{4,1}= 'Stdev check?';                                     r{4,2}=1;                   % 1 = enable global standard deviation test
r{5,1}= 'Stdev threshold';                                  r{5,2}=7;                   % Threshold for the stdev test
r{6,1}= 'Local median check?';                              r{6,2}=1;                   % 1 = enable local median test
r{7,1}= 'Local median threshold';                           r{7,2}=3;                   % Threshold for the local median test

u_filt=cell(size(u));
v_filt=cell(size(v));
typevector_filt=typevector;

if nr_of_cores >1 % parallel

	if pivparpool('size')<nr_of_cores
		pivparpool('open',nr_of_cores);
	end

	parfor PIVresult=1:size(x,1)

		[u_filt{PIVresult,1}, v_filt{PIVresult,1},typevector_filt{PIVresult,1}]= ...
			post_proc_wrapper(u{PIVresult,1},v{PIVresult,1},typevector{PIVresult,1},r,true);

	end

else % sequential loop

	for PIVresult=1:size(x,1)

		[u_filt{PIVresult,1}, v_filt{PIVresult,1},typevector_filt{PIVresult,1}]= ...
			post_proc_wrapper(u{PIVresult,1},v{PIVresult,1},typevector{PIVresult,1},r,true);

	end

end

%% clean up parallel pool, and cluster
%{
if nr_of_cores >1 % parallel
	poolobj = gcp('nocreate'); % GET the current parallel pool
	if ~isempty(poolobj ); delete(poolobj );end
	clear local_cluster;
end
%}
%%
save(fullfile(directory, [filenames{1} '_' filenames{end} '_' num2str(amount) '_frames_result_.mat']));

%%
clearvars -except p s r x y u v typevector directory filenames u_filt v_filt typevector_filt correlation_map
disp('DONE.')

function [u_filt, v_filt,typevector_filt] = post_proc_wrapper(u,v,typevector,post_proc_setting,paint_nan)
% wrapper function for PIVlab_postproc

% INPUT
% u, v: u and v components of vector fields
% typevector: type vector
% post_proc_setting: post processing setting
% paint_nan: bool, whether to interpolate missing data

% OUTPUT
% u_filt, v_filt: post-processed u and v components of vector fields
% typevector_filt: post-processed type vector

[u_filt,v_filt] = PIVlab_postproc(u,v, ...
	post_proc_setting{1,2},...
	post_proc_setting{2,2},...
	post_proc_setting{3,2},...
	post_proc_setting{4,2},...
	post_proc_setting{5,2},...
	post_proc_setting{6,2},...
	post_proc_setting{7,2});

typevector_filt = typevector; % initiate
typevector_filt(isnan(u_filt))=2;
typevector_filt(isnan(v_filt))=2;
typevector_filt(typevector==0)=0; %restores typevector for mask

if paint_nan
	u_filt=inpaint_nans(u_filt,4);
	v_filt=inpaint_nans(v_filt,4);
end

end


function neqn = p22_neqn ( )

%*****************************************************************************80
%
%% P22_NEQN returns the number of equations for problem P22.
%
%  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 = 2;

  return
end


function gridlines_test ( )

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

  gridlines_test01 ( );
  gridlines_test02 ( );
  gridlines_test03 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'GRIDLINES_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function res = test_nested_1

% This is the top level function.
% Define some variables.
a = 1;
b = 2;
x = 0;
y = 9;

% Display variables before call to fun1
disp('Before call to fun1:')
disp(['a = ' num2str(a)]);
disp(['b = ' num2str(b)]);
disp(['x = ' num2str(x)]);
disp(['y = ' num2str(y)]);

% Call fun1
x = fun1(x);

% Display variables after call to fun1
disp(' ');
disp('After call to fun1:')
disp(['a = ' num2str(a)]);
disp(['b = ' num2str(b)]);
disp(['x = ' num2str(x)]);
disp(['y = ' num2str(y)]);

   % Declare a nested function
   function res = fun1(y)
   res = y + a;
   a = a + 1;

   % Display variables inside call to fun1
   disp(' ');
   disp('Inside call to fun1:')
   disp(['a = ' num2str(a)]);
   disp(['b = ' num2str(b)]);
   disp(['x = ' num2str(x)]);
   disp(['y = ' num2str(y)]);

   end % function fun1

end % function test_nested_1


function polygons = splitPolygons(polygon)
%SPLITPOLYGONS Convert a NaN separated polygon list to a cell array of polygons.
%
%   POLYGONS = splitPolygons(POLYGON);
%   POLYGON is a N-by-2 array of points, possibly with pairs of NaN values.
%   The functions separates each component separated by NaN values, and
%   returns a cell array of polygons.
%
%   See also
%   polygons2d
%

% ------
% Author: David Legland
% E-mail: david.legland@inra.fr
% Created: 2007-10-12, using Matlab 7.4.0.287 (R2007a)
% Copyright 2007-2022 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas

if iscell(polygon)
    % case of a cell array
    polygons = polygon;

elseif sum(isnan(polygon(:))) == 0
    % single polygon -> no break
    polygons = {polygon};

else
    % find indices of NaN couples
    inds = find(sum(isnan(polygon), 2) > 0);

    % number of polygons
    N = length(inds) + 1;
    polygons = cell(N, 1);

    % iterate over NaN-separated regions to create new polygon
    inds = [0; inds; size(polygon, 1)+1];
    for i = 1:N
        polygons{i} = polygon((inds(i)+1):(inds(i+1)-1), :);
    end
end


function stochastic_rk_test ( )

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

  stochastic_rk_test01 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'STOCHASTIC_RK_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function out = get(f, propName)
%GET   GET method for the CHEBOP2 class.
%   P = GET(N, PROP) returns the property P specified in the string PROP from
%   the CHEBOP2 N. Valid entries for the string PROP are:
%       'DOMAIN'         - The domain of definition of N.
%       'OP'             - The partial differential operator of N.
%       'LBC'            - The left boundary constraints of N.
%       'RBC'            - The right boundary constraints of N.
%       'UBC'            - The top boundary constraints of N.
%       'DBC'            - The bottom boundary constraints of N.
%
% The following are also supported:
%       'DIM'            - The size of the system.
%       'SCALE'          - The relative scale of the solution.
%       'COEFFS'         - The variable coefficients of N.
%       'XORDER'         - The order of differentiation in the x-direction.
%       'YORDER'         - The order of differentiation in the y-direction.
%       'U', 'S', 'V'    - The low rank structure of N.

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

if ( numel(f) > 1 )
    out = cell(numel(f));
    for k = 1:numel(f)
        out{k} = get(f(k), propName);
    end
    return
end

switch propName
    case fieldnames(f)
        % Allow access to any of the properties of F via GET:
        out = f.(propName);
    otherwise
        error('CHEBFUN:CHEBOP2:get:propName', ...
            [propName,' is not a valid chebop2 property.'])
end


function ht = my_yticklabels(varargin)

%MY_YTICKLABELS replaces YTickLabels with "normal" texts
%   accepting multiline texts and TEX interpreting
%   and shrinks the axis to fit the texts in the window
%
%    ht = my_yticklabels(Ha, ytickpos, ytickstring)
% or
%    ht = my_yticklabels(ytickpos, ytickstring)
%
%  in:    ytickpos     YTick positions [N*1]
%        ytickstring   Strings to use as labels {N*1} cell of cells
%
% Examples:
% plot(randn(20,1))
% ytl = {{'one';'two';'three'} '\alpha' {'\beta';'\gamma'}};
% h = my_yticklabels(gca,[-1 0 1],ytl);
% % vertical
% h = my_yticklabels([-1 0 1],ytl, ...
%     'Rotation',-90, ...
%     'VerticalAlignment','middle', ...
%     'HorizontalAlignment','center');

% Pekka Kumpulainen 5.3.2008

textopts = {};
if length(varargin{1})==1 && ...
        ishandle(varargin{1}) && ...
        strcmpi(get(varargin{1},'Type'),'axes');
    Ha = varargin{1};
    ytickpos = varargin{2};
    ytickstring = varargin{3};
    if nargin > 3
        textopts = varargin(4:end);
    end
else
    Ha = gca;
    %Hfig = get(Ha,'Parent');
    ytickpos = varargin{1};
    ytickstring = varargin{2};
    if nargin > 2
        textopts = varargin(3:end);
    end
end

set(Ha,'YTick',ytickpos, 'YTickLabel','')
h_olds = findobj(Ha, 'Tag', 'MUYTL');
if ~isempty(h_olds)
    delete(h_olds)
end

%% Make XTickLabels
NTick = length(ytickpos);
Xbot = min(get(gca,'XLim'));
ht = zeros(NTick,1);
for ii = 1:NTick
    ht(ii) = text('String',ytickstring{ii}, ...
        'Units','data', ...
        'VerticalAlignment', 'middle', ...
        'HorizontalAlignment', 'center', ...
        'Position',[Xbot ytickpos(ii)], ...
        'Tag','MUYTL');
end
if ~isempty(textopts)
    set(ht,textopts{:})
end

%% shift texts left to fit & squeeze axis if needed

set(Ha,'Units','pixels')
Axpos = get(Ha,'Position');
% set(Hfig,'Units','pixels')
% Figpos = get(Hfig,'Position');

set(ht,'Units','pixels')
TickPos = zeros(NTick,3);
TickExt = zeros(NTick,4);
for ii = 1:NTick
    TickPos(ii,:) = get(ht(ii),'Position');
    tmpext = get(ht(ii),'Extent');
    set(ht(ii),'Position',[TickPos(ii,1)-tmpext(3)/2-5 TickPos(ii,2:end)])
    TickExt(ii,:) = get(ht(ii),'Extent');
end

needmove = -(Axpos(1) + min(TickExt(:,1)));

if needmove>0;
    Axpos(1) = Axpos(1)+needmove+2;
    Axpos(3) = Axpos(3)-needmove+2;
    set(Ha,'Position',Axpos);
end

set(Ha,'Units','normalized')
set(ht,'Units','normalized')


function pass = test_emptyObjects( pref )
% For empty chebfun2 objects, does each command deal with them
% appropriately?

% Check things work for empty chebfun2s.
f = chebfun2();
try
    f + f;
    2*f;
    f*2;
    f.^2;
    2.^f;
    f.^f;
    sqrt(f);
    sum(f);
    integral2(f);
    % max(f)
    norm(f);
    squeeze(f);
    diff(f);
    cos(f);
    sin(f);
    sinh(f);
    f.^f + f;
    diag(f);
    trace(f);
    mean(f);
    minandmax2(f);
    median(f);
    flipud(f);
    flipdim(f,1);
    pass = 1;
catch
    pass = 0;
end
end


function FigSize(xdim,ydim)
% =======================================================================
% Sets the figure window to a desired size. The default is full screen
% =======================================================================
% FigSize(xdim,ydim)
% -----------------------------------------------------------------------
% OPTIONAL INPUT
%   - xdim: horizontal size (in cm)
%   - ydim: vertical size (in cm)
% =======================================================================
% Ambrogio Cesa Bianchi, March 2015
% ambrogio.cesabianchi@gmail.com

if nargin==0
    figure('units','normalized','outerposition',[0 0.1 1 0.9])
else
    % Get the position of the figure
    % [left bottom width height] [standard in px: 403 246   560   420]
    position = get(gcf, 'Position');

    % Place the figure on the south west corner of the screen (in cm)
    position(1) = 1;
    position(2) = 2;

    % xdim dimension in cm
    if exist('xdim','var')
        position(3) = xdim;
    end

    % ydim dimension in cm
    if exist ('ydim','var')
        position(4) = ydim;
    end

    % Apply rescaling
    set(gcf, 'units', 'centimeters', 'Position', position)
end


function xy_display ( xy_filename )

%*****************************************************************************80
%
%% XY_DISPLAY plots a set of points in 2D.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 January 2009
%
%  Author:
%
%    John Burkardt
%
%  Usage:
%
%    xy_display ( 'xy_filename' )
%
%  Parameters:
%
%    Input, string XY_FILENAME, the name of the file
%    containing the coordinates of the points.
%
  fprintf ( 1, '\n' );
  timestamp ( );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'XY_DISPLAY\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Read a file of POINT_NUM points in 2 dimensions;\n' );
  fprintf ( 1, '  Display the points in a MATLAB graphics window.\n' );
%
%  First argument is the point file.
%
  if ( nargin < 1 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'XY_DISPLAY:\n' );
    xy_filename = input ( '  Enter the name of the point file (in ''quotes''!).\n' );
  end
%
%  Read the data.
%
  point_num = xy_header_read (  xy_filename );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Read the header of "%s".\n', xy_filename );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of points POINT_NUM  = %d\n', point_num );

  xy = xy_data_read ( xy_filename, point_num );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Read the data in "%s".\n', xy_filename );

  r8mat_transpose_print_some ( 2, point_num, xy, 1, 1, ...
    2, 5, '  First 5 nodes:' );

  scatter ( xy(1,:), xy(2,:), 'filled' );

  xy_min(1) = min ( xy(1,:) );
  xy_max(1) = max ( xy(1,:) );

  xy_min(2) = min ( xy(2,:) );
  xy_max(2) = max ( xy(2,:) );

  xy_range(1) = xy_max(1) - xy_min(1);
  xy_range(2) = xy_max(2) - xy_min(2);

  margin = 0.025 * max ( xy_range(1), xy_range(2) );

  x_min = xy_min(1) - margin;
  x_max = xy_max(1) + margin;
  y_min = xy_min(2) - margin;
  y_max = xy_max(2) + margin;

  xlabel ( '--X axis--' )
  ylabel ( '--Y axis--' )
%
%  The TITLE function will interpret underscores in the title.
%  We need to unescape such escape sequences!
%
  title_string = s_escape_tex ( xy_filename );
  title ( title_string )

  axis ( [ x_min, x_max, y_min, y_max ] );
  axis equal

  fprintf ( 1, '\n' );
  fprintf ( 1, 'XY_DISPLAY\n' );
  fprintf ( 1, '  Normal end of execution.\n' );

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

  return
end
function r8mat_transpose_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )

%*****************************************************************************80
%
%% R8MAT_TRANSPOSE_PRINT_SOME prints some of an R8MAT, transposed.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 May 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns.
%
%    Input, real A(M,N), an M by N matrix to be printed.
%
%    Input, integer ILO, JLO, the first row and column to print.
%
%    Input, integer IHI, JHI, the last row and column to print.
%
%    Input, string TITLE, an optional title.
%
  incx = 5;

  if ( 0 < s_len_trim ( title ) )
    fprintf ( 1, '\n' );
    fprintf ( 1, '%s\n', title );
  end

  for i2lo = max ( ilo, 1 ) : incx : min ( ihi, m )

    i2hi = i2lo + incx - 1;
    i2hi = min ( i2hi, m );
    i2hi = min ( i2hi, ihi );

    inc = i2hi + 1 - i2lo;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Row: ' );
    for i = i2lo : i2hi
      fprintf ( 1, '%7d       ', i );
    end
    fprintf ( 1, '\n' );
    fprintf ( 1, '  Col\n' );

    j2lo = max ( jlo, 1 );
    j2hi = min ( jhi, n );

    for j = j2lo : j2hi

      fprintf ( 1, '%5d ', j );
      for i2 = 1 : inc
        i = i2lo - 1 + i2;
        fprintf ( 1, '%12f', a(i,j) );
      end
      fprintf ( 1, '\n' );

    end

  end

  return
end
function s2 = s_escape_tex ( s1 )

%*****************************************************************************80
%
%% S_ESCAPE_TEX de-escapes TeX escape sequences.
%
%  Discussion:
%
%    In particular, every occurrence of the characters '\', '_',
%    '^', '{' and '}' will be replaced by '\\', '\_', '\^',
%    '\{' and '\}'.  A TeX interpreter, on seeing these character
%    strings, is then likely to return the original characters.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 January 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string S1, the string to be de-escaped.
%
%    Output, string S2, a copy of the string, modified to avoid TeX escapes.
%
  s1_length = length ( s1 );

  s1_pos = 0;
  s2_pos = 0;
  s2 = [];

  while ( s1_pos < s1_length )

    s1_pos = s1_pos + 1;

    if ( s1(s1_pos) == '\' || ...
         s1(s1_pos) == '_' || ...
         s1(s1_pos) == '^' || ...
         s1(s1_pos) == '{' || ...
         s1(s1_pos) == '}' )
      s2_pos = s2_pos + 1;
      s2 = strcat ( s2, '\' );
    end

    s2_pos = s2_pos + 1;
    s2 = strcat ( s2, s1(s1_pos) );

  end

  return
end
function len = s_len_trim ( s )

%*****************************************************************************80
%
%% S_LEN_TRIM returns the length of a character string to the last nonblank.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 June 2003
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string S, the string to be measured.
%
%    Output, integer LEN, the length of the string up to the last nonblank.
%
  len = length ( s );

  while ( 0 < len )
    if ( s(len) ~= ' ' )
      return
    end
    len = len - 1;
  end

  return
end
function timestamp ( )

%*****************************************************************************80
%
%% 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 xy = xy_data_read ( input_filename, point_num )

%*****************************************************************************80
%
%% XY_DATA_READ reads data from an XY file.
%
%  Discussion:
%
%    The number of points in the file can be determined by calling
%    XY_HEADER_READ first.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILENAME, the name of the input file.
%
%    Input, integer POINT_NUM, the number of points.
%
%    Output, real XY(2,POINT_NUM), the point coordinates.
%
  input_unit = fopen ( input_filename, 'r' );

  if ( input_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'XY_DATA_READ - Error!\n' );
    fprintf ( 1, '  Could not open the input file.\n' );
    error ( 'XY_DATA_READ - Error!' );
  end

  i = 0;
  xy = zeros ( 2, point_num );
%
%  Use FGETL, not FGETS, so we don't pick up the NEWLINE character.
%
  while ( i < point_num )

    text = fgetl ( input_unit );

    if ( text(1) == '#' )
      continue;
    end

    if ( s_len_trim ( text ) == 0 )
      continue;
    end

    temp = sscanf ( text, '%f %f' );

    i = i + 1;
    xy(1,i) = temp(1);
    xy(2,i) = temp(2);

  end
%
%  Close the file.
%
  fclose ( input_unit );

  return
end
function point_num = xy_header_read ( input_filename )

%*****************************************************************************80
%
%% XY_HEADER_READ determines the number of pairs of data in an XY file.
%
%  Discussion:
%
%    This routine assumes that the file contains exactly three kinds of
%    records:
%
%    COMMENTS which begin with a '#' character in column 1;
%    BLANKS which contain nothing but 'whitespace';
%    XY coordinates, which each contain one pair of real values.
%
%    The routine ignores comments and blank lines and returns
%    the number of lines containing XY coordinates.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILENAME, the name of the input file.
%
%    Output, integer POINT_NUM, the number of points in the file.
%
  point_num = 0;
%
%  Open the file.
%
  input_unit = fopen ( input_filename, 'r' );

  if ( input_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'XY_HEADER_READ - Error!\n' );
    fprintf ( 1, '  Could not open the input file.\n' );
    error ( 'XY_HEADER_READ - Error!' );
  end
%
%  Read every line in the file.
%
%  Use FGETL, not FGETS, so we don't pick up the NEWLINE character.
%
  while ( 1 )

    text = fgetl ( input_unit );

    if ( text == -1 )
      break;
    end

    if ( text(1) == '#' )
      continue;
    end

    if ( s_len_trim ( text ) == 0 )
      continue;
    end

    sscanf ( text, '%f %f' );

    point_num = point_num + 1;

  end
%
%  Close the file.
%
  fclose ( input_unit );

  return
end


function test_bug1618

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY

filename = dccnpath('/home/common/matlab/fieldtrip/data/test/bug1618/bug1618.dat');

h = ft_read_header(filename);

disp(h)
disp(h.chanunit)
disp(h.chantype)

X = ft_read_data(filename);
assert(~any(isnan(X(:))), 'NaN values are not expected for this dataset!');