function scimat = scimat_squeeze(scimat, todouble)
% SCIMAT_SQUEEZE  Remove dummy dimension from SCIRUNNRRD struct so that it
% becomes a SCIMAT struct.
%
% SCIMAT = scimat_squeeze(SCIRUNNRRD)
%
%   When the application Seg3D saves images to Matlab format, it saves them
%   to a SCIRUNNRRD struct, which is basically SCIMAT with a dummy
%   dimension.
%
%   SCIMAT is a struct that contains a 3D volume. We use SCIMAT structs
%   widely in Gerardus, because that way we have the image data and
%   metainformation (e.g. voxel size) together in the same
%   variable. For details on SCIMAT structs, see "help scimat".
%
%   This function removes the dummy dimension.
%
% SCIMAT = scimat_squeeze(..., TODOUBLE)
%
%   TODOUBLE is a flag to convert the image data from uint8 to double. This
%   is useful for image processing, but the data will be 8 times larger. By
%   default, TODOUBLE=false.
%
% See also: scimat_load.

% Author: Ramon Casero <rcasero@gmail.com>
% Copyright © 2010-2014 University of Oxford
% Version: 0.2.1
%
% University of Oxford means the Chancellor, Masters and Scholars of
% the University of Oxford, having an administrative office at
% Wellington Square, Oxford OX1 2JD, UK.
%
% This file is part of Gerardus.
%
% 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. The offer of this
% program under the terms of the License is subject to the License
% being interpreted in accordance with English Law and subject to any
% action against the University of Oxford being under the jurisdiction
% of the English Courts.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

% check arguments
narginchk(1, 2);
nargoutchk(0, 1);

% defaults
if (nargin < 2 || isempty(todouble))
    todouble = false;
end

% remove dummy dimension
scimat.data = squeeze(scimat.data);
if (length(scimat.axis) > 3)
    scimat.axis = scimat.axis(2:end);
end

% convert data to double
if (todouble)
    scimat.data = double(scimat.data);
end


function shape = load_ply(filename)

[tri,vert] = ply_read(filename, 'tri');
shape = {};
shape.VERT = vert';
shape.TRIV = tri';

shape.n = size(shape.VERT,1);
shape.m = size(shape.TRIV,1);

end


function hole_num = p07_hole_num ( )

%*****************************************************************************80
%
%% P07_HOLE_NUM counts the holes in problem 07.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer HOLE_NUM, the number of holes.
%
  hole_num = 0;

  return
end


classdef TestCircle
    %TestCircle

    methods (Static)
        function test_circle
            img = 255*ones(64,64,3,'uint8');
            out = cv.circle(img, [32,32], 20);
            validateattributes(out, {class(img)}, {'size',size(img)});
        end

        function test_options
            img = zeros([50 50 3],'uint8');
            out = cv.circle(img, [25 25], 15, ...
                'Color',[255 0 0], 'Thickness','Filled', 'LineType',8);
            validateattributes(out, {class(img)}, {'size',size(img)});
        end

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

end


%  smin smooth approximation of min(x,0)
%
%  ::
%
%
%  Args:
%
%  Returns:
%     :
%
%  Note:
%
%  Example:
%
%     See also:
%


function [ALLEEG cfg handles] = pop_vis_TimeFreqGrid(ALLEEG,typeproc,varargin)
%
% Create a Time-Frequency Grid from a connectivity matrix. For details on
% the Interactive Time-Frequency Grid see [1].
% This function generates an interactive GUI. Default GUI options can be
% pre-specified as <name, value> pairs as listed in vis_TimeFreqGrid().
% Alternately, an arg configuration structure can be provided in lieu of
% name, value pairs (see Example below).
%
% Inputs:
%
%       ALLEEG:     Array of 1 or 2 EEGLAB datasets. If 2 sets, this function
%                   plots difference (and Conn must also be 1x2 array of
%                   structs)
%       Conn:       SIFT Connectivity Structure
%
% Optional:
%
%       <Name, Value> pairs as defined in vis_TimeFreqGrid()
%
% Outputs:
%
%       cfg:                          Argument specification struct. Can be
%                                     supplied in lieu of <name, value>
%                                     argument pairs to exactly reconstruct
%                                     TF-grid.
%       figureHandles:                Handles to figures.
%
% Example:  >> cfg = pop_vis_TimeFreqGrid(ALLEEG);    % now select some options from GUI and click "OK"
%           >> vis_TimeFreqGrid(ALLEEG,cfg);          % TF-grid will now be recreated from command-line
%                                                     % exactly as specified in GUI
%
% See Also: vis_TimeFreqGrid()
%
% References:
%
% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):
%   Theoretical Handbook and User Manual. Chapter 6.
%   Available at: http://www.sccn.ucsd.edu/wiki/Sift
%
% Author: Tim Mullen, 2010, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

% This function is part of the Source Information Flow Toolbox (SIFT)
%
% 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, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

handles = [];

if length(varargin) == 1 && isempty(varargin{1})
    varargin = {};
end

if nargin<2
    typeproc = 0;
end

fcnName     = strrep(mfilename,'pop_','');
fcnHandle   = str2func(fcnName);

% check the dataset
res = hlp_checkeegset(ALLEEG,{'conn'});
if ~isempty(res)
    error(['SIFT:' fcnName],res{1});
end

% check if we have statistics
hasStats = isempty(hlp_checkeegset(ALLEEG,{'stats'}));

% pass in stats as separate option
if hasStats, varargin = [varargin 'Stats',ALLEEG(1).CAT.Stats]; end

if isfield(ALLEEG(1).CAT.configs,fcnName)
    % get default configuration (from prior use) and merge with varargin
    varargin = [hlp_struct2varargin(ALLEEG(1).CAT.configs.(fcnName)) varargin];
end

for cnd=1:length(ALLEEG);
    % make node labels a row array
    ALLEEG(cnd).CAT.curComponentNames = ALLEEG(cnd).CAT.curComponentNames(:)';
end

% extract the Connectivity structures
for cnd=1:length(ALLEEG);
    Conn(cnd) = ALLEEG(cnd).CAT.Conn;
end

if strcmpi(typeproc,'nogui')
    % get the config from function
    cfg = arg_tovals(arg_report('rich',fcnHandle,[{'EEG',ALLEEG,'Conn',Conn},varargin]),false);
else
    % render the GUI
    [PGh figh] = feval(['gui_' fcnName],ALLEEG,Conn,varargin{:});

    if isempty(PGh)
        % user chose to cancel
        cfg = [];
        return;
    end

    % get the specification of the PropertyGrid
    ps = PGh.GetPropertySpecification;
    cfg = arg_tovals(ps,false);
end

drawnow;

if strcmpi(typeproc,'cfg_only')
    return;
end

% execute the low-level function
if length(ALLEEG)==2 && ~cfg.plotCondDiff.arg_selection
    % there is more than one condition and user wants to
    % plot each condition sequentially
    for cnd=1:length(ALLEEG)
        if hasStats
            handles{cnd} = vis_TimeFreqGrid('ALLEEG',ALLEEG(cnd),'Conn',Conn(cnd),'Stats',ALLEEG(cnd).CAT.Stats,cfg);
        else
            handles{cnd} = vis_TimeFreqGrid('ALLEEG',ALLEEG(cnd),'Conn',Conn(cnd),cfg);
        end
        if ~isempty(cfg)
            % store the configuration structure
            ALLEEG(cnd).CAT.configs.(fcnName) = cfg;
        end
    end
else
    % either user wants to plot condition difference
    % or there is only one condition
    if hasStats
            handles = vis_TimeFreqGrid('ALLEEG',ALLEEG,'Conn',Conn,'Stats',ALLEEG(1).CAT.Stats,cfg);
        else
            handles = vis_TimeFreqGrid('ALLEEG',ALLEEG,'Conn',Conn,cfg);
    end
    if ~isempty(cfg) && length(ALLEEG)==1
        for k=1:length(ALLEEG)
            % store the configuration structure
            ALLEEG(k).CAT.configs.(fcnName) = cfg;
        end
    end
end

function x = hasStatsField(EEG)
    x = isfield(EEG.CAT,'Stats');


function draw_loudspeakers(x0,dimensions,conf)
%DRAW_LOUDSPEAKERS draws loudspeaker symbols or "o" at the given positions
%
%   Usage: draw_loudspeakers(x0,[dimensions],conf)
%
%   Input parameters:
%       x0          - positions and directions of the loudspeakers / m
%       dimensions  - dimension defining the plane in which the loudspeaker
%                     symbol should be plotted. For example [1 1 0] corresponds
%                     to the xy-plane. Default: [1 1 0]
%       conf        - configuration struct (see SFS_config)
%
%   DRAW_LOUDSPEAKERS(x0,dimensions,conf) draws loudspeaker symbols or filled
%   points at the given secondary source positions. This can be controlled by
%   the conf.plot.realloudspeakers setting. The loudspeaker symbols are pointing
%   in their given direction and are colored accordingly to their weights,
%   whereby the weights are scaled to an absolute maximum of 1 before.
%
%   See also: plot_sound_field

%*****************************************************************************
% The MIT License (MIT)                                                      *
%                                                                            *
% Copyright (c) 2010-2019 SFS Toolbox Developers                             *
%                                                                            *
% Permission is hereby granted,  free of charge,  to any person  obtaining a *
% copy of this software and associated documentation files (the "Software"), *
% to deal in the Software without  restriction, including without limitation *
% the rights  to use, copy, modify, merge,  publish, distribute, sublicense, *
% and/or  sell copies of  the Software,  and to permit  persons to whom  the *
% Software is furnished to do so, subject to the following conditions:       *
%                                                                            *
% The above copyright notice and this permission notice shall be included in *
% all copies or substantial portions of the Software.                        *
%                                                                            *
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
% IMPLIED, INCLUDING BUT  NOT LIMITED TO THE  WARRANTIES OF MERCHANTABILITY, *
% FITNESS  FOR A PARTICULAR  PURPOSE AND  NONINFRINGEMENT. IN NO EVENT SHALL *
% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
% LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT, TORT  OR OTHERWISE, ARISING *
% FROM,  OUT OF  OR IN  CONNECTION  WITH THE  SOFTWARE OR  THE USE  OR OTHER *
% DEALINGS IN THE SOFTWARE.                                                  *
%                                                                            *
% The SFS Toolbox  allows to simulate and  investigate sound field synthesis *
% methods like wave field synthesis or higher order ambisonics.              *
%                                                                            *
% https://sfs.readthedocs.io                            sfstoolbox@gmail.com *
%*****************************************************************************

%% ===== Checking of input parameter =====================================
nargmin = 2;
nargmax = 3;
narginchk(nargmin,nargmax);
isargsecondarysource(x0)
nls = size(x0,1);
if nargin<nargmax
    conf = dimensions;
    dimensions = [1 1 0];
end

%% ===== Configuration ===================================================
p.realloudspeakers = conf.plot.realloudspeakers;
p.lssize = conf.plot.lssize;

%% ===== Plotting ========================================================
% Check in which plane we should plot the secondary sources and shift them
% around accordingly
if ~any(dimensions)
    return;
elseif ~dimensions(1)
    x0(:,1:2) = x0(:,2:3);
elseif ~dimensions(2)
    x0(:,2) = x0(:,3);
end

% Plot only "o" at the loudspeaker positions, use this as default for all cases
% that are not the x-y-plane
if ~p.realloudspeakers || ~(dimensions(1)&&dimensions(2))

    if p.realloudspeakers && ~(dimensions(1)&&dimensions(2))
        warning('%s: Real loudspeaker can only be drawn in the x-y-plane', ...
            upper(mfilename));
    end
    % Plot all secondary sources with the same color + symbol
    plot(x0(:,1),x0(:,2),'o', ...
        'MarkerFaceColor','k', ...
        'MarkerEdgeColor','k', ...
        'MarkerSize',4);

else

    % Weightings of the single loudspeakers (scale maximum to 1)
    weights = x0(:,7) / max(abs(x0(:,7)));
    % Set fill color for active loudspeakers
    % Scale the color: sc = 1 => black, sc = 0.5 => gray.
    sc = 0.6;
    fc = [(1-sc.*weights), ...
          (1-sc.*weights), ...
          (1-sc.*weights)];

    % Plot a real speaker symbol at the desired position
    % vertex coordinates with height and width after lssize
    w = p.lssize;
    h = p.lssize;
    v1 = [-h -h -h/2 -h/2 -h ; -w/2 w/2 w/2 -w/2 -w/2 ; 0 0 0 0 0];
    v2 = [-h/2 0 0 -h/2 ; -w/6 -w/2 w/2 w/6 ; 0 0 0 0 ];

    hold on;

    % Draw loudspeakers
    for n=1:nls

        % Get the azimuth direction of the secondary sources
        [phi,~] = cart2pol(x0(n,4),x0(n,5));

        % Rotation matrix (orientation of the speakers)
        % R = [cos(phi(n)) -sin(phi(n));sin(phi(n)) cos(phi(n))];
        R = rotation_matrix(phi);
        for k=1:length(v1)
            vr1(:,k) = R * v1(:,k);
        end
        for k=1:length(v2)
            vr2(:,k) = R * v2(:,k);
        end

        % Shift
        v01(1,:) = vr1(1,:) + x0(n,1);
        v01(2,:) = vr1(2,:) + x0(n,2);
        v02(1,:) = vr2(1,:) + x0(n,1);
        v02(2,:) = vr2(2,:) + x0(n,2);

        % Draw loudspeakers
        fill(v01(1,:),v01(2,:),fc(n,:));
        fill(v02(1,:),v02(2,:),fc(n,:));

    end

    hold off;

end

% Set equal axis ratio
axis image


function[imdb] = setupImdbDetection(trainName, testName, net)
% [imdb] = setupImdbDetection(trainName, testName, net)

global DATAopts;

%%% Setup the Imdb
% Get and test images
trainIms = textread(sprintf(DATAopts.imgsetpath, trainName), '%s'); %#ok<DTXTRD>
testIms = textread(sprintf(DATAopts.imgsetpath, testName), '%s'); %#ok<DTXTRD>

% Make train, val, and test set. For Pascal, I illegally use part of the test images
% as validation set. This is to match Girshick performance while still having
% meaningful graphs for the validation set.
% Note: allIms are just all images. datasetIdx determines how these are divided over
% train, val, and test.
allIms = cat(1, trainIms, testIms);
datasetIdx = cell(3, 1);
datasetIdx{1} = (1:length(trainIms))';  % Jasper: Use all training images. Only for comparison Pascal Girshick
datasetIdx{2} = (length(trainIms)+1:length(trainIms)+501)'; % Use part of the test images for validation. Not entirely legal, but otherwise it will take much longer to get where we want.
datasetIdx{3} = (length(trainIms)+1:length(allIms))';

imdb = ImdbDetectionFullSupervision(DATAopts.imgpath(1:end-6), ...        % path
    DATAopts.imgpath(end-3:end), ...      % image extension
    DATAopts.gStructPath, ...             % gStruct path
    allIms, ...                           % all images
    datasetIdx, ...                       % division into train/val/test
    net.meta.normalization.averageImage);      % average image used to pretrain network

% Usually instance weighting gives better performance. But not Girshick style
% imdbPascal.SetInstanceWeighting(true);

% Store lists for use in eval
imdb.misc.trainIms  = trainIms;
imdb.misc.testIms   = testIms;


function test_suite = test_zinegbin

%   Run specific demo, save values and compare the results to the expected.
%   Works for both xUnit Test Framework package by Steve Eddins and for
%   the built-in Unit Testing Framework (as of Matlab version 2013b).
%
%   See also
%     TEST_ALL, DEMO_ZINEGBIN
%
% Copyright (c) 2011-2012 Ville Tolvanen
% Copyright (c) 2014 Tuomas Sivula

% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.

  % Check which package to use
  if exist('initTestSuite', 'file')
    initTestSuite_path = which('initTestSuite');
  else
    initTestSuite_path = '';
  end
  if ~isempty(initTestSuite_path) && ...
     exist([initTestSuite_path(1:end-15) 'runtests'], 'file')
    % xUnit package
    initTestSuite;
  else
    % Built-in package
    % Use all functions except the @setup
    tests = localfunctions;
    tests = tests(~cellfun(@(x)strcmp(func2str(x),'setup'),tests));
    test_suite = functiontests(tests);
  end
end

% -------------
%     Tests
% -------------

function testRunDemo(testCase)
  % Run the correspondin demo and save the values. Note this test has to
  % be run at lest once before the other test may succeed.
  rundemo(getName(), ...
    {{'Ef' @(x)x(1:100)}, {'Varf', @(x)diag(x(1:100,1:100))}})
end

function testPredictionsZinegbin(testCase)
  verifyVarsEqual(testCase, getName(), {'Ef', 'Varf'}, ...
    'RelTolElement', 0.1, 'RelTolRange', 0.02)
end

% ------------------------
%     Helper functions
% ------------------------

function testCase = setup
  % Helper function to suply empty array into variable testCase as an
  % argument for each test function, if using xUnit package. Not to be
  % used with built-in test framework.
  testCase = [];
end

function name = getName
  % Helperfunction that returns the name of the demo, e.g. 'binomial1'.
  name = mfilename;
  name = name(6:end);
end


% Test file for scribble.m.

function pass = test_scribble(pref)

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

% Save the current warning state and then clear it in case scribble() issued a
% warning previously.
[lastmsg, lastid] = lastwarn();
lastwarn('');

% To pass, this call to scribble() must not crash or generate any warnings.
c = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,;:?!''"`_ )([]{}-+*/^=<>\|%#~@$&';
s = scribble(c);

[wmsg, wid] = lastwarn();
if ( strcmp(wid, 'CHEBFUN:scribble:unknownchar') )
    pass(1) = false;
else
    % If this run of scribble() didn't issue a warning, pass and restore the
    % warning state.
    pass(1) = true;
    lastwarn(lastmsg, lastid);
end

end


function test_bug1911

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

% When ft_movieplotER is called within ft_databrowser by right-clicking on a
% segment of data and selecting ft_movieplotER the movieplot is opened in the
% ft_databrowser window. Only a quarter of the topoplot is visible in this case.
%
% I have only experienced this problem in Windows.

cd(dccnpath('/home/common/matlab/fieldtrip/data/test'));
load bug1911.mat

cfg = [];
cfg.layout = 'easycapM10.lay';
ft_databrowser(cfg,timelock);


function conf = rfcn_config_ohem(varargin)
% conf = rfcn_config(varargin)
% --------------------------------------------------------
% D&T implementation
% Modified from MATLAB  R-FCN (https://github.com/daijifeng001/R-FCN/)
% and Faster R-CNN (https://github.com/shaoqingren/faster_rcnn)
% Copyright (c) 2017, Christoph Feichtenhofer
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
%

     ip = inputParser;

    %% training
    % whether use gpu
    ip.addParamValue('use_gpu',         gpuDeviceCount > 0, ...
                                                        @islogical);
    % Image scales -- the short edge of input image
    ip.addParamValue('scales',          600,            @ismatrix);
    % Max pixel size of a scaled input image
    ip.addParamValue('max_size',        1000,           @isscalar);
    % Images per batch
    ip.addParamValue('ims_per_batch',   2,              @isscalar);
    % Minibatch size, set as -1 if using all the rois
    ip.addParamValue('batch_size',      -1,            @isscalar);
    % Fraction of minibatch that is foreground labeled (class > 0),
    % which is disabled when batch_size = -1
    ip.addParamValue('fg_fraction',     -1,           @isscalar);
    % Overlap threshold for a ROI to be considered foreground (if >= fg_thresh)
    ip.addParamValue('fg_thresh',       0.5,            @isscalar);
    % Overlap threshold for a ROI to be considered background (class = 0 if
    % overlap in [bg_thresh_lo, bg_thresh_hi))
    ip.addParamValue('bg_thresh_hi',    0.5,            @isscalar);
    ip.addParamValue('bg_thresh_lo',    0.0,            @isscalar);
    % mean image, in RGB order
    ip.addParamValue('image_means',     128,            @ismatrix);
    % Use horizontally-flipped images during training?
    ip.addParamValue('use_flipped',     true,           @islogical);
    % Vaild training sample (IoU > bbox_thresh) for bounding box regresion
    ip.addParamValue('bbox_thresh',     0.5,            @isscalar);
    % Whether to perform class agnostic bbox regression
    ip.addParamValue('bbox_class_agnostic', true,  @islogical);

    % random seed
    ip.addParamValue('rng_seed',        6,              @isscalar);

    %% testing
    ip.addParamValue('test_scales',     600,            @isscalar);
    ip.addParamValue('test_max_size',   1000,           @isscalar);
    ip.addParamValue('test_nms',        0.3,            @isscalar);
    ip.addParamValue('test_binary',     false,          @islogical);

    ip.parse(varargin{:});
    conf = ip.Results;

    % if image_means is a file, load it
    if ischar(conf.image_means)
        s = load(conf.image_means);
        s_fieldnames = fieldnames(s);
        assert(length(s_fieldnames) <= 2);
        conf.image_means = s.(s_fieldnames{1});
        if length(s_fieldnames) == 2
          conf.image_std = s.(s_fieldnames{2});
        end
    end

end


function [Y, skel, remIndices] = hsvargplvmLoadSkelData(subject, trimDims)

if nargin < 2
    trimDims = 1;
end
% ------- LOAD DATASET

switch subject
     case '13'
        examples = {'14','16','17','18'};%laugh,laugh,box,box,
        try
            load 'cmu13_14_16_17_18.mat';
        catch
            [Y, lbls, Ytest, lblstest,skel] = lvmLoadData2('cmuXNoRoot', '13', examples);
            save 'cmu13_14_16_17_18.mat' 'Y' 'lbls' 'skel'
        end
        Ynew{1}=Y(1:15:end,:);
    case '93'
        examples = {'02'};
        try
            load 'cmu93_02.mat';
        catch
            [Y, lbls, Ytest, lblstest,skel] = lvmLoadData2('cmuXNoRoot', '93', examples);
            save 'cmu93_02.mat' 'Y' 'lbls' 'skel'
        end
        Ynew{1}=Y([1:3:100 101:2:270],:);
    case '02'
        examples= {'01','05','10'};
        [Y, lbls, Ytest, lblstest,skel] = lvmLoadData2('cmuXNoRoot', '02', examples);
        seq = cumsum(sum(lbls)) - [1:31];
        seq = seq(1:length(examples));
        % Ywalk = Y(1:3:70,:); % Orig: Y(1:85,:);
        % Ypunch = Y(86:13:548,:); % Orig: Y(86:548,:);
        % Ywash = Y(549:20:1209,:); % Orig:  Y(549:1209,:);
        Ynew{1} = Y(1:2:70,:); % Orig: Y(1:85,:); % Walk
        Ynew{2} = Y(86:4:250,:); % Orig: Y(86:548,:);  % Punch
        Ynew{3} = Y(830:6:1140,:); % Orig:  Y(549:1209,:); % Wash
    case '17'
        %[Y,skel, channels] = loadMocapData();
        % Motions: angry walk, hobble, whistle/jauntily, box
        examples = {'02','05','07','10'};
        try
            load cmu17_02_05_07_10.mat
        catch
            [Y, lbls, Ytest, lblstest,skel] = lvmLoadData2('cmuXNoRoot', '17', examples);
            save 'cmu17_02_05_07_10.mat' 'Y' 'lbls' 'Ytest' 'lblstest' 'skel'
        end
        seq = cumsum(sum(lbls)) - [1:31];
        seq = seq(1:length(examples));
        Ynew{1} = Y(1:10:400,:); % Orig: Y(1:85,:);
        Ynew{2} = Y(seq(1)+1:40:seq(2)-280,:); % Orig: Y(86:548,:);
        Ynew{3} = Y(seq(2)+1:55:seq(3)-200,:); % Orig:  Y(549:1209,:);
        Ynew{4} = Y(seq(3)+1:8:5000,:);
    case '20'
        %[Y,skel, channels] = loadMocapData();
        % Motions: angry walk, hobble, whistle/jauntily, box
        examples = {'01','05','11'};
        try
            load cmu20_01_05_11.mat
        catch
            [Y, lbls, Ytest, lblstest,skel] = lvmLoadData2('cmuXNoRoot', '20', examples);
            save 'cmu20_01_05_11.mat' 'Y' 'lbls' 'skel'
        end
        seq = cumsum(sum(lbls)) - [1:31];
        seq = seq(1:length(examples));
        Ynew{1} = Y;
end
Yorig = Y;

if trimDims
    for i=1:length(Ynew)
        [channels, xyzDiffIndices{i}, rotInd{i}] = skelGetChannels(Ynew{i});
        %%% ATTENTION: 'remIndices' should be the same for all!! (for
        %%% consistency)
        remIndices{i} = [xyzDiffIndices{i} rotInd{i}];
        Ynew{i}(:, remIndices{i}) = zeros(size(Ynew{i}(:, remIndices{i}) ));
    end
else
    remIndices = {};
end

Y = [];
for i=1:length(Ynew)
    Y = [Y ; Ynew{i}];
end

%{
   [channels] = skelGetChannels(Ynew{1});
   close; skelPlayData(skel, channels, 1/5);
%}


function kern = whiteKernExpandParam(kern, params)

% WHITEKERNEXPANDPARAM Create kernel structure from WHITE kernel's parameters.
% FORMAT
% DESC returns a white noise kernel structure filled with the
% parameters in the given vector. This is used as a helper function to
% enable parameters to be optimised in, for example, the NETLAB
% optimisation functions.
% ARG kern : the kernel structure in which the parameters are to be
% placed.
% ARG param : vector of parameters which are to be placed in the
% kernel structure.
% RETURN kern : kernel structure with the given parameters in the
% relevant locations.
%
% SEEALSO : whiteKernParamInit, whiteKernExtractParam, kernExpandParam
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006

% KERN

kern.variance = params(1);


%% Training face landmark detector
%
% This demo helps to train your own face landmark detector. You can train your
% own face landmark detection by just providing the paths for directory
% containing the images and files containing their corresponding face
% landmarks. As this landmark detector was originally trained on
% <http://www.ifp.illinois.edu/~vuongle2/helen/ HELEN dataset>, the training
% follows the format of data provided in HELEN dataset.
%
% The dataset consists of |.txt| files whose first line contains the image
% name which then follows the annotations. The format of a file containing
% annotations should be the following:
%
%  /data/helen/100032540_1.jpg
%  565.86 , 758.98
%  564.27 , 781.14
%  ...
%
% The above format is similar to HELEN dataset which is used for training the
% model.
%
% For a description of training parameters used in |configFile|, see the demo
% |facemark_kazemi_train_config_demo.m|.
%
% <<https://docs.opencv.org/3.4.0/2.jpg>>
%
% You can also download a pre-trained model |face_landmark_model.dat|,
% see the demo |facemark_kazemi_detect_img_demo|.
% (that way you can skip training and simply load the model).
%
% Sources:
%
% * <https://github.com/opencv/opencv_contrib/blob/3.4.0/modules/face/samples/sample_train_landmark_detector.cpp>
% * <https://github.com/opencv/opencv_contrib/blob/3.4.0/modules/face/tutorials/face_landmark/face_landmark_trainer.markdown>
%

%% Options

% [INPUT] path to the directory containing all text and image files
dname = fullfile(mexopencv.root(),'test','facemark','helen');
assert(isdir(dname), 'missing data directory');

% [INPUT] path to configuration xml file containing parameters for training
% https://github.com/opencv/opencv_contrib/raw/3.4.0/modules/face/samples/sample_config_file.xml
configFile = fullfile(mexopencv.root(),'test','facemark','config.xml');
assert(exist(configFile, 'file') == 2, 'missing train config file');

% [OUTPUT] path for saving the trained model
modelFile = fullfile(tempdir(), 'model_kazemi.dat');

% [INPUT] path to the cascade xml file for the face detector
xmlFace = fullfile(mexopencv.root(),'test','lbpcascade_frontalface.xml');
download_classifier_xml(xmlFace);

% name of user-defined face detector function
faceDetectFcn = 'myFaceDetector';
assert(exist([faceDetectFcn '.m'], 'file') == 2, 'missing face detect function');

% width/height which you want all images to get to scale the annotations.
% larger images are slower to process
scale = [460 460];

%% Data

% get names of files in which annotations and image names are found
filenames = cv.glob(fullfile(dname, '*.txt'));

% load image names and their corresponding landmarks
disp('Loading data...')
[imgFiles, pts] = cv.Facemark.loadTrainingData3(filenames);

% load images
imgs = cell(size(imgFiles));
for i=1:numel(imgFiles)
    if true
        % HELEN dataset annotations only store image basename
        fname = fullfile(dname, [imgFiles{i} '.jpg']);
    else
        fname = imgFiles{i};
    end
    imgs{i} = cv.imread(fname);
end

%% Init
% create instance of the face landmark detection class,
% and set the face detector function
obj = cv.FacemarkKazemi('ConfigFile',configFile);
obj.setFaceDetector(faceDetectFcn);

%% Train
% perform training
disp('Training...')
tic
success = obj.training(imgs, pts, configFile, scale, 'ModelFilename',modelFile);
toc
if success
    disp('Training successful')
else
    disp('Training failed')
end

%%
% In the above call, |scale| is passed to scale all images and their
% corresponding landmarks, as it takes greater time to process large images.
% After scaling data it calculates mean shape of the data which is used as
% initial shape while training. It trains the model and stores the trained
% model file with the specified filename. As the training starts, you will see
% something like this:
%
% <<https://docs.opencv.org/3.4.0/train1.png>>
%
% The error rate on trained images depends on the number of images used for
% training:
%
% <<https://docs.opencv.org/3.4.0/train.png>>
%
% The error rate on test images depends on the number of images used for
% training:
%
% <<https://docs.opencv.org/3.4.0/test.png>>
%

%% Helper functions

function download_classifier_xml(fname)
    if exist(fname, 'file') ~= 2
        % attempt to download trained Haar/LBP/HOG classifier from Github
        url = 'https://cdn.rawgit.com/opencv/opencv/3.4.0/data/';
        [~, f, ext] = fileparts(fname);
        if strncmpi(f, 'haarcascade_', length('haarcascade_'))
            url = [url, 'haarcascades/'];
        elseif strncmpi(f, 'lbpcascade_', length('lbpcascade_'))
            url = [url, 'lbpcascades/'];
        elseif strncmpi(f, 'hogcascade_', length('hogcascade_'))
            url = [url, 'hogcascades/'];
        else
            error('File not found');
        end
        urlwrite([url f ext], fname);
    end
end

% The facemark API provides the functionality to the user to use their own
% face detector. The code below implements a sample face detector. This
% function must be saved in its own M-function to be used by the facemark API.
function faces = myFaceDetector(img)
    persistent obj
    if isempty(obj)
        obj = cv.CascadeClassifier();
        obj.load(xmlFace);
    end

    if size(img,3) > 1
        gray = cv.cvtColor(img, 'RGB2GRAY');
    else
        gray = img;
    end
    gray = cv.equalizeHist(gray);
    faces = obj.detect(gray, 'ScaleFactor',1.4, 'MinNeighbors',2, ...
        'ScaleImage',true, 'MinSize',[30 30]);
end


function [shape] = ft_read_headshape(filename, varargin)

% FT_READ_HEADSHAPE reads the fiducials and/or the measured headshape
% from a variety of files (like CTF and Polhemus). The headshape and
% fiducials can for example be used for coregistration.
%
% Use as
%   [shape] = ft_read_headshape(filename)
%
% See also FT_READ_VOL, FT_READ_SENS, FT_WRITE_HEADSHAPE

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

% check the input: if filename is a cell-array, call ft_read_headshape recursively and combine the outputs
if iscell(filename)
  for i=1:numel(filename)
    tmpshape = ft_read_headshape(filename{i}, varargin{:});
    if i==1,
      shape = tmpshape;
    else
      tmpshape  = ft_convert_units(tmpshape, shape.unit);
      npnt      = size(shape.pnt,1);
      shape.pnt = cat(1, shape.pnt, tmpshape.pnt);
      if isfield(shape, 'tri') && isfield(tmpshape, 'tri')
        shape.tri = cat(1, shape.tri, tmpshape.tri + npnt);
      elseif ~isfield(shape, 'tri') && ~isfield(tmpshape, 'tri')
        % this is ok
      else
        error('not all input files seem to contain a triangulation');
      end
    end
  end
  return
end

% test whether the file exists
if ~exist(filename)
  error(sprintf('file ''%s'' does not exist', filename));
end

% get the options
fileformat  = keyval('format',      varargin);
coordinates = keyval('coordinates', varargin); if isempty(coordinates), coordinates = 'head'; end

if isempty(fileformat)
  fileformat = ft_filetype(filename);
end

% start with an empty structure
shape           = [];
shape.pnt       = [];
shape.fid.pnt   = [];
shape.fid.label = {};

switch fileformat
  case {'ctf_ds', 'ctf_hc', 'ctf_meg4', 'ctf_res4', 'ctf_old'}
    [p, f, x] = fileparts(filename);

    if strcmp(fileformat, 'ctf_old')
      fileformat = ft_filetype(filename);
    end

    if strcmp(fileformat, 'ctf_ds')
      filename = fullfile(p, [f x], [f '.hc']);
    elseif strcmp(fileformat, 'ctf_meg4')
      filename = fullfile(p, [f '.hc']);
    elseif strcmp(fileformat, 'ctf_res4')
      filename = fullfile(p, [f '.hc']);
    end

    orig = read_ctf_hc(filename);
    switch coordinates
      case 'head'
        shape.fid.pnt = cell2mat(struct2cell(orig.head));
      case 'dewar'
        shape.fid.pnt = cell2mat(struct2cell(orig.dewar));
      otherwise
        error('incorrect coordinates specified');
    end
    shape.fid.label = fieldnames(orig.head);

  case 'ctf_shape'
    orig = read_ctf_shape(filename);
    shape.pnt = orig.pnt;
    shape.fid.label = {'NASION', 'LEFT_EAR', 'RIGHT_EAR'};
    for i = 1:numel(shape.fid.label)
      shape.fid.pnt = cat(1, shape.fid.pnt, ...
        getfield(orig.MRI_Info, shape.fid.label{i}));
    end

  case {'4d_xyz', '4d_m4d', '4d_hs', '4d', '4d_pdf'}
    [p, f, x] = fileparts(filename);
    if ~strcmp(fileformat, '4d_hs')
      filename = fullfile(p, 'hs_file');
    end
    [shape.pnt, fid] = read_bti_hs(filename);

    % I'm making some assumptions here
    % which I'm not sure will work on all 4D systems

    %fid = fid(1:3, :);

    [junk, NZ] = max(fid(1:3,1));
    [junk, L]  = max(fid(1:3,2));
    [junk, R]  = min(fid(1:3,2));
    rest       = setdiff(1:size(fid,1),[NZ L R]);

    shape.fid.pnt = fid([NZ L R rest], :);
    shape.fid.label = {'NZ', 'L', 'R'};
    if ~isempty(rest),
      for i = 4:size(fid,1)
        shape.fid.label{i} = ['fiducial' num2str(i)];
        % in a 5 coil configuration this corresponds with Cz and Inion
      end
    end

  case 'itab_asc'
    shape = read_itab_asc(filename);

  case 'neuromag_mex'
    [co,ki,nu] = hpipoints(filename);
    fid = co(:,find(ki==1))';

    [junk, NZ] = max(fid(:,2));
    [junk, L]  = min(fid(:,1));
    [junk, R]  = max(fid(:,1));

    shape.fid.pnt = fid([NZ L R], :);
    shape.fid.label = {'NZ', 'L', 'R'};

  case {'mne_source'}
    % read the source space from an MNE file
    ft_hastoolbox('mne', 1);

    src = mne_read_source_spaces(filename, 1);
    shape = [];
    % only keep the points that are in use
    inuse1 = src(1).inuse==1;
    inuse2 = src(2).inuse==1;
    shape.pnt=[src(1).rr(inuse1,:); src(2).rr(inuse2,:)];

    % only keep the triangles that are in use; these have to be renumbered
    newtri1 = src(1).use_tris;
    newtri2 = src(2).use_tris;
    for i=1:numel(src(1).vertno)
      newtri1(newtri1==src(1).vertno(i)) = i;
    end
    for i=1:numel(src(2).vertno)
      newtri2(newtri2==src(2).vertno(i)) = i;
    end
    shape.tri  = [newtri1; newtri2 + numel(src(1).vertno)];
    shape.orig.pnt = [src(1).rr; src(2).rr];
    shape.orig.tri = [src(1).tris; src(2).tris + src(1).np];
    shape.orig.inuse = [src(1).inuse src(2).inuse]';

  case {'neuromag_mne', 'neuromag_fif'}
    % read the headshape and fiducials from an MNE file
    hdr = ft_read_header(filename,'headerformat','neuromag_mne');
    nFid = size(hdr.orig.dig,2); %work out number of fiducials
    switch coordinates
      case 'head' % digitiser points should be stored in head coordinates by default

        fidN=1;
        pntN=1;
        for i=1:nFid %loop over fiducials
          %check this point is in head coordinates:
          if hdr.orig.dig(i).coord_frame~=4 % 4 is MNE constant for head coordinates
            error(['Digitiser point (' num2str(i) ') not stored in head coordinates!']);
          end

          switch hdr.orig.dig(i).kind % constants defined in MNE - see p.215 of MNE manual
            case 1 % Cardinal point (nasion, LPA or RPA)
              %get location of fiducial:
              shape.fid.pnt(fidN,1:3) = hdr.orig.dig(i).r*100; %multiply by 100 to convert to cm
              switch hdr.orig.dig(i).ident
                case 1 % LPA
                  shape.fid.label{fidN} = 'LPA';
                case 2 % nasion
                  shape.fid.label{fidN} = 'Nasion';
                case 3 % RPA
                  shape.fid.label{fidN} = 'RPA';
                otherwise
                  error('Unidentified cardinal point in file!');
              end
              fidN = fidN + 1;

            case 2 % HPI coil
              shape.pnt(pntN,1:3) = hdr.orig.dig(i).r*100;
              pntN = pntN + 1;
            case 3 % EEG electrode location (or ECG)
              shape.pnt(pntN,1:3) = hdr.orig.dig(i).r*100;
              pntN = pntN + 1;
            case 4 % Additional head point
              shape.pnt(pntN,1:3) = hdr.orig.dig(i).r*100;
              pntN = pntN + 1;
            otherwise
              warning('Unidentified digitiser point in file!');
          end

        end
        shape.fid.label=shape.fid.label';

      case 'dewar'
        error('Dewar coordinates not supported for headshape yet (MNE toolbox)');
      otherwise
        error('Incorrect coordinates specified');
    end

  case {'yokogawa_mrk', 'yokogawa_ave', 'yokogawa_con', 'yokogawa_raw' }

    hdr = read_yokogawa_header(filename);
    marker = hdr.orig.matching_info.marker;

    % markers 1-3 identical to zero: try *.mrk file
    if ~any([marker(:).meg_pos])
      [p, f, x] = fileparts(filename);
      filename = fullfile(p, [f '.mrk']);
      if exist(filename, 'file')
        hdr    = read_yokogawa_header(filename);
        marker = hdr.orig.matching_info.marker;
      end
    end

    % non zero markers 1-3
    if any([marker(:).meg_pos])
      shape.fid.pnt = cat(1, marker(1:5).meg_pos);
      sw_ind = [3 1 2];
      shape.fid.pnt(1:3,:)= shape.fid.pnt(sw_ind, :);
      shape.fid.label = {'nas'; 'lpa'; 'rpa'; 'Marker4'; 'Marker5'};
    else
      error('no coil information found in Yokogawa file');
    end

    % Convert to the units of the grad.
    shape = ft_convert_units(shape, 'cm');

  case 'yokogawa_coregis'

    in_str = textread(filename, '%s');
    nr_items = size(in_str,1);
    ind = 1;
    coil_ind = 1;
    while ind < nr_items
      if strcmp(in_str{ind},'MEG:x=')
        shape.fid.pnt = [shape.fid.pnt; str2num(strtok(in_str{ind+1},[',','['])) ...
          str2num(strtok(in_str{ind+3},[',','['])) str2num(strtok(in_str{ind+5},[',','[']))];
        shape.fid.label = [shape.fid.label ; ['Marker',num2str(coil_ind)]];
        coil_ind = coil_ind + 1;
        ind = ind + 6;
      else
        ind = ind +1;
      end
    end
    if size(shape.fid.label,1) ~= 5
      error('Wrong number of coils');
    end

    sw_ind = [3 1 2];

    shape.fid.pnt(1:3,:)= shape.fid.pnt(sw_ind, :);
    shape.fid.label(1:3)= {'nas', 'lpa', 'rpa'};

  case 'polhemus_fil'
    [shape.fid.pnt, shape.pnt, shape.fid.label] = read_polhemus_fil(filename, 0);

  case 'spmeeg_mat'
    tmp = load(filename);
    if isfield(tmp.D, 'fiducials') && ~isempty(tmp.D.fiducials)
      shape = tmp.D.fiducials;
    else
      error('no headshape found in SPM EEG file');
    end

  case 'matlab'
    tmp = load(filename);
    if isfield(tmp, 'shape')
      shape = tmp.shape;
    elseif isfield(tmp, 'bnd')
      % the variable in the file is most likely a precomputed triangulation of some
      % sort
      shape = tmp.bnd;
    elseif isfield(tmp, 'elec')
      shape.fid.pnt   = tmp.elec.pnt;
      shape.fid.label = tmp.elec.label;
    else
      error('no headshape found in Matlab file');
    end

  case {'freesurfer_triangle_binary', 'freesurfer_quadrangle'}
    % the freesurfer toolbox is required for this
    ft_hastoolbox('freesurfer', 1);
    [pnt, tri] = read_surf(filename);
    if min(tri(:)) == 0
      % start counting from 1
      tri = tri + 1;
    end
    shape.pnt = pnt;
    shape.tri = tri;
    shape = rmfield(shape, 'fid');

  case 'mne_tri'
    % FIXME this should be implemented, consistent with ft_write_headshape
    keyboard

  case 'mne_pos'
    % FIXME this should be implemented, consistent with ft_write_headshape
    keyboard

  otherwise
    % try reading it from an electrode of volume conduction model file
    success = false;

    if ~success
      % try reading it as electrode positions
      % and treat those as fiducials
      try
        elec = ft_read_sens(filename);
        if ~ft_senstype(elec, 'eeg')
          error('headshape information can not be read from MEG gradiometer file');
        else
          shape.fid.pnt   = elec.pnt;
          shape.fid.label = elec.label;
          success = 1;
        end
      catch
        success = false;
      end % try
    end

    if ~success
      % try reading it as volume conductor
      % and treat the skin surface as headshape
      try
        vol = ft_read_vol(filename);
        if ~ft_voltype(vol, 'bem')
          error('skin surface can only be extracted from boundary element model');
        else
          if ~isfield(vol, 'skin')
            vol.skin = find_outermost_boundary(vol.bnd);
          end
          shape.pnt = vol.bnd(vol.skin).pnt;
          shape.tri = vol.bnd(vol.skin).tri; % also return the triangulation
          success = 1;
        end
      catch
        success = false;
      end % try
    end

    if ~success
      error('unknown fileformat for head shape information');
    end
end

if issubfield(shape, 'fid.label')
  % ensure that it is a column
  shape.fid.label = shape.fid.label(:);
end

% this will add the units to the head shape
shape = ft_convert_units(shape);


function a = ipermute(a,order)
%IPERMUTE     Inverse permute array dimensions
%
%Implements the Matlab function "ipermute", similar syntax and semantics
%

% written  09/17/08     S.M. Rump
%

  if isa(a,'intval')
    if a.complex
      a.mid = ipermute(a.mid,order);
      if ~isequal(a.rad,0)
        a.rad = ipermute(a.rad,order);
      end
    else
      a.inf = ipermute(a.inf,order);
      a.sup = ipermute(a.sup,order);
    end
  else
    error('invalid call of permute for intervals')
  end


%PRGLOBAL Define or reset PRTools globals
%
%   PRGLOBAL
%   PRGLOBAL RESET
%   PRGLOBAL(PAR1,VAL1,PAR2,VAL2, ....)
%
% INPUT
%   PAR1,PAR2  String with variable name of global variable
%   VAL1,VAL2  Desired value of global variable
%
% DESCRIPTION
% The functioning of PRTools depends on the values of a number of global
% variables. Many of them have their own routine to change them. This
% routine is a central routine to list them (no arguments), reset them
% to their initial values or set them to some user preference.
%
% The following global variables can be changed:
% PRMEMORY,  see corresponding routine
% DEFAULTBATCHSIZE,  see SETBATCH
% GRIDSIZE,  see corresponding routine and PLOTC
% CHECK_SIZES,  TRUE or FALSE, disables or enables some size checking
% STAMP_MAP,  TRUE or FALSE, see corresponding routine
% PRWAITBAR,  ON or OFF, see corresponding routine
% PRWARNING,  set level, see corresponding routine
% REGOPT_NFOLDS,  see REGOPTC
% REGOPT_ITERMAX,  see REGOPTC
% REGOPT_REPS,  see REGOPTC
%
% For more information just type PRGLOBAL
%
% SEE ALSO (PRTools Guide)
% PRMEMORY, SETBATCH, GRIDSIZE, STAMP_MAP, PRWAITBAR, PRWARNING, REGOPTC

% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com

function prglobal(varargin)

global CHECK_SIZES
global REGOPT_NFOLDS REGOPT_REPS REGOPT_ITERMAX REGOPT_OPTCRIT
global DEFAULTBATCHSIZE
if isempty(DEFAULTBATCHSIZE)
  DEFAULTBATCHSIZE = 1000;
end

if nargin == 0
  s = '\n          ';
  fprintf(['\n%5i  PRMEMORY/1e6, the maximum size of matrices intermediately created by' ...
    s 'PRTools. If set too high Matlab may crash. If set low PRTools may' s ...
    'generate many loops. \n'],prmemory/1e6);
  fprintf(['\n%5i  DEFAULTBATCHSIZE, the batch size set as default by setbatch. If set ' ...
    s 'too high Matlab may crash. If set low PRTools may generate many loops. \n'], ...
    DEFAULTBATCHSIZE);
  fprintf(['\n%5i  GRIDSIZE, to be used in scatterplots. Its value determines the' ...
    s 'accuracy by which classifiers are drawn using plotc. The default is' s ...
    '30 but sometimes 300 or more is needed causing long computing times.\n'],gridsize);
  fprintf(['\n%5i  CHECK_SIZES, true (1) or false(0), determines whether in sequential' ...
    s 'combining of datassets and mappings output and input sizes should be' s ...
    'checked on matching.\n'],CHECK_SIZES);
  fprintf(['\n%5i  STAMP_MAP, disabled (0), retrieval only (1), storage and retrieval (2)' ...
    s 'of trained mappings to avoid recomputation of precomputed results.\n'],stamp_map);
  fprintf(['\n%5s  PRWAITBAR, the status of prwaitbar, ''on'' or ''off''\n'],prwaitbar);
  fprintf(['\n%5i  PRWARNING, the level of prwarning.\n'],prwarning);
  fprintf(['\n%5i  REGOPT_NFOLDS, the number of folds used in the crossvalidation' ...
    s 'procedure by which the classifier performance is estimated for a' s ...
    'single setting of the parameters during their optimization by REGOPTC.\n'],REGOPT_NFOLDS);
  fprintf(['\n%5i  REGOPT_ITERMAX, the maximum number of iterations in the optimization' ...
    s 'procedure by which the classifier performance is estimated for a' s ...
    'single setting of the parameters during their optimization by REGOPTC.\n'],REGOPT_ITERMAX);
  fprintf(['\n%5i  REGOPT_REPS, the number of repetitions used in the crossvalidation' ...
    s 'procedure by which the classifier performance is estimated for a' s ...
    'single setting of the parameters during their optimization by REGOPTC.\n'],REGOPT_REPS);
  fprintf(['\n          Note that automatic parameter optimization for classifiers may slow' ...
    s 'down training by a factor REGOPT_NFOLDS*REGOPT_ITERMAX*REGOPT_REPS.\n']);

elseif (nargin == 1) & strcmpi(varargin{1},'reset')
  prmemory(50000000);
  gridsize(30);
  prwarning(1);
  prwaitbar;
  CHECK_SIZES = true;
  stamp_map(0);
  REGOPT_NFOLDS = 5;
  REGOPT_REPS = 1;
  REGOPT_ITERMAX = 20;
  DEFAULTBATCHSIZE = 1000;
elseif nargin ~= 2*floor(nargin/2)
  error('Wrong number of input arguments')
else
  for j=1:2:nargin
    switch lower(varargin{j})
      case 'globalprmemory'
        prmemory(varargin{j+1});
      case 'defaultbatchsize'
        DEFAULTBATCHSIZE = varargin{j+1};
      case 'current_gridsize'
        gridsize(varargin{j+1});
      case 'prwaitbar'
        prwaitbar(varargin{j+1});
      case 'prwarning'
        prwarning(varargin{j+1});
      case 'check_sizes'
        if all(varargin{j+1} ~= [true,false])
          error('CHECK_SIZES should either be ''true'' or ''false''')
        end
        CHECK_SIZES = varargin{j+1};
      case 'stamp_map'
        stamp_map(varargin{j+1});
      case 'regopt_nfolds'
        REGOPT_NFOLDS = varargin{j+1};
      case 'regopt_reps'
        REGOPT_REPS = varargin{j+1};
      case 'regopt_itermax'
        REGOPT_ITERMAX = varargin{j+1};
      otherwise
        error('Unknown global parameter')
    end
  end
end


% Gets the number of seconds since Jan 1 1970 (epoch)
%
% @return seconds Number of seconds since epoch
function [seconds] = get_seconds_since_epoch()
    if (is_octave())
        seconds = uint64(time());
    else
        seconds = uint64(convertTo(datetime('now', 'TimeZone', 'UTC'), 'epochtime'));
    end
end


function [] = autoWrite(S,fs,method)
% 'S':Len * Num
if(~exist('method','var'))
    method = [];
end
num = size(S,2);
S = S/max(max(abs(S)));
for i = 1:num
    eval(strcat('audiowrite(''S_',method,num2str(i),'.wav''',',S(:,',num2str(i),'),','fs);'));
end

return


function dimensionMap = getMapOfDimensions(MRSIStruct)
    values = cell2mat(struct2cell(MRSIStruct.dims));
    dimsFieldNames = fieldnames(MRSIStruct.dims);
    zeroIndexs = values == 0;
    nonZeroFieldName = dimsFieldNames(~zeroIndexs);
    dimensionMap = containers.Map(values(~zeroIndexs), nonZeroFieldName);
end


function [meg] = read_ctf_meg4(fname, hdr, begsample, endsample, chanindx)

% READ_CTF_MEG4 reads specified samples from a CTF continous datafile
% It neglects all trial boundaries as if the data was acquired in
% non-continous mode.
%
% Use as
%   [meg] = read_ctf_meg4(filename, hdr, begsample, endsample, chanindx)
% where
%   filename    name of the datafile, including the .meg4 extension
%   header      with all data information (from read_ctf_meg4)
%   begsample   index of the first sample to read
%   endsample   index of the last sample to read
%   chanindx    index of channels to read (optional, default is all)
%
% See also READ_CTF_MEG4

% "VSM MedTech Ltd. authorizes the release into public domain under the
% GPL licence of the Matlab source code files "read_ctf_res4.m" and
% "read_ctf_meg4.m" by the authors of said files from the F.C. Donders
% Centre, Nijmegen, The Netherlands."

% Author(s): Jim McKay November 1999
% Last revision: Jim McKay
% Copyright (c) 1999-2000 CTF Systems Inc. All Rights Reserved.
%
% modifications Copyright (C) 2002, Ole Jensen
% modifications Copyright (C) 2003, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: read_ctf_meg4.m 945 2010-04-21 17:41:20Z roboos $

% use global flag for feedback
global fb
if isempty(fb)
  fb = 0;
end

nsmp = hdr.nSamples;
ntrl = hdr.nTrials;
nchn = hdr.nChans;

if begsample<1,              error('cannot read before the start of the data');        end
if endsample>nsmp*ntrl*nchn, error('cannot read beyond the end of the data');          end
if begsample>endsample,      error('cannot read a negative number of samples');        end
if nargin<5,                 chanindx = 1:nchn;                                        end
if isempty(chanindx),        error('no channels were specified for reading CTF data'); end

%open the .meg4 file
fid = fopen(fname,'r','ieee-be');
if fid == -1,
  error('could not open datafile');
end

%check whether it is a known format
CTFformat=char(fread(fid, 8, 'uint8'))';
% This function was written for MEG41RS, but also seems to work for some other formats
if ~strcmp(CTFformat(1,1:7),'MEG41CP') && ~strcmp(CTFformat(1,1:7),'MEG4CPT')
  warning('meg4 format (%s) is not supported for file %s, trying anyway...', CTFformat(1,1:7), fname);
end

%determine size of .meg4 file
fseek(fid, 0, 'eof');
nbytes   = ftell(fid);

%number of trials per 2GB file FIXME assumes constancy across the .meg4 files
ntrlfile = round((nbytes-8)/(4*nchn*nsmp));
%ntrlfile = (nbytes-8)/(4*nchn*nsmp);
openfile = 0;

%determine which trials have to be read
begtrial = ceil(begsample/nsmp);
endtrial = ceil(endsample/nsmp);
trials   = begtrial:endtrial;

%to ensure correct sample handling in the case of multiple trials
sumsmp = [(begtrial-1):(endtrial-1)]*nsmp;
rawbeg = 1;

minchn  = min(chanindx); %to ensure correct channel handling in the case of blockwise reading
maxchn  = max(chanindx);
loopchn = length(trials)==1 || (maxchn-minchn+1)<=nchn; %decide whether to read in blockwise, or the specified samples per channel

raw     = zeros(endsample-begsample+1, length(chanindx)); %allocate memory
for trllop = 1:length(trials)
  trlnr  = trials(trllop);
  filenr = floor(trlnr/(ntrlfile+0.1));

  %ensure that the correct .meg4 file is open
  if filenr~=openfile && filenr>0,
    fclose(fid);
    nextname = sprintf('%s.%d_meg4', fname(1:(end-5)), filenr);
    if fb
      fprintf('data goes beyond 2GB file boundary, continuing with %s\n', nextname);
    end
    fid = fopen(nextname,'r','ieee-be');
    fseek(fid, 0, 'eof');
    openfile = filenr;
  end

  %this is relative to the current datafile
  rawtrl = mod(trlnr-1, ntrlfile) + 1;
  offset = 8 + 4*(rawtrl-1)*nsmp*nchn;

  %begin and endsamples expressed as samples with respect to the current trial
  tmpbeg = max(begsample-sumsmp(trllop), 1);
  tmpend = min(endsample-sumsmp(trllop), nsmp);
  rawend = rawbeg+tmpend-tmpbeg;

  %either read per channel or read entire trialblock and postselect the channels
  if loopchn,
    for chnlop = 1:length(chanindx)
      %this is relative to the current trial
      chanoffset = 4*(chanindx(chnlop)-1)*nsmp;
      sampoffset = 4*(tmpbeg-1);
      fseek(fid, offset+chanoffset+sampoffset, 'bof');
      [tmp, count]               = fread(fid,[tmpend-tmpbeg+1,1],'int32');
      raw(rawbeg:rawend, chnlop) = tmp;
    end
  else
    %this is relative to the current trial
    chanoffset = 4*(minchn-1)*nsmp;
    fseek(fid, offset+chanoffset, 'bof');
    ntmpchn               = maxchn - minchn + 1;
    [tmp, count]          = fread(fid,[nsmp,length(ntmpchn)],'int32');
    selchn                = chanindx - minchn + 1; %relative to the first channel to be read
    raw(rawbeg:rawend, :) = tmp(tmpbeg:tmpend, selchn);
  end
  rawbeg = rawend+1;
end
fclose(fid);

% multiply the dimensionless values with the calibration value
gain = hdr.gainV(chanindx); % only for selected channels
meg  = raw';            % transpose the raw data
for i=1:size(meg,1)
  meg(i,:) = gain(i)*meg(i,:);
end


problemToSolve = 'test2d_triangle';
origin = 'P1';
variable = 'd_u';
projectDestination = 'P1D';


function output_info=move_output_info_cpu(output_info)

if output_info.is_group_data

    data_child_groups=output_info.data_child_groups;
    output_valid_flags=output_info.child_valid_flags;
    data_child_groups=data_child_groups(output_valid_flags);
    child_num=length(data_child_groups);

    for g_idx=1:child_num
        data_child_groups{g_idx}=move_output_info_cpu(data_child_groups{g_idx});
    end

    output_info.data_child_groups(output_valid_flags)=data_child_groups;

else

    if isfield(output_info, 'x')
        output_info.x=move_to_cpu_values(output_info.x);
    end
    if isfield(output_info, 'aux')
        output_info.aux=move_to_cpu_values(output_info.aux);
    end
    if isfield(output_info, 'dzdx')
        output_info.dzdx=move_to_cpu_values(output_info.dzdx);
    end
    if isfield(output_info, 'dzdw')
        output_info.dzdw=move_to_cpu_values(output_info.dzdw);
    end

end

end


function [depVarValue, depVarUnit, taskStr, refBodyInfo] = lvd_getDepVarValueUnit(i, subLog, taskStr, refBodyId, celBodyData, onlyReturnTaskStr, inFrame)
    %lvd_getDepVarValueUnit Summary of this function goes here
    %   Detailed explanation goes here

    if(~isempty(refBodyId))
        refBodyInfo = getBodyInfoByNumber(refBodyId, celBodyData);
    else
        refBodyInfo = [];
    end

    if(onlyReturnTaskStr == true)
        depVarValue = NaN;
        depVarUnit = NaN;

        return;
    end

    switch taskStr
        case 'Yaw Angle'
            depVarValue = lvd_SteeringAngleTask(subLog(i), 'yaw', inFrame);
            depVarUnit = 'deg';
        case 'Pitch Angle'
            depVarValue = lvd_SteeringAngleTask(subLog(i), 'pitch', inFrame);
            depVarUnit = 'deg';
        case 'Roll Angle'
            depVarValue = lvd_SteeringAngleTask(subLog(i), 'roll', inFrame);
            depVarUnit = 'deg';
        case 'Bank Angle'
            depVarValue = lvd_SteeringAngleTask(subLog(i), 'bank', inFrame);
            depVarUnit = 'deg';
        case 'Angle of Attack'
            depVarValue = lvd_SteeringAngleTask(subLog(i), 'angleOfAttack', inFrame);
            depVarUnit = 'deg';
        case 'SideSlip Angle'
            depVarValue = lvd_SteeringAngleTask(subLog(i), 'sideslip', inFrame);
            depVarUnit = 'deg';
        case 'Total Angle of Attack'
            depVarValue = lvd_SteeringAngleTask(subLog(i), 'totalAngleOfAttack', inFrame);
            depVarUnit = 'deg';
        case 'Throttle'
            depVarValue = lvd_ThrottleTask(subLog(i), 'throttle', inFrame);
            depVarUnit = 'Percent';
        case 'Thrust to Weight Ratio'
            depVarValue = lvd_ThrottleTask(subLog(i), 't2w', inFrame);
            depVarUnit = ' ';
        case 'Total Thrust'
            depVarValue = lvd_ThrottleTask(subLog(i), 'totalthrust', inFrame);
            depVarUnit = 'kN';
        case 'Two-Body Time To Impact'
            depVarValue = lvd_TwoBodyImpactPointTasks(subLog(i), 'timeToImpact');
            depVarUnit = 'sec';
        case 'Two-Body Impact Latitude'
            depVarValue = lvd_TwoBodyImpactPointTasks(subLog(i), 'latitude');
            depVarUnit = 'degN';
        case 'Two-Body Impact Longitude'
            depVarValue = lvd_TwoBodyImpactPointTasks(subLog(i), 'longitude');
            depVarUnit = 'degE';
        case 'Drag Coefficient'
            depVarValue = lvd_AeroTasks(subLog(i), 'dragCoeff', []);
            depVarUnit = 'm^2';
        case 'Event Number'
            depVarValue = lvd_EventNumTask(subLog(i), 'eventNum');
            depVarUnit = '';
        case 'Total Effective Isp'
            depVarValue = lvd_PropulsionTasks(subLog(i), 'totalEffIsp');
            depVarUnit = 'sec';
        case 'Total Thrust Vector X Component'
            depVarValue = lvd_ThrottleTask(subLog(i), 'thrust_x', inFrame);
            depVarUnit = 'kN';
        case 'Total Thrust Vector Y Component'
            depVarValue = lvd_ThrottleTask(subLog(i), 'thrust_y', inFrame);
            depVarUnit = 'kN';
        case 'Total Thrust Vector Z Component'
            depVarValue = lvd_ThrottleTask(subLog(i), 'thrust_z', inFrame);
            depVarUnit = 'kN';
        case 'Power Net Charge Rate'
            [depVarValue, depVarUnit] = lvd_ElectricalPowerGlobalTasks(subLog(i), 'netChargeRate');
        case 'Power Cumulative Storage State of Charge'
            [depVarValue, depVarUnit] = lvd_ElectricalPowerGlobalTasks(subLog(i), 'cumStorageSoC');
        case 'Power Maximum Available Storage'
            [depVarValue, depVarUnit] = lvd_ElectricalPowerGlobalTasks(subLog(i), 'maxAvailableStorage');

        case 'Position Vector (X)'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'rVectX', inFrame);
            depVarUnit = 'km';
        case 'Position Vector (Y)'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'rVectY', inFrame);
            depVarUnit = 'km';
        case 'Position Vector (Z)'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'rVectZ', inFrame);
            depVarUnit = 'km';
        case 'Velocity Vector (X)'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'vVectX', inFrame);
            depVarUnit = 'km/s';
        case 'Velocity Vector (Y)'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'vVectY', inFrame);
            depVarUnit = 'km/s';
        case 'Velocity Vector (Z)'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'vVectZ', inFrame);
            depVarUnit = 'km/s';
        case 'Position Vector Magnitude'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'radius', inFrame);
            depVarUnit = 'km';
        case 'Velocity Vector Magnitude'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'velocity', inFrame);
            depVarUnit = 'km/s';
        case 'Surface Velocity'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'horzVel', inFrame);
            depVarUnit = 'km/s';
        case 'Vertical Velocity'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'vertVel', inFrame);
            depVarUnit = 'km/s';

        case 'Semi-major Axis'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'sma', inFrame);
            depVarUnit = 'km';
        case 'Eccentricity'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'ecc', inFrame);
            depVarUnit = '';
        case 'Inclination'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'inc', inFrame);
            depVarUnit = 'deg';
        case 'Right Asc. of the Asc. Node'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'raan', inFrame);
            depVarUnit = 'deg';
        case 'Argument of Periapsis'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'arg', inFrame);
            depVarUnit = 'deg';
        case 'True Anomaly'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'tru', inFrame);
            depVarUnit = 'deg';
        case 'Mean Anomaly'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'mean', inFrame);
            depVarUnit = 'deg';
        case 'Orbital Period'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'period', inFrame);
            depVarUnit = 'sec';
        case 'Radius of Periapsis'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'rPe', inFrame);
            depVarUnit = 'km';
        case 'Radius of Apoapsis'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'rApo', inFrame);
            depVarUnit = 'km';
        case 'Altitude of Apoapsis'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'altApo', inFrame);
            depVarUnit = 'km';
        case 'Altitude of Periapsis'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'altPeri', inFrame);
            depVarUnit = 'km';
        case 'Equinoctial H1'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'H1', inFrame);
            depVarUnit = '';
        case 'Equinoctial K1'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'K1', inFrame);
            depVarUnit = '';
        case 'Equinoctial H2'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'H2', inFrame);
            depVarUnit = '';
        case 'Equinoctial K2'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'K2', inFrame);
            depVarUnit = '';
        case 'Flight Path Angle'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'FPA', inFrame);
            depVarUnit = 'deg';

        case 'Altitude'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'alt', inFrame);
            depVarUnit = 'km';
        case 'Longitude (East)'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'long', inFrame);
            depVarUnit = 'deg';
        case 'Latitude (North)'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'lat', inFrame);
            depVarUnit = 'deg';
        case 'Velocity Azimuth'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'velAz', inFrame);
            depVarUnit = 'deg';
        case 'Velocity Elevation'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'velEl', inFrame);
            depVarUnit = 'deg';
        case 'Longitudinal Drift Rate'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'longDriftRate', inFrame);
            depVarUnit = 'deg/hr';

        case 'C3 Energy'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'c3', inFrame);
            depVarUnit = 'km^2/s^2';
        case 'Seconds Past Periapsis'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'tau', inFrame);
            depVarUnit = 'sec';

        case 'Central Body ID'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'centralBodyId', inFrame);
            depVarUnit = '';

        case  'Hyperbolic Velocity Unit Vector X'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'hyperVelUnitVectX', inFrame);
            depVarUnit = '';
        case  'Hyperbolic Velocity Unit Vector Y'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'hyperVelUnitVectY', inFrame);
            depVarUnit = '';
        case  'Hyperbolic Velocity Unit Vector Z'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'hyperVelUnitVectZ', inFrame);
            depVarUnit = '';
        case  'Hyperbolic Velocity Vector Right Ascension'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'hyperVelUnitVectRA', inFrame);
            depVarUnit = 'deg';
        case  'Hyperbolic Velocity Vector Declination'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'hyperVelUnitVectDec', inFrame);
            depVarUnit = 'deg';
        case  'Hyperbolic Velocity Magnitude'
            depVarValue = lvd_KinematicStateTasks(subLog(i), 'hyperVelMag', inFrame);
            depVarUnit = 'km/s';
        case 'Drag Force'
            depVarValue = lvd_AeroTasks(subLog(i), 'dragForce', inFrame);
            depVarUnit = 'kN';

        otherwise %is a programmatically generated string that we'll handle here
            fluidTypeMassPattern = '^Fluid Type (\d+?) Mass - ".*"';

            tankMassPattern = '^Tank (\d+?) Mass - ".*"';
            tankMassDotPattern = '^Tank (\d+?) Mass Flow Rate - ".*"';

            stageDryMassPattern = '^Stage (\d+?) Dry Mass - ".*"';
            stageActivePattern = '^Stage (\d+?) Active State - ".*"';

            engineActivePattern = '^Engine (\d+?) Active State - ".*"';

            stopwatchValuePattern = '^Stopwatch (\d+?) Value - ".*"';

            extremaValuePattern = '^Extrema (\d+?) Value - ".*"';

            grdObjAzValuePattern = '^Ground Object (\d+?) Azimuth to S/C - ".*"';
            grdObjElValuePattern = '^Ground Object (\d+?) Elevation to S/C - ".*"';
            grdObjRngValuePattern = '^Ground Object (\d+?) Range to S/C - ".*"';
            grdObjLoSValuePattern = '^Ground Object (\d+?) Line of Sight to S/C - ".*"';

            calcObjValuePattern = '^Calculus (\d+?) Value - ".*"';

            pwrStorageActivePattern = '^Power Storage (\d+?) Active State - ".*"';
            pwrStorageSoCPattern = '^Power Storage (\d+?) State of Charge - ".*"';
            pwrSinkActivePattern = '^Power Sink (\d+?) Active State - ".*"';
            pwrSinkDischargeRatePattern = '^Power Sink (\d+?) Discharge Rate - ".*"';
            pwrSrcActivePattern = '^Power Source (\d+?) Active State - ".*"';
            pwrSrcChargeRatePattern = '^Power Source (\d+?) Charge Rate - ".*"';

            geoPtPosXPattern = '^Point (\d+?) Position \(X\) - ".*"';
            geoPtPosYPattern = '^Point (\d+?) Position \(Y\) - ".*"';
            geoPtPosZPattern = '^Point (\d+?) Position \(Z\) - ".*"';
            geoPtVelXPattern = '^Point (\d+?) Velocity \(X\) - ".*"';
            geoPtVelYPattern = '^Point (\d+?) Velocity \(Y\) - ".*"';
            geoPtVelZPattern = '^Point (\d+?) Velocity \(Z\) - ".*"';

            geoVectXPattern = '^Vector (\d+?) X Component - ".*"';
            geoVectYPattern = '^Vector (\d+?) Y Component - ".*"';
            geoVectZPattern = '^Vector (\d+?) Z Component - ".*"';
            geoVectMagPattern = '^Vector (\d+?) Magnitude - ".*"';
            geoVectOriginXPattern = '^Vector (\d+?) Origin Position \(X\) - ".*"';
            geoVectOriginYPattern = '^Vector (\d+?) Origin Position \(Y\) - ".*"';
            geoVectOriginZPattern = '^Vector (\d+?) Origin Position \(Z\) - ".*"';

            geoAngleMagPattern = '^Angle (\d+?) Magnitude - ".*"';

            geoPlaneNormXPattern = '^Plane (\d+?) Normal Vector X Component - ".*"';
            geoPlaneNormYPattern = '^Plane (\d+?) Normal Vector Y Component - ".*"';
            geoPlaneNormZPattern = '^Plane (\d+?) Normal Vector Z Component - ".*"';

            pluginValuePattern = '^Plugin (\d+?) Value - ".*"';

            if(not(isempty(regexpi(taskStr, fluidTypeMassPattern)))) %#ok<*RGXPI>
                tokens = regexpi(taskStr, fluidTypeMassPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                fluidTypeInd = str2double(tokens);

                [~,fluidTypes] = subLog(i).launchVehicle.tankTypes.getFluidTypesGraphAnalysisTaskStrs();
                fluidType = fluidTypes(fluidTypeInd);

                depVarValue = lvd_FluidTypeMassTasks(subLog(i), 'totalFluidTypeMass', fluidType);
                depVarUnit = 'mT';

            elseif(not(isempty(regexpi(taskStr, tankMassPattern))))
                tokens = regexpi(taskStr, tankMassPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                tankInd = str2double(tokens);

                [~,tanks] = subLog(i).launchVehicle.getTanksGraphAnalysisTaskStrs();
                tank = tanks(tankInd);

                depVarValue = lvd_TankMassTasks(subLog(i), 'tankMass', tank);
                depVarUnit = 'mT';

            elseif(not(isempty(regexpi(taskStr, tankMassDotPattern))))
                tokens = regexpi(taskStr, tankMassDotPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                tankInd = str2double(tokens);

                [~,tanks] = subLog(i).launchVehicle.getTanksGraphAnalysisTaskStrs();
                tank = tanks(tankInd);

                depVarValue = lvd_TankMassTasks(subLog(i), 'tankMDot', tank);
                depVarUnit = 'mT/s';

            elseif(not(isempty(regexpi(taskStr, stageDryMassPattern))))
                tokens = regexpi(taskStr, stageDryMassPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                stageInd = str2double(tokens);

                [~,stages] = subLog(i).launchVehicle.getStagesGraphAnalysisTaskStrs();
                stage = stages(stageInd);

                depVarValue = lvd_StageTasks(subLog(i), 'dryMass', stage);
                depVarUnit = 'mT';

            elseif(not(isempty(regexpi(taskStr, stageActivePattern))))
                tokens = regexpi(taskStr, stageActivePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                stageInd = str2double(tokens);

                [~,stages] = subLog(i).launchVehicle.getStagesGraphAnalysisTaskStrs();
                stage = stages(stageInd);

                depVarValue = lvd_StageTasks(subLog(i), 'active', stage);
                depVarUnit = '';

            elseif(not(isempty(regexpi(taskStr, engineActivePattern))))
                tokens = regexpi(taskStr, engineActivePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                engineInd = str2double(tokens);

                [~,engines] = subLog(i).launchVehicle.getEnginesGraphAnalysisTaskStrs();
                engine = engines(engineInd);

                depVarValue = lvd_EngineTasks(subLog(i), 'active', engine);
                depVarUnit = '';

            elseif(not(isempty(regexpi(taskStr, stopwatchValuePattern))))
                tokens = regexpi(taskStr, stopwatchValuePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                stopwatchInd = str2double(tokens);

                [~,stopwatches] = subLog(i).launchVehicle.getStopwatchGraphAnalysisTaskStrs();
                stopwatch = stopwatches(stopwatchInd);

                depVarValue = lvd_StopwatchMassTasks(subLog(i), 'swValue', stopwatch);
                depVarUnit = 'sec';

            elseif(not(isempty(regexpi(taskStr, extremaValuePattern))))
                tokens = regexpi(taskStr, extremaValuePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                calcObjInd = str2double(tokens);

                [~,calcObjs] = subLog(i).launchVehicle.getExtremaGraphAnalysisTaskStrs();
                calcObj = calcObjs(calcObjInd);

                [depVarValue, depVarUnit] = lvd_ExtremaTasks(subLog(i), 'extremumValue', calcObj);

            elseif(not(isempty(regexpi(taskStr, grdObjAzValuePattern))))
                tokens = regexpi(taskStr, grdObjAzValuePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                ind = str2double(tokens);

                [~, grdObjs] = subLog(i).lvdData.groundObjs.getGrdObjAzGraphAnalysisTaskStrs();
                grdObj = grdObjs(ind);

                [depVarValue, depVarUnit] = lvd_GrdObjTasks(subLog(i), 'azimuth', grdObj, inFrame);

            elseif(not(isempty(regexpi(taskStr, grdObjElValuePattern))))
                tokens = regexpi(taskStr, grdObjElValuePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                ind = str2double(tokens);

                [~, grdObjs] = subLog(i).lvdData.groundObjs.getGrdObjAzGraphAnalysisTaskStrs();
                grdObj = grdObjs(ind);

                [depVarValue, depVarUnit] = lvd_GrdObjTasks(subLog(i), 'elevation', grdObj, inFrame);

            elseif(not(isempty(regexpi(taskStr, grdObjRngValuePattern))))
                tokens = regexpi(taskStr, grdObjRngValuePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                ind = str2double(tokens);

                [~, grdObjs] = subLog(i).lvdData.groundObjs.getGrdObjAzGraphAnalysisTaskStrs();
                grdObj = grdObjs(ind);

                [depVarValue, depVarUnit] = lvd_GrdObjTasks(subLog(i), 'range', grdObj, inFrame);

            elseif(not(isempty(regexpi(taskStr, grdObjLoSValuePattern))))
                tokens = regexpi(taskStr, grdObjLoSValuePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                ind = str2double(tokens);

                [~, grdObjs] = subLog(i).lvdData.groundObjs.getGrdObjAzGraphAnalysisTaskStrs();
                grdObj = grdObjs(ind);

                [depVarValue, depVarUnit] = lvd_GrdObjTasks(subLog(i), 'LoS', grdObj, inFrame);

            elseif(not(isempty(regexpi(taskStr, calcObjValuePattern))))
                tokens = regexpi(taskStr, calcObjValuePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                calcObjInd = str2double(tokens);

                [~,calcObjs] = subLog(i).launchVehicle.getCalculusCalcObjGraphAnalysisTaskStrs();
                calcObj = calcObjs(calcObjInd);

                [depVarValue, depVarUnit] = lvd_CalculusCalculationTasks(subLog(i), 'calcObjValue', calcObj);

            elseif(not(isempty(regexpi(taskStr, pwrStorageActivePattern))))
                tokens = regexpi(taskStr, pwrStorageActivePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                pwrStorageObjInd = str2double(tokens);

                [~, pwrStorages] = subLog(i).launchVehicle.getPowerStorageGraphAnalysisTaskStrs();
                pwrStorage = pwrStorages(pwrStorageObjInd);

                [depVarValue, depVarUnit] = lvd_ElectricalPowerStorageTasks(subLog(i), 'active', pwrStorage);

            elseif(not(isempty(regexpi(taskStr, pwrStorageSoCPattern))))
                tokens = regexpi(taskStr, pwrStorageSoCPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                pwrStorageObjInd = str2double(tokens);

                [~, pwrStorages] = subLog(i).launchVehicle.getPowerStorageGraphAnalysisTaskStrs();
                pwrStorage = pwrStorages(pwrStorageObjInd);

                [depVarValue, depVarUnit] = lvd_ElectricalPowerStorageTasks(subLog(i), 'stateOfCharge', pwrStorage);

            elseif(not(isempty(regexpi(taskStr, pwrSinkActivePattern))))
                tokens = regexpi(taskStr, pwrSinkActivePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                pwrSinkObjInd = str2double(tokens);

                [~, pwrSinks] = subLog(i).launchVehicle.getPowerSinksGraphAnalysisTaskStrs();
                pwrSink = pwrSinks(pwrSinkObjInd);

                [depVarValue, depVarUnit] = lvd_ElectricalPowerSinkTasks(subLog(i), 'active', pwrSink);

            elseif(not(isempty(regexpi(taskStr, pwrSinkDischargeRatePattern))))
                tokens = regexpi(taskStr, pwrSinkDischargeRatePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                pwrSinkObjInd = str2double(tokens);

                [~, pwrSinks] = subLog(i).launchVehicle.getPowerSinksGraphAnalysisTaskStrs();
                pwrSink = pwrSinks(pwrSinkObjInd);

                [depVarValue, depVarUnit] = lvd_ElectricalPowerSinkTasks(subLog(i), 'dischargeRate', pwrSink);

            elseif(not(isempty(regexpi(taskStr, pwrSrcActivePattern))))
                tokens = regexpi(taskStr, pwrSrcActivePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                pwrSrcObjInd = str2double(tokens);

                [~, powerSrcs] = subLog(i).launchVehicle.getPowerSrcsGraphAnalysisTaskStrs();
                powerSrc = powerSrcs(pwrSrcObjInd);

                [depVarValue, depVarUnit] = lvd_ElectricalPowerSrcTasks(subLog(i), 'active', powerSrc);

            elseif(not(isempty(regexpi(taskStr, pwrSrcChargeRatePattern))))
                tokens = regexpi(taskStr, pwrSrcChargeRatePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                pwrSrcObjInd = str2double(tokens);

                [~, powerSrcs] = subLog(i).launchVehicle.getPowerSrcsGraphAnalysisTaskStrs();
                powerSrc = powerSrcs(pwrSrcObjInd);

                [depVarValue, depVarUnit] = lvd_ElectricalPowerSrcTasks(subLog(i), 'chargeRate', powerSrc);

            elseif(not(isempty(regexpi(taskStr, geoPtPosXPattern))))
                tokens = regexpi(taskStr, geoPtPosXPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                pointInd = str2double(tokens);

                [~, points] = subLog(i).lvdData.geometry.points.getPointPositionXGraphAnalysisTaskStrs();
                point = points(pointInd);

                [depVarValue, depVarUnit] = lvd_GeometricPointTasks(subLog(i), 'PosX', point, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoPtPosYPattern))))
                tokens = regexpi(taskStr, geoPtPosYPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                pointInd = str2double(tokens);

                [~, points] = subLog(i).lvdData.geometry.points.getPointPositionXGraphAnalysisTaskStrs();
                point = points(pointInd);

                [depVarValue, depVarUnit] = lvd_GeometricPointTasks(subLog(i), 'PosY', point, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoPtPosZPattern))))
                tokens = regexpi(taskStr, geoPtPosZPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                pointInd = str2double(tokens);

                [~, points] = subLog(i).lvdData.geometry.points.getPointPositionXGraphAnalysisTaskStrs();
                point = points(pointInd);

                [depVarValue, depVarUnit] = lvd_GeometricPointTasks(subLog(i), 'PosZ', point, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoPtVelXPattern))))
                tokens = regexpi(taskStr, geoPtVelXPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                pointInd = str2double(tokens);

                [~, points] = subLog(i).lvdData.geometry.points.getPointPositionXGraphAnalysisTaskStrs();
                point = points(pointInd);

                [depVarValue, depVarUnit] = lvd_GeometricPointTasks(subLog(i), 'VelX', point, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoPtVelYPattern))))
                tokens = regexpi(taskStr, geoPtVelYPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                pointInd = str2double(tokens);

                [~, points] = subLog(i).lvdData.geometry.points.getPointPositionXGraphAnalysisTaskStrs();
                point = points(pointInd);

                [depVarValue, depVarUnit] = lvd_GeometricPointTasks(subLog(i), 'VelY', point, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoPtVelZPattern))))
                tokens = regexpi(taskStr, geoPtVelZPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                pointInd = str2double(tokens);

                [~, points] = subLog(i).lvdData.geometry.points.getPointPositionXGraphAnalysisTaskStrs();
                point = points(pointInd);

                [depVarValue, depVarUnit] = lvd_GeometricPointTasks(subLog(i), 'VelZ', point, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoVectXPattern))))
                tokens = regexpi(taskStr, geoVectXPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                vectInd = str2double(tokens);

                [~, vectors] = subLog(i).lvdData.geometry.vectors.getVectorXComponentGraphAnalysisTaskStrs();
                vector = vectors(vectInd);

                [depVarValue, depVarUnit] = lvd_GeometricVectorTasks(subLog(i), 'VectorX', vector, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoVectYPattern))))
                tokens = regexpi(taskStr, geoVectYPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                vectInd = str2double(tokens);

                [~, vectors] = subLog(i).lvdData.geometry.vectors.getVectorYComponentGraphAnalysisTaskStrs();
                vector = vectors(vectInd);

                [depVarValue, depVarUnit] = lvd_GeometricVectorTasks(subLog(i), 'VectorY', vector, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoVectZPattern))))
                tokens = regexpi(taskStr, geoVectZPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                vectInd = str2double(tokens);

                [~, vectors] = subLog(i).lvdData.geometry.vectors.getVectorZComponentGraphAnalysisTaskStrs();
                vector = vectors(vectInd);

                [depVarValue, depVarUnit] = lvd_GeometricVectorTasks(subLog(i), 'VectorZ', vector, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoVectMagPattern))))
                tokens = regexpi(taskStr, geoVectMagPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                vectInd = str2double(tokens);

                [~, vectors] = subLog(i).lvdData.geometry.vectors.getVectorMagComponentGraphAnalysisTaskStrs();
                vector = vectors(vectInd);

                [depVarValue, depVarUnit] = lvd_GeometricVectorTasks(subLog(i), 'VectMag', vector, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoVectOriginXPattern))))
                tokens = regexpi(taskStr, geoVectOriginXPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                vectInd = str2double(tokens);

                [~, vectors] = subLog(i).lvdData.geometry.vectors.getOriginPosXComponentGraphAnalysisTaskStrs();
                vector = vectors(vectInd);

                [depVarValue, depVarUnit] = lvd_GeometricVectorTasks(subLog(i), 'OriginX', vector, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoVectOriginYPattern))))
                tokens = regexpi(taskStr, geoVectOriginYPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                vectInd = str2double(tokens);

                [~, vectors] = subLog(i).lvdData.geometry.vectors.getOriginPosYComponentGraphAnalysisTaskStrs();
                vector = vectors(vectInd);

                [depVarValue, depVarUnit] = lvd_GeometricVectorTasks(subLog(i), 'OriginY', vector, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoVectOriginZPattern))))
                tokens = regexpi(taskStr, geoVectOriginZPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                vectInd = str2double(tokens);

                [~, vectors] = subLog(i).lvdData.geometry.vectors.getOriginPosZComponentGraphAnalysisTaskStrs();
                vector = vectors(vectInd);

                [depVarValue, depVarUnit] = lvd_GeometricVectorTasks(subLog(i), 'OriginZ', vector, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoAngleMagPattern))))
                tokens = regexpi(taskStr, geoAngleMagPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                angleInd = str2double(tokens);

                [~, angles] = subLog(i).lvdData.geometry.angles.getAngleMagGraphAnalysisTaskStrs();
                angle = angles(angleInd);

                [depVarValue, depVarUnit] = lvd_GeometricAngleTasks(subLog(i), 'Mag', angle, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoPlaneNormXPattern))))
                tokens = regexpi(taskStr, geoPlaneNormXPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                planeInd = str2double(tokens);

                [~, planes] = subLog(i).lvdData.geometry.planes.getPlaneNormalXComponentGraphAnalysisTaskStrs();
                plane = planes(planeInd);

                [depVarValue, depVarUnit] = lvd_GeometricPlaneTasks(subLog(i), 'NormVectorX', plane, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoPlaneNormYPattern))))
                tokens = regexpi(taskStr, geoPlaneNormYPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                planeInd = str2double(tokens);

                [~, planes] = subLog(i).lvdData.geometry.planes.getPlaneNormalYComponentGraphAnalysisTaskStrs();
                plane = planes(planeInd);

                [depVarValue, depVarUnit] = lvd_GeometricPlaneTasks(subLog(i), 'NormVectorY', plane, inFrame);

            elseif(not(isempty(regexpi(taskStr, geoPlaneNormZPattern))))
                tokens = regexpi(taskStr, geoPlaneNormZPattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                planeInd = str2double(tokens);

                [~, planes] = subLog(i).lvdData.geometry.planes.getPlaneNormalZComponentGraphAnalysisTaskStrs();
                plane = planes(planeInd);

                [depVarValue, depVarUnit] = lvd_GeometricPlaneTasks(subLog(i), 'NormVectorZ', plane, inFrame);

            elseif(not(isempty(regexpi(taskStr, pluginValuePattern))))
                tokens = regexpi(taskStr, pluginValuePattern, 'tokens');
                tokens = tokens{1};
                tokens = tokens{1};
                pluginInd = str2double(tokens);

                lvdData = subLog(i).lvdData;
                [~, plugins] = lvdData.plugins.getAllPluginGraphAnalysisTaskStrs();
                plugin = plugins(pluginInd);

                depVarValue = lvd_PluginValueTask(subLog(i), 'plugin_value', plugin, lvdData, inFrame);
                depVarUnit = '';
            else
                error('Unknown LVD task string: "%s"', taskStr);
            end
    end
end