function obj=stat_fit(obj,varargin)
% stat_fit() Display a custom fit of the data
%
% Example syntax gramm_object.stat_fit('fun',@(alpha,beta,x)alpha*cos(x-beta),'disp_fit',true)
%
% This fuction uses the curve fitting toolbox function fit() to
% fit a provided anonymous function with arguments
% (param1,param2,...paramN,x) to the data.
% Parameters:
% - 'fun': anonymous function used for the fit
% - 'StartPoint': Array containing starting values for the
% parameter to be fitted [start_param1,start_param2,...start_paramN]
% - 'intopt': Option passed to predint() for the type of bounds
% to compute, 'observation' for bounds of a new observation
% (default), or 'functional' for bounds of the fitted curve.
% - 'geom', 'fullrange', 'disp_fit' options: see stat_glm()
% - 'fullrange': set to true if you want the fits to be
%   displayed over the whole width of each subplot instead of
%   being displayed over the range of x values used for the fit
% - 'disp_fit': set to true to display the fitted parameters

p=inputParser;
my_addParameter(p,'fun',@(a,b,x)a*x+b);
my_addParameter(p,'StartPoint',[]);
my_addParameter(p,'intopt','observation');
my_addParameter(p,'geom','area');
my_addParameter(p,'fullrange',false);
my_addParameter(p,'disp_fit',false);
parse(p,varargin{:});
obj.geom=vertcat(obj.geom,{@(dobj,dd)my_fit(dobj,dd,p.Results)});
obj.results.stat_fit={};
end

function hndl=my_fit(obj,draw_data,params)

combx=comb(draw_data.x);
comby=comb(draw_data.y);

%Remove NaNs
sel=~isnan(combx) & ~isnan(comby);
combx=combx(sel);
comby=comby(sel);

%Do the fit depending on options
if isempty(params.StartPoint)
    mdl=fit(shiftdim(combx),shiftdim(comby),params.fun);
else
    mdl=fit(shiftdim(combx),shiftdim(comby),params.fun,'StartPoint',params.StartPoint);
end

%Create x values for the fit plot
if params.fullrange
    newx=linspace(obj.var_lim.minx,obj.var_lim.maxx,100)';
else
    newx=linspace(min(combx),max(combx),100)';
end
%Get fit value and CI
newy=feval(mdl,newx);
yci=predint(mdl,newx,1-obj.stat_options.alpha,params.intopt);

obj.results.stat_fit{obj.result_ind,1}.x=newx;
obj.results.stat_fit{obj.result_ind,1}.y=newy;
obj.results.stat_fit{obj.result_ind,1}.yci=yci;
obj.results.stat_fit{obj.result_ind,1}.model=mdl;

%Plot fit
hndl=plotci(obj,newx,newy,yci,draw_data,params.geom);

%Store plotted handles
hnames=fieldnames(hndl);
for k=1:length(hnames)
    obj.results.stat_fit{obj.result_ind,1}.(hnames{k})=hndl.(hnames{k});
end

%Do we display the results ?
if params.disp_fit
    %Set Y position of display
    if obj.firstrun(obj.current_row,obj.current_column)
        obj.extra.mdltext(obj.current_row,obj.current_column)=0.05;
    else
        obj.extra.mdltext(obj.current_row,obj.current_column)=obj.extra.mdltext(obj.current_row,obj.current_column)+0.03;
    end
    %Get formula and parameters
    form=formula(mdl);
    cvals=coeffvalues(mdl);
    cnames=coeffnames(mdl);
    %Replace parameter names by their value in the formula
    for c=1:length(cnames)
        form=strrep(form,cnames{c},num2str(cvals(c),2));
    end
    obj.results.stat_fit{obj.result_ind,1}.text_handle=text('Units','normalized','Position',[0.1 obj.extra.mdltext(obj.current_row,obj.current_column)],'color',draw_data.color,...
        'String',form);
end

end


function corrplot(c)

% Called internally by correlation/plot to plot correlation matrix.

% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks
% $Date$
% $Revision$

% PREP PLOT
figure('Color','w','Position',[50 50 600 500]);
set(gcf,'DefaultAxesFontSize',14);
imagesc(c.C);
title('Maximum correlation coefficient');

% ADD DATES TO AXES
n = length(c.trig);
set(gca,'XTick',[1:round(n/25):n]);
set(gca,'YTick',[1:round(n/25):n]);
yt = get(gca,'YTick');
set(gca,'YTickLabel',datestr(c.trig(yt),'yyyy-mm-dd HH:MM'),'FontSize',6);

%xt = get(gca,'XTick');
%set(gca,'XTickLabel',datestr(c.trig(xt),'yyyy-mm-dd HH:MM'),'FontSize',6,'Rotation',90);

% DRESS UP THE FIGURE
caxis([0 1]);
cmap = load('colormap_corr.txt');
colormap(cmap);
colorbar;
xlabel('Event number');
ylabel('Event date');

%PRINT OUT FIGURE
set(gcf, 'paperorientation', 'portrait');
set(gcf, 'paperposition', [1.25 2.5 6 6] );
%print(gcf, '-depsc2', 'FIG_tartan.ps');


classdef cluster

methods(Static)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Following functions are meant for assisting in
% setting up experiments.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    function labels = labels_from_cluster_sizes(cluster_sizes)
        % total number of points
        S = sum(cluster_sizes);
        % Number of points in array
        K = numel(cluster_sizes);
        labels = zeros(1, S);
        i = 0;
        for k=1:K
            Sk  = cluster_sizes(k);
            for s=1:Sk
                i = i+1;
                labels(i) = k;
            end
        end
        return;
    end

    function [cluster_sizes, labels] = cluster_sizes_from_labels(labels)
        tbl = tabulate(labels);
        labels = tbl(:, 1)';
        cluster_sizes =  tbl(:, 2)';
    end

    function [start_indices, end_indices] = start_end_indices(cluster_sizes)
        % Returns start and end indices from cluster sizes
        start_indices = cumsum(cluster_sizes) + 1;
        start_indices = [1 start_indices(1:end-1)];
        end_indices = start_indices + cluster_sizes -1;
    end

    function result = clustering_error(estimated_labels, true_labels, num_clusters)
        % finds out an appropriate mapping between
        % true labels and estimated labels and
        % calculates the corresponding clustering error

        % make sure that both are row vectors
        if ~isrow(estimated_labels)
            estimated_labels = estimated_labels';
        end
        if ~isrow(true_labels)
            true_labels = true_labels';
        end
        if size(estimated_labels) ~= size(true_labels)
            error('Both estimated and true label arrays should have same size.');
        end
        % Let us consider all possible mappings
        possible_mappings = perms(1:num_clusters);
        % number of possible mappings
        num_mappings = size(possible_mappings,1 );
        % number of labels
        num_labels = size(estimated_labels, 2);
        % number of misclustered points for each mapping
        missed_points = zeros(num_mappings, 1);
        for j=1:num_mappings
            %cur_mapping = possible_mappings(j, :)
            mapped_labels = possible_mappings(j, true_labels);
            missed_points(j) = sum(estimated_labels ~= mapped_labels);
        end
        % missed_points
        % we choose the mapping with minimum mismatch
        [miss, index] = min(missed_points, [], 1);
        % final clustering error value
        result.num_labels = num_labels;
        result.num_missed_points = miss;
        result.error  = miss / num_labels;
        result.error_perc = result.error * 100;
        % corresponding mapping
        result.mapping = possible_mappings(index, :);
        result.mapped_labels = result.mapping(true_labels);
        result.misses = estimated_labels ~= result.mapped_labels;
    end

    function result = clustering_error_hungarian_mapping(estimated_labels, true_labels, num_clusters)
        % make sure that both are row vectors
        if ~isrow(estimated_labels)
            estimated_labels = estimated_labels';
        end
        if ~isrow(true_labels)
            true_labels = true_labels';
        end
        if size(estimated_labels) ~= size(true_labels)
            error('Both estimated and true label arrays should have same size.');
        end
        % number of labels
        num_labels = size(estimated_labels, 2);
        mapped_labels = bestMap(estimated_labels, true_labels)';
        miss = sum(estimated_labels ~= mapped_labels);
        % final clustering error value
        result.num_labels = num_labels;
        result.num_missed_points = miss;
        result.error  = miss / num_labels;
        result.error_perc = result.error * 100;
        result.mapped_labels = mapped_labels;
        result.misses = estimated_labels ~= result.mapped_labels;
    end

end

end


% main file

close all
clear all

% read Template image
im1=imread('K.bmp');
%im1=imread('S.bmp');
%im1=imread('image1.jpg');

% read Traget Image
im2=imread('letters.bmp');
%im2=imread('image2.jpg');

% apply templete matching using power of the image
result1=tmp(im1,im2);

figure,
subplot(2,2,1),imshow(im1);title('Template');
subplot(2,2,2),imshow(im2);title('Target');
subplot(2,2,3),imshow(result1);title('Matching Result using tmp');

% apply templete matching using DC components of the image
result2=tmc(im1,im2);

figure,
subplot(2,2,1),imshow(im1);title('Template');
subplot(2,2,2),imshow(im2);title('Target');
subplot(2,2,3),imshow(result2);title('Matching Result using tmc');


function E = edges4connected(height,width)

% EDGE4CONNECTED Creates edges where each node
%   is connected to its four adjacent neighbors on a
%   height x width grid.
%   E - a vector in which each row i represents an edge
%   E(i,1) --> E(i,2). The edges are listed is in the following
%   neighbor order: down,up,right,left, where nodes
%   indices are taken column-major.
%
%   (c) 2008 Michael Rubinstein, WDI R&D and IDC
%   $Revision$
%   $Date$
%

N = height*width;
I = []; J = [];
% connect vertically (down, then up)
is = [1:N]'; is([height:height:N])=[];
js = is+1;
I = [I;is;js];
J = [J;js;is];
% connect horizontally (right, then left)
is = [1:N-height]';
js = is+height;
I = [I;is;js];
J = [J;js;is];

E = [I,J];

end


function [Cext,val] = extendLSAPEinstance(C,val)
% Extend a cost matrix for error-correcting matching to its square version
%
%  [Cext,val] = extendCostMtx(C,val)
%
%  inputs:
%  C (n+1)x(m+1) cost matrix of an error-correcting bipartite graph
%  val the value used to fill 2nd and 3rd block of Cext (optional)
%  val = max(max(C)) + 1 if not given
%
%  outputs:
%  Cext (n+m)x(m+n) extended cost matrix
%  valcpt (optional) is the value val used to fill 2nd and 3rd block of
%  Cext
%
%         | c(1,1)   ...  c(1,m-1)  | c(1,m) val   ...      val   |
%         |   .              .      |  val  c(2,m) val ...   .    |
%         |   .              .      |   .                   val   |
%         | c(n-1,1) ... c(n-1,m-1) |  val     ...   val c(n-1,m) |
%  Cext =  -------------------------------------------------------
%         | c(n,1) val  ...    val  |                             |
%         |  val c(n,2) val ..  .   |           0_{m,n}           |
%         |   .                val  |                             |
%         |  val  ...  val c(n,m-1) |                             |
%
%
%   author: Sebastien Bougleux
%   institution: Normandie Univ, UNICAEN, ENSICAEN, CNRS, GREYC
% -----------------------------------------------------------
% This file is part of LSAPE.
% LSAPE is free software: you can redistribute it and/or modify
% it under the terms of the CeCILL-C License. See README file
% for more details.
% -----------------------------------------------------------

    if ~exist('val','var') || nargin == 1
        val = max(max(C)) + 1;
    end

    D = val .* cast(ones(size(C,1)-1),class(C));
    E = val .* cast(ones(size(C,2)-1),class(C));
    D(logical(eye(size(D)))) = C(1:end-1,end);
    E(logical(eye(size(E)))) = C(end,1:end-1);
    Cext = [[C(1:end-1,1:end-1),D];[E,zeros(size(C,2)-1,size(C,1)-1)]];

end


classdef trigdouble < chebdouble
%FOURDOUBLE   Fourier double class.
%
%   See the CHEBDOUBLE class for details.
%
%   This class in intended solely as a worker-class for PDESOLVE.

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

    methods

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CLASS CONSTRUCTOR:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        function obj = trigdouble(varargin)

            % Call the CHEBDOUBLE constructor:
            obj = obj@chebdouble(varargin{:});

        end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CLASS METHODS:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  DIFF  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        function u = diff(u, k)
            %DIFF   Compute the k-th derivative of u using Fourier
            % differentiation matrices defined by diffmat.

            % Store the diffmat D as a persistent variable to allow speeding up
            % if we work with the same discretization at multiple time steps.
            % Note that the matrix D is independent of the domain, since it is
            % scaled separately below.
            persistent D

            % Assume first-order derivative:
            if ( nargin == 1 )
                k = 1;
            end

            N = length(u.values);

            % Construct D if we don't match a previous discretization:
            if ( isempty(D) || numel(D) < k || size(D{k}, 1) ~= N )
                D{k} = trigcolloc.diffmat(N, k); % Diffmat
            end

            % Interval scaling. (Note: trigtech.diffmat is defined on [0, 2*pi))
            c = 2/diff(u.domain);

            % Muliplying by the kth-order differentiation matrix:
            u.values = c^k*(D{k}*u.values);

            % Update the difforder:
            u.diffOrder = u.diffOrder + k;

        end

        %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  SUM  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % The differential operators
        function I = sum(u, a, b)
            %SUM  Compute the integral of u.

            persistent W

            if ( nargin > 1 )
                % TODO: Add support.
                error('CHEBFUN:FOURDOUBLE:sum:notImplemented', ...
                    'Partial integrals not implemented yet.')
            end

            N = length(u.values);

            % Retrieve or compute weights:
            if ( N > 5 && numel(W) >= N && ~isempty(W{N}) )
                % Weights are already in storage!
            else
                c = diff(u.domain)/2; % Interval scaling.
                W{N} = c*trigtech.quadwts(N);
            end

            % Find the sum by muliplying by the weights vector:
            I = W{N}*u.values;

        end

        function I = integral(varargin)
            I = sum(varargin{:});
        end

        %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  CUMSUM  %%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % The differential operators
        function u = cumsum(u)
            %CUMSUM   Compute the indefinite integral of the Chebyshev
            %         interpolant to u.

            % TODO: Add support.
            error('CHEBFUN:FOURDOUBLE:cumsum:notImplemented', ...
                'CUMSUM not implemented yet.')

        end

        %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  FRED  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        function u = fred(K, u)
            %FRED  Fredholm operator with kernel K.
            %   FRED(K, U) computes the action of the Fredholm operator with
            %   kernel K on the Chebyshev interpolant to the points in the
            %   vector U.

            % TODO: Add support.
            error('CHEBFUN:FOURDOUBLE:fred:notImplemented', ...
                'FRED not implemented yet.')

        end

        %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  VOLT  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        function u = volt(K, u)
            %VOLT  Volterra operator with kernel K.
            %   VOLT(K, U) computes the action of the Volterra operator with
            %   kernel K on the Chebyshev interpolant to the points in the
            %   vector U.

            % TODO: Add support.
            error('CHEBFUN:FOURDOUBLE:volt:notImplemented', ...
                'VOLT not implemented yet.')

        end

        %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  FEVAL  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        function out = feval(u, y)
            %FEVAL  Evaluate polynomial interpolant of data {X_four, U} at a
            % point y using barycentric interpolation.

            persistent dom x

            n = length(u.values);
            udom = u.domain;

            if ( length(x) ~= n || isempty(dom) || ~all(dom == udom) )
                x = trigpts(n, dom);
                dom = udom;
            end

            out = trigBary(y, u.values, x, udom);

        end

    end

end


[K u] = sphere_wp;
h=trisurf(K,u(:,1),u(:,2),u(:,3));
set(h,'FaceColor',[0.7 0.7 0.7],'EdgeColor','none','FaceLighting','gouraud');
axis equal;
light('Position',[1 -1 0],'Style','infinite');
% light('Position',[10 10 10],'Style','infinite');
xlim([-2,10]);
ylim([-2,2]);
zlim([-2,2]);

% animation loop:
u0=u;
for t=0:0.02:5
    R=1+0.2*sin(10*t); % change radius
    x=0+4+3*sin(8.1234*t); % change x position
    u=R*u0;
    u(:,1)=u(:,1)+x;
    set(h,'Vertices',u);
    drawnow;
    pause(1/50);
end


function [h, compUpJV] =  lfmComputeH3JV(gamma1_p, gamma1_m, sigma2, t1, ...
    t2, preFactor, mode)

% LFMCOMPUTEH3JV Helper function for computing part of the LFMJV kernel.
% FORMAT
% DESC computes a portion of the LFMJV kernel.
% ARG gamma1 : Gamma value for first system.
% ARG gamma2 : Gamma value for second system.
% ARG sigma2 : length scale of latent process.
% ARG t1 : first time input (number of time points x 1).
% ARG t2 : second time input (number of time points x 1).
% ARG preFactor : precomputed constants.
% ARG mode: indicates the correct derivative.
% RETURN h : result of this subcomponent of the kernel for the given values.
%
% COPYRIGHT : Mauricio Alvarez, 2010

% KERN

% Evaluation of h

if nargout>1
    compUpJV{1} = lfmjvComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode);
    compUpJV{2} = lfmjvComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);
    h = preFactor(1)*compUpJV{1} + preFactor(2)*compUpJV{2};
else
    h = preFactor(1)*lfmjvComputeUpsilonMatrix(gamma1_p,sigma2, t1,t2, mode) ...
        + preFactor(2)*lfmjvComputeUpsilonMatrix(gamma1_m,sigma2, t1,t2, mode);
end


function output = calc_traversal_dist(ai)

% This function will generate position coordinates of chain code (ai). Number of
% harmonic elements (n), and number of points for reconstruction (m) must be
% specified.

    x_ = 0;
    y_ = 0;

    for i = 1 : size(ai, 2)
        x_ = x_ + sign(6 - ai(i)) * sign(2 - ai(i));
        y_ = y_ + sign(4 - ai(i)) * sign(ai(i));
        p(i, 1) = x_;
        p(i, 2) = y_;
    end

    output = p;

end


function xDup=dupEls(x,numTimes)
%%DUPELS Return a vector with the elements of the vector x duplicated
%        numTimes.
%
%INPUTS: x A vectors whose elements are to be duplicated.
% numTimes The number of times the elements in x are to be duplicated.
%
%OUTPUTS: xDup A vector the same orientation (row or column vector) as x
%              where the elements of x have been duplicated numTimes. For
%              example, if x=[1;2;3], then dupEls(x,3) returns
%              [1;1;1;2;2;2;3;3;3].
%
%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

xDim=length(x);
xDup=zeros(xDim*numTimes,1);

%If the input was a row vector.
if(size(x,1)==1)
    xDup=xDup';
end

sel=(0:(xDim-1))*numTimes;
for curDup=1:numTimes
    xDup(sel+curDup)=x;
end

end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.


function [r, s] = randInt(rangeNums, dimensions)
    start = rangeNums(1);
    last = rangeNums(2);
    r = start + (last - start) * rand(dimensions);
    r = round(r);
    s = sum(sum(r));
end


function A = HALS_spatial_thresh(Y, A, C, active_pixel, maxIter, sn)
%% run HALS by fixating all spatial components
% input:
%   Y:  d*T, fluorescence data
%   A:  d*K, spatial components
%   C:  K*T, temporal components
%   active_pixel, mask for pixels to be updated

% output:
%   A: d*K, updated spatial components

% Author: Pengcheng Zhou, Carnegie Mellon University, adapted from Johannes
% Friedrich's NIPS paper "Fast Constrained Non-negative Matrix
% Factorization for Whole-Brain Calcium Imaging Data

%% options for HALS
if nargin<5;    maxIter = 1;    end   %maximum iteration number
if nargin<4;    active_pixel=true(size(A));
elseif isempty(active_pixel)
    active_pixel = true(size(A));
else
    active_pixel = logical(active_pixel);
end     %determine nonzero pixels
if ~exist('sn', 'var')||isempty(sn)
    sn = GetSn(Y);
end
sn = reshape(sn, [], 1);
%% initialization
A(~active_pixel) = 0;
K = size(A, 2);     % number of components
Cmean = mean(C,2);
Ymean = mean(Y,2);
T = size(C,2);
U = double(Y*C'-T*(Ymean*Cmean'));
V = double(C*C'-T*(Cmean*Cmean'));
cc = diag(V);   % squares of l2 norm all all components
cc_thr = 3.0./sqrt(cc);

%% updating
for miter=1:maxIter
    for k=1:K
        if cc(k)==0
            continue;
        end
        tmp_ind = active_pixel(:, k);
        if sum(tmp_ind)==0
            A(:, k) = 0;
            continue;
        end
        ak = A(tmp_ind, k)+(U(tmp_ind, k)-A(tmp_ind,:)*V(:, k))/cc(k);
        ak(ak<sn(tmp_ind)*cc_thr(k)) = 0;
        A(tmp_ind, k) = ak;
    end
end


function ComparingSymmetry

incPhi = pi/180;

fileName = 'StressSymmetryTraction';
sPnormT = computeExperiment(incPhi,fileName);

fileName = 'StressSymmetryCompression';
sPnormC = computeExperiment(-incPhi,fileName);

end

function sPnorm = computeExperiment(incPhi,fileName)

txi = pi/2 - 0.2;%1083;
rho = 0.9;
q = 4;

phi = 0+incPhi;
pNorm = 'max';
print = false;
hMesh = 0.01;
hasToCaptureImage = true;

mx = SuperEllipseParamsRelator.mx(txi,rho,q);
my = SuperEllipseParamsRelator.my(txi,rho,q);

s.mx       = mx;
s.my       = my;
s.q        = q;
s.phi      = phi;
s.pNorm    = pNorm;
s.print    = print;
s.hMesh    = hMesh;
s.fileName = fileName;
s.hasToCaptureImage = false;
sN = StressNormSuperEllipseComputer(s);
sPnorm = sN.compute();
sN.printStress();

end


%returns the first component of the frequency representation of the signal
classdef SpectralEntropy < Algorithm

    methods (Access = public)

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

        %receives a power spectrum
        function result = compute(~,powerSpectrum)

            %Normalization
            sumPower = sum(powerSpectrum + 1e-12);
            powerSpectrum = powerSpectrum / sumPower;

            %entropy calculation
            result = -sum(powerSpectrum .* log2(powerSpectrum+eps));
        end

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


%%********************************************************************
%% blkbarrier: calculate
%% [-v(p)*logdet(X{p}),   v(p)*logdet(Z{p}) + n*v(p)*(1-log(v(p)))]
%% [-v(p)*log(gam(X{p})), v(p)*log(gam(Z{p})) + v(p)]
%% [-v(p)*log(X{p}),      v(p)*log(Z{p}) + n*v(p)*(1-log(v(p)))]
%%********************************************************************

  function objadd = blkbarrier(blk,X,Z,Xchol,Zchol,v);

   objadd = zeros(1,2); tmp = zeros(1,2);
   for p = 1:size(blk,1)
      pblk = blk(p,:);
      vp = v{p};
      idx = find(vp > 0);
      if ~isempty(idx)
         vpsub = vp(idx);
         if size(vpsub,1) < size(vpsub,2); vpsub = vpsub'; end
         if strcmp(pblk{1},'s')
            ss = [0, cumsum(pblk{2})];
            logdetX = 2*log(diag(Xchol{p}));
            logdetZ = 2*log(diag(Zchol{p}));
            logdetXsub = zeros(length(idx),1);
            logdetZsub = zeros(length(idx),1);
            for k = 1:length(idx)
               idxtmp = [ss(idx(k))+1:ss(idx(k)+1)];
               logdetXsub(k) = sum(logdetX(idxtmp));
               logdetZsub(k) = sum(logdetZ(idxtmp));
            end
            tmp(1) = -sum(vpsub.*logdetXsub);
            tmp(2) = sum(vpsub.*logdetZsub + (pblk{2}(idx)').*vpsub.*(1-log(vpsub)));
         elseif strcmp(pblk{1},'q')
            gamX = sqrt(qops(pblk,X{p},X{p},2));
            gamZ = sqrt(qops(pblk,Z{p},Z{p},2));
            tmp(1) = -sum(vpsub.*log(gamX(idx)));
            tmp(2) = sum(vpsub.*log(gamZ(idx)) + vpsub);
         elseif strcmp(pblk{1},'l')
            logX = log(X{p}); logZ = log(Z{p});
            tmp(1) = -sum(vpsub.*logX(idx));
            tmp(2) = sum(vpsub.*logZ(idx) + vpsub.*(1-log(vpsub)));
         end
         objadd = objadd + tmp;
      end
   end
%%********************************************************************


function [ class, clsize, critvl, ntrans, ifault ] = swap ( varval, class, ...
  clsize, in, ik, iv, critvl, ntrans, ifault )

%*****************************************************************************80
%
%% SWAP interchanges objects between different classes to improve a criterion.
%
%  Discussion:
%
%    This routine is given a classification of objects, including the
%    number of objects in each class, and the current value of some criterion
%    which is desired to be minimized.
%
%    The routine calculates the change in criterion for all possible swaps,
%    that is, operations in which two objects in different classes exchange
%    places. Each swap that would result in a lowering of the criterion is
%    executed, and the related quantities are updated.
%
%    When no more advantageous swaps can be found, the routine returns.
%
%    The routine relies on a user-supplied routine, CRSWAP, to report the
%    expected change in the criterion for a given swap, and to carry
%    out that transfer if requested.
%
%    The variables CLASS and CRITVL have been added to the argument list
%    of CRSWAP.
%
%    Also, the order of the two classes "L" and "M" was interchanged in
%    the call to CRSWAP.  The original order was counterintuitive.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 February 2008
%
%  Author:
%
%    Original FORTRAN77 version by Banfield, Bassill.
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Colin Banfield, LC Bassill,
%    Algorithm AS 113:
%    A transfer for non-hierarchichal classification,
%    Applied Statistics,
%    Volume 26, Number 2, 1977, pages 206-210.
%
%  Parameters:
%
%    Input, real VARVAL(IN,IV), the data values.  There are
%    IN objects, each having spatial dimension IV.
%
%    Input, integer CLASS(IN), the initial classification of
%    each object.
%
%    Input, integer CLSIZE(IK), the initial number of objects
%    in each class.
%
%    Input, integer IN, the number of objects.
%
%    Input, integer IK, the number of classes.
%
%    Input, integer IV, the number of spatial dimensions,
%    or variates, of the objects.
%
%    Input, real CRITVL, the initial value of the criterion.
%
%    Output, integer CLASS(IN), the classification of
%    each object.
%
%    Output, integer CLSIZE(IK), the number of objects
%    in each class.
%
%    Output, real CRITVL, the current value of the criterion.
%
%    Output, integer NTRANS, the number of transfers executed.
%
%    Output, integer IFAULT, error indicator.
%    0, no error detected.
%    1, the number of classes was less than 2.
%    2, the number of objects was less than the number of classes.
%
  eps = 1.0E-38;
  ntrans = 0;

  if ( ik <= 1 )
    ifault = 1
    return
  end

  if ( in <= ik )
    ifault = 2;
    return
  end

  ifault = 0;
  icount = 0;
  itop = ( in * ( in - 1 ) ) / 2;

  i = 1;

  while ( 1 )

    i = i + 1;

    if ( itop <= icount )
      break
    end

    if ( in < i )
      i = 1;
      continue
    end

    l = class(i);
    k = l;
    it = i - 1;
%
%  Test the swap of object I from class M to L,
%  and object J from class L to M.
%
    for j = 1 : it

      icount = icount + 1;
      m = class(j);

      if ( l ~= j )

        if ( clsize(l) ~= 1 | clsize(m) ~= 1 )

          iswitch = 1;
          inc = crswap ( varval, class, clsize, in, ik, iv, critvl, ...
            i, j, l, m, iswitch );

          if ( inc < - eps )

            critvl = critvl + inc;
            icount = 0;

            iswitch = 2;
            crswap ( varval, class, clsize, in, ik, iv, critvl, ...
              i, j, l, m, iswitch );

            ntrans = ntrans + 1;
            class(i) = m;
            class(j) = l;
            l = m;

          end

        end
      end

    end

  end

  return
end


function jrt=jacprojRT(j, i, rt, xyz, r0, a)
% symbolic projection function Jacobian
% code automatically generated with maple

  qr0=r0(j*4+1:(j+1)*4);

  t1 = (rt(1) ^ 2);
  t2 = (rt(2) ^ 2);
  t3 = (rt(3) ^ 2);
  t5 = sqrt((1 - t1 - t2 - t3));
  t6 = 0.1e1 / t5;
  t7 = t6 * qr0(2);
  t9 = -t7 * rt(1) + qr0(1);
  t11 = t6 * qr0(3);
  t13 = -t11 * rt(1) - qr0(4);
  t15 = t6 * qr0(4);
  t17 = -t15 * rt(1) + qr0(3);
  t19 = -t9 * xyz(1) - t13 * xyz(2) - t17 * xyz(3);
  t24 = -t5 * qr0(2) - qr0(1) * rt(1) - rt(2) * qr0(4) + rt(3) * qr0(3);
  t31 = t5 * qr0(3) + qr0(1) * rt(2) + rt(3) * qr0(2) - rt(1) * qr0(4);
  t37 = t5 * qr0(4) + qr0(1) * rt(3) + rt(1) * qr0(3) - rt(2) * qr0(2);
  t39 = t24 * xyz(1) - t31 * xyz(2) - t37 * xyz(3);
  t41 = t6 * qr0(1);
  t43 = -t41 * rt(1) - qr0(2);
  t48 = t5 * qr0(1) - rt(1) * qr0(2) - rt(2) * qr0(3) - rt(3) * qr0(4);
  t52 = t48 * xyz(1) + t31 * xyz(3) - t37 * xyz(2);
  t57 = t43 * xyz(1) + t13 * xyz(3) - t17 * xyz(2);
  t62 = t43 * xyz(2) + t17 * xyz(1) - t9 * xyz(3);
  t67 = t48 * xyz(2) + t37 * xyz(1) + t24 * xyz(3);
  t72 = t43 * xyz(3) + t9 * xyz(2) - t13 * xyz(1);
  t77 = t48 * xyz(3) - t24 * xyz(2) - t31 * xyz(1);
  t89 = -t19 * t31 - t39 * t13 + t43 * t67 + t48 * t62 + t72 * t24 - t77 * t9 + t57 * t37 + t52 * t17;
  t99 = -t19 * t37 - t39 * t17 + t43 * t77 + t48 * t72 - t57 * t31 - t52 * t13 - t62 * t24 + t67 * t9;
  t106 = -t39 * t37 + t48 * t77 - t52 * t31 - t67 * t24 + rt(6);
  t107 = 0.1e1 / t106;
  t119 = -t39 * t31 + t48 * t67 + t77 * t24 + t52 * t37 + rt(5);
  t123 = t106 ^ 2;
  t124 = 0.1e1 / t123;
  t125 = (a(1) * (t39 * t24 + t48 * t52 - t67 * t37 + t77 * t31 + rt(4)) + a(2) * t119 + a(3) * t106) * t124;
  t129 = -t7 * rt(2) + qr0(4);
  t132 = -t11 * rt(2) + qr0(1);
  t135 = -t15 * rt(2) - qr0(2);
  t137 = -t129 * xyz(1) - t132 * xyz(2) - t135 * xyz(3);
  t141 = -t41 * rt(2) - qr0(3);
  t146 = t141 * xyz(1) + t132 * xyz(3) - t135 * xyz(2);
  t151 = t141 * xyz(2) + t135 * xyz(1) - t129 * xyz(3);
  t157 = t141 * xyz(3) + t129 * xyz(2) - t132 * xyz(1);
  t170 = -t137 * t31 - t39 * t132 + t141 * t67 + t48 * t151 + t157 * t24 - t77 * t129 + t146 * t37 + t52 * t135;
  t180 = -t137 * t37 - t39 * t135 + t141 * t77 + t48 * t157 - t146 * t31 - t52 * t132 - t151 * t24 + t67 * t129;
  t187 = -t7 * rt(3) - qr0(3);
  t190 = -t11 * rt(3) + qr0(2);
  t193 = -t15 * rt(3) + qr0(1);
  t195 = -t187 * xyz(1) - t190 * xyz(2) - t193 * xyz(3);
  t199 = -t41 * rt(3) - qr0(4);
  t204 = t199 * xyz(1) + t190 * xyz(3) - t193 * xyz(2);
  t209 = t199 * xyz(2) + t193 * xyz(1) - t187 * xyz(3);
  t215 = t199 * xyz(3) + t187 * xyz(2) - t190 * xyz(1);
  t228 = -t195 * t31 - t39 * t190 + t199 * t67 + t48 * t209 + t215 * t24 - t77 * t187 + t204 * t37 + t52 * t193;
  t238 = -t195 * t37 - t39 * t193 + t199 * t77 + t48 * t215 - t204 * t31 - t52 * t190 - t209 * t24 + t67 * t187;
  t255 = (a(4) * t119 + a(5) * t106) * t124;
  jrt(1) = (a(1) * (t19 * t24 - t39 * t9 + t43 * t52 + t48 * t57 - t62 * t37 - t67 * t17 + t72 * t31 + t77 * t13) + a(2) * t89 + a(3) * t99) * t107 - t125 * t99;
  jrt(2) = (a(1) * (t137 * t24 - t39 * t129 + t141 * t52 + t48 * t146 - t151 * t37 - t67 * t135 + t157 * t31 + t77 * t132) + a(2) * t170 + a(3) * t180) * t107 - t125 * t180;
  jrt(3) = (a(1) * (t195 * t24 - t39 * t187 + t199 * t52 + t48 * t204 - t209 * t37 - t67 * t193 + t215 * t31 + t77 * t190) + a(2) * t228 + a(3) * t238) * t107 - t125 * t238;
  jrt(4) = a(1) * t107;
  jrt(5) = a(2) * t107;
  jrt(6) = a(3) * t107 - t125;
  jrt(7) = (a(4) * t89 + a(5) * t99) * t107 - t255 * t99;
  jrt(8) = (a(4) * t170 + a(5) * t180) * t107 - t255 * t180;
  jrt(9) = (a(4) * t228 + a(5) * t238) * t107 - t255 * t238;
  jrt(10) = 0.0e0;
  jrt(11) = a(4) * t107;
  jrt(12) = a(5) * t107 - t255;


%% ARDRONE TEST

% Author: James A. Douthwaite

classdef ARdrone_LQR < ARdrone_prev
%% INITIALISE THE AGENT SPECIFIC PARAMETERS
    % LQR SPECIFIC PARAMETERS
    properties

    end
    %% ///////////////////////// MAIN METHODS /////////////////////////////
    methods
        % Constructor
        function this = ARdrone_LQR(varargin)

            % Call the super class
            this@ARdrone_prev(varargin);                                         % Create the super class 'agent'

            % DYNAMIC CONSTRAINTS
            this.v_nominal = 2.0;
            this.v_max = 3;

            % Append control parameter
            %obj.DYNAMICS.Q = diag([1 1 1 1 1 1 2 1 1 1 1 1])*1.5E1;
            this.DYNAMICS.Q = diag([1 1 1 1 1 1 1 1 1 1 1 1])*1.5E1;
            this.DYNAMICS.R = diag(ones(4,1))*1E-4;
            this.DYNAMICS.N = zeros(size(this.DYNAMICS.SS.B));        % Terminal input penalisation

            % Calculate the linear feedback from the LQR
            this.DYNAMICS.K_lqr = this.CreateController_LQR(...
                this.DYNAMICS.SS,...
                this.DYNAMICS.Q,...
                this.DYNAMICS.R,...
                this.DYNAMICS.N);

            % //////////////// Check for user overrides ///////////////////
            % - It is assumed that overrides to the properties are provided
            %   via the varargin structure.
            [this] = this.ApplyUserOverrides(varargin); % Recursive overrides
            % /////////////////////////////////////////////////////////////
        end
        % Setup
        % - The same as any 2D/3D object
        % Main
        function this = main(this,ENV,varargin)
            % INPUTS:
            % varargin - Cell array of inputs
            % >dt      - The timestep
            % >objects - The detectable objects cell array of structures
            % OUTPUTS:
            % obj      - The updated project

            % //////////// CHECK FOR NEW INFORMATION UPDATE ///////////////
            % UPDATE THE AGENT WITH THE NEW ENVIRONMENTAL INFORMATION
            this = this.GetAgentUpdate(ENV,varargin{1});

            % /////////////////// WAYPOINT TRACKING ///////////////////////
            % Get desired heading
            desiredHeadingVector = this.GetTargetHeading();
            desiredVelocity = desiredHeadingVector*this.v_nominal;

            % Express velocity vector in NED coordinates
            if ENV.currentTime <= 1
                desiredVelocity = zeros(3,1);
            end

            p_wp = this.targetWaypoint.position(:,this.targetWaypoint.sampleNum);

            % Convert from 'xyz' to 'ned'
%             desiredVelocity = enu2ned(desiredVelocity);
%             desiredNEDstate = [p_wp;zeros(3,1);zeros(6,1)];

            % LQR controller update
            this = this.Controller_position(ENV,enu2ned(p_wp));

%             this = this.Controller_velocity(ENV,enu2ned(desiredVelocity));

            % \\\\\\\\\\\\\\\ RECORD THE AGENT-SIDE DATA \\\\\\\\\\\\\\\\\\
            this.DATA.inputNames = {'$\dot{x}$ (m/s)','$\dot{y}$ (m/s)','$\dot{z}$ (m/s)',...
                                   '$\dot{\phi}$ (rad/s)','$\dot{\theta}$ (rad/s)','$\dot{\psi}$ (rad/s)'};
            this.DATA.inputs(1:numel(this.DATA.inputNames),ENV.currentStep) = this.localState(7:end);          % Record the control inputs
        end
    end

    %% /////////////////////// AUXILLARY METHODS //////////////////////////
    % CONTROLLER METHODS
    methods
        % ARdrone controller (local position)
        function [this] = Controller_position(this,ENV,NEDposition)

            % CALCULATE THE NEW STATE REFERENCE
            if ~this.IsIdle()
                X_desired = [NEDposition;zeros(2,1);-this.localState(6);zeros(6,1)];
            else
                % Idle reference
                X_desired = [zeros(5,1);this.localState(6);zeros(6,1)];
            end

            % /////////////////// AIRCRAFT DYNAMICS ///////////////////////
            useLinearModel = false;
            if ~useLinearModel
                [this.localState] = this.UpdateNonLinearPlant(ENV,this.localState,X_desired);
            else
                [this.localState] = this.UpdateLinearPlant(ENV,this.localState,X_desired);
            end

            % \\\\\\\\\\\\\\\\\\\\\ GLOBAL UPDATE \\\\\\\\\\\\\\\\\\\\\\\\\
            this = this.GlobalUpdate_ARdrone(ENV.dt,this.localState);
        end
        % ARdrone controller (local velocity)
        function [this] = Controller_velocity(this,ENV,NEDVelocity)

            % CALCULATE THE NEW STATE REFERENCE
            if ~this.IsIdle()
                X_desired = [zeros(5,1);this.localState(6);NEDVelocity;zeros(3,1)];
            else
                % Idle reference
                X_desired = [zeros(5,1);this.localState(6);zeros(6,1)];
            end

            % /////////////////// AIRCRAFT DYNAMICS ///////////////////////
            useLinearModel = false;
            if ~useLinearModel
                [this.localState] = this.UpdateNonLinearPlant(ENV,this.localState,X_desired);
            else
                [this.localState] = this.UpdateLinearPlant(ENV,this.localState,X_desired);
            end

            % \\\\\\\\\\\\\\\\\\\\\ GLOBAL UPDATE \\\\\\\\\\\\\\\\\\\\\\\\\
            this = this.GlobalUpdate_ARdrone(ENV.dt,this.localState);
        end
    end
    methods (Static)
        % Create an LQR controller (feedback gain)
        function [K_lqr] = CreateController_LQR(SS,Q,R,N)
            % This function designs the LQR controller used to provide
            % error feedback.

            if nargin < 6
                N = zeros(size(SS.B));
            end

            % Get the LQR feedback
            [K_lqr,~,~] = lqr(SS,Q,R,N);

            % IGNORE POSITION FEEDBACK
            K_lqr(:,1:3) = 0;   % Omit position feedback
            % IGNORE XY POSITION FEEDBACK
%             K_lqr(:,1:2) = 0; % Omit XY position feedback
            % IGNORE HEADING FEEDBACK
%             K_lqr(:,6) = 0;
        end
    end
    % //////////////////////// MODELLING/DYNAMICS /////////////////////////
    methods
        % ODE45 - UPDATE NONLINEAR CLOSED LOOP DYNAMICS
        function [X] = UpdateNonLinearPlant(this,TIME,X0,X_desired)
            % This function computes the state update for the current agent
            % using the ode45 function.

            % Input sanity check
            assert(isstruct(TIME),'Expecting a time structure.');

            X = X0; % Default to no change

            % DETERMINE THE INTEGRATION PERIOD
            if TIME.currentTime ~= TIME.timeVector(end)
                % INTEGRATE THE DYNAMICS OVER THE TIME STEP
                [~,Xset] = ode45(@(t,X) this.ARdrone_nonLinear_closedLoop(X,X_desired),...
                    [0 TIME.dt],X0,odeset('RelTol',1e-2,'AbsTol',TIME.dt*1E-2));
                X = Xset(end,:)';
            end
        end
        % ODE45 - UPDATE LINEAR CLOSED LOOP DYNAMICS
        function [X] = updateLinearPlant(this,TIME,X0,X_desired)
            % This function computes the state update for the current agent
            % using the ode45 function.

            % Input sanity check
            assert(isstruct(TIME),'Expecting a time structure.');

            X = X0; % Default to no change

            % Check for the last time-step
            if TIME.currentTime ~= TIME.timeVector(end)
                % INTEGRATE THE DYNAMICS OVER THE TIME STEP
                [~,Xset] = ode45(@(t,X) this.ARdrone_linear_closedLoop(X,X_desired),...
                    [0 TIME.dt],X0,odeset('RelTol',1e-2,'AbsTol',TIME.dt*1E-2));
                X = Xset(end,:)';
            end
        end
    end
    methods
        % CLOSED-LOOP NONLINEAR DYNAMICS
        function [dX] = ARdrone_nonLinear_closedLoop(this,X,X_desired)
            % THE STATE ERROR
            Xerror = X - X_desired;
            % THE NOMINAL INPUT
            [Uss] = this.ARdrone_nominalInput(X);
            % GET THE NOMINAL INPUT + LQR FEEDBACK
            U = Uss - this.DYNAMICS.K_lqr*Xerror;
            % CALL THE OPENLOOP DYNAMICS
            [dX] = this.ARdrone_nonLinear_openLoop(X,U);
        end
        % CLOSED-LOOP LINEAR DYNAMICS
        function [dX] = ARdrone_linear_closedLoop(this,X,X_desired)
            % THE STATE ERROR
            Xerror = X - X_desired;
            % GET THE NOMINAL INPUT + LQR FEEDBACK
            dU = - this.DYNAMICS.K_lqr*Xerror;
            % CALL THE OPENLOOP DYNAMICS
            [dX] = this.ARdrone_linear_openLoop(X,dU);
        end
    end
end
% AGENT STATE VECTOR [x;y;z;psi;the;phi;v;u;w;p;q;r]


function results  = RS_DF_rstest(z);

rvec = (0:0.001:1);
P = size(z,1);

cumcumz = [];
for r = rvec
    cumcumz = [cumcumz (z<r)-r];
end

v = sum(cumcumz,1)/sqrt(P);

Qv = []; Qvabs = [];
for rs = 1:size(rvec,2);
    Qv = [Qv; v(1,rs)'*v(1,rs)];
    Qvabs = [Qvabs; abs(v(1,rs)')];
end

Kv = max(Qvabs);
CVMv = mean(Qv);

results(1,1) = Kv;
results(1,2) = CVMv;


function mpe = find_mpe(engine, evidence)
% FIND_MPE Find the most probable explanation (Viterbi)
% mpe = enter_evidence(engine, evidence, ...)
%
% evidence{i,t} = [] if if X(i,t) is hidden, and otherwise contains its observed value (scalar or column vector)
%

obslik = mk_hmm_obs_lik_matrix(engine, evidence);
path = viterbi_path(engine.startprob, engine.transprob, obslik);
bnet = bnet_from_engine(engine);
ns = bnet.node_sizes_slice;
ns(bnet.observed) = 1;
ass = ind2subv(ns, path);
mpe = num2cell(ass');
mpe(bnet.observed,:) = evidence(bnet.observed,:);


function [stats,Y,X] = spm_mci_mvnpost (post,method,verbose,max_lag)
% Are MCMC samples consistent with Gaussian posterior ?
% FORMAT [stats,Y,X] = spm_mci_mvnpost (post,method,verbose,max_lag)
%
% post      posterior data structure from spm_mci_post
% method    'ESS' or 'thinning'
% verbose   create plots
% max_lag   maximum potential lag for MAR model
%
% stats     (multivariate) normal test statistics
%           See spm_mci_mvntest.m
% Y         uncorrelated posterior samples
% X         original posterior samples
%
% Run Gaussianity test on Markov chain samples
%__________________________________________________________________________
% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging

% Will Penny
% $Id: spm_mci_mvnpost.m 6697 2016-01-27 14:57:28Z spm $

try, pmax=max_lag; catch, pmax=10; end
try, meth=method; catch, meth='ESS'; end
try, ver=verbose; catch, ver=1; end

j=post.ind;
X=post.P(:,j)';
Nj=length(j);
Np=size(post.P,1);

if any(std(X)==0)
    disp('Warning from spm_mci_mvnpost: some parameters have zero variance');
    stats=[];
    return
end

switch meth
    case 'ESS',
        %C=cov(post.P(:,post.ind)');
        for p=1:Np,
            ess(p)=spm_mci_ess(post.P(p,j));
            %v(p)=C(p,p)*ess(p)/Nj;
        end
        %post.Cp=diag(v);
        %mess=mean(ess);
        mess=ceil(min(ess));
        stats = spm_mci_mvntest(X,mess);

        if ver
            disp('ESS method');
            disp('Effective Sample Sizes:');
            disp(ess);
        end

    case 'thinning',
        for p=1:Np,
            [tmp,m(p)]=spm_mci_ess(post.P(p,j));
        end
        lag=max(m)+1;
        Y=X(1:lag:end,:);
        stats = spm_mci_mvntest(Y);
        if ver
            disp('Thinning method');
            disp(sprintf('Using only every %d-th sample',lag));
        end

    otherwise
        disp('Unknown method in spm_mci_mvnpost.m');
        return
end


function r8poly_print ( m, a, title )

%*****************************************************************************80
%
%% R8POLY_PRINT prints out a polynomial.
%
%  Discussion:
%
%    The power sum form is:
%
%      p(x) = a(1) + a(2) * x + ... + a(m-1) * x^(m-1) + a(m) * x^(m-1)
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 February 2015
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the nominal degree of the polynomial.
%
%    Input, real A(1:M+1), the polynomial coefficients.
%    A(1) is the constant term and
%    A(M+1) is the coefficient of X^(M).
%
%    Input, string TITLE, a title.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );
  fprintf ( 1, '\n' );

  if ( a(m+1) < 0.0 )
    plus_minus = '-';
  else
    plus_minus = ' ';
  end

  mag = abs ( a(m+1) );

  if ( 3 <= m + 1 )
    fprintf ( 1, '  p(x) = %c%14g * x^%d\n', plus_minus, mag, m );
  elseif ( m + 1 == 2 )
    fprintf ( 1, '  p(x) = %c%14g * x\n', plus_minus, mag );
  elseif ( m + 1 == 1 )
    fprintf ( 1, '  p(x) = %c%14g\n', plus_minus, mag );
  end

  for i = m : -1 : 1

    if ( a(i) < 0.0 )
      plus_minus = '-';
    else
      plus_minus = '+';
    end

    mag = abs ( a(i) );

    if ( mag ~= 0.0 )

      if ( 3 <= i )
        fprintf ( 1, '         %c%14g * x^%d\n', plus_minus, mag, i-1 );
      elseif ( i == 2 )
        fprintf ( 1, '         %c%14g * x\n', plus_minus, mag );
      elseif ( i == 1 )
        fprintf ( 1, '         %c%14g\n', plus_minus, mag );
      end
    end

  end

  return
end


function group = GroupDV(Problem,DV,PV,nPerGroup)

%------------------------------- 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".
%--------------------------------------------------------------------------

% This function is written by Huangke Chen

   ub  = Problem.upper(DV);
   lb  = Problem.lower(DV);
   dim = length(DV);	% the dim of the distance variables

   fixPV  = (Problem.lower(PV)+Problem.upper(PV))/2;	% the value vector for position variables
   meanDV = (ub+lb)/2;

   f_archiveF = repmat(zeros(dim,dim),1,Problem.M);	% cell(dim, dim);

   fhatDVDecs     = repmat(lb,dim,1) + eye(dim).*repmat(meanDV,dim,1);
   fhatDecs       = [repmat(fixPV,dim,1) fhatDVDecs];
   fhatPopulation = Problem.Evaluation(fhatDecs);
   fhat_archiveF  = fhatPopulation.objs;

   lambdaF = repmat(zeros(dim,dim),1,Problem.M);	% cell(dim, dim);

   p1Dec   = [fixPV lb];
   tempFp1 = Problem.Evaluation(p1Dec);
   fp1F    = tempFp1.objs;

   for i = 1 : dim-1
       fp2 = fhat_archiveF(i,:);
       for j = i+1 : dim

           fp3 = fhat_archiveF(j,:);

           p4      = lb;
           p4(i)   = meanDV(i);	% temp;
           p4(j)   = meanDV(j);	% temp;
           p4Dec   = [fixPV p4];
           tempFp4 = Problem.Evaluation(p4Dec);
           fp4     = tempFp4.objs;

           f_archiveF(i,j:dim:size(f_archiveF,2)) = fp4;

           d1 = fp2 - fp1F;
           d2 = fp4 - fp3;

           lambdaF(i,j:dim:size(lambdaF,2)) = abs(d1-d2);
       end
   end

   % Check for each objective
   bigTheta = false(length(DV));

   for i = 1 : Problem.M

       lambda = lambdaF(:,(i-1)*dim+1:i*dim);
       fp1    = fp1F(i);

       fhat_archive = fhat_archiveF(:,i);

       tempF_archive = f_archiveF(:,(i-1)*dim+1:i*dim);
       f_archive     = tempF_archive + tempF_archive';

       F1 = ones(dim,dim)*fp1;
       F2 = repmat(fhat_archive',dim,1);
       F3 = repmat(fhat_archive,1,dim);
       F4 = f_archive;

       FS   = cat(3,F1,F2,F3,F4);
       Fmax = max(FS,[],3);

       FS       = cat(3,F1+F4,F2+F3);
       Fmax_inf = max(FS,[],3);

       theta = false(dim);

       muM       = eps/2;
       gamma     = @(n)((n.*muM)./(1-n.*muM));
       errlb     = gamma(2)*Fmax_inf;
       errub     = gamma(dim^0.5)*Fmax;
       I2        = lambda >= errub;
       theta(I2) = 1;

       % add, then find not less than 1
       bigTheta = bigTheta + theta;
   end

   bigTheta(bigTheta>0) = true;

   L = size(bigTheta,1);	% number of vertex

   % Breadth-first search
   labels = zeros(1,L);     % all vertex unexplored at the begining
   rts    = [];
   ccc    = 0;              % connected components counter
   while true
       ind = find(labels==0);
       if ~isempty(ind)
           fue  = ind(1);   % first unexplored vertex
           rts  = [rts fue];
           list = [fue];
           ccc  = ccc + 1;
           labels(fue) = ccc;
           while true
               list_new = [];
               for lc = 1 : length(list)
                   p   = list(lc);              % point
                   cp  = find(bigTheta(p,:));	% points connected to p
                   cp1 = cp(labels(cp)==0);     % get only unexplored vertecies
                   labels(cp1) = ccc;
                   list_new    = [list_new cp1];
               end
               list = list_new;
               if isempty(list)
                   break;
               end
           end
       else
           break;
       end
   end

   group_num = max(labels);
   allgroups = cell(1,group_num);
   for i = 1 : group_num
       allgroups{i} = find(labels==i);
   end

   h = @(x)(length(x)==1);
   sizeone = cellfun(h,allgroups);

   seps = allgroups(sizeone);
   seps = cell2mat(seps);

   allgroups(sizeone) = [];
   nonseps            = allgroups;

   group = {};
   for ns = 1 : length(nonseps)     % the non-seperate variables
       group = {group{1:end} DV(nonseps{ns})};
   end

   for g = 1 : nPerGroup : length(seps)
       index = seps(g:min(g+nPerGroup-1,length(seps)));
       group = {group{1: end} DV(index)};
   end
end


function hermite_poly_phys_values_test ( )

%*****************************************************************************80
%
%% HERMITE_POLY_PHYS_VALUES_TEST demonstrates the use of HERMITE_POLY_PHYS_VALUES.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 February 2012
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'HERMITE_POLY_PHYS_VALUES_TEST:\n' );
  fprintf ( 1, '  HERMITE_POLY_PHYS_VALUES stores values of\n' );
  fprintf ( 1, '  the physicist''s Hermite polynomials.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '     N      X            H(N,X)\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, n, x, fx ] = hermite_poly_phys_values ( n_data );

    if ( n_data == 0 )
      break
    end

    fprintf ( 1, '  %4d  %12f  %24.16e\n', n, x, fx );

  end

  return
end


function [m, maxnum] = mymode(x)
% computes the mode of x (the most commonly occuring value)
% x must be discrete and numeric
% if several values tie for frequency of occurance, each will be returned
% m - the most common value
% maxnum - the number of times that x==m

[g, gn] = grp2idx(x);
maxnum = 0;
m = [];
for i = 1:length(gn)
    count = sum(g==i);
    if count > maxnum
        maxnum = count;
        m = str2num(gn{i});
        c = 1;
    elseif count == maxnum
        m(c+1) = str2num(gn{i});
        c = c + 1;
    end
end

m = sort(m);


function s = logsumexp(a, dim)
% Returns log(sum(exp(a),dim)) while avoiding numerical underflow.
% Default is dim = 1 (columns).
% logsumexp(a, 2) will sum across rows instead of columns.
% Unlike matlab's "sum", it will not switch the summing direction
% if you provide a row vector.

% Written by Tom Minka
% (c) Microsoft Corporation. All rights reserved.

if nargin < 2
  dim = 1;
end

% subtract the largest in each column
[y, i] = max(a,[],dim);
dims = ones(1,ndims(a));
dims(dim) = size(a,dim);
a = a - repmat(y, dims);
s = y + log(sum(exp(a),dim));
i = find(~finite(y));
if ~isempty(i)
  s(i) = y(i);
end


function vrot=givapp(c,s,vin,k)
%givapp   apply a sequence of Givens rotations
%   input
%          c, s      vectors of length k-1 defining rotations
%          vin       vector of length k to which rotations are applied
%          k         k-1 = number of rotations
%   output
%          tranformed vector after rotations are applied
% called by gmres_r
%   IFISS function: HCE; 15 March 2005.

%
%  C. T. Kelley, July 10, 1994
%Copyright 1994 C. T. Kelley.
%Reproduced and distributed with permission of the copyright holder.
%
% This code comes with no guarantee or warranty of any kind.
%
%  function vrot=givapp(c, s, vin, k)
%
vrot=vin;
for i=1:k
    w1=c(i)*vrot(i)-s(i)*vrot(i+1);        % Change on next line, 6/3/97
    w2=s(i)*vrot(i)+conj(c(i))*vrot(i+1);  % w2=s(i)*vrot(i)+c(i)*vrot(i+1);
    vrot(i:i+1)=[w1,w2];
end


function test_triangulation_test02 ( )

%*****************************************************************************80
%
%% TEST02 tests P00_TEST_NUM and P00_SAMPLE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
  m = 2;
  seed_start = 123456789;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST02\n' );
  fprintf ( 1, '  P00_TEST_NUM reports the number of problems.\n' );
  fprintf ( 1, '  P00_SAMPLE returns sample points from the region.\n' );

  test_num = p00_test_num ( );

  for test = 1 : test_num

    seed = seed_start;

    title = p00_title ( test );

    n = 20;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Test number         =  %d\n', test );
    fprintf ( 1, '  Title:              = "%s"\n', title );
    fprintf ( 1, '  Spatial dimension M =  %d\n', m );
    fprintf ( 1, '  Number of samples N =  %d\n', n );
    fprintf ( 1, '  Initial SEED:       =  %d\n', seed );
    fprintf ( 1, '\n' );

    [ point, seed ] = p00_sample ( test, m, n, seed );

    r8mat_transpose_print ( m, n, point, '  The sample points:' );

  end

  return
end


clear all;
close all;
clc;
export = true;
configs = cell(1, 5);
configs{1} = create_config([1 1 1 1 1 1], 4, '1-4');
configs{2} = create_config([2 1 1 1 1 1], 4, '2.1-4');
configs{3} = create_config([4 2 1 1 1 1], 4, '42.1-4');
configs{4} = create_config([2 2 2 2 2 2], 4, '2-4');
configs{5} = create_config([2 2 2 2 2 2], 8, '2-8');

nc = numel(configs);

points = [150  275  490  885 1600 2885 5205 9400 16980];
nns = numel(points);
clustering_acc_perc_mat = zeros(nc, nns);
spr_perc_mat = zeros(nc, nns);
spr_error_perc_mat = zeros(nc, nns);

for c=1:nc
    config = configs{c};
    if isempty(config)
        continue;
    end
    solver_name = sprintf('ssc_mc_omp_%s', config.name);
    filepath = sprintf('bin/solver_%s.mat', solver_name);
    load(filepath);

    clustering_acc_perc_mat(c, :)  = result.clustering_acc_perc_arr;
    spr_perc_mat(c, :) = result.spr_perc_arr;
    spr_error_perc_mat(c, :) = 100 * result.spr_error_arr;
    fprintf('%s Points: \n', solver_name);
    fprintf('%4d ', result.num_points_arr);
    fprintf('\n');

    fprintf('Accuracy: \n');
    fprintf('%.2f ', result.clustering_acc_perc_arr);
    fprintf('\n');

    % plot_bench_results(result, solver_name);
end

legends = {'OMP', 'MC-OMP 2.1-4', 'MC-OMP 42.1-4', 'MC-OMP 2-4', 'MC-OMP 2-8'};

fprintf('\n\nAccuracy: \n');
disp(clustering_acc_perc_mat);

fprintf('\nSubspace preserving representations: \n');
disp(spr_perc_mat);

fprintf('\nSubspace representation error: \n');
disp(spr_error_perc_mat);

styles = spx.graphics.plot_styles();
mf = spx.graphics.Figures;
mf.new_figure('Clustering Accuracy');
for c=1:nc
    style = styles{c};
    plot(points, clustering_acc_perc_mat(c, :), style);
    hold on;
end
xlabel('Points');
ylabel('Clustering accuracy (%)');
ylim([40 100]);
grid on;
legend(legends, 'Location', 'SouthEast');
if export
set(gcf, 'units', 'inches', 'position', [.8 .8 4 3]);
set(gca,'FontSize',8);
set(findall(gcf,'type','text'),'FontSize',8);
export_fig plots/clustering_accuracy.png -r120 -nocrop;
export_fig plots/clustering_accuracy.pdf;
end

mf.new_figure('Subspace preserving representations');
for c=1:nc
    style = styles{c};
    plot(points, spr_perc_mat(c, :), style);
    hold on;
end
xlabel('Points');
ylabel('Subspace preserving representation percentage (%)');
ylim([0 100]);
grid on;
legend(legends, 'Location', 'SouthEast');
if export
set(gcf, 'units', 'inches', 'position', [.8 .8 4 3]);
set(gca,'FontSize',8);
set(findall(gcf,'type','text'),'FontSize',8);
export_fig plots/subspace_preserving_representation_perc.png -r120 -nocrop;
export_fig plots/subspace_preserving_representation_perc.pdf;
end

mf.new_figure('Subspace representation error');
for c=1:nc
    style = styles{c};
    plot(points, spr_error_perc_mat(c, :), style);
    hold on;
end
xlabel('Points');
ylabel('Subspace representation error  (%)');
ylim([0 50]);
grid on;
legend(legends);
if export
set(gcf, 'units', 'inches', 'position', [.8 .8 4 3]);
set(gca,'FontSize',8);
set(findall(gcf,'type','text'),'FontSize',8);
export_fig plots/subspace_representation_error_perc.png -r120 -nocrop;
export_fig plots/subspace_representation_error_perc.pdf;
end


classdef CEC2017_F20 < PROBLEM
% <single> <real> <constrained>
% CEC'2017 constrained optimization benchmark problem

%------------------------------- Reference --------------------------------
% G. Wu, R. Mallipeddi, and P. N. Suganthan, Problem definitions and
% evaluation criteria for the CEC 2017 competition on constrained real-
% parameter optimization, National University of Defense Technology, China,
% 2016.
%------------------------------- 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".
%--------------------------------------------------------------------------

    properties
        O;  % Optimal decision vector
    end
    methods
        %% Default settings of the problem
        function Setting(obj)
            CallStack = dbstack('-completenames');
            load(fullfile(fileparts(CallStack(1).file),'CEC2017.mat'),'Data');
            obj.O = Data{12}.o;
            obj.M = 1;
            if isempty(obj.D); obj.D = 10; end
            obj.D = min(obj.D,length(obj.O));
            obj.lower    = zeros(1,obj.D) - 100;
            obj.upper    = zeros(1,obj.D) + 100;
            obj.encoding = ones(1,obj.D);
        end
        %% Calculate objective values
        function PopObj = CalObj(obj,PopDec)
            Y = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);
            Y = Y.^2;
            PopObj = sum(0.5+(sin(sqrt(Y(:,1:end-1)+Y(:,2:end))).^2-0.5)./(1+0.001*sqrt(Y(:,1:end-1)+Y(:,2:end))).^2,2) + ...
                     0.5+(sin(sqrt(Y(:,end)+Y(:,1))).^2-0.5)./(1+0.001*sqrt(Y(:,end)+Y(:,1))).^2;
        end
        %% Calculate constraint violations
        function PopCon = CalCon(obj,PopDec)
            Y = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);
            Y = sum(Y,2);
            PopCon(:,1) = cos(Y).^2 - 0.25*cos(Y) - 0.125;
            PopCon(:,2) = exp(cos(Y)) - exp(0.25);
        end
    end
end


function Tfin=final(yy,T,robot)
tam=length(T);
Tf=yy*T{tam};
global radio;
global Tinicial;
global intervalos;
%Tinicial=directkinematic(robot,[0 0 0 0 0 0]);

 x=Tf(1:3,1);
 y=Tf(1:3,2);
 z=Tf(1:3,3);
 Tfin{1}=Tf;
 pmedio=[Tf(1,4),Tf(2,4),(Tf(3,4)- radio)/2];

 for j=2:1:(intervalos*2);
    if j<=intervalos
       final(1,j)=(j-1)*(pmedio(1)-Tf(1,4))/intervalos + Tf(1,4);
       final(2,j)=(j-1)*(pmedio(2)-Tf(2,4))/intervalos + Tf(2,4);
       final(3,j)=(j-1)*(pmedio(3)-Tf(3,4))/intervalos + Tf(3,4);
       %Ejes tramo final
       xz=final(1,j);
       yz=final(2,j);
       zz=final(3,j);
       p(:,j)=[xz yz zz]';
       z(:,j)=p(:,j)/norm(p(:,j)');
       x(2:3,j)=x(2:3,j-1);
       x(1,j)=(-z(2,j)*x(2,j)-z(3,j)*x(3,j))/z(1,j);
       x(:,j) = x(:,j)/norm(x(:,j));
       y(:,j)=cross(z(:,j),x(:,j));
       f=[x(:,j) y(:,j) z(:,j) p(:,j)];
       Tfin{j}=[f; 0 0 0 1];
    else

       final(1,j)=(j-(intervalos))*(Tinicial(1,4)-pmedio(1))/intervalos + pmedio(1);
       final(2,j)=(j-(intervalos))*(Tinicial(2,4)-pmedio(2))/intervalos + pmedio(2);
       final(3,j)=(j-(intervalos))*(Tinicial(3,4)-pmedio(3))/intervalos + pmedio(3);

       %Ejes tramo final
       xz=final(1,j);
       yz=final(2,j);
       zz=final(3,j);
       p(:,j)=[xz yz zz]';
       z(:,j)=p(:,j)/norm(p(:,j)');
       x(2:3,j)=x(2:3,j-1);
       x(1,j)=(-z(2,j)*x(2,j)-z(3,j)*x(3,j))/z(1,j);
       x(:,j) = x(:,j)/norm(x(:,j));
       y(:,j)=cross(z(:,j),x(:,j));
       f=[x(:,j) y(:,j) z(:,j) p(:,j)];
       Tfin{j}=[f; 0 0 0 1];
    end
 end

 Tfin{j+1}=Tinicial;
%     figure
%     hold on
%     z=Tf(1:3,4);
%     v=Tinicial(1:3,4);
%     h(:,1)=Tf(1:3,4);
%     for i=2:length(Tfin);
%         h(:,i)=Tfin{i-1}(1:3,4);
%     end
%    % h(:,7)=T1(1:3,4)
%      plot3(z(1),z(2),z(3),'*')
%      plot3(pmedio(1),pmedio(2),pmedio(3),'*')
%      hold on
%      plot3(h(1,:),h(2,:),h(3,:))
%      d=length(h);
%      plot3(v(1),v(2),v(3),'*')
end


function [p T hFig res] = rmCompareModelsGUI_paramTTest(M, plotFlag);
% Compare the distributions of pRF parameters between models in a compare
% models GUI.
%
%   [p T hFig df res] = rmCompareModelsGUI_paramTTest([M, plotFlag=1]);
%
% INPUTS:
%	M: rmCompareModelsGUI structure. See rmCompareModelsGUI_getData.
%	[Default: get from current figure]
%
%	plotFlag: flag to indicate whether to plot the results or just return
%	them. [default: 1, plot 'em]
%
% OUTPUTS:
%	p: [nModels x nModels x 7] matrix of p-values, for one-tailed T tests
%	between the parameters for each model. The 7 slices reflect the 7
%	parameters analyzed:
%		1) x0
%		2) y0
%		3) sigma (major)
%		4) polar angle
%		5) eccentricity
%		6) variance explained
%		7) beta coefficient for main pRF term.
%	So, for instance, p(2,1,3) reflects a comparison of the third parameter
%	(pRF size or sigma) for the test where model 2 is greater than model 1.
%
%	T: [nModels x nModels x 7] matrix of T-values, corresponding to the p-
%	values given in p.
%
%	hFig: if plotFlag==1, returns a handle to the plotted data. Otherwise,
%	returns empty.
%
%	res: further results struct, with the following fields:
%		df: degrees of freedom for the T tests
%
%		alpha: alpha threshold for the T tests, based on p=0.01 with
%		Bonferroni correction for multiple comparisons within these tests
%
%		H: matrix of 'results' indicating whether to accept (=0) or reject (=1)
%		the null hypothesis that the parameters come from the same
%		distribution. Same format as p and T.
%
%		CI_lo, CI_hi: 100 * (1-alpha)% confidence intervals for the true mean for
%		each comparison (same format as H). CI_lo is the lower bound, CI_hi
%		is the upper bound.
%
%		sd: pooled estimate of the population standard deviation for each
%		comparison (same format as H).
%
%
% ras, 05/2009.
if notDefined('M'),		M = get(gcf, 'UserData');			end
if notDefined('plotFlag'),	plotFlag = 1;					end
if ishandle(M),			M = get(M, 'UserData');				end

p = [];
T = [];
hFig = [];

fields = {'x0' 'y0' 'sigma' 'pol' 'ecc' 'varexp' 'beta'};

% let's pick an alpha value that takes into account multiple comparisons
% (not that it really matters -- in the initial iteration, we don't return
% these, and let the user decide their own thresholds based on the
% p-values):
alpha = 0.01 / (7 * M.nModels);
res.alpha = alpha;

%% loop across parameters
for n = 1:7
	f = fields{n};

	% get the param values for all models
	if n < 7
		data = reshape( [M.(f){:}], [M.nVoxels M.nModels] );
	else
		% n==7: beta values: need the specific beta for the main
		% effect
		for m = 1:M.nModels
			tmp{m} = [ M.beta{m}(:,1) ]';
		end
		data = reshape( [tmp{:}], [M.nVoxels M.nModels] );
	end

	%% loop across model pairs
	for ii = 1:M.nModels
		for jj = 1:M.nModels
			% run the one-sided T test
			[H P CI STATS] = ttest2(data(:,ii), data(:,jj), alpha, 'right');

			% record the main stat values
			p(ii,jj,n) = P;
			T(ii,jj,n) = STATS.tstat;

			% record other results
			res.df(ii,jj,n) = STATS.df;
			res.H(ii,jj,n) = H;
			res.CI_lo(ii,jj,n) = CI(1);
			res.CI_hi(ii,jj,n) = CI(2);
			res.sd(ii,jj,n) = STATS.sd;
		end
	end
end

%% plot if requested
if plotFlag==1
	nm = sprintf('Cross-Model T Tests %s', M.roi.name);
	h = figure('Color', 'w', 'Name', nm);

	for z = 1:7
		subplot(3, 3, z);

		% get the param values for all models
		f = fields{z};
		if z < 7
			data = reshape( [M.(f){:}], [M.nVoxels M.nModels] );
		else
			% ii==7: beta values: need the specific beta for the main
			% effect
			for m = 1:M.nModels
				tmp{m} = [ M.beta{m}(:,1) ]';
			end
			data = reshape( [tmp{:}], [M.nVoxels M.nModels] );
		end

		% compute the mean, SEM of the data
		Y = nanmean(data);
		E = nanstd(data); %  ./ sqrt(M.nVoxels - 1);

		starbar(Y, E, any(res.H(:,:,z)));
		set(gca, 'Box', 'off');  tuftify;
		xlabel('Model #', 'FontSize', 12);
		ylabel(f, 'FontSize', 12);

		title(f, 'FontSize', 14);
	end

	nm = sprintf('Cross-Model T Values %s', M.roi.name);
	h = figure('Color', 'w', 'Name', nm, 'Units', 'norm', ...
			  'Position', [.4 .3 .4 .4]);

	for z = 1:7
		subplot(3, 3, z);

		f = fields{z};

		drawXCorrMatrix( T(:,:,z), mrvMinmax(T) + [-.2 .2], 1 );

		% label each entry in the lower-left-hand plot
% 		if z==7
			axis on
			set(gca, 'Box', 'off', 'XTick', 1:M.nModels, ...
				'YTick', 1:1:M.nModels, 'FontSize', 9)
			xlabel('Model #', 'FontSize', 12);
			ylabel('Model #', 'FontSize', 12);
% 		end

		title( ['T Values: ' f], 'FontSize', 14 );
	end

end

return


%% parLimNat
% Below is a demonstration of the features of the |parLimNat| function

%% Syntax
% |[xx,S]=parLimNat(xx_c,[xx_min xx_max],x);|

%% Description
% The |parLimNat| function can be used to constrain parameters from
% [-inf,inf] to the range [xx_min xx_max] with the values xx_c at its
% centre. The constraining can be used in combination with optimization
% routinges that do not naturally handle parameter constraints.

%% Examples

clear; close all; clc;

%%
% PLOT SETTINGS
fontSize=25;
fontSize2=15;
markerSize=45;
lineWidth1=2;
lineWidth2=1;

%% Example: Constraining parameters (normal centre)
xx_c=5;
xx_min=0;
xx_max=10;
x=linspace(xx_c-10,xx_c+10,1000);
[xx,S]=parLimNat(xx_c,[xx_min xx_max],x);

cFigure; hold on; grid on;
title('Constraining using parLimNat','FontSize',fontSize);
xlabel('"free" x','FontSize',fontSize); ylabel('constrained x','FontSize',fontSize);

plot(x,xx,'r-','LineWidth',lineWidth1);
plot(xx_min,xx_min,'k.','markerSize',markerSize);
plot(xx_max,xx_max,'k.','markerSize',markerSize);
plot(xx_c,xx_c,'k.','markerSize',markerSize);

text(xx_c+0.5,xx_c,'xx_c = centre','Interpreter','none','FontSize',fontSize2);
text(xx_max,xx_max-0.5,'xx_max = upper bound','Interpreter','none','FontSize',fontSize2);
text(xx_min-2.5,xx_min+0.5,'xx_min = lower bound','Interpreter','none','FontSize',fontSize2);

axis tight; axis equal;
set(gca,'FontSize',fontSize);
drawnow;

%% Example: Constraining parameters (out of centre centre)
xx_c=2;
xx_min=0;
xx_max=10;
x=linspace(xx_c-10,xx_c+15,100);
[xx,S]=parLimNat(xx_c,[xx_min xx_max],x);

cFigure; hold on; grid on;
title('Constraining using parLimNat','FontSize',fontSize);
xlabel('"free" x','FontSize',fontSize); ylabel('constrained x','FontSize',fontSize);

plot(x,xx,'r-','LineWidth',lineWidth1);
plot(xx_min,xx_min,'k.','markerSize',markerSize);
plot(xx_max,xx_max,'k.','markerSize',markerSize);
plot(xx_c,xx_c,'k.','markerSize',markerSize);

text(xx_c+0.5,xx_c,'xx_c = centre','Interpreter','none','FontSize',fontSize2);
text(xx_max,xx_max-0.5,'xx_max = upper bound','Interpreter','none','FontSize',fontSize2);
text(xx_min-2.5,xx_min+0.5,'xx_min = lower bound','Interpreter','none','FontSize',fontSize2);

axis tight; axis equal;
set(gca,'FontSize',fontSize);
drawnow;

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

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


function [modelstring, typeflag, order] = modeltype(ar,ma)

%MODELTYPE provides a description for an ARMA-model
%   [modelstring, typeflag, order] = modeltype(AR,MA)
%
%   modelstring: AR, MA, ARMA
%   typeflag:    1   2   3
%   order: AR(p): p, MA(q): q, ARMA(r,r-1): r, NaN otherwise.
%   (ARMA setting for 'order' only for use with ARMAsel)
%
%   Example:
%   modeltype([1 .2 .5],[1 .3])
%   modeltype: ARMA(2,1)
%
%   See also: ARMAsel.

%S. de Waele, MARCH 2001

k = length(ar)-1; l = length(ma)-1;
if ~l,
   modelstring = ['AR(' int2str(k) ')']; typeflag = 1; order = k;
elseif ~k
   modelstring = ['  MA(' int2str(l) ')']; typeflag = 2; order = l;
else
   modelstring = ['ARMA(' int2str(k) ',' int2str(l) ')']; typeflag = 3;
   if l == k-1,
       order = k;
   else
       order = NaN;
   end
end

if ~nargout,
   disp(['modeltype: ' modelstring])
   clear modelstring typeflag
end


% Chapter 8 - Planar Systems.
% Program_8c - Phase Portrait of a Nonlinear System (Fig. 8.12).
% Copyright Birkhauser 2013. Stephen Lynch.

% Phase portrait of a nonlinear system of ODE's.
% IMPORTANT - Program_8a is vectorfield.m.
clear
% sys=inline('[x(2);x(1)*(1-(x(1))^2)+x(2)]','t', 'x');
sys = @(t,x) [x(2);x(1)*(1-(x(1))^2)+x(2)];
vectorfield(sys,-3:.5:3,-3:.5:3);
     hold on
     sep=1;
     for x0=-3:sep:3
         for y0=-3:sep:3
            [ts,xs] = ode45(sys,[0 6],[x0 y0]);
            plot(xs(:,1),xs(:,2))
         end
     end
     for x0=-3:sep:3
         for y0=-3:sep:3
            [ts,xs] = ode45(sys,[0 -6],[x0 y0]);
            plot(xs(:,1),xs(:,2))
         end
     end
     hold off
axis([-3 3 -3 3])
fsize=15;
set(gca,'XTick',-3:1:3,'FontSize',fsize)
set(gca,'YTick',-3:1:3,'FontSize',fsize)
xlabel('x(t)','FontSize',fsize)
ylabel('y(t)','FontSize',fsize)
hold off

% End of Program_8c.


function SF = SF_evaluation(MF)
RF = diff(MF,1,1);
RF1 = sqrt(mean(mean(RF.^2)));
CF = diff(MF,1,2);
CF1 = sqrt(mean(mean(CF.^2)));
SF = sqrt(RF1^2+CF1^2);
end


classdef OmoriModel < int32
    enumeration
        pck   (1) % 3 free parameters: p, c , k      % Modified Omori law (pck)
        pckk  (2) % 4 free parameters: p, c , k1, k2 % MOL with secondary aftershock (pckk)
        ppckk (3) % 5 free parameters: p1,p2,c,k1,k2 % MOL with secondary aftershock
        ppcckk(4) % 6 free parameters: p1,p2,c1, c2,k1,k2 % MOL with secondary aftershock
    end

    methods(Static)
        function cm = doForecast(nMod, t, p_1, c_1, k_1, t_break, k_2, p_2, c_2) % notice funky order!
            % log likelyhood
            %   where p = pvalues as n x 1
            %   where c = cvalues as n x 1
            %   where k = kvalues as n x 1
            %   where t = amount of time after the main shock, as m x 1 duration
            %
            %   returns an n x m matrix of values
            %
            % each row represents ONE time.
            % each column represents one itteration of p,c, and k
            %
            %  for scalar p,c,k, this would return a single row of values. one for each time.
            %  for scalar t, this would returna  single column of values.
            %
            %  p1t1   p2t1  p3t1     params ->
            %  p1t2   p2t2  p3t2
            %  p1t3   p2t3  p3t3
            %  p1t4   p2t4  p3t4
            %
            %  time
            %    |
            %    v

            assert(isrow(p_1) && isrow(c_1) && isrow(k_1) , 'All p,c,k input values should be rows');
            assert(all(numel(p_1) == [ numel(k_1), numel(c_1)]),'p, c, and k values should have same length');
            assert(isvector(t), 'time should be a vector');
            if isduration(t)
                t=days(t);
            end
            if ~iscolumn(t)
                t=t';
            end

            cm = nan(numel(t),numel(p_1));
            sz=size(cm);
            switch nMod
                case OmoriModel.pck
                    % deal with non infinite solutions first
                    idx = p_1 ~= 1;
                    c=c_1(idx);
                    k=k_1(idx);
                    p=p_1(idx);
                    cm(:,idx) = k ./ (p-1) .* (c .^ (1-p)-(t +c).^ (1-p));

                    c=c_1(~idx);
                    k=k_1(~idx);
                    p=[];
                    cm(:,~idx) = k .* log(t ./ c + 1);

                case {OmoriModel.pckk, OmoriModel.ppckk, OmoriModel.ppcckk}

                    assert(isrow(p_2) && isrow(c_2) && isrow(k_2) , 'All p2,c2,k2 input values should be rows');
                    assert(all(numel(p_1) == [ numel(p_2) numel(k_2), numel(c_2)]),'pn, cn, and kn values should have same length');
                    assert(isscalar(t_break));
                    if isduration(t_break)
                        t_break=days(t_break);
                    end

                    isafter = t >= t_break;
                    cm(~isafter,:) =  OmoriModel.doForecast(OmoriModel.pck, t(~isafter), p_1, c_1, k_1);

                    idx = p_1 ~= 1 & p_2 ~= 1;
                    if any(idx)
                        c1 = c_1(idx);
                        c2 = c_2(idx);
                        p1 = p_1(idx);
                        p2 = p_2(idx);
                        k1 = k_1(idx);
                        k2 = k_2(idx);
                        cm(isafter,idx) = k1./(p1-1) .* (c1.^(1-p1)-(t(isafter)+c1).^(1-p1)) + k2./(p2-1).*(c2.^(1-p2)-(t(isafter)-t_break + c2).^(1-p2));
                    end

                    idx = p_1 ~= 1 & p_2 == 1;
                    if any(idx)
                        c1 = c_1(idx);
                        c2 = c_2(idx);
                        p1 = p_1(idx);
                        p2 = [];
                        k1 = k_1(idx);
                        k2 = k_2(idx);
                        cm(isafter,idx) = k1./(p1-1) .* (c1.^(1-p1)-(t(isafter)+c1).^(1-p1)) + k2 .* log((t(isafter)-t_break)./c2+1);
                    end

                    idx = p_1 == 1 & p_2 ~= 1;
                    if any(idx)
                        c1 = c_1(idx);
                        c2 = c_2(idx);
                        p1 = [];
                        p2 = p_2(idx);
                        k1 = k_1(idx);
                        k2 = k_2(idx);
                        cm(isafter,idx) =k1.*log(t(isafter)./c1+1) + k2./(p2-1).*(c2.^(1-p2)-(t(isafter)-t_break+c2).^(1-p2));
                    end

                    idx = p_1 == 1 & p_2 == 1;
                    if any(idx)
                        c1 = c_1(idx);
                        c2 = c_2(idx);
                        p1 = [];
                        p2 = [];
                        k1 = k_1(idx);
                        k2 = k_2(idx);
                        cm(isafter,idx) = k1.*log(t(isafter)./c1+1) + k2.*log((t(isafter)-t_break)./c2+1);
                    end

            end
            assert(isequal(size(cm),sz)); % make sure sizes are as expected
        end
    end
end


function pred = knntest(Xtest,class_t,X,class,K,dist_type,pret_type)

% prediction of new samples with calculated model
%
% pred = knnpred(Xtest,X,class,K,dist_type,pret_type)
%
% ------------ INPUT ---------------------------------------------------
% Xtest:        dataset to be predicted [n_test x p] n objects, p variables
% X:            training data matrix (n x p)
% class:        training class vector (n x 1)
% K:            number of neighbors
% dist_type:    'euclidean' Euclidean distance
%               'mahalanobis' Mahalanobis distance
%               'cityblock' City Block metric
%               'minkowski' Minkowski metric
%               'sm' Sokal-Michener
%               'jt' Jaccard Tanimoto
%               'gle' Gleason-Dice
%               'ct4' Consonni-Todeschini
%               'ac' Austin-Colwell
% pret_type:    'cent' cenering
%               'scal' variance scaling
%               'auto' for autoscaling (centering + variance scaling)
%               'rang' range scaling (0-1)
%               'fp'   fingerprints
%
% ------------ OUTPUT --------------------------------------------------
% pred is a structure conyaining
% class_pred    predicted class vector [n_test x 1]
% neighbors     list of k neighbors for each predicted sample [n_test x k]
%
% version 1.0 - september 2009
% Davide Ballabio
% Milano Chemometrics and QSAR Research Group
% www.disat.unimib.it/chm

% version 2.0 - February 2012
% Kamel Mansouri
% Milano Chemometrics and QSAR Research Group
% www.disat.unimib.it/chm

% data check
if length(class)~=size(X,1)
    disp('the class input should be for the training set')
    %class_tr=input('class tr');
    %class=evalin(WS,);
    %keyboard
end

[n,p] = size(Xtest);
[X_scal_train,param] = data_pretreatment(X,pret_type);
X_scal = test_pretreatment(Xtest,param);
Xd = [X_scal;X_scal_train];
% D = pdist(Xd,model.set.dist_type);
% D = squareform(D);
D = knn_calc_dist(X_scal_train,X_scal,dist_type,pret_type);
neighbors = zeros(n,K);
for i=1:n
    D_in = D(i,:);
    [d_tmp,n_tmp] = sort(D_in);
    neighbors(i,:) = n_tmp(1:K);
    d_neighbors = d_tmp(1:K);
    class_calc(i) = knnclass(class(neighbors(i,:)),d_neighbors,max(class),K);
    dc(i,:)=d_neighbors;
end

pred.neighbors  = neighbors;
pred.class_pred = class_calc';
pred.class_param = calc_class_param(pred.class_pred ,class_t);
pred.D=D;
pred.dc=dc;


% m-file which generates data from a simple system with a localized
% nonlinearity and processes it using RLM's zeroing algorithm.
%
% Matt Allen, June 27, 2005
% MSA: Major Update - Nov, 2005 - changed to two arbitrary subsystems.
%
clear all; close all;

% Set up system parameters
% m1 = 1; m2 = 1; m3 = 1; m4 = 1; m5 = 1;
    M1 = eye(5);
    M2 = 0.1*eye(2); % Subsystem is about 10% the weight of normal system.

    kall = 1e6;
    k1 = kall; k2 = kall; k3 = kall; k4 = kall; k5 = kall; k6 = kall; kat = kall;
    K1 = [k1, -k1, 0, 0, 0; % System 1
        -k1, k1+k2, -k2, 0, 0
        0, -k2, k2+k3, -k3, 0;
        0, 0, -k3, k3+k4, -k4;
        0, 0, 0, -k4, k4];
    Ns1 = 5; Ns2 = 2; Ntot = 7;
    K2 = [k5, -k5; % System 2 - attached subsystem - dof's
        -k5, k5];
    Mtot = [M1, zeros(size(M1,1),size(M2,2));
        zeros(size(M2,1),size(M1,2)), M2];
    Ktot = [K1, zeros(size(K1,1),size(K2,2));
        zeros(size(K2,1),size(K1,2)), K2];
    % Specify how systems are connected
    at_ns = [2,6]; % attachment happens between this pair of nodes.
    fext_ns = 5; % Node at which external force is applied
    fnl_vec = zeros(Ntot,1); fnl_vec(at_ns(1)) = -1; fnl_vec(at_ns(2)) = 1;
    fext_vec = zeros(Ntot,1); fext_vec(fext_ns(1)) = 1;
    dnodes = [1:Ntot];
    vnodes = [(Ntot+1):(Ntot*2)];

    % Damping Matrix
    cfactk = 0.00003; % multiplied by K to get damping.
    cfactm = 8; % Multiplied by M to get damping
    % for k = 1:5; eval(['c',num2str(k),' = cfact*k',num2str(k),';']); end
    C1 = cfactk*K1 + cfactm*M1;
    C2 = cfactk*K2 + cfactm*M2; % proportional damping
    Ctot = [C1, zeros(size(C1,1),size(C2,2));
        zeros(size(C2,1),size(C1,2)), C2];

    % Linearized System Analysis %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % add a linear spring between attachment nodes
        Mlin = Mtot;
        Klin = Ktot;
        Klin(at_ns,at_ns) = Klin(at_ns,at_ns) + kat*[1, -1; -1, 1];
        % Linear Damping matrix:
        Clin = Ctot;
        Clin(at_ns,at_ns) = Clin(at_ns,at_ns) + cfactk*kat*[1, -1; -1, 1];

    % State Space Eigenanalysis
    Slin = [Clin, Mlin; Mlin, zeros(size(Mlin))];
    Rlin = [-Klin, zeros(size(Mlin));
        zeros(size(Mlin)), Mlin];
    Alin = (Slin\Rlin);
    [Philin,lamlin] = eig(Alin);
    lamlin = diag(lamlin);
    [junk,sind] = sort(abs(lamlin) - 0.001*min(abs(lamlin))*(imag(lamlin) > 0));
    lamlin = lamlin(sind);
    Philin = Philin(:,sind);

%         % Plot Mode Shapes
%         figure(1)
%         hls = plot([1:Ntot], imag(Philin(1:Ntot,1:2:end ))); grid on;
%         legend(hls, num2str([1:Ntot].'));
%         xlabel('X-coordinate');
%         ylabel('Im\{Mode Shape\}');

    wns = abs(lamlin);
    fns = wns/2/pi;
    zts = -real(lamlin)./abs(lamlin);
    disp('Natural Frequencies:, Damping Ratios:');
    [fns, zts]
%     DispFnZt(lamlin) - replace 2 lines abouve with this if you have the EMA Functions toolbox

    % Nonlinear Parameters
    NLType = 'bang'
    if strcmp(NLType,'bang');
        % Bang (Contact) Nonlinearity
        delcont = 1e-3;
        k4mult = 20; % Factor by which k4 increases: k4_contact = k4*k4mult
        c4mult = 1; % Factor by which c4 increases: c4_contact = c4*c4mult
    elseif strcmp(NLType,'cubic');
        % Cubic Spring
        katnl = 1e8;
    else
        error('NLType not recognized');
    end
    % Force paramters
        % length of half-sine force pulse
        % This is normalized in the EOM to unit area and multiplied by Afnl
        tfp = 1e-4;
        Afnl = 4e9;

    % Which Response to Use in evaluating Nonlinearity (i.e. x1, x2, x3..?)
    respind = 6;

    % Number of numerical derivatives to evaluate.  This M-file simulates
    % the displacement response of the 5-DOF system.  To simulate the
    % measurement of the velocity or acceleration response, the
    % displacement response is differentiated using finite differences
    % (i.e. Matlab's 'diff' command.)  This parameter sets the number of
    % derivatives to perform:
    nders = 2;
        % nders = 0; => use displacement
        % nders = 1; => use velocity
        % nders = 2; => use acceleration

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Put all of this in a structure for the EOM
global eom
S = whos;
for k = 1:length(S)
    eval(['eom.',S(k).name,' = ',S(k).name,';']);
end

    % Compute TF of Linearized System
    F = zeros(Ntot,1); F(fext_ns) = 1;
    wlin = [1:1:500]*2*pi;
    Halin = zeros(Ntot,length(wlin));
    for k = 1:length(wlin)
        Halin(:,k) = wlin(k).^2*([Mlin*-wlin(k).^2 + Clin*i*wlin(k) + Klin]\F);
    end
    Halin = Halin.';

%     figure(2)
%     semilogy(wlin/2/pi,abs(Halin)); grid on;
%     xlabel('Frequency (Hz)')
%     ylabel('H_{ACCEL}(\omega)');
%     for k = 1:Ntot; leg_txt{k} = ['H_{',num2str(k),',5}']; end
%     legend(leg_txt);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Nonlinear Simulation
% Compute sample rate and time
    elas_modes = find(imag(lamlin) > 0);
    dt = (5*2*max(fns(elas_modes)))^-1;
    Tmin = log(0.001)/(-min(abs(real(lamlin(elas_modes)))));
    N = 2^ceil(log2(Tmin/dt));

    ts = [0:dt:(N-1)*dt].';

% Specify initial time step so the solver doesn't miss the pulse:
    odeopts = odeset('InitialStep',tfp/10,'AbsTol',1e-9);

    % [ts_ode,hnl] = ode45(@nldetect_anex2_v1_eom,ts,zeros(10,1),odeopts,eom);

% Alternate Calling form:
sol = ode45(@nldt_bng_cub_v2_eom,[ts(1),ts(end)],zeros(Ntot*2,1),odeopts);
    [hnl, hnldot] = deval(sol,ts);
    hnl = hnl.';  hnldot = hnldot.';

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Linear Simulation
ltisys = ss(Alin,Slin\[F; zeros(Ntot,1)],[eye(Ntot), zeros(Ntot)], zeros(Ntot,1));

    % Use fine sample increment over duration of pulse
    if tfp < dt
        tlini = [0:100].'*tfp/100;
        ulini = (Afnl*2*tfp/pi)*sin((pi/tfp)*tlini);
        % Over Pulse duation to first sample
        [ylini,junki,xlini] = lsim(ltisys, [ulini], [tlini], zeros(Ntot*2,1));
        [ylin, junk2, xlin2] = lsim(ltisys, zeros(2,1), [junki(end); ts(2)], xlini(end,:).');
        % Free Response
        [ylin, junk3, xlin3] = lsim(ltisys, zeros(size(ts(2:end))), ts(2:end), xlin2(end,:).');
        hlin = [xlini(1,:); xlin2(end,:); xlin3(2:end,:)];
    else
        error('tfp > dt not yet supported!');
    end

% Plot Results
figure(10); set(gcf,'Position',[532   189   560   567]);
subplot(2,1,1)
plot(ts, hlin(:,respind), ts, hnl(:,respind), 'o-',sol.x, sol.y(respind,:), '.:'); grid on;
legend('h_{(r,5)} LIN','h_{(r,5)} NL','h_{(r,5)} ODE45');
xlabel('time (s)');
title('Comparison of Linear and Nonlinear Time Responses')

% Approximate derivatives of the response:
disp(['Number of Derivatives Requested: ',num2str(nders)]);
ndhlin = [zeros(nders,1); dt^-nders*diff(hlin(:,respind ),nders,1);];
ndhnl = [zeros(nders,1); dt^-nders*diff(hnl(:,respind ),nders,1); ];
%   Derivatives computed by "diff" don't appear to be ideal.  I don't know
%   that they are equivalent to a forward difference scheme.
% Select ODE45 derivatives - USE ODE45 Derivatives in the analysis!
if nders == 0;
    dhnlode = hnl(:,respind);
elseif nders == 1;
    dhnlode = hnl(:,respind + Ntot);
elseif nders == 2;
    dhnlode = hnldot(:,respind + Ntot);
end
tsdh = ts;%ts((1+nders):end);
subplot(2,1,2)
plot(tsdh, ndhlin, tsdh, ndhnl, ts, dhnlode, '.'); grid on;
legend(['h_D_{(',num2str(respind),',5)} LIN'],['h_D_{(',num2str(respind),',5)} NL'],...
    ['h_D_{(',num2str(respind),',5)} NL-ODE45']);
xlabel('time (s)');
title('Comparison of Derivatives of Linear and Nonlinear Responses')

% Find Actual force curve:
% This must be modified manually
% Fnl2 = Mtot(at_ns(2),at_ns(2))*hnldot(:,Ntot+at_ns(2)) - k5*(hnl(:,at_ns(2)) - hnl(:,at_ns(2)+1));
Fnl2 = Mtot(at_ns(2),:)*(hnldot(:,vnodes).') + Ktot(at_ns(2),:)*(hnl(:,dnodes).');
    if abs(fext_vec(at_ns(1))) > 0; warning('Equation for Force may not be correct'); end
Fnl3 = - Mtot(at_ns(1),:)*(hnldot(:,vnodes).') - Ktot(at_ns(1),:)*(hnl(:,dnodes).');
    if abs(fext_vec(at_ns(1))) > 0; warning('Equation for Force may not be correct'); end
delt_nl = hnl(:,at_ns(1)) - hnl(:,at_ns(2));

% Track the magnitude of the displacement of spring 4 - for NL
figure(11); set(gcf, 'Units','Normalized'); set(gcf,'Position',[0.069444,  0.48444, 0.43819, 0.39111]);
    set(gcf,'Name','Force vs. Delta Curve','Toolbar','figure');
subplot(1,3,1)
deltas = [-100:100]*(max(delt_nl)/100);
if strcmp(NLType,'bang');
    for k = 1:length(deltas)
        if deltas(k) < eom.delcont % No Contact Occurs
            Fnl(k) = eom.kat*deltas(k);
        else                % Contact Occurs
            Fnl(k) = eom.kat*eom.k4mult*deltas(k);
        end
    end
elseif strcmp(NLType,'cubic');
    Fnl = kat*deltas.*(1+katnl.*deltas.^2);
end
plot(Fnl, deltas*1e3, ...
    k4*deltas, deltas*1e3, '--',...
    Fnl2,delt_nl*1e3,'.',...
    Fnl3,delt_nl*1e3,'k.'); grid on;
ax1h = gca;
ylabel('\bf\Delta - NL Spring (mm)'); xlabel('\bfSpring Force')
title('\bfSpring Curve');
hx = subplot(1,3,2:3)
plot(ts*1e3, delt_nl*1e3); grid on;
% Set Axes to Equal
    ylim2 = get(gca,'Ylim');
    set(ax1h,'Ylim',ylim2);
xlabel('\bftime (ms)'); ylabel('\bf\Delta - NL Spring (mm)');
title('\bfDisplacement of NL Spring');

% Add button to make y-axes equal
set(hx,'tag','Main');
    PointsPerPixel = 72/get(0,'ScreenPixelsPerInch');
    hf = gcf;
    h1 = uicontrol('Parent',hf, ...
        'Units','points', ...
        'Position',[168, 51, 45, 25]*PointsPerPixel, ...
        'Callback','set_equal_ylims(hf);', ...
        'String','EqYlim', ...
        'Tag','YAxEqual');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Analysis

if strcmp(NLType,'bang');
    % ZNLDetect(hlin(:,respind),ts,[0,0.2],400)
    [Hmat,fs,ts_zc] = ZNLDetect(dhnlode,tsdh,[0,0.1],500);
    % ZNLDetectC(hnldot(:,6:10),tsdh,[0,0.3],30,400)
elseif strcmp(NLType,'cubic');
    [Hmat,fs,ts_zc] = ZNLDetect(dhnlode,tsdh,[0,0.15],500,4);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Alternate analysis - use all sensors with ZNLDetectC
% This gives 20 ZEFFTs equally distributed between 0 and 0.1 s, 0 to 500 Hz
%
% [Hmat,fs,ts_zc] = ZNLDetectC(hnldot(:,8:end),tsdh,[0,0.1],500,20);


function [km] = in2km(in)
% Convert length from inches to kilometers.
% Chad Greene 2012
km = in*0.0000254;


 function [sn,psdx,ff] = get_noise_fft(Y,options)

        defoptions = CNMFSetParms;
        if nargin < 2 || isempty(options); options = defoptions; end

        if ~isfield(options,'noise_range'); options.noise_range = defoptions.noise_range; end
        range_ff = options.noise_range;
        if ~isfield(options,'noise_method'); options.noise_method = defoptions.noise_method; end
        method = options.noise_method;
        if ~isfield(options,'block_size'); options.block_size = defoptions.block_size; end
        block_size = options.block_size;
        if ~isfield(options,'split_data'); options.split_data = defoptions.split_data; end
        split_data = options.split_data;
        if ~isfield(options,'max_timesteps') || isempty(options.max_timesteps);
            options.max_timesteps = defoptions.max_timesteps;
        end

        dims = ndims(Y);
        sizY = size(Y);
        N = min(sizY(end),options.max_timesteps);
        if N < sizY(end)
           %Y = reshape(Y,prod(sizY(1:end-1)),[]);
           switch ndims(Y),
               case 2,
                    Y(:,N+1:end) = [];
               case 3,
                    Y(:,:,N+1:end) = [];
               case 4,
                    Y(:,:,:,N+1:end) = [];
           end
        end

        Fs = 1;
        ff = 0:Fs/N:Fs/2;
        indf=ff>range_ff(1);
        indf(ff>range_ff(2))=0;
        if dims > 1
            d = prod(sizY(1:dims-1));
            Y = reshape(Y,d,N);
            Nb = prod(block_size);
            SN = cell(ceil(d/Nb),1);
            PSDX = cell(ceil(d/Nb),1);
            if ~split_data
                for ind = 1:ceil(d/Nb);
                    xdft = fft(Y((ind-1)*Nb+1:min(ind*Nb,d),:),[],2);
                    xdft = xdft(:,1: floor(N/2)+1); % FN: floor added.
                    psdx = (1/(Fs*N)) * abs(xdft).^2;
                    psdx(:,2:end-1) = 2*psdx(:,2:end-1) + eps;
                    %SN{ind} = mean_psd(psdx(:,indf),method);
                    switch lower(method)
                        case 'mean'
                            SN{ind}=sqrt(mean(psdx(:,indf)/2,2));
                        case 'median'
                            SN{ind}=sqrt(median(psdx(:,indf)/2,2));
                        case 'logmexp'
                            SN{ind} = sqrt(exp(mean(log(psdx(:,indf)/2),2)));
                        otherwise
                            error('unknown method for averaging noise..')
                    end
                    PSDX{ind} = psdx;
                end
            else
                nc = ceil(d/Nb);
                Yc = mat2cell(Y,[Nb*ones(nc-1,1);d-(nc-1)*Nb],N);
                parfor ind = 1:ceil(d/Nb);
                    xdft = fft(Yc{ind},[],2);
                    xdft = xdft(:,1:floor(N/2)+1);
                    psdx = (1/(Fs*N)) * abs(xdft).^2;
                    psdx(:,2:end-1) = 2*psdx(:,2:end-1) + eps;
                    Yc{ind} = [];
                    switch lower(method)
                        case 'mean'
                            SN{ind}=sqrt(mean(psdx(:,indf)/2,2));
                        case 'median'
                            SN{ind}=sqrt(median(psdx(:,indf)/2,2));
                        case 'logmexp'
                            SN{ind} = sqrt(exp(mean(log(psdx(:,indf)/2),2)));
                        otherwise
                            error('unknown method for averaging noise..')
                    end

                end
            end
            sn = cell2mat(SN);
        else
            xdft = fft(Y);
            xdft = xdft(:,1:floor(N/2)+1);
            psdx = (1/(Fs*N)) * abs(xdft).^2;
            psdx(:,2:end-1) = 2*psdx(:,2:end-1) + eps;
            switch lower(method)
                case 'mean'
                    sn = sqrt(mean(psdx(:,indf)/2,2));
                case 'median'
                    sn = sqrt(median(psdx(:,indf)/2,2));
                case 'logmexp'
                    sn = sqrt(exp(mean(log(psdx(:,indf)/2),2)));
                otherwise
                    error('unknown method for averaging noise..')
            end
        end
        psdx = cell2mat(PSDX);
        if dims > 2
            sn = reshape(sn,sizY(1:dims-1));
        end
 end


function adjust_bvecs(ecclog,bvecsfile,newbvecsfile)
% This code is written by Liang Zhan (zhan.liang@ucla.edu)
% This is to rotate gradient table using eddy_correct output
% Input variables are:
%  1) ecclog --- this is one output from eddy_correct
%  2) bvecsfile --- this is bvec generated from dicom
%  3) newbvecsfile --- this is output name for adjusted bvecs

fid=fopen(ecclog);
mat=[];
while ~feof(fid)
    % skip first three lines
    for i=1:3
      fgetl(fid);
    end
    % read four lines
    for i=1:4
     x=str2num(fgetl(fid))
    mat=[mat
         x];
    end
    % skip one line
    fgetl(fid);
end
fclose(fid);

% read bvecs file
bvecs = load(bvecsfile);
if(size(bvecs,2)==3 && size(bvecs,1)>3)
    bvecs = bvecs';
end

% rotate bvecs
rotbvecs = zeros(size(bvecs));
for i = 1:size(bvecs,2)
    %M = mat((i-1)*4+1:i*4,:);
    %M = mat(((i-1)*3+1):i*4,:);
    %M = M(1:3,1:3);
    M = mat(1:3,1:3);
    % extract rotation matrix
    [u,s,v] = svd(M*M');
    R = inv(u*sqrt(s)*v')*M;

    rotbvecs(:,i) = R*bvecs(:,i);
end

save(newbvecsfile,'rotbvecs','-ascii');
end


function imin = i4vec_imin ( n, a )

%*****************************************************************************80
%
%% I4VEC_IMIN computes the index of the minimum element of an I4VEC.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 April 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of entries in the array.
%
%    Input, integer A(N), the array.
%
%    Output, integer IMIN, the index of the smallest entry.
%
  if ( n <= 0 )

    imin = 0;

  else

    amin = a(1);
    imin = 1;

    for i = 2 : n

      if ( a(i) < amin )
        amin = a(i);
        imin = i;
      end

    end

  end

  return
end


classdef nnsoftmax < nntest
  properties (TestParameter)
    h = {1 2 3}
    w = {1 2}
  end
  methods (Test)
    function basic(test,h,w)
      d = 10 ;
      n = 3 ;
      x = test.randn(h,w,d,n,'single')/test.range ;
      y = vl_nnsoftmax(x) ;
      dzdy = test.randn(size(y),'single') ;
      dzdx = vl_nnsoftmax(x, dzdy) ;
      test.der(@(x) vl_nnsoftmax(x), x, dzdy, dzdx, 1e-2) ;
    end
  end
end


function [CD0] = DetermineProfileDrag(airfoildata,geo,panel)
%Determine the wing profile drag from the airfoils' drag polars

airfoil_r = geo.rootindex;
airfoil_t = geo.tipindex;

%Root dimensions
chord_r = geo.c_r;

%Determine Reynolds number at root; using log10 because regression was
%done this way
Re_r = log10(geo.Re_r);

%Convert back to degrees because the polynomial regression of the XFOIL
%drag data is in terms of degrees
alpha_r = (geo.i_r + geo.alpha)*180/pi;
b = cell2mat(airfoildata{2}(airfoil_r)); %Load the coefficients
c = cell2mat(airfoildata{3}(airfoil_r));
d = cell2mat(airfoildata{4}(airfoil_r));
k = cell2mat(airfoildata{5}(airfoil_r));
cd0_r = b(1) + b(2)*Re_r + b(3)*Re_r^2;
cd1_r = c(1) + c(2)*Re_r + c(3)*Re_r^2;
cd2_r = d(1) + d(2)*Re_r + d(3)*Re_r^2;
alpha_stall_r = k(1) + k(2)*Re_r + k(3)*Re_r^2;

%Test to see if airfoil is past stall angle of attack
if alpha_r > alpha_stall_r
    cd2_r = 2*cd2_r;
    %Double the last coefficient to account for the large increase in drag
    %past stall
end

%Tip dimensions
chord_t = geo.c_r*geo.taper;

%Determine Reynolds number at tip, use log10 because performed regression
%using log10
Re_t = log10(geo.Re_t);

%Convert back to degrees because the polynomial regression of the XFOIL
%drag data is in terms of degrees
alpha_t = (geo.i_r + geo.twist + geo.alpha)*180/pi;
b = cell2mat(airfoildata{2}(airfoil_t)); %Load the coefficients
c = cell2mat(airfoildata{3}(airfoil_t));
d = cell2mat(airfoildata{4}(airfoil_t));
k = cell2mat(airfoildata{5}(airfoil_t));
cd0_t = b(1) + b(2)*Re_t + b(3)*Re_t^2;
cd1_t = c(1) + c(2)*Re_t + c(3)*Re_t^2;
cd2_t = d(1) + d(2)*Re_t + d(3)*Re_t^2;
alpha_stall_t = k(1) + k(2)*Re_t + k(3)*Re_t^2;

%Test to see if airfoil is past stall angle of attack
if alpha_t > alpha_stall_t
    cd2_t = 2*cd2_t;
    %Double the last coefficient to account for the large increase in drag
    %past stall
end

%eta represents the fraction from 0 to 1 at the center of the panel where 0
%corresponds to y = 0 and 1 corresponds to y = b
eta = (2*(1:geo.ns)-1)/(2*geo.ns);
chord = chord_r + eta*(chord_t-chord_r);
alpha = alpha_r + eta*(alpha_t-alpha_r);
cd0 = cd0_r + eta*(cd0_t-cd0_r);
cd1 = cd1_r + eta*(cd1_t-cd1_r);
cd2 = cd2_r + eta*(cd2_t-cd2_r);

Deltay = zeros(1,geo.ns);
for i = 1:geo.ns
    Deltay(i) = panel(i,1).BV2(2) - panel(i,1).BV1(2);
end

D_q = (cd0 + cd1.*alpha + cd2.*alpha.^2).*chord.*Deltay;

CD0 = 2*sum(D_q,2)/geo.S;