classdef OptimizationVariablesNearBoundsValidator < AbstractLaunchVehicleDataValidator
    %NoOptimizationVariablesValidator Summary of this class goes here
    %   Detailed explanation goes here

    properties
        lvdData LvdData
    end

    methods
        function obj = OptimizationVariablesNearBoundsValidator(lvdData)
            obj.lvdData = lvdData;
        end

        function [errors, warnings] = validate(obj)
            errors = LaunchVehicleDataValidationError.empty(0,1);
            warnings = LaunchVehicleDataValidationWarning.empty(0,1);

            varSet = obj.lvdData.optimizer.vars;
            varSet.sortVarsByEvtNum();
            [x, ~, varNameStrs, ~] = varSet.getTotalScaledXVector();
            [lb, ub] = varSet.getTotalScaledBndsVector();

            warnInd = [];
            for(i=1:length(x)) %#ok<*NO4LP>
                normX = (x(i) - lb(i)) / (ub(i) - lb(i));

                if(normX >= 0.99 || normX <= 0.01 || (ub(i) == lb(i) && x(i) == lb(i)))
                    warnInd(end+1) = i; %#ok<AGROW>
                end
            end

            if(isempty(warnInd))
                return;
            end

            for(i=1:length(warnInd))
                varNames{i} = varNameStrs{warnInd(i)}; %#ok<AGROW>
            end

            varNamesSubStr = strjoin(varNames,'\n');

            str = sprintf('Variables are near optimization bounds on some events:\n%s', varNamesSubStr);
            warnings(end+1) = LaunchVehicleDataValidationWarning(str);
        end
    end
end


function hole_num = p06_hole_num ( )

%*****************************************************************************80
%
%% P06_HOLE_NUM counts the holes in problem 06.
%
%  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 = 1;

  return
end


function my_clear_net_trn(net_config)

    cnn_update_net_group(net_config, @do_clear, []);

end

function one_group_info=do_clear(one_group_info, opts)

net_info=one_group_info.net_info;
if isempty(net_info)
    return;
end

for i=1:numel(net_info.ref.layers)

  if strcmp(net_info.ref.layers{i}.type,'conv')

      net_info.ref.layers{i}.filtersMomentum = zeros('like',net_info.ref.layers{i}.filters) ;
      net_info.ref.layers{i}.biasesMomentum = zeros('like',net_info.ref.layers{i}.biases) ;

      if ~isfield(net_info.ref.layers{i}, 'filtersLearningRate')
        net_info.ref.layers{i}.filtersLearningRate = 1 ;
      end
      if ~isfield(net_info.ref.layers{i}, 'biasesLearningRate')
        net_info.ref.layers{i}.biasesLearningRate = 1 ;
      end
      if ~isfield(net_info.ref.layers{i}, 'filtersWeightDecay')
        net_info.ref.layers{i}.filtersWeightDecay = 1 ;
      end
      if ~isfield(net_info.ref.layers{i}, 'biasesWeightDecay')
        net_info.ref.layers{i}.biasesWeightDecay = 1 ;
      end

  end

  if strcmp(net_info.ref.layers{i}.type,'my_custom')
      layer_update_fn=net_info.ref.layers{i}.layer_update_fn;
      if ~isempty(layer_update_fn)
          update_info=[];
          update_info.group_info=one_group_info;
          net_info.ref.layers{i}=net_info.ref.layers{i}.layer_update_fn(...
                'init_trn', net_info.ref.layers{i}, update_info);
      end
  end

end

end


classdef TestResize
    %TestResize

    methods (Static)
        function test_1
            img = imread(fullfile(mexopencv.root(),'test','img001.jpg'));
            ref = img(1:2:end,1:2:end,:);
            dst = cv.resize(img, 0.5, 0.5, 'Interpolation','Nearest');
            validateattributes(dst, {class(img)}, {'size',size(ref)});
            assert(isequal(ref, dst));
        end

        function test_2
            img = imread(fullfile(mexopencv.root(),'test','img001.jpg'));
            ref = img(1:2:end,1:2:end,:);
            dst = cv.resize(img, [256,256], 'Interpolation','Nearest');
            validateattributes(dst, {class(img)}, {'size',size(ref)});
            assert(all(abs(ref(:) - dst(:)) < 1e-5));
        end

        function test_3
            img = imread(fullfile(mexopencv.root(),'test','img001.jpg'));
            interps = {'Nearest', 'Linear', 'Cubic', 'Area', 'Lanczos4'};
            for i=1:numel(interps)
                dst = cv.resize(img, [700 800], 'Interpolation',interps{i});
                validateattributes(dst, {class(img)}, {'size',[800 700 size(img,3)]});
            end
        end

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

end


function newMsh = meshSmooth(msh,QueryFlag)
%Smooth a VTK mesh and update if there is a mesh in a current window
%
%   newMsh = meshSmooth(msh,QueryFlag)
%
% The msh can either be a file name to a white matter classification
% file or one of our VTK mesh data structures (see meshGet, meshSet).
%
% Several msh fields are checked to determine the smoothing
% parameters.  These are
%   smooth_iterations  (default 35)
%   smooth_relaxation  (default 0.15)
%   smooth_sinc_method (default 1)
%
% If you set  QueryFlag = 1, you will be asked about these parameter
% values.
%
% The relaxation factor only changes the smoothness by increasing the
% current value. If want you choose a value that is smaller than the
% current mesh smoothing, you should really revert to the original mesh and
% then smooth it.  Yes, we know, we could do that for you here.
%
% The smooth iterations specifies how much you want to process in order to
% converge.
%
% Example:
%  fName ='X:\anatomy\nakadomari\left\20050901_fixV1\left.Class';
%  msh = meshBuild(fName);
%
%  Not very smooth, default = 35
%  msh = meshSet(msh,'smooth_iterations',1);
%  msh = meshSmooth(msh);
%  msh = meshVisualize(msh);
%
% Author GB
% ras 01/07: if there's a mesh window open, auto-update the vertices
% rfb 08/10: populate initial vertices within meshSmooth
% al 04/11: removed a line in the code that repopulated the initialVertices

if notDefined('msh'), error('This function needs a mesh input'); end
if notDefined('QueryFlag'), QueryFlag = 0; end
% If the input is a string, we build the mesh.
if ischar(msh), msh = meshBuild(msh); end

% If the parameters are set, we don't query the user.  If they are not set,
% we will pop up a window and check the parameters.
%
if isempty(meshGet(msh,'smooth_iterations')), msh = meshSet(msh,'smooth_iterations',30);  end
if isempty(meshGet(msh,'smooth_relaxation')), msh = meshSet(msh,'smooth_relaxation',0.5);  end
if isempty(meshGet(msh,'smooth_sinc_method')), msh = meshSet(msh,'smooth_sinc_method',0);  end
if isempty(meshGet(msh,'mod_depth')), msh = meshSet(msh,'mod_depth',0.15);  end
if QueryFlag
    prompt = {'Smooth with Windowed Sinc (0|1):',...
        'Smooth Iterations:',...
        'Smooth Relaxation (0-2):'};
    defAns = {num2str(meshGet(msh,'smooth_sinc_method')),...
        num2str(meshGet(msh,'smooth_iterations')),...
        num2str(meshGet(msh,'smooth_relaxation'))};
    resp = inputdlg(prompt, 'Set Mesh Build Parameters', 1, defAns);
    if(~isempty(resp))
        msh = meshSet(msh,'smooth_sinc_method',str2num(resp{1}));
        msh = meshSet(msh,'smooth_iterations',str2num(resp{2}));
        msh = meshSet(msh,'smooth_relaxation',str2num(resp{3}));
    else
        newMsh = msh;
        return
    end
end
fprintf('[%s]: Smoothing mesh...', mfilename)
smoothedMsh = smooth_mesh(msh);
fprintf('done. \n');
newMsh = msh;

newMsh = meshSet(newMsh,'vertices',meshGet(smoothedMsh,'vertices'));
newMsh = meshSet(newMsh,'colors',meshGet(smoothedMsh,'colors'));
newMsh = meshSet(newMsh,'normals',meshGet(smoothedMsh,'normals'));
newMsh = meshSet(newMsh,'triangles',meshGet(smoothedMsh,'triangles'));

% update display if it's open - which we detect by the presence of an id
if newMsh.id > 0
    mrmSet(newMsh, 'vertices');
end

return


function plaza = clear_boundary(plaza)

[a,b] = size(plaza);
for i = 1:b
    if plaza(a,i) > 0
        plaza(a,i) = 0;
    end
end


% Use get_pencil_curves to draw a polyline for an elaborate two-dimensional
% shape that you like. Be creative!


% USERDATAGRAPH  User data for SLAMTB_GRAPH.
%   Edit this script to enter the information you need for SLAM. Variable
%   names and comments should make this file easy to understand. Follow
%   these guidelines:
%
%   * Specify site and estimation details for the current run in ExpOpt.
%   * Specify sampling time and start and end frames in Tim.
%   * Use as many robots and sensors as you wish with Robot{} and Sensor{}.
%   * Assign sensors to robots via Sensor{i}.robot.
%   * Use field Sensor{i}.distortion for radial distortion parameters if
%   desired.
%   * Use the field Opt.map.numLmk and .lmkSize to specify the maximum
%   number of landmarks that the SLAM map must support.
%   * Use Opt.init.initType to select the type of landmarks to use. Try
%   with one in this list:
%       'eucPnt'. -- only this one is supported so far.
%   * Use World.points to create artificial worlds of points.
%   Check function THICKCLOISTER.
%
%   See further comments within the file for more detailed information.
%
%   NOTE: You can have multiple copies of this file with different names to
%   store different simulation conditions. Just modify the call in
%   SLAMTB_GRAPH to point to the particular 'USERDATAGRAPH' file you want.
%
%   See also SLAMTB_GRAPH, EULERANGLES, THICKCLOISTER.

%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.
%   Copyright 2015-     Joan Sola @ IRI-CSIC-UPC.

% Time variables
%   - sampling time, first and last frames
Time = struct(...
  'dt',                   .1,...          % sampling time, seconds
  'firstFrame',           1,...           % first frame #
  'lastFrame',            800);           % last frame #

% Simulated world
%   - Simulation landmark sets, playground dimensions
World = struct(...
  'points',           thickCloister(-6,6,-6,6,1,7),... % 3d point landmarks - see THICKCLOISTER.
  'segments',         []);  % 3D segments - see HOUSE.

% Robot things with their controls
%   - each robot's type and initial configuration, and controls.
%   - motion models (add new model strings if you need more):
%       'constVel'    6D Constant velocity model
%       'odometry'    6D Odometry model
%       'inertial'    6D IMU-based model
%   - See EULERANGLES for orientations specifications.
Robot{1} = struct(...                  % ODOMETRY EXAMPLE
  'id',                 1,...           % robot identifier
  'name',               'Dala',...      % robot name
  'type',               'atrv',...      % type of robot
  'motion',             'odometry',...  % motion model
  'position',           [0;-5;0],...     % robot position in map
  'orientationDegrees', [0;0;0],...     % orientation, in degrees, [roll; pitch; yaw].
  'positionStd',        [0;0;0],...     % position error, std
  'orientationStd',     [0;0;0],...     % orient. error, std, in degrees
  'dx',                 [.08;0;0],...     % position increment
  'daDegrees',          [0;0;.9],...     % angle increment, degrees
  'dxStd',              0.03*[1;1;1],...  % odo linear error std
  'daStd',              0.3*[1;1;1]);      % odo ang error std, degrees

% Robot{2} = struct(...                  % ODOMETRY EXAMPLE
%   'id',                 2,...           % robot identifier
%   'name',               'Dala',...      % robot name
%   'type',               'atrv',...      % type of robot
%   'motion',             'odometry',...  % motion model
%   'position',           [0;5;0],...     % robot position in map
%   'orientationDegrees', [0;0;180],...     % orientation, in degrees, [roll; pitch; yaw].
%   'positionStd',        [0;0;0],...     % position error, std
%   'orientationStd',     [0;0;0],...     % orient. error, std, in degrees
%   'dx',                 [.08;0;0],...     % position increment
%   'daDegrees',          [0;0;.9],...     % angle increment, degrees
%   'dxStd',              0.005*[1;1;1],...  % odo linear error std
%   'daStd',              0.05*[1;1;1]);      % odo ang error std, degrees

% Sensor things
%   - each sensor's type and parameters, noise, non-measurable prior.
%   - Sensor types (add new type strings if you need more):
%       'pinHole'       Pin-hole camera
%       'pinHoleDepth'  Pin-hole camera with depth measurement (RGBD)
%   - See EULERANGLES for orientations specifications.
% Sensor{1} = struct(...
%   'id',                 1,...           % sensor identifier
%   'name',               'Micropix',...  % sensor name
%   'type',               'pinHole',...   % type of sensor
%   'robot',              1,...           % robot where it is mounted
%   'position',           [0;0;.6],...    % position in robot
%   'orientationDegrees', [-90;0;-90],... % orientation in robot, [roll; pitch; yaw]
%   'positionStd',        [0;0;0],...     % position error std
%   'orientationStd',     [0;0;0],...     % orient. error std
%   'imageSize',          [640;480],...   % image size
%   'pixErrorStd',        1.0,...         % pixel error std
%   'intrinsic',          [320;240;320;320],... % intrinsic params [u0 v0 au av]
%   'distortion',         [-0.3;0.1],...          % distortion params
%   'frameInMap',         false,...       % add sensor frame in slam map?
%   'imGrid',               struct(...      % grid for Active Search
%     'numCells',         [8;6],...         % number of H and V grid cells
%     'skipOuter',        true));           % skip outer cells for initialization?

Sensor{1} = struct(...
  'id',                 1,...           % sensor identifier
  'name',               'Micropix',...  % sensor name
  'type',               'pinHoleDepth',...   % type of sensor
  'robot',              1,...           % robot where it is mounted
  'position',           [0;0;.6],...    % position in robot
  'orientationDegrees', [-90;0;-90],... % orientation in robot, [roll; pitch; yaw]
  'positionStd',        [0;0;0],...     % position error std
  'orientationStd',     [0;0;0],...     % orient. error std
  'imageSize',          [640;480],...   % image size
  'pixErrorStd',        1.0,...         % pixel error std [pixels]
  'depthErrorStd',      0.5,...         % depth error std [m]
  'intrinsic',          [320;240;320;320],... % intrinsic params [u0 v0 au av]
  'distortion',         [],...          % distortion params, e.g. [-0.3;0.1]
  'frameInMap',         false,...       % add sensor frame in slam map?
  'imGrid',             struct(...      % grid for Active Search
    'numCells',         [8;6],...         % number of H and V grid cells
    'skipOuter',        true));           % skip outer cells for initialization?

% Estimation options
Opt = struct(...
  'map',              struct(...    % options for the map
    'type',           'graph',...    % type of map {'ekf','graph'}
    'numLmks',        73,...         % number of 3d landmarks
    'lmkSize',        3,...          % Size of landmark state
    'lmkDSize',       3,...          % Size of lmk error state
    'numFrames',      25,...         % number of frames in graph
    'kfrmPeriod',     20),...        % period between keyframes
  'solver',           struct(...    % graph solver
    'decomposition',  'QR',...        % Matrix decomposition {'Cholesky', 'QR', 'Schur'}
    'niterations',    1,...           % number of iterations
    'target_dres',    1e-2,...        % exit criterion for residual variation
    'target_res',     1e-3),...       % exit criterion for current residual
  'correct',          struct(...    % options for lmk correction
    'reprojectLmks',  false,...       % reproject lmks after active search?
    'reparametrize',  true,...       % reparametrize lmk?
    'nUpdates',       10,...          % max simultaneus updates
    'MD2th',          9,...          % Threshold on Mahalanobis distance squared
    'linTestIdp',     0.1,...        % threshold on IDP linearity test
    'lines',          struct(...     % options for line corrections
      'innType',      'ortDst',...    % innovation type for lines
      'extPolicy',    false,...       % line extending policy ?
      'extSwitch',    10)),...        % extension policy switch point in pixels
  'init',             struct(...    % Options for initialization
    'nbrInits',       [5 3],...      % number of inits [firstFrame, otherFrames]
    'initType',       'eucPnt',...   % Type of lmk to use for init
    'idpPnt',         struct(...     % options for lmk initialization
      'nonObsMean',   .1,...         % mean of non obs
      'nonObsStd',    .5),...         % std of non obs
    'plkLin',         struct(...     % opt. for Plucker and anchored Plucker lines init
      'nonObsMean',   [.1;0],...      % mean of non obs
      'nonObsStd',    [.25;1])),...   % std of non obs
  'obs',              struct(...    % Observation options
    'lines',          struct(...     % lines options
      'minLength',    20)));          % minimum segment length

% Simulation options
%   - random
SimOpt = struct(...
  'random',           struct(...      % random generator options
    'newSeed',        false,...         % select new random seed?
    'fixedSeed',      209065,...       % random seed for non-random runs
    'seed',           []),...          % current seed
  'obs',              Opt.obs);       % Observation options

% Figure options
%   - view, projection, video, ellipses.
%   - figure projections - mapProj:
%       'persp'     Perspective
%       'ortho'     Orthographic
%   - 3D figure views - mapView - see MAPOBSERVER.
%       [a,e,f]     Custom azimuth/elevation/FOV vector. Distance automatic
%       [a,e,f,d]   custom az/el/fov/distance vector.
%   - 3D figure predefined views (edit mapObserver.m to create/edit views):
%       'top'       Top view
%       'side'      Side view
%       'view'      Generic view
%       'normal'    Normal view
%   - objects colors - two options for color specification:
%       'rgbcmykw'  1-char predifined Matlab colors
%       [r g b]     RGB color vector. [0 0 0] is black, [1 1 1] is white.
FigOpt = struct(...
  'renderer',       'zbuffer',...    % renderer
  'rendPeriod',     10,...           % frames to skip for faster processing
  'createVideo',    false,...       % create video sequences?
  'map',            struct(...      % map figure options
    'size',         [320 240],...   % map figure size
    'lims',         struct(...      % playground limits
      'xMin',            -10,...
      'xMax',             10,...
      'yMin',            -10,...
      'yMax',             10,...
      'zMin',            -10,...
      'zMax',             10),...
    'proj',         'persp',...     % projection of the 3d figure {'persp', 'ortho'}
    'view',         'view',...      % viewpoint of the 3d figure [30 45 40 20]
    'orbit',        [0 0],...       % Azimuth and Elevation orbit angle increments - use to animate figure
    'showSimLmk',   false,...        % show simulated landmarks?
    'showLmkId',    true,...        % Show landmark id?
    'showEllip',    true,...        % show ellipsoids?
    'showMotFac',   true,...        % show motion factors?
    'showMeaFac',   false,...       % show measurement factors?
    'colors',       struct(...      % map figure colors
      'border',     [1 1 1],...      %   [r g b]
      'axes',       [0 0 0],...      % with:
      'bckgnd',     [1 1 1],...      %   [0 0 0] black
      'simLmk',     .3*[1 1 1],...   %   [1 1 1] white
      'defPnt',     struct(...       % euclidean point colors
        'mean',     'b',...           % mean dot
        'ellip',    [.7 .7 1]),...    % ellipsoid
      'othPnt',     struct(...       % other point colors
        'mean',     'r',...           % mean dot
        'ellip',    [1 .7 .7]),...    % ellipsoid
      'defLin',     struct(...       % Plucker line colors
        'mean',     [0 .8 0],...      % mean line
        'ellip',    [.6 1 .6]),...    % ellipsoid
      'othLin',     struct(...       % Plucker line colors
        'mean',     [.8 0 0],...      % mean line
        'ellip',    [1 .6 .6]),...    % ellipsoid
      'graph',      struct(...       % graph
        'frame',    'b',...           % frame
        'motion',   'b',...           % motion factors
        'meas',     [1 .8 .6]),...          % measurement factors
      'simu',       'b',...          %   or 'r', 'b', etc.
      'est',        'g',...          % estimated robots and sensors
      'ground',     [.8 .8 .8],...   % simulated robots and sensors
      'label',      [.0 .5 0])),...  % landmark ID labels
  'sensor',         struct(...      % sensor figures options
    'size',         [320 240],...    % sensor figure size
    'showEllip',    false,...        % show ellipses?
    'colors',       struct(...       % Sensor figure colors:
      'border',     .8*[1 1 1],...    %
      'axes',       [0 0 0],...       %
      'bckgnd',     [1 1 1],...       %
      'raw',        .3*[1 1 1],...    %
      'defPnt',     struct(...       % Default point colors
        'updated',  'c',...           % updated
        'predicted','b'),...          % predicted
      'othPnt',     struct(...       % other point colors
        'updated',  'r',...           % updated
        'predicted','m'),...          % predicted
      'defLin',     struct(...       % Default line colors
        'meas',     'b',...           % measurement
        'mean',     'g',...           % mean line
        'ellip',    'y'),...          % ellipsoid
      'othLin',     struct(...       % other line colors
        'meas',     'b',...           % measurement
        'mean',     'm',...           % mean line
        'ellip',    'r'),...          % ellipsoid
      'label',      [.5 .5 .5])));    %

% Experiment options
%   - site name, series gathered, estimation run number
ExpOpt = struct(...
  'root',         '~/SLAM/',...         % root directory
  'site',         'simu',...            % Name of the site
  'dataRun',      1,...                 % Run # on this site
  'estimateRun',  1,...                 % slam run for data and site
  'lmkTypes',     Opt.init.initType,... % types of landmarks used
  'sensingType',  'mono',...            % sensing mode
  'mappingType',  'single');            % mapping mode

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB 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.
%
%   SLAMTB 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 SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE


% std_figtitle() - Generate plotting figure titles in a cell array
%
% Usage:
%   >> celltxt = std_figtitle(key1, val1, key2, val2);
%
% Inputs:
%  'subject'     - [string] Subject name
%  'datatype'    - [string] data type (For example 'erp')
%  'chanlabels'  - [cell array or string] channel names
%  'compnames'   - [cell array or string] component names
%  'condnames'   - [cell array] names of conditions
%  'cond2names'  - [cell array] names of conditions
%  'vals'        - [cell array or real array] value for plot panel (for
%                  example, 0 ms)
%  'valsunit'    - [cell array or string] unit value (i.e. ms)
%
% Optional statistical titles:
%  'condstat'    - ['on'|'off'] default is 'off'
%  'cond2stat'   - ['on'|'off'] default is 'off'
%  'mcorrect'    - [string] correction for multiple comparisons. Default is
%                  empty.
%  'statistics'  - [string] type of statictics
%  'threshold'   - [real] treshold value
%
% Optional grouping:
%  'condgroup'   - ['on'|'off'] group conditions together default is 'off'
%  'cond2group'  - ['on'|'off'] default is 'off'
%
% Outputs:
%   celltxt      - cell array of text string, one for each set of condition
%
% Example:
%  std_figtitle('subject', 'toto', 'condnames', { 'test1' 'test2' }, ...
%               'vals' , { [100] [4] }, 'valsunit', { 'ms' 'Hz' })
%
% Authors: Arnaud Delorme, SCCN/UCSD, Feb 2010

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

function [all_titles alllegends ] = std_figtitle(varargin)

if nargin < 1
    help std_figtitle;
    return;
end;

alllegends = {};
opt = finputcheck( varargin, { 'chanlabels'  {'cell' 'string'}   []     {};
                               'condnames'   {'cell' 'string'}   []     '';
                               'cond2names'  {'cell' 'string'}   []     '';
                               'condstat'    'string'            {'on' 'off'}     'off';
                               'cond2stat'   'string'            {'on' 'off'}     'off';
                               'condgroup'   'string'            {'on' 'off' 'together' 'apart'}     'off';
                               'cond2group'  'string'            {'on' 'off' 'together' 'apart'}     'off';
                               'plotmode'    'string'            {'normal' 'condensed'}              'normal';
                               'plotsubjects' 'string'           {'on' 'off'}                        'off';
                               'threshold'   'real'              []     NaN;
                               'statistics'  'string'            []     '';
                               'mcorrect'    'string'            []     '';
                               'datatype'    'string'            []     '';
                               'clustname'   'string'            []     '';
                               'compnames'   {'cell' 'string'}   []     {};
                               'vals'        {'cell' 'real'}     []     {}; % just for titles
                               'valsunit'    {'cell' 'string'}   []     {}; % just for titles
                               'subject'     'string'            []              '' }, 'std_figtitle'); %, 'ignore');
if isstr(opt), error(opt); end;
if ~iscell(opt.vals),       opt.vals       = { opt.vals }; end;
ncori  = length(opt.condnames);
nc2ori = length(opt.cond2names);
if ~isempty(opt.vals) && ~isempty(opt.vals{1}) && ~isnan(opt.vals{1}(1)), opt.condgroup = 'off'; opt.cond2group = 'off'; end;
if strcmpi(opt.plotmode, 'condensed'), opt.condgroup = 'on';  opt.cond2group = 'on';  end;
if strcmpi(opt.plotsubjects, 'on'),    opt.condgroup = 'off'; opt.cond2group = 'off'; end;
if strcmpi(opt.plotsubjects, 'on')
    opt.condgroup  = 'apart';
    opt.cond2group = 'apart';
end;
if strcmpi(opt.condgroup,  'on'), opt.condgroup =  'together'; end;
if strcmpi(opt.cond2group, 'on'), opt.cond2group = 'together'; end;

if strcmpi(opt.condgroup,  'together') &&  strcmpi(opt.cond2stat, 'on'),  opt.condgroup  = 'apart'; end;
if strcmpi(opt.cond2group, 'together') &&  strcmpi(opt.condstat , 'on') , opt.cond2group = 'apart'; end;
if ~( strcmpi(opt.condgroup,  'together') && strcmpi(opt.cond2group, 'together') )
    if strcmpi(opt.condgroup,  'together'), alllegends = opt.condnames ; opt.condnames  = ''; end;
    if strcmpi(opt.cond2group, 'together'), alllegends = opt.cond2names; opt.cond2names = ''; end;
end;
if ~iscell(opt.valsunit),   opt.valsunit   = { opt.valsunit }; end;
if ~iscell(opt.chanlabels), opt.chanlabels = { opt.chanlabels }; end;
if ~iscell(opt.condnames),  opt.condnames  = { opt.condnames }; end;
if ~iscell(opt.cond2names), opt.cond2names = { opt.cond2names }; end;
if isempty(opt.condnames),  opt.condnames{1}  = ''; end;
if isempty(opt.cond2names), opt.cond2names{1} = ''; end;

for c1 = 1:length(opt.condnames)
    for c2 = 1:length(opt.cond2names)

        % value (ms or Hz)
        % ----------------
        fig_title1 = '';
        for i = 1:length(opt.vals)
            if ~isempty(opt.vals{i}) && ~isnan(opt.vals{i}(1))
                if opt.vals{i}(1) == opt.vals{i}(end), fig_title1 = [ num2str(opt.vals{i}(1)) '' opt.valsunit{i} fig_title1];
                else                                   fig_title1 = [ num2str(opt.vals{i}(1)) '-' num2str(opt.vals{i}(2)) '' opt.valsunit{i} fig_title1 ];
                end;
                if length(opt.vals) > i, fig_title1 = [ ' & ' fig_title1 ]; end;
            end;
        end;

        % conditions
        % ----------
        if ~isempty(opt.condnames{c1})
            fig_title1 = [ value2str(opt.condnames{c1}) ', ' fig_title1];
        end;
        if ~isempty(opt.cond2names{c2})
            fig_title1 = [ value2str(opt.cond2names{c2}) ', ' fig_title1];
        end;

        % channel labels, component name, subject name and datatype
        % ---------------------------------------------------------
        fig_title2 = '';
        if length( opt.chanlabels ) == 1 && ~isempty( opt.chanlabels{1} )
            fig_title2 = [ opt.chanlabels{1} ', ' fig_title2 ];
        end;

        % cluster and component name
        % --------------------------
        if ~isempty( opt.clustname )
            if ~isempty( opt.compnames )
                if iscell( opt.compnames )
                     compstr = [ 'C' num2str(opt.compnames{min(c1,size(opt.compnames,1)),min(c2,size(opt.compnames,2))}) ];
                else compstr = [ opt.compnames ];
                end;
            else compstr = '';
            end;
            if ~isempty( opt.subject )
                if ~isempty( compstr )
                     fig_title2 = [ opt.subject '/' compstr ', ' fig_title2 ];
                else fig_title2 = [ opt.subject ', ' fig_title2 ];
                end;
            elseif ~isempty( compstr )
                fig_title2 = [ compstr ', ' fig_title2 ];
            end;

            if ~isempty( opt.datatype )
                 fig_title2 = [ opt.clustname ' ' opt.datatype ', ' fig_title2 ];
            else fig_title2 = [ opt.clustname ', ' fig_title2 ];
            end;

        else
            if ~isempty( opt.compnames )
                if iscell( opt.compnames )
                else fig_title2 = [ 'C' num2str(opt.compnames{c1,c2}) ', ' fig_title2 ];
                     fig_title2 = [ opt.compnames        ', ' fig_title2 ];
                end;
            end;

            % subject and data type
            % ---------------------
            if ~isempty( opt.subject )
                if ~isempty( opt.datatype )
                     fig_title2 = [ opt.subject ' ' opt.datatype ', ' fig_title2 ];
                else fig_title2 = [ opt.subject ', ' fig_title2 ];
                end;
            elseif ~isempty( opt.datatype )
                fig_title2 = [ opt.datatype ' - ' fig_title2 ];
            end;
        end;

        if strcmpi(opt.cond2group, 'together') && strcmpi(opt.condgroup, 'together')
            fig_title = fig_title2;
            if ~isempty(fig_title1) && strcmpi(fig_title1(end-1:end), ', '), fig_title1(end-1:end) = []; end;
            if ~isempty(fig_title1) && strcmpi(fig_title1(end-1:end), '- '), fig_title1(end-1:end) = []; end;
            alllegends{c1, c2} = fig_title1;
        else
            fig_title = [ fig_title2 fig_title1 ];
        end;
        if ~isempty(fig_title) && strcmpi(fig_title(end-1:end), ', '), fig_title(end-1:end) = []; end;
        if ~isempty(fig_title) && strcmpi(fig_title(end-1:end), '- '), fig_title(end-1:end) = []; end;
        all_titles{c1,c2}  = fig_title;

    end;
end;
if ~isempty(alllegends)
    alllegends = alllegends';
    alllegends = alllegends(:)';

    % convert legends to string if necessary
    % --------------------------------------
    for ileg = 1:length(alllegends), alllegends{ileg} = num2str(alllegends{ileg}); end;
end;

% statistic titles
% ----------------
if isnan(opt.threshold),
    basicstat = '(p-value)';
else
    if length(opt.threshold) >= 1
        basicstat = sprintf([ '(p<%.' thresh_pres(opt.threshold(1)) 'f)'], opt.threshold(1));
    end;
    if length(opt.threshold) >= 2
        basicstat = [ basicstat(1:end-1) sprintf([' red;p<%.' thresh_pres(opt.threshold(2))  'f brown)'], opt.threshold(2)) ];
    end;
    if length(opt.threshold) >= 3
        basicstat = [ basicstat(1:end-1) sprintf([';\np<%.' thresh_pres(opt.threshold(3)) 'f black)' ], opt.threshold(3)) ];
    end;
end;
if ~isempty(opt.statistics), basicstat = [ basicstat ' ' opt.statistics    ]; end;
if ~isempty(opt.mcorrect) && ~strcmpi(opt.mcorrect, 'none'),   basicstat = [ basicstat ' with ' opt.mcorrect ]; end;
if strcmpi(opt.condstat, 'on')
    rown = size(all_titles,1)+1;
    for c2 = 1:length(opt.cond2names)
        all_titles{rown, c2} = [ num2str(opt.cond2names{c2}) ' ' basicstat ];
    end;
end;
if strcmpi(opt.cond2stat, 'on')
    coln = size(all_titles,2)+1;
    for c1 = 1:length(opt.condnames)
        all_titles{c1, coln} = [ num2str(opt.condnames{c1}) ' ' basicstat ];
    end;
end;
if strcmpi(opt.condstat, 'on') && strcmpi(opt.cond2stat, 'on')
   all_titles{rown, coln} = [ 'Interaction ' basicstat ];
end;

function pres = thresh_pres(thresh_pres);
    if (round(thresh_pres*100)-thresh_pres*100) == 0
        pres = 2;
    elseif (round(thresh_pres*1000)-thresh_pres*1000) == 0
        pres = 3;
    else
        pres = -round(log10(thresh_pres))+1;
    end;
    pres = num2str(pres);

% convert
% -------
function str = value2str(value)

    if isstr(value)
        str = value;
    elseif isnumeric(value)
        if length(value) == 1
            str = num2str(value);
        else
            str = num2str(value(1));
            if length(value) <= 5
                for ind = 2:length(value)
                    str = [ str ' & ' num2str(value(ind)) ];
                end;
            else
                str = [ str ' & ' num2str(value(2)) ' & ...' ];
            end;
        end;
    else % cell array
        str = value{1};
        for ind = 2:length(value)
            str = [ str ' & ' value{ind} ];
        end;
    end;


function params = gpSubspaceExtractParam(model)

% GPSUBSPACEEXTRACTPARAM
%
% COPYRIGHT : Carl Henrik Ek, 2008

% GP

params = gpExtractParam(model);

return;


%DRAWMATCHES  Draws the found matches of keypoints from two images
%
%     out = cv.drawMatches(im1, keypoints1, im2, keypoints2, matches1to2)
%     out = cv.drawMatches(..., 'OptionName', optionValue, ...)
%
% ## Input
% * __im1__ First source image.
% * __keypoints1__ Keypoints from the first source image. A 1-by-N structure
%   array with the following fields:
%   * __pt__ coordinates of the keypoint `[x,y]`
%   * __size__ diameter of the meaningful keypoint neighborhood
%   * __angle__ computed orientation of the keypoint (-1 if not applicable).
%     Its possible values are in a range [0,360) degrees. It is measured
%     relative to image coordinate system (y-axis is directed downward), i.e
%     in clockwise.
%   * __response__ the response by which the most strong keypoints have been
%     selected. Can be used for further sorting or subsampling.
%   * __octave__ octave (pyramid layer) from which the keypoint has been
%     extracted.
%   * **class_id** object id that can be used to clustered keypoints by an
%     object they belong to.
% * __im2__ Second source image.
% * __keypoints2__ Keypoints from the second source image. Same format as
%   `keypoints1`.
% * __matches1to2__ Matches from the first image to the second one, which means
%   that `keypoints1(i)` has a corresponding point in `keypoints2(matches(i))`.
%   A 1-by-M structure array with the following fields:
%   * __queryIdx__ query descriptor index (zero-based index)
%   * __trainIdx__ train descriptor index (zero-based index)
%   * __imgIdx__ train image index (zero-based index)
%   * __distance__ distance between descriptors (scalar)
%
% ## Output
% * __out__ Output image. Its content depends on the option values defining
%   what is drawn in the output image. See possible options below. By default,
%   the two source images, matches, and single keypoints will be drawn. For
%   each keypoint, only the center point will be drawn (without a circle
%   around the keypoint with the keypoint size and orientation).
%
% ## Options
% * __MatchColor__ Color of matches (lines and connected keypoints). If all -1,
%   the color is generated randomly. default [-1,-1,-1,-1].
% * __SinglePointColor__ Color of single keypoints (circles), which means that
%   keypoints do not have the matches. If all -1, the color is generated
%   randomly. default [-1,-1,-1,-1].
% * __MatchesMask__ Mask determining which matches are drawn. If the mask is
%   empty, all matches are drawn. default empty.
% * __NotDrawSinglePoints__ Single keypoints will not be drawn. default false
% * __DrawRichKeypoints__ For each keypoint, the circle around keypoint with
%   keypoint size and orientation will be drawn. default false.
% * __OutImage__ If set, matches will be drawn on existing content of output
%   image, otherwise source image is used instead. Default not set
%
% This function draws matches of keypoints from two images in the output
% image. Match is a line connecting two keypoints (circles).
%
% In pseudo-code, the function works as follows:
%
%     for m=1:numel(matches1to2)
%         if ~MatchesMask(m), continue, end
%         kp1 = keypoints1(matches1to2(m).queryIdx + 1);
%         kp2 = keypoints2(matches1to2(m).trainIdx + 1);
%         draw_match(kp1, kp2);
%     end
%
% See also: cv.drawKeypoints, showMatchedFeatures
%


function model = gpdisimOptimise(model, display, iters);

% GPDISIMOPTIMISE Optimise the GPSIM model.
% FORMAT
% DESC optimises the Gaussian process single input motif model for
% a given number of iterations.
% ARG model : the model to be optimised.
% ARG display : whether or not to display while optimisation
% proceeds, set to 2 for the most verbose and 0 for the least
% verbose.
% ARG iters : number of iterations for the optimisation.
% RETURN model : the optimised model.
%
% SEEALSO : scg, conjgrad, gpdisimCreate, gpdisimGradient, gpdisimObjective
%
% COPYRIGHT : Neil D. Lawrence, 2006
%
% COPYRIGHT : Antti Honkela, 2007

% SHEFFIELDML

if nargin < 3
  iters = 2000;
  if nargin < 2
    display = 1;
  end
end

params = gpdisimExtractParam(model);

options = optOptions;
if display
  options(1) = 1;
  if length(params) <= 100
    options(9) = 1;
  end
end
options(14) = iters;

if isfield(model, 'optimiser')
  optim = str2func(model.optimiser);
else
  optim = str2func('conjgrad');
end

params = optim('gpdisimObjective', params,  options, ...
               'gpdisimGradient', model);

model = gpdisimExpandParam(model, params);


function vars = depends(F)

vars = depends(lmi(F));


function varargout = ode113(varargin)
%ODE113   Solve stiff differential equations and DAEs. Output a CHEBFUN.
%
% This syntax is deprecated. Please use chebfun.ode113(...) instead.

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

warning('CHEBFUN:DOMAIN:ode113:deprecated', ...
    ['Usage of ODE113 via the @DOMAIN class is deprecated and may be ', ...
    'removed from future releases. Please use chebfun.ode113(...) instead.']);

varargin = domain.toDouble(varargin{:});

varargout{1:nargout} = chebfun.ode113(varargin{:});

end


function header=nifticreate(img,format)
%
%    header=nifticreate(img)
%       or
%    header=nifticreate(img,format)
%
%    Create a default NIfTI header
%
%    author: Qianqian Fang (q.fang <at> neu.edu)
%
%    input:
%        img: the image data matching the header
%        format: can only be 'nifti1'. can be ignored
%
%    output:
%        header: a struct that is byte-wise compatible with NIfTI-1
%
%    this file is part of JNIfTI specification: https://github.com/fangq/jnifti
%
%    License: Apache 2.0, see https://github.com/fangq/jnifti for details
%

if(nargin<2)
    format='nifti1';
end

datatype=struct('int8',256,'int16',4,'int32',8,'int64',1024,'uint8',2,'uint16',512,'uint32',768,'uint64',1280,'single',16,'double',64);

if(strcmp(format,'nifti1'))
    headerlen=348;
else
    headerlen=540;
end

header=memmapstream(uint8(zeros(1,headerlen+4)),niiformat(format));
header.sizeof_hdr=cast(headerlen, class(header.sizeof_hdr));
header.datatype=cast(datatype.(class(img)), class(header.datatype));
header.dim(1:end)=cast(1,class(header.dim));
header.dim(1:ndims(img)+1)=cast([ndims(img),size(img)], class(header.dim));
header.pixdim(1:ndims(img)+1)=cast(1, class(header.pixdim));
header.vox_offset=cast(headerlen+4, class(header.vox_offset));
if(header.sizeof_hdr==540)
    header.magic(1:3)=cast('ni2',class(header.magic));
else
    header.magic(1:3)=cast('ni1',class(header.magic));
end
header.srow_x(1)=cast(1, class(header.srow_x));
header.srow_y(2)=cast(1, class(header.srow_y));
header.srow_z(3)=cast(1, class(header.srow_z));
header.sform_code=cast(1, class(header.sform_code));


function [ actions ] = BuildActionList
%BuildActionList

%actions for the mountain car problem
actions = [-1.0; 1.0];


function [Fc,Vc]=patchDetach(varargin)

% function [Fc,Vc]=patchDetach(F,V,scaleFactor)
%-------------------------------------------------------------------------
%
%
% Change log:
% 2010
% 2019/04/23 Updated function header text
%-------------------------------------------------------------------------

%%

[Fc,Vc]=scalePatch(varargin{:});

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


function view = meshLighting(view, msh, L, distance);
% Set the lighting parameters for a surface mesh.
%
% view = meshLighting(<view>, <msh>, <L, distance=dialog>);
%
% view: mrVista view w/ mesh loaded. Defaults to selected gray.
%
% msh: mesh structure. Defaults to current mesh in view.
%
% L: structure with two fields:
%	ambient: [r g b] ambient lighting parameter (not sure details myself?)
%	diffuse: [r g b] diffuse lighting parameter
%
% distance: flag to move lights closer to, or further from, the mesh origin
% (and the mesh). If 1, don't move; <1, move closer; >1, move further away.
%
% If either L or distance are omitted, pops up a dialog.
%
% ras, 04/2008
if notDefined('view'), view = getSelectedGray; end
if notDefined('msh'), msh = viewGet(view,'currentmesh'); end

if isnumeric(msh), msh = view.mesh{msh};		end

lights = meshGet(msh,'lights');

% get params from dialog, if they're not provided
if notDefined('L') | notDefined('distance')
	%% put up a dialog for editing lighting levels --
	% for this function, we set the coefficients for all
	% lights to be the same. Build up an 'L' light struct
	% which will eventually be handed to mrMesh:
	if iscell(lights)
		L.diffuse = lights{1}.diffuse;
		L.ambient = lights{1}.ambient;
	else
		L.diffuse = lights(1).diffuse;
		L.ambient = lights(1).ambient;
	end

	% create the dialog
	dlg(1).fieldName = 'ambient';
	dlg(1).style	 = 'edit';
	dlg(1).string	 = 'Ambient Light Level';
	dlg(1).value	 = num2str(L.ambient);

	dlg(2).fieldName = 'diffuse';
	dlg(2).style	 = 'edit';
	dlg(2).string	 = 'Light Diffusion Coeffcient';
	dlg(2).value	 = num2str(L.diffuse);

	dlg(3).fieldName = 'distance';
	dlg(3).style	 = 'edit';
	dlg(3).string	 = ['Move lights closer (<1) or further (>1) ' ...
						'from current distance?'];
	dlg(3).value	 = '1';

	% get the response
	resp = generalDialog(dlg, 'Set Mesh Lighting');

	% parse the response
	L.diffuse = str2num(resp.diffuse);
	L.ambient = str2num(resp.ambient);
	distance  = str2num(resp.distance);
end

% apply the user settings to each light
host = meshGet(msh, 'host');
windowID = meshGet(msh, 'windowID');
for n = 1:length(lights)
	if iscell(lights)
		L.actor = lights{n}.actor;
		if distance ~= 1
			L.origin = distance .* lights{n}.origin;
		end

		lights{n} = mergeStructures(lights{n}, L);
	else
		L.actor = lights(n).actor;
		if distance ~= 1
			L.origin = distance .* lights(n).origin;
		end

		lights(n) = mergeStructures(lights(n), L);
	end
     mrMesh(host, windowID, 'set', L);
end

% update mesh, lights in view
msh = meshSet(msh, 'lights', lights);
view = viewSet(view, 'mesh', msh);

return


function varargout = plot(varargin)
% plot method for GIfTI objects
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Guillaume Flandin
% $Id: plot.m 7513 2019-01-15 15:17:29Z guillaume $

% if ishandle(varargin{1})
%     h = figure(varargin{1});
% else
%     h = figure;
%     %axis equal;
%     %axis off;
%     %camlight;
%     %camlight(-80,-10);
%     %lighting gouraud;
% end
% cameratoolbar;

cdata = [];
ax = [];
if nargin == 1
    this = varargin{1};
    h = gcf;
else
    if ishandle(varargin{1})
        ax = varargin{1};
        h = figure(get(ax,'parent'));
        this = varargin{2};
    else
        this = varargin{1};
        h = gcf;
        cdata = subsref(varargin{2},struct('type','.','subs','cdata'));
    end
    if nargin > 2
        indc = varargin{3};
    else
        indc = 1;
    end
end

if isempty(ax), ax = axes('Parent',h); end
axis(ax,'equal');
axis(ax,'off');
hp = patch(struct(...
    'vertices',  subsref(this,struct('type','.','subs','vertices')),...
    'faces',     subsref(this,struct('type','.','subs','faces'))),...
    'FaceColor', 'b',...
    'EdgeColor', 'none',...
    'Parent',ax);

if ~isempty(cdata)
    set(hp,'FaceVertexCData',cdata(:,indc), 'FaceColor','interp')
end

axes(ax);
camlight;
camlight(-80,-10);
lighting(ax,'gouraud');
if strcmp(spm_check_version,'matlab')
    cameratoolbar(h);
end

if nargout
    varargout{1} = hp;
end


function colorsPlot(red, green, blue, justGreen)
%CREATEFIGURE(red,green,blue,justGreen)
%  red:  image cdata
%  green:  image cdata
%  blue:  image cdata
%  justGreen:  image cdata

%  Auto-generated by MATLAB on 12-Nov-2007 09:55:06

% Copyright 2011 The MathWorks, Inc.

% Create figure
figure1 = figure('Colormap',...
    [0 0 0;0.01587 0.01587 0.01587;0.03175 0.03175 0.03175;0.04762 0.04762 0.04762;0.06349 0.06349 0.06349;0.07937 0.07937 0.07937;0.09524 0.09524 0.09524;0.1111 0.1111 0.1111;0.127 0.127 0.127;0.1429 0.1429 0.1429;0.1587 0.1587 0.1587;0.1746 0.1746 0.1746;0.1905 0.1905 0.1905;0.2063 0.2063 0.2063;0.2222 0.2222 0.2222;0.2381 0.2381 0.2381;0.254 0.254 0.254;0.2698 0.2698 0.2698;0.2857 0.2857 0.2857;0.3016 0.3016 0.3016;0.3175 0.3175 0.3175;0.3333 0.3333 0.3333;0.3492 0.3492 0.3492;0.3651 0.3651 0.3651;0.381 0.381 0.381;0.3968 0.3968 0.3968;0.4127 0.4127 0.4127;0.4286 0.4286 0.4286;0.4444 0.4444 0.4444;0.4603 0.4603 0.4603;0.4762 0.4762 0.4762;0.4921 0.4921 0.4921;0.5079 0.5079 0.5079;0.5238 0.5238 0.5238;0.5397 0.5397 0.5397;0.5556 0.5556 0.5556;0.5714 0.5714 0.5714;0.5873 0.5873 0.5873;0.6032 0.6032 0.6032;0.619 0.619 0.619;0.6349 0.6349 0.6349;0.6508 0.6508 0.6508;0.6667 0.6667 0.6667;0.6825 0.6825 0.6825;0.6984 0.6984 0.6984;0.7143 0.7143 0.7143;0.7302 0.7302 0.7302;0.746 0.746 0.746;0.7619 0.7619 0.7619;0.7778 0.7778 0.7778;0.7937 0.7937 0.7937;0.8095 0.8095 0.8095;0.8254 0.8254 0.8254;0.8413 0.8413 0.8413;0.8571 0.8571 0.8571;0.873 0.873 0.873;0.8889 0.8889 0.8889;0.9048 0.9048 0.9048;0.9206 0.9206 0.9206;0.9365 0.9365 0.9365;0.9524 0.9524 0.9524;0.9683 0.9683 0.9683;0.9841 0.9841 0.9841;1 1 1]);

% Create subplot
subplot1 = subplot(2,2,1,'Parent',figure1,'YDir','reverse','Layer','top');
% Uncomment the following line to preserve the X-limits of the axes
 xlim([0.5 320.5]);
% Uncomment the following line to preserve the Y-limits of the axes
 ylim([0.5 240.5]);
box('on');
hold('all');

% Create image
image(red,'Parent',subplot1,'CDataMapping','scaled');

% Create title
title('Red');

% Create subplot
subplot2 = subplot(2,2,2,'Parent',figure1,'YDir','reverse','Layer','top');
% Uncomment the following line to preserve the X-limits of the axes
 xlim([0.5 320.5]);
% Uncomment the following line to preserve the Y-limits of the axes
 ylim([0.5 240.5]);
box('on');
hold('all');

% Create title
title('Green');

% Create image
image(green,'Parent',subplot2,'CDataMapping','scaled');

% Create subplot
subplot3 = subplot(2,2,3,'Parent',figure1,'YDir','reverse','Layer','top');
% Uncomment the following line to preserve the X-limits of the axes
 xlim([0.5 320.5]);
% Uncomment the following line to preserve the Y-limits of the axes
 ylim([0.5 240.5]);
box('on');
hold('all');

% Create title
title('Blue');

% Create image
image(blue,'Parent',subplot3,'CDataMapping','scaled');

% Create subplot
subplot4 = subplot(2,2,4,'Parent',figure1,'YDir','reverse','Layer','top');
% Uncomment the following line to preserve the X-limits of the axes
 xlim([0.5 320.5]);
% Uncomment the following line to preserve the Y-limits of the axes
 ylim([0.5 240.5]);
box('on');
hold('all');

% Create title
title('Just Green');

% Create image
image(justGreen,'Parent',subplot4,'CDataMapping','scaled');


function [net,stats] = cnn_train_dag(net, imdb, getBatch, varargin)
%CNN_TRAIN_DAG Demonstrates training a CNN using the DagNN wrapper
%    CNN_TRAIN_DAG() is similar to CNN_TRAIN(), but works with
%    the DagNN wrapper instead of the SimpleNN wrapper.

% Copyright (C) 2014-16 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).

opts.expDir = fullfile('data','exp') ;
opts.continue = true ;
opts.batchSize = 256 ;
opts.numSubBatches = 1 ;
opts.averageImage = [];
opts.train = [] ;
opts.val = [] ;
opts.gpus = [] ;
opts.prefetch = false ;
opts.numEpochs = 300 ;
opts.gamma = 0.9;
opts.constraint = 10;
opts.learningRate = 0.001 ;
opts.weightDecay = 0.0005 ;
opts.momentum = 0.9 ;
opts.saveMomentum = true ;
opts.nesterovUpdate = false ;
opts.randomSeed = 0 ;
opts.profile = false ;
opts.parameterServer.method = 'mmap' ;
opts.parameterServer.prefix = 'mcn' ;

opts.derOutputs = {'objective', 1} ;
opts.extractStatsFn = @extractStats ;
opts.plotStatistics = true;
opts = vl_argparse(opts, varargin) ;

if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end
if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end
if isnan(opts.train), opts.train = [] ; end
if isnan(opts.val), opts.val = [] ; end

% -------------------------------------------------------------------------
%                                                            Initialization
% -------------------------------------------------------------------------

evaluateMode = isempty(opts.train) ;
if ~evaluateMode
  if isempty(opts.derOutputs)
    error('DEROUTPUTS must be specified when training.\n') ;
  end
end

% -------------------------------------------------------------------------
%                                                        Train and validate
% -------------------------------------------------------------------------

modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));
modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;

start = opts.continue * findLastCheckpoint(opts.expDir) ;
if start >= 1
  fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ;
  [net, state, stats] = loadState(modelPath(start)) ;
else
  state = [] ;
end

for epoch=start+1:opts.numEpochs

  % Set the random seed based on the epoch and opts.randomSeed.
  % This is important for reproducibility, including when training
  % is restarted from a checkpoint.

  rng(epoch + opts.randomSeed) ;
  prepareGPUs(opts, epoch == start+1) ;

  % Train for one epoch.
  params = opts ;
  params.epoch = epoch ;
  params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
  params.train = opts.train(randperm(numel(opts.train))) ; % shuffle
  params.val = opts.val(randperm(numel(opts.val))) ;
  params.imdb = imdb ;
  params.getBatch = getBatch ;

  if numel(opts.gpus) <= 1
    [net, state] = processEpoch(net, state, params, 'train',opts) ;
    [net, state] = processEpoch(net, state, params, 'val',opts) ;
    if ~evaluateMode
      saveState(modelPath(epoch), net, state) ;
    end
    lastStats = state.stats ;
  else
    spmd
      [net, state] = processEpoch(net, state, params, 'train',opts) ;
      [net, state] = processEpoch(net, state, params, 'val',opts) ;
      if labindex == 1 && ~evaluateMode
        saveState(modelPath(epoch), net, state) ;
      end
      lastStats = state.stats ;
    end
    lastStats = accumulateStats(lastStats) ;
  end

  stats.train(epoch) = lastStats.train ;
  stats.val(epoch) = lastStats.val ;
  clear lastStats ;
  saveStats(modelPath(epoch), stats) ;

  if opts.plotStatistics
    switchFigure(1) ; clf ;
    plots = setdiff(...
      cat(2,...
      fieldnames(stats.train)', ...
      fieldnames(stats.val)'), {'num', 'time'}) ;
    for p = plots
      p = char(p) ;
      values = zeros(0, epoch) ;
      leg = {} ;
      for f = {'train', 'val'}
        f = char(f) ;
        if isfield(stats.(f), p)
          tmp = [stats.(f).(p)] ;
          values(end+1,:) = tmp(1,:)' ;
          leg{end+1} = f ;
        end
      end
      subplot(1,numel(plots),find(strcmp(p,plots))) ;
      plot(1:epoch, values','o-') ;
      xlabel('epoch') ;
      title(p) ;
      legend(leg{:}) ;
      grid on ;
    end
    drawnow ;
    print(1, modelFigPath, '-dpdf') ;
  end
end

% With multiple GPUs, return one copy
if isa(net, 'Composite'), net = net{1} ; end

% -------------------------------------------------------------------------
function [net, state] = processEpoch(net, state, params, mode,opts)
% -------------------------------------------------------------------------
% Note that net is not strictly needed as an output argument as net
% is a handle class. However, this fixes some aliasing issue in the
% spmd caller.

% initialize with momentum 0
if isempty(state) || isempty(state.momentum)
  state.r = num2cell(zeros(1, numel(net.params))) ;
  state.momentum = num2cell(zeros(1, numel(net.params))) ;
end

% move CNN  to GPU as needed
numGpus = numel(params.gpus) ;
if numGpus >= 1
  net.move('gpu') ;
  state.momentum = cellfun(@gpuArray, state.momentum, 'uniformoutput', false) ;
  %state.r = cellfun(@gpuArray, state.r, 'uniformoutput', false) ;
end
if numGpus > 1
  parserv = ParameterServer(params.parameterServer) ;
  net.setParameterServer(parserv) ;
else
  parserv = [] ;
end

% profile
if params.profile
  if numGpus <= 1
    profile clear ;
    profile on ;
  else
    mpiprofile reset ;
    mpiprofile on ;
  end
end

num = 0 ;
epoch = params.epoch ;
subset = params.(mode) ;
adjustTime = 0 ;

stats.num = 0 ; % return something even if subset = []
stats.time = 0 ;

start = tic ;
for t=1:params.batchSize:numel(subset)
  fprintf('%s: epoch %02d: %3d/%3d:', mode, epoch, ...
          fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;
  batchSize = min(params.batchSize, numel(subset) - t + 1) ;

  for s=1:params.numSubBatches
    % get this image batch and prefetch the next
    batchStart = t + (labindex-1) + (s-1) * numlabs ;
    batchEnd = min(t+params.batchSize-1, numel(subset)) ;
    batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
    num = num + numel(batch) ;
    if numel(batch) == 0, continue ; end
    opts.epoch = params.epoch;
    inputs = params.getBatch(params.imdb, batch,opts) ;

    if params.prefetch
      if s == params.numSubBatches
        batchStart = t + (labindex-1) + params.batchSize ;
        batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;
      else
        batchStart = batchStart + numlabs ;
      end
      nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
      params.getBatch(params.imdb, nextBatch,opts) ;
    end

    if strcmp(mode, 'train')
      net.mode = 'normal' ;
      net.accumulateParamDers = (s ~= 1) ;
      net.eval(inputs, params.derOutputs, 'holdOn', s < params.numSubBatches) ;
    else
      net.mode = 'test' ;
      net.eval(inputs) ;
    end
  end

  % Accumulate gradient.
  if strcmp(mode, 'train')
    if ~isempty(parserv), parserv.sync() ; end
    state = accumulateGradients(net, state, params, batchSize, parserv) ;
  end

  % Get statistics.
  time = toc(start) + adjustTime ;
  batchTime = time - stats.time ;
  stats.num = num ;
  stats.time = time ;
  stats = params.extractStatsFn(stats,net) ;
  currentSpeed = batchSize / batchTime ;
  averageSpeed = (t + batchSize - 1) / time ;
  if t == 3*params.batchSize + 1
    % compensate for the first three iterations, which are outliers
    adjustTime = 4*batchTime - time ;
    stats.time = time + adjustTime ;
  end

  fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;
  for f = setdiff(fieldnames(stats)', {'num', 'time'})
    f = char(f) ;
    fprintf(' %s: %.3f', f, stats.(f)) ;
  end
  fprintf('\n') ;
end

% Save back to state.
state.stats.(mode) = stats ;
if params.profile
  if numGpus <= 1
    state.prof.(mode) = profile('info') ;
    profile off ;
  else
    state.prof.(mode) = mpiprofile('info');
    mpiprofile off ;
  end
end
if ~params.saveMomentum
  state.momentum = [] ;
else
  state.momentum = cellfun(@gather, state.momentum, 'uniformoutput', false) ;
end

net.reset() ;
net.move('cpu') ;

% -------------------------------------------------------------------------
function state = accumulateGradients(net, state, params, batchSize, parserv)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
otherGpus = setdiff(1:numGpus, labindex) ;

for p=1:numel(net.params)

  if ~isempty(parserv)
    parDer = parserv.pullWithIndex(p) ;
  else
    parDer = net.params(p).der ;
    %parDer(parDer>params.constraint) = params.constraint;
    %parDer(parDer<-params.constraint) = -params.constraint;
  end

  % skip
  thisLR = net.params(p).learningRate ;
  if(thisLR ==0 )
      continue;
  end

  switch net.params(p).trainMethod

    case 'average' % mainly for batch normalization
      thisLR = net.params(p).learningRate ;
      net.params(p).value = vl_taccum(...
          1 - thisLR, net.params(p).value, ...
          (thisLR/batchSize/net.params(p).fanout),  parDer) ;

    case 'gradient'
      thisDecay = params.weightDecay * net.params(p).weightDecay ;
      thisLR = params.learningRate * net.params(p).learningRate ;

      if thisLR>0 || thisDecay>0
        % Normalize gradient and incorporate weight decay.
        parDer = vl_taccum(1/batchSize, parDer, ...
                           thisDecay, net.params(p).value) ;

        % Update momentum.
        state.momentum{p} = vl_taccum(...
          params.momentum, state.momentum{p}, ...
          -1, parDer) ;

        % Nesterov update (aka one step ahead).
        if params.nesterovUpdate
          delta = vl_taccum(...
            params.momentum, state.momentum{p}, ...
            -1, parDer) ;
        else
          delta = state.momentum{p} ;
        end

        % Update parameters.
        net.params(p).value = vl_taccum(...
          1,  net.params(p).value, thisLR, delta) ;
      end
    case 'rmsprop'
      opts = params;
      thisDecay = opts.weightDecay * net.params(p).weightDecay ;
      thisLR = opts.learningRate * net.params(p).learningRate ;
      state.r{p} = (1 - opts.gamma) * (net.params(p).der).^2 + opts.gamma * state.r{p};
      der_constraint = (1 / batchSize) * net.params(p).der./ (sqrt(state.r{p})+1e-8);
      der_constraint(der_constraint>opts.constraint) = opts.constraint;
      der_constraint(der_constraint<-opts.constraint) = -opts.constraint;
      state.momentum{p} = opts.momentum * state.momentum{p} ...
          - thisDecay * net.params(p).value ...
          - der_constraint ;
      net.params(p).value = net.params(p).value  + thisLR * state.momentum{p} ;
    otherwise
      error('Unknown training method ''%s'' for parameter ''%s''.', ...
        net.params(p).trainMethod, ...
        net.params(p).name) ;
  end
end

% -------------------------------------------------------------------------
function stats = accumulateStats(stats_)
% -------------------------------------------------------------------------

for s = {'train', 'val'}
  s = char(s) ;
  total = 0 ;

  % initialize stats stucture with same fields and same order as
  % stats_{1}
  stats__ = stats_{1} ;
  names = fieldnames(stats__.(s))' ;
  values = zeros(1, numel(names)) ;
  fields = cat(1, names, num2cell(values)) ;
  stats.(s) = struct(fields{:}) ;

  for g = 1:numel(stats_)
    stats__ = stats_{g} ;
    num__ = stats__.(s).num ;
    total = total + num__ ;

    for f = setdiff(fieldnames(stats__.(s))', 'num')
      f = char(f) ;
      stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;

      if g == numel(stats_)
        stats.(s).(f) = stats.(s).(f) / total ;
      end
    end
  end
  stats.(s).num = total ;
end

% -------------------------------------------------------------------------
function stats = extractStats(stats, net)
% -------------------------------------------------------------------------
sel = find(cellfun(@(x) isa(x,'dagnn.Loss'), {net.layers.block})) ;
for i = 1:numel(sel)
  stats.(net.layers(sel(i)).outputs{1}) = net.layers(sel(i)).block.average ;
end

% -------------------------------------------------------------------------
function saveState(fileName, net_, state)
% -------------------------------------------------------------------------
net = net_.saveobj() ;
state.r = [];
save(fileName, 'net', 'state') ;

% -------------------------------------------------------------------------
function saveStats(fileName, stats)
% -------------------------------------------------------------------------
if exist(fileName)
  save(fileName, 'stats', '-append') ;
else
  save(fileName, 'stats') ;
end

% -------------------------------------------------------------------------
function [net, state, stats] = loadState(fileName)
% -------------------------------------------------------------------------
load(fileName, 'net', 'state', 'stats') ;
net = dagnn.DagNN.loadobj(net) ;
if isempty(whos('stats'))
  error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...
        fileName) ;
end

% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir)
% -------------------------------------------------------------------------
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;

% -------------------------------------------------------------------------
function switchFigure(n)
% -------------------------------------------------------------------------
if get(0,'CurrentFigure') ~= n
  try
    set(0,'CurrentFigure',n) ;
  catch
    figure(n) ;
  end
end

% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
clear vl_tmove vl_imreadjpeg ;

% -------------------------------------------------------------------------
function prepareGPUs(opts, cold)
% -------------------------------------------------------------------------
numGpus = numel(opts.gpus) ;
if numGpus > 1
  % check parallel pool integrity as it could have timed out
  pool = gcp('nocreate') ;
  if ~isempty(pool) && pool.NumWorkers ~= numGpus
    delete(pool) ;
  end
  pool = gcp('nocreate') ;
  if isempty(pool)
    parpool('local', numGpus) ;
    cold = true ;
  end

end
if numGpus >= 1 && cold
  fprintf('%s: resetting GPU\n', mfilename)
  clearMex() ;
  if numGpus == 1
    gpuDevice(opts.gpus)
  else
    spmd
      clearMex() ;
      gpuDevice(opts.gpus(labindex))
    end
  end
end


function [imgs, sess_images, spersess] = scn_get_image_names(nruns, ndisdaqs)

    if nargin < 2, ndisdaqs = 0;
    else
        fprintf('Removing first %03d image names from each session.\n', ndisdaqs);
    end

 % get image names
    % --------------------------------------------------------------
    filestr = ['r[1-' num2str(nruns) ']' filesep 'vols.V*.img'];
    disp(['Getting images: ' filestr])
    imgs = filenames(filestr, 'char', 'absolute');

    clear sess_images

    for i = 1:nruns
        filestr = ['r[' num2str(i) ']' filesep 'vols.V*.img'];
        sess_images{i} = filenames(filestr, 'char', 'absolute');

        % disdaqs
        if ~isempty(sess_images{i}) && size(sess_images{i}, 1) > ndisdaqs && ndisdaqs
            sess_images{i}(1:ndisdaqs, :) = [];
        end

    end

    wh_empty = false(1, nruns);
    spersess = zeros(1, nruns);
    for i = 1:nruns
        if isempty(sess_images{i}) || size(sess_images{1}, 1) == 0  % do seem to need 2nd expression
            wh_empty(i) = true;
        else
            spersess(i) = size(sess_images{1}, 1);
        end
    end

    if ndisdaqs
        % re-get all image names, w.o disdaqs
        imgs = char(sess_images{:});
    end

    fprintf('Sessions (runs) with images: %03d\tSessions without images:%03d\n', sum(~wh_empty), sum(wh_empty));
    spersess(wh_empty) = [];
    fprintf('Images per Session (spersess):\n');
    fprintf('%3.0f\t', spersess);
    fprintf('\n');

end


function num = licenseuser(username,verbose)
%LICENSEUSER Displays the names of users who have a license checked out.
% NUM = LICENSEUSER(USERNAME) displays the feature toolboxes that are
%  currently checked out by USERNAME from a shared network license.
%  LICENSEUSER uses the Flexlm (R) license manager utility to get
%  information about the license status.
%
% USERNAME is the username on the host system. Default, if USERNAME is not
%  given, is to try and get the username of the current user from the host.
% VERBOSE (0|1|2) is the level of messages printed on the command line.
%
% NUM returns the total number of licenses checked out by USERNAME.
%
% Example:
%  To see a list of the toolboxes that user wsmith is using, use:
%
%  >> licenseuser('wsmith')
%
%
% Note that the only way to release a license is to exit Matlab.
%
%   See also LICENSEUSE, LICENSE, VER.
%
%
% Matt Hopcroft
%  mhopeng@gmail.com
%

% MH Nov2012
% v2.01 handle Win/Mac/Linux environment username
% v2.0  update for current Matlab releases (& sync with licenseuse)
% MH Jun2011
% v1.1  return total number of licenses checked out
% MH Apr2011
% v1.0
%

%% Welcome
if nargin < 2
    verbose=1;
end
if verbose >= 1, fprintf(1,'licenseuser v2.01: %s\n',datestr(clock)); end

if nargin < 1 || isempty(username)
    % use this ridiculous logic to handle Win/Mac/Linux (v2.01)
    username=[];
    try %#ok<TRYNC>
        username = getenv('USER');
    end
    if isempty(username)
        try %#ok<TRYNC>
            username = getenv('USERNAME');
        end
    end
end

if isempty(username)
    error('licenseuser: Could not determine username');
end

% get the list of all active licenses ("-a")
fprintf(1,'licenseuser: Finding licenses checked out to "%s"...\n',username);

cdir=cd;

%% Determine path to lmutil
if isunix % v2.11
    lmExe='lmutil';
else
    lmExe='lmutil.exe';
end

lmPath=[matlabroot filesep 'bin' filesep computer('arch') filesep]; % prior to R2010b
if ~exist([lmPath lmExe],'file')
    lmPath=[matlabroot filesep 'etc' filesep computer('arch') filesep]; % R2010b+
    if ~exist([lmPath lmExe],'file')
        fprintf(1,'ERROR: "%s" not found in bin/ or etc/ locations!\n\n',lmExe);
        return
    end
end
if verbose >= 3, fprintf(1,'License manager utilities found at:\n  %s\n',lmPath); end

cd(lmPath);

%% Execute license manager command
[ltstat, lt]=system(['.' filesep 'lmutil lmstat -c "' matlabroot filesep 'licenses' filesep 'network.lic" -a']);

cd(cdir);

if ltstat ~= 0
    fprintf(1,'ERROR: "%s"\n',strtrim(lt));
    if strfind(lt, 'No such file')
        fprintf(1,'On Linux you may need to upgrade the package "lsb"\n  (see %s)\n',...
            'https://www.mathworks.com/support/solutions/en/data/1-GLXUHV/index.html?product=ML&solution=1-GLXUHV');
    end
    error('OS returned error %d when executing lmutil',ltstat);
else
    if verbose >= 2, disp(lt); end % display the license manager status
end

%% Process the list

% tline = 1; tlineMatch={};
% k=0; k2=0;

tlines=textscan(lt,'%s','delimiter','\n'); tlines=tlines{1};
tIndC=strfind(tlines,'Users of');
%length(tIndC)
uIndC=strfind(tlines,username);
% create numeric binary arrays
for i=1:length(tIndC)
    if isempty(tIndC{i})
        tInd(i)=0;                                                              %#ok<*AGROW>
    else
        tInd(i)=1;
    end
    if isempty(uIndC{i})
        uInd(i)=0;
    else
        uInd(i)=1;
    end
end

tlbInd=find(tInd);
usrInd=find(uInd);

if ~isempty(usrInd)
    num = length(usrInd);
    fprintf(1,'User %s has %d licenses checked out:\n',username,num);

    for i=usrInd
        tlbx=tlbInd(tlbInd<i);
        %tlines{tlbx(end)}
        toolbox=textscan(tlines{tlbx(end)},'Users of %s','Delimiter',':'); toolbox=toolbox{1};
        fprintf(1,' %s',toolbox{1});
        hostname=textscan(tlines{i},[username '%s']); hostname=hostname{1};
        fprintf(1,' (on host %s)\n',hostname{1});
    end
    fprintf(1,'\n');
else
    fprintf(1,'No licenses found for username "%s".\n',username);
    num = 0;
end


function [trl, event] = ft_trialfun_imotions(cfg)

% FT_TRIALFUN_IMOTIONS makes a trial definition for an iMotions event structure
%
% The trialdef structure can contain the following specifications
% cfg.trialdef.eventtype  = string or cell-array of strings (default = 'StimulusName')
% cfg.trialdef.eventvalue = string or cell-array of strings (default = [])
%
% See also FT_DEFINETRIAL, FT_TRIALFUN_GENERAL

assert(isfield(cfg, 'event'), 'the configuration should contain the event structure');
assert(isfield(cfg, 'fsample'), 'the configuration should contain the sampling frequency');

% set the defaults
cfg.trialdef            = ft_getopt(cfg, 'trialdef', []);
cfg.trialdef.eventtype  = ft_getopt(cfg.trialdef, 'eventtype', 'StimulusName');
cfg.trialdef.eventvalue = ft_getopt(cfg.trialdef, 'eventvalue', []);
cfg.trialdef.offset     = ft_getopt(cfg.trialdef, 'offset', 'absolute'); % absolute or relative

event = cfg.event;

% start by selecting all events
sel = true(size(event));
% make a subselection of events
if ~isempty(cfg.trialdef.eventtype)
  sel = sel & strcmp({event.type}, cfg.trialdef.eventtype);
end
if ~isempty(cfg.trialdef.eventvalue)
  sel = sel & strcmp({event.value}, cfg.trialdef.eventvalue);
end

sample   = [event(sel).sample];
duration = [event(sel).duration];
type     = {event(sel).type};
value    = {event(sel).value};

begsample = sample(:);
endsample = sample(:)+duration(:)-1;

switch cfg.trialdef.offset
  case 'relative'
    % start of each trial/segment is t=0
    offset    = zeros(size(begsample));
  case 'absolute'
    % start of recording is t=0
    offset    = begsample - 1;
end

type  = type(:);
value = value(:);
trl   = table(begsample, endsample, offset, type, value);


classdef LaunchVehicleGroundObjectWayPt < matlab.mixin.SetGet
    %LaunchVehicleGroundObjectWayPt Summary of this class goes here
    %   Detailed explanation goes here

    properties
        elemSet(1,:) GeographicElementSet
        timeToNextWayPt(1,1) double = 0
    end

    methods
        function obj = LaunchVehicleGroundObjectWayPt(elemSet, timeToNextWayPt)
            obj.elemSet = elemSet;
            obj.timeToNextWayPt = timeToNextWayPt;
        end

        function str = getDisplayStr(obj)
            str = sprintf('Lat: %0.3f deg, Long: %0.3f deg, Alt: %0.3f km', ...
                          rad2deg(obj.getLatitude()), rad2deg(obj.getLongitude()), obj.getAltitude());
        end

        function timesToNextWayPt = getTimesToNextWaypt(obj)
            timesToNextWayPt = [obj.timeToNextWayPt];
        end

        function gElemSet = getElemSet(obj)
            gElemSet = obj.elemSet;
        end

        function lat = getLatitude(obj)
            lat = obj.elemSet.lat;
        end

        function long = getLongitude(obj)
            long = obj.elemSet.long;
        end

        function alt = getAltitude(obj)
            alt = obj.elemSet.alt;
        end

        function setLatitude(obj, newLat)
            obj.elemSet.lat = newLat;
        end

        function setLongitude(obj, newLong)
            obj.elemSet.long = newLong;
        end

        function setAltitude(obj, newAlt)
            obj.elemSet.alt = newAlt;
        end
    end

    methods(Static)
        function wayPt = getDefaultWayPt(initialTime, frameToUse)
            durToNextWayPt1 = 3600;
            elemSet = GeographicElementSet(initialTime + durToNextWayPt1, 0, 0, 0, 0, 0, 0, frameToUse);
            wayPt = LaunchVehicleGroundObjectWayPt(elemSet, durToNextWayPt1);
        end
    end
end


% RES = spyrHigh(PYR, INDICES)
%
% Access the highpass residual band from a steerable pyramid.

% Eero Simoncelli, 6/96.

function res =  spyrHigh(pyr,pind)

res  = pyrBand(pyr, pind, 1);


function plotstations(ax, options)
    %plotstations plots stations on specified axes
    % (Not fully IMPLEMENTED)
    % plotstatiosn(ax) plots the default station list, cropped to the current window
    % to the axis AX.
    % to the specified axes. STATIONS is a structure or table
    % with fields Network, Name, Latitude, Longitude,
    % additionally, it should have Elevation, StartTime, and EndTime.
    % by default, only plots stations active during main catalog dates.
    %
    % if stations is a file, then it should have a variable `'stations' with the
    % same fields.
    % options would be a struct with filtervalues
    %
    % eg.
    %  options=struct('Network','CH'); % show only stations belonging to network CH
    %  options=struct('Network',{'CH','DK'}) % show only stations belonging either to CH or DK
    %  valid options are:
    %  Network, Station, StartBefore, EndAfter, Marker, MarkerSize, MarkerColor
    %
    % FileName:
    % path&name of a station file meeting above criteria. Samples that come with Zmap:
    %  resrc/features/stations_irisall_20170714.mat       %unfiltered IRIS station list
    %  or  resrc/features/stations_sedall_20170714.mat    %unfiltered SED station list

    % TODO Maybe these should be actually go into a get/load stations file.
    % TODO Provide ability to update the stations file?
    % TODO set default network?

    % all swiss stations:
    % http://eida.ethz.ch/fdsnws/station/1/query?format=text&level=station&nodata=404
    unimplemented_error()
    report_this_filefun();

    ZG=ZmapGlobal.Data;
    if ~exist('options','var')
        options=struct();
    end

    if ~isfield(options,'Marker'), options.Marker='s';end
    if ~isfield(options,'MarkerSize'), options.MarkerSize=6;end
    if ~isfield(options,'MarkerEdgeColor'), options.MarkerEdgeColor='gray';end
    if ~isfield(options,'MarkerFaceColor'), options.MarkerFaceColor='gray';end
    if ~isfield(options,'StartBefore')
        %     w   [x   y ]  z   want stations that start some time before y and end some time after x
        options.StartTime=max(ZG.primeCatalog.Date);
    end
    if ~isfield(options,'EndAfter')
        options.EndTime=min(ZG.primeCatalog.Date);
    end
    stations=ZG.features('stations');
    if isempty(stations)
        stations.load();
    end

    % filter the stations down to something managable
    % WARNING: If same station has multiple periods at same place, it gets plotted twice.
    yl = ylim(ax);
    xl = xlim(ax);
    idx = stations.Latitude <= yl(2) & ...
        stations.Latitude >= yl(1) & ...
        stations.Longitude <= xl(2) & ...
        stations.Longitude >= xl(1); %doesn't account for dateline
    if isa(stations,'Table')
        if ismember('StartTime',stations.Properties.VariableNames) && ~isempty(options.StartBefore)
            idx=idx & stations.StartTime <= options.StartBefore;
        end
        if ismember('EndTime',stations.Properties.VariableNames) && ~isempty(options.EndAfter)
            idx=idx & stations.EndTime >= options.EndAfter;
        end
        if isfield(options.Network) && ~isempty(options.Network)
            idx=idx & ismember(stations.Network, options.Network);
        end
        stas = stations(idx,:);
    else % struct
        if isfield(stations,'StartTime') && ~isempty(options.StartBefore)
            idx=idx & stations.StartTime <= options.StartBefore;
        end
        if isfield(stations,'EndTime') && ~isempty(options.EndAfter)
            idx=idx & stations.EndTime >= options.EndAfter;
        end
        if isfield(options.Network) && ~isempty(options.Network)
            idx=idx & ismember(stations.Value.Network, options.Network);
        end
        stas = stations(idx);
    end

    showNames = ~isfield(options,'ShowNames') || options.ShowNames;
    options = rmfield(options, {'StartTime','EndTime','Network', 'ShowNames'});

    set(gca,'NextPlot','add')
    dx = abs(s1_east-s2_west)/130;
    pl = plot(ax, stas.Longitude,stas.Latitude,options.Marker);
    set(pl,'LineWidth',1,options);
    if showNames
        te1 = text(stas.Longitude+dx,lastas.Latitudet,char(stas.Name),'clipping','on');
        set(te1,'FontWeight','bold','Color','k','FontSize',9);
    end
    drawnow
    set(gca,'NextPlot','replace')
end


function [outMat,procInfo,dcmInfo]=ReadDicomDir(inDir,debugLevel)
% [outMat,procInfo,dcmInfo]=ReadDicomDir(inDir [,debugLevel])
%   Read DICOM files from directory 'inDir'.
%   If mag and phase images in same directory: read and sort these images;
%   phase images will be at 2nd half of outMat
%
% inDir: directory where the DICOM files are stored
% debugLevel: if >0, print debug message; debugLevel=0, 1, 2
%
% outMat: a 2D matrix for a single slice, 3D matrix for multiple slices
% procInfo: abbreviated DICOM information
% dcmInfo: DICOM information from 1st DICOM file
%
% Example:
% d1 = 'C:\Data\TAG7MM-92_11'
% [a,pname,pp]=ReadDicomDir(d1);
% figure; imagesc(abs(a(:,:,20))
%
% check current directory
% [a]=ReadDicomDir('.');
%
% use GUI to choose directory
% [a]=ReadDicomDir;
%
% Tested using Siemens dicom images and Philips mag, phase dicom images.
% Tested using Philips mag and phase images
% Tested using GE dicom images: mag, phase, mag, phase, mag, phase ....
%
% For Siemens dicom in mosaic format: default to be magnitude.
% Works for Siemens PET dicom images.
% For Philips real, imag images: check ImageType and revise flags
%
% Wen-Tung Wang, 201106
% Revised to read and sort mag and phase images (currently Siemens images only). 201107
% Revised to read Siemens dicom in mosaic format (all magnitude images).201205
% Revised to read GE dicom images. 201205

% msg = nargchk(1,2,nargin);
% if ~isempty(msg)
%    fprintf(1,'\tusage: [outMat,procInfo,dcmInfo]=ReadDicomDir(inDir [, debugLevel])\n');
%    fprintf(1,'\tRead multiple single-slice DICOM data (*.dcm, not *.ima)\n');
%    fprintf(1,'\tcheck "help ReadDicomDir" for more details\n');
%    return;
% end
% input from ui
    if (nargin<1) || (isempty(inDir)),
        inDir=uigetdir('','Select DICOM Directory');
        if ~ischar(inDir)
            disp('no valid Directory selected.');
            outMat=[]; procInfo=[]; dcmInfo=[];
            return;
        end
    end
% debugLevel
    if nargin<2, debugLevel=0; end
% check if directory exist
    if (debugLevel), tic; end
    if (exist(inDir,'dir'))~=7,
	    fprintf(2,'%s \nnot exist or not a folder\n',inDir);
	    outMat=[]; procInfo=[]; dcmInfo=[];
	    return
    end
	aaDir = strfind(inDir,filesep);
	lenDir = length(inDir);
    if (~isempty(aaDir)),
        if (aaDir(end)==lenDir), % remove last filesep: either / or \
            inDir = inDir(1:end-1);
        end
    end
% read all files
    ffext = sprintf('*');
    fdir = fullfile(inDir,ffext);
    if (debugLevel), fprintf(1,'%s\n',fdir); end
	ff = dir(fdir);
    flen0 = numel(ff);
	flen = length(ff);
% exclude '.' and '..', and other files if needed
    ff(cell2mat({ff(:).isdir})>0)=[];
	flen = length(ff);
    ff0 = ff; %filenames without directory
% add path to filenames
    if (debugLevel),
        fprintf(1,'%d files. 1st file = %s\n',flen,ff(1).name);
    end
	for k=1:flen
		ff(k).name = [inDir,filesep,ff(k).name];
	end
% GE or Siemens or Philips DICOM
% Use magmatch, phamatch, realmatch, imagmatch to distinguish magnitude,
% phase, real, and imaginary dicom images
	display(ff(1).name);
	dinfo=dicominfo(ff(1).name);
    GEflag = 0; Siemensflag = 0; Philipsflag = 0;
    dcmInfo = dinfo;
    if (strfind(dinfo.Manufacturer,'SIEMENS')),
        Siemensflag = 1;
        vendor = 'Siemens';
        magmatch = 'ORIGINAL\PRIMARY\M\ND\NORM';
        magmatch = 'ORIGINAL\PRIMARY\M\';
        magmatch2= 'ORIGINAL\PRIMARY\M\ND\MOSAIC'; %mosaic format: magnitude
        phamatch = 'ORIGINAL\PRIMARY\P\';
    elseif (strfind(dinfo.Manufacturer,'GE')),
        % GE mag and phase images alternates.
        % e.g. i1110030.MRDC.1 is magnitude; i1110031.MRDC.2 is phase
        GEflag = 1;
        vendor = 'GE';
        magmatch = 'ORIGINAL\PRIMARY\OTHER'; %
        phamatch = 'ORIGINAL\PRIMARY\M'; % need to be revised
        if (mod(flen,2)~=0),
            fprintf(1,'GE data: #files=%d. Need even number of files.\n',flen);
            outMat=[]; procInfo=[]; dcmInfo=[]; return;
        end
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %fprintf(1,'CHECK IMAGETYPE for GE Dicom images (%s), stop\n');
	    %outMat=[]; procInfo=[]; dcmInfo=[]; return;
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    elseif (strfind(dinfo.Manufacturer,'Philips')),
        Philipsflag = 1;
        vendor = 'Philips';
        magmatch = '\M\';
        phamatch = '\PHASE MAP\';
        realmatch = '\Real\'; % may need to be revised
        imagmatch = '\Imag\';
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %fprintf(1,'CHECK IMAGETYPE for Philips Dicom images, stop\n');
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    else
        fprintf(1,'not recognized Manufacturer\n');
	    outMat=[]; procInfo=[]; dcmInfo=[]; return;
    end
    if (debugLevel>1), fprintf(1,'vendor: %s\n',vendor); end
% name strings: dicom tags to read. Add if need more.
    namestring = {'FileModDate','SeriesDescription','EchoTime',...
        'SeriesNumber','RepetitionTime','EchoTrainLength',...
        'PixelBandwidth','SequenceName','PercentPhaseFieldOfView',...
        'StudyDate','Manufacturer','InstanceNumber',...
        'SliceLocation','SliceThickness','FlipAngle','EchoNumber',...
        'Rows','Columns','Width','Height','ProtocolName',...
        'ImageType'};
    lenstr = length(namestring);
% assign parameters
    %matching variables
    for kk=1:lenstr
        str = cell2mat(namestring(kk));
        ttxt = sprintf('if(isfield(dinfo,''%s'')), %s = dinfo.%s; end',str,str,str);
        %disp(ttxt); %for checking
        eval([ttxt]);
    end
    if (debugLevel>1), fprintf(1,'variable matching done\n'); end
    % trim
    if (exist('SequenceName','var')),
        ind1 = strfind(SequenceName,'*');
        SequenceName = SequenceName(ind1+1:end);
    else
        ind1 = [];
    end
% display procInfo
    if (exist('ProtocolName')),
        line1 = sprintf('%s Protocol: %s',vendor,ProtocolName);
    else
        line1 = sprintf('%s Protocol: %s',vendor,SequenceName);
    end
% for multiple images: (1) read in all images. (2) sort mag and phase
% images, if exist. Phase images will be at 2nd half of outMat
	slc1=dicomread(dinfo);
    slcIndex = InstanceNumber;
    if (exist('EchoNumber','var')),
        EchoNumberMax = EchoNumber;
    else
        EchoNumberMax = 0;
    end
    if (debugLevel>1), fprintf(1,'start looping through files\n'); end
	if flen==1,
        outMat = double(slc1);
        % for procInfo
        magFlag = 0;
        phaFlag = 0;
		line2 = sprintf('  TE/TR/FA/SlcThk=%.2fms/%.0fms/%.1fdeg/%.1fmm',EchoTime,RepetitionTime,FlipAngle,SliceThickness);
		line3 = sprintf('  matrix=%dx%d, FoV=%dx%d',Rows,Columns,Height,Width);
        if (strfind(ImageType,magmatch)),
            magFlag = 1;
        elseif (strfind(ImageType,phamatch2)),
            magFlag = 1;
        elseif (strfind(ImageType,phamatch)),
            phaFlag = 1;
            if (magFlag==1),
                slcIndex = slcIndex + skipNumber;
            end
        else
            fprintf(1,'neither mag nor phase. ImageType=%s\n',ImageType);
            procInfo=[];
        end
		if (magFlag==1)&&(phaFlag==0),
			line3 = [line3,', Magnitude images'];
		elseif (magFlag==0)&&(phaFlag==1),
			line3 = [line3,', Phase images'];
		elseif (magFlag==1)&&(phaFlag==1),
			line3 = [line3,', Magnitude+Phase images'];
		else
        end
		if (EchoNumberMax>1),
            ETline=sprintf('  %d TEs=',EchoNumberMax);
            for kk=1:EchoNumberMax-1, ETline=[ETline,sprintf('%.2f/',ETsort(kk))]; end
            ETline=[ETline,sprintf('%.1f ms',ETsort(EchoNumberMax))];
            procInfo = sprintf('%s\n%s\n%s\n%s',line1,line2,line3,ETline);
        else
            procInfo = sprintf('%s\n%s\n%s',line1,line2,line3);
        end
		disp(procInfo);
    else
        kk = 1;
        magFlag = 0;
        phaFlag = 0;
        magSlices = [];
        phaSlices = [];
        skipNumber = flen/2;
        if (strfind(ImageType,magmatch)),
            magFlag = 1;
            magSlices = [magSlices; kk InstanceNumber];
        elseif (strfind(ImageType,magmatch2)),
            magFlag = 1;
            magSlices = [magSlices; kk InstanceNumber];
        elseif (strfind(ImageType,phamatch)),
            phaFlag = 1;
            phaSlices = [phaSlices; kk InstanceNumber+skipNumber];
        else
            fprintf(1,'neither mag nor phase. Default: mag\n');
            magFlag = 1;
            magSlices = [magSlices; kk InstanceNumber];
            %procInfo=[];
        end
        % philips may output mag, phase, real, imag
        % still use magSlices and phaSlice to store real and imag data
        if (Philipsflag),
            if (strfind(ImageType,realmatch)), %using strfind maybe better than strcmp
                magFlag = 1;
                magSlices = [magSlices; kk InstanceNumber];
            elseif (strfind(ImageType,imagmatch)),
                phaFlag = 1;
                phaSlices = [phaSlices; kk InstanceNumber+skipNumber];
            else
                fprintf(1,'neither real nor imag\n');
                procInfo=[];
            end
        end
        if (debugLevel>2), fprintf(1,'%3d ',kk); end
        outMat=zeros([Rows,Columns,flen]);
        outMat(:,:,kk) = double(slc1);
        InstanceNumbers=zeros([flen,1]);
        if (exist('EchoTime','var')),
            EchoTimes=zeros([flen,1]);
            EchoTimes(kk)=EchoTime;
        end
        InstanceNumbers(kk)=InstanceNumber;
		for kk=2:flen,
			dinfo = dicominfo(ff(kk).name);
            %EchoTrainLength = dinfo.EchoTrainLength;
            %SliceLocation = dinfo.SliceLocation;
            InstanceNumber = dinfo.InstanceNumber;
            slcIndex = InstanceNumber;
            if (exist('EchoTime','var')),
                EchoTime = dinfo.EchoTime;
            end
            if (exist('EchoNumber','var')),
                EchoNumber = dinfo.EchoNumber;
                if (EchoNumber>EchoNumberMax), EchoNumberMax = EchoNumber; end
            end
            ImageType = dinfo.ImageType;
            if (debugLevel>4),
                fprintf(1,'%s ',ff0(kk).name);
                if (debugLevel>5),
                    fprintf(1,' type=%s ',ImageType);
                end
            end
			if (strfind(ImageType,magmatch)),
                magFlag = 1;
                magSlices = [magSlices; kk slcIndex];
            elseif (strfind(ImageType,magmatch2)),
                magFlag = 1;
                magSlices = [magSlices; kk slcIndex];
			elseif (strfind(ImageType,phamatch)),
                phaFlag = 1;
                phaSlices = [phaSlices; kk slcIndex+skipNumber];
				if (magFlag==1),
                    slcIndex = slcIndex + skipNumber;
                end
            else %default: mag
                magFlag = 1;
                magSlices = [magSlices; kk slcIndex];
            end
            InstanceNumbers(kk)=slcIndex;
            if (exist('EchoTime','var')),
                EchoTimes(kk)=EchoTime;
            end
            % output
			outMat(:,:,kk) = double(dicomread(dinfo));
            if (debugLevel>2), fprintf(1,'%3d ',kk); end
            if (debugLevel>2)&&((mod(kk,20)==0)||(mod(kk,flen)==0)), fprintf(1,'\n'); end
        end
        % swap order according to InstanceNumber
        % for mag+phase images: phase images at 2nd half of outMat
        tmp = zeros(size(outMat));
        lenMag = length(magSlices);
        lenPha = length(phaSlices);
        if (debugLevel>1), fprintf(1,'#(magintude, phase)images = (%d, %d)\n',lenMag,lenPha); end
        if ((lenMag<1)&&(lenPha<1)), procInfo=[]; fprintf(1,'check magSlices (%s) and phasSlices (%s)\n',magmatch,phamatch); return; end
        % Philips data are in order of mag+phase already, they don't mixed
        if (~Philipsflag),
            if (lenMag*lenPha)>0, % mag + phase images
                tmp(:,:,magSlices(:,2))=outMat(:,:,magSlices(:,1));
                tmp(:,:,phaSlices(:,2))=outMat(:,:,phaSlices(:,1));
            else
                if (lenMag>0), % magnitude images only
                    tmp(:,:,magSlices(:,2))=outMat(:,:,magSlices(:,1));
                else % phase images only: subtract skipNumber
                    phaSlices(:,2) = phaSlices(:,2) - skipNumber;
                    tmp(:,:,phaSlices(:,2))=outMat(:,:,phaSlices(:,1));
                end
            end
            outMat=tmp;
        end

        % find echo times
        if (exist('EchoTime','var')),
            uEchoTimes = unique(EchoTimes);
            [ETsort] = sort(uEchoTimes,'ascend');
        end
        lenETsort = length(ETsort);

	   	%display procInfo
        %if (debugLevel>1), fprintf(1,'\n'); end
        if (exist('EchoTime','var')),
            line2 = sprintf('  TE/TR/FA/SlcThk=%.2fms/%.0fms/%.1fdeg/%.1fmm',EchoTime,RepetitionTime,FlipAngle,SliceThickness);
        else
            line2 = sprintf('  SlcThk=%.1fmm',SliceThickness);
        end
		line3 = sprintf('  matrix=%dx%d, FoV=%dx%d',Rows,Columns,Height,Width);
		if (magFlag==1)&&(phaFlag==0),
			line3 = [line3,', Magnitude images'];
		elseif (magFlag==0)&&(phaFlag==1),
			line3 = [line3,', Phase images'];
		elseif (magFlag==1)&&(phaFlag==1),
			line3 = [line3,', Magnitude+Phase images'];
		else
		end
		if ((EchoNumberMax>1)&(lenETsort>1)),
            ETline=sprintf('  %d TEs=',EchoNumberMax);
            for kk=1:EchoNumberMax-1, ETline=[ETline,sprintf('%.2f/',ETsort(kk))]; end
            ETline=[ETline,sprintf('%.1f ms',ETsort(EchoNumberMax))];
            procInfo = sprintf('%s\n%s\n%s\n%s',line1,line2,line3,ETline);
        else
            procInfo = sprintf('%s\n%s\n%s',line1,line2,line3);
		end
		disp(procInfo);
		if (flen>1),
			fprintf(1,'total %d files/images\n',flen);
		end
    end
    if ((GEflag)&(flen>1)),
        reply = input('Place odd slices as 2nd half of 3D matrix? Y/N [Y]:','s');
        if isempty(reply)
            reply = 'Y';
        end
        if ((reply=='Y')|(reply=='y')),
            tmpOdd=outMat(:,:,1:2:end-1);
            tmpEven=outMat(:,:,2:2:end);
            outMat = cat(3, tmpOdd, tmpEven);
        end
    end
% total elapsed time
    if (debugLevel),
        fprintf(1,'elapsed time = %f\n',toc);
    end
return;


function cMap=grayjet(varargin)

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

ns=7;
cMap=[flipud(gray(ns)); jet(ns)];

[cMap]=resampleColormap(cMap,n);

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


function x = p07_root ( i )

%*****************************************************************************80
%
%% P07_ROOT returns a root for problem 7.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 May 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer I, the index of the requested root.
%
%    Output, real X, the value of the root.
%
  if ( i == 1 )
    x = 0.0;
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'P07_ROOT - Fatal error!\n' );
    fprintf ( 1, '  Illegal root index = %d\n', i );
    error ( 'P07_ROOT - Fatal error!' );
  end

  return
end


function [ h ] = my_drawArrow(x1,y1,x2,y2,headwidth,props)

h = annotation('arrow');
set(h,'parent', gca, ...
    'position', [x1,y1,x2-x1,y2-y1], ...
    'HeadLength', 10, 'HeadWidth', headwidth, 'HeadStyle', 'cback1', ...
    props{:} );
end


function test_suite = testFunctionHandlesC
%testFunctionHandlesC Test file used by TestFunctionHandlesTest
%   Contains two passing tests that use a test fixture containing an intentional
%   error.

%   Steven L. Eddins
%   Copyright 2008 The MathWorks, Inc.

initTestSuite;

function testData = setUpFcn
testData = 5;

function testA(testData)
assertEqual(testData, 5);

function testB(testData)
assertEqual(testData, 5);

function tearDownFcn(testData)
% This assertion is expected to error.
assertEqual(testData, 20);