function stla_node_xyz_print ( node_num, node_xyz )

%*****************************************************************************80
%
%% STLA_NODE_XYZ_PRINT prints the node coordinates.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 September 2005
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    3D Systems, Inc,
%    Stereolithography Interface Specification,
%    October 1989.
%
%  Parameters:
%
%    Input, integer NODE_NUM, the number of nodes.
%
%    Input, real NODE_XYZ(3,NODE_NUM), the coordinates of the nodes.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '    Node         Coordinates\n' );
  fprintf ( 1, '\n' );

  for node = 1 : node_num

    fprintf ( 1, '  %6d  %14f  %14f  %14f\n', node, node_xyz(1:3,node) );

  end

  return
end


function r = isintval(a)
%ISINTVAL     Returns 1 if  a  is intval Taylor
%
%   r = isintval(a)

% written  05/21/09     S.M. Rump
%

  r = isa(a.t,'intval');


function data_set = create_interaction_variables(data_set,vars,range_nways,separator,max_varname_length)
% create_interaction_variables
%
% for Matlab R13+
% version 1.1 (April 2012)
% (c) Brian Weidenbaum
% website: http://www.BrianWeidenbaum.com/.
%
%
% OUTPUT: your dataset (or a dataset based on your matrix), updated with new, aptly-named *unique* interaction variables,
% ranging from at least 2 to any number the user specifies
%
% INPUTS (** = OPTIONAL)
% input name: (input datatype/s) -- description
%
% data_set: (dataset OR matrix) -- the data you want to alter
%
% **vars: (cell array of chars/numbers, OR vector of numbers, OR 'ALL') --
% default: 'ALL'
% the names of the variables you want to interact; alternatively, the column numbers of the variables you want to interact
% OR, you can just say 'ALL' to include all variables automatically
%
% **range_nways (vector OR 'MAX') --
% default: 2
% the range of numbers of variables to include in the interaction terms generated by this function
% alternatively, just type 'MAX' to use 2 variables to the maximum possible number of vars
%
% **separator (char) --
% default: '_'
% the separator string you want to use to divide the
% variable names that contributed to a new interaction variable.  Default
% is '_'.  E.g., by default, an interaction between Var1 and Var2 will be
% named 'Var1_Var2'.
%
% **max_varname_length (number) --
% default: 63
% the maximum length of the newly created interaction terms' variable names.
% Any dynamically generated variable names (e.g. 'Var1_Var2') that exceed this number will be excluded from the new dataset.
% You should set max_varname_length according to the database you plan to use with your data--
% e.g., if you only want to use this data in MATLAB, you should set max_varname_length=63 (the maximum length supported by the dataset class,
% but if you plan to export your data to Oracle, you should set it to around 30
%
%
%
% EXAMPLES
%
% You have a dataset with 3 variables: a, b, and c.
% You want to create interaction terms, up to 3 ways, for all of your variables.
% You type:
% new_dataset = create_interaction_variables(old_dataset,'all','max');
% new_dataset will contain:
% a.*b, named 'a_b'
% a.*c, named 'a_c'
% b.*c, named 'b_c'
% and a.*b.*c, named 'a_b_c',
% plus all original variables.
% It will NOT contain b.*a, c.*a, etc because these are not unique combos.
%
% You have a dataset with 3 variables: a, b, and c.
% You want to create interaction terms, up to 2 ways, only for columns 2 and 3.
% You type:
% new_dataset = create_interaction_variables(old_dataset,[2 3],2);
% new_dataset will contain only b.*c,
% plus all original variables.
%
% You have a dataset with 3 variables: a, b, and c.
% You want to create interaction terms, up to 2 ways, only for 'a' and 'c'.
% You type:
% new_dataset = create_interaction_variables(old_dataset,{'a','c'},2);
% new_dataset will contain only a.*c,
% plus all original variables.
%
% You have a dataset with 3 variables: a, b, and c.
% You want to create interaction terms, ONLY 3 ways, only for all vars.
% You type:
% new_dataset = create_interaction_variables(old_dataset,'all',3);
% new_dataset will contain only a .* b .* c,
% plus all original variables.
%
%
%
% CHANGE LOG
% Changes between 1.0 and 1.1:
% -added 'separator' parameter, enabling users to create custom named vars
% -changed 'max_nways' parameter to 'range_nways', giving user more control
% over the types of interactions created
% -enforced maximum max_varname_length as 63
% -reduced min number of arguments to 1, setting defaults for other 4 params
% -minor performance tweaks via vectorizing some inner function loops
%
%

	%PHASE ONE: USER INPUT VALIDATION

    % set default values for all params except data_set
    if nargin==1
       vars='all';
       range_nways=2;
       separator='_';
       max_varname_length = 63; %max length supported by MATLAB dataset class
    elseif nargin==2
       range_nways=2;
       separator='_';
       max_varname_length = 63;
    elseif nargin==3
        separator='_';
        max_varname_length = 63;
    elseif nargin==4
        max_varname_length = 63;
    end

    %if data_set param is a regular matrix, convert it to a dataset
	%Otherwise, user will be unable to know which columns correspond to which interactions
	if ~strcmp(class(data_set),'dataset')
	   data_set = matrix2dataset(data_set);
	   %this data_set will include default variable names, like 'Var1', 'Var2', etc
    end

    %check if user input 'all' or 'ALL' for vars param
    %if so, convert vars = data_set.Properties.VarNames;
    if ischar(vars)
        if strcmpi(vars,'ALL')
            vars = data_set.Properties.VarNames;
        else
            error('If you are using a char array as your vars parameter, you can only set it as ''all'' or ''ALL''. ');
        end
    end

    nvars = length(vars);
    if nvars<2
       error('You must specify at least 2 variable names/column numbers inside the vars parameter.');
    end

    %validate range_nways
    if ischar(range_nways)
        range_nways = 2:nvars;
    elseif isnumeric(range_nways)
        if length(range_nways)<1
           error('The max_nways parameter should contain at least one number.');
        end
        % 2 <= max vars per interaction <= total number of variable names passed in
        % set any nways <2 =2 or >nvars = nvwars and drop all but one
        % cannot have any repeating numbers, so in end just replace with unique
        if sum(range_nways<2)>0
           disp(['At least one number in range_nways is < 2.' ...
               '  Since you must have at least 2 variables per interaction, all numbers < 2 have been replaced with 2.']);
        end
        range_nways(range_nways<2)=2;
         if sum(range_nways>nvars)>0
            disp(['At least one number in range_nways is > ' num2str(nvars)...
                ' (the total number of variables you are trying to create interactions from).' ...
                '  All such numbers will be dropped from range_nways and replaced with a single ' num2str(nvars) '.']);
         end
        range_nways(range_nways>nvars)=nvars;
        range_nways=unique(range_nways);
        %force rnways to be a row vector
        range_nways = reshape(range_nways,1,length(range_nways));
    else
        error('range_nways parameter MUST be a vector of numbers, or ''ALL''.');
    end

	%check if each variable name/column number in vars param exists inside the dataset
	%also, if necessary, convert column numbers to variable names, for future use with eval strings
    if iscell(vars)
      if ~ischar(vars{1}) %if the varnames are NOT chars
        vars = columns2names(vars);
      else %vars are chars, so check if each name is member of vars
            for i=1:length(vars)
                if ~ismember(vars{i},data_set.Properties.VarNames)
                    disp([vars{i} ' is not a valid column and will not be included in the interactions.' ]);
                    nvars=nvars-1;
                end
            end
            vars(~ismember(vars,data_set.Properties.VarNames))=[];
      end
    else %its for sure a vector of numbers
        vars = columns2names(vars);
    end

    %validate separator
    if ~ischar(separator)
       error('Seperator needs to be a char array.');
    elseif length(separator)>60
        error('Your separator term is too long.');
    elseif ismember('%',separator)
        error('Your separator contains one or more illegal characters.');
    end

    %validate max_varname_length
    if max_varname_length>63
       error('Max varname length exceeds 63, which is the highest number supported by the MATLAB dataset class.');
    end

	%END INPUT VALIDATION

	%PHASE TWO: CREATE ALL THE INTERACTION VARIABLES
	all_evalstrs = get_evalstrs;
	for i=1:length(all_evalstrs)
	%trycatch prevents multiplying chars by numbers
		try
			eval(all_evalstrs{i});
		catch e
            disp(e.message);
		end
    end

    %PHASE THREE: PROFIT

	%
	%
	% INNER FUNCTIONS
	%
	%

	%inner function that translates varname INDICES to actual varnames cellarray of chars
	%for use in eval() function
    function char_varnames = columns2names(columns)
        %first detect if the columns are a cell array; if so, xform to vector
        if iscell(columns)
            columns = cell2mat(columns);
        end

        %check if all column numbers are between 1 and total nvars in data_set
        for ii=1:length(columns)
         if ((columns(ii)<1) || (columns(ii)>size(data_set,2)))
            disp(['Column number ' num2str(columns(ii)) ' is not a valid column and will not be included in the interactions.' ]);
            nvars=nvars-1;
         end
        end
        columns(columns(:)<1 | columns(:)>size(data_set,2))=[];
        char_varnames = data_set.Properties.VarNames(columns);
    end %inner function

	% inner function that creates all UNIQUE combinations of indices for 2:maxvars_perinteraction
	% adds them all to a cell array
    function all_indices = get_interaction_indices()
        all_indices={};
        ct=0;
        %for each number of vars per interaction...
        %get all unique combos of indices
        %e.g. if 3 vars, and 3 max vars per interaction
        %first, get 2 var combos:
        %12,13,23
        %then get 3 var combo: 123
        %add all that to cell array and return it
        for nways = range_nways

            %need to dynamically create allcomb args
            %if it's choose2, there are 2 args: 1:nvars,1:nvars
            %if it's choose3, there are 3 args: 1:nvars,1:nvars,1:nvars ...etc
            allcomb_argstr = repmat('1:nvars,',1,nways);
            %remove final ','
            allcomb_argstr  = allcomb_argstr(1:end-1);

            %allcomb returns cartesian product
            all_combos = eval(['allcomb(' allcomb_argstr ');']);

            %now choose all appropriate combos
            %so we only have unique combinations (eg not 2 1 and 1 2)
            logical_str='';
            for choose_columns= nways:-1:2
               logical_str=[logical_str, '(all_combos(:,' , num2str(choose_columns) , ')>all_combos(:,' , num2str(choose_columns-1) , '))&' ];
            end
            %remove final '&'
            logical_str = logical_str(1:end-1);

            % below gives the combo indices
            good_combos = all_combos(eval(logical_str),:);

            %now add each row in good_combos to all_indices
            ngood = size(good_combos,1);
            for ii=1:ngood
                ct =ct+1;
                all_indices{ct} = good_combos(ii,:);
            end %adding rows to all_indices
        end %loop that goes thru each possible number of vars per interaction
    end %get_interaction_indices inner fx

    % inner function that gets the 'data_set.var1_var2_varN=data_set.var1.*data_set.var2.*datset.varN' version of indices
    function str = indices2str(indices)
        % goal: if give two indices [1 2], return the following string:
        %   'data_set.var1_var2 = data_set.var1.*data_set.var2;'

        n_indices = length(indices);
        %left of equals sign should be: 'data_set.var1_var2'
        left_str = 'data_set.';

        %add each varname separated by _
        for i=1:n_indices
            left_str = [left_str vars{indices(i)} separator]; %seperator var
        end %building varname string
        %remove the final separator
        left_str = left_str(1:end-length(separator));
        %check if varname is too big
        if length(left_str)-length('data_set.') > max_varname_length
           error(['Name of new variable: ''' left_str(length('data_set.')+1:end) ...
               ''' exceeded max varname length of ' num2str(max_varname_length) ', and will not be included in the new dataset.']);
        end

        %now for the righthand side of equals, which should be:
        %'data_set.var1.*data_set.var2;'
        right_str = '';
        for i=1:n_indices
            right_str = [right_str 'data_set.' vars{indices(i)} '.*'];
        end %building varname string
        %removing the final '.*'
        right_str=[right_str(1:end-2) ';'];

        str= [left_str '=' right_str];
    end %indices2str inner fx

    %will give cellarray where each cell contains a good evalstr
    function all_evalstrs = get_evalstrs
        %first get all the indices
        inds = get_interaction_indices;
        ncombos= length(inds);
        all_evalstrs = cell(ncombos,1);

        %go thru each combo of indices and try to create an eval str
        %need try catch bc of potential max varname length problems
        for ii = 1:ncombos
            try
                all_evalstrs{ii}=indices2str(inds{:,ii});
            catch e
                all_evalstrs{ii}='';
                disp(e.message);
            end
        end
    end %get all evalstrs

    function A = allcomb(varargin)
        % ALLCOMB - All combinations
        %    B = ALLCOMB(A1,A2,A3,...,AN) returns all combinations of the elements
        %    in A1, A2, ..., and AN. B is P-by-N matrix is which P is the product
        %    of the number of elements of the N inputs.
        %    Empty inputs yields an empty matrix B of size 0-by-N. Note that
        %    previous versions (1.x) simply ignored empty inputs.
        %
        %    Example:
        %       allcomb([1 3 5],[-3 8],[0 1]) ;
        %         1  -3   0
        %         1  -3   1
        %         1   8   0
        %         ...
        %         5  -3   1
        %         5   8   0
        %         5   8   1
        %
        %    ALLCOMB(A1,..AN,'matlab') causes the first column to change fastest.
        %    This is more consistent with matlab indexing. Example:
        %    allcomb(1:2,3:4,5:6,'matlab') %->
        %      1   3   5
        %      2   3   5
        %      1   4   5
        %      ...
        %      2   4   6
        %
        %    This functionality is also known as the cartesian product.
        %
        %    See also NCHOOSEK, PERMS, NDGRID
        %    and COMBN, KTHCOMBN (Matlab Central FEX)

        % for Matlab R13+
        % version 2.2 (jan 2012)
        % (c) Jos van der Geest
        % email: jos@jasen.nl

        % History
        % 1.1 (feb 2006), removed minor bug when entering empty cell arrays;
        %     added option to let the first input run fastest (suggestion by JD)
        % 1.2 (jan 2010), using ii as an index on the left-hand for the multiple
        %     output by NDGRID. Thanks to Jan Simon, for showing this little trick
        % 2.0 (dec 2010). Bruno Luong convinced me that an empty input should
        % return an empty output.
        % 2.1 (feb 2011). A cell as input argument caused the check on the last
        %      argument (specifying the order) to crash.
        % 2.2 (jan 2012). removed a superfluous line of code (ischar(..))

        error(nargchk(1,Inf,nargin)) ;

        % check for empty inputs
        q = ~cellfun('isempty',varargin) ;
        if any(~q),
            warning('ALLCOMB:EmptyInput','Empty inputs result in an empty output.') ;
            A = zeros(0,nargin) ;
        else

            ni = sum(q) ;

            argn = varargin{end} ;

            if ischar(argn) && (strcmpi(argn,'matlab') || strcmpi(argn,'john')),
                % based on a suggestion by JD on the FEX
                ni = ni-1 ;
                ii = 1:ni ;
                q(end) = 0 ;
            else
                % enter arguments backwards, so last one (AN) is changing fastest
                ii = ni:-1:1 ;
            end

            if ni==0,
                A = [] ;
            else
                args = varargin(q) ;
                if ~all(cellfun('isclass',args,'double')),
                    error('All arguments should be arrays of doubles') ;
                end
                if ni==1,
                    A = args{1}(:) ;
                else
                    % flip using ii if last column is changing fastest
                    [A{ii}] = ndgrid(args{ii}) ;
                    % concatenate
                    A = reshape(cat(ni+1,A{:}),[],ni) ;
                end
            end
        end
    end %allcomb inner fx

	function output = matrix2dataset(matrix,ifx_varnames)
	% matrix2dataset
	%
	% INPUTS
	% matrix (N x M matrix): the matrix version of the data you want to convert
	% varnames (OPTIONAL cell vector of chars): the names of the columns, in order
	%
	% OUTPUT:
	% a dataset that contains all the data from your matrix, named according to
	% your varnames
	% assumes that each column in matrix is one dataset column-- eg no dataset
	% column should consist of >1 matrix column
	%
	%
	% EXAMPLE:
	% This function is great for when you have converted an old dataset
	% into a matrix of doubles for performing some calculations, but now you
	% want to update your original dataset with new values or new columns that
	% you have created from your calculations.
	%
	% In that situation, you would type the following:
	% updated_dataset = matrix2dataset(matrix_from_old_dataset, old_dataset.Properties.VarNames);
	%
	% If you don't have any varnames, you can choose not to use the varnames parameter
	% In that case, you will get the default dataset names: Var1, Var2,..VarN
	%

		n_vars = size(matrix,2);
		if nargin==2
			if ~(length(ifx_varnames)==n_vars)
				error('You must have one variable name for each column in the matrix parameter.');
			end
		end

		str_vars = '';
		for ii=1:n_vars
		   str_vars = [str_vars, 'matrix(:,', num2str(ii), '),' ];
		end

		if nargin == 2
			ds_arguments = [str_vars, '''VarNames'',','ifx_varnames'];
		elseif nargin==1
			ds_arguments = str_vars(1:end-1);
		end
		output = eval(['dataset(' ds_arguments ');']);
	end%innerfx

	%END OF INNER FUNCTIONS

end%main fx


function haar_test ( )

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

  haar_test01 ( );
  haar_test02 ( );
  haar_test03 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'HAAR_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function [ subG ] = gsp_subgraph( G,c )
%GSP_SUBGRAPH Create a subgraph from G
%   Usage: [ subG ] = gsp_subgraph( G,c )
%
%   Input parameters:
%       G   : Original graph
%       c   : Node to keep
%
%   Output parameters:
%       subG: Subgraph
%
%   This function create a subgraph from G taking only the node in c.

% Author: Nathanael Perraudin
% Date : Mai 2015

subG.W = G.W(c,c);
subG.N = length(c);
if isfield(G,'type')
    subG.type = ['sub-',G.type];
end

if isfield(G,'directed')
    subG.directed = G.directed;
end

if isfield(G,'lap_type')
    subG.lap_type = G.lap_type;
end

if isfield(G,'coords')
    subG.coords = G.coords(c,:);
end

if isfield(G,'limits')
    subG.limits = G.limits;
end

if isfield(G,'edge_width')
    subG.edge_width = G.edge_width;
end

if isfield(G,'edge_color')
    subG.edge_color = G.edge_color;
end

if isfield(G,'edge_style')
    subG.edge_style = G.edge_style;
end

if isfield(G,'vertex_size')
    subG.vertex_size = G.vertex_size;
end

if isfield(G,'vertex_color')
    subG.vertex_color = G.vertex_color;
end

if isfield(G,'vertex_edge_color')
    subG.vertex_edge_color = G.vertex_edge_color;
end

subG = gsp_graph_default_parameters(subG);

end


%Nice grid by Kris Donhowe, SC Solutions, Inc.
%
h_axes = findobj(get(gcf,'Children'),'Type','axes');
grey = [0.7,0.7,0.7];
set(h_axes,'xcolor',grey,'ycolor',grey, ...
    'GridLineStyle','-','MinorGridLineStyle','-', ...
    'Units','pixels');
grid on
c11=copyobj(h_axes,gcf);
set(c11,'color','none','xcolor','k', ...
    'xgrid','off','ycolor','k', ...
    'ygrid','off');


function varargout = isreal(varargin)
%ISREAL   Real-valued CHEBFUN2 test.
%   ISREAL(F) returns logical true if F does not have an imaginary part and
%   false otherwise.
%
%   ~ISREAL(F) detects CHEBFUN2 object that have an imaginary part even if it is
%   all zero.

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

[varargout{1:nargout}] = isreal@separableApprox(varargin{:});

end


function title = p32_title ( )

%*****************************************************************************80
%
%% P32_TITLE returns the title of problem P32
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, the title of the problem.
%
  title = 'Problem 32, The Lorenz System';

  return
end


function title = p05_title ( option )

%*****************************************************************************80
%
%% P05_TITLE sets the title for problem 5.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer OPTION, the option index.
%
%    Output, string TITLE, the title of the problem.
%
  if ( option == 1 )
    title = 'Wacker function, A = 0.1.';
  elseif ( option == 2 )
    title = 'Wacker function, A = 0.5.';
  elseif ( option == 3 )
    title = 'Wacker function, A = 1.0.';
  end

  return
end


classdef ODE45Integrator < AbstractFirstOrderIntegrator
    %ODE45Integrator Summary of this class goes here
    %   Detailed explanation goes here

    properties
        options(1,1) BuiltInIntegratorOptions = BuiltInIntegratorOptions();
        integratorEnum = IntegratorEnum.ODE45;
    end

    methods
        function obj = ODE45Integrator(options)
            if(nargin > 0)
                obj.options = options;
            else
                obj.options = BuiltInIntegratorOptions();
            end
        end

        function [t,y,te,ye,ie] = integrate(obj, odefun, tspan, y0, evtsFunc, odeOutputFun)
            odeSetOptions = obj.options.getIntegratorOptions();
            optionsToUse = odeset(odeSetOptions, 'Events',evtsFunc, 'OutputFcn',odeOutputFun);

            [t,y,te,ye,ie] = ode45(odefun, tspan, y0, optionsToUse);
        end

        function options = getOptions(obj)
            options = obj.options;
        end
    end
end


function tf = strlexne(a, b)
%STRLEXNE Lexicographic not equal to.
%
%   STRLEXNE(A, B) returns 1 if A is lexicographically not equal to B, and 0
%   otherwise.
%
%   This is a MATLAB version of the Perl `ne' operator.

%   See also NE.

%   Author:      Peter J. Acklam
%   Time-stamp:  2003-10-13 11:15:37 +0200
%   E-mail:      pjacklam@online.no
%   URL:         http://home.online.no/~pjacklam

   tf = strlexcmp(a, b) ~= 0;


function value = p37_autonomous ( )

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

  return
end


classdef AgastFeatureDetector < handle
    %AGASTFEATUREDETECTOR  Wrapping class for feature detection using the AGAST method
    %
    % Detects corners using the AGAST algorithm by [mair2010].
    %
    % ## References
    % [mair2010]:
    % > E. Mair, G. D. Hager, D. Burschka, M. Suppa, and G. Hirzinger.
    % > "Adaptive and generic corner detection based on the accelerated segment test".
    % > In "European Conference on Computer Vision (ECCV'10)", Sept 2010.
    % > [Link](http://www6.in.tum.de/Main/ResearchAgast).
    %
    % See also: cv.AGAST, cv.FAST, cv.FeatureDetector
    %

    properties (SetAccess = private)
        % Object ID
        id
    end

    properties (Dependent)
        % Threshold on difference between intensity of the central pixel
        % and pixels of a circle around this pixel.
        %
        % Default is 10
        Threshold
        % If true, non-maximum suppression is applied to detected corners
        % (keypoints).
        %
        % Default is true.
        NonmaxSuppression
        % One of the four neighborhoods as defined in the paper:
        %
        % * **AGAST_5_8**
        % * **AGAST_7_12d**
        % * **AGAST_7_12s**
        % * **OAST_9_16** (default)
        Type
    end

    methods
        function this = AgastFeatureDetector(varargin)
            %AGASTFEATUREDETECTOR  Constructor
            %
            %     obj = cv.AgastFeatureDetector()
            %     obj = cv.AgastFeatureDetector(..., 'OptionName',optionValue, ...)
            %
            % ## Options
            % * __Threshold__ See cv.AgastFeatureDetector.Threshold, default 10
            % * __NonmaxSuppression__ See
            %   cv.AgastFeatureDetector.NonmaxSuppression, default true
            % * __Type__ See cv.AgastFeatureDetector.Type, default `OAST_9_16`
            %
            % See also: cv.AgastFeatureDetector.detect
            %
            this.id = AgastFeatureDetector_(0, 'new', varargin{:});
        end

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

        function typename = typeid(this)
            %TYPEID  Name of the C++ type (RTTI)
            %
            %     typename = obj.typeid()
            %
            % ## Output
            % * __typename__ Name of C++ type
            %
            typename = AgastFeatureDetector_(this.id, 'typeid');
        end
    end

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

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

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

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

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

    %% Features2D: FeatureDetector
    methods
        function keypoints = detect(this, img, varargin)
            %DETECT  Detects keypoints in an image or image set
            %
            %     keypoints = obj.detect(img)
            %     keypoints = obj.detect(imgs)
            %     [...] = obj.detect(..., 'OptionName',optionValue, ...)
            %
            % ## Input
            % * __img__ Image (first variant), 8-bit grayscale image where
            %   keypoints (corners) are detected.
            % * __imgs__ Image set (second variant), cell array of images.
            %
            % ## Output
            % * __keypoints__ The detected keypoints. In the first variant, a
            %   1-by-N structure array. In the second variant of the method,
            %   `keypoints{i}` is a set of keypoints detected in `imgs{i}`.
            %
            % ## Options
            % * __Mask__ A mask specifying where to look for keypoints
            %   (optional). It must be a logical or 8-bit integer matrix with
            %   non-zero values in the region of interest. In the second
            %   variant, it is a cell-array of masks for each input image,
            %   `masks{i}` is a mask for `imgs{i}`. Not set by default.
            %
            % See also: cv.AgastFeatureDetector.AgastFeatureDetector
            %
            keypoints = AgastFeatureDetector_(this.id, 'detect', img, varargin{:});
        end
    end

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

        function value = get.NonmaxSuppression(this)
            value = AgastFeatureDetector_(this.id, 'get', 'NonmaxSuppression');
        end
        function set.NonmaxSuppression(this, value)
            AgastFeatureDetector_(this.id, 'set', 'NonmaxSuppression', value);
        end

        function value = get.Type(this)
            value = AgastFeatureDetector_(this.id, 'get', 'Type');
        end
        function set.Type(this, value)
            AgastFeatureDetector_(this.id, 'set', 'Type', value);
        end
    end

end


 hold on;
 len = length(obps);
 for i = 1 : len
     plot3(obps(i,1), obps(i,2), obps(i,3), '*', 'Color', 'r');
 end

 hold off;


% ------------------------------------------------------------------------
%  Copyright (C)
%  Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain
%  University of California Berkeley (UCB) - USA
%
%  Jordi Pont-Tuset <jordi.pont@upc.edu>
%  Pablo Arbelaez <arbelaez@berkeley.edu>
%  June 2014
% ------------------------------------------------------------------------
% This file is part of the MCG package presented in:
%    Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J,
%    "Multiscale Combinatorial Grouping,"
%    Computer Vision and Pattern Recognition (CVPR) 2014.
% Please consider citing the paper if you use this code.
% ------------------------------------------------------------------------
% Test robustness to empty ucms
% ------------------------------------------------------------------------

% Empty input image
I = zeros(40,80);

candidates_scg = im2mcg(I,'fast');
candidates_mcg = im2mcg(I,'accurate');


function imgs = modcrop(imgs, modulo)
if size(imgs,3)==1
    sz = size(imgs);
    sz = sz - mod(sz, modulo);
    imgs = imgs(1:sz(1), 1:sz(2));
else
    tmpsz = size(imgs);
    sz = tmpsz(1:2);
    sz = sz - mod(sz, modulo);
    imgs = imgs(1:sz(1), 1:sz(2),:);
end


function dfupdatelegend(dffig,reset)
%DFUPLDATELEGEND Update legend in dfittool window

%   $Revision: 1.1.6.5 $  $Date: 2004/01/24 09:36:01 $
%   Copyright 2001-2004 The MathWorks, Inc.

if nargin<2, reset=false; end

% If figure not passed in, find figure that contains this thing
while ~isequal(get(dffig,'parent'),0),
  dffig = get(dffig,'parent');
end

% Remember info about old legend, if any
ax = get(dffig,'CurrentAxes');
if isempty(get(ax,'Children'))
   legh = [];
else
   legh = legend('-find',ax);
end

% Try to put the legend where the curves are not likely to be.
% Position "0" is supposed to do this, but it is deprecated
% and can be slow.  Instead use a heurisitic.
ftype = dfgetset('ftype');
if ischar(ftype) && ~isempty(ftype) && ismember(ftype, {'pdf' 'survivor'})
   % The survivor function is decreasing.  Most pdf functions drop more
   % quickly to the right.  "top right" is probably good for these functions.
   legendpos = 'TR';
else
   % The remaining ones are increasing, so "top left" is probably good.
   legendpos = 'TL';
end
legend(ax, 'off');

% Maybe no legend has been requested
if isequal(dfgetset('showlegend'),'off')
   return
end

% Get data line handles and labels
hh = flipud(findobj(ax,'Type','line'));
hData = findobj(hh,'flat','Tag','dfdata');
n = length(hData);

textData = cell(n,1);
for j=1:length(hData)
   nm = '';
   ds = get(hData(j),'UserData');
   if ~isempty(ds) && ishandle(ds) && ~isempty(findprop(ds,'name'))
      nm = ds.name;
   end
   if isempty(nm)
      hData(j) = NaN;
   else
      textData{j} = nm;
   end
end
t = ~isnan(hData);
textData = textData(t);
hData = hData(t);
sortData = 1000*(1:length(hData));
if isempty(sortData)
   maxnum = 0;
else
   maxnum = max(sortData) + 1000;
end

% Indent bounds if there are two or more data set lines
if n>1
   pre = '  ';
else
   pre = '';
end

% Deal with confidence bounds, if any, around empirical cdf
n = length(hData);
textDataBounds = cell(n,1);
hDataBounds = repmat(NaN,n,1);
sortDataBounds = zeros(n,1);
for j=1:n
   ds = get(hData(j),'UserData');
   if ds.showbounds
      hbounds = ds.boundline;
      if ~isempty(hbounds) && ishandle(hbounds) ...
                           && ~isempty(get(hbounds,'YData'))
         textDataBounds{j} = [pre 'confidence bounds'];
         hDataBounds(j) = hbounds;
         sortDataBounds(j) = sortData(j) + .5;
      end
   end
end
if any(isnan(hDataBounds))
   t = isnan(hDataBounds);
   textDataBounds(t) = [];
   hDataBounds(t) = [];
   sortDataBounds(t) = [];
end

% Indent fits if there are two or more data lines
if (length(hData)>1)
   pre = '  ';
else
   pre = '';
end

% Get fit line handles and labels
hFit = findobj(hh,'flat','Tag','distfit');
sortFit = NaN*hFit;
n = length(hFit);
hFitConf = NaN*zeros(n,1);
textFit = cell(n,1);
nms = cell(n,1);
for j=1:length(hFit)
   try
      fit = get(hFit(j),'UserData');
      nm = fit.name;
   catch
      nm = '';
   end
   if isempty(nm)
      hFit(j) = NaN;
   else
      nms{j} = nm;
      textFit{j} = [pre nm];

      % Find the dataset for this fit
      ds = fit.dshandle;
      sortFitj = maxnum + j;
      for k=1:length(hData)
         if isequal(ds.name,textData{k})
            sortFitj = sortData(k) + j;
            break;
         end
      end
      sortFit(j) = sortFitj;

      % Look for bounds
      b = get(fit,'boundline');
      if ~isempty(b)
         hFitConf(j) = b(1);
      end
   end
end
t = ~isnan(hFit);
nms = nms(t);
textFit = textFit(t);
hFit = hFit(t);
sortFit = sortFit(t);
hFitConf = hFitConf(t);

% Indent bounds if there are two or more fits
if (length(hFit)>1)
   pre = [pre '  '];
end

% Get confidence bound line handles and labels
n = length(hFitConf);
textFitBounds = cell(n,1);
sortFitBounds = zeros(size(hFitConf));
for j=1:length(hFitConf)
   if ~isnan(hFitConf(j)) && ishandle(hFitConf(j)) ...
                          && ~isempty(get(hFitConf(j),'XData'))
      textFitBounds{j} = sprintf('%sconfidence bounds (%s)',pre,nms{j});
      sortFitBounds(j) = sortFit(j) + 0.5;
   else
      hFitConf(j) = NaN;
   end
end
t = ~isnan(hFitConf);
textFitBounds = textFitBounds(t);
hFitConf = hFitConf(t);
sortFitBounds = sortFitBounds(t);

% Combine everything together for the legend
h = [hData(:); hDataBounds(:); hFit(:); hFitConf(:)];
c = [textData; textDataBounds; textFit; textFitBounds];
s = [sortData(:); sortDataBounds(:); sortFit(:); sortFitBounds(:)];

% Sort so related things are together
[s,j] = sort(s);
c = c(j);
h = h(j);

% Create the legend
if (length(h)>0)
   ws = warning;
   lw = lastwarn;
   warning('off');
   oldu = get(ax,'Units');
   set(ax,'Units','normalized');
   try
      havecoords = isnumeric(legendpos) && length(legendpos)>1;
      if havecoords
          temppos = 0;
      else
          temppos = legendpos;
      end
      [legh,objh] = legend(ax,h,c,temppos);
      if havecoords
         set(legh,'Units','points');
         newpos = get(legh,'Position');
         newpos(1:2) = legendpos(1:2);
         set(legh,'Position',newpos);
      end
   catch
      objh = [];
   end
%   set(ax,'Units',oldu);
   warning(ws);
   lastwarn(lw);

   % Avoid treating ds/fit names as TeX strings
   objh = findobj(objh,'flat','Type','text');
   set(objh,'Interpreter','none','Hittest','off');
end

% Set a resize function that will handle legend and layout
set(dffig,'resizefcn','dfittool(''adjustlayout'');');


function Dy = computeDy(Xmin, Xmax, ny)
    Dy_tmp = cell(2*ny);

    for i=1:2*ny
        if i <= ny
            Dy_tmp{i,1} = Xmax;
        else
            Dy_tmp{i,1} = -Xmin;
        end
    end

    Dy =cell2mat(Dy_tmp);
end


function ni_def = afni_ni_defs()
    persistent cached_ni_def

    % for efficency reasons generate the definitions only once;
    % upon each subsequent call the cached data is used
    if ~isstruct(cached_ni_def)
        cached_ni_def=generate_ni_def();
    end

    ni_def=cached_ni_def;

function ni_def=generate_ni_def()
    ni_def=struct();
    %work out types /* definitions from niml.h
    ni_def.NI_BYTE     =   0        ;       %/* == MRI_byte    */
    ni_def.NI_SHORT    =   1       ;        %/* == MRI_short   */
    ni_def.NI_INT      =   2       ;        %/* == MRI_int     */
    ni_def.NI_FLOAT32  =   3       ;        %/* == MRI_float   */
    ni_def.NI_FLOAT    =   ni_def.NI_FLOAT32;
    ni_def.NI_FLOAT64  =   4      ;         %/* == MRI_double  */
    ni_def.NI_DOUBLE   =   ni_def.NI_FLOAT64;
    ni_def.NI_COMPLEX64=   5   ;            %/* == MRI_complex */
    ni_def.NI_COMPLEX  =   ni_def.NI_COMPLEX64;
    ni_def.NI_RGB      =   6   ;            %/* == MRI_rgb     */
    ni_def.NI_RGBA     =   7  ;             %/* == MRI_rgba    */
    ni_def.NI_STRING   =   8  ;             %/* after "basic" types */

    %/*! Number of types of fixed size ("basic" types).
    %    Note that if this changes,
    %    the NI_rowtype stuff must be altered accordingly. */
    ni_def.NI_NUM_BASIC_TYPES = 8;

    %/*! One more than the last NI_ data type code defined above. */
    ni_def.NI_NUM_TYPES       = 9;

    ni_def.type_name = strvcat({
      'byte'  ; 'short'  ; 'int'     ;
      'float' ; 'double' ; 'complex' ;
      'rgb'   ; 'rgba'   ; 'String' });

    ni_def.type_alias = strvcat({   %/* aliases */
     'uint8'   ; 'int16'   ; 'int32'     ;
     'float32' ; 'float64' ; 'complex64' ;
     'rgb8'    ; 'rgba8'   ; 'CString' });

    % TODO: see how to deal with other types
    undef=@()error('Unsupported type');

    ni_def.type = {...
       @uint8  ; @int16    ; @int32      ; ...
       @single ; @double   ; undef       ; ...
       undef   ; undef     ; @char       };

    ni_def.size_bytes=[...
       1       ; 2          ; 4          ; ...
       4       ; 8          ; NaN        ; ...
       NaN     ; NaN        ; 1          ];

    ni_def.init = 1;

    ni_def.escape={'<'  ,'<' ;...
                   '>'  ,'>' ;...
                   '"','"' ;...
                   ''','''';...
                   '&' ,'&' };


%FINDNLAB Determine indices of specified classes (numeric)
%
%    J = FINDNLAB(A,NLAB)
%
% INPUT
%     A        Dataset
%     NLAB     vector with numerical indices of reqested classes
%
% OUTPUT
%     J        vector of sample indices
%
% DESCRIPTION
% J is a column vector of indices to the objects in A that have one of the
% numeric labels stored in NLAB. Note that NLAB should contain indices to
% the labellist of A, which may be retrieved by LABLIST = GETLABLIST(A).
% This command thereby retrieves the indices to all objects a specific class
% or set of classes.


%% Example
% An example script, it is used to show how to use the different
% functions of the KUKA iiwa matlab toolbox

% First run the following script in Matlab
% Then start the client on the KUKA iiwa controller

% Mohammad SAFEEA, 24th of April 2018

close all,clear all,clc
warning('off')
ip='172.31.1.147'; % The IP of the controller
% start a connection with the server
t_Kuka=net_establishConnection( ip );

if ~exist('t_Kuka','var') || isempty(t_Kuka) || strcmp(t_Kuka.Status,'closed')
  warning('Connection could not be establised, script aborted');
  return;
else
    %% move to initial position
pinit={0,pi*20/180,0,-pi*70/180,0,pi*90/180,0}; % initial confuguration
relVel=0.15; % relative velocity
movePTPJointSpace( t_Kuka , pinit, relVel); % point to point motion in joint space

    %% Get the joints positions
      jPos  = getJointsPos( t_Kuka );
      fprintf('The joints positions of the robot are: \n');
      disp(jPos);
 % jPos =

 %   [-8.6886e-06]    [0.3491]    [9.9110e-05]    [-1.2218]    [-8.1109e-05]    [1.5708]    [7.7778e-05]

      %% Get position roientation of end effector
      fprintf('Cartesian position/orientation of end-effector:\n');
      pos=getEEFPos( t_Kuka );
      disp(pos);
% pos =

%    [536.8023]    [0.0255]    [563.8379]    [-3.1416]    [-1.1624e-04]    [-3.1415]

      %% Get position of end effector
      fprintf('Cartesian position of end-effecotr:\n')
      cpos=getEEFCartesianPosition( t_Kuka );
      disp(cpos);
%cpos =

%    [536.8023]    [0.0254]    [563.8380]
      %% Get orientation of end effector
      fprintf('Cartesian orientation of end-effecotr:\n')
      orie=getEEFCartesianOrientation( t_Kuka );
      disp(orie);
% orie =

%    [-3.1416]    [-1.1606e-04]    [-3.1415]
      %% Get force at end effector
      fprintf('Cartesian force acting at end effector:\n')
      f=getEEF_Force(t_Kuka);
      disp(f);
% f =

%    [-2.6678]    [-0.3954]    [10.5507]
      %% Get moment at end effector
      fprintf('moment at eef\n');
      m=getEEF_Moment(t_Kuka);
      disp(m);
% m =

%    [-0.1500]    [0.3462]    [-0.0949]
      %% turn off the server
       net_turnOffServer( t_Kuka );

       fclose(t_Kuka);
end


function test_num = p00_test_num ( )

%*****************************************************************************80
%
%% P00_TEST_NUM returns the number of test problems.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer TEST_NUM, the number of test problems.
%
  test_num = 40;

  return
end


function disk_integrals_test ( )

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

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

  return
end


function out = isempty(F)
%ISEMPTY   Empty Boolean check for a CHEBFUN3V object.
%   ISEMPTY(F) returns 1 if every component of F is an empty CHEBFUN3V, and
%   return 0 otherwise.

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

if ( isempty(F.components) )
    out = 1;
    return
end

% Take isempty of each component:
out = cellfun(@isempty, F.components, 'UniformOutput', false);
out = all(cell2mat(out));

end


function n = p06_n ( )

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

  return
end


function T = convert_to_table(CPD, domain, evidence)
% CONVERT_TO_TABLE Convert a discrete CPD to a table
% T = convert_to_table(CPD, domain, evidence)
%
% We convert the CPD to a CPT, and then lookup the evidence on the discrete parents.
% The resulting table can easily be converted to a potential.

domain = domain(:);
CPT = CPD_to_CPT(CPD);
odom = domain(~isemptycell(evidence(domain)));
vals = cat(1, evidence{odom});
map = find_equiv_posns(odom, domain);
index = mk_multi_index(length(domain), map, vals);
T = CPT(index{:});
T = T(:);


function C = boundaryConditions(X0, XF)
% C = boundaryConditions(X0, XF)
%
% This function computes the boundary conditions for periodic solutions.
%
% INPUTS:
%   X0 = Initial State
%   XF = Final State
%
% OUTPUTS:
%   C = defect constraint
%

C = X0 - XF;

end


function niederreiter2_test ( )

%*****************************************************************************80
%
%% NIEDERREITER2_TEST tests the NIEDERREITER2 library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 November 2008
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'NIEDERREITER2_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the NIEDERREITER2 library.\n' );

  niederreiter2_test01 ( );
  niederreiter2_test02 ( );
  niederreiter2_test03 ( );
  niederreiter2_test04 ( );
  niederreiter2_test05 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'NIEDERREITER2_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function describe(threecomp)

%Detailed description of threecomp properties
% DESCRIBE(THREECOMP) provides detailed descriptions of threecomp object
% properties and how they are related.
%
%
% ------------------- COORDINATE SYSTEM -------------------------
% The threecomp object is designed to use a familiar spherical polar
% coordinate system in which horizontal direction on Earth is given in
% clockwise degrees from north: north is 0; east is 90; south is 180; and
% west is 270 degrees. Vertical directions are given with respect to
% vertical up. up is 0 degrees; horizontal is 90 degrees; and 180 is down.
%
%
% ------------------ TRACE NAME CONVENTIONS -----------------------
% Trace names follow the convention of network-station-channel-location.
% (Internally, this is enforced via the scnlobject and waveform objects.)
% Station and channel codes have particular importance in threecomp
% objects. A simple check is performed upon initiation to ensure that all
% three traces in each object come from the same seismic station. In other
% words, all three traces must have the same station code. The channel
% codes have specific meaning and users are encouraged to make sure that
% channel names are correct before converting to a threecomp object. The
% threecomp channel code convention adheres to the SEED standard of a
% minimum three character name where the third character represents the
% component orientation. Threecomp requires that the third channel
% characters be: Z-N-E, Z-R-T, or Z-2-1. Modest deviations from these
% channel names are accomodated by the horizontal and vertical orientation
% properties (see below). However, the actual channel names must contain
% one of these character sets.
%
%
% ------------------ COMPONENT ORIENTATIONS ----------------------
% The orientation of each component of trace data is essential to
% performing any type of three component analysis. The safest way to ensure
% that component orientations are correct is to provide them explicitly.
% The THREECOMP function allows users to provide the horizontal and
% vertical orientation of all three channels of data. It is also possible
% to read these parameters automatically from the original waveforms if they
% have been set as properties there. If no orientation information is
% given, THREECOMP will assign default values where possible.
%
% DEFAULT VALUES
% If the component (third character of the channel name) is Z, N, E and no
% explicit orientation is given, then the orientations are assumed to be
%       Z: [0 0]    N:[0 90]    E: [90 90]
% This is equivalent to calling the THREECOMP function with an orientation
% matrix [0 0 0 90 90 90 ; ... ; ... ]. If the components are Z, R, T, and
% a backazimuth is given, then the horizontal components will be aligned
% accordingly. Components of Z, 2, 1 do not have any default orientations.
% Orientations provided as arguments to function THREECOMP, and
% orientations described in the input waveform properties, will override
% default values. For details see horizontal and vertical orientation
% descriptions below.
%
% HORIZONTAL ORIENTATION
% This attribute specifies the orientation of the component in the
% horizontal plane, measured clockwise from North.  For a North-South
% orientation, positive toward the north, the horizontal orientation is 0.
% For East-West orientation with positive to the east, the horizontal
% orientation is 90. Allowable range is 0 to 360.
%
% VERTICAL ORIENTATION
% This attribute measures the angle between the sensitive axis of a
% seismometer and the outward-pointing vertical direction.  For a
% vertically-oriented seismometer, the vertical orientation is 0, or 180
% (to reverse the sense of the instrument). For a horizontally oriented
% component, the vertical orientation is 90. Allowable range is 0 - 180.
%
% RADIAL TRANSVERSE COORDINATE SYSTEM
% Threecomp objects recognize the familiar coordinate system of vertical,
% radial, and transverse (ZRT). In this system the positive radial
% direction (R+) is 180 degrees opposite the backazimuth. The relative
% component orientations in a ZRT coordinate system are the same as in ZNE
% coordinates. That is, the positive transverse direction points 90 degrees
% clockwise from the positive radial direction. For example, for a wave
% arriving from due south on Z-N-E components, there is no rotation and N
% becomes R, while E becomes T.
%
%
% ------------------ PARTICLE MOTION ----------------------
% Particle motions are calculated in a sliding time window. In each window
% the covariance matrix of the three waveform vectors in computed. The
% eigenvectors of the covariance matrix define the dominant orientations of
% the data, while the eigenvalues express the relative amplitudes in each
% of these directions. Conceptually, rectilinearity expresseses the
% relative dominance of the largest eigenvalue (range is 0 to 1). Planarity
% is the degree to which the largest two eigenvalues dominate (range is 0
% to 1). Azimuth and inclination give the spherical polar orientation of
% the largest eigenvector. It is important to note that azimuth and
% inclination only have meaning if the waveforms show a high degree of
% rectilinearity or in some orientations, planarity. It makes sense - think
% about it!
%
% Energy is computed from the trace of the eigenvalue matrix. The
% calculation is performed independent of the data type. The term "energy"
% should be treated carefully however. This term is essentially just the
% square of the total particle velocity. The "energy" units are the square
% of whatever units the input waveforms had. IF the input traces are in
% velocity, then the energy term is the seismic kenetic energy density,
% (smoothed over size of the sliding time window). If the input traces are
% not velocity, then the output cannot be used as a proxy for physical
% energy.

% As defined here, the azimuth range is 0 to 360 degrees measured from
% north. Inclination ranges from 0 (up) to 90 (horizontal). This reference
% frame differs from some in the literature, but is used here because it is
% intuitive; it is consistent through the threecomp toolbox; and, most
% importantly, to match the reference frame used for component
% orientations. See horizontal and vertical orientation, above. For
% mathematical descriptions of the particle motion coefficients, users are
% encouraged to consult the PARTICLEMOTION.M code. It is reasonably short
% and well commented. Note that rectilinearity and planarity have somewhat
% variable definitions in the literature. For the discerning user, parallel
% definitions are included in the PARTICLEMOTION code, but are commented
% out.

help describe


%Figure 1.1       Feedback Control of Dynamic Systems, 5e
%                      Franklin, Powell, Emami

% script to generate figure 1.1
clf
sim('fig1_01bsim',16)
plot(roomtemp(:,1),roomtemp(:,2))
grid on;
axis([0 16 0 70]);
title('Figure 1.1(b) Plot of room temperature and thermostat setting')
hold on
plot(heatin(:,1),10*heatin(:,2))
x=[0 16];
y=[50 50];
plot(x,y)
xlabel('Time (hours)');
ylabel('Temperature (degrees F)');
gtext('Room Temperature')
gtext ('Outside Temperature')
gtext(' Furnace on')
gtext(' Furnace off')


% FORMATFIGURE: Formats Matlab figures
%
% FormatFigure( FIG, FONTNAME, FONTSIZE, FIGSIZE, BORDER )
%
% Formats a figure for presentations or papers.  The font
% style, font size, figure size and border size can all be
% adjusted.  All parameters are optional.
%
% FIG     : Figure handle.
% FONTNAME: Name of the font as a string.
% FONTSIZE: Size of the font (points) as a vector.
%           Format: [axes_labels tick_labels]
% FIGSIZE : Size of the figure (inches) as a vector.
%           Format: [width height]
% BORDER  : Space around the figure (inches) as a vector.
%           Format: [left bottom right top] or
%                   [left/right  botom/top]
%
% Default settings of the inputs are:
%   FIG     : gcf (current figure)
%   FONTNAME: 'Helvetica'
%   FONTSIZE: [18 14]
%   FIGSIZE : [6 6]
%   BORDER  : [0.8 0.5]
%
% Note: Function has a problem settiing the font size of the
% legend sometimes.  If the legend font is the wrong size,
% call this function again.  The second call corrects the
% problem.  I believe this to be a Matlab problem.
%
% Written By  : Jeffrey DiCarlo
% Last updated: 07-26-00

function FormatFigure( fig, fontname, fontsize, figsize, border )

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Format the input parameters.

% Load default paramemters.

if (~exist('fig','var'))
   fig = 0;
end
if (~exist('fontname'))
   fontname = 'Helvetica';
end
if (~exist('fontsize'))
   fontsize = [18 14];
end
if (~exist('figsize'))
   figsize  = [6 6];
end
if (~exist('border'))
   border = [0.8 0.5];
end

% Check the fontsize.

if (length(fontsize) == 1)
   fontsize = [fontsize fontsize];
end

% Check the figure size.

if (length(figsize) == 1)
   figsize = [figsize figsize];
end

% Check the border.

if (length(border) == 2)
   border = [border(1) border(1) border(2) border(2)];
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Get the figure axes.

if (exist('fig') ~= 1 | fig == 0)
   fig = gcf;
end
axs = get( fig, 'CurrentAxes' );

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Get the current figure position.

if (strcmp(get(fig, 'Units'),'inches') == 1)
   pos = get(fig, 'Position');
else
   pos = [1 1 1 1];
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set the figure properties.

set( fig,         'Units', 'inches' );
set( fig,      'Position', [pos(1:2) figsize] );
set( fig, 'PaperPosition', [4.25-figsize(1)/2 5.5-figsize(2)/2 figsize] );
set( fig,         'Color', [1 1 1] );

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set the axes properties.

set( get(axs,  'Title'), 'FontName', fontname, ...
   'FontSize', fontsize(1) );
set( get(axs, 'XLabel'), 'FontName', fontname, ...
	'FontSize', fontsize(1) );
set( get(axs, 'YLabel'), 'FontName', fontname, ...
   'FontSize', fontsize(1) );
set( get(axs, 'ZLabel'), 'FontName', fontname, ...
   'FontSize', fontsize(1) );
set( axs,                'FontName', fontname, ...
   'FontSize', fontsize(2) );

set( axs,    'Units', 'inches' );
set( axs, 'Position', [border(1:2) (figsize-border(1:2)-border(3:4))] );


function title = p05_title ( )

%*****************************************************************************80
%
%% P05_TITLE returns a title for problem 05.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Per-Olof Persson and Gilbert Strang,
%    A Simple Mesh Generator in MATLAB,
%    SIAM Review,
%    Volume 46, Number 2, June 2004, pages 329-345.
%
%  Parameters:
%
%    Output, string TITLE, a title for the problem.
%
  title = '#5: The horn.';

  return
end


function calpak_test327 ( )

%*****************************************************************************80
%
%% CALPAK_TEST327 tests MONTH_CAL_STORE_COMMON.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 March 2013
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALPAK_TEST327\n' );
  fprintf ( 1, '  For the Common calendar:\n' );
  fprintf ( 1, '  MONTH_CAL_STORE_COMMON writes the day numbers for\n' );
  fprintf ( 1, '  a monthly calendar into a data structure.\n' );

  y = 1984;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'Calendar:\n' );
  fprintf ( 1, '  Year = %d\n', y );

  for m = 1 : 12

    lines = month_cal_store_common ( y, m );
    [ r, ~ ] = size ( lines );
    fprintf ( 1, '\n' );
    fprintf ( 1, '  Month = %d\n', m );
    fprintf ( 1, '\n' );
    for i = 1 : r
      fprintf ( 1, '  %d    %s\n', i, lines(i,:) );
    end

  end

  return
end


function zvalues = interactivedendrogramvalues(fig)
% zvalues = interactivedendrogramvalues(fig)
% from http://www.mathworks.com/help/techdoc/ref/datacursormode.html#bsawkea-7
dcm_obj = datacursormode(fig);
stop = 0;
inp = input('How many nodes?\n');
for ii=1:inp

    set(dcm_obj,'DisplayStyle','datatip',...
        'SnapToDataVertex','off','Enable','on')

    disp('Click on a node, then press Return.')
    figure(fig)
    pause                            % Wait while the user does this.
    c_info = getCursorInfo(dcm_obj);
    zvalues(ii)=c_info.Position(2);
    fprintf('Zvalue:%g\n', zvalues(ii))
end

% while ~stop
%     set(dcm_obj,'DisplayStyle','datatip',...
%         'SnapToDataVertex','off','Enable','on')
%
%     disp('Click on a node, then press Return.')
%     pause                            % Wait while the user does this.
%
%     c_info = getCursorInfo(dcm_obj);
%     zvalues(ii)=c_info.Position(2);
%     ii=ii+1;
%
%     inp = input('More? Yes = [anything but n]/ No = [n]\n','s');
%
%     if strcmp(inp,'n')
%         stop=1;
%     end
% end


function [ nodeco, nodecotype, elnode, elnodetype, bdynde, bdyndetype ] = ...
  mesh2d_extract ( filename )

%*****************************************************************************80
%
%% MESH2D_EXTRACT extracts the information from the mesh file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 May 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string FILENAME, the name of the MAT file.
%
%    Output, real NODECO(NODE_NUM,2), the node coordinates.
%
%    Output, integer NODECOTYPE(NODE_NUM,1), the node type.
%
%    Output, integer ELNODE(ELEMENT_NUM,3), the node indices that form
%    each element.
%
%    Output, integer ELNODETYPE(ELEMENT_NUM,1), the element type.
%
%    Output, integer BDYNDE(BDY_NUM,2), pairs of nodes that form the boundary.
%
%    Output, integer BDYNDETYPE(BDY_NUM), the boundary condition type.
%
  input = fopen ( filename );

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

  line = fgets ( input );
  [ abc, count ] = sscanf ( line, '%d%d%d' );

  node_num = abc(1);
  element_num = abc(2);
  bdy_num = abc(3);

  nodeco = zeros ( node_num, 2 );
  nodecotype = zeros ( node_num, 1 );

  for node = 1 : node_num
    line = fgets ( input );
    [ abc, count ] = sscanf ( line, '%f%f%d' );
    nodeco(node,1) = abc(1);
    nodeco(node,2) = abc(2);
    nodecotype(node) = abc(3);
  end

  elnode = zeros ( element_num, 3 );
  elnodetype = zeros ( element_num,1 );

  for element = 1 : element_num
    line = fgets ( input );
    [ abcd, count ] = sscanf ( line, '%d%d%d%d' );
    elnode(element,1) = abcd(1);
    elnode(element,2) = abcd(2);
    elnode(element,3) = abcd(3);
    elnodetype(element) = abcd(4);
  end

  bdynde = zeros ( bdy_num, 2 );
  bdyndetype = zeros ( bdy_num, 1 );

  for bdy = 1 : bdynde
    line = fgets ( input );
    [ abc, count ] = sscanf ( line, '%d%d%d' );
    bdynde(node,1) = abc(1);
    bdynde(node,2) = abc(2);
    bdyndetype(node) = abc(3);
  end

  fclose ( input );

  return
end


function pass = test_merge(pref)

if ( nargin < 1 )
    pref = chebfunpref();
end

d = domain.merge([-inf 1 10 inf], [-inf 1 5 inf]);
pass = all(d == [-Inf     1     5    10   Inf]);

end


function [DataMat, ChannelMat] = in_data_ws_csv(DataFile)
% IN_DATA_WS_CSV: Imports a Wearable Sensing CSV file.

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

% ===== READ CSV =====
bst_progress('text', 'Reading csv file...');
% Open file
fid = fopen(DataFile, 'r');
if (fid == -1)
    error('Cannot open file.');
end
% Read header line with channel names
Labels = [];
while 1
    csvLine = fgetl(fid);
    % End of file
    if (csvLine == -1)
        break;
    % Empty line
    elseif isempty(csvLine)
        continue;
    % Comment line
    elseif (csvLine(1) == '#')
        continue;
    % Header line with channel names
    elseif (nnz(csvLine == ',') > 0)
        Labels = strtrim(str_split(csvLine, ','));
        break;
    end
end
% Channel names not found
if isempty(Labels)
    fclose(fid);
    error('Header line with channel names not found in CSV.');
end
% Default reading pattern
cellFormat = repmat({'%f'}, 1, length(Labels));

% Final reading format for the rest of the file
strFormat = sprintf('%s ', cellFormat{:});
strFormat(end) = [];
% Read the rest of the file
RecMat = textscan(fid, strFormat, 'Delimiter', ',');
% Close file
fclose(fid);
% Check for errors
if isempty(RecMat) || isempty(RecMat{1})
    error('File could not be read as CSV.');
end
% If the last line is incomplete: delete it
lastFullRow = length(RecMat{end});
if (length(RecMat{1}) > lastFullRow)
    for i = 1:length(RecMat)
        if (length(RecMat{i}) > lastFullRow)
            RecMat{i} = RecMat{i}(1:lastFullRow);
        end
    end
end

% ===== GET TIME =====
bst_progress('text', 'Processing time stamps...');
% Find timestamp
iTimestamp = find(strcmpi(Labels, 'Time'));
if isempty(iTimestamp)
    error('Missing time column.');
end
% Convert time stamps to datenum
rawTime = RecMat{iTimestamp}';
% Set t=0 at the first sample
rawTime = rawTime - rawTime(1);
% Detect sampling frequency
sfreq = 1./mean(diff(rawTime));
sfreq = round(sfreq * 100) ./ 100;
% Reconstructed file time
Time = (0:length(rawTime)-1) ./ sfreq;

% ===== GET DATA =====
bst_progress('text', 'Reconstructing data matrix...');
% Get other useless channels
iComments = find(strcmpi(Labels, 'Comments'));
% Find a column that has non-empty values that is not a special column
iColAll = setdiff(1:length(Labels), [iTimestamp, iComments]);
iColRec = iColAll(~cellfun(@(c)all(isnan(c)), RecMat(iColAll)));
% Rebuild data matrix
rawF = [RecMat{iColRec}]';
% Remove other missing values: replacing with values
iMissing = find(any(isnan(rawF),1));
if ~isempty(iMissing)
    disp(sprintf('BST> Muse: Missing data at %d time points. Replacing with zeros...', length(iMissing)));
    rawF(isnan(rawF)) = 0;
end
nChannels = size(rawF,1);

% % ===== DETECT EVENTS =====
% % Find events
% iTimeEvt = find(all(isnan(rawF),1));
% % Get event timing
% evtTime = rawTime(iTimeEvt);
% % Get event labels
% if ~isempty(iElements) && ~all(cellfun(@isempty, RecMat{iElements}(iTimeEvt)))
%     evtLabels = cellfun(@(c)strrep(c, '/muse/elements/', ''), RecMat{iElements}(iTimeEvt), 'UniformOutput', 0);
% else
%     evtLabels = repmat({'Trigger'}, length(iTimeEvt), 1);
% end
% Remove events from data matrix
% rawF(:,iTimeEvt) = [];
% rawTime(iTimeEvt) = [];

% ===== BRAINSTORM DATA =====
% Get file name
[fPath, fBase, fExt] = bst_fileparts(DataFile);
% Create empty structure
DataMat = db_template('DataMat');
% Fill structure
DataMat.F           = rawF .* 1e-6;  % Data stored in microV
DataMat.Time        = Time;
DataMat.Comment     = fBase;
DataMat.ChannelFlag = ones(nChannels, 1);
DataMat.nAvg        = 1;
DataMat.Device      = 'Wearable Sensing';
% % Add events
% if ~isempty(iTimeEvt)
%     % Initialize events list
%     DataMat.Events = repmat(db_template('event'), 0);
%     % Events list
%     uniqueEvt = unique(evtLabels);
%     % Build events list
%     for iEvt = 1:length(uniqueEvt)
%         % Find all the occurrences of this event
%         iOcc = find(strcmpi(uniqueEvt{iEvt}, evtLabels));
%         % Set event
%         DataMat.Events(iEvt).label    = strtrim(uniqueEvt{iEvt});
%         DataMat.Events(iEvt).times    = unique(round(evtTime(iOcc) .* sfreq)) ./ sfreq;
%         DataMat.Events(iEvt).epochs   = 1 + 0*DataMat.Events(iEvt).times;
%         DataMat.Events(iEvt).select   = 1;
%         DataMat.Events(iEvt).channels = [];
%         DataMat.Events(iEvt).notes    = [];
%     end
% end

% ===== CHANNEL FILE =====
ChannelMat = db_template('channelmat');
for i = 1:nChannels
    % Split type/name
    ch = Labels{iColAll(i)};
    ChannelMat.Channel(i).Name = ch;
    switch (ch)
        case 'Trigger'
            ChannelMat.Channel(i).Type = 'Trigger';
        case 'Event'
            ChannelMat.Channel(i).Type = 'Event';
        case 'Time_Offset'
            ChannelMat.Channel(i).Type = 'Time_Offset';
        case 'CM'
            ChannelMat.Channel(i).Type = 'CM';
        case {'ADC_Status', 'ADC_Sequence'}
            ChannelMat.Channel(i).Type = 'Trigger';
        otherwise
            ChannelMat.Channel(i).Type = 'EEG';
    end
    ChannelMat.Channel(i).Loc     = [];
    ChannelMat.Channel(i).Orient  = [];
    ChannelMat.Channel(i).Comment = '';
    ChannelMat.Channel(i).Weight  = 1;
end


function l = s_to_l ( s )

%*****************************************************************************80
%
%% S_TO_L reads a logical value from a string.
%
%  Discussion:
%
%    There are several ways of representing logical data that this routine
%    recognizes:
%
%      False   True
%      -----   ----
%
%      0       1
%      F       T
%      f       t
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 December 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string S, the string to be read.
%
%    Output, integer L, the logical value read from the string.
%
  s_length = length ( s );

  for i = 1 : s_length
    if ( s(i) == '0' || s(i) == 'F' || s(i) == 'f' )
      l = 0;
      return
    elseif ( s(i) == '1' || s(i) == 'T' || s(i) == 't' )
      l = 1;
      return
    end
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, 'S_TO_L - Fatal error!\n' );
  fprintf ( 1, '  The input string did not contain logical data.\n' );
  error ( 'S_TO_L - Fatal error!' );
end


function plotByColorMap(time,velocity,colorVar)
% TODO
%
if ndims(time) ~= ndims(velocity)
    error('Time and Velocity are not same size')
end

% Is there a current figure?
h = get(0,'CurrentFigure');
if isempty(h)
  h = figure;
end

% set colormap environment
colormap('autumn');
cmap = colormap;
[cmapVar, cax] = mcColorMap(colorVar,cmap);
figure(h), set(h,'Colormap',cmap), caxis(cax), colorbar, hold on

% add lines to plot
for i = 1:length(time)
   line(time{i},velocity{i},'color',cmapVar(i,:))
end

% add labels
xlabel('Time (s)')
ylabel('Angular Velocity (rpm)')


function n = p14_n ( )

%*****************************************************************************80
%
%% P14_N returns the number of variables for problem 14.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 March 2000
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer N.  If N is positive, N represents the
%    only legal value for N for this problem.  If N is
%    negative, the absolute value of N is the least legal
%    value of N, but other values are allowable.
%
  n = - 1;

  return
end


function test_suite = test_graphDiameter
%TEST_GRAPHDIAMETER  One-line description here, please.
%
%   output = test_graphDiameter(input)
%
%   Example
%   testGraphDiameter
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2011-05-19,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.

test_suite = functiontests(localfunctions);

function testGraph02(testCase) %#ok<*DEFNU>

[nodes, edges] = createTestGraph02;
diam = graphDiameter(nodes, edges);

exp = 6;
testCase.assertEqual(exp, diam);


function value = s_scrabble_points ( s )

%*****************************************************************************80
%
%% S_SCRABBLE_POINTS returns the Scrabble point value of a string.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 January 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string S, the string.
%
%    Output, integer S_SCRABBLE_POINTS, the point value of
%    the string.
%
  s_length = length ( s );

  value = 0;
  for i = 1 : s_length
    value = value + ch_scrabble_points ( s(i:i) );
  end

  return
end


function in = scn_mat_conform(in)
% :Usage:
% ::
%
%     function in = scn_mat_conform(in)
%
% sets flipping to 0 (no flip) in SPM2 and adjusts mat file accordingly
% input in spm-style mat file or struct with .mat or .M fields
%
% ..
%    tor wager, dec 06
% ..

    global defaults

    if isstruct(in)
        if isfield(in,'mat')
            in.mat = scn_mat_conform(in.mat);
        end

        if isfield(in,'M')
            in.M = scn_mat_conform(in.M);
        end

        return
    end

    if in(1) < 0
        disp('Warning: Image has negative x voxel size, indicating ''flipped'' in SPM.')
        disp('This will be changed to positive. This program does not do any image flipping.')

        in(1) = abs(in(1));     % voxel size
        in(1,4) = -(in(1,4));   % origin offset
    end

    if isempty(defaults)
        spm_defaults
    end

    if defaults.analyze.flip
        disp('Warning: Setting defaults.analyze.flip to 0.  No flipping.')
        defaults.analyze.flip = 0;
    end

    return


classdef STL10 < datasets.Dataset
%STL10 STL-10 dataset
%   Encapsulates the STL-10 dataset for training.
%
%   D = datasets.STL10('/data/stl') loads the STL-10 dataset from the
%   directory '/data/stl'. The dataset can be downloaded from:
%   https://cs.stanford.edu/~acoates/stl10/
%
%   D.train() returns a cell array with mini-batches, from the shuffled
%   training set. Each mini-batch consists of a set of indexes.
%
%   D.val() returns a cell array with mini-batches, from the validation set
%   (without shuffling). Each mini-batch consists of a set of indexes.
%
%   [IMAGES, LABELS] = D.get(BATCH) returns a tensor of images and the
%   corresponding labels for the given mini-batch BATCH. The images are
%   always mean-centered (by subtracting D.dataMean).
%
%   datasets.STL10(...,'option', value, ...) sets the following properties:
%
%   `batchSize`:: 128
%     The batch size.
%
%   `partialBatches`:: false
%     Whether partial batches are returned (which can happen for the last
%     batch in a set, if the batch size does not divide the set size).
%
%   `small`:: false
%     Loads smaller images with size 48x48, instead of the original 96x96.

% Copyright (C) 2018 Joao F. Henriques, Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

  properties
    images  % images tensor
    dataMean  % image mean
    labels  % labels (1 to 10)
    labelNames  % string name associated with each numeric label
    sets  % set identities (1 for training, 3 for test)
    folds  % identities of original training folds as defined in the dataset

    small = false  % downsample images 2x
  end

  methods
    function o = STL10(dataDir, varargin)
      % parse generic Dataset arguments
      varargin = o.parseGenericArgs(varargin) ;

      % parse arguments specific to this dataset
      vl_parseprop(o, varargin, {'small'}) ;

      % load object from memory cache if possible
      persistent s
      if ~isempty(s) && isequal(o.small, s.small)
        [o.images, o.dataMean, o.labels, o.labelNames, o.sets, o.folds] = ...
          deal(s.images, s.dataMean, s.labels, s.labelNames, s.sets, s.folds);

      else
        % otherwise, create from scratch
        o.loadRawData(dataDir);

        % save to cache
        [s.images, s.dataMean, s.labels, s.labelNames, s.sets, s.folds, s.small] = ...
          deal(o.images, o.dataMean, o.labels, o.labelNames, o.sets, o.folds, o.small);
      end
    end

    function [images, labels] = get(o, idx)
      % return a single batch (may be wrapped in a cell)
      if iscell(idx) && isscalar(idx)
        idx = idx{1} ;
      end
      images = (single(o.images(:,:,:,idx)) - o.dataMean) / 255;
      labels = o.labels(idx);
    end
  end

  methods (Access = protected)
    function loadRawData(o, data_dir)
      % labeled training data
      s = load([data_dir '/train.mat']);
      data = convert(s.X);
      labels = s.y(:);
      classes = s.class_names;
      folds = s.fold_indices;

      % unlabeled training data
      s = load([data_dir '/unlabeled.mat']);
      data = cat(4, data, convert(s.X));
      labels = [labels; zeros(size(s.X, 1), 1)];

      set = ones(size(labels));

      % labeled test data
      s = load([data_dir '/test.mat']);
      data = cat(4, data, convert(s.X));
      labels = [labels; s.y(:)];
      set = [set; 3 * ones(size(s.X, 1), 1)];

      % resize by 1/2 with bilinear interpolation
      if o.small
        data = uint16(data);  % avoid overflow
        data = (data(1:2:end,1:2:end,:,:) + data(2:2:end,1:2:end,:,:) + ...
                data(1:2:end,2:2:end,:,:) + data(2:2:end,2:2:end,:,:)) / 4;
        data = uint8(data);
      end

      o.images = data;
      o.labels = labels;  %#ok<*PROPLC>
      o.labelNames = classes;
      o.sets = set;
      o.folds = folds;

      o.dataMean = single(mean(data(:,:,:,set == 1), 4));

      % train and validation sample indexes
      o.trainSet = find(set == 1);
      o.valSet = find(set == 3);
    end
  end
end

% simple helper function to convert STL-10 array to MatConvNet format
function X = convert(X)
  X = permute(reshape(X, [], 96, 96, 3), [2:4, 1]);
end


function x = mysqueeze(x)
% Like squeeze(x), but row vectors become columns.

% Written by Thomas P Minka

s = size(x);
dim = find(s==1);
if ~isempty(dim)
  s(dim) = [];
  % [1 1] handles special cases
  x = reshape(x,[s 1 1]);
end


function [retX,retY] = get_xy(dat,ind)

%   get_xy(data)           returns X and Y matrices of the data_global object
%   get_xy(data,indexes)   returns X and Y matrices of the data_global object for given
%                           indexes

global X;
global Y;

if nargin==1
  if isempty(dat.myX)
      ind=[1:length(dat.index)];
  else
      ind=[1:size(dat.myX,1)];
  end;
end;
if ~isempty(dat.myX)
  retX=dat.myX(ind,:);
else
  retX=X(dat.index(ind),dat.findex);
end
if ~isempty(dat.myY)
  retY=dat.myY(ind,:);
else
  retY=Y(dat.index(ind),:);
end


% STD_RMDAT - remove datasets from STUDY
%
% Usage:
%   >> [STUDY,ALLEEG] = std_rmdat(STUDY, ALLEEG, 'key', val);
%
% Inputs:
%   STUDY      - EEGLAB STUDY set
%   ALLEEG     - vector of the EEG datasets included in the STUDY structure
%
% Optional inputs:
%   'datinds'     - [integer array] indices of datasets to remove
%   'pntsrange'   - [min max] minimum and maximum of samples. Default is
%                   [0 Inf] (no constraint)
%   'chanrange'   - [min max] minimum and maximum of channels. Default is
%                   [0 Inf] (no constraint)
%   'sraterange'  - [min max] minimum and maximum for sampling rate. Default is
%                   [0 Inf] (no constraint)
%   'trialrange'  - [min max] minimum and maximum of trials. Default is
%                   [1 Inf]
%   'rmvarvalues' - {'string' range} remove datasets having variable value
%                   in the selected range. May also be {'string' 'value'}
%                   for non-numerical variables.
%   'keepvarvalues' - {'string' range} keep datasets having variable value
%                   in the selected range. May also be {'string' 'value'}
%                   for non-numerical variables.
%   'subjectind'  - [integer array] keep only specific subject indices in
%                   STUDY.subject. To remove or keep specificy subjects,
%                   use 'rmvarvalues' and 'keepvarvalues'
%   'checkeventtype' - [cell|array|string] check event type are present.
%   'numeventrange' - [min max] range for number of event of type above.
%                    Default is [1 Inf].
%
% Inputs:
%   STUDY      - EEGLAB STUDY set updated. The fields which is created or
%                updated is STUDY.datasetinfo.trialinfo
%
% Authors: Arnaud Delorme, SCCN/INC/UCSD, July 2022

% Copyright (C) Arnaud Delorme arno@ucsd.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

function [STUDY, ALLEEG, rmDats] = std_rmdat(STUDY, ALLEEG, varargin)

if nargin < 3
    help std_rmdat;
    return;
end

g = finputcheck( varargin, { ...
    'datinds'         'integer'  {} []; ...
    'chanrange'       'integer'  {} [0 Inf]; ...
    'pntsrange'       'integer'  {} [0 Inf]; ...
    'sraterange'      'float'    {} [0 Inf]; ...
    'trialrange'      'float'    {} [1 Inf]; ...
    'checkeventtype'  ''         {} []; ...
    'numeventrange'   'integer'  {} 1; ...
    'subjectind'   'integer'     {} []; ...
    'rmvarvalues'     'cell'     {} {}; ...
    'keepvarvalues'   'cell'     {} {} }, 'std_rmdat');
if isstr(g)
    error(g);
end

allPnts   = [ALLEEG.pnts];
allSrate  = [ALLEEG.srate];
allChans  = [ALLEEG.nbchan];
allTrials = [ALLEEG.trials];

% check pnts range
rmDats = zeros(1, length(allPnts));
if ~isempty(g.datinds)
    rmDats(g.datInds) = 1;
end
rmDats = g.pntsrange(1)  > allPnts   | allPnts   > g.pntsrange(2)  | rmDats;
rmDats = g.sraterange(1) > allSrate  | allSrate  > g.sraterange(2) | rmDats;
rmDats = g.chanrange(1)  > allChans  | allChans  > g.chanrange(2)  | rmDats;
rmDats = g.trialrange(1) > allTrials | allTrials > g.trialrange(2) | rmDats;

% check subject indices
% ---------------------
if ~isempty(g.subjectind)
    if ~isempty(g.keepvarvalues)
        error('Cannot use ''subjectind'' and ''keepvarvalues'' at the same time')
    end
    g.keepvarvalues = { 'subject' STUDY.subject(g.subjectind) };
end

% check variable name values
% --------------------------
if ~isempty(g.rmvarvalues)
    varName   = g.rmvarvalues{1};
    varValues = g.rmvarvalues{2};
    allValues = { STUDY.datasetinfo.(varName) };
    if ischar(varValues)
        allValues = cellfun(@num2str, allValues, 'uniformoutput', false);
        rmDats = rmDats | cellfun(@(x)isequal(x, varValues),  allValues);
    elseif iscell(varValues)
        for iCell = 1:length(varValues)
            allValues = cellfun(@num2str, allValues, 'uniformoutput', false);
            rmDats = rmDats | cellfun(@(x)isequal(x, varValues{iCell}),  allValues);
        end
    elseif length(varValues) ~= 2
        error('When providing nmumerical input for variable selection, there must be 2 values - min and max');
    else
        allValues = cellfun(@(x)fastif(ischar(x), str2double(x), x), allValues);
        rmVals = varValues(1) <= allValues & allValues <= varValues(2); % to deal with NaNs
        rmDats = rmDats | rmVals;
    end
end
if ~isempty(g.keepvarvalues)
    varName   = g.keepvarvalues{1};
    varValues = g.keepvarvalues{2};
    allValues = { STUDY.datasetinfo.(varName) };
    if ischar(varValues)
        allValues = cellfun(@num2str, allValues, 'uniformoutput', false);
        rmDats = rmDats | ~cellfun(@(x)isequal(x, varValues),  allValues);
    elseif iscell(varValues)
        keepDats = zeros(1, length(allPnts));
        for iCell = 1:length(varValues)
            allValues = cellfun(@num2str, allValues, 'uniformoutput', false);
            keepDats = keepDats | cellfun(@(x)isequal(x, varValues{iCell}),  allValues);
        end
        rmDats = rmDats | ~keepDats;
    elseif length(varValues) ~= 2
        error('When providing nmumerical input for variable selection, there must be 2 values - min and max');
    else
        allValues = cellfun(@(x)fastif(ischar(x), str2double(x), x), allValues);
        keepVals = varValues(1) <= allValues & allValues <= varValues(2); % to deal with NaNs
        rmDats = rmDats | ~keepVals;
    end
end

% check event type present
% --------------------------
if ~isempty(g.checkeventtype)
    if ischar(g.checkeventtype) g.checkeventtype = { g.checkeventtype }; end
    rmDatEvents = zeros(1, length(ALLEEG));
    for iDat = 1:length(ALLEEG)
        if isfield(ALLEEG(iDat).event, 'type')
            curEventTypes = { ALLEEG(iDat).event.type };
            if ischar(curEventTypes{1})
                for iType = 1:length(g.checkeventtype)
                    inds = strmatch(g.checkeventtype{iType}, curEventTypes, 'exact');
                    if length(inds) < g.numeventrange(1) || length(inds) > g.numeventrange(2)
                        rmDatEvents(iDat) = true;
                    end
                end
            else
                % numerical or string event types
                curEventTypes = [ ALLEEG(iDat).event.type ];
                for iType = 1:length(g.checkeventtype)
                    inds = find(g.checkeventtype(iType) == curEventTypes);
                    if length(inds) < g.numeventrange(1) || length(inds) > g.numeventrange(2)
                        rmDatEvents(iDat) = true;
                    end
                end
            end
        end
    end
    rmDats = rmDats | rmDatEvents;
end

if sum(rmDats) > 0
    fprintf('%d dataset meet the criteria for removal and have been removed\n', sum(rmDats));
    ALLEEG(rmDats) = [];
    STUDY.datasetinfo(rmDats) = [];
    for iDat = 1:length(STUDY.datasetinfo)
        STUDY.datasetinfo(iDat).index = iDat;
    end
else
    fprintf('No dataset meet the criteria for removal and have been removed\n');
end
STUDY.subject = {};
STUDY = std_checkset(STUDY, ALLEEG);

for iDesign = 1:length(STUDY.design)
    STUDY.design(iDesign).cases.value = intersect(STUDY.design(iDesign).cases.value, STUDY.subject);
end


% Compile MEX files for Synchrosqueezing toolbox
%
%---------------------------------------------------------------------------------
%    Synchrosqueezing Toolbox
%    Authors: Eugene Brevdo (http://www.math.princeton.edu/~ebrevdo/)
%---------------------------------------------------------------------------------
mex curve_ext.c
mex synsq_cwt_squeeze_mex.c
mex diff_mex.c


classdef (Abstract) Rx  < adi.common.RxTx & matlab.system.mixin.SampleTime
    % Rx: Common shared functions between receiver classes
    properties(Constant, Hidden, Logical)
        %EnableCyclicBuffers Enable Cyclic Buffers
        %   Not used for RX
        EnableCyclicBuffers = false;
    end

    methods (Hidden, Access = protected)

        function sts = getSampleTimeImpl(obj)
            sts = createSampleTime(obj,'Type','Discrete',...
                'SampleTime',obj.SamplesPerFrame/obj.SamplingRate);
        end

    end

    methods (Access=protected)

        function numOut = getNumOutputsImpl(~)
            numOut = 2;
        end

        function names = getOutputNamesImpl(~)
            % Return output port names for System block
            names = {'data','valid'};
        end

        function sizes = getOutputSizeImpl(obj)
            % Return size for each output port
            sizes = {[obj.SamplesPerFrame,obj.channelCount],[1,1]};
        end

        function types = getOutputDataTypeImpl(~)
            % Return data type for each output port
            types = ["int16","logical"];
        end

        function complexities = isOutputComplexImpl(obj)
            % Return true for each output port with complex data
            complexities = {obj.ComplexData,false};
        end

        function fixed = isOutputFixedSizeImpl(~)
            % Return true for each output port with fixed size
            fixed = {true,true};
        end
    end

    methods (Hidden, Access = protected)

        function [data,valid] = stepImpl(obj)
            % [data,valid] = rx() returns data received from the radio
            % hardware associated with the receiver System object, rx.
            % The output 'valid' indicates whether the object has received
            % data from the radio hardware. The first valid data frame can
            % contain transient values, resulting in packets containing
            % undefined data.
            %
            % The output 'data' will be an [NxM] vector where N is
            % 'SamplesPerFrame' and M is the number of elements in
            % 'EnabledChannels'. 'data' will be complex if the devices
            % assumes complex data operations.

            % Get the data
            if obj.ComplexData
                kd = 1;
                ce = length(obj.EnabledChannels);
                [dataRAW, valid] = getData(obj);
                data = complex(zeros(obj.SamplesPerFrame,ce));
                for k = 1:ce
                    data(:,k) = complex(dataRAW(kd,:),dataRAW(kd+1,:)).';
                    kd = kd + 2;
                end
            else
                [data, valid] = getData(obj);
                data = data.';
            end

        end

    end

end