function [X, nh, hrf] = designMatrix(stim,params,tSeries,reshapeFlag);
%
% Create a design matrix appropriate for the hrf option
% specified in the selected event-related params
% (see eventParamsDefault for more info on the params struct).
%
% Usage:
% [X, nh, hrf] = designMatrix(stim, [params], [tSeries or nFrames], ...
%                                   [reshapeFlag]);
%
%
% If the params.glmHRF option is 0, the design matrix X will
% be appropriate for a deconvolution GLM in which time
% courses relative to trial onset for each condition are
% estimated as part of the GLM. If this flag is positive (1-3),
% a design matrix X will be returned in which there is a single
% predictor function for each condition, using an assumed form
% of the hemodynamic response function (HRF).
%
% Entering the optional tSeries argument is needed if the
% params.glmHRF option is 1 -- estimate HRF from mean
% response to all stim. If entered, the design matrix
% will also be clipped to the # of frames in the tSeries.
% You can enter the # of frames directly as the third
% argument instead of the whole tSeries if you are using
% a different HRF option, but want to clip to the # of frames.
%
% The optional reshape flag, if set to 1 [default 0], will
% cause the otherwise-2D matrix to be set as a 3D matrix
% with the third dimension being different scans. This is
% appropriate for much of the new GLM code.
%
% Also returns nh, the # of time points to use in the
% hemodynamic response window for estimating a GLM.
% (see glm, applyGlm); and hrf, the response function
% used (empty if deconvolving).
%
%
% ras, 04/05
% ras, 08/05 -- imported into mrVista 2.0.
if notDefined('params'),      params = eventParamsDefault;    end
if notDefined('reshapeFlag'), reshapeFlag = 0;                end
if notDefined('tSeries'),     tSeries = [];                   end

tr = params.framePeriod;

% figure out whether an entire tSeries
% was passed, or just a # of frames:
if length(tSeries)==1
    % nFrames is specified, rather than tSeries
    nFrames = tSeries;
    tSeries = [];
elseif ~isempty(tSeries)
   nFrames = size(tSeries,1);
   if nFrames==1
       % need it as a column vector
       tSeries = tSeries';
       nFrames = size(tSeries,1);
   end
end

if isempty(tSeries)
	% default is max frames specified in stim struct
    nFrames = stim.onsetFrames(end);
end

% decide whether we're deconvolving (getting
% estimated time courses for each condition)
% or fitting an HIRF (getting only a single beta value
% for each condition) based on the selected event-related
% hrf parameter. Get a corresponding stimulus matrix:
if params.glmHRF==0
    framesPerScan = max(stim.framesPerRun);

    % make a delta-function matrix for onsets of
    % different conditions:
    s = delta_function_from_parfile(stim.parfiles,tr,framesPerScan);

    % create Toeplitz matrix for estimating deconvolved responses
    % (see papers on 'selective-averaging', e.g. by Randy Buckner
    % or Douglas Greve for the Freesurfer code)
    fw = unique(round(params.timeWindow/tr)); % time window
    hrf = [];
    nConds =  size(s,2);
    [X nh] = eventDeconvolutionMatrix(s,fw);

    % reshape to 2D (will undo later if needed)
    X = reshape(permute(X,[1 3 2]),[size(X,1)*size(X,3) size(X,2)]);
else
    % apply HRF -- first, construct the impulse response function:
    switch params.glmHRF
        case 1,
            % estimate hrf as mean time course to all stim
            if isempty(tSeries)
                errmsg = 'Need tSeries to estimate mean trial response (glmHRF option 1)';
                error(errmsg);
            end

            disp('Estimating mean trial response for GLM')
            tSeries = squeeze(mean(tSeries,2)); % mean across voxels
            anal = eventTimeCourses(tSeries(:),stim,params);
            postStim = find(anal.timeWindow>=0);
            hrf = anal.meanTcs(postStim,anal.condNums>0);
            hrf = hrf(:,params.snrConds);
            if size(hrf,2) > 1
                hrf = nanmeanDims(hrf,2);
            end
            hrf = hrf ./ sum(hrf); % normalize to integral 1
        case 2,  % boynton gamma function
            hrf = 'boynton';
        case 3,  % spm difference-of-gammas
            hrf = 'spm';
        case 4, % dale & buckner HRF
            hrf = 'dale';
    end

    % apply HRF -- return a 2D matrix covering whole time course
    [X, hrf] = eventConvolveHRF(stim,params,hrf,nFrames);

    % we're only returning one predictor per condition: the
    % nh variable should note this:
    nh = 1;
end

if reshapeFlag==1
    % return a 3D matrix w/ runs as the 3rd dimension

    % figure out max # frames per run to
    % use for reshaping
    for run = unique(stim.run)
        ind = find(stim.run==run);
        onsets{run} = stim.onsetFrames(ind);
        framesPerRun(run) = onsets{run}(end)-onsets{run}(1)+1;
    end
    maxFrames = max(framesPerRun);
    nRuns = length(framesPerRun);
    nPredictors = size(X,2);

    % init 3D X matrix
    oldX = X;
    X = zeros(maxFrames,nPredictors,nRuns);

    % reshape (allow for different-length runs)
    for run = 1:nRuns
        rng = onsets{run}(1):onsets{run}(end);
        X(1:framesPerRun(run),:,run) = oldX(rng,:);
    end
end

return


%%%  e8.2_Sim
clear
path('./icon/',path);
%Run the model initialization file icon/init.m
Init;

%Constant value
RAD2DEG = 57.2957795;
DEG2RAD = 0.0174533;
%throttle when UAV hover
THR_HOVER = 0.609;

%% control parameter
%Attitude PID parameters
Kp_PITCH_ANGLE =6.5;
Kp_PITCH_AngleRate = 0.1;
Ki_PITCH_AngleRate = 0.02;
Kd_PITCH_AngleRate = 0.001;
Kp_ROLL_ANGLE =6.5;
Kp_ROLL_AngleRate = 0.1;
Ki_ROLL_AngleRate = 0.02;
Kd_ROLL_AngleRate = 0.001;

Kp_YAW_ANGLE = 3;
Kp_YAW_AngleRate = 0.5;
Ki_YAW_AngleRate = 0.01;
Kd_YAW_AngleRate = 0.00;

%Position PID parameters
Kpxp = 1.0;
Kpyp = 1.0;
Kpzp = 4.0;
Kvxp = 3.0; Kvxi = 0.1; Kvxd = 0.01;
Kvyp = 3.0; Kvyi = 0.1; Kvyd = 0.01;
Kvzp = 0.45; Kvzi = 0.01; Kvzd = 0.005;

Saturation_I_RP_Max = 0.3;
Saturation_I_RP_Min = -0.3;
Saturation_I_Y_Max = 0.2;
Saturation_I_Y_Min = -0.2;
Saturation_I_ah = 3.43;
Saturation_I_az = 5;

%max control angle,default 35deg
MAX_CONTROL_ANGLE_ROLL = 35;
MAX_CONTROL_ANGLE_PITCH  = 35;
%Maximum navigation angle, used in position control to avoid large attitude angles
MAX_CONTROL_ANGLE_NAV_ROLL = 15;
MAX_CONTROL_ANGLE_NAV_PITCH  = 15;
%max control angle rate,rad/s
MAX_CONTROL_ANGLE_RATE_PITCH = 220;
MAX_CONTROL_ANGLE_RATE_ROLL = 220;
MAX_CONTROL_ANGLE_RATE_Y = 200;
%Maximum control speed, m/s
MAX_CONTROL_VELOCITY_XY = 5;
MAX_CONTROL_VELOCITY_Z = 3;
%Throttle amplitude
MAX_MAN_THR = 0.9;
MIN_MAN_THR = 0.05;
%% run simulink model
e8_2_sim


function Offspring = GLMO_SMPSOOperator(Problem, Particle, Pbest, Gbest, numberOfGroups, typeOfGroups)
% -----------------------------------------------------------------------
%  Copyright (C) 2020 Heiner Zille
%
%  This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0
%  International License. (CC BY-NC-SA 4.0). To view a copy of this license,
%  visit http://creativecommons.org/licenses/by-nc-sa/4.0/ or see the
%  pdf-file "License-CC-BY-NC-SA-4.0.pdf" that came with this code.
%
%  You are free to:
%  * Share ? copy and redistribute the material in any medium or format
%  * Adapt ? remix, transform, and build upon the material
%  Under the following terms:
%  * Attribution ? You must give appropriate credit, provide a link to the
%     license, and indicate if changes were made. You may do so in any reasonable
%     manner, but not in any way that suggests the licensor endorses you or your use.
%  * NonCommercial ? You may not use the material for commercial purposes.
%  * ShareAlike ? If you remix, transform, or build upon the material, you must
%    distribute your contributions under the same license as the original.
%  * No additional restrictions ? You may not apply legal terms or technological
%    measures that legally restrict others from doing anything the license permits.
%
%  Author of this Code:
%   Heiner Zille <heiner.zille@ovgu.de> or <heiner.zille@gmail.com>
%
%  This code is based on the following publications:
%
%  1) Heiner Zille
%     "Large-scale Multi-objective Optimisation: New Approaches and a Classification of the State-of-the-Art"
%     PhD Thesis, Otto von Guericke University Magdeburg, 2019
%     http://dx.doi.org/10.25673/32063
%
%  2) Heiner Zille, Hisao Ishibuchi, Sanaz Mostaghim and Yusuke Nojima
%     "Mutation Operators Based on Variable Grouping for Multi-objective Large-scale Optimization"
%     IEEE Symposium Series on Computational Intelligence (SSCI), IEEE, Athens, Greece, December 2016
%     https://ieeexplore.ieee.org/document/7850214
%
%  This file is intended to work with the PlatEMO framework version 2.5.
%  Date of publication of this code: 06.04.2020
%  Last Update of this code: 06.04.2020
%  A newer version of this algorithm may be available. Please contact the author
%  or see http://www.ci.ovgu.de/Research/Codes.html.
%
% The files may have been modified in Feb 2021 by the authors of the Platemo framework to work with the Platemo 3.0 release.
% -----------------------------------------------------------------------
% This file is derived from its original version containied in the PlatEMO
% framework. The original copyright disclaimer can be found below.
% -----------------------------------------------------------------------

% Particle swarm optimization in SMPSO

    %% Parameter setting
    ParticleDec = Particle.decs;
    PbestDec    = Pbest.decs;
    GbestDec    = Gbest.decs;
    [N,D]       = size(ParticleDec);
    ParticleVel = Particle.adds(zeros(N,D));

    %% Particle swarm optimization
    W  = repmat(unifrnd(0.1,0.5,N,1),1,D);
    r1 = repmat(rand(N,1),1,D);
    r2 = repmat(rand(N,1),1,D);
    C1 = repmat(unifrnd(1.5,2.5,N,1),1,D);
    C2 = repmat(unifrnd(1.5,2.5,N,1),1,D);
    OffVel = W.*ParticleVel + C1.*r1.*(PbestDec-ParticleDec) + C2.*r2.*(GbestDec-ParticleDec);
    phi    = max(4,C1+C2);
    OffVel = OffVel.*2./abs(2-phi-sqrt(phi.^2-4*phi));
    delta  = repmat((Problem.upper-Problem.lower)/2,N,1);
    OffVel = max(min(OffVel,delta),-delta);
    OffDec = ParticleDec + OffVel;

    %% Deterministic back
    Lower  = repmat(Problem.lower,N,1);
    Upper  = repmat(Problem.upper,N,1);
    repair = OffDec < Lower | OffDec > Upper;
    OffVel(repair) = 0.001*OffVel(repair);
    OffDec = max(min(OffDec,Upper),Lower);

    %% Polynomial mutation
    disM  = 20;
    Site1 = repmat(rand(N,1)<0.15,1,D);

    [outIndexList,~] = GLMO_createGroups(numberOfGroups,OffDec,D,typeOfGroups); % 3 = random groups
    chosengroups = randi(numberOfGroups,size(outIndexList,1),1);
    Site2 = outIndexList == chosengroups;
    mu    = rand(N,1);
    mu    = repmat(mu,1,D);

    temp  = Site1 & Site2 & mu<=0.5;
    OffDec(temp) = OffDec(temp)+(Upper(temp)-Lower(temp)).*((2.*mu(temp)+(1-2.*mu(temp)).*...
                   (1-(OffDec(temp)-Lower(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1))-1);
    temp  = Site1 & Site2 & mu>0.5;
    OffDec(temp) = OffDec(temp)+(Upper(temp)-Lower(temp)).*(1-(2.*(1-mu(temp))+2.*(mu(temp)-0.5).*...
                   (1-(Upper(temp)-OffDec(temp))./(Upper(temp)-Lower(temp))).^(disM+1)).^(1/(disM+1)));
    Offspring = Problem.Evaluation(OffDec,OffVel);
end


function [g1, g2] = lfmXrbfKernGradient(lfmKern, rbfKern, t1, t2, covGrad, meanVector)

% LFMXRBFKERNGRADIENT Compute gradient between the LFM and RBF kernels.
% FORMAT
% DESC computes the gradient of an objective function with respect
% to cross kernel terms between LFM and RBF kernels for
% the multiple output kernel.
% ARG lfmKern : the kernel structure associated with the LFM
% kernel.
% ARG rbfKern : the kernel structure associated with the RBF
% kernel.
% ARG t : inputs for which kernel is to be computed.
% RETURN g1 : gradient of objective function with respect to kernel
% parameters of LFM kernel.
% RETURN g2 : gradient of objective function with respect to kernel
% parameters of RBF kernel.
%
% FORMAT
% DESC computes the gradient of an objective function with respect
% to cross kernel terms between LFM and RBF kernels for
% the multiple output kernel.
% ARG lfmKern : the kernel structure associated with the LFM
% kernel.
% ARG rbfKern : the kernel structure associated with the RBF
% kernel.
% ARG t1 : row inputs for which kernel is to be computed.
% ARG t2 : column inputs for which kernel is to be computed.
% RETURN g1 : gradient of objective function with respect to kernel
% parameters of LFM kernel.
% RETURN g2 : gradient of objective function with respect to kernel
% parameters of RBF kernel.
%
% FORMAT
% DESC computes the gradient of an objective function with respect
% to cross kernel terms between LFM and RBF kernels for
% the multiple output kernel.
% ARG lfmKern : the kernel structure associated with the LFM
% kernel.
% ARG rbfKern : the kernel structure associated with the RBF
% kernel.
% ARG t1 : row inputs for which kernel is to be computed.
% ARG t2 : column inputs for which kernel is to be computed.
% ARG meanVec : precomputed factor that is used for the switching dynamical
% latent force model.
% RETURN g1 : gradient of objective function with respect to kernel
% parameters of LFM kernel.
% RETURN g2 : gradient of objective function with respect to kernel
% parameters of RBF kernel.
%
% SEEALSO : multiKernParamInit, multiKernCompute, lfmKernParamInit, rbfKernParamInit
%
% COPYRIGHT : David Luengo, 2007, 2008
%
% MODIFICATIONS : Neil D. Lawrence, 2007
%
% MODIFICATIONS : Mauricio A. Alvarez, 2008, 2010

% KERN

subComponent = false; % This is just a flag that indicates if this kernel is part of a bigger kernel (SDLFM)

if nargin == 4
    covGrad = t2;
    t2 = t1;
elseif nargin == 6
    subComponent = true;
    if numel(meanVector)>1
        if size(meanVector,1) == 1,
            if size(meanVector, 2)~=size(covGrad, 2)
                error('The dimensions of meanVector don''t correspond to the dimensions of covGrad')
            end
        else
            if size((meanVector'), 2)~=size(covGrad,2)
                error('The dimensions of meanVector don''t correspond to the dimensions of covGrad')
            end
        end
    else
        if numel(t1)==1 && numel(t2)>1
            % matGrad will be row vector and so should be covGrad
            dimcovGrad = length(covGrad);
            covGrad = reshape(covGrad, [1 dimcovGrad]);
        elseif numel(t1)>1 && numel(t2)==1
            % matGrad will be column vector and sp should be covGrad
            dimcovGrad = length(covGrad);
            covGrad = reshape(covGrad, [dimcovGrad 1]);
        end
    end
end

if size(t1, 2) > 1 || size(t2, 2) > 1
    error('Input can only have one column');
end
if lfmKern.inverseWidth ~= rbfKern.inverseWidth
    error('Kernels cannot be cross combined if they have different inverse widths.')
end

if lfmKern.isNormalised ~= rbfKern.isNormalised
  error('Kernels cannot be cross combined if they have different normalization settings.')
end

m = lfmKern.mass;
D = lfmKern.spring;
C = lfmKern.damper;
S = lfmKern.sensitivity;

alpha = C/(2*m);
omega = sqrt(D/m-alpha^2);

sigma2 = 2/lfmKern.inverseWidth;
sigma = sqrt(sigma2);

if isreal(omega)
    gamma = alpha + j*omega;
    ComputeUpsilon1 = lfmComputeUpsilonMatrix(gamma,sigma2,t1, t2);
    if lfmKern.isNormalised
        K0 = S/(2*sqrt(2)*m*omega);
    else
        K0 = sigma*sqrt(pi)*S/(2*m*omega);
    end
else
    gamma1 = alpha + j*omega;
    gamma2 = alpha - j*omega;
    ComputeUpsilon1 = lfmComputeUpsilonMatrix(gamma2,sigma2,t1, t2);
    ComputeUpsilon2 = lfmComputeUpsilonMatrix(gamma1,sigma2,t1, t2);
    if lfmKern.isNormalised
        K0 = (S/(j*4*sqrt(2)*m*omega));
    else
        K0 = sigma*sqrt(pi)*S/(j*4*m*omega);
    end
end

g1 = zeros(1,5);

% Gradient with respect to m, C and D

for ind = 1:3 % Parameter (m, D or C)
    switch ind
        case 1  % Gradient wrt m
            gradThetaM = 1;
            gradThetaAlpha = -C/(2*(m^2));
            gradThetaOmega = (C^2-2*m*D)/(2*(m^2)*sqrt(4*m*D-C^2));
        case 2  % Gradient wrt D
            gradThetaM = 0;
            gradThetaAlpha = 0;
            gradThetaOmega = 1/sqrt(4*m*D-C^2);
        case 3  % Gradient wrt C
            gradThetaM = 0;
            gradThetaAlpha = 1/(2*m);
            gradThetaOmega = -C/(2*m*sqrt(4*m*D-C^2));
    end

    % Gradient evaluation

    if isreal(omega)
        gamma = alpha + j*omega;
        gradThetaGamma = gradThetaAlpha + j*gradThetaOmega;
        matGrad = -K0*imag(lfmGradientUpsilonMatrix(gamma,sigma2,t1, t2)*gradThetaGamma ...
            - (gradThetaM/m + gradThetaOmega/omega) ...
            * ComputeUpsilon1);
    else
        gamma1 = alpha + j*omega;
        gamma2 = alpha - j*omega;
        gradThetaGamma1 = gradThetaAlpha + j*gradThetaOmega;
        gradThetaGamma2 = gradThetaAlpha - j*gradThetaOmega;
        matGrad = K0*(lfmGradientUpsilonMatrix(gamma2,sigma2, t1, t2)*gradThetaGamma2 ...
            -  lfmGradientUpsilonMatrix(gamma1,sigma2, t1, t2)*gradThetaGamma1 ...
            - (gradThetaM/lfmKern.mass + gradThetaOmega/omega) ...
            * (ComputeUpsilon1 - ComputeUpsilon2));

    end
    if subComponent
        if size(meanVector,1) ==1,
            matGrad = matGrad*meanVector;
        else
            matGrad = (meanVector*matGrad).';
        end
    end
    g1(ind) = sum(sum(matGrad.*covGrad));
end

% Gradient with respect to sigma

if isreal(omega)
    gamma = alpha + j*omega;
    if lfmKern.isNormalised
        matGrad = -K0*imag(lfmGradientSigmaUpsilonMatrix(gamma,sigma2,t1, t2));
    else
        matGrad = -(sqrt(pi)*S/(2*m*omega)) ...
            * imag(ComputeUpsilon1 ...
            + sigma*lfmGradientSigmaUpsilonMatrix(gamma,sigma2,t1, t2));
    end
else
    gamma1 = alpha + j*omega;
    gamma2 = alpha - j*omega;
    if lfmKern.isNormalised
        matGrad = K0*(lfmGradientSigmaUpsilonMatrix(gamma2,sigma2,t1,t2) ...
            - lfmGradientSigmaUpsilonMatrix(gamma1,sigma2,t1,t2));
    else
        matGrad = (sqrt(pi)*S/(j*4*m*omega)) ...
            *(ComputeUpsilon1 - ComputeUpsilon2 ...
            + sigma*(lfmGradientSigmaUpsilonMatrix(gamma2,sigma2,t1,t2) ...
            - lfmGradientSigmaUpsilonMatrix(gamma1,sigma2,t1,t2)));
    end
end;

if subComponent
    if size(meanVector,1) ==1,
        matGrad = matGrad*meanVector;
    else
        matGrad = (meanVector*matGrad).';
    end
end

g1(4) = sum(sum(matGrad.*covGrad))*(-(sigma^3)/4); % temporarly introduced by MA
g2(1) = g1(4);

% Gradient with respect to S

if isreal(omega)
    if lfmKern.isNormalised
        matGrad = -(1/(2*sqrt(2)*m*omega))* imag(ComputeUpsilon1);
    else
        matGrad = -(sqrt(pi)*sigma/(2*m*omega))* imag(ComputeUpsilon1);
    end
else
    if lfmKern.isNormalised
        matGrad = (1/(j*4*sqrt(2)*m*omega))*(ComputeUpsilon1 - ComputeUpsilon2);
    else
        matGrad = (sqrt(pi)*sigma/(j*4*m*omega))*(ComputeUpsilon1 - ComputeUpsilon2);
    end
end;

if subComponent
    if size(meanVector,1) ==1,
        matGrad = matGrad*meanVector;
    else
        matGrad = (meanVector*matGrad).';
    end
end

g1(5) = sum(sum(matGrad.*covGrad));
g1 = real(g1);
% Gradient with respect to the "variance" of the RBF
g2(1) = 0; % Otherwise is counted twice, temporarly changed by MA
g2(2) = 0;


function fem2d_pack_test11 ( )

%*****************************************************************************80
%
%% TEST11 tests GRID_TEST.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST11\n' );
  fprintf ( 1, '  Test the grid routines.\n' );

  grid_test ( 'Q4' );

  grid_test ( 'Q8' );

  grid_test ( 'Q9' );

  grid_test ( 'Q12' );

  grid_test ( 'Q16' );

  grid_test ( 'QL' );

  grid_test ( 'T3' );

  grid_test ( 'T4' );

  grid_test ( 'T6' );

  grid_test ( 'T10' );

  return
end


% COMP_UGRID_UV
% Compare depth-averaged current from 2 unstructured grid
% models with UGRID conventions (http://bit.ly/cf_ugrid), allowing
% comparison with no model specific code.  This code makes a movie
% if there is more than one time step specified

comp_titl='Comparison of 2D No-Wave runs for Hurricane Ike';

titl{1}='ADCIRC';
uris{1}='http://testbedapps.sura.org/thredds/dodsC/in/und/adcirc/ike/ultralite/lr/vardrag/nowave/3d'
%uris{1}='http://testbedapps.sura.org/threddsdev/dodsC/inundation/ADCIRC/rita/2Dvrwoww'
uname{1}='u-vel';
vname{1}='v-vel';
tname{1}='time';

titl{2}='FVCOM';
uris{2}='http://testbedapps.sura.org/thredds/dodsC/inundation/FVCOM/ike/3Dvrwww';
%uris{2}='http://testbedapps.sura.org/threddsdev/dodsC/inundation/FVCOM/rita/2Dvrwoww';
uname{2}='ua';
vname{2}='va';
tname{2}='time';

% for just one plot, define one time:
jdi=datenum([2008 9 13 03 0 0]); %Ike
%jdi=datenum([2005 9 24 06 0 0]); %Rita

% for a movie define more than one time
%jdi=datenum([2008 9 12 21 0 0]):3/24:datenum([2008 9 13 15 0 0]);
if length(jdi)>1
  movie_name='ike';
end

% scale factor for arrows
vfac=0.03;
% bounding box for figures
ax=[-95.2  -94.4   28.8   29.9]
% color range for figures
cax=[0 3];

if length(jdi)>1
  vidobj=VideoWriter(movie_name,'Uncompressed AVI');
  vidobj.FrameRate = 1;
  open(vidobj);
end

% There is nothing model specific below this point

%  loop through each model to read the grid information
for i=1:length(uris)
  tic
  %initialize dataset object
  nc{i}=ncgeodataset(uris{i});
  %get geovariable object
  uvar{i}=nc{i}.geovariable(uname{i});
  vvar{i}=nc{i}.geovariable(vname{i});
  jd{i}=nc{i}.time(tname{i});
  % get mesh variable name (inference array)
  gvar_name{i}=uvar{i}.attribute('mesh');
  if isempty(gvar_name{i}),
    gtype{i}='structured';
  else
    gtype{i}='unstructured';
  end
  switch gtype{i}
    case 'structured'
      g=uvar{i}.grid(itime,:,:);
      lon{i}=g.lon;
      lat{i}=g.lat;
    case 'unstructured'
      gridvar=nc{i}.variable(gvar_name{i});
      a=textscan(gridvar.attribute('node_coordinates'),'%s %s');
      lon{i}=nc{i}{a{1}}(:);
      lat{i}=nc{i}{a{2}}(:);
      location{i}=uvar{i}.attribute('location');
      % find connectivity array variable from mesh variable
      trivar_name=gridvar.attribute('face_node_connectivity');
      % get connnectivity array data
      tri{i}=nc{i}{trivar_name}(:);
      [m,n]=size(tri{i});
      % check/fix orientation of connectivity array
      if m==3,
        tri{i}=tri{i}.';
      elseif n~=3
        disp('Error:Currently handling triangles only');return
      end
  end
end
% loop through time, reading data at each step from all models
fig=figure(1);
clf;set(gcf,'renderer','zbuffer');set(gcf,'color','white');
for k=1:length(jdi);
  for i=1:length(uris)
    itime=date_index(jd{i},jdi(k));
    subplot(1,2,i);cla
    switch gtype{i}
      case 'structured'
        u=double(squeeze(uvar{i}.data(itime,:,:)));
        v=double(squeeze(vvar{i}.data(itime,:,:)));
        U=complex(u,v);
        pcolorjw(lon{i},lat{i},abs(U));shading interp;colorbar;...
          axis(ax);caxis(cax);
        arrows(lon{i},lat{i},U,0.03,'black');
      case 'unstructured'
        % read data at specified time step for all nodes
        u=double(squeeze(uvar{i}.data(itime,:)));
        v=double(squeeze(vvar{i}.data(itime,:)));
        U=complex(u,v);
        U(U==0)=nan;
        igood=isfinite(U);
        % handle case of 'face' location (e.g. FVCOM)
        if strmatch('face',location{i}),
          % calculate u,v lon,lat positions (faster than reading lonc,latc)
          lon_vel=1/3*(lon{i}(tri{i}(:,1))+lon{i}(tri{i}(:,2))+lon{i}(tri{i}(:,3)));
          lat_vel=1/3*(lat{i}(tri{i}(:,1))+lat{i}(tri{i}(:,2))+lat{i}(tri{i}(:,3)));
          lonp=lon{i}(tri{i});
          latp=lat{i}(tri{i});
          patch(lonp.',latp.',abs(U));view(2);shading flat % shading 'interp' doesn't work with patch
          arrows(lon_vel(igood),lat_vel(igood),U(igood),vfac,'black');
        else
          trisurf(tri{i},lon{i},lat{i},0*lon{i}-5,abs(U));view(2);shading interp;
          arrows(lon{i}(igood),lat{i}(igood),U(igood),vfac,'black');
        end
        colorbar;axis(ax);caxis(cax);...
          fac=cos(mean(lat{1}(:))*pi/180);...
          title(sprintf('%s %s (%s): %sZ',titl{i},uname{i},...
          uvar{i}.attribute('units'),datestr(jd{i}(itime),'yyyy-mm-dd HH:MM')));...
          set (gca, 'DataAspectRatio', [1 fac 1] );...
          set (gca, 'tickdir','out');
        toc

    end
  end
  if(length(jdi)>1)
    F=getframe(fig);
    writeVideo(vidobj,F);
  end
end
if(length(jdi)>1)
  close(vidobj)
end


function [varargout]=minesweeper(varargin)
%initialization
clc
clear all
close all
% playing a background music
% % [bk,fs]=wavread('bk2.wav',1000);
% % wavplay(bk,fs,'async');
%declaration and initializing variables
h=struct;
h.row=10;
h.column=10;
h.iposx=100;h.iposy=100;
h.boxdim=[35 35];
h.gap=[0.5 0.5];
h.mine=imread(strcat('mine','.png'));
% initializing gui
h.main=figure('name','Suleman''s minesweeper','NumberTitle','off','Position',[h.iposx,h.iposy,(h.row+4)*h.boxdim(1),(h.column+4)*h.boxdim(2)]);
h.newgame=uicontrol(h.main,'style','pushbutton','position',[0,h.boxdim(2)*(h.column+4)-35,100,35],'string','New Game','callback','minesweeper','tooltipstring','Newgame');
h.close=uicontrol(h.main,'style','pushbutton','position',[h.boxdim(1)*(h.row+4)-100,0,100,35],'string','Close','callback','close gcbf');
h.popup=uicontrol(h.main,'style','popup','position',[h.boxdim(1)*(h.row+4)-150,h.boxdim(2)*(h.column+4)-20,100,20],...
    'tooltipstring','Go for Expert','string','Difficulty|Beginner|Intermediate|Expert','interruptible','off');
for x=1:h.row+2
    for y=1:h.column+2
        h.box(y,x)=uicontrol(h.main,'style','pushbutton','FontWeight','bold','foregroundcolor','b','fontsize',12,...
            'position',[h.boxdim(1)*(x),h.boxdim(2)*(h.column+3-y),h.boxdim(1)-h.gap(1),h.boxdim(2)-h.gap(2)]);
        if x==1 || y==1 || x==h.row+2 || y==h.column+2
            set(h.box(y,x),'visible','off');
        end
    end
end
% initializing background work like bomb placement
h.difficulty=0.65;
bomb=int8(h.difficulty*rand(h.row+2,h.column+2));
bomb(:,1)=zeros(h.row+2,1);bomb(:,h.column+2)=zeros(h.row+2,1);bomb(1,:)=zeros(1,h.column+2);bomb(h.row+2,:)=zeros(1,h.column+2);
h.game=bomb*9;
for x=2:h.row+1
    for y=2:h.column+1
        n=0;
        if bomb(x,y)==0
            if bomb(x-1,y-1)==1
                n=n+1;
            end
            if bomb(x-1,y)==1
                n=n+1;
            end
            if bomb(x-1,y+1)==1
                n=n+1;
            end
            if bomb(x,y-1)==1
                n=n+1;
            end
            if bomb(x,y+1)==1
                n=n+1;
            end
            if bomb(x+1,y-1)==1
                n=n+1;
            end
            if bomb(x+1,y)==1
                n=n+1;
            end
            if bomb(x+1,y+1)==1
                n=n+1;
            end
        h.game(x,y)=n;
        end
    end
end
h.game=flipud(h.game');
% disp(h.game);
% defining callbacks
set(h.popup,'callback',{@difficultylevel,h});
for ii=1:h.row+2
    for jj=1:h.column+2
        set(h.box(ii,jj),'callback',{'button',h},'buttondownfcn',{'mark',h});
    end
end
end


% teststat - EEGLAB statistical testing function
%
% Statistics are critical for inference testing in Science. It is thus
% primordial to make sure than all the statistics implemented are
% robust and at least bug free. Statistical function using complex
% formulas are inherently prone to bugs. EEGLAB functions are all the
% more prone to bugs given that they only use complex Matlab code to
% avoid loops and speed up computation.
%
% This test function does not garantee that EEGLAB statistical functions
% are bug free. It does assure though that bugs are unlikely and minor
% if they are present.
%
% This function test 3 things.
%
% * First, it checks that for vector inputs the EEGLAB functions return
%   the same output as other reference functions from the Matlab statistical
%   toolbox or from other packages tested against the SPSS software for
%   repeated measure ANOVA (rm_anova2 function).
%
% * Second, it checks that array inputs with different number of dimensions
%   (from 1 to 3) the EEGLAB function return the same output.
%
% * Third, it checks that the permutation and bootstrap methods shuffle
%   the data properly by running multiple tests.

function teststat;

% testing paired t-test
% ---------------------
a = { rand(1,10) rand(1,10)+0.5 };
[t df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[h p tmp stats] = ttest(a{1}, a{2});
fprintf('Statistics paired statcond    t-value %2.2f df=%d p=%0.4f\n', t, df, pvals);
fprintf('Statistics paired ttest func. t-value %2.2f df=%d p=%0.4f\n', stats.tstat, stats.df, p);
assertsame([t stats.tstat], [df stats.df], [pvals p]);
disp('--------------------');

% testing unpaired t-test
% -----------------------
[t df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[h p tmp stats] = ttest2(a{1}, a{2});
fprintf('Statistics paired statcond     t-value %2.2f df=%d p=%0.4f\n', t, df, pvals);
fprintf('Statistics paired ttest2 func. t-value %2.2f df=%d p=%0.4f\n', stats.tstat, stats.df, p);
assertsame([t stats.tstat], [df stats.df], [pvals p]);
disp('--------------------');

% testing paired 1-way ANOVA
% --------------------------
a = { rand(1,10) rand(1,10) rand(1,10)+0.2; rand(1,10) rand(1,10)+0.2 rand(1,10) };
[F df pvals surog] = statcond(a(1,:), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2;
stats = rm_anova2(  [ a{1,1}';a{1,2}';a{1,3}'], repmat([1:10]', [3 1]), [o;o;o], [z;o;t], {'a','b'});
fprintf('Statistics 1-way paired statcond        F-value %2.2f df1=%d df2=%d p=%0.4f\n', F, df(1), df(2), pvals);
fprintf('Statistics 1-way paired rm_avova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{3,5}, stats{3,3}, stats{6,3}, stats{3,6});
assertsame([F stats{3,5}], [df(1) stats{3,3}], [df(2) stats{6,3}], [pvals stats{3,6}]);
disp('--------------------');

% testing paired 2-way ANOVA
% --------------------------
[F df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2;
stats = rm_anova2(  [ a{1,1}';a{1,2}';a{1,3}';a{2,1}';a{2,2}';a{2,3}' ], ...
            repmat([1:10]', [6 1]), [o;o;o;z;z;z], [z;o;t;z;o;t], {'a','b'});
fprintf('Statistics 2-way paired statcond        F-value %2.2f df1=%d df2=%d p=%0.4f\n', F{3}, df{3}(1), df{3}(2), pvals{3});
fprintf('Statistics 2-way paired rm_avova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{4,5}, stats{4,3}, stats{7,3}, stats{4,6});
assertsame([F{3} stats{4,5}], [df{3}(1) stats{4,3}], [df{3}(2) stats{7,3}], [pvals{3} stats{4,6}]);
disp('--------------------');

% testing 1-way unpaired ANOVA
% ----------------------------
[F df pvals surog] = statcond(a(1,:), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[p stats] = anova1( [ a{1,1}' a{1,2}' a{1,3}' ],{}, 'off');
fprintf('Statistics 1-way unpaired statcond     F-value %2.2f df1=%d df2=%d p=%0.4f\n', F, df(1), df(2), pvals);
fprintf('Statistics 1-way unpaired anova1 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{2,5}, stats{2,3}, stats{3,3}, stats{2,6});
assertsame([F stats{2,5}], [df(1) stats{2,3}], [df(2) stats{3,3}], [pvals stats{2,6}]);
disp('--------------------');

% testing 2-way unpaired ANOVA
% ----------------------------
[F df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[p stats] = anova2( [ a{1,1}' a{1,2}' a{1,3}'; a{2,1}' a{2,2}' a{2,3}' ], 10, 'off');
fprintf('Statistics 2-way paired statcond       F-value %2.2f df1=%d df2=%d p=%0.4f\n', F{3}, df{3}(1), df{3}(2), pvals{3});
fprintf('Statistics 1-way unpaired anova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{4,5}, stats{4,3}, stats{5,3}, stats{4,6});
assertsame([F{3} stats{4,5}], [df{3}(1) stats{4,3}], [df{3}(2) stats{5,3}], [pvals{3} stats{4,6}]);
disp('--------------------');

% testing different dimensions in statcond
% ----------------------------------------
a = { rand(1,10)      rand(1,10)+0.5      rand(1,10)};
b = { rand(10,10)     rand(10,10)+0.5     rand(10,10)};     b{1}(4,:)     = a{1}; b{2}(4,:)     = a{2}; b{3}(4,:)     = a{3};
c = { rand(5,10,10)   rand(5,10,10)+0.5   rand(5,10,10)};   c{1}(2,4,:)   = a{1}; c{2}(2,4,:)   = a{2}; c{3}(2,4,:)   = a{3};
d = { rand(2,5,10,10) rand(2,5,10,10)+0.5 rand(2,5,10,10)}; d{1}(1,2,4,:) = a{1}; d{2}(1,2,4,:) = a{2}; d{3}(1,2,4,:) = a{3};
[t1 df1 pvals1] = statcond(a(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t2 df2 pvals2] = statcond(b(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t3 df3 pvals3] = statcond(c(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t4 df4 pvals4] = statcond(d(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
fprintf('Statistics paired statcond t-test dim1 t-value %2.2f df=%d p=%0.4f\n', t1, df1, pvals1);
fprintf('Statistics paired statcond t-test dim2 t-value %2.2f df=%d p=%0.4f\n', t2(4), df2, pvals2(4));
fprintf('Statistics paired statcond t-test dim3 t-value %2.2f df=%d p=%0.4f\n', t3(2,4), df3, pvals3(2,4));
fprintf('Statistics paired statcond t-test dim4 t-value %2.2f df=%d p=%0.4f\n', t4(1,2,4), df4, pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t2 df2 pvals2] = statcond(b(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t3 df3 pvals3] = statcond(c(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t4 df4 pvals4] = statcond(d(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
fprintf('Statistics unpaired statcond t-test dim1 t-value %2.2f df=%d p=%0.4f\n', t1, df1, pvals1);
fprintf('Statistics unpaired statcond t-test dim2 t-value %2.2f df=%d p=%0.4f\n', t2(4), df2, pvals2(4));
fprintf('Statistics unpaired statcond t-test dim3 t-value %2.2f df=%d p=%0.4f\n', t3(2,4), df3, pvals3(2,4));
fprintf('Statistics unpaired statcond t-test dim4 t-value %2.2f df=%d p=%0.4f\n', t4(1,2,4), df4, pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
fprintf('Statistics paired statcond anova 1-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1, df1(1), df1(2), pvals1);
fprintf('Statistics paired statcond anova 1-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2(4), df2(1), df2(2), pvals2(4));
fprintf('Statistics paired statcond anova 1-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3(2,4), df3(1), df3(2), pvals3(2,4));
fprintf('Statistics paired statcond anova 1-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4(1,2,4), df4(1), df4(2), pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
fprintf('Statistics unpaired statcond anova 1-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1, df1(1), df1(2), pvals1);
fprintf('Statistics unpaired statcond anova 1-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2(4), df2(1), df2(2), pvals2(4));
fprintf('Statistics unpaired statcond anova 1-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3(2,4), df3(1), df3(2), pvals3(2,4));
fprintf('Statistics unpaired statcond anova 1-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4(1,2,4), df4(1), df4(2), pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
a(2,:) = a; a{1} = a{1}/2;
b(2,:) = b; b{1} = b{1}/2;
c(2,:) = c; c{1} = c{1}/2;
d(2,:) = d; d{1} = d{1}/2;
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
fprintf('Statistics paired statcond anova 2-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1{3}, df1{3}(1), df1{3}(2), pvals1{3});
fprintf('Statistics paired statcond anova 2-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2{3}(4), df2{3}(1), df2{3}(2), pvals2{3}(4));
fprintf('Statistics paired statcond anova 2-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3{3}(2,4), df3{3}(1), df3{3}(2), pvals3{3}(2,4));
fprintf('Statistics paired statcond anova 2-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4{3}(1,2,4), df4{3}(1), df4{3}(2), pvals4{3}(1,2,4));
assertsame([t1{3} t2{3}(4) t3{3}(2,4) t4{3}(1,2,4)], [df1{3}(1) df2{3}(1) df3{3}(1) df4{3}(1)], [df1{3}(2) df2{3}(2) df3{3}(2) df4{3}(2)], [pvals1{3} pvals2{3}(4) pvals3{3}(2,4) pvals4{3}(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
fprintf('Statistics unpaired statcond anova 2-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1{3}, df1{3}(1), df1{3}(2), pvals1{3});
fprintf('Statistics unpaired statcond anova 2-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2{3}(4), df2{3}(1), df2{3}(2), pvals2{3}(4));
fprintf('Statistics unpaired statcond anova 2-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3{3}(2,4), df3{3}(1), df3{3}(2), pvals3{3}(2,4));
fprintf('Statistics unpaired statcond anova 2-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4{3}(1,2,4), df4{3}(1), df4{3}(2), pvals4{3}(1,2,4));
assertsame([t1{3} t2{3}(4) t3{3}(2,4) t4{3}(1,2,4)], [df1{3}(1) df2{3}(1) df3{3}(1) df4{3}(1)], [df1{3}(2) df2{3}(2) df3{3}(2) df4{3}(2)], [pvals1{3} pvals2{3}(4) pvals3{3}(2,4) pvals4{3}(1,2,4)]);
disp('--------------------');

% testing shuffling and permutation for bootstrap
% -----------------------------------------------
clear a;
m1 = [1:10];
m2 = [1:10]+100;
m3 = [1:10]+1000;
a{1} = { m1 m2 };
a{2} = { m1 m2 m3 };
a{3} = { [ zeros(9,10); m1] [ zeros(9,10); m2] };
a{4} = { [ zeros(9,10); m1] [ zeros(9,10); m2] [ zeros(9,10); m3] };
tmpa = zeros(9,8,10); tmpa(end,end,:) = m1;
tmpb = zeros(9,8,10); tmpb(end,end,:) = m2;
tmpc = zeros(9,8,10); tmpc(end,end,:) = m3;
a{5} = { tmpa tmpb };
a{6} = { tmpa tmpb tmpc };

for method = 1:2
    if method == 2, opt = {'arraycomp', 'off'}; else opt = {}; end;
    for dim = 1:length(a)
        [sa1] = statcond(a{dim}, 'mode', 'bootstrap', 'verbose', 'off', 'paired', 'on',  'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
        [sa2] = statcond(a{dim}, 'mode', 'perm'     , 'verbose', 'off', 'paired', 'on',  'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
        [sa3] = statcond(a{dim}, 'mode', 'bootstrap', 'verbose', 'off', 'paired', 'off', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
        [sa4] = statcond(a{dim}, 'mode', 'perm'     , 'verbose', 'off', 'paired', 'off', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10);

        % select data
        nd = ndims(sa1{1});
        if nd == 2 && size(sa1{1},2) > 1
            for t=1:length(sa1),
                sa1{t} = sa1{t}(end,:);
                sa2{t} = sa2{t}(end,:);
                sa3{t} = sa3{t}(end,:);
                sa4{t} = sa4{t}(end,:);
            end;
        elseif nd == 3
            for t=1:length(sa1),
                sa1{t} = squeeze(sa1{t}(end,end,:));
                sa2{t} = squeeze(sa2{t}(end,end,:));
                sa3{t} = squeeze(sa3{t}(end,end,:));
                sa4{t} = squeeze(sa4{t}(end,end,:));
            end;
        elseif nd == 4
            for t=1:length(sa1),
                sa1{t} = squeeze(sa1{t}(end,end,end,:));
                sa2{t} = squeeze(sa2{t}(end,end,end,:));
                sa3{t} = squeeze(sa3{t}(end,end,end,:));
                sa4{t} = squeeze(sa4{t}(end,end,end,:));
            end;
        end;

        % for paired bootstrap, we make sure that the resampling has only shuffled between conditions
        % for instance [101 2 1003 104 ...] is an acceptable sequence
        if all(rem(sa1{1}(:)',10) == [1:9 0]) && all(rem(sa1{2}(:)',10) == [1:9 0])
            fprintf('Bootstrap paired dim%d resampling method %d Pass\n', dim, method);
        else  error('Bootstrap paired resampling Error');
        end;
        % for paired permutation, in addition, we make sure that the sum accross condition is constant
        % which is not true for bootstrap
        msa = meansa(sa2); msa = msa(:)-msa(1);
        if all(rem(sa1{1}(:)',10) == [1:9 0]) && all(rem(sa1{2}(:)',10) == [1:9 0]) && ...
            all(round(msa) == [0:9]') && length(unique(sa2{1})) == 10 && length(unique(sa2{2})) == 10
            fprintf('Permutation paired dim%d resampling method %d Pass\n', dim, method);
        else  error('Permutation paired resampling Error');
        end;
        % for unpaired bootstrap, only make sure there are enough unique
        % values
        if length(unique(sa3{1})) > 3 && length(unique(sa3{2})) > 3
             fprintf('Bootstrap unpaired dim%d reampling method %d Pass\n', dim, method);
        else   error('Bootstrap unpaired reampling Error');
        end;
        % for unpaired permutation, the number of unique values must be 10
        % and the sum must be constant (not true for bootstrap)
        if length(unique(sa4{1})) == 10 && length(unique(sa4{2})) == 10 && ( floor(mean(meansa(sa4))) == 55 || floor(mean(meansa(sa4))) == 372 )
             fprintf('Permutation unpaired dim%d reampling method %d Pass\n', dim, method);
        else   error('Permutation unpaired reampling Error');
        end;

        disp('------------------------');
    end;
end;

% function to check
function assertsame(varargin)

for ind = 1:length(varargin)
    if length(varargin{1}) > 2
        for tmpi = 1:length(varargin{1})-1
            assertsame(varargin{1}(tmpi:tmpi+1));
        end;
        return;
    else
        if (varargin{ind}(1)-varargin{ind}(2)) > abs(mean(varargin{ind}))*0.01
            error('Test failed');
        end;
    end;
end;
disp('Test pass');

function [meanmat] = meansa(mat)

meanmat = zeros(size(mat{1}));
for index = 1:length(mat)
    meanmat = meanmat+mat{index}/length(mat);
end;

function stats = rm_anova2(Y,S,F1,F2,FACTNAMES)
%
% function stats = rm_anova2(Y,S,F1,F2,FACTNAMES)
%
% Two-factor, within-subject repeated measures ANOVA.
% For designs with two within-subject factors.
%
% Parameters:
%    Y          dependent variable (numeric) in a column vector
%    S          grouping variable for SUBJECT
%    F1         grouping variable for factor #1
%    F2         grouping variable for factor #2
%    F1name     name (character array) of factor #1
%    F2name     name (character array) of factor #2
%
%    Y should be a 1-d column vector with all of your data (numeric).
%    The grouping variables should also be 1-d numeric, each with same
%    length as Y. Each entry in each of the grouping vectors indicates the
%    level # (or subject #) of the corresponding entry in Y.
%
% Returns:
%    stats is a cell array with the usual ANOVA table:
%      Source / ss / df / ms / F / p
%
% Notes:
%    Program does not do any input validation, so it is up to you to make
%    sure that you have passed in the parameters in the correct form:
%
%       Y, S, F1, and F2 must be numeric vectors all of the same length.
%
%       There must be at least one value in Y for each possible combination
%       of S, F1, and F2 (i.e. there must be at least one measurement per
%       subject per condition).
%
%       If there is more than one measurement per subject X condition, then
%       the program will take the mean of those measurements.
%
% Aaron Schurger (2005.02.04)
%   Derived from Keppel & Wickens (2004) "Design and Analysis" ch. 18
%

%
% Revision history...
%
% 11 December 2009 (Aaron Schurger)
%
% Fixed error under "bracket terms"
% was: expY = sum(Y.^2);
% now: expY = sum(sum(sum(MEANS.^2)));
%

stats = cell(4,5);

F1_lvls = unique(F1);
F2_lvls = unique(F2);
Subjs = unique(S);

a = length(F1_lvls); % # of levels in factor 1
b = length(F2_lvls); % # of levels in factor 2
n = length(Subjs); % # of subjects

INDS = cell(a,b,n); % this will hold arrays of indices
CELLS = cell(a,b,n); % this will hold the data for each subject X condition
MEANS = zeros(a,b,n); % this will hold the means for each subj X condition

% Calculate means for each subject X condition.
% Keep data in CELLS, because in future we may want to allow options for
% how to compute the means (e.g. leaving out outliers > 3stdev, etc...).
for i=1:a % F1
    for j=1:b % F2
        for k=1:n % Subjs
            INDS{i,j,k} = find(F1==F1_lvls(i) & F2==F2_lvls(j) & S==Subjs(k));
            CELLS{i,j,k} = Y(INDS{i,j,k});
            MEANS(i,j,k) = mean(CELLS{i,j,k});
        end
    end
end

% make tables (see table 18.1, p. 402)
AB = reshape(sum(MEANS,3),a,b); % across subjects
AS = reshape(sum(MEANS,2),a,n); % across factor 2
BS = reshape(sum(MEANS,1),b,n); % across factor 1

A = sum(AB,2); % sum across columns, so result is ax1 column vector
B = sum(AB,1); % sum across rows, so result is 1xb row vector
S = sum(AS,1); % sum across columns, so result is 1xs row vector
T = sum(sum(A)); % could sum either A or B or S, choice is arbitrary

% degrees of freedom
dfA = a-1;
dfB = b-1;
dfAB = (a-1)*(b-1);
dfS = n-1;
dfAS = (a-1)*(n-1);
dfBS = (b-1)*(n-1);
dfABS = (a-1)*(b-1)*(n-1);

% bracket terms (expected value)
expA = sum(A.^2)./(b*n);
expB = sum(B.^2)./(a*n);
expAB = sum(sum(AB.^2))./n;
expS = sum(S.^2)./(a*b);
expAS = sum(sum(AS.^2))./b;
expBS = sum(sum(BS.^2))./a;
expY = sum(sum(sum(MEANS.^2))); %sum(Y.^2);
expT = T^2 / (a*b*n);

% sums of squares
ssA = expA - expT;
ssB = expB - expT;
ssAB = expAB - expA - expB + expT;
ssS = expS - expT;
ssAS = expAS - expA - expS + expT;
ssBS = expBS - expB - expS + expT;
ssABS = expY - expAB - expAS - expBS + expA + expB + expS - expT;
ssTot = expY - expT;

% mean squares
msA = ssA / dfA;
msB = ssB / dfB;
msAB = ssAB / dfAB;
msS = ssS / dfS;
msAS = ssAS / dfAS;
msBS = ssBS / dfBS;
msABS = ssABS / dfABS;

% f statistic
fA = msA / msAS;
fB = msB / msBS;
fAB = msAB / msABS;

% p values
pA = 1-fcdf(fA,dfA,dfAS);
pB = 1-fcdf(fB,dfB,dfBS);
pAB = 1-fcdf(fAB,dfAB,dfABS);

% return values
stats = {'Source','SS','df','MS','F','p';...
         FACTNAMES{1}, ssA, dfA, msA, fA, pA;...
         FACTNAMES{2}, ssB, dfB, msB, fB, pB;...
         [FACTNAMES{1} ' x ' FACTNAMES{2}], ssAB, dfAB, msAB, fAB, pAB;...
         [FACTNAMES{1} ' x Subj'], ssAS, dfAS, msAS, [], [];...
         [FACTNAMES{1} ' x Subj'], ssBS, dfBS, msBS, [], [];...
         [FACTNAMES{1} ' x ' FACTNAMES{2} ' x Subj'], ssABS, dfABS, msABS, [], []};

 return


function appdata = sliceomaticsetdata(d,xmesh,ymesh,zmesh)
% SLICEOMATICSETDATA(rawdata) - Create the data used for
% sliceomatic in the appdata D.

% Check variables
error(nargchk(1,4,nargin))

% Simplify the isonormals
  disp('Smoothing for IsoNormals...');
  d.smooth=smooth3(d.data);  % ,'box',5);
  d.reducenumbers=[floor(size(d.data,2)/20)...
          floor(size(d.data,1)/20)...
          floor(size(d.data,3)/20) ];
  d.reducenumbers(d.reducenumbers==0)=1;

  if nargin == 4
      % Reorder vectors: make them horizontal (prepare to flipdim)
      if size(xmesh,1)>size(xmesh,2)
          xmesh=xmesh';
      end
      if size(ymesh,1)>size(ymesh,2)
          ymesh=ymesh';
      end
      if size(zmesh,1)>size(zmesh,2)
          zmesh=zmesh';
      end
      % Set axis orientation
      xdir='normal';
      ydir='normal';
      zdir='normal';
      if issorted(xmesh)~=1
          xmesh=flipdim(xmesh,2);
          xdir='reverse';
          d.xlim = [xmesh(1) xmesh(end)];
          xmesh=flipdim(xmesh,2);
      else
          d.xlim = [xmesh(1) xmesh(end)];
      end
      if issorted(ymesh)~=1
          ymesh=flipdim(ymesh,2);
          ydir='reverse';
          d.ylim = [ymesh(1) ymesh(end)];
          ymesh=flipdim(ymesh,2);
      else
          d.ylim = [ymesh(1) ymesh(end)];
      end
      % This should not be the case for medical images
      if issorted(zmesh)~=1
          zmesh=flipdim(zmesh,2);
          zdir='reverse';
          d.zlim = [zmesh(1) zmesh(end)];
          zmesh=flipdim(zmesh,2);
      else
          d.zlim = [zmesh(1) zmesh(end)];
      end

      % Vol vis suite takes numbers in X/Y form.
      ly = 1:d.reducenumbers(1):size(d.data,2);
      lx = 1:d.reducenumbers(2):size(d.data,1);
      lz = 1:d.reducenumbers(3):size(d.data,3);

      for i = 1:length(ly)
          ly(i) = xmesh(ly(i));
      end
      for i = 1:length(lx)
          lx(i) = ymesh(lx(i));
      end
      for i = 1:length(lz)
          lz(i) = zmesh(lz(i));
      end

      d.reducelims={ ly lx lz };
      disp('Generating reduction volume...');
      d.reduce= reducevolume(d.data,d.reducenumbers);
      d.reducesmooth=smooth3(d.reduce,'box',5);
      % Set axis
      %d.xlim = [xmesh(1) xmesh(end)];
      %d.ylim = [ymesh(1) ymesh(end)];
      %d.zlim = [zmesh(1) zmesh(end)];
      d.xmesh = xmesh;
      d.ymesh = ymesh;
      d.zmesh = zmesh;
        d.xdir = xdir;
        d.ydir = ydir;
        d.zdir = zdir;

  else
        % Vol vis suite takes numbers in X/Y form.
        ly = 1:d.reducenumbers(1):size(d.data,2);
        lx = 1:d.reducenumbers(2):size(d.data,1);
        lz = 1:d.reducenumbers(3):size(d.data,3);

        d.reducelims={ ly lx lz };
        disp('Generating reduction volume...');
        d.reduce= reducevolume(d.data,d.reducenumbers);
        d.reducesmooth=smooth3(d.reduce,'box',5);

        d.xlim = [1 size(d.data,2)];
        d.ylim = [1 size(d.data,1)];
        d.zlim = [1 size(d.data,3)];
        d.xmesh = nan;
        d.ymesh = nan;
        d.zmesh = nan;
        d.xdir = 'normal';
        d.ydir = 'normal';
        d.zdir = 'normal';
    end

  appdata = d;


function dx = tora_dx(u, x)

tora_lpv

p = [x(3) x(4)];

AB = querylpv(lpv, p);

% dx = A x + B u
dx = AB * [x(:); u];


function [dv, dvArr, flyBy1DVVect, flyBy2DVVect, flyBy1Rp, flyBy2Rp, ...
          xferOrbitP1, xferOrbitP2, xferOrbitP3, flyBy1OrbitIn, flyBy1OrbitOut, ...
          flyBy2OrbitIn, flyBy2OrbitOut] = ...
          findOptimalTwoFlyByTraj(x, departBodyInfo, flyby1BodyInfo, flyby2BodyInfo, arrivalBodyInfo, gmuXfr)
%findOptimalTwoFlyByTraj Summary of this function goes here
%   Detailed explanation goes here
    if(length(x)~=4)
        error('Length of x in findOptimalTwoFlyByTraj must be 4');
    end

    departDate = x(1);
    phase1TOF = x(2);
    phase2TOF = x(3);
    phase3TOF = x(4);

    xDates = [departDate,
              departDate + phase1TOF,
              departDate + phase1TOF + phase2TOF,
              departDate + phase1TOF + phase2TOF + phase3TOF];

    preFunc1 = @(arrivalUT, departUT) findOptimalDepartureArrivalObjFunc(arrivalUT, departUT, departBodyInfo, flyby1BodyInfo, gmuXfr, 'departDVRadioBtn');
    objFuncDepart = @(x) preFunc1(x(2), x(1));

    objFuncFlyby1DV = @(x) flybyDVObjFunc([xDates(1) xDates(2) xDates(3)], departBodyInfo, flyby1BodyInfo, flyby2BodyInfo, gmuXfr);
    objFuncFlyby2DV = @(x) flybyDVObjFunc([xDates(2) xDates(3) xDates(4)], flyby1BodyInfo, flyby2BodyInfo, arrivalBodyInfo, gmuXfr);

    preFunc2 = @(arrivalUT, departUT) findOptimalDepartureArrivalObjFunc(arrivalUT, departUT, flyby2BodyInfo, arrivalBodyInfo, gmuXfr, 'arrivalDVRadioBtn');
    objFuncArrival = @(x) preFunc2(x(4), x(3));

    dv1 = objFuncDepart(xDates);
    [dv2, flyBy1DVVect, flyBy1Rp, xferOrbitP1, xferOrbitP2, flyBy1OrbitIn, flyBy1OrbitOut] = objFuncFlyby1DV(xDates);
    [dv3, flyBy2DVVect, flyBy2Rp, xferOrbitP2, xferOrbitP3, flyBy2OrbitIn, flyBy2OrbitOut] = objFuncFlyby2DV(xDates);
    dv4 = objFuncArrival(xDates);
    dvArr = [dv1, dv2, dv3, dv4];

    dv = dv1 + dv2 + dv3 + dv4;
end


function table_io_test03 ( )

%*****************************************************************************80
%
%% TABLE_IO_TEST03 tests I4MAT_WRITE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 February 2010
%
%  Author:
%
%    John Burkardt
%
  n = 20;
  m = 5;
  output_filename = 'i4mat_05_00020.txt';

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST03\n' );
  fprintf ( 1, '  I4MAT_WRITE writes an I4MAT file.\n' );

  table = i4mat_indicator ( m, n );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Spatial dimension M = %d\n', m );
  fprintf ( 1, '  Number of points N  = %d\n', n );

  i4mat_print_some ( m, n, table, 1, 1, 5, 5, ...
    '  5x5 portion of the data written to file:' );

  i4mat_write ( output_filename, m, n, table );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Wrote the file "%s".\n', output_filename );

  return
end


function p = approxeq_pot(A, B, tol)

if nargin < 3, tol = 1e-3; end

p = approxeq(A.p, B.p, tol) & approxeq(A.u, B.u, tol);


%Program for one sided image reflection along a Line
function R = reflection(I,L)
%Author : Jeny Rajan
%I - Image to be Reflected
%L - Line position
%R - Reflected image
%eg : R = reflection(I,128);
% L should be between 1 and number of columns
[x y z]=size(I);
R=zeros(x,y,z);
R(:,L+1:y,:)=I(:,1:y-L,:);
R(:,1:L,:)=I(:,L:-1:1,:);
R=uint8(R);
end


function [ y, j, f, ierror ] = yjf_check_common ( y, j, f )

%*****************************************************************************80
%
%% YJF_CHECK_COMMON normalizes a Common YJF date.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input/output, integer Y, J, real F, the YJF date.
%
%    Output, integer IERROR, nonzero if there was an error.
%
  [ y, j, ierror ] = yj_check_common ( y, j );

  if ( ierror ~= 0 )
    return
  end
%
%  Force the fraction to lie between 0 and 1.
%
  while ( f < 0.0 )
    f = f + 1.0;
    j = j - 1;
  end

  while ( 1.0 <= f )
    f = f - 1.0;
    j = j + 1;
  end

  return
end


% SYNTAX:
% [data_d, svs, nSV] = hmrR_MotionCorrectPCA(data_d, mlActMan, mlActAuto, tIncMan, tIncAuto, nSV)
%
% UI NAME:
% Motion_Correct_PCA
%
% This function uses PCA to filter only the segments of data identified as
% a motion artifact. The motion artifacts are indicated in the tInc vector
% by the value of 0.
%
%
% INPUTS
% data_d:  SNIRF object containing data matrix, timepoints x sd pairs
% mlActMan: Cell array of vectors, one for each time base in data, specifying
%        active/inactive channels with 1 meaning active, 0 meaning inactive
% mlActAuto: Cell array of vectors, one for each time base in data, specifying
%        active/inactive channels with 1 meaning active, 0 meaning inactive
% tIncMan: Cell array for eqach data block with vectors of length time points
%          where 1's indicating data included and 0's indicating motion artifact
% tIncAuto: Cell array for eqach data block with vectors of length time points
%          where 1's indicating data included and 0's indicating motion artifact
% nSV: Cell array for each data block with the number of principal components to remove
%      from each data block. If this number is less than 1, then the filter removes the first n
%      components of the data that removes a fraction of the variance up to nSV. Percent variance
%      you want to remove, or give an integer for number ofcomponents to remove
%
%
% OUTPUTS
% data_dN: SNIRF object containing the motion corrected data matrix.
% svs: Cell array for each data block with the singular values of the PCA
% nSV: Cell array for each data block with the number of singular values removed from the data.
%
%
% USAGE OPTIONS:
% Motion_Correct_PCA:  [dod, svs, nSV] = hmrR_MotionCorrectPCA(dod, mlActMan, mlActAuto, tIncMan, tIncAuto, nSV)
%
% PARAMETERS:
% nSV: 0.0
%
% PREREQUISITES:
% Intensity_to_Delta_OD: dod = hmrR_Intensity2OD( intensity )
%
function [data_dN, svs, nSV] = hmrR_MotionCorrectPCA(data_d,  mlActMan, mlActAuto, tIncMan, tIncAuto, nSV)

% Init output
data_dN = DataClass.empty();
svs = cell(length(data_d),1);
if ~iscell(nSV)
    nSV = repmat({nSV}, length(data_d),1);
end

% Check input args
if isempty(tIncMan)
    tIncMan = cell(length(data_d),1);
end
if isempty(tIncAuto)
    tIncAuto = cell(length(data_d),1);
end
if isempty(mlActMan)
    mlActMan = cell(length(data_d),1);
end
if isempty(mlActAuto)
    mlActAuto = cell(length(data_d),1);
end

for iBlk=1:length(data_d)
    data_dN(iBlk) = DataClass(data_d(iBlk));

    d           = data_d(iBlk).GetDataTimeSeries();
    MeasList    = data_d(iBlk).GetMeasList();
    mlActMan{iBlk} = mlAct_Initialize(mlActMan{iBlk}, MeasList);
    mlActAuto{iBlk} = mlAct_Initialize(mlActAuto{iBlk}, MeasList);
    mlAct = mlActMan{iBlk}(:,3) & mlActAuto{iBlk}(:,3);

    if isempty(tIncMan{iBlk})
        tIncMan{iBlk} = ones(size(d,1),1);
    end
    if isempty(tIncAuto{iBlk})
        tIncAuto{iBlk} = ones(size(d,1),1);
    end
    tInc = tIncMan{iBlk} & tIncAuto{iBlk};

    lstNoInc = find(tInc==0);
    lstAct = find(mlAct==1);

    if isempty(lstNoInc)
        nSV{iBlk} = 0;
        continue;
    end

    %
    % Do PCA
    %
    y = d(lstNoInc,lstAct);
    yo = y;

    c = y.' * y;
    [V,St,foo] = svd(c);
    svs{iBlk} = diag(St) / sum(diag(St));

    svsc = svs{iBlk};
    for idx = 2:size(svs{iBlk},1)
        svsc(idx) = svsc(idx-1) + svs{iBlk}(idx);
    end
    if nSV{iBlk}<1 & nSV{iBlk}>0 % find number of SV to get variance up to nSV{iBlk}
        ev = diag(svsc<nSV{iBlk});
        nSV{iBlk} = find(diag(ev)==0,1)-1;
    end

    ev = zeros(size(svs{iBlk},1),1);
    ev(1:nSV{iBlk}) = 1;
    ev = diag(ev);

    yc = yo - y*V*ev*V';

    %
    % splice the segments of data together
    %
    lstMs = find(diff(tInc)==-1);
    lstMf = find(diff(tInc)==1);
    if isempty(lstMf)
        lstMf = length(tInc);
    end
    if isempty(lstMs)
        lstMs = 1;
    end
    if lstMs(1)>lstMf(1)
        lstMs = [1;lstMs];
    end
    if lstMs(end)>lstMf(end)
        lstMf(end+1,1) = length(tInc);
    end
    lstMb = lstMf-lstMs;
    for ii=2:length(lstMb)
        lstMb(ii) = lstMb(ii-1) + lstMb(ii);
    end

    dN = d;

    for ii=1:length(lstAct)
        jj = lstAct(ii);

        lst = (lstMs(1)):(lstMf(1)-1);
        if lstMs(1)>1
            dN(lst,jj) = yc(1:lstMb(1),ii) - yc(1,ii) + dN(lst(1),jj);
        else
            dN(lst,jj) = yc(1:lstMb(1),ii) - yc(lstMb(1),ii) + dN(lst(end),jj);
        end

        for kk=1:(length(lstMf)-1)
            lst = (lstMf(kk)-1):lstMs(kk+1);
            dN(lst,jj) = d(lst,jj) - d(lst(1),jj) + dN(lst(1),jj);

            lst = (lstMs(kk+1)):(lstMf(kk+1)-1);
            dN(lst,jj) = yc((lstMb(kk)+1):lstMb(kk+1),ii) - yc(lstMb(kk)+1,ii) + dN(lst(1),jj);
        end

        if lstMf(end)<length(d)
            lst = (lstMf(end)-1):length(d);
            dN(lst,jj) = d(lst,jj) - d(lst(1),jj) + dN(lst(1),jj);
        end
    end

    data_dN(iBlk).SetDataTimeSeries(dN);
end


% test for image rotation

M = load_image('lena', 256);

theta = pi/50;
for i=1:100
    M = perform_image_rotation(M,theta);
    imageplot(M); drawnow;
end


function v = eigenmat(x)
% x is the size
v= eig(magic(x));


function grad = mapDataTerm_gradImage(SR, model, LR, W, Wt)

    if isempty(model.photometricParams)
        % Get residual error for super-resolved estimate.
        r = getResidual(SR, LR, W, model.photometricParams);
        % Weight residual error by associated confidence map
        confidence = model.confidence;
        if isempty(confidence)
            % Default: equal confidence for each pixel
            confidence = ones(size(LR));
        end
        if ~isvector(confidence)
            confidence = imageToVector(confidence);
        end
        % Calculate the gradient w.r.t. image pixels of HR image
        if strcmp(model.errorModel, 'l2NormErrorModel')
            grad = - 2 * (Wt * (confidence .* r));
        elseif strcmp(model.errorModel, 'l1NormErrorModel')
            grad = - Wt * (confidence .* sign(r));
        else
            % User-defined error model
            [~, g] = model.errorModel(r);
            grad = - Wt * (confidence .* g);
        end
    else
        % Calculate the residual using photometric parameters.
        numFrames = size(model.photometricParams.mult, 3);
        numLRPixel = length(LR)/numFrames;
        if isvector(model.photometricParams.mult(:,:,1))
            % Global, affine photometric model
            bm = zeros(size(LR));
            ba = zeros(size(LR));
            for k = 1:numFrames
                bm( ((k-1)*numLRPixel + 1):(k*numLRPixel) ) = repmat(model.photometricParams.mult(k), numLRPixel, 1);
                ba( ((k-1)*numLRPixel + 1):(k*numLRPixel) ) = repmat(model.photometricParams.add(k), numLRPixel, 1);
            end
        else
            % Local (pixel-wise) photometric model
            bm = zeros(size(LR));
            ba = zeros(size(LR));
            for k = 1:numFrames
                bm( ((k-1)*numLRPixel + 1):(k*numLRPixel) ) = imageToVector(model.photometricParams.mult(:,:,k));
                ba( ((k-1)*numLRPixel + 1):(k*numLRPixel) ) = imageToVector(model.photometricParams.add(:,:,k));
            end
        end
        r = LR - bm .* (W*SR) - ba;
        % Weight residual error by associated confidence map
        confidence = model.confidence;
        if ~isvector(confidence)
            confidence = imageToVector(confidence);
        end
        if isempty(confidence)
            % Default: equal confidence for each pixel
            confidence = ones(size(LR));
        end

        % Calculate the gradient w.r.t. image pixels of HR image taking
        % photometric parameters into account.
%         grad = 0;
%         for k = 1:numFrames
%             m = numLRPixel*(k-1) + 1;
%             %Wkt = Wt(:, m:(m + numLRPixel-1));
%             Wk = W(m:(m + numLRPixel-1), :);
%             ck = confidence(m:(m + numLRPixel-1));
%             rk = r(m:(m + numLRPixel-1));
%
%             if ~isvector(model.photometricParams.mult(:,:,k))
%                 % Local (pixel-wise) photometric model
%                 bm = imageToVector( model.photometricParams.mult(:,:,k) );
%             else
%                 % Global, affine photometric model
%                 bm = model.photometricParams.mult(k);
%             end
%         end

            if strcmp(model.errorModel, 'l2NormErrorModel')
                %grad = grad - 2 * Wkt * (bm .* ck .* rk);
                grad = (-2 * (bm .* confidence .* r)' * W)';
                %grad = grad + g';
            elseif strcmp(model.errorModel, 'l1NormErrorModel')
                %grad = grad - Wkt * (bm .* ck .* sign(rk));
                grad = - Wt * (bm .* confidence .* sign(r));
                %grad = grad + g';
            else
                % User-defined error model
                [~, g] = model.errorModel(rk);
                %grad = grad - Wkt * (bm .* ck .* g);
                grad = - Wt * (bm .* confidence .* g);
                %grad = grad + g';
            end
        end
    end


function dtiWarpToWhiteMatter(handles)

view = getSelectedVolume;
anatSize = size(view.anat);
wmVol = zeros(anatSize);

classFileName = [view.leftPath(1:end-5) '.class'];
c = readClassFile(classFileName);
voi = c.header.voi;
wmVol([voi(3):voi(4)], [voi(1):voi(2)], [voi(5):voi(6)]) = permute(c.data, [2,1,3])==c.type.white;

classFileName = [view.rightPath(1:end-5) '.class'];
c = readClassFile(classFileName);
voi = c.header.voi;
wmVolTmp = wmVol;
wmVolTmp([voi(3):voi(4)], [voi(1):voi(2)], [voi(5):voi(6)]) = permute(c.data, [2,1,3])==c.type.white;

% combine left and right
wmVol = wmVol | wmVolTmp;

wmVol = smooth3(wmVol, 'gaussian', 3);

[wmDti,mmDt,xformDt] = dtiGetNamedImage(handles.bg, 'white matter');
xform = handles.xformVAnatToAcpc;
bb = [-72 -110 -45; 72 85 85];
wmVolDti = dtiResliceVolume(wmVol, inv(xform), bb, mmDt);
wmVolDti = permute(wmVolDti, [2 1 3]);

figure;imagesc(wmVolDti(:,:,20)); colorbar;
figure;imagesc(wmDti(:,:,20)); colorbar;
figure;imagesc(wmVolDti(:,:,20)-wmDti(:,:,20)); colorbar;

% M = estMotionIter3(wmDti, wmVolDti, 3, eye(4), 0, 1);
%
% x = inv(dtiGetStandardXform(handles, xformDt)) * M;
% newWmDti = dtiResliceVolume(wmDti, x, bb, mmDt);
% newWmDti = permute(newWmDti, [2 1 3]);
% figure;imagesc(newWmDti(:,:,20)); colorbar;
% figure;imagesc(wmVolDti(:,:,20)-newWmDti(:,:,20)); colorbar;

[deformField, newImg, absDeform, MSE] = dtiDeformationScalar(wmVolDti, wmDti, 25, [7 5 3]);
figure;imagesc(newImg(:,:,20)); colorbar;
figure;imagesc(newImg(:,:,20)-wmVolDti(:,:,20)); colorbar;


%% Example
% real time control of the KUKA iiwa 7 R 800
% the impedence control is turned on
% Moving first joint of the robot, using a sinisoidal function

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

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

% Mohammad SAFEEA, 24th of April 2018

close all,clear all;clc;

warning('off')

ip='172.31.1.147'; % The IP of the controller
% start a connection with the server
global t_Kuka;
t_Kuka=net_establishConnection( ip );

if ~exist('t_Kuka','var') || isempty(t_Kuka) || strcmp(t_Kuka.Status,'closed')
  warning('Connection could not be establised, script aborted');
  return;
else

      %% Get position roientation of end effector

%      jPos={0,pi/6,0,-pi/2,0,pi/2-pi/6,0};

        jPos={0,0,0,-pi/2,0,pi/2,0};
      %jPos={0,0,0,0,0,0,0};
      setBlueOff(t_Kuka); % turn Off blue light

      relVel=0.15;
      movePTPJointSpace( t_Kuka , jPos, relVel); % move to initial configuration
     %% Pause for 3 seocnds
     pause(3);
        %% Start direct servo in joint space
        massOfTool=0.5; % the mass of the tool attached to flange in Kg
        cOMx=0; % X coordinate of the center of mass of the tool in (mm)
        cOMy=0; % Y coordinate of the center of mass of the tool in (mm)
        cOMz=40; % Z coordinate of the center of mass of the tool in (mm)
        cStiness=900; % cartizian stifness
        rStifness=80; % rotational stifness
        nStifness=50; % null space stifness

        % Start the realtime control with impedence
        realTime_startImpedanceJoints(t_Kuka,massOfTool,cOMx,cOMy,cOMz,...
        cStiness,rStifness,nStifness);

       w=0.6; % motion constants, frequency rad/sec
       A=0.2; % motion constants, amplitude of motion

       a=datevec(now);
       t0=a(6)+a(5)*60+a(4)*60*60; % calculate initial time

       dt=0;
     precission=1000;
     precission_flag=true;
     tstart=t0;
     counter=0;
     duration=1*60; %1 minutes
     time_stamps=zeros(1,1000*duration);
       while(dt<duration)
         %% ferform trajectory calculation here
          a=datevec(now);
          time=a(6)+a(5)*60+a(4)*60*60;
          dt=time-t0;

          temp=A*(1-cos(w*dt));
            for dacount=1:7
                jPosCommand{dacount}=jPos{dacount}+temp;
            end
          counter=counter+1;
          %% Send joint positions to robot
          %sendJointsPositions( t ,jPos);
          sendJointsPositionsf( t_Kuka ,jPosCommand);
          time_stamps(counter)=dt;

       end
       tend=time;
       rate=counter/(tend-tstart);

       %% Stop the realtime control with impedence motion
       realTime_stopImpedanceJoints( t_Kuka );

       fprintf('\nThe rate of joint nagles update per second is: \n');
       disp(rate);
       fprintf('\n')
       pause(2);
       %% turn off light
       setBlueOff(t_Kuka);

      %% turn off the server
       net_turnOffServer( t_Kuka );

       fclose(t_Kuka);

       %% save time stamps
       save('timingdata.mat','time_stamps');

end
 warning('on')


function PlotPoint2DLikePolarity(aedat, numPlots, distributeBy, minTime, maxTime, proportionOfPixels, transpose, flipVertical, flipHorizontal)

%{
Works like PlotPolarity, except that:
 - the values comes from point2D instead of polarity,
 - the colour shows the type of the event (a unique color is chosen for each type)
 - there's no concept of contrast.
%}

% The proportion of an array-full of events which is shown on a plot
if ~exist('proportionOfPixels', 'var')
	proportionOfPixels = 0.1;
end

if ~exist('numPlots', 'var')
	numPlots = 12;
end

if ~exist('distributeBy', 'var')
	distributeBy = 'time';
end

% Unpack

timeStamp = aedat.data.point2D.timeStamp;
x = aedat.data.point2D.x;
y = aedat.data.point2D.y;
type = aedat.data.point2D.type;

% Distribute plots in a raster with a 3:4 ratio
numPlotsX = round(sqrt(numPlots / 3 * 4));
numPlotsY = ceil(numPlots / numPlotsX);

numEvents = length(timeStamp);
if strcmpi(distributeBy, 'time')
    if ~exist('minTime', 'var') || (exist('minTime', 'var') && minTime == 0)
        minTime = min(timeStamp);
    else
        minTime = minTime * 1e6;
    end
    if ~exist('maxTime', 'var') || (exist('maxTime', 'var') && maxTime == 0)
        maxTime = max(timeStamp);
    else
        maxTime = maxTime * 1e6;
    end
	totalTime = maxTime - minTime;
	timeStep = totalTime / numPlots;
	timePoints = minTime + timeStep * 0.5 : timeStep : maxTime;
else % distribute by event number
	eventsPerStep = numEvents / numPlots;
	timePoints = timeStamp(ceil(eventsPerStep * 0.5 : eventsPerStep : numEvents));
end

if exist ('transpose', 'var') && transpose
    % Swap x and y
    y = y + x;
    x = x - y;
    y = y - x;
end

minY = double(min(y));
maxY = double(max(y));
minX = double(min(x));
maxX = double(max(x));
numPixelsInArray = (maxY - minY) * (maxX - minX);
numPixelsToSelectEachWay = ceil(numPixelsInArray * proportionOfPixels / 2);

if numPlots > 1
    figure
end
for plotCount = 1 : numPlots
    if numPlots > 1
    	subplot(numPlotsY, numPlotsX, plotCount);
    end
	hold all
	% Find eventIndex nearest to timePoint
	eventIndex = find(timeStamp >= timePoints(plotCount), 1, 'first');
	firstIndex = max(1, eventIndex - numPixelsToSelectEachWay);
	lastIndex = min(numEvents, eventIndex + numPixelsToSelectEachWay);
	selectedLogical = [false(firstIndex - 1, 1); ...
					true(lastIndex - firstIndex + 1, 1); ...
					false(numEvents - lastIndex, 1)];
	typeSelected = type(selectedLogical);
    typeUniqueValues = unique(typeSelected);

    for uniqueValue = typeUniqueValues'
        selectedByTypeLogical = selectedLogical & type == uniqueValue;
    	plot(x(selectedByTypeLogical), y(selectedByTypeLogical), '.');
    end

	axis equal tight
	if ~exist('flipVertical', 'var') || flipVertical
		set(gca, 'YDir', 'reverse')
	end
    if exist('flipHorizontal', 'var') && flipHorizontal
		set(gca, 'XDir', 'reverse')
    end
	title([num2str(double(timeStamp(eventIndex)) / 1e6) ' s'])
end


function mask = mask_create_from_image_set(imgs, outname, atleastN, varargin)
% Take a set of images and create a mask of voxels in which at least N
% subjects have valid (not exactly zero, non NaN) data.
%
% :Usage:
% ::
%
%     mask = mask_create_from_image_set(imgs, outname, atleastN, ['sum'])
%
% This makes a useful results mask for a set of images, i.e., in a
% group analysis.
%
% :Optional: 'sum' input writes the sum image instead of the mask image,
% so that the values in the image reflect the number of input images
% with valid values.
%
% compatible with SPM5 and above only!
%
% :Examples:
% ::
%
%    mask_create_from_image_set(EXPT.SNPM.P{1}, 'mask_all_valid.img');
%
%    imgs = filenames('vascular_mask_*img');
%    mask_create_from_image_set(imgs, 'vascular_group_sum.img', 6, 'sum');
%
% ..
%    Tor Wager, April 2, 2008
%    Edit Sept 13, 2008: Sum image output option
% ..

    write_sum = 0;

    for i = 1:length(varargin)
        if ischar(varargin{i})
            switch varargin{i}
                % reserved keywords
                case {'sum', 'sumimage'}, write_sum = 1;

                otherwise, warning(['Unknown input string option:' varargin{i}]);
            end
        end
    end

    imgs = strvcat(imgs); % enforce string

    if nargin < 3 || isempty(atleastN), atleastN = size(imgs, 1); end

    spm_defaults

    disp('Mapping images.');
    V = spm_vol(imgs);

    disp('Checking dimensions and spaces.');
    anybad = iimg_check_volinfo(V(1), V);
    if anybad, error('Exiting.'); end

    disp('Reading images.');
    dat = spm_read_vols(V);

    % number of subjects for which each vox is valid
    sumimg = sum(abs(dat) > eps & ~isnan(dat), 4);

    % threshold
    mask = double(sumimg >= atleastN);

    % write output
    if ~isempty(outname)

        outV = struct( 'fname', outname, 'mat', V(1).mat, 'dim', V(1).dim, 'dt', V(1).dt, 'pinfo', [1 0 0]', 'n', [1 V(1).n(2)]  );
        outV.descrip = sprintf('At least %3.0f out of %3.0f images valid', atleastN, size(imgs, 1));

        fprintf('Writing: %s\n', outV.fname);

        if write_sum
            spm_write_vol(outV, sumimg);
        else
            spm_write_vol(outV, mask);
        end
    end

end


filename='Gripping_triangle_coarse';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'nonadjoint_compliance'};
weights = [1, 0.1];
constraint = {'volumeConstraint'};
constraint_case = 'INEQUALITY';
optimizer = 'SLERP'; incrementFactor = 1;
filterType = 'P1';

nsteps = 1;
Vfrac_final = 1;
optimality_final = 1e-3;
constr_final =1e-3;

Vfrac_initial = 1;
optimality_initial = 1e-3;
constr_initial = 1e-3;
TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;
TOL.nu_plus = 1/3;
TOL.nu_minus = 1/3;


function writeAllLabeledImages(imdir, imsegs, pg, outdir)
% writeAllLabeledImages(imdir, imsegs, pg, outdir)
%
% Write label images to specified outdir
%

DO_GT = 0;
if isempty(pg)
    disp('Writing ground truth')
    DO_GT = 1;
end

for f = 1:numel(imsegs)

    if DO_GT
        nclasses =  numel(imsegs(f).label_names);
        pg{f} = zeros(imsegs(f).nseg, nclasses);
        lab = imsegs(f).labels;
        ind = find(lab>0);
        pg{f}(ind + imsegs(f).nseg*(lab(ind)-1)) = 1;
    end

    im = im2double(imread([imdir '/' imsegs(f).imname]));
    disp([num2str(f) ': ' imsegs(f).imname])
    [vc, hc] = splitpg(pg{f});

    lim = APPgetLabeledImage2(im, imsegs(f), vc, hc);

    %system(['cp ' imdir '/' imsegs(f).imname ' ' outdir '/' imsegs(f).imname]);
    imwrite(lim, [outdir '/' strtok(imsegs(f).imname, '.') '.l.jpg'], 'Quality', 90);
end


function [V,D]=gabmuleigs(K,c,p3,varargin)
%GABMULEIGS  Eigenpairs of Gabor multiplier
%   Usage:  h=gabmuleigs(K,c,g,a);
%           h=gabmuleigs(K,c,a);
%           h=gabmuleigs(K,c,ga,gs,a);
%
%   Input parameters:
%         K     : Number of eigenvectors to compute.
%         c     : symbol of Gabor multiplier
%         g     : analysis/synthesis window
%         ga    : analysis window
%         gs    : synthesis window
%         a     : Length of time shift.
%   Output parameters:
%         V     : Matrix containing eigenvectors.
%         D     : Eigenvalues.
%
%   `gabmuleigs` has been deprecated. Please use construct a frame multiplier
%   and use |framemuleigs| instead.
%
%   A call to `gabmuleigs(K,c,ga,gs,a)` can be replaced by ::
%
%     [Fa,Fs]=framepair('dgt',ga,gs,a,M);
%     [V,D]=framemuleigs(Fa,Fs,s,K);
%
%   Original help:
%   --------------
%
%   `gabmuleigs(K,c,g,a)` computes the *K* largest eigenvalues and eigen-
%   vectors of the Gabor multiplier with symbol *c* and time shift *a*.  The
%   number of channels is deduced from the size of the symbol *c*.  The
%   window *g* will be used for both analysis and synthesis.
%
%   `gabmuleigs(K,c,ga,gs,a)` does the same using the window the window *ga*
%   for analysis and *gs* for synthesis.
%
%   `gabmuleigs(K,c,a)` does the same using the a tight Gaussian window of
%   for analysis and synthesis.
%
%   If *K* is empty, then all eigenvalues/pairs will be returned.
%
%   `gabmuleigs` takes the following parameters at the end of the line of input
%   arguments:
%
%     'tol',t      Stop if relative residual error is less than the
%                  specified tolerance. Default is 1e-9
%
%     'maxit',n    Do at most n iterations.
%
%     'iter'       Call `eigs` to use an iterative algorithm.
%
%     'full'       Call `eig` to sole the full problem.
%
%     'auto'       Use the full method for small problems and the
%                  iterative method for larger problems. This is the
%                  default.
%
%     'crossover',c
%                  Set the problem size for which the 'auto' method
%                  switches. Default is 200.
%
%     'print'      Display the progress.
%
%     'quiet'      Don't print anything, this is the default.
%
%   See also: gabmul, dgt, idgt, gabdual, gabtight

warning(['LTFAT: GABMULEIGS has been deprecated, please use FRAMEMULEIGS ' ...
         'instead. See the help on FRAMEMULEIGS for more details.']);

% Change this to 1 or 2 to see the iterative method in action.
printopts=0;

if nargin<3
  error('%s: Too few input parameters.',upper(mfilename));
end;

if nargout==2
  doV=1;
else
  doV=0;
end;

M=size(c,1);
N=size(c,2);

istight=1;
if numel(p3)==1
  % Usage: h=gabmuleigs(c,K,a);
  a=p3;
  L=N*a;
  ga=gabtight(a,M,L);
  gs=ga;
  arglist=varargin;
else
  if numel(varargin{1})==1
    % Usage: h=gabmuleigs(c,K,g,a);
    ga=p3;
    gs=p3;
    a=varargin{1};
    L=N*a;
    arglist=varargin(2:end);
  else
    if numel(varargin{2})==1
      % Usage: h=gabmuleigs(c,K,ga,gs,a);
      ga=p3;
      gs=varargin{1};
      a =varargin{2};
      L=N*a;
      istight=0;
      arglist=varargin(3:end);
    end;
  end;
end;

definput.keyvals.maxit=100;
definput.keyvals.tol=1e-9;
definput.keyvals.crossover=200;
definput.flags.print={'quiet','print'};
definput.flags.method={'auto','iter','full'};

[flags,kv]=ltfatarghelper({},definput,arglist);

% Do the computation. For small problems a direct calculation is just as
% fast.

if (flags.do_iter) || (flags.do_auto && L>kv.crossover)

  if flags.do_print
    opts.disp=1;
  else
    opts.disp=0;
  end;
  opts.isreal = false;
  opts.maxit  = kv.maxit;
  opts.tol    = kv.tol;

  % Setup afun
  afun(1,c,ga,gs,a,M,L);

  if doV
    [V,D] = eigs(@afun,L,K,'LM',opts);
  else
    D     = eigs(@afun,L,K,'LM',opts);
  end;

else
  % Compute the transform matrix.
  bigM=tfmat('gabmul',c,ga,gs,a);

  if doV
    [V,D]=eig(bigM);
  else
    D=eig(bigM);
  end;

end;

% The output from eig and eigs is a diagonal matrix, so we must extract the
% diagonal.
D=diag(D);

% Sort them in descending order
[~,idx]=sort(abs(D),1,'descend');
D=D(idx(1:K));

if doV
  V=V(:,idx(1:K));
end;

% Clean the eigenvalues, if we know that they are real-valued
%if isreal(ga) && isreal(gs) && isreal(c)
%  D=real(D);
%end;

% The function has been written in this way, because Octave (at the time
% of writing) does not accept additional parameters at the end of the
% line of input arguments for eigs
function y=afun(x,c_in,ga_in,gs_in,a_in,M_in,L_in)
  persistent c;
  persistent ga;
  persistent gs;
  persistent a;
  persistent M;
  persistent L;

  if nargin>1
    c  = c_in;
    ga = ga_in;
    gs = gs_in;
    a  = a_in;
    M  = M_in;
    L  = L_in;
  else
    y=comp_idgt(c.*comp_dgt(x,ga,a,M,[0 1],0,0,0),gs,a,[0 1],0,0);
  end;


function test_model = test_nrsfm(test,model_3d,test_em_iters)
% Use a trained shape model to predict keypoints on new instances
% given the bounding box and visible keypoints
% NOTE: The keypoints are already scaled to make all bboxes the same size
    params = get_params();
    P = test.points;
    MD = isnan(P(1:end/2,:));
    P(isnan(P)) = 0;
    tol = params.nrsfm.tol;
    max_em_iter = test_em_iters;
    try
        seg.poly_x = test.poly_x;
        seg.poly_y = test.poly_y;
    catch
        seg = test.mask;
    end
    % Do EM for inference with missing data
    [P3, RO, Tr, basis_coeffs,c] = em_sfm_known_shape(P, MD, model_3d.S_bar,...
        model_3d.defBasis, model_3d.sigma_sq, seg, test.imsize, test.bbox, tol, max_em_iter);

    %Set up test_model

    test_model.class = model_3d.class;
    test_model.S_bar = model_3d.S_bar;
    test_model.defBasis = model_3d.defBasis;
    test_model.part_names = model_3d.part_names;
    test_model.sigma_sq = model_3d.sigma_sq;
    test_model.points3 = P3;
    test_model.rots = RO;
    test_model.trs = Tr;
    test_model.def_weights = basis_coeffs;
    test_model.voc_image_id = test.voc_image_id;
    if(isfield(test,'voc_rec_id'))
        test_model.voc_rec_id = test.voc_rec_id;
    end
    if(isfield(test,'flip'))
        test_model.flip = test.flip;
    end
    test_model.bbox = test.bbox;
    test_model.points2 = test.points;
    test_model.params = params;
    test_model.c = c;
    test_model.seg = seg;
end


function [l, L_rf, L_sf, L_k, L_seg, L_n] = ...
    retroProjHmgLinFromPinHoleOnRob(Rf, Sf, k, seg, n)

% RETROPROJHMGLINFROMPINHOLEONROB retroprj Hmg Line from pinhole on robot.

%   Copyright 2009 Teresa Vidal.

if nargout == 1

    ls = invPinHoleHmgLin(k, seg, n) ;
    lr = fromFrameHmgLin(Sf, ls);
    l  = fromFrameHmgLin(Rf, lr);

else % Jacobians requested

    [ls, LS_seg, LS_n, LS_k] = invPinHoleHmgLin(seg, n, k) ;
    [lr, LR_sf, LR_ls]       = fromFrameHmgLin(Sf, ls);
    [l, L_rf, L_lr]          = fromFrameHmgLin(Rf, lr);

    L_sf  = L_lr*LR_sf;
    L_ls  = L_lr*LR_ls;
    L_k   = L_ls*LS_k;
    L_seg = L_ls*LS_seg;
    L_n   = L_ls*LS_n;

end

% ========== 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


classdef GDE3 < ALGORITHM
% <multi> <real/integer> <constrained/none>
% Generalized differential evolution 3

%------------------------------- Reference --------------------------------
% S. Kukkonen and J. Lampinen, GDE3: The third evolution step of
% generalized differential evolution, Proceedings of the IEEE Congress on
% Evolutionary Computation, 2005, 443-450.
%------------------------------- 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();

            %% Optimization
            while Algorithm.NotTerminated(Population)
                Offspring  = OperatorDE(Problem,Population,Population(randi(Problem.N,1,Problem.N)),Population(randi(Problem.N,1,Problem.N)));
                Population = EnvironmentalSelection(Population,Offspring,Problem.N);
            end
        end
    end
end


function [KB] = TB2KB(TB)
% Convert computery things from terabytes to kilobytes.
% Chad A. Greene 2012
KB = TB*1073741824 ;


function rx = rxSaveBestrotvol(rx,savePath);
%
% rxSaveBestrotvol([rx],[savePath]);
%
% Save a mrAlign3 bestrotvol.mat file.
%
% ras 03/05
if ieNotDefined('rx')
    cfig = findobj('Tag','rxControlFig');
    rx = get(cfig,'UserData');
end

if ieNotDefined('savePath')
    savePath = fullfile(pwd,'bestrotvol.mat');
end

newXform = rx.xform;

A = newXform(1:3,1:3);
b = newXform(1:3,4)';

% account for scale factors
scaleFac(1,:) = 1./rx.rxVoxelSize;
scaleFac(2,:) = 1./rx.volVoxelSize;
rot = diag(1./scaleFac(2,:))*A*diag(scaleFac(1,:));
trans = b ./ scaleFac(2,:);

save(savePath,'rot','trans','scaleFac');
fprintf('Saved %s.\n',savePath);

return


classdef Max < Algorithm

    methods (Access = public)

        function obj = Max()
            obj.name = 'Max';
            obj.inputPort = DataType.kSignal;
            obj.outputPort = DataType.kFeature;
        end

        function dataOut = compute(~,signal)
            dataOut = max(signal);
        end

        function metrics = computeMetrics(~,input)
            n = size(input,1);
            flops = 1 * n;
            memory = 1;
            outputSize = Constants.kFeatureBytes;
            metrics = Metric(flops,memory,outputSize);
        end
    end
end


function []=fdisp(Y,n,T,endo,stringdates2,decimaldates2,Fstartlocation,Fendlocation,forecast_estimates,pref)

% function []=fdisp(Y,n,T,endo,stringdates2,decimaldates2,Fstartlocation,Fendlocation,forecast_estimates,datapath)
% plots the results for unconditional forecasts
% inputs:  - matrix 'Y': matrix of regressands for the VAR model (defined in 1.1.8)
%          - integer 'n': number of endogenous variables in the BVAR model (defined p 7 of technical guide)
%          - integer 'T': number of sample time periods (defined p 7 of technical guide)
%          - cell 'endo': list of endogenous variables of the model
%          - cell 'stringdates2': date strings for the sample+forecasts period
%          - vector 'decimaldates2': dates converted into decimal values, for the sample+forecasts period
%          - integer 'Fstartlocation': position of the forecast start date in stringdates2
%          - integer 'Fendlocation': position of the forecast end date in stringdates2
%          - cell 'forecast_estimates': lower bound, point estimates, and upper bound for the unconditional forecasts
%          - string 'datapath': user-supplied path to excel data spreadsheet
% outputs: none

% first, create a cell that will store the data to be plot
plotdata=cell(n,1);

% each cell entry is a matrix of actual and forecast values
% this matrix comprises 4 rows: the first row is actual data, while the three other rows are the estimates (point estimates and confidence bands) for the forecasts
% also, this matrix has a number of rows equal to the dimension of decimaldates2, which comprises the total period sample+forecasts

% loop over variables

for ii=1:n
   plotdata{ii,1}=nan(4,size(decimaldates2,1));
   % record actual sample values
   plotdata{ii,1}(1,1:T)=Y(:,ii)';
   % copy the last point of the actual sample for the forecast part of the matrix (required to have a clean plot)
   plotdata{ii,1}(:,Fstartlocation-1)=repmat(Y(Fstartlocation-1,ii),4,1);
   % record forecast, lower bound
   plotdata{ii,1}(2,Fstartlocation:Fendlocation)=forecast_estimates{ii,1}(1,:);
   % record forecast, point estimate
   plotdata{ii,1}(3,Fstartlocation:Fendlocation)=forecast_estimates{ii,1}(2,:);
   % record forecast, upper bound
   plotdata{ii,1}(4,Fstartlocation:Fendlocation)=forecast_estimates{ii,1}(3,:);
end

if pref.plot

% create forecast figure
% then plot actual vs. fitted
forecast=figure('Tag','BEARresults');
set(forecast,'Color',[0.9 0.9 0.9]);
set(forecast,'name','unconditional forecasts');
ncolumns=ceil(n^0.5);
nrows=ceil(n/ncolumns);
for ii=1:n
subplot(nrows,ncolumns,ii);
hold on
Xpatch=[decimaldates2(Fstartlocation-1:Fendlocation,1)' fliplr((decimaldates2(Fstartlocation-1:Fendlocation,1))')];
Ypatch=[plotdata{ii,1}(2,Fstartlocation-1:Fendlocation) fliplr(plotdata{ii,1}(4,Fstartlocation-1:Fendlocation))];
Fpatch=patch(Xpatch,Ypatch,[0.7 0.78 1]);
set(Fpatch,'facealpha',0.6);
set(Fpatch,'edgecolor','none');
plot(decimaldates2,plotdata{ii,1}(3,:),'Color',[0.4 0.4 1],'LineWidth',2);
plot(decimaldates2,plotdata{ii,1}(1,:),'Color',[0 0 0],'LineWidth',2);
hold off
set(gca,'XLim',[decimaldates2(1,1) decimaldates2(end,1)],'FontName','Times New Roman');
set(gca,'XGrid','on');
set(gca,'YGrid','on');
title(endo{ii,1},'FontName','Times New Roman','FontSize',10,'FontWeight','normal','Interpreter','none');
end

end % pref.plot
% finally, save on excel
bear.data.excelrecord5fcn(stringdates2, endo, plotdata, n, pref)


function [f,g] = detGrad(fun,x0,xdata)
%DETGRAD  Determine whether supplied function contains gradient information

%   Copyright (C) 2011 Jonathan Currie (IPL)

%Sort out gradient (unfortunately rather inefficient)
no = nargout(fun);

if(no == 1)
    f = fun;
    g = [];
elseif(no == 2)
        f = @(x) fval(fun,x);
        g = @(x) gval(fun,x);
elseif(no < 0)
    %Either anonymous function or varargout (i.e. deal?)
    try
        if(nargin(fun) > 1)
            fun(x0,xdata);
        else
            fun(x0);
        end
        f = fun;
        g = [];
    catch me
        try
            [~,~] = fun(x0);
            f = @(x) fval(fun,x);
            g = @(x) gval(fun,x);
        catch
            error(['Unknown function / gradient format: ' me.message])
        end
    end

else
    error('Unknown function / gradient format');
end

%Dummy functions
function f = fval(fun,x)
[f,~] = fun(x);

function g = gval(fun,x)
[~,g] = fun(x);


function exampleFilter
% function exampleFilter
%
% Example of how the Kalman filter performs for real data

load raw

%Apply filter
k=Kalman_Stack_Filter(raw);
k75=Kalman_Stack_Filter(raw,0.75);

%Set up image window
minMax=[min(raw(:)),max(raw(:))];
clf, colormap gray

subplot(1,3,1)
imagesc(raw(:,:,1))
title('original')
set(gca,'clim',minMax), axis off equal

subplot(1,3,2)
imagesc(k(:,:,1))
title('filtered, gain=0.5')
set(gca,'clim',minMax), axis off equal

subplot(1,3,3)
imagesc(k75(:,:,1))
title('filtered, gain=0.75')
set(gca,'clim',minMax), axis off equal

%Loop movie
disp('crtl-c to stop movie')
while 1
    for i=1:size(k,3)

        subplot(1,3,1)
        set(get(gca,'children'),'CData',raw(:,:,i))

        subplot(1,3,2)
        set(get(gca,'children'),'CData',k(:,:,i))

        subplot(1,3,3)
        set(get(gca,'children'),'CData',k75(:,:,i))

        pause(0.05)
        drawnow
    end
end


function [segclassifier] = mcmcTrainSegmentationClassifier2(features, labels, weights, maxdata, classparams)

if exist('classparams') && ~isempty(classparams)
    nnodes = classparams(1);
    ntrees = classparams(2);
    stopval = classparams(3);
else
    ntrees = 20;
    nnodes = 8;
    stopval = 0;
end

if ~exist('maxdata') || isempty(maxdata)
    maxdata = 25000;
end

[data, lab, w] = formatData(features, labels, weights, maxdata);

segclassifier = train_boosted_dt_2c(data, [], lab, ntrees, nnodes, stopval, w);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [data, lab, w] = formatData(features, labels, weights, maxdata)
% concatenate data
%disp(num2str(maxdata))
nimages = numel(features);

[tmp, nvars] = size(features{1});

% count segments
tseg = 0;
nseg = 0;
for f = 1:nimages
    nseg = nseg + sum((labels{f}~=0) & (weights{f}>0));
    tseg = tseg + numel(labels{f});
end
%disp(num2str([nseg tseg]))

data = zeros(nseg, nvars);
lab = zeros(nseg, 1);
w = zeros(nseg, 1);

% concatenate data
vc = 0;
for f = 1:nimages
    ind = find((labels{f}~=0) & (weights{f}>0));
    data(vc+1:vc+numel(ind), :) = features{f}(ind, :);
    lab(vc+1:vc+numel(ind)) = (labels{f}(ind)>0)*2-1;
    w(vc+1:vc+numel(ind)) = weights{f}(ind); % weight according to area in image
    vc = vc + numel(ind);
end

if nseg > maxdata
    rind = randperm(nseg);
    rind = rind(1:maxdata);
    data = data(rind, :);
    lab = lab(rind);
    w = w(rind);
end

w = w / sum(w);


function varargout=m2v(varargin)
%
% vol=m2v(node,face,Nxyz)
%  or
% vol=m2v(node,face,xi,yi,zi)
%
% shortcut for mesh2vol, rasterizing a teterahedral mesh to a volume using graphics
%
% author: Qianqian Fang (q.fang at neu.edu)
%
% input/output: please see details in the help for mesh2vol
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

[varargout{1:nargout}]=mesh2vol(varargin{:});


function info = vl_simplenn_display(net, res)
% VL_SIMPLENN_DISPLAY  Simple CNN statistics
%    VL_SIMPLENN_DISPLAY(NET) prints statistics about the network NET.

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

fields={'layer', 'type', 'support', 'stride', 'pad', 'dim', 'fdim', 'field', 'mem'};
if nargin > 1
  fields = {fields{:}, 'xwhd', 'xmem', 'dxmem'} ;
end

do_print = (nargout == 0) ;

for w=fields
  switch char(w)
    case 'type', s = 'type' ;
    case 'stride', s = 'stride' ;
    case 'padding', s = 'pad' ;
    case 'field', s = 'rec. field' ;
    case 'dim', s = 'out dim' ;
    case 'fdim', s = 'filt dim' ;
    case 'mem', s = 'c/g net KB' ;
    case 'xwhd', s = 'x w/h/d' ;
    case 'xmem', s = 'c/g x MB' ;
    case 'dxmem', s = 'c/g dx MB' ;
    otherwise, s = char(w) ;
  end
  if do_print, fprintf('%10s',s) ; end
  for l=1:numel(net.layers)
    ly=net.layers{l} ;
    switch char(w)
      case 'layer', s=sprintf('%d', l) ;
      case 'type'
        switch ly.type
          case 'normalize', s='nrm';
          case 'pool', if strcmpi(ly.method,'avg'), s='apool'; else s='mpool'; end
          case 'conv', s='cnv' ;
          case 'softmax', s='sftm' ;
          case 'loss', s='lloss' ;
          case 'softmaxloss', 'sftml' ;
          otherwise s=ly.type ;
        end
      case 'support'
        switch ly.type
          case 'conv', support(1:2,l) = max([size(ly.filters,1) ; size(ly.filters,2)],1) ;
          case 'pool', support(1:2,l) = ly.pool(:) ;
          otherwise, support(1:2,l) = [1;1] ;
        end
        s=sprintf('%dx%d', support(1,l), support(2,l)) ;
      case 'fdim'
        switch ly.type
          case 'conv'
            filterDimension(l) = size(ly.filters,3) ;
            s=sprintf('%d', filterDimension(l)) ;
          otherwise
            filterDimension(l) = 0 ;
            s='n/a' ;
        end
      case 'stride'
        switch ly.type
          case {'conv', 'pool'}
            if numel(ly.stride) == 1
              stride(1:2,l) = ly.stride ;
            else
              stride(1:2,l) = ly.stride(:) ;
            end
          otherwise, stride(1:2,l)=1 ;
        end
        if all(stride(:,l)==stride(1,l))
          s=sprintf('%d', stride(1,l)) ;
        else
          s=sprintf('%dx%d', stride(1,l), stride(2,l)) ;
        end
      case 'pad'
        switch ly.type
          case {'conv', 'pool'}
            if numel(ly.pad) == 1
              pad(1:4,l) = ly.pad ;
            else
              pad(1:4,l) = ly.pad(:) ;
            end
          otherwise, pad(1:4,l)=0 ;
        end
        if all(pad(:,l)==pad(1,l))
          s=sprintf('%d', pad(1,l)) ;
        else
          s=sprintf('%d,%dx%d,%d', pad(1,l), pad(2,l), pad(3,l), pad(4,l)) ;
        end
      case 'field'
        for i=1:2
          field(i,l) = sum(cumprod([1 stride(i,1:l-1)]).*(support(i,1:l)-1))+1 ;
        end
        if all(field(:,l)==field(1,l))
          s=sprintf('%d', field(1,l)) ;
        else
          s=sprintf('%dx%d', field(1,l), field(2,l)) ;
        end
      case 'mem'
        [a,b] = xmem(ly) ;
        mem(1:2,l) = [a;b] ;
        s=sprintf('%.0f/%.0f', a/1024, b/1024) ;
      case 'dim'
        switch ly.type
          case 'conv', dimension(1,l) = size(ly.filters,4) ;
          otherwise
            if l > 1
              dimension(1,l) = dimension(1,l-1) ;
            end
        end
        s=sprintf('%d', dimension(1,l)) ;
      case 'xwhd'
        for d=1:4, sz(d) = size(res(l+1).x,1) ; end
        s=sprintf('%dx%dx%d%d', sz(1), sz(2), sz(3), sz(4)) ;
      case 'xmem'
        [a,b]=xmem(res(l+1).x) ;
        rmem(1:2,l) = [a;b] ;
        s=sprintf('%.0f/%.0f', a/1024^2, b/1024^2) ;
      case 'dxmem'
        [a,b]=xmem(res(l+1).dzdx) ;
        rmem(1:2,l) = [a;b] ;
        s=sprintf('%.0f/%.0f', a/1024^2, b/1024^2) ;
    end
    if do_print, fprintf('|%7s', s) ; end
  end
  if do_print, fprintf('|\n') ; end
end
if do_print
  [a,b] = xmem(net) ;
  fprintf('total network CPU/GPU memory: %.1f/%1.f MB\n', a/1024^2, b/1024^2) ;
  if nargin > 1
    [a,b] = xmem(res) ;
    fprintf('total result CPU/GPU memory: %.1f/%1.f MB\n', a/1024^2, b/1024^2) ;
  end
end

if nargout > 0
  info.support = support ;
  info.receptiveField = field ;
  info.stride = stride ;
  info.pad = pad ;
end

% -------------------------------------------------------------------------
function [cpuMem,gpuMem] = xmem(s, cpuMem, gpuMem)
% -------------------------------------------------------------------------
if nargin <= 1
  cpuMem = 0 ;
  gpuMem = 0 ;
end
if isstruct(s)
  for f=fieldnames(s)'
    f = char(f) ;
    for i=1:numel(s)
      [cpuMem,gpuMem] = xmem(s(i).(f), cpuMem, gpuMem) ;
    end
  end
elseif iscell(s)
  for i=1:numel(s)
    [cpuMem,gpuMem] = xmem(s{i}, cpuMem, gpuMem) ;
  end
elseif isnumeric(s)
  if isa(s, 'single')
    mult = 4 ;
  else
    mult = 8 ;
  end
  if isa(s,'gpuArray')
    gpuMem = gpuMem + mult * numel(s) ;
  else
    cpuMem = cpuMem + mult * numel(s) ;
  end
end