function params = hlp_getDefaultArglist(prefix)
% params = hlp_getDefaultArglist(prefix)
% Returns a cell array of default arguments for finputcheck. The set of
% parameters depends on the specific prefix ('est','hlp','viz','pop')
%
% This function will be deprecated in the beta release

if ~ischar(prefix)
    help(hlp_getDefaultParams);
    error('input argument must be a prefix string (est,hlp,viz,pop)');
end

switch lower(prefix)
    case 'pre'
        params = {
            'resample',         'real'         []                0;              ...                     % new sampling rate
            'components',       'integer'      []               [];              ...
            'newtlims',         'real'         []               [];              ...                     % seconds
            'filter',           'cell'         {}               {};              ...                     % {low-edge hi-edge 'eegfilt'}
            'detrend',          'boolean'      []                0;              ...
            'normalize',        ''             {'ensemble','time',{'time','ensemble'},''}   '';    ...   % 'time' | 'ensemble' | 'both'
            'center',           'boolean'      []                0;              ...                     % remove the mean of each series
            'diff',             'integer'      [0 10]            0;              ...                     % number of times to difference
            'verb',             'integer'      [0 2]             1;              ...                     % verbosity level
            'DO_JACKET',        'boolean'      []                0;              ...                     % use jacket (GPU parallel)
            'newtrials',        'integer'      []               [];              ...                     % list of trials to include
            'badsegments',      'real'         []               [];              ...                     % K x 2 matrix of [lo hi] intervals (seconds) of data within ea. trial to set to nan
            'equalizetrials',   'boolean'      {0 1}             0;              ...                     % equalize the number of trials between two conditions
            };
    case 'est'
        params = {                                                               ...
            'algorithm',          ''           {'vieira-morf','arfit'}     'vieira-morf'; ...            % which algorithm to use for model fitting
            'winStartIdx',        'real'       []               [];              ...                     % vector of sample points (start of windows) at which to estimate windowed VAR model
            'morder',             'real'       []               [];              ...                     % VAR model order
            'winlen',             'real'       []               0.5;             ...                     % window length (sec)
            'winstep',            'real'       []               0.03;            ...                     % window step size (sec)
            'epochTimeLims',      'real'       []               [];              ...                     % time range to analyze (sec) where 0 = event time
            'prctWinToSample',    'real'       [0 100]          100;             ...                     % percent of time windows to randomly select
            'verb',               'real'       [0 2]            2;               ...                     % verbosity level (0=no output, 1=text, 2=gui)
            'timer'               'boolean'    []               0;               ...                     % estimate time required to fit model
            'normalize',          ''           {'ensemble','time',{'time','ensemble'},''}   '';    ...   % normalization 'time' | 'ensemble' | 'both'
            'icselector',         ''           {'sbc','aic','fpe','hq'}   {'sbc','aic'}; ...             % information criteria to use for selecting model order
            'detrend',            ''           {} [] ...
            };
    case 'hlp'
        params = {};
    case 'stat'
        params = {};
    case 'vis'
        params = {};
end


function asGetAllRoiMeans()

global asObjs
for i = 1 : length(asObjs)
    [m,s] = asObjs(i).roi.getMeanAndStd;
    fprintf('%f\n',m);
%     fprintf('%s\n',num2str(m));
end


%
% Default configuration for Redundant Robotic Manipulator nDOF
%
% by Olzhas Adiyatov
% 6/10/2013

conf = struct;

conf.delta_goal_point = 3;                                          % Radius of goal point
conf.num_link = 6;                                                  % Number of links in the manipulator model
conf.max_ang = [pi; 3*pi/4*ones(conf.num_link-1,1)];                % Maximum joint angle for each joint
conf.min_ang = [0 ;-3*pi/4*ones(conf.num_link-1,1)];                % Minimum joint angle for each joint
conf.delta_ang_max = 10 * pi / 180;                                 % Maximum joint angle change at each iteration
conf.delta_ang_neighbor = 30 * pi / 180;                            % Maximum joint angle change at each neighbor search
conf.disp_interval = 100;                                           % Interval for progress monitoring
conf.init_conf = [pi/2; zeros(conf.num_link-1,1)];                  % Initial configuration of the manipulator model
conf.step_div = 4;                                                  % Number of transition states between nodes, used for collision detection

conf.len_link    = 14*ones(conf.num_link, 1);                       % Array storing the length of the links
conf.height_link = 12 *ones(conf.num_link, 1);                      % Array storing the height of the links
conf.width_link  = 4 *ones(conf.num_link, 1);                       % Array storing the width of the links


%% QUAD_POOL uses the MATLABPOOL command to run the QUAD code.
%
%  Discussion:
%
%    Output printed by the function appears directly on the screen.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 March 2010
%
%  Author:
%
%    John Burkardt
%
  matlabpool open local 4

  n = 100000;
  fprintf ( 1, '\n' );
  fprintf ( 1, 'QUAD_POOL\n' );
  fprintf ( 1, '  Estimate integral using %d points\n', n );

  value = quad_fun ( n );

  matlabpool close

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Integral estimate is %f\n', value );
  fprintf ( 1, '  Exact integral    is %f\n', pi );
  fprintf ( 1, '  Error is             %e\n', abs ( value - pi ) );


% OP_FDOTN_V: assemble the vector r = [r(i)], with  r(i) = (f * n, v), with n the normal exterior vector.
%  v should be a scalar-valued function.
%
%   rhs = op_fdotn_v (spv, msh, coeff);
%
% INPUT:
%
%   spv:   structure representing the function space (see sp_vector/sp_eval_boundary_side)
%   msh:   structure containing the domain partition and the quadrature rule (see msh_cartesian/msh_eval_boundary_side)
%   coeff: source function evaluated at the quadrature points
%
% OUTPUT:
%
%   rhs: assembled right-hand side
%
% Copyright (C) 2009, 2010 Carlo de Falco, Rafael Vazquez
% Copyright (C) 2011, 2014, 2017 Rafael Vazquez
%
%    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 rhs = op_fdotn_v (spv, msh, coeff)

  coeff = reshape (coeff, [], msh.nqn, msh.nel);
  shpv  = reshape (spv.shape_functions, spv.ncomp, msh.nqn, spv.nsh_max, msh.nel);

  rhs = zeros (spv.ndof, 1);

  for iel = 1:msh.nel
    if (all (msh.jacdet(:,iel)))
     jacdet_weights = reshape (msh.jacdet(:, iel) .* msh.quad_weights(:, iel), 1, msh.nqn);

     shpv_iel = reshape (shpv(:, :, :, iel), spv.ncomp, msh.nqn, spv.nsh_max);
     coeff_dot_n = sum (bsxfun (@times, coeff(:,:,iel), msh.normal(:,:,iel)), 1);

     coeff_times_jw = bsxfun (@times, jacdet_weights, coeff_dot_n);

     aux_val = bsxfun (@times, coeff_times_jw, shpv_iel);
     rhs_loc = sum (sum (aux_val, 1), 2);

     indices = find (spv.connectivity(:,iel));
     rhs_loc = rhs_loc(indices); conn_iel = spv.connectivity(indices,iel);
     rhs(conn_iel) = rhs(conn_iel) + rhs_loc(:);
    else
      warning ('geopdes:jacdet_zero_at_quad_node', 'op_fdotn_v: singular map in element number %d', iel)
    end
  end

end


function tests = test_ft_preproc_slidingrange

% MEM 1gb
% WALLTIME 00:10:00
% DEPENDENCY ft_preproc_slidingrange

if nargout
  % assume that this is called by RUNTESTS
  tests = functiontests(localfunctions);
else
  % assume that this is called from the command line
  fn = localfunctions;
  for i=1:numel(fn)
    feval(fn{i});
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function testOptions(testCase)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

nchan   = 8;
nsample = 1000;
dat     = randn(nchan, nsample) + 1;

result = [];
result{end+1} = ft_preproc_slidingrange(dat, 1,  false);
result{end+1} = ft_preproc_slidingrange(dat, 11, false);
result{end+1} = ft_preproc_slidingrange(dat, 31, false);
result{end+1} = ft_preproc_slidingrange(dat, 71, false);
result{end+1} = ft_preproc_slidingrange(dat, 11, true);
result{end+1} = ft_preproc_slidingrange(dat, 31, true);
result{end+1} = ft_preproc_slidingrange(dat, 71, true);

% all iterations were done with (slightly) different options, hence the results should not be equal
for i=1:numel(result)
  for j=(i+1):numel(result)
    assert(~isequal(result{i}, result{j}), 'the results %d and %d should not be equal', i, j);
  end
end


function bool = is_dim_singleton(varargin)
%IS_DIM_SINGLETON true for a singleton axis dimension
%
%   Usage: bool = is_dim_singleton(x1,x2,...)
%
%   Input parameters:
%       x1,x2,... - axis / m; single value or [xmin,xmax] or nD-array
%
%   Output parameters:
%       bool      - array of logical indicating whether each input is a
%                   singleton dimension
%
%   See also: is_dim_custom, xyz_axes_selection, plot_sound_field

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

%% ===== Checking input parameters =======================================
isargnumeric(varargin{:});

%% ===== Computation =====================================================
bool = cellfun(@(x) numel(x) <= 2 && x(1) == x(end), varargin);


% ------------------------------------------------------
% SwarmOps - Heuristic optimization for Matlab
% Copyright (C) 2003-2010 Magnus Erik Hvass Pedersen.
% Please see the file license.txt for license details.
% SwarmOps on the internet: http://www.Hvass-Labs.org/
% ------------------------------------------------------

% Create data-struct for Griewank problem.
% Parameters:
%     dim; the dimensionality of the search-space, e.g. 10.
%     maxEvaluations; the maximum number of fitness evaluations
%                     to perform in optimization.
% Returns:
%     data; the data-struct.
function data = griewankdata(dim, maxEvaluations)
    data = benchmarkdata(dim, 0.001, maxEvaluations, 300, 600, -600, 600);

    % Array used by griewank function to save time.
    data.steps = sqrt([1:dim]);
end

% ------------------------------------------------------


function SO3VF = sqrt(SO3VF, varargin)
% square root of a SO3VectorField
%
% Syntax
%   SO3VF = sqrt(SO3VF)
%
% Input
%  SO3VF - @SO3VectorField
%
% Output
%  SO3VF - @SO3VectorField
%

SO3VF = SO3VF.^(1/2);

end


classdef DNNSGAII < ALGORITHM
% <multi> <real/integer> <multimodal>
% Decision space based niching NSGA-II

%------------------------------- Reference --------------------------------
% J. Liang, C. Yue, and B. Qu. Multimodal multi-objective optimization: A
% preliminary study, Proceedings of the IEEE Congress on Evolutionary
% Computation, 2016, 2454-2461.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        function main(Algorithm,Problem)
            %% Generate random population
            Population = Problem.Initialization();
            [~,FrontNo,CrowdDis] = EnvironmentalSelection(Population,Problem.N);

            %% Optimization
            while Algorithm.NotTerminated(Population)
                MatingPool = TournamentSelection_Mod(round(Problem.N/2),round(Problem.N/2),Population.decs,FrontNo,-CrowdDis);
                Offspring  = OperatorGA(Problem,Population(MatingPool));
                [Population,FrontNo,CrowdDis] = EnvironmentalSelection([Population,Offspring],Problem.N);
            end
        end
    end
end


function []=panel4irfdisp_mean(N,n,Units,endo,irf_estimates_m,strshocks_estimates_m,IRFperiods,IRFt,stringdates1,T,decimaldates1,pref)

% IRFs
if pref.plot
% plot the figure
irf=figure('Tag','BEARresults');
set(irf,'Color',[0.9 0.9 0.9]);
   if IRFt==1
   set(irf,'name',['impulse response functions (no structural identification)']);
   elseif IRFt==2
   set(irf,'name',['impulse response functions (structural identification by Choleski ordering)']);
   elseif IRFt==3
   set(irf,'name',['impulse response functions (structural identification by triangular factorisation)']);
   elseif IRFt==4
   set(irf,'name',['impulse response functions (structural identification by sign restrictions)']);
   end
% initiate the count
count=0;
% loop over endogenous variables
for ii=1:n
   % loop over shocks
   for jj=1:n
   % increment count
   count=count+1;
   % then plot
   subplot(n,n,count)
   temp=irf_estimates_m{ii,jj};
   hold on
   Xpatch=[(1:IRFperiods) (IRFperiods:-1:1)];
   Ypatch=[temp(1,:) fliplr(temp(3,:))];
   IRFpatch=patch(Xpatch,Ypatch,[0.7 0.78 1]);
   set(IRFpatch,'facealpha',0.5);
   set(IRFpatch,'edgecolor','none');
   plot(temp(2,:),'Color',[0.4 0.4 1],'LineWidth',2);
   plot([1,IRFperiods],[0 0],'k--');
   hold off
   minband=min(temp(1,:));
   maxband=max(temp(3,:));
   space=maxband-minband;
   Ymin=minband-0.2*space;
   Ymax=maxband+0.2*space;
   set(gca,'XLim',[1 IRFperiods],'YLim',[Ymin Ymax],'FontName','Times New Roman');
      % top labels
      if count<=n
      title(endo{count,1},'FontWeight','normal');
      end
      % side labels
      if jj==1
      ylabel(endo{ii,1},'FontWeight','normal');
      end
   end
end
% top supertitle
ax=axes('Units','Normal','Position',[.11 .075 .85 .88],'Visible','off');
set(get(ax,'Title'),'Visible','on')
title('Shock:','FontSize',11,'FontName','Times New Roman','FontWeight','normal');
% side supertitle
ylabel('Response of:','FontSize',12,'FontName','Times New Roman','FontWeight','normal');
set(get(ax,'Ylabel'),'Visible','on');
% save on Excel
% create the cell that will be saved on excel
irfcell={};
% build preliminary elements: space between the tables
vertspace=repmat({''},IRFperiods+3,1);
horzspace=repmat({''},3,5*n);
% loop over endogenous variables
for ii=1:n
% initiate the cell of results
endocell={};
   % loop over shocks
   for jj=1:n
   % create a header
   header=[{['response of ' endo{ii,1} ' to ' endo{jj,1} ' shocks']} {''} {''} {''};{''} {''} {''} {''};{''} {'lower bound'} {'median'} {'upper bound'}];
   % complete the cell
   tempcell=[[header;num2cell((1:IRFperiods)') num2cell((irf_estimates_m{ii,jj})')] vertspace];
   % concatenate to the previous parts of unitcell
   endocell=[endocell tempcell];
   end
% concatenate to the previous parts of irfcell
irfcell=[irfcell;horzspace;endocell];
end
% trim
irfcell=irfcell(4:end,1:end-1);
% write in excel
warning on MATLAB:xlswrite:AddSheet
xlswrite([datapath '\results.xlsx'],irfcell,'IRF','B2');
warning off MATLAB:xlswrite:AddSheet

% structural shocks

% generate plot, if there is any structural decomposition
if IRFt~=1
% plot
strshocks=figure('Tag','BEARresults');
set(strshocks,'Color',[0.9 0.9 0.9]);
set(strshocks,'name','structural shocks')
% initiate the count
count=0;
   % loop over units
   for ii=1:N
      % loop over endogenous variables
      for jj=1:n
      % increment count
      count=count+1;
      % then plot
      subplot(N,n,count)
      hold on
      Xpatch=[decimaldates1' fliplr(decimaldates1')];
      Ypatch=[strshocks_estimates_m{jj,1,ii}(1,:) fliplr(strshocks_estimates_m{jj,1,ii}(3,:))];
      Fpatch=patch(Xpatch,Ypatch,[0.7 0.78 1]);
      set(Fpatch,'facealpha',0.6);
      set(Fpatch,'edgecolor','none');
      strs=plot(decimaldates1,strshocks_estimates_m{jj,1,ii}(2,:),'Color',[0.4 0.4 1],'LineWidth',2);
      plot([decimaldates1(1,1),decimaldates1(end,1)],[0 0],'k--');
      hold off
      minband=min(strshocks_estimates_m{jj,1,ii}(1,:));
      maxband=max(strshocks_estimates_m{jj,1,ii}(3,:));
      space=maxband-minband;
      Ymin=minband-0.2*space;
      Ymax=maxband+0.2*space;
      set(gca,'XLim',[decimaldates1(1,1) decimaldates1(end,1)],'YLim',[Ymin,Ymax],'FontName','Times New Roman');
         % top labels
         if count<=n
         title(endo{count,1},'FontWeight','normal');
         end
         % side labels
         if jj==1
         ylabel(Units{ii,1},'FontWeight','normal');
         end
      end
   end
end
end
   % save on Excel
% create the cell that will be saved on excel
strshockcell={};
% build preliminary elements: space between the tables
vertspace=repmat({''},T+3,1);
horzspace=repmat({''},3,5*n);
   % loop over units
   for ii=1:N
   % initiate the cell of results
   unitcell={};
      % loop over endogenous variables (horizontal dimension)
      for jj=1:n
      % create a header
      header=[{[Units{ii,1} ': ' endo{jj,1}]} {''} {''} {''};{''} {''} {''} {''};{''} {'lower bound'} {'median'} {'upper bound'}];
      % complete the cell
      endocell=[[header;stringdates1 num2cell(strshocks_estimates_m{jj,:,ii}')] vertspace];
      % concatenate to the previous parts of unitcell
      unitcell=[unitcell endocell];
      end
   % concatenate to the previous parts of afcell
   strshockcell=[strshockcell;horzspace;unitcell];
   end

   % trim
strshockcell=strshockcell(4:end,1:end-1);
% write in excel
if pref.results==1
bear.xlswritegeneral(fullfile(pref.results_path, [pref.results_sub '.xlsx']),strshockcell,'shocks','B2');
end
end


function uv = compute_flow_base(this, uv)
%%
%COMPUTE_FLOW_BASE   Base function for computing flow field
%   UV = COMPUTE_FLOW_BASE(THIS, INIT) computes the flow field UV with
%   algorithm THIS and the initialization INIT.
%
%   This is a member function of the class 'classic_nl_optical_flow'.
%
% Authors: Deqing Sun, Department of Computer Science, Brown University
% Contact: dqsun@cs.brown.edu
% $Date: $
% $Revision: $
%
% Copyright 2007-2010, Brown University, Providence, RI. USA
%
%                          All Rights Reserved
%
% All commercial use of this software, whether direct or indirect, is
% strictly prohibited including, without limitation, incorporation into in
% a commercial product, use in a commercial service, or production of other
% artifacts for commercial purposes.
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for research purposes is hereby granted without fee,
% provided that the above copyright notice appears in all copies and that
% both that copyright notice and this permission notice appear in
% supporting documentation, and that the name of the author and Brown
% University not be used in advertising or publicity pertaining to
% distribution of the software without specific, written prior permission.
%
% For commercial uses contact the Technology Venture Office of Brown University
%
% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO
% THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
% FITNESS FOR ANY PARTICULAR PURPOSE.  IN NO EVENT SHALL THE AUTHOR OR
% BROWN UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
% DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
% PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
% ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
% THIS SOFTWARE.

  % Construct quadratic formulation
  qua_this          = this;
  qua_this.lambda   = this.lambda_q;

  % Spatial
  if isa(this.rho_spatial_u{1}, 'robust_function')
      for i = 1:length(this.rho_spatial_u)
          a = this.rho_spatial_u{i}.param;
          qua_this.rho_spatial_u{i}   = robust_function('quadratic', a(1));
          a = this.rho_spatial_u{i}.param;
          qua_this.rho_spatial_v{i}   = robust_function('quadratic', a(1));
      end;
  elseif isa(this.rho_spatial_u{1}, 'gsm_density')
      for i = 1:length(this.rho_spatial_u)
          qua_this.rho_spatial_u{i}   = robust_function('quadratic', sqrt(1/this.rho_spatial_u{i}.precision));
          qua_this.rho_spatial_v{i}   = robust_function('quadratic', sqrt(1/this.rho_spatial_v{i}.precision));
      end;
  else
      error('evaluate_log_posterior: unknown rho function!');
  end;

  % Data
  if isa(qua_this.rho_data, 'robust_function')
      a = this.rho_data.param;
      qua_this.rho_data        = robust_function('quadratic', a(1));
  elseif isa(qua_this.rho_data, 'gsm_density')
      qua_this.rho_data        = robust_function('quadratic', sqrt(1/this.rho_data.precision));
  else
      error('evaluate_log_posterior: unknown rho function!');
  end;

  % Iterate flow computation
  for i = 1:this.max_iters

    duv = zeros(size(uv));

    % Compute spatial and temporal partial derivatives
    [It Ix Iy] = partial_deriv(this.images, uv, this.interpolation_method, this.deriv_filter);

    for j = 1:this.max_linear

        % Every linearization step updates the nonlinearity using the
        % previous flow increments

        % Compute linear flow operator
        if this.alpha == 1
            [A, b, parm, iterative] = ...
                flow_operator(qua_this, uv, duv, It, Ix, Iy);

        elseif this.alpha > 0
            [A, b] = ...
                flow_operator(qua_this, uv, duv, It, Ix, Iy);
            [A1, b1, parm, iterative] = ...
                flow_operator(this, uv, duv, It, Ix, Iy);
            A = this.alpha * A + (1-this.alpha) * A1;
            b = this.alpha * b + (1-this.alpha) * b1;

        elseif this.alpha == 0
            [A, b, parm, iterative] = ...
                flow_operator(this, uv, duv, It, Ix, Iy);

        else
            error('flow_operator@classic_nl_optical_flow: wrong gnc parameter alpha %3.2e', this.alpha);
        end;

        % Invoke the selected linear equation solver
        switch (lower(this.solver))
            case 'backslash'
                x = reshape(A \ b, size(uv));
            case 'sor'
                % Use complied mex file (may need to compile utils/mex/sor.pp)
                [x, flag, res, n] = sor(A', b, 1.9, this.sor_max_iters, 1E-2, uv(:));
                x = reshape(x, size(uv));
                fprintf('%d %d %d  ', flag, res, n);

            case 'bicgstab'
                [x,flag] = reshape(bicgstab(A, b, 1E-3, 200, [], [], uv(:)), size(uv)); %, parm
            case 'pcg'
                [x flag] = pcg(A,b, [], 10);
                x        = reshape(x, size(uv));
            otherwise
                error('Invalid solver!')
        end

        % If limiting the incremental flow to [-1, 1] is requested, do so
        if (this.limit_update)
            x(x > 1)  = 1;
            x(x < -1) = -1;
        end

        % Print status information (change betwen flow increment = flow
        %   increment at first linearization step)
        if this.display
            disp(['--Iteration: ', num2str(i), '   ', num2str(j), '   (norm of flow increment   ', ...
                num2str(norm(x(:)-duv(:))), ')'])
        end;

        % Terminate iteration early if flow doesn't change substantially
%         if norm(x(:)-duv(:)) < 1E-3
%             break;
%         end

        duv = x;

        uv0 = uv;
        uv  = uv+duv;

        if ~isempty(this.median_filter_size)

            %Compute weighted median solved by Li & Osher formula
            occ = detect_occlusion(uv, this.images);
            uv = denoise_color_weighted_medfilt2(uv, this.color_images, occ, this.area_hsz, this.median_filter_size, this.sigma_i, this.fullVersion);

        end;

        duv = uv - uv0;
        uv  = uv0;

    end;

    % Update flow fileds
    uv = uv + duv;

  end


% Gcone_twv_test.m
% test the Gcone object for "thread within view" version by Brian Gonzalez
% Copyright 2015-07-20, Jeff Fessler, University of Michigan

pn = jf_protected_names;

systypes = 'sf2,v:all';
systypes = {'sf2', systypes}
nsys = numel(systypes);

f.is_zxy = true;
if f.is_zxy
	to_zxy = @(x) permute(x, [3 1 2]); to_xyz = @(z) permute(z, [2 3 1]);
else
	to_zxy = @(x) x;
end

% small systems for basic tests
if 1 && (0 || ~isvar('Ac')), printm 'setup small'
	f.down = 16;

	dfs_list = [0 inf inf]; % arc flat parallel
	dsd_list = [949.075 949.075 inf]; % arc flat parallel

	f.dy = 0.7; % stress test SF with non-square
	igs = image_geom('nx', 512, 'ny', 480, 'nz', 416, ...
		'dx', 1, 'dy', f.dy, 'dz', 0.5, ...
		'offset_x', 2.9, 'offset_y', 3.5, ...
		'offset_z', -3.4, ...
		'mask', 'all-but-edge', ... % trick: for hct2
		'down', f.down);

	for kk = 1:numel(dfs_list)

		cgs = ct_geom('ge2', 'nt', 320, ...
			'source_z0', -20, 'pitch', 0.5, ... % test helix
			'dfs', dfs_list(kk), ... % arc or flat
			'dsd', dsd_list(kk), ... % fan or parallel beam
			'down', f.down);

		for ii=1:nsys
			systype = systypes{ii};
			printm('testing type %s dfs=%g dsd=%g', ...
				systype, cgs.dfs, cgs.dsd)

			args = {cgs, igs, 'type', systype};
			args = {args{:}, 'zxy', f.is_zxy};

			Ac = Gcone(args{:});

		%	im(Ac * to_zxy(single(igs.mask)))
		%	im(to_xyz(Ac' * cgs.ones)), prompt

			tester_tomo2(Ac, to_zxy(igs.mask)) % paces
			test_adjoint(Ac, 'big', 1, 'tol', 5e-5)
		end % systype
	end % dfs
end % small

if ~isvar('x0'), printm 'x0 big'
	f.down = 4;
	igb = image_geom('nx', 512, 'ny', 480, 'nz', 416, ...
		'dx', 1, 'dz', 0.5, ...
		'dy', 0.7, ... % stress test
		'offset_x', 12.9, 'offset_y', 3.5, 'offset_z', -3.4, ...
		'down', f.down);
	ell = [3*igb.dx 5*igb.dx -2*igb.dz ...
		igb.dx*igb.nx/3 igb.dy*igb.ny/4 igb.zfov/4 ...
		0 0 10];
	x0 = ellipsoid_im(igb, ell, 'oversample', 2);
end

% big systems for accuracy tests
if 0 || ~isvar('Ab'), printm 'setup big'
	cgb = ct_geom('ge1', 'nt', 320, ...
		'source_z0', -40, 'pitch', 0.5, ... % test helix
		'down', f.down);
%		'dfs', inf, ... % flat detector
%		'dsd', inf, 'dfs', inf, ... % parallel beam

	for ii=1:nsys
		systype = systypes{ii};
		Ab{ii} = Gcone(cgb, igb, 'type', systype, 'zxy', f.is_zxy);
	end
end

if ~isvar('ya'), printm 'analytical projections'
	ya = ellipsoid_proj(cgb, ell, 'oversample', 2);
%	im clf, im(ya)
%prompt
end

if 0 || ~isvar('yb'), printm 'discrete projections'
	nrmse = @(x,y) norm(y(:)-x(:)) / norm(x(:)) * 100;
	x00 = to_zxy(x0);
	for ii=1:nsys
		cpu etic
		yb{ii} = Ab{ii} * x00;
		f.time(ii) = cpu('etoc');
		printm('%s: time %g nrmse %g %%', ...
			systypes{ii}, f.time(ii), nrmse(ya, yb{ii}))
	end
end

if 0
	im_toggle(ya(:,end/2,:), yb{1}(:,end/2,:), ...
		yb{1}(:,end/2,:) - ya(:,end/2,:))
	im(ya(:,end/2,:) - yb{1}(:,end/2,:))
	im(yb{1}(:,end/2,:) - yb{2}(:,end/2,:))
end

if 1, printm 'look at error in worst views'
	im('pl', 2, nsys+1)
	for ii=1:numel(systypes)
		err = yb{ii} - ya;
		tmp = reshape(err, [], cgb.na);
		tmp = sqrt(mean(tmp.^2)); % error in each view
		ia = imax(tmp); % worst view
		im(ii, err(:,:,ia)), cbar h
		titlef('%s ia=%d', systypes{ii}, ia)
		im('subplot', ii+1+nsys)
		if im
			plot(1:cgb.na, tmp), axis tight
			titlef('%s RMS', systypes{ii})
			xlabelf('view')
		end
	end
	if 1
		err = yb{2} - yb{1};
		tmp = reshape(err, [], cgb.na);
		tmp = sqrt(mean(tmp.^2)); % error in each view
		ia = imax(tmp); % worst view
		im(nsys+1, err(:,:,ia)), cbar h
		titlef('%s vs %s', systypes{1}, systypes{2})
	end
return
end

if 1, printm 'projection profiles'
	it = cgb.nt;
	it = round(cgb.nt/2); % middle
	it = it + [-2 0 2];
	ia = imin(abs(cgb.ad - 45));
%	ia = ceil(ia/2);
	pro = @(y) col(y(:,it,ia));
	arg = [];
	for ii=1:numel(systypes)
		arg = [arg pro(yb{ii})];
	end
	if im
		clf, plot([arg pro(ya)])
		text(10, 200, sprintf('ia=%d', ia))
		text(10, 400, sprintf('ang=%g', cgb.ad(ia)))
		legend(systypes{:}, 'true')
		axisy(0, 1.2 * max(ya(:)))
		grid
	end
return
end


clear
% define the root name of database
root = '../data_preparation/prepared_data/';

% which scales we're doing
sigma = 1;
num_samples = 5e5;

scales = [0.25,0.35,0.5];
frontalView = 1;

profileViewInds = [2,3,4];

version = 'multi_pie';
ratio_neg = 5;
norm = 1;

data_loc = 'mpie_';
rng(0);

% where to save generated patches for external training
% (e.g. for training CEN patches)
patches_loc = './patches/';
patch_folder = [patches_loc version '/'];

for s=scales
    Save_all_patches(root, frontalView, profileViewInds,...
        s, sigma, version, patch_folder, 'ratio_neg', ratio_neg,...
        'num_samples', num_samples, 'data_loc', data_loc,...
        'normalisation_size', 19);
end


function [F,S] = bodyForceSSD(A,B,BGrad,U,X,NumRows,NumCols,NumPages,VoxSize,RegDim,HX,HY,HZ);
% bodyForceSSD: compute SSD body force
%
% arguments:
%   A - reference image
%   B - floating image
%   BGrad - gradient of floating image
%   U - displacement field
%   X - field of grid positions
%   NumRows - number of rows in image
%   NumCols - number of columns in image
%   NumPages (optional) - number of pages in (3D) images
%   F - body force field
%   S - value of similarity measure
%
%
%
% author: Nathan D. Cahill
% email: nathan.cahill@rit.edu
% affiliation: Rochester Institute of Technology
% date: January 2014
% licence: GNU GPL v3 licence.
%
% Copyright Nathan D. Cahill
% Code available from https://github.com/tomdoel/npReg
%
%

if RegDim == 2 % 2-D

    % evaluate floating image and gradient at deformation grid
    % x and y index are flipped!
    XNew = X-U;

    BWarp = interp2(X(:,:,2),X(:,:,1),B,XNew(:,:,2),XNew(:,:,1),'*linear',0);
    BWarpGrad = cat(3,imfilter(BWarp,HX,'replicate','same'),...
        imfilter(BWarp,HY,'replicate','same'));

    % compute difference image
    DiffImage = A - BWarp;

    % compute SSD value
    S = sum(DiffImage(:).^2);

    % finally, compute body force
    F = repmat(DiffImage,[1 1 2]).*BWarpGrad;

else % 3-D

    % evaluate floating image and gradient at deformation grid
    % x and y index are flipped!
    XNew = X-U;

    BWarp = interp3(X(:,:,:,2),X(:,:,:,1),X(:,:,:,3),B,XNew(:,:,:,2),XNew(:,:,:,1),XNew(:,:,:,3),'*linear',0);
    BWarpGrad = cat(4,imfilter(BWarp,HX,'replicate','same'),...
        imfilter(BWarp,HY,'replicate','same'),...
        imfilter(BWarp,HZ,'replicate','same'));

    % compute difference image
    DiffImage = A - BWarp;

    % compute SSD value
    S = sum(DiffImage(:).^2);

    % finally, compute body force
    F = repmat(DiffImage,[1 1 1 3]).*BWarpGrad;

end


classdef S2AxisFieldHarmonic < S2AxisField
% a class represeneting a axis field on the sphere

properties
  sF;
end

properties(Dependent = true, Access = protected)
  xx;
  xy;
  yy;
  xz;
  yz;
  zz;
end

properties(Dependent = true)
  bandwidth
end

methods

  function sVF = S2AxisFieldHarmonic(sF, varargin)
    % initialize a spherical vector field
    if nargin == 0, return; end

    if length(sF) == 6
      sVF.sF = sF(:);
    end

  end

  function bw = get.bandwidth(sVF), bw = sVF.sF.bandwidth; end
  function xx = get.xx(sVF), xx = sVF.sF(1); end
  function xy = get.xy(sVF), xy = sVF.sF(2); end
  function yy = get.yy(sVF), yy = sVF.sF(3); end
  function xz = get.xz(sVF), xz = sVF.sF(4); end
  function yz = get.yz(sVF), yz = sVF.sF(5); end
  function zz = get.zz(sVF), zz = sVF.sF(6); end
  function sVF = set.xx(sVF, xx), sVF.sF(1) = xx; end
  function sVF = set.xy(sVF, xy), sVF.sF(2) = xy; end
  function sVF = set.yy(sVF, yy), sVF.sF(3) = yy; end
  function sVF = set.xz(sVF, xz), sVF.sF(4) = xz; end
  function sVF = set.yz(sVF, yz), sVF.sF(5) = yz; end
  function sVF = set.zz(sVF, zz), sVF.sF(6) = zz; end

end

methods(Static = true)
  sAF = quadrature(f, varargin)
  sAF = approximation(v, y, varargin)
  function sAF = normal
    sAF = S2AxisFieldHarmonic.quadrature(@(v) v(:),'bandwidth',2);
  end
end

end


%%*****************************************************************
%% HKMcorr: corrector step for the HKM direction.
%%
%%*****************************************************************
%% SDPT3: version 4.0
%% Copyright (c) 1997 by
%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************

  function [dX,dy,dZ,resnrm,EinvRc] = HKMcorr(blk,At,par,rp,Rd,sigmu,hRd,...
            dX,dZ,coeff,L,X,Z);

    global matfct_options solve_ok

    printlevel = par.printlevel;
%%
    [rhs,EinvRc] = HKMrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ);
    m = length(rp); ncolU = size(coeff.mat12,2);
    rhs = [rhs; zeros(m+ncolU-length(rhs),1)];
%%
    solve_ok = 1; resnrm = norm(rhs);
    if strcmp(matfct_options,'chol') | strcmp(matfct_options,'spchol') ...
       | strcmp(matfct_options,'ldl') | strcmp(matfct_options,'spldl')
       [xx,resnrm,solve_ok] = symqmr(coeff,rhs,L,[],[],printlevel);
       if (solve_ok<=0) & (printlevel)
          fprintf('\n  warning: symqmr fails: %3.1f.',solve_ok);
       end
    else
       [xx,resnrm,solve_ok] = mybicgstab(coeff,rhs,L,[],[],printlevel);
       if (solve_ok<=0) & (printlevel)
          fprintf('\n  warning: bicgstab fails: %3.1f.',solve_ok);
       end
    end
    if (printlevel>=3); fprintf('%2.0d ',length(resnrm)-1); end
%%
    [dX,dy,dZ] = HKMdirfun(blk,At,par,Rd,EinvRc,X,xx,m);
%%*****************************************************************


function pv=computePositionVariance(view)
% computePostionVariance - compute position variance across
% cortical surface
%
% pv=computePositionVariance(view)
%
% 2008/05 SD & KA: wrote it

if ~exist('view','var') || isempty(view), error('Need view struct'); end

model = viewGet(view,'rmCurModel');

x = rmGet(model,'x0');
y = rmGet(model,'y0');
w = rmGet(model,'varexp');

edges        = double(view.edges);
numNeighbors = double(view.nodes(4,:));
edgeOffsets  = double(view.nodes(5,:));

pv = varOfNeighbors(x,y,w,edges,edgeOffsets,numNeighbors);

return


function tf = spm_cfg_eeg_tf
% Configuration file for M/EEG time-frequency analysis
%__________________________________________________________________________
% Copyright (C) 2010-2011 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: spm_cfg_eeg_tf.m 6929 2016-11-14 13:07:31Z guillaume $

%--------------------------------------------------------------------------
% D
%--------------------------------------------------------------------------
D        = cfg_files;
D.tag    = 'D';
D.name   = 'File Name';
D.filter = 'mat';
D.num    = [1 1];
D.help   = {'Select the M/EEG mat file.'};

%--------------------------------------------------------------------------
% timewin
%--------------------------------------------------------------------------
timewin         = cfg_entry;
timewin.tag     = 'timewin';
timewin.name    = 'Time window';
timewin.strtype = 'r';
timewin.num     = [1 2];
timewin.val     = {[-Inf Inf]};
timewin.help    = {'Time window (ms)'};

%--------------------------------------------------------------------------
% frequencies
%--------------------------------------------------------------------------
frequencies         = cfg_entry;
frequencies.tag     = 'frequencies';
frequencies.name    = 'Frequencies of interest';
frequencies.strtype = 'r';
frequencies.num     = [0 Inf];
frequencies.val     = {[]};
frequencies.help    = {'Frequencies of interest (as a vector), if empty 1-48 with optimal frequency bins ~1 Hz or above resolution'};

%--------------------------------------------------------------------------
% phase
%--------------------------------------------------------------------------
phase        = cfg_menu;
phase.tag    = 'phase';
phase.name   = 'Save phase';
phase.help   = {'Save phase as well as power'};
phase.labels = {'yes', 'no'};
phase.values = {1, 0};
phase.val    = {0};

%--------------------------------------------------------------------------
% method
%--------------------------------------------------------------------------
method      = cfg_choice;
method.tag  = 'method';
method.name = 'Spectral estimation';
method.help = {'Spectral estimation'};

specest_funs = spm_select('List',spm('dir'),'^spm_eeg_specest_.*\.m$');
specest_funs = cellstr(specest_funs);
method.values = cell(1,numel(specest_funs));
for i = 1:numel(specest_funs)
    method.values{i} = feval(spm_file(specest_funs{i},'basename'));
end

%--------------------------------------------------------------------------
% prefix
%--------------------------------------------------------------------------
prefix         = cfg_entry;
prefix.tag     = 'prefix';
prefix.name    = 'Filename Prefix';
prefix.help    = {'Specify the string to be prepended to the filenames of the output dataset.'};
prefix.strtype = 's';
prefix.num     = [0 Inf];
prefix.val     = {''};

%--------------------------------------------------------------------------
% M/EEG Time-Frequency Analysis
%--------------------------------------------------------------------------
tf = cfg_exbranch;
tf.tag = 'tf';
tf.name = 'Time-frequency analysis';
tf.val = {D, spm_cfg_eeg_channel_selector, frequencies, timewin, method, phase, prefix};
tf.help = {'Perform time-frequency analysis of epoched M/EEG data.'};
tf.prog = @eeg_tf;
tf.vout = @vout_eeg_tf;
tf.modality = {'EEG'};

%==========================================================================
% function out = eeg_tf(job)
%==========================================================================
function out = eeg_tf(job)
% construct the S struct
S   = [];
S.D = job.D{1};

S.channels = spm_cfg_eeg_channel_selector(job.channels);

S.frequencies = job.frequencies;
S.timewin = job.timewin;
S.phase = job.phase;

S.method = cell2mat(fieldnames(job.method));
S.settings = job.method.(S.method);

S.prefix = job.prefix;

[Dtf, Dtph] = spm_eeg_tf(S);

out.Dtf = Dtf;
out.Dtfname = {Dtf.fullfile};

out.Dtph = Dtph;
if ~isempty(Dtph)
    out.Dtphname = {Dtph.fullfile};
else
    out.Dtphname = {''};
end

%==========================================================================
% function dep = vout_eeg_tf(job)
%==========================================================================
function dep = vout_eeg_tf(job)
% return dependencies
dep(1)            = cfg_dep;
dep(1).sname      = 'M/EEG time-frequency power dataset';
dep(1).src_output = substruct('.','Dtf');
% this can be entered into any evaluated input
dep(1).tgt_spec   = cfg_findspec({{'strtype','e'}});

dep(2)            = cfg_dep;
dep(2).sname      = 'M/EEG time-frequency power dataset';
dep(2).src_output = substruct('.','Dtfname');
% this can be entered into any file selector
dep(2).tgt_spec   = cfg_findspec({{'filter','mat'}});

if job.phase
    dep(3)            = cfg_dep;
    dep(3).sname      = 'M/EEG time-frequency phase dataset';
    dep(3).src_output = substruct('.','Dtph');
    % this can be entered into any evaluated input
    dep(3).tgt_spec   = cfg_findspec({{'strtype','e'}});

    dep(4)            = cfg_dep;
    dep(4).sname      = 'M/EEG time-frequency phase dataset';
    dep(4).src_output = substruct('.','Dtphname');
    % this can be entered into any file selector
    dep(4).tgt_spec   = cfg_findspec({{'filter','mat'}});
end


function []=addColormapButton(varargin)
%% Viewing figures: changing colormap
% addColormapButton
% addColormapButton(hf)

% This script creates a new pushtool in a figure's toolbar to manipulate
% the color scheme displayed in the figure images
%%
switch nargin
    case 0
        hf=gcf;
    case 1
        hf=varargin{1};
end

% Create icon
S=zeros(16,16,3);
S(1,:,:)=parula(16);
S(2,:,:)=parula(16);
S(3,:,:)=parula(16);
S(4,:,:)=parula(16);
S(5,:,:)=jet(16);
S(6,:,:)=jet(16);
S(7,:,:)=jet(16);
S(8,:,:)=jet(16);
S(9,:,:)=gray(16);
S(10,:,:)=gray(16);
S(11,:,:)=gray(16);
S(12,:,:)=gray(16);
S(13,:,:)=coldwarm(16);
S(14,:,:)=coldwarm(16);
S(15,:,:)=coldwarm(16);
S(16,:,:)=coldwarm(16);

hb = findall(hf,'Type','uitoolbar');

% Create a uipushtool in the toolbar
uipushtool(hb(1),'TooltipString','colormap','CData',S,'Tag','colormap_button','ClickedCallback',{@colormapFunc,{hf}});

end

%% Colormap function  colormapFunc

function colormapFunc(~,~,inputCell)

hf = inputCell{1};
prompt = {'Colormap'};
title = '';
format = struct('type','list');
format.style = 'popupmenu';
format.items = {' -- Select a color scheme -- ','coldwarm','parula','jet','hsv','hot','cool','gray','bone'};
default = cell(size(prompt,1),1);
default{1,1} = 1; % Default selection will always be instruction item
default = cell2struct(default,prompt,1);
prompt = repmat(prompt,1,2);
options.AlignControls = 'on';
choice = inputsdlg(prompt,title,format,default,options);

% Change color scheme for all existing images accordingly
if choice.Colormap == 2
    colormap(0.8*coldwarm);
elseif choice.Colormap == 3
    colormap(parula);
elseif choice.Colormap == 4
    colormap(jet);
elseif choice.Colormap == 5
    colormap(hsv);
elseif choice.Colormap == 6
    colormap(hot);
elseif choice.Colormap == 7
    colormap(cool);
elseif choice.Colormap == 8
    colormap(gray);
elseif choice.Colormap == 9
    colormap(bone);
end
end

%%
% MultiDIC: a MATLAB Toolbox for Multi-View 3D Digital Image Correlation
%
% License: <https://github.com/MultiDIC/MultiDIC/blob/master/LICENSE.txt>
%
% Copyright (C) 2018  Dana Solav
%
% Modified by Rana Odabas 2018
%
% If you use the toolbox/function for your research, please cite our paper:
% <https://engrxiv.org/fv47e>


function rgb = computeSliceRGB(slice, displayRange, lut)
%COMPUTESLICERGB Convert slice data to renderable slice
%
%   RGB = computeSliceRGB(SLICE)
%
%   RGB = computeSliceRGB(SLICE, DISPLAYRANGE, LUT)
%
%   Example
%     computeSliceRGB
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2011-11-07,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.

% RGB slices are returned directly
if ndims(slice) > 2
    rgb = slice;
    return;
end

% forces computation of extreme values
if isempty(displayRange) || islogical(slice)
    displayRange = [0 max(slice(:))];
end

% converts to uint8, rescaling data between 0 and max value
displayRange = double(displayRange);
extent = displayRange(2) - displayRange(1);
slice = uint8((double(slice) - displayRange(1)) * 255 / extent);

% eventually apply a LUT
if ~isempty(lut)
    if ischar(lut)
        lut = feval(lut, 256);
    end

    lutMax = max(lut(:));
    dim = size(slice);
    rgb = zeros([dim 3], 'uint8');

    % compute each channel
    for c = 1:size(lut, 2)
        res = zeros(size(slice));
        for i = 0:size(lut,1)-1
            res(slice==i) = lut(i+1, c);
        end
        rgb(:,:,c) = uint8(res * 255 / lutMax);
    end

else
    % if no LUT, simply use gray equivalent
    rgb = repmat(slice, [1 1 3]);
end


function test_bug1850

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_prepare_neighbours ft_channelrepair
%
% http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1850

load(dccnpath('/home/common/matlab/fieldtrip/data/test/latest/raw/meg/preproc_ctf275.mat'));

cfg = [];
cfg.channel = {'all', '-MRT23', '-MLP57'};
data = ft_selectdata(cfg, data);

cfg = [];
cfg.method = 'template';
cfg.template = 'CTF275_neighb.mat';
neighbours = ft_prepare_neighbours(cfg);

% get the full list of 275 channel names
allchans = {neighbours.label};
missingchans = setdiff(allchans, data.label);

% repair the two channels that were removed
cfg = [];
cfg.missingchannel = missingchans;
cfg.neighbours = neighbours;
cfg.method = 'spline';
data_repaired = ft_channelrepair(cfg,data);


%krf_logpolar 'log-polar transform'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros rf_logpolar.pane file
%
% Parameters:
% InputFile: i 'Input (rect)', required: 'input image, rectangular coordinates'
% OutputFile: o 'Output (log-polar)', required: 'output image, log-polar coordinates'
% Double: rmin 'min', default: 1: 'minimum radius'
% Double: rmax 'max', default: 64: 'maximum radius'
% Double: amin 'min', default: -90: 'minimum angle'
% Double: amax 'max', default: 90: 'maximum angle'
%
% Example: o = krf_logpolar(i, {'i','';'o','';'rmin',1;'rmax',64;'amin',-90;'amax',90})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% rf_logpolar - log-polar transform
%
%  DESCRIPTION
% This is a spacial transform (warping) of an image.
% Specifically, we map the specified section of an
% annulus in the input image to a rectangle in the
% output image.  This is done by mapping annulus pixels
% (m,n) to (rho, theta) pixels, where rho is the log of
% the radius and theta is the angle from m-axis.
%
% The center of the annulus is also specified as the
% upper left corner of the image (0,0), or the center
% (N/2, N/2).  In both cases, angles are measured from
% the m (horizontal) axis, and positive in the
% clockwise direction (to remain consistant with the
% left-hand coordinate system typically used in image
% processing).
%
% The dimensions of the output image are set to either
% the minimum size that will retain the resolution of
% the input image, or that size rounded up to the
% nearest power of 2 depending on the -logradsz and -anglesz flags.
%
%
%
%  EXAMPLES
% See the html tutorial in $REGISTER/examples/html/README_FIRST.html
%
%  "SEE ALSO"
%
%  RESTRICTIONS
%
%  REFERENCES
% Cideciyan, Artur V.  "Registration of Ocular Fundus
% Images" IEEE Engineering in Medicine and Biology.
% Jan/Feb 1995, pp. 52-58.
%
%  COPYRIGHT
% Copyright (C) 1996 - 1997, University of New Mexico.  All rights reserved.
%

function varargout = krf_logpolar(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = krf_logpolar(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'o', '__output';'rmin', 1;'rmax', 64;'amin', -90;'amax', 90};
maxval={0,0,2,2,360,360};
minval={0,0,2,2,-360,-360};
istoggle=[0,0,0,0,0,0];
was_set=istoggle * 0;
paramtype={'InputFile','OutputFile','Double','Double','Double','Double'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(1,1);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
[varargout{:}]=callKhoros([w 'rf_logpolar"  '],Inputs,narglist);


function [data_endo,favar]=favar_gensample3(data_endo,favar)

% determine the numbers of variables other than factors
favar.numdata_exfactors=size(favar.data_exfactors,2);

if favar.onestep==1
    % initalise variables
    XZ=favar.XZ;
    nfactorvar=favar.nfactorvar;
    numpc=favar.numpc;
    Lf=favar.l;
    % identify factors in the case of onestep estimation: rotate the
    % factors and the loadings matrix following Bernanke, Boivin, Eliasz (2005)
    Lfy=bear.favar_olssvd(favar.X(:,numpc+1:nfactorvar),data_endo)';% upper KxM block of Ly set to zero
    Lf=[Lf(1:numpc,:);Lfy(:,1:numpc)];
    Ly=[zeros(numpc,favar.numdata_exfactors);Lfy(:,numpc+1:numpc+favar.numdata_exfactors)];

    %transform factors and loadings for LE normalization
    [ql,rl]=qr(Lf');
    Lf=rl;  % do not transpose yet, is upper triangular
    XZ=XZ*ql;
    %need identity in the first K columns of Lf, call them A for now
    A=Lf(:,1:numpc); %index here for factors
    Lf=[eye(numpc),inv(A)*Lf(:,numpc+1:nfactorvar)]';
    favar.XZ_rotated=XZ*A;

    %rotated loadings
    favar.L=[Lf Ly;zeros(favar.numdata_exfactors,numpc),eye(favar.numdata_exfactors)];

    %replace factors with factors rotated in data_endo
    for ii=1:size(favar.variablestrings_factorsonly)
        data_endo(:,favar.variablestrings_factorsonly(ii))=favar.XZ_rotated(:,ii);
    end

    %errors of factor equation (observation equation)
    if favar.numdata_exfactors~=0
        favar.evf=favar.X-favar.data_exfactors*Ly'-favar.XZ_rotated*Lf';
    elseif favar.numdata_exfactors==0 % in this case we have a pure factor model
        favar.evf=favar.X-favar.XZ_rotated*Lf';
    end
    %favar.evf=favar.XY-data_endo*favar.L';
    favar.Sigma=favar.evf'*favar.evf/size(favar.X,1);
    favar.Sigma=diag(diag(favar.Sigma));
    favar.Sigma=diag([diag(favar.Sigma);zeros(favar.numdata_exfactors,1)]);

    % from here proceed with non-standardised data
    favar.data_exfactors=favar.data_exfactors_temp;
    favar.X=favar.X_temp;

    % replace standardised data with not-standardised data in endo
    for ii=1:size(favar.variablestrings_exfactors)
        data_endo(:,favar.variablestrings_exfactors(ii))=favar.data_exfactors(:,ii);
    end

    % state-space representation
    favar.XY=[favar.X,favar.data_exfactors];

elseif favar.onestep==0 % two-step
    if favar.numdata_exfactors==0
        favar.slowfast=0; % this identifiaction is not applicable in a pure factor model
    end
    if favar.slowfast==1 %apply slowfast recursive identification as in BBE (2005)
        % factor roation with slow/fast scheme
        favar.XZ_rotated=bear.favar_facrot(favar.XZ,favar.data_exfactors(:,end),favar.XZ_slow); %end, has eventually to be changed
        %replace factors with factors rotated
        for ii=1:size(favar.variablestrings_factorsonly)
            data_endo(:,favar.variablestrings_factorsonly(ii))=favar.XZ_rotated(:,ii);
        end
    end
    % state-space representation
    favar.XY=[favar.X,favar.data_exfactors];
    % new loadings
    favar.L=(bear.favar_olssvd(favar.XY,data_endo))';
    % manipulate loadings matrix for blocks
    if favar.blocks==1
        for bb=1:favar.nbnames
            Xbindex=favar.blockindex_each{bb,1};
            Xbindex2=favar.blockindex_each{bb,1}==0;
            %
            favar.L(Xbindex,favar.blocks_index{bb,1})=favar.l_block{bb,1};
            favar.L(Xbindex2,favar.blocks_index{bb,1})=0;
            favar.L(1:favar.nfactorvar,favar.variablestrings_exfactors)=0;
            favar.L(favar.nfactorvar+1:end,favar.variablestrings_factorsonly)=0;
        end
        for vv=1:favar.numdata_exfactors
            favar.L(favar.nfactorvar+1:end,favar.variablestrings_exfactors(vv,1))=1;
        end
    end

    %errors of factor equation (observation equation)
    favar.evf=favar.XY-data_endo*favar.L';
    favar.Sigma=favar.evf'*favar.evf/size(favar.XY,1); %
    favar.Sigma=diag(diag(favar.Sigma));
end

% to activate routines in the BVAR framwork and IRFt 4, where we have It-Bu
% x X, Y and L
favar.bvar=1;
%%% this should be equivalent
%regressing the factors from all x on the slow moving factors and the FFR
% % %         favar.Beta = mvregress(data_endo,favar.XZ);
% % %         favar.Beta_exfactors = favar.Beta(favar.variablestrings_exfactors(:,end),:); %we assume here that favar.variablestrings_exfactors, all the variables that are not factors, are
% % %         favar.Frot=favar.XZ-favar.data_endo(:,favar.variablestrings_exfactors(:,end))*favar.Beta_exfactors;


classdef (Abstract) mm_shared_pfcpf_acps < mp.mm_shared_pfcpf_acp

%   MATPOWER
%   Copyright (c) 2021-2022, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

%     properties
%     end

    methods
        function ad = build_aux_data(obj, nm, dm, mpopt)
            %% call parent
            ad = build_aux_data@mp.mm_shared_pfcpf_acp(obj, nm, dm, mpopt);

            switch mpopt.pf.alg
                case 'GS'
                    ad.Y = nm.C * nm.get_params([], 'Y') * nm.C';
                case 'ZG'
                    pvq = [ad.pv; ad.pq];
                    Y = nm.C * nm.get_params([], 'Y') * nm.C';
                    Y21 = Y(pvq, ad.ref);
                    Y22 = Y(pvq, pvq);
                    [L, U, p, q] = lu(Y22, 'vector');
                    [junk, iq] = sort(q);
                    [ad.Y, ad.Y21, ad.L, ad.U, ad.p, ad.iq] = ...
                        deal(Y, Y21, L, U, p, iq);
            end
        end

        function obj = add_system_vars_pf(obj, nm, dm, mpopt)
            %% get model variables
            vvars = nm.model_vvars();

            %% voltage angles
            obj.add_system_varset_pf(nm, vvars{1}, 'pv');
            obj.add_system_varset_pf(nm, vvars{1}, 'pq');

            %% voltage magnitudes
            obj.add_system_varset_pf(nm, vvars{2}, 'pq');
        end

        function [f, J] = node_balance_equations(obj, x, nm, fdpf)
            %% index vector
            ad = obj.aux_data;
            pvq = [ad.pv; ad.pq];

            %% update network model state ([v_; z_]) from math model state (x)
            [v_, z_] = obj.convert_x_m2n(x, nm, 1);

            %% incidence matrix
            C = nm.C;

            %% Jacobian
            if nargout > 1
                %% get port power injections with derivatives
                var_names = cellfun(@(x)x{1}, ad.var_map, 'UniformOutput', false);
                dz = any(strcmp(var_names, 'zr')) || ...
                     any(strcmp(var_names, 'zi'));
                if dz
                    [S, dS.va, dS.vm, dS.zr, dS.zi] = nm.port_inj_power([v_; z_], 1);
                else
                    [S, dS.va, dS.vm] = nm.port_inj_power([v_; z_], 1);
                end
                dS.va = C * dS.va;
                dS.vm = C * dS.vm;
                if dz
                    dS.zr = C * dS.zr;
                    dS.zi = C * dS.zi;
                end
                JJ = cell(2, length(ad.var_map));

                for k = 1:length(ad.var_map)
                    m = ad.var_map{k};
                    name = m{1};
                    if ~isempty(m{2})       %% i1:iN
                        i1 = m{2};
                        iN = m{3};
                        JJ{1, k} = real(dS.(name)(pvq,   i1:iN));
                        JJ{2, k} = imag(dS.(name)(ad.pq, i1:iN));
                    elseif isempty(m{4})    %% :
                        JJ{1, k} = real(dS.(name)(pvq,   :));
                        JJ{2, k} = imag(dS.(name)(ad.pq, :));
                    else                    %% idx
                        idx = m{4};
                        JJ{1, k} = real(dS.(name)(pvq,   idx));
                        JJ{2, k} = imag(dS.(name)(ad.pq, idx));
                    end
                end
                J = vertcat( horzcat(JJ{1, :}), ...
                             horzcat(JJ{2, :})  );
            else
                %% get port power injections (w/o derivatives)
                S = nm.port_inj_power([v_; z_], 1);
            end

            %% nodal power balance
            if nargin > 3 && fdpf
                SS = C * S ./ abs(v_);  %% for fast-decoupled formulation
            else
                SS = C * S;
            end
            f = [real(SS(pvq)); imag(SS(ad.pq))];
        end
    end     %% methods
end         %% classdef


function roi = roiFromMesh(seg, mapMethod, mr);
%
% roi = roiFromMesh(seg, [mapMethod='all'], [mr]);
%
% Create an ROI based on vertices in the selected mesh contained
% within a given segmentation struct seg, based on the
% sepecified mapping method.
%
% mapMethod can be 'layer1' or 'all' ('all' by default).
%
% If an mr struct is passed as an optional third argument, will
% check the new ROI coords against these coords and return it
% relative to that mr object. (E.g., will xform the ROI from
% segmented volume -> inplanes).
%
% ras, 01/2007.
if nargin < 1, error('Need roi and segmentation inputs.'); end

if notDefined('mapMethod'),     mapMethod = 'all'; end

msh = segGet(seg, 'SelectedMesh');
mrmRoi = mrmGet(msh,'curRoi'); % ROI as defined on mesh
if ~isfield(mrmRoi,'vertices'), error('No ROI defined on mesh!'); end

% initialize empty ROI based on the same anatomy coords as the segmentation
roi = roiCreate('I|P|R');
roi.voxelSize = msh.mmPerVox;

% the main part of this code will be finding the indices I
% from the gray coordinates which are contained within the
% ROI, given the current mapping method.
% We initialize I to include those layer 1 nodes in the ROI:
layer1Nodes = msh.vertexGrayMap(1,mrmRoi.vertices);
curLayer = unique( layer1Nodes(layer1Nodes>0) );
I = curLayer;

if isequal(lower(mapMethod), 'all')
    [nodes edges] = segGet(seg, 'gray');

    % Start with the ROI vertices, which *should* be just layer 1 nodes.
    curLayerNum = 1;
    while ~isempty(curLayer)
        nextLayer = [];
        curLayerNum = curLayerNum+1;
        for ii = 1:length(curLayer)
            offset = nodes(5,curLayer(ii));
            if offset>length(edges), continue; end
            numConnected = nodes(4,curLayer(ii));
            neighbors = edges(offset:offset+numConnected-1);
            nextLayer = [nextLayer, neighbors(nodes(6,neighbors)==curLayerNum)];
        end
        nextLayer = unique(nextLayer);
        I = [I nextLayer];
        curLayer = nextLayer;
    end
end

grayCoords = segGet(seg, 'GrayCoords');
roi.coords = grayCoords(:,I);

% give the ROI a name that describes approx where it is
cen = round( mean(roi.coords, 2) );
roi.name = sprintf('MeshROI ~(%i, %i, %i)', cen(2), cen(1), cen(3));

if exist('mr', 'var') | ~isempty(mr)
    mr = mrParse(mr);
    roi = roiCheckCoords(roi, mr);
end

return


%% DEMO_febio_0003_beam_bending
% Below is a demonstration for:
%
% * Building geometry for a beam with hexahedral elements
% * Defining the boundary conditions
% * Coding the febio structure
% * Running the model
% * Importing and visualizing the displacement results

%% Keywords
%
% * febio_spec version 4.0
% * febio, FEBio
% * beam pressure loading
% * surface pressure boundary condition
% * hexahedral elements, hex8
% * beam, rectangular
% * static, solid
% * hyperelastic, Ogden
% * displacement logfile
% * force logfile

%%

clear; close all; clc;

%% Plot settings
fontSize=20;
faceAlpha1=0.8;
markerSize=40;
markerSize2=20;
lineWidth=3;

%% Control parameters

% Path names
defaultFolder = fileparts(fileparts(mfilename('fullpath')));
savePath=fullfile(defaultFolder,'data','temp');

% Defining file names
febioFebFileNamePart='tempModel';
febioFebFileName=fullfile(savePath,[febioFebFileNamePart,'.feb']); %FEB file name
febioLogFileName=[febioFebFileNamePart,'.txt']; %FEBio log file name
febioLogFileName_disp=[febioFebFileNamePart,'_disp_out.txt']; %Log file name for exporting displacement
febioLogFileName_force=[febioFebFileNamePart,'_force_out.txt']; %Log file name for exporting force

%Specifying dimensions and number of elements
beamWidth=10;
sampleWidth=beamWidth; %Width
sampleThickness=4*beamWidth; %Thickness
sampleHeight=beamWidth; %Height
pointSpacings=2*ones(1,3); %Desired point spacing between nodes
numElementsWidth=round(sampleWidth/pointSpacings(1)); %Number of elemens in dir 1
numElementsThickness=round(sampleThickness/pointSpacings(2)); %Number of elemens in dir 2
numElementsHeight=round(sampleHeight/pointSpacings(3)); %Number of elemens in dir 3

%Define applied force
appliedPressure=1e-5;

%Material parameter set
c1=1e-3; %Shear-modulus-like parameter
m1=8; %Material parameter setting degree of non-linearity
k_factor=1e2; %Bulk modulus factor
k=c1*k_factor; %Bulk modulus

% FEA control settings
numTimeSteps=10; %Number of time steps desired
max_refs=25; %Max reforms
max_ups=0; %Set to zero to use full-Newton iterations
opt_iter=6; %Optimum number of iterations
max_retries=5; %Maximum number of retires
dtmin=(1/numTimeSteps)/100; %Minimum time step size
dtmax=1/numTimeSteps; %Maximum time step size

runMode='external';% 'internal' or 'external'

%% Creating model geometry and mesh
% A box is created with tri-linear hexahedral (hex8) elements using the
% |hexMeshBox| function. The function offers the boundary faces with
% seperate labels for the top, bottom, left, right, front, and back sides.
% As such these can be used to define boundary conditions on the exterior.

% Create a box with hexahedral elements
beamDimensions=[sampleWidth sampleThickness sampleHeight]; %Dimensions
beamElementNumbers=[numElementsWidth numElementsThickness numElementsHeight]; %Number of elements
outputStructType=2; %A structure compatible with mesh view
[meshStruct]=hexMeshBox(beamDimensions,beamElementNumbers,outputStructType);

%Access elements, nodes, and faces from the structure
E=meshStruct.elements; %The elements
V=meshStruct.nodes; %The nodes (vertices)
Fb=meshStruct.facesBoundary; %The boundary faces
Cb=meshStruct.boundaryMarker; %The "colors" or labels for the boundary faces
elementMaterialIndices=ones(size(E,1),1); %Element material indices

%%
% Plotting model boundary surfaces and a cut view

hFig=cFigure;

subplot(1,2,1); hold on;
title('Model boundary surfaces and labels','FontSize',fontSize);
gpatch(Fb,V,Cb,'k',faceAlpha1);
colormap(gjet(6)); icolorbar;
axisGeom(gca,fontSize);

hs=subplot(1,2,2); hold on;
title('Cut view of solid mesh','FontSize',fontSize);
optionStruct.hFig=[hFig hs];
meshView(meshStruct,optionStruct);
axisGeom(gca,fontSize);

drawnow;

%% Defining the boundary conditions
% The visualization of the model boundary shows colors for each side of the
% cube. These labels can be used to define boundary conditions.

%Define supported node set
bcSupportList=unique(Fb(Cb==4,:)); %Node set part of selected face

%Loaded surface
F_pressure=Fb(Cb==6,:);

%%
% Visualizing boundary conditions. Markers plotted on the semi-transparent
% model denote the nodes in the various boundary condition lists.

hf=cFigure;
title('Boundary conditions','FontSize',fontSize);
xlabel('X','FontSize',fontSize); ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize);
hold on;

gpatch(Fb,V,'kw','k',0.5);

hl(1)=plotV(V(bcSupportList,:),'k.','MarkerSize',markerSize);
hl(2)=gpatch(F_pressure,V,'r','k',1);

legend(hl,{'BC support','BC prescribe'});

axisGeom(gca,fontSize);
camlight headlight;
drawnow;

%% Defining the FEBio input structure
% See also |febioStructTemplate| and |febioStruct2xml| and the FEBio user
% manual.

%Get a template with default settings
[febio_spec]=febioStructTemplate;

%febio_spec version
febio_spec.ATTR.version='4.0';

%Module section
febio_spec.Module.ATTR.type='solid';

%Control section
febio_spec.Control.analysis='STATIC';
febio_spec.Control.time_steps=numTimeSteps;
febio_spec.Control.step_size=1/numTimeSteps;
febio_spec.Control.solver.max_refs=max_refs;
febio_spec.Control.solver.qn_method.max_ups=max_ups;
febio_spec.Control.time_stepper.dtmin=dtmin;
febio_spec.Control.time_stepper.dtmax=dtmax;
febio_spec.Control.time_stepper.max_retries=max_retries;
febio_spec.Control.time_stepper.opt_iter=opt_iter;

%Material section
materialName1='Material1';
febio_spec.Material.material{1}.ATTR.name=materialName1;
febio_spec.Material.material{1}.ATTR.type='Ogden';
febio_spec.Material.material{1}.ATTR.id=1;
febio_spec.Material.material{1}.c1=c1;
febio_spec.Material.material{1}.m1=m1;
febio_spec.Material.material{1}.c2=c1;
febio_spec.Material.material{1}.m2=-m1;
febio_spec.Material.material{1}.k=k;

%Mesh section
% -> Nodes
febio_spec.Mesh.Nodes{1}.ATTR.name='nodeSet_all'; %The node set name
febio_spec.Mesh.Nodes{1}.node.ATTR.id=(1:size(V,1))'; %The node id's
febio_spec.Mesh.Nodes{1}.node.VAL=V; %The nodel coordinates

% -> Elements
partName1='Part1';
febio_spec.Mesh.Elements{1}.ATTR.name=partName1; %Name of this part
febio_spec.Mesh.Elements{1}.ATTR.type='hex8'; %Element type
febio_spec.Mesh.Elements{1}.elem.ATTR.id=(1:1:size(E,1))'; %Element id's
febio_spec.Mesh.Elements{1}.elem.VAL=E; %The element matrix

% -> Surfaces
surfaceName1='LoadedSurface';
febio_spec.Mesh.Surface{1}.ATTR.name=surfaceName1;
febio_spec.Mesh.Surface{1}.quad4.ATTR.id=(1:1:size(F_pressure,1))';
febio_spec.Mesh.Surface{1}.quad4.VAL=F_pressure;

% -> NodeSets
nodeSetName1='bcSupportList';
febio_spec.Mesh.NodeSet{1}.ATTR.name=nodeSetName1;
febio_spec.Mesh.NodeSet{1}.VAL=bcSupportList(:)';

%MeshDomains section
febio_spec.MeshDomains.SolidDomain.ATTR.name=partName1;
febio_spec.MeshDomains.SolidDomain.ATTR.mat=materialName1;

%Boundary condition section
% -> Fix boundary conditions
febio_spec.Boundary.bc{1}.ATTR.name='zero_displacement_xyz';
febio_spec.Boundary.bc{1}.ATTR.type='zero displacement';
febio_spec.Boundary.bc{1}.ATTR.node_set=nodeSetName1;
febio_spec.Boundary.bc{1}.x_dof=1;
febio_spec.Boundary.bc{1}.y_dof=1;
febio_spec.Boundary.bc{1}.z_dof=1;

%Loads section
% -> Surface load
febio_spec.Loads.surface_load{1}.ATTR.type='pressure';
febio_spec.Loads.surface_load{1}.ATTR.surface=surfaceName1;
febio_spec.Loads.surface_load{1}.pressure.ATTR.lc=1;
febio_spec.Loads.surface_load{1}.pressure.VAL=appliedPressure;
febio_spec.Loads.surface_load{1}.symmetric_stiffness=1;

%LoadData section
% -> load_controller
febio_spec.LoadData.load_controller{1}.ATTR.id=1;
febio_spec.LoadData.load_controller{1}.ATTR.type='loadcurve';
febio_spec.LoadData.load_controller{1}.interpolate='LINEAR';
febio_spec.LoadData.load_controller{1}.points.point.VAL=[0 0; 1 1];

%Output section
% -> log file
febio_spec.Output.logfile.ATTR.file=febioLogFileName;
febio_spec.Output.logfile.node_data{1}.ATTR.file=febioLogFileName_disp;
febio_spec.Output.logfile.node_data{1}.ATTR.data='ux;uy;uz';
febio_spec.Output.logfile.node_data{1}.ATTR.delim=',';

febio_spec.Output.logfile.node_data{2}.ATTR.file=febioLogFileName_force;
febio_spec.Output.logfile.node_data{2}.ATTR.data='Rx;Ry;Rz';
febio_spec.Output.logfile.node_data{2}.ATTR.delim=',';

%% Quick viewing of the FEBio input file structure
% The |febView| function can be used to view the xml structure in a MATLAB
% figure window.

%%
% |febView(febio_spec); %Viewing the febio file|

%% Exporting the FEBio input file
% Exporting the febio_spec structure to an FEBio input file is done using
% the |febioStruct2xml| function.

febioStruct2xml(febio_spec,febioFebFileName); %Exporting to file and domNode

%% Running the FEBio analysis
% To run the analysis defined by the created FEBio input file the
% |runMonitorFEBio| function is used. The input for this function is a
% structure defining job settings e.g. the FEBio input file name. The
% optional output runFlag informs the user if the analysis was run
% succesfully.

febioAnalysis.run_filename=febioFebFileName; %The input file name
febioAnalysis.run_logname=febioLogFileName; %The name for the log file
febioAnalysis.disp_on=1; %Display information on the command window
febioAnalysis.disp_log_on=1; %Display convergence information in the command window
febioAnalysis.runMode=runMode;

[runFlag]=runMonitorFEBio(febioAnalysis);%START FEBio NOW!!!!!!!!

%% Import FEBio results

if runFlag==1 %i.e. a succesful run

    %%
    % Importing nodal displacements from a log file
    dataStruct=importFEBio_logfile(fullfile(savePath,febioLogFileName_disp),1,1);

    %Access data
    N_disp_mat=dataStruct.data; %Displacement
    timeVec=dataStruct.time; %Time

    %Create deformed coordinate set
    V_DEF=N_disp_mat+repmat(V,[1 1 size(N_disp_mat,3)]);

    %%
    % Plotting the simulated results using |anim8| to visualize and animate
    % deformations

    DN_magnitude=sqrt(sum(N_disp_mat(:,:,end).^2,2)); %Current displacement magnitude

    % Create basic view and store graphics handle to initiate animation
    hf=cFigure; %Open figure
    gtitle([febioFebFileNamePart,': Press play to animate']);
    title('Displacement magnitude [mm]','Interpreter','Latex')
    hp=gpatch(Fb,V_DEF(:,:,end),DN_magnitude,'k',1); %Add graphics object to animate
    hp.Marker='.';
    hp.MarkerSize=markerSize2;
    hp.FaceColor='interp';
    gpatch(Fb,V,0.5*ones(1,3),'k',0.25); %A static graphics object

    axisGeom(gca,fontSize);
    colormap(gjet(250)); colorbar;
    caxis([0 max(DN_magnitude)]);
    axis(axisLim(V_DEF)); %Set axis limits statically
        camlight headlight;

    % Set up animation features
    animStruct.Time=timeVec; %The time vector
    for qt=1:1:size(N_disp_mat,3) %Loop over time increments
        DN_magnitude=sqrt(sum(N_disp_mat(:,:,qt).^2,2)); %Current displacement magnitude

        %Set entries in animation structure
        animStruct.Handles{qt}=[hp hp]; %Handles of objects to animate
        animStruct.Props{qt}={'Vertices','CData'}; %Properties of objects to animate
        animStruct.Set{qt}={V_DEF(:,:,qt),DN_magnitude}; %Property values for to set in order to animate
    end
    anim8(hf,animStruct); %Initiate animation feature
    drawnow;

end

%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>

%%
% _*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 [stiff, diinsy, cols, sysmat] = sb_calc_stiff(vol)

% SB_CALC_STIFF
%
% $Id$

if(~(size(vol.pos,2)==3))
    if(size(vol.pos,1)==3)
        node = vol.pos';
        warning('Dimension of vol.pos should be #nodes x 3!')
    else
        error('vol.pos has wrong dimension!')
    end
else
    node = vol.pos;
end
npnt = size(node,1);
npnt = int32(npnt);

if isfield(vol,'tet')
    if size(vol.tet,1) == 4
        mele = size(vol.tet,1);
        elem = vol.tet;
    elseif size(vol.tet,2) == 4
        mele = size(vol.tet,2);
        elem = vol.tet';
    else
        error('vol.tet has wrong dimensions!')
    end
    elem = [elem; zeros(4,size(elem,2))];
elseif isfield(vol,'hex')
    if size(vol.hex,1) == 8
        mele = size(vol.hex,1);
        elem = vol.hex;
    elseif size(vol.hex,2) == 8
        mele = size(vol.hex,2);
        elem = vol.hex';
    else
        error('vol.hex has wrong dimensions!')
    end
else
    error('Could not find connectivity information!')
end

if min(min(elem(1:mele,:))) == 0
    elem = elem + 1;
    warning('Numbering of nodes in vol.tet/vol.hex must start at 1 (Fortran numbering)!')
elseif min(min(elem(1:mele,:))) < 0
    error('No negative indices for conectivity information allowed!')
end

if isfield(vol,'cond') && isfield(vol,'tissue') && isfield(vol,'tissuelabel')
    if length(vol.tissuelabel) == length(vol.cond)
         if length(vol.tissue) == size(elem,2)
             cond = zeros(size(elem,2),1);
             numlabels = length(vol.tissuelabel);
             for i=1:numlabels
                 cond(vol.tissue == i) = vol.cond(i);
             end
        else
            error('Dimensions of vol.tet or vol.hex and vol.tissue do not fit!');
        end
    else
        error('Dimensions of vol.cond and entries of vol.tissuelabel do not fit!');
    end
end

mele = int32(mele);
elem = int32(elem);

% check whether the nodes have right orientation

if isfield(vol,'tet')
  if ~sb_test_ori(node,elem(1:4,:)')
    error('Elements have wrong orientation, consider exchanging node 3 and 4');
  end
elseif isfield(vol,'hex')
  if ~sb_test_ori(node,elem')
    error('Elements have wrong orientation or are degenerated');
  end
end

try
  [diinsy,cols,sysmat] = calc_stiff_matrix_val(node,elem,cond,mele);
catch err
  if ispc && strcmp(err.identifier,'MATLAB:invalidMEXFile')
    error('Error executing mex-file. Microsoft Visual C++ 2008 Redistributables and Intel Visual Fortran Redistributables are required.')
  else
    rethrow(err)
  end
end
npnt   = double(npnt);
diinsy = double(diinsy);
cols   = double(cols);
rows   = sb_sparse_to_mat(diinsy);
stiff  = sparse(rows,cols,sysmat,npnt,npnt,length(sysmat));
end


function coinWrite(prob,filename,type)
%COINWRITE  Write a Mathematical File From Matlab Values
%
% coinWrite(prob,filename,type) writes the problem prob to the file specified
% by filename and problem type specified by type. If you do not specify a
% file extension it will default to the type specified.
%
%   Available File Types:
%       - MPS  [.mps]
%       - QPS  [.qps]
%       - LP   [.lp]  (Appears to be CPLEX LP version - Simplified)
%
% You may specify a full path to the file, or if you specify a filename
% only, it will be written to the current MATLAB directory.
%
% The routines underneath use COIN-OR utilities for File IO. See
% attached EPL License.

%   Copyright (C) 2011 Jonathan Currie (I2C2)

%Quick Checks
if(~exist('type','var') || isempty(type))
    %See if contained within file name
    dots = strfind(filename,'.');
    if(isempty(dots))
        error('You must supply the file type to this function');
    else %hopefully got a good ext, will check below
        type = filename(dots(end)+1:end);
    end
end
if(~ischar(filename))
    error('Filename must be a char array!');
end

%Problem Checks
if(~isempty(prob.fun) || ~isempty(prob.nlcon))
    error('You cannot write Nonlinear problems using this interface');
end
if(isa(prob.f,'function_handle') || isa(prob.H,'function_handle'))
    error('f and H must be vectors / matrices!');
end
if(~isempty(prob.Q))
    error('You cannot write quadratic constraints using this interface');
end
if(prob.sense == -1)
    error('You cannot explicity write maximization problems using this interface'); %fix up later
end

%Determine file type
switch(lower(type))
    case 'mps'
        filetype = 'mps';
    case 'qps'
        filetype = 'qps';
    case 'lp'
        filetype = 'lp';
    otherwise
        error('Unknown file type %s',type);
end

%Check problem type vs file type
if(isfield(prob,'type') && ~isempty(prob.type))
    switch(lower(prob.type))
        case {'lp','bilp','milp'}
            if(strcmpi(filetype,'qps'))
                error('LP/BILP/MILPs should be written to MPS or LP files');
            end
        case {'qp','miqp'}
            if(~strcmpi(filetype,'qps'))
                error('QP/MIQPs should be written to QPS files');
            end
        otherwise
            error('Problem type %s is not supported by this interface',upper(prob.type));
    end
end

% Make sure we have file extension
if(isempty(strfind(filename,['.' filetype])))
    filename = [filename '.' filetype];
end

% If filename includes absolute path, we can skip which
if(~isempty(strfind(filename,':')))
    p = filename;
else %Locate the full path to the file
    p = [cd filesep filename];
end

%Convert to coin problem
if(~isempty(prob.b) || ~isempty(prob.beq))
    [prob.A,prob.rl,prob.ru] = gen2row(prob.A,prob.b,prob.Aeq,prob.beq);
end
if(isempty(prob.A))
    prob.A = spalloc(0,length(prob.f),0); %error thrown internally if not ok
end

%Ensure sparsity
prob.A = sparse(prob.A);
prob.H = sparse(prob.H);

%Ensure Bounds
if(isempty(prob.lb))
    prob.lb = -Inf(size(prob.f));
end
if(isempty(prob.ub))
    prob.ub = Inf(size(prob.f));
end

%Setup Integer Vars
if(isstruct(prob.int))
    prob.int = prob.int.str;
end
if(isempty(prob.int))
    prob.int = zeros(size(prob.f));
elseif(ischar(prob.int)) %char string
    prob.int = lower(prob.int);
    i = zeros(size(prob.f));
    int = prob.int == 'i';
    bin = prob.int == 'b';
    i(int) = 1;
    i(bin) = 1;
    prob.lb(bin) = 0;
    prob.ub(bin) = 1;
    prob.int = i;
elseif(length(prob.int) ~= length(prob.f) || any(prob.int > 1)) %find indicies (might be wrong though!)
    i = zeros(size(prob.f));
    i(prob.int) = 1;
    prob.int = i;
end
prob.int = int8(prob.int);

%Setup SOS
if(~isempty(prob.sos))
    [r,c] = size(prob.sos.type);
    if(r > c)
        prob.sos_type = str2num(prob.sos.type); %#ok<ST2NM>
    else
        prob.sos_type = str2num(prob.sos.type'); %#ok<ST2NM>
    end
    if(length(prob.sostype) == 1)
        prob.sos_index = {prob.sos.index};
        prob.sos_weight = {prob.sos.weight};
    end
else
    prob.sos_type = [];
    prob.sos_index = [];
    prob.sos_weight = [];
end
%Setup Objc
if(~isempty(prob.objbias) && prob.objbias == 0)
    prob.objbias = 0;
end

%Call coin-or mex
coinW(prob,p,filetype);


%SerialLink.IKINE Inverse manipulator kinematics
%
% Q = R.ikine(T) is the joint coordinates corresponding to the robot
% end-effector pose T which is a homogenenous transform.
%
% Q = R.ikine(T, Q0, OPTIONS) specifies the initial estimate of the joint
% coordinates.
%
% Q = R.ikine(T, Q0, M, OPTIONS) specifies the initial estimate of the joint
% coordinates and a mask matrix.  For the case where the manipulator
% has fewer than 6 DOF the solution space has more dimensions than can
% be spanned by the manipulator joint coordinates.  In this case
% the mask matrix M specifies the Cartesian DOF (in the wrist coordinate
% frame) that will be ignored in reaching a solution.  The mask matrix
% has six elements that correspond to translation in X, Y and Z, and rotation
% about X, Y and Z respectively.  The value should be 0 (for ignore) or 1.
% The number of non-zero elements should equal the number of manipulator DOF.
%
% For example when using a 5 DOF manipulator rotation about the wrist z-axis
% might be unimportant in which case  M = [1 1 1 1 1 0].
%
% In all cases if T is 4x4xM it is taken as a homogeneous transform sequence
% and R.ikine() returns the joint coordinates corresponding to each of the
% transforms in the sequence.  Q is MxN where N is the number of robot joints.
% The initial estimate of Q for each time step is taken as the solution
% from the previous time step.
%
% Options::
%
% Notes::
% - Solution is computed iteratively using the pseudo-inverse of the
%   manipulator Jacobian.
% - The inverse kinematic solution is generally not unique, and
%   depends on the initial guess Q0 (defaults to 0).
% - Such a solution is completely general, though much less efficient
%   than specific inverse kinematic solutions derived symbolically.
% - This approach allows a solution to obtained at a singularity, but
%   the joint angles within the null space are arbitrarily assigned.
%
% See also SerialLink.fkine, tr2delta, SerialLink.jacob0, SerialLink.ikine6s.

% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9)
%
% Copyright (C) 1993-2011, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com

function qt = ikine(robot, tr, varargin)
    %  set default parameters for solution
    opt.ilimit = 100;
    opt.tol = 1e-6;
    opt.alpha = 1;
    opt.plot = false;
    opt.pinv = false;

    [opt,args] = tb_optparse(opt, varargin);

    n = robot.n;

    % robot.ikine(tr, q)
    if length(args) > 0
        q = args{1};
        if isempty(q)
            q = zeros(1, n);
        else
            q = q(:)';
        end
    else
        q = zeros(1, n);
    end

    % robot.ikine(tr, q, m)
    if length(args) > 1
        m = args{2};
        m = m(:);
        if numel(m) ~= 6
            error('Mask matrix should have 6 elements');
        end
        if numel(find(m)) ~= robot.n
            error('Mask matrix must have same number of 1s as robot DOF')
        end
    else
        if n < 6
            error('For a manipulator with fewer than 6DOF a mask matrix argument must be specified');
        end
        m = ones(6, 1);
    end
    % make this a logical array so we can index with it
    m = logical(m);

    npoints = size(tr,3);    % number of points
    qt = zeros(npoints, n);  % preallocate space for results
    tcount = 0;              % total iteration count
    eprev = Inf;

    save.e = Inf;
    save.q = [];

    history = [];
    for i=1:npoints
        T = tr(:,:,i);
        nm = Inf;
        count = 0;

        optim = optimset('Display', 'iter', 'TolX', 0, 'TolFun', opt.tol, 'MaxIter', opt.ilimit);
        optim
        q = fminsearch(@(x) ikinefunc(x, T, robot, m), q, optim);

    end
    qt = q;
end

function E = ikinefunc(q, T, robot, m)
        e = tr2delta(fkine(robot, q'), T);
        E = norm(e(m));
end


classdef DropOut < dagnn.ElementWise
  properties
    rate = 0.5
    frozen = false
  end

  properties (Transient)
    mask
  end

  methods
    function outputs = forward(obj, inputs, params)
      if strcmp(obj.net.mode, 'test')
        outputs = inputs ;
        return ;
      end
      if obj.frozen & ~isempty(obj.mask)
        outputs{1} = vl_nndropout(inputs{1}, 'mask', obj.mask) ;
      else
        [outputs{1}, obj.mask] = vl_nndropout(inputs{1}, 'rate', obj.rate) ;
      end
    end

    function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)
      if strcmp(obj.net.mode, 'test')
        derInputs = derOutputs ;
        derParams = {} ;
        return ;
      end
      derInputs{1} = vl_nndropout(inputs{1}, derOutputs{1}, 'mask', obj.mask) ;
      derParams = {} ;
    end

    % ---------------------------------------------------------------------
    function obj = DropOut(varargin)
      obj.load(varargin{:}) ;
    end

    function obj = reset(obj)
      reset@dagnn.ElementWise(obj) ;
      obj.mask = [] ;
      obj.frozen = false ;
    end
  end
end


function f = round(f)
%ROUND   Pointwise round function of a CHEBTECH.
%   G = FLOOR(F) returns the CHEBTECH G such that G(X) = FLOOR(F(x)) for each x
%   in [-1, 1].
%
%   If F is complex, then the G = ROUND(REAL(F)) + 1i*ROUND(IMAG(F)).
%
%   Note that ROUND() assumes the output G(X) is a constant. If it is not, then
%   garbage is returned with no warning.
%
% See also CEIL, FLOOR, FIX.

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

% Evaluate at the two end points, and an arbitrary interior point:
arbitraryPoint = 0.1273881594;
fx = feval(f, [-1 ; arbitraryPoint ; 1]);
% Take the mean:
meanfx = mean(fx, 1);
% Compute the round:
f.coeffs = round(meanfx);

end


%
% example file for generating a movie from a sequence of viewpoint
%
%% Olivier Salvado, Case Western Reserve University, 16-Sep-04

% construct a 3D scene
[X,Y] = meshgrid(-3:.125:3);
Z = peaks(X,Y);
surfl(X,Y,Z);
axis vis3d
axis off

% create the structure with current view
cam = CamSeqUpdate([]);
% change to view #2
% normally the new view is changed manually using the camera toolbar
campos([20 20 0])
camtarget([1 0 0])
% add the new view to be 5s after view #1
cam = CamSeqUpdate(cam,5);

% change to view #3
% normally the new view is changed manually using the camera toolbar
campos([5 5 50])
camtarget([0 1 1])
% add the new view to be 10s after view #2
cam = CamSeqUpdate(cam,10);

% change to view #4
% normally the new view is changed manually using the camera toolbar
zoom(0.8)
% add the new view to be 5s after view #3
cam = CamSeqUpdate(cam,5);

% generate the sequence
fps = 20;   % 20 frames per second
seq = CamSeqGen(cam,fps);

% play the movie and save the file
M = CamSeqPlay(seq,fps,'GoodLookingMovie.avi');