function [ar,ma,ASAsellog,ASAcontrol]=armasel_rs(varargin)
%ARMASEL_RS ARMAsel model identification
%   [AR,MA,SELLOG] = ARMASEL_RS(ARH,N_OBS) estimates autoregressive, moving
%   average, and autoregressive moving average models from the high-order
%   AR model ARH and selects the model with optimal predictive qualities.
%   ARH has been estimated from N_OBS observations. The AR and MA parts of
%   the selected model, each possibly of order 0, are returned in the
%   parameter vectors AR and MA. The structure SELLOG provides additional
%   information on the selection process.
%
%   SELLOG contains the fields 'ar', 'ma' and 'arma', in which SELLOG
%   structures are nested, as returned by the functions ARH2AR, ARH2MA
%   and ARH2ARMA, invoked by ARMASEL. In the field 'armasel' a structure
%   is nested that reports information about the final stage of model
%   selection, where the preselected AR, MA and ARMA models are compared.
%
%   ARMASEL(ARH,N_OBS,CAND_AR_ORDER,CAND_MA_ORDER,CAND_ARMA_ORDER)
%   narrows the selection to candidate models with orders provided by the
%   rows CAND_AR_ORDER, CAND_MA_ORDER and CAND_ARMA_ORDER AR, MA and
%   ARMA(r,r-1) models independently.
%   For any of these arguments it is allowed to pass an
%   empty array. Alternatively, additional arguments may be omitted from
%   the input list. In both cases, default values are automatically
%   determined and substituted for the missing arguments. The functions
%   ARH2AR, ARH2MA and ARH2ARMA provide additional information on
%   defining candidate orders. Note in this respect, that the candidate
%   AR orders of the ARMA model are called CAND_ARMA_ORDER in this help
%   text, while in ARH2ARMA they are called CAND_AR_ORDER.
%
%   The selection of MA and ARMA models can be conditioned to the
%   selection of AR models from a specific set of candidate orders
%   CAND_AR_ORDER. See ASAGLOB_AR_COND for more information.
%
%   ARMASEL_RS is an ARMASA_RS main function.
%   ARMASEL_RS can also be used to selected models based on an ARH model
%   that has been estimated from segments of data.
%
%   See also: ARMASEL, ARH2AR, ARH2MA, ARH2ARMA, DATA_SEGMENTS.

%   Reference:  P. M. T. Broersen and S. de Waele, Selection of Order and
%               Type of Time Series Models Estimated from Reduced Statistics
%               Proceedings of SYSID 2002, May 2002.

%Header
%===================================================================================================

%Declaration of variables
%------------------------

%Declare and assign values to local variables
%according to the input argument pattern
[ar_rs,n_obs,cand_ar_order,cand_ma_order,cand_arma_order,arma_order_diff,ASAcontrol] = ASAarg(varargin, ...
{'ar_rs'       ;'n_obs'      ;'cand_ar_order';'cand_ma_order';'cand_arma_order';'arma_order_diff';'ASAcontrol'}, ...
{'isnumeric'   ;'isnumeric'  ;'isnumeric'    ;'isnumeric'    ;'isnumeric'      ;'isnumeric'      ;'isstruct'  }, ...
{'ar_rs'       ;'n_obs'                                                                                }, ...
{'ar_rs'       ;'n_obs'      ;'cand_ar_order'                                                                 }, ...
{'ar_rs'       ;'n_obs'      ;'cand_ar_order';'cand_ma_order'                                                 }, ...
{'ar_rs'       ;'n_obs'      ;'cand_ar_order';'cand_ma_order';'cand_arma_order'                               }, ...
{'ar_rs'       ;'n_obs'      ;'cand_ar_order';'cand_ma_order';'cand_arma_order';'arma_order_diff'             });

%Declare ASAglob variables
ASAglob = {'ASAglob_subtr_mean';'ASAglob_mean_adj';'ASAglob_rc';'ASAglob_ar';'ASAglob_final_f'; ...
      'ASAglob_final_b';'ASAglob_ar_cond'};

%Assign values to ASAglob variables by screening the
%caller workspace
for ASAcounter = 1:length(ASAglob)
   ASAvar = ASAglob{ASAcounter};
   eval(['global ' ASAvar]);
   if evalin('caller',['exist(''' ASAvar ''',''var'')'])
      eval([ASAvar '=evalin(''caller'',ASAvar);']);
   else
      eval([ASAvar '=[];']);
   end
end

%ARMASA-function version information
%-----------------------------------

%This ARMASA-function is characterized by
%its current version,
ASAcontrol.is_version = [2000 12 30 20 0 0];
%and its compatability with versions down to,
ASAcontrol.comp_version = [2000 12 30 20 0 0];

%This function calls other functions of the ARMASA
%toolbox. The versions of these other functions
%must be greater than or equal to:
ASAcontrol.req_version.sig2ar = [2000 12 30 20 0 0];
ASAcontrol.req_version.sig2ma = [2000 12 30 20 0 0];
ASAcontrol.req_version.sig2arma = [2000 12 30 20 0 0];

%Checks
%------

if ~isfield(ASAcontrol,'error_chk') | ASAcontrol.error_chk
      %Perform standard error checks
   %Input argument format checks
   ASAcontrol.error_chk = 1;
   if ~isnum(ar_rs)
      error(ASAerr(11,'ar_rs'))
   elseif ~isvector(ar_rs)
      error([ASAerr(14) ASAerr(15,'ar_rs')])
   end
   if ~isempty(cand_ar_order)
      if ~isnum(cand_ar_order) | ~isintvector(cand_ar_order) |...
            cand_ar_order(1)<0 | ~isascending(cand_ar_order)
         error(ASAerr(12,{'candidate';'cand_ar_order'}))
      elseif size(cand_ar_order,1)>1
         cand_ar_order = cand_ar_order';
         warning(ASAwarn(25,{'column';'cand_ar_order';'row'},ASAcontrol))
      end
   end
   if ~isempty(cand_ma_order)
      if ~isnum(cand_ma_order) | ~isintvector(cand_ma_order) |...
            cand_ma_order(1)<0 | ~isascending(cand_ma_order)
         error(ASAerr(12,{'candidate';'cand_ma_order'}))
      elseif size(cand_ma_order,1)>1
         cand_ma_order = cand_ma_order';
         warning(ASAwarn(25,{'column';'cand_ma_order';'row'},ASAcontrol))
      end
   end
   if ~isempty(cand_arma_order)
      if ~isnum(cand_arma_order) | ~isintvector(cand_arma_order) |...
            cand_arma_order(1)<0 | ~isascending(cand_arma_order)
         error(ASAerr(12,{'candidate';'cand_arma_order'}))
      elseif size(cand_arma_order,1)>1
         cand_arma_order = cand_arma_order';
         warning(ASAwarn(25,{'column';'cand_arma_order';'row'},ASAcontrol))
      end
   end
   if ~isempty(arma_order_diff) & ...
         (~isnum(arma_order_diff) | ...
         ~isintscalar(arma_order_diff) |...
         arma_order_diff<0)
      error(ASAerr(17,'arma_order_diff'))
   end

   %Input argument value checks
   if ~isreal(ar_rs)
      error(ASAerr(13))
   end
   if max(cand_ar_order) > length(ar_rs)-1
      error(ASAerr(37,'cand_ar_order'))
   end
   if max(cand_ma_order) > length(ar_rs)-1
      error(ASAerr(37,'cand_ma_order'))
   end
   if ~isempty(cand_arma_order) & ...
         ~isempty(arma_order_diff)
      if cand_arma_order(1)~=0 & ...
            (arma_order_diff < 1 | ...
            arma_order_diff > cand_arma_order(1))
         error(ASAerr(18,{'arma_order_diff';'1';...
               num2str(cand_arma_order(1))}))
      elseif length(cand_arma_order)>1 & ...
            (arma_order_diff < 1 | ...
            arma_order_diff > cand_arma_order(2))
         error(ASAerr(18,{'arma_order_diff';'1';...
               num2str(cand_arma_order(2))}))
      end
   end
end

if ~isfield(ASAcontrol,'version_chk') | ...
      ASAcontrol.version_chk %Perform version check
   ASAcontrol.version_chk = 1;

   %Make sure the requested version of this function
   %complies with its actual version
   ASAversionchk(ASAcontrol);

   %Make sure the requested versions of the called
   %functions comply with their actual versions
   arh2ar(ASAcontrol);
   arh2ma(ASAcontrol);
   arh2arma(ASAcontrol);
end

if ~isfield(ASAcontrol,'run') | ASAcontrol.run
   ASAcontrol.run = 1;
   ASAdate = now;
end

if ASAcontrol.run %Run the computational kernel
   ASAcontrol.version_chk = 0;
   ASAcontrol.error_chk = 0;

%Main
%=====================================================

%Initialization of variables
%---------------------------

if ASAglob_ar_cond
   ASAglob_ar_cond = 1;
else
   ASAglob_ar_cond = 0;
end

n_obs_tot = sum(n_obs);

%AR-, MA- and ARMA-model identification
%--------------------------------------

[ar_ar,ar_sellog] = arh2ar...
   (ar_rs,n_obs,cand_ar_order,ASAcontrol);
[ma_ma,ma_sellog] = arh2ma...
   (ar_rs,n_obs,cand_ma_order,ASAcontrol);
[arma_ar,arma_ma,arma_sellog] = arh2arma...
   (ar_rs,n_obs,cand_arma_order,arma_order_diff,ASAcontrol);

%Selection of the ARMAsel model
%------------------------------

%Asess the selected model orders
order = ...
   [length(ar_ar)-1;length(ma_ma)-1;length(arma_ar)-1];

%Asess the corresponding prediction error estimates
sel_location = ...
   [find(order(1) == ar_sellog.cand_order);...
    find(order(2) == ma_sellog.cand_order);...
    find(order(3) == arma_sellog.cand_ar_order)];
pe_est = [ar_sellog.pe_est(sel_location(1));...
      ma_sellog.pe_est(sel_location(2));...
      arma_sellog.pe_est(sel_location(3))];

%Select the model with the smallest prediction error
%estimate
[sel_pe_est,model] = min(pe_est);

%Arranging output arguments
%--------------------------

%Retrieve the parameters of the selected model
ar = 1;
ma = 1;
switch model
case 1 %The AR model has been selected
   ar = ar_ar;
case 2 %The MA model has been selected
   ma = ma_ma;
case 3 %The ARMA model has been selected
   ar = arma_ar;
   ma = arma_ma;
end

%Gernerate a structure variable ASAsellog to report
%the selection process
ASAsellog.funct_name = mfilename;
ASAsellog.funct_version = ASAcontrol.is_version;
ASAsellog.date_time = ...
   [datestr(ASAdate,8) 32 datestr(ASAdate,0)];
ASAsellog.comp_time = ar_sellog.comp_time+...
   ma_sellog.comp_time+...
   arma_sellog.comp_time;
ASAsellog.armasel.ar = ar;
ASAsellog.armasel.ma = ma;
ASAsellog.armasel.ar_pe_est = pe_est(1);
ASAsellog.armasel.ma_pe_est = pe_est(2);
ASAsellog.armasel.arma_pe_est = pe_est(3);
ASAsellog.armasel.ar_cond = ASAglob_ar_cond;
ASAsellog.armasel.mean_adj = ASAglob_mean_adj;
ASAsellog.ar = ar_sellog;
ASAsellog.ma = ma_sellog;
ASAsellog.arma = arma_sellog;

%Footer
%=====================================================

else %Skip the computational kernel
   %Return ASAcontrol as the first output argument
   if nargout>1
      warning(ASAwarn(9,mfilename,ASAcontrol))
   end
   ar = ASAcontrol;
   ASAcontrol = [];
end

%Program history
%======================================================================
%
% Version                Programmer(s)          E-mail address
% -------                -------------          --------------
% former versions        P.M.T. Broersen        broersen@tn.tudelft.nl
%                        S. de Waele            waele@tn.tudelft.nl
% [2000 11  1 12 0 0]    W. Wunderink           wwunderink01@freeler.nl
% [2000 12 30 20 0 0]         ,,                          ,,


classdef prtClassPlsda < prtClass
    % prtClassPlsda  Partial least squares discriminant classifier
    %
    %    CLASSIFIER = prtClassPlsda returns a Partial least squares
    %    discriminant classifier
    %
    %    CLASSIFIER = prtClassPlsda(PROPERTY1, VALUE1, ...) constructs a
    %    prtClassMAP object CLASSIFIER with properties as specified by
    %    PROPERTY/VALUE pairs.
    %
    %    A prtClassPlsda object inherits all properties from the abstract
    %    class prtClass. In addition is has the following properties:
    %
    %    nComponents  -  The number of components
    %    Bpls         -  The regression weights, estimated during training
    %    xMeans       -  The xMeans, estimated during training
    %    yMeans       -  The yMeana, estimated during training
    %
    %    trainingTechnique - Either 'simpls' or 'pls2' - the training
    %       technique to utilize.  See prtUtilSimpls and prtUtilPls2.
    %
    %    For information on the partial least squares discriminant
    %    algorithm, please refer to the following URL:
    %
    %    http://en.wikipedia.org/wiki/Partial_least_squares_regression
    %
    %    A prtClassPlsda object inherits the TRAIN, RUN, CROSSVALIDATE and
    %    KFOLDS methods from prtAction. It also inherits the PLOT method
    %    from prtClass.
    %
    %    Example:
    %
    %   TestDataSet = prtDataGenUnimodal;      % Create some test and
    %   TrainingDataSet = prtDataGenUnimodal;  % training data
    %   classifier = prtClassPlsda;           % Create a classifier
    %   classifier = classifier.train(TrainingDataSet);    % Train
    %   classified = run(classifier, TestDataSet);         % Test
    %   subplot(2,1,1);
    %   classifier.plot;
    %   subplot(2,1,2);
    %   [pf,pd] = prtScoreRoc(classified,TestDataSet);
    %   h = plot(pf,pd,'linewidth',3);
    %   title('ROC'); xlabel('Pf'); ylabel('Pd');
    %
    %    See also prtClass, prtClassLogisticDiscriminant, prtClassBagging,
    %    prtClassMap, prtClassCap, prtClassBinaryToMaryOneVsAll, prtClassDlrt,
    %    prtClassKnn, prtClassFld, prtClassRvm, prtClassGlrt,  prtClass

    % Copyright (c) 2013 New Folder Consulting
    %
    % Permission is hereby granted, free of charge, to any person obtaining a
    % copy of this software and associated documentation files (the
    % "Software"), to deal in the Software without restriction, including
    % without limitation the rights to use, copy, modify, merge, publish,
    % distribute, sublicense, and/or sell copies of the Software, and to permit
    % persons to whom the Software is furnished to do so, subject to the
    % following conditions:
    %
    % The above copyright notice and this permission notice shall be included
    % in all copies or substantial portions of the Software.
    %
    % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
    % OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    % NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    % DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
    % OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    % USE OR OTHER DEALINGS IN THE SOFTWARE.

    properties (SetAccess=private)
        name = 'Partial Least Squares Discriminant' % Partial Least Squares Discriminant
        nameAbbreviation = 'PLSDA' % PLSDA
        isNativeMary = true;  % True
    end

    properties
        % w is a DataSet.nDimensions x 1 vector of projection weights
        % learned during Fld.train(DataSet)
        nComponents = 2;
    end

    properties (SetAccess=protected)
        Bpls     % The prediction weights
        xScores % T
        yScores % U
        xVectors% P
        yVectors% Q

        yMeansFactor % Factor to be added into regression output (accounts for X means and yMeans);
        vipXY   % VIP scores including variations in X
        vipY    % VIP scores including only variations in Y
    end

    properties (Hidden)
        trainingTechnique = 'simpls'; %{'Simpls','pls2'};
        %         xMeans % Used for PLS2 (vs. SIMPLS)
    end

    methods

        function self = prtClassPlsda(varargin)
            self = prtUtilAssignStringValuePairs(self,varargin{:});
        end

        function self = set.trainingTechnique(self,val)
            if ~any(strcmpi(val,{'pls2','simpls'}))
                error('prtClassPlsda:trainingTechnique','trainingTechnique must be one of {''pls2'',''simpls''}; string provided was: %s',val);
            end
            self.trainingTechnique = val;
        end
        function self = set.nComponents(self,val)
            if ~prtUtilIsPositiveInteger(val)
                error('prt:prtClassPlsda:nComponents','nComponents must be a positive integer');
            end
            self.nComponents = val;
        end

    end

    methods (Access=protected, Hidden = true)

        function self = trainAction(self,DataSet)

            X = DataSet.getObservations;

            Y = DataSet.getTargetsAsBinaryMatrix;

            if DataSet.nClasses < 2
                warning('prt:prtClassPlda:unaryOrUnlabeled','Training dataset for PLSDA has %d classes. This may cause issues.',DataSet.nClasses)
            end

            maxComps = min(size(X));
            if self.nComponents > maxComps;
                self.nComponents = maxComps;
            end

            xMeans = mean(X,1);
            yMeans = mean(Y,1);
            X = bsxfun(@minus, X, xMeans);
            Y = bsxfun(@minus, Y, yMeans);
            switch self.trainingTechnique
                case 'simpls'
                    [self.Bpls, R, self.xVectors, self.yVectors, self.xScores, self.yScores] = prtUtilSimpls(X,Y,self.nComponents);

                case 'pls2'
                    [self.Bpls, W, P, Q, T, U, B] = prtUtilPls2(X,Y,self.nComponents);

                    self.yVectors = Q;
                    self.xVectors = P;
                    self.yScores = T*B;
                    self.xScores = T;

                otherwise
                    error('prtClassPlsda:trainingTechnique','Invalid trainingTechnique specified');
            end
            self.yMeansFactor = yMeans - xMeans*self.Bpls;

            ssT = diag(self.xScores'*self.yScores);
            ssT = ssT./sum(ssT(:));

            self.vipXY = sqrt(size(X,2)) * sum(bsxfun(@times, bsxfun(@rdivide,self.xVectors,sqrt(sum(self.xVectors.^2,2))).^2, ssT'),2);

            ssT = diag(self.yScores'*self.yScores);
            ssT = ssT./sum(ssT(:));

            self.vipY = sqrt(size(X,2)) * sum(bsxfun(@times, bsxfun(@rdivide,self.xVectors,sqrt(sum(self.xVectors.^2,2))).^2, ssT'),2);
        end

        function DataSet = runAction(self,DataSet)
            yOut = bsxfun(@plus,DataSet.getObservations*self.Bpls, self.yMeansFactor);
            DataSet = DataSet.setObservations(yOut);
        end

        function xOut = runActionFast(self,xIn,ds) %#ok<INUSD>
            xOut = bsxfun(@plus,xIn*self.Bpls, self.yMeansFactor);
        end
    end

    methods (Hidden)
        function str = exportSimpleText(self) %#ok<MANU>
            titleText = sprintf('%% prtClassPlsda\n');
            plsdBText = prtUtilMatrixToText(full(self.Bpls),'varName','plsdaWeights');
            plsdYText = prtUtilMatrixToText(full(self.yMeansFactor),'varName','yMeansFactor');
            str = sprintf('%s%s%s',titleText,plsdBText,plsdYText);
        end
    end
end


% repeat a matrix
%
function [output] = F_transpose(input_layer, curr_layer)
input = input_layer.a;

output = input';

end


classdef nme_branch_dc < mp.nme_branch & mp.form_dc

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

%     properties
%         name = 'branch';
%     end

    methods
        function obj = build_params(obj, nm, dm)
            build_params@mp.nme_branch(obj, nm, dm);    %% call parent

            dme = obj.data_model_element(dm);
            nl = obj.nk;

            tm = ones(nl, 1);           %% default tap ratio = 1
            i = find(dme.tm);           %% indices of non-zero tap ratios
            tm(i) = dme.tm(i);          %% assign non-zero tap ratios

            b = 1 ./ dme.x;             %% series susceptance
            b = b ./ tm;
            Pfinj = b .* (-dme.ta);
            obj.B = sparse( ...
                [1:nl 1:nl nl+1:2*nl nl+1:2*nl]', ...
                [1:nl nl+1:2*nl 1:nl nl+1:2*nl]', ...
                [b; -b; -b; b], ...
                2*nl, 2*nl );
            obj.p = [Pfinj + dme.g_fr; -Pfinj + dme.g_to];
        end
    end     %% methods
end         %% classdef


% This class is for computing superpixel-based affinities described in the paper.
% This class requires the image graphs methods by Steve Eddins. Find it here:
% http://www.mathworks.com/matlabcentral/fileexchange/53614-image-graphs

classdef Superpixels
    properties
        labels
        spcount
        neigh
        centroids
    end
    methods
        function obj = Superpixels(im, spcnt)
            if ~exist('spcnt', 'var') || isempty(spcnt)
                spcnt = 2500;
            end
            [L, N] = superpixels(im, spcnt, 'Compactness', 1e-20);
            obj.labels = L;
            obj.spcount = N;
            % Find neighboring superpixels
            g = adjacentRegionsGraph(L);
            obj.neigh = g.Edges.Labels;
            % Find centroids
            s = regionprops(L, 'centroid');
            cent = cat(1, s.Centroid);
            obj.centroids = round(cent(:, 2:-1:1));
            [h, w, ~] = size(im);
            obj.centroids(:, 3) = sub2ind([h, w], obj.centroids(:, 1), obj.centroids(:, 2));
        end

        function regmeans = computeRegionMeans(obj, image)
            [h, w, c] = size(image);
            image = reshape(image, [h*w, c]);
            regmeans = zeros(obj.spcount, c);
            idx = label2idx(obj.labels);
            for i = 1 : length(idx)
                regmeans(i, :) = mean(image(idx{i}, :), 1);
            end
        end

        % This is for the semantic affinity, generates affinities in [-1, 1]
        function W = neighborAffinities(obj, features, erfSteepness, erfCenter)
            if ~exist('erfSteepness', 'var') || isempty(erfSteepness)
                erfSteepness = 20;
            end
            if ~exist('erfCenter', 'var') || isempty(erfCenter)
                erfCenter = 0.85;
            end
            [h, w, ~] = size(features);
            N = h * w;
            spMeans = obj.computeRegionMeans(features);
            affs = zeros(size(obj.neigh, 1), 1);
            inds1 = affs;
            inds2 = affs;
            for i = 1 : size(obj.neigh, 1)
                ind1 = obj.neigh(i, 1);
                ind2 = obj.neigh(i, 2);
                affs(i) = sigmoidAff(spMeans(ind1, :), spMeans(ind2, :), erfSteepness, erfCenter);
                inds1(i) = obj.centroids(ind1, 3);
                inds2(i) = obj.centroids(ind2, 3);
            end
            W = sparse(inds1, inds2, affs, N, N);
            W = W' + W;
        end

        % This is for the nonlocal color affinity, generates affinities in [0, 1]
        function W = nearbyAffinities(obj, image, erfSteepness, erfCenter, proxThresh)
            if ~exist('erfSteepness', 'var') || isempty(erfSteepness)
                erfSteepness = 50;
            end
            if ~exist('erfCenter', 'var') || isempty(erfCenter)
                erfCenter = 0.95;
            end
            if ~exist('proxThresh', 'var') || isempty(proxThresh)
                proxThresh = 0.2;
            end
            [h, w, ~] = size(image);
            N = h * w;
            spMeans = obj.computeRegionMeans(image);
            combinationCnt = obj.spcount;
            combinationCnt = combinationCnt * (combinationCnt - 1) / 2;
            affs = zeros(combinationCnt, 1);
            inds1 = affs;
            inds2 = affs;
            cnt = 1;
            cents = obj.centroids(:, 1:2);
            cents(:,1) = cents(:,1) / h;
            cents(:,2) = cents(:,2) / w;
            for i = 1 : obj.spcount
                for j = i + 1 : obj.spcount
                    centdist = cents(i, 1:2) - cents(j, 1:2);
                    centdist = sqrt(centdist * centdist');
                    if centdist > proxThresh
                        affs(cnt) = 0;
                    else
                        affs(cnt) = sigmoidAffPos(spMeans(i, :), spMeans(j, :), erfSteepness, erfCenter);
                    end
                    inds1(cnt) = obj.centroids(i, 3);
                    inds2(cnt) = obj.centroids(j, 3);
                    cnt = cnt + 1;
                end
            end
            W = sparse(inds1, inds2, affs, N, N);
            W = W' + W;
        end

        function vis = visualizeRegionMeans(obj, im)
            vis = label2rgb(obj.labels, obj.computeRegionMeans(im));
        end

    end
end

function aff = sigmoidAff(feat1, feat2, steepness, center)
    aff = abs(feat1 - feat2);
    aff = 1 - sqrt(aff * aff');
    aff = (erf(steepness * (aff - center)));
end

function aff = sigmoidAffPos(feat1, feat2, steepness, center)
    aff = abs(feat1 - feat2);
    aff = 1 - sqrt(aff * aff');
    aff = (erf(steepness * (aff - center)) + 1) / 2;
end


function img_mrtrix=tensor_model_2(gx,gy,gz)
% This script convert vector file to tensor visulization in MRtrix
% vectorFile='Average_Vn2_VectorFile.mat';

%Select eignvector
%Gradient 1, 2 or 3
%1 is eigenvector 2, 2 is eigenvector 3, 3 is eigenvector 4

%Scale factor for all values in the tensor
%Affects all models
ScaleFactor=0.05; %Model 2

%Balance between isotropic and anistropic component in Model 2
%1 fully anisotropic; 0 fully isotropic
%Only affects Model 2
BalanceFactor=0.995;

% Model 2: Outlier detection method with clipping

gx1=gx; gy1=gy; gz1=gz;

%Size of image
N=size(gx);

%Initialize tensors for the three models
for i=1:6
    tnsr{i}=zeros(N); %tensor image
end

mag1=sqrt(gx1.^2+gy1.^2+gz1.^2);

%Mask of non-zero eigenvectors
msk=zeros(N);
ind=find(mag1);
msk(ind)=1;

%Eigenvector magnitudes
mag_vec1=mag1(ind);

%Scale eignvector magnitudes
meth='quartile'; t=5;
mag_vec1x=filloutliers(mag_vec1,'clip',meth,'ThresholdFactor',t);

%V=3;
for i=1:length(ind)
    v1=[gx1(ind(i));gy1(ind(i));gz1(ind(i))];
    v1=v1/mag_vec1(i); %normalize

    vv=v1;
    mag_vecx=mag_vec1x;

    % scale anistropic component by scaled eigenvector magnitude
    tmp2=ScaleFactor*( BalanceFactor*mag_vecx(i)*(vv*vv') + (1-BalanceFactor)*eye(3) );

    tnsr{1}(ind(i))=tmp2(1,1); tnsr{2}(ind(i))=tmp2(1,2);
    tnsr{3}(ind(i))=tmp2(2,2); tnsr{4}(ind(i))=tmp2(1,3);
    tnsr{5}(ind(i))=tmp2(2,3); tnsr{6}(ind(i))=tmp2(3,3);

end

% MRtrix order D11, D22, D33, D12, D13, D23
img_mrtrix=cat(4,tnsr{1},tnsr{3},tnsr{6},tnsr{2},tnsr{4},tnsr{5});


clear; clc;

%% dataset related arguments
train_path = 'data/ml1m/validation/train.txt';
test_path = 'data/ml1m/validation/test.txt';
rate_once = 1;           % whether each item will only be rated once by each user
L = 5;                   % length of sequence
T = 3;                   % number of targets

%% training arguments
seed = 1234;             % random seed
n_iter = 50;             % number of iteration
learning_rate = 1e-3;    % learning rate for ADAM
l2 = 1e-6;               % l2 norm weight
neg_samples = 3;         % negative samples per target
early_stop = true;       % whether to perform early stop during training

%% Caser related arguments
d = 50;                 % number of latent dimensions
nv = 4;                 % number of vertical filters
nh = 16;                % number of horizontal filters
ac_conv = 'relu';       % activation function for convolution layer (i.e., phi_c in paper)
ac_fc = 'relu';         % activation function for fully-connected layer (i.e., phi_a in paper)
drop_rate = 0.5;        % drop ratio when performing dropout

%% Perform training
args = struct(...
        'trainpath',train_path,...
        'testpath',test_path,...
        'rateonce',rate_once,...
        'L',L,...
        'T', T,...
        'seed',seed,...
        'niter',n_iter,...
        'lrate',learning_rate,...
        'l2',l2,...
        'negsample',neg_samples,...
        'earlystop',early_stop,...
        'd',d,...
        'nv',nv,...
        'nh',nh,...
        'acconv',ac_conv,...
        'acfc',ac_fc,...
        'droprate',drop_rate...
        );

caser_train(args);


function [Q, R] = qr(A, econ)
%QR   QR factorization of an array-valued CHEBFUN.
%   [Q, R] = QR(A) or QR(A, 0), where A is a column CHEBFUN with n columns,
%   produces a column CHEBFUN Q with n orthonormal columns and an n x n upper
%   triangular matrix R such that A = Q*R.
%
% See also SVD, MRDIVIDE, RANK.

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

% Check inputs:
if ( (nargin == 2) && (econ ~= 0) )
    error('CHEBFUN:CHEBFUN:qr:twoargs',...
      ['Use qr(A) or qr(A, 0) for QR decomposition of an array-valued ' ...
      'CHEBFUN or quasimatrix']);
elseif ( A(1).isTransposed )
    error('CHEBFUN:CHEBFUN:qr:transpose',...
        'CHEBFUN QR works only for column CHEBFUN objects.')
elseif ( ~all(isfinite(A(1).domain)) )
    error('CHEBFUN:CHEBFUN:qr:infdomain', ...
        'CHEBFUN QR does not support unbounded domains.');
end

numCols = numColumns(A);
if ( numCols == 1 )
    % Trivial case: If A has only one column we simply scale it.
    R = sqrt(innerProduct(A, A));
    if ( R ~= 0 )
       Q = A./R;
    else
       Q = 1./sqrt(diff(A.domain)) + 0*A;
    end
    return
end

% Attempt to convert to an array-valued CHEBFUN:
[A, isArrayValued] = quasi2cheb(A);

if ( isArrayValued && (numel(A.funs) == 1) )
    % Array-valued CHEBFUN with a single FUN.

    % Call QR at the FUN level:
    [Q, R] = qr(A.funs{1});
    Q = chebfun({Q});

elseif ( isArrayValued )
    % Array-valued CHEBFUN with multiple FUNS.

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Developer note:
    %   Here we essentially use a panel-factored QR which allows us to do a QR
    %   factorization on each fun individually and then combine the result.
    %   Here's an example of this in a 2-FUN case:
    %    [A1] = [Q1*R^1] = [Q1 0][R^1] = [Q1 0][Q^1 ~][R] = [Q1*Q^1]R
    %    [A2] 1 [Q2*R^2]   [0 Q2][R^2] 2 [0 Q2][Q^2 ~][0] 3 [Q2*Q^2]
    %                                  ^
    %                               here [Q^:=Qhat, R] = qr(Rhat:=[R^1;R^2])
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    numFuns = numel(A.funs);

    % Step 1: Perform QR on each piece.
    Q = cell(numFuns, 1); Rhat = Q;
    for k = 1:numFuns
        [Q{k}, Rhat{k}] = qr(A.funs{k});
    end

    % Step 2: Compute [Qhat, R] = qr(Rhat),
    [Qhat, R] = qr(cell2mat(Rhat));
    R = R(1:numCols,:);       % Extract first block row.
    Qhat = Qhat(:,1:numCols); % Extract first block column.

    % Step 2b: Ensure the diagonal is non-negative. (A = QR = (Q*S)*(S*R))
    s = sign(diag(R)); s(~s) = 1;
    S = spdiags(s, 0, numCols, numCols);
    Qhat = Qhat*S;
    R = S*R;

    % Step 2c: Separate the segments of Qhat back into a cell.
    m = cellfun(@(v) size(v, 1), Rhat); % m(k) = length of A.FUN{k}.
    Qhat = mat2cell(Qhat, m, numCols);

    % Step 3: Fold Qhat back in to Q.
    Q = cellfun(@mtimes, Q, Qhat, 'UniformOutput', false);

    % Construct a new CHEBFUN from the computed FUNS:
    Q = chebfun(Q);

else
    % Quasimatrix case (tricky/slow):

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Developer note:
    %   Currently (5th Feb 2016) the only way this is reachable is in the
    %   case of a quasimatrix consisting of SINGFUN or DELTAFUN objects,
    %   neither of which return anything sensible when we attempt to compute
    %   a QR factorization. Try for example
    %    x = chebfun('x', [0 1]);
    %    qr([1 x sqrt(x)])
    %
    %   This case is not tested (which is OK)
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    % Legendre-Vandermonde matrix:
    L = legpoly(0:numCols-1, domain(A), 'norm', 1);
    % Convert so that L is also quasimatrix:
    L = cheb2quasi(L);
    % Call abstract QR:
    [Q, R] = abstractQR(A, L, @innerProduct, @normest);

end

end


function box = mergeBoxes3d(box1, box2)
%MERGEBOXES3D Merge 3D boxes, by computing their greatest extent.
%
%   BOX = mergeBoxes3d(BOX1, BOX2);
%
%   Example
%   box1 = [5 20 5 30 10 50];
%   box2 = [0 15 0 15 0 20];
%   mergeBoxes3d(box1, box2)
%   ans =
%       0 20 0 30 0 50
%
%
%   See also
%   boxes3d, drawBox3d, intersectBoxes3d
%

% ------
% Author: David Legland
% E-mail: david.legland@grignon.inra.fr
% Created: 2010-07-26, using Matlab 7.9.0.529 (R2009b)
% Copyright 2010-2022 INRA - Cepia Software Platform

% unify sizes of data
if size(box1,1) == 1
    box1 = repmat(box1, size(box2,1), 1);
elseif size(box2, 1) == 1
    box2 = repmat(box2, size(box1,1), 1);
elseif size(box1,1) ~= size(box2,1)
    error('Bad size for inputs');
end

% compute extreme coords
mini = min(box1(:,1:2:end), box2(:,1:2:end));
maxi = max(box1(:,2:2:end), box2(:,2:2:end));

% concatenate result into a new box structure
box = [mini(:,1) maxi(:,1) mini(:,2) maxi(:,2) mini(:,3) maxi(:,3)];


function varargout = cgal_insurftri(varargin)
% CGAL_INSURFTRI  Find whether a point is inside or outside a closed
% surface.
%
%   This function evaluates whether one or more points belong inside a
%   closed surface. First, we check whether the point is on the surface
%   itself (in that case, it's considered inside). If not, a ray is
%   projected from the point and the intersections with the surface are
%   counted. An odd number means that the point is inside. This approach
%   fails if the point is not on the surface, but the ray lies on the
%   surface or crosses a vertex, because this spans many arbitrary
%   intersections. To solve this problem, a few rays are used for each
%   point, and the majority vote decides whether it's inside or outside.
%
% ISIN = cgal_insurftri(TRI, X, XI)
%
%   TRI is a 3-column matrix. Each row represents the indices of the three
%   vertices that form a triangle. TRI as a whole represents the closed
%   surface.
%
%   X is a 3-column matrix. Each row represents the Cartesian coordinates
%   of a vertex on the surface, indexed by TRI values.
%
%   XI is a 3-column matrix. Each row represents the Carterian coordinates
%   of a point for which we want to find whether it's inside or outside the
%   closed surface. Note that if you want to test all the voxels in an
%   image, it is very slow and memory intensive to generate coordinates for
%   each voxel. In that scenario, it is much better to use the cell array
%   CI syntax shown below, and provide only values for the coordinate axes.
%
%   ISIN is a boolean vector with one element per point in XI. True means
%   that the corresponding point is inside the closed surface (or on the
%   surface), and false means that it's outside.
%
% ISIN = cgal_insurftri(TRI, X, CI)
%
%   CI is a cell array CI={XI, YI, ZI}, where XI, YI and ZI are row vectors
%   that describe a rectangular grid. For example,
%
%     CI={linspace(-.25, .25, 5), ...
%         linspace(-.25, .25, 4), ...
%         linspace(-.25, .25, 3)};
%
%   describes a sampling grid of 4 rows x 5 columns x 3 slices (note that
%   rows correspond to YI and columns to XI), of a domain
%   [-0.25, 0.25] x [-0.25, 0.25] x [-0.25, 0.25].
%
% ISIN = cgal_insurftri(..., DIRECTIONS, TOL)
%
%   DIRECTIONS is a 3-column matrix. Each row represents a vector with a
%   ray direction. By default,
%
%          DIRECTIONS=[ 1.0,  0.0,  0.0; ...
%                      -1.0,  1.0,  1.0; ...
%                      -1.0, -1.0, -1.0]
%
%   This default can fail with regular voxels, as rays may cross vertices.
%   A good practical alternative is to use a few random directions, e.g.
%
%          DIRECTIONS=rand(5, 3);
%
%   Warning! For the voting system to make sense, select an odd number of
%   rays.
%
%   TOL is a scalar with the distance tolerance. Points at distance <= TOL
%   are considered to be on the surface, and thus "inside". By default,
%   TOL=1e-15.

% Author: Ramon Casero <rcasero@gmail.com>
% Copyright © 2012-2013 University of Oxford
% Version: 0.2.0
%
% University of Oxford means the Chancellor, Masters and Scholars of
% the University of Oxford, having an administrative office at
% Wellington Square, Oxford OX1 2JD, UK.
%
% This file is part of Gerardus.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details. The offer of this
% program under the terms of the License is subject to the License
% being interpreted in accordance with English Law and subject to any
% action against the University of Oxford being under the jurisdiction
% of the English Courts.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see
% <http://www.gnu.org/licenses/>.

error('MEX file not found')


function calpak_test010 ( )

%*****************************************************************************80
%
%% CALPAK_TEST010 tests JED_TO_YJF_HEBREW and YJF_TO_JED_HEBREW.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 March 2013
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALPAK_TEST010\n' );
  fprintf ( 1, '  For the Hebrew calendar:\n' );
  fprintf ( 1, '  JED_TO_YJF_HEBREW: JED -> YJF.\n' );
  fprintf ( 1, '  YJF_TO_JED_HEBREW: YJF -> JED.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  JED (in)    YJF                JED (out)\n' );
  fprintf ( 1, '\n' );

  jed_epoch = epoch_to_jed_hebrew ( );

  i = 0;

  while ( 1 )

    i = i + 1;
    jed1 = jed_test ( i );

    if ( jed1 < 0.0 )
      break
    end

    if ( jed_epoch <= jed1 )

      [ y2, j2, f2 ] = jed_to_yjf_hebrew ( jed1 );

      s2 = yjf_to_s_hebrew ( y2, j2, f2 );

      jed3 = yjf_to_jed_hebrew ( y2, j2, f2 );

      fprintf ( 1, '  %11.2f  %20s  %11.2f\n', jed1, s2, jed3 );

    end

  end

  return
end


% MatrixUser, a multi-dimensional matrix analysis software package
% https://sourceforge.net/projects/matrixuser/
%
% The MatrixUser is a matrix analysis software package developed under Matlab
% Graphical User Interface Developing Environment (GUIDE). It features
% functions that are designed and optimized for working with multi-dimensional
% matrix under Matlab. These functions typically includes functions for
% multi-dimensional matrix display, matrix (image stack) analysis and matrix
% processing.
%
% Author:
%   Fang Liu <leoliuf@gmail.com>
%   University of Wisconsin-Madison
%   Aug-30-2014

function MU_funcFreeROI(Temp,Event,handles)
global Figure_handles;
MU_main_handles=guidata(Figure_handles.MU_main);
handles = guidata(handles.MU_matrix_display);

MU_enable('off',[],handles);
ROI_h=imfreehand;
MU_enable('on',[],handles);

MU_main_handles.V.ROIs{end+1,1}='imfreehand';
MU_main_handles.V.ROIs{end,2}=ROI_h;
MU_main_handles.V.ROIs{end,3}=getPosition(ROI_h);
ROI_ind=length(MU_main_handles.V.ROIs(:,1));

p=round(getPosition(ROI_h));
if max(p(:,1))>handles.V.Column | max(p(:,2))>handles.V.Row | min(p(:,1))<1 | min(p(:,2))<1
    delete(ROI_h);
    errordlg('Out of range subscript.');
    return;
end
BW=createMask(ROI_h);
p=[min(p(:,1)) min(p(:,2)) max(p(:,1))-min(p(:,1)) max(p(:,2))-min(p(:,2))];
TTMatrix=handles.BMatrix(p(2):p(2)+p(4),p(1):p(1)+p(3));
TTMatrix=TTMatrix(double(BW(p(2):p(2)+p(4),p(1):p(1)+p(3)))~=0);
ROI_Stat_h=text(p(1)+p(3),p(2)+p(4),{[' ROI#: ' num2str(ROI_ind)]; ...
                                     [' mean: ' num2str(mean(double(TTMatrix(:))))]; ...
                                     [' sd:' num2str(std(double(TTMatrix(:))))]; ...
                                     [' sd(%):' num2str(abs(std(double(TTMatrix(:)))./mean(double(TTMatrix(:)))*100))]},...
                                     'FontSize',10,'Color','g');

handles.V.ROI=struct(...
                     'ROI_flag', 1,...
                     'ROI_mov',[],...  % ROI movement track
                     'ROI_Stat_h', ROI_Stat_h,... % ROI stats
                     'ROI_h', ROI_h ... % ROI handle
                     );
handles.ROIData=TTMatrix;
guidata(handles.MU_matrix_display, handles);
guidata(Figure_handles.MU_main,MU_main_handles);

addNewPositionCallback(ROI_h,@(p) MU_ROI_stat(p,ROI_h,ROI_ind,handles));
fcn=makeConstrainToRectFcn('imfreehand',[0.5 handles.V.Column+0.4],[0.5 handles.V.Row+0.4]);
setPositionConstraintFcn(ROI_h,fcn);

end


function calpak_test275 ( )

%*****************************************************************************80
%
%% CALPAK_TEST275 tests JED_TO_YMDF_ZOROASTRIAN and YMDF_TO_JED_ZOROASTRIAN.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 March 2013
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALPAK_TEST275\n' );
  fprintf ( 1, '  For the Zoroastrian calendar:\n' );
  fprintf ( 1, '  JED_TO_YMDF_ZOROASTRIAN: JED -> YMDF.\n' );
  fprintf ( 1, '  YMDF_TO_JED_ZOROASTRIAN: YMDF -> JED.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  JED (in)    YMDF                JED (out)\n' );
  fprintf ( 1, '\n' );

  jed_epoch = epoch_to_jed_zoroastrian ( );

  i = 0;

  while ( 1 )

    i = i + 1;
    jed1 = jed_test ( i );

    if ( jed1 < 0.0 )
      break
    end

    if ( jed_epoch <= jed1 )

      [ y2, m2, d2, f2 ] = jed_to_ymdf_zoroastrian ( jed1 );

      s2 = ymdf_to_s_numeric ( y2, m2, d2, f2 );

      jed3 = ymdf_to_jed_zoroastrian ( y2, m2, d2, f2 );

      fprintf ( 1, '  %11.2f  %20s  %11.2f\n', jed1, s2, jed3 );

    end

  end

  return
end


function family=getclusterstat(c)

%GETCLUSTERSTAT gets detais of individual correlation clusters.
% family = GETCLUSTERSTAT(C) outputs a structure FAMILY which contains
% pertinent details of clusters that exist in C. This is a simple routine
% that assumes all cluster calculation has already been done. Note that in
% many cases it may be more appropriate to get the direct CLUST field from
% a correlation object. In some cases however, GETCLUSTERSTAT may be more
% expedient. The FAMILY structure includes the fields:
%   rank:    size order of the cluster (scalar)
%   numel:   number of events in the cluster (scalar)
%   index:   the index of the cluster events in the correlation object(Nx1)
%   trig:    trigger times of the cluster events (Nx1)
%   begin:   the eariest trigger time in the cluster (scalar)
%   finish:  the last trigger time in the cluster (scalar)
% The fields index and trig are cell arrays.
%
% See also correlation/cluster

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

if nargin <= 0
    error('Wrong number of inputs');
end

if ~isa(c,'correlation')
    error('First input must be a correlation object');
end

if isempty(get(c,'CLUST'))
    error('CLUSTER field must be filled in input argument. See HELP CLUSTER');
end

for n = 1:max(get(c,'CLUST'))
    f = find(c,'CLUST',n);
    c1 = subset(c,f);
    family.rank(n) = n;
    family.numel(n) = numel(f);
    family.index(n) = {f};
    family.begin(n) = min(get(c1,'TRIG'));
    family.finish(n) = max(get(c1,'TRIG'));
    family.trig(n) = {get(c1,'TRIG')};
end


function [x_hat,PSNR,estFin,estHist] = VAMP(y,iters,n,M_func,Mt_func,PSNR_func,U_func,Ut_func,d,UtM_func,MtU_func)
%
% [x_hat,PSNR] = VAMP(y,iters,n,M_func,Mt_func,PSNR_func)
%
% This function implements VAMP for sparse recovery
%
% Inputs:
%       y       : the measurements
%       iters   : the number of iterations
%       n       : signal size
%       M_func  : function handle that projects onto A. Or a matrix A.
%       Mt_func : function handle that projects onto A'. Or no entry
%       PSNR_func : optional function handle to evaluate PSNR
%
% Output:s
%       x_hat   : the recovered signal.
%       PSNR    : the PSNR trajectory.

vampOpt = VampSlmOpt3;
vampOpt.nitMax = iters;

if (nargin>4)&&(~isempty(Mt_func)) % function handles
    vampOpt.Ah = Mt_func;
    vampOpt.N = n;
end
if (nargin>5)&&(~isempty(PSNR_func)) % error trajectory
    vampOpt.fxnErr = @(x2) PSNR_func(x2);
end
if (nargin>6) % external eigendecomposition [U,D]=eig(M_func(Mt_func(I)))
    vampOpt.U = @(x) U_func(x); % function handle to U
    vampOpt.Uh = @(x) Ut_func(x); % function handle to U'
    vampOpt.d = d; % eigenvalues d=diag(D)
end
if (nargin>9) % external SVD [U,S,V]=svd(M_func) with U matching eigenvectors above
    vampOpt.UhA = @(x) UtM_func(x); % function handle to U'*M = S*V'
    vampOpt.AhU = @(x) MtU_func(x); % function handle to M'*U = V*S'
end

% prepare for VAMP
alf = 1.0;
debias = false; % automatically debias the soft thresholder?
denoi = SoftThreshDMMEstimIn(alf,'debias',debias);

% run VAMP
if nargout==4
  [x_hat,estFin,estHist] = VampSlmEst3(denoi,y,M_func,vampOpt);
else
  [x_hat,estFin] = VampSlmEst3(denoi,y,M_func,vampOpt);
end
PSNR = estFin.err;


%% Copyright (C) 2014-2016, 2019, 2022 Colin B. Macdonald
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy 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 software 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 software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @defmethod  @@sym symsum (@var{f}, @var{n}, @var{a}, @var{b})
%% @defmethodx @@sym symsum (@var{f}, @var{n}, [@var{a} @var{b}])
%% @defmethodx @@sym symsum (@var{f}, @var{a}, @var{b})
%% @defmethodx @@sym symsum (@var{f}, [@var{a} @var{b}])
%% @defmethodx @@sym symsum (@var{f}, @var{n})
%% @defmethodx @@sym symsum (@var{f})
%% Symbolic summation.
%%
%% The sum of the expression @var{f} for @var{n} from @var{a} to
%% @var{b}.  When @var{n} is omitted it is determined using
%% @code{symvar} and defaults to @code{x} if @var{f} is constant. The
%% limits @var{a} and @var{b} default to 0 and @var{n} - 1
%% respectively.
%%
%% @example
%% @group
%% syms n m
%% symsum(1/n^2, n, 1, m)
%%   @result{} (sym) harmonic(m, 2)
%%
%% symsum(exp(2*n)/sin(n), n, 2*m, 6*m)
%%   @result{} (sym)
%%           6⋅m
%%           ____
%%           ╲
%%            ╲      2⋅n
%%             ╲    ℯ
%%             ╱   ──────
%%            ╱    sin(n)
%%           ╱
%%           ‾‾‾‾
%%         n = 2⋅m
%% @end group
%% @end example
%%
%% @seealso{@@sym/symprod, @@sym/sum}
%% @end defmethod

function S = symsum(f, n, a, b)

  if (nargin > 4)
    print_usage ();
  end

  idx1.type = '()';
  idx1.subs = {1};
  idx2.type = '()';
  idx2.subs = {2};

  if (nargin == 1)
    n = symvar(f, 1);
    if (isempty(n))
      n = sym('x');
    end
    a = sym(0);
    b = n - 1;
  elseif (nargin == 2) && (length(n) == 2)
    f = sym(f);
    %a = n(1);  % issue #17
    %b = n(2);
    a = subsref(n, idx1);
    b = subsref(n, idx2);
    n = symvar(f, 1);
    if (isempty(n))
      n = sym('x');
    end
  elseif (nargin == 2)
    f = sym(f);
    n = sym(n);
    a = sym(0);
    b = n - 1;
  elseif (nargin == 3) && (length(a) == 2)
    f = sym(f);
    n = sym(n);
    %b = a(2);  % issue #17
    %a = a(1);
    b = subsref(a, idx2);
    a = subsref(a, idx1);
  elseif (nargin == 3)
    f = sym(f);
    b = a;
    a = n;
    n = symvar(f, 1);
    if (isempty(n))
      n = sym('x');
    end
  else
    f = sym(f);
    n = sym(n);
    a = sym(a);
    b = sym(b);
  end

  cmd = { '(f, n, a, b) = _ins'
           'S = sp.summation(f, (n, a, b))'
           'return S,' };

  S = pycall_sympy__ (cmd, sym(f), sym(n), sym(a), sym(b));

end

%!error symsum (sym(1), 2, 3, 4, 5)

%!test
%! % finite sums
%! syms n
%! assert (isequal (symsum(n,n,1,10), 55))
%! assert(isa(symsum(n,n,1,10), 'sym'))
%! assert (isequal (symsum(n,n,sym(1),sym(10)), 55))
%! assert (isequal (symsum(n,n,sym(1),sym(10)), 55))
%! assert (isequal (symsum(1/n,n,1,10), sym(7381)/2520))

%!test
%! % negative limits
%! syms n
%! assert (isequal (symsum(n,n,-3,3), sym(0)))
%! assert (isequal (symsum(n,n,-3,0), sym(-6)))
%! assert (isequal (symsum(n,n,-3,-1), sym(-6)))

%!test
%! % one input
%! syms n
%! f = symsum (n);
%! g = n^2/2 - n/2;
%! assert (isequal (f, g))
%! f = symsum (2*n);
%! g = n^2 - n;
%! assert (isequal (f, g))

%!test
%! % constant input
%! f = symsum (sym(2));
%! syms x
%! g = 2*x;
%! assert (isequal (f, g))

%!test
%! % two inputs
%! syms n
%! f = symsum (2*n, n);
%! g = n^2 - n;
%! assert (isequal (f, g))

%!test
%! % two inputs, second is range
%! syms n
%! f = symsum (n, [1 6]);
%! g = 21;
%! assert (isequal (f, g))
%! f = symsum (n, [sym(1) 6]);
%! g = 21;
%! assert (isequal (f, g))
%! f = symsum (2*n, [1 6]);
%! g = 2*21;
%! assert (isequal (f, g))

%!test
%! % three inputs, last is range
%! syms n
%! f = symsum (2*n, n, [1 4]);
%! g = sym(20);
%! assert (isequal (f, g))
%! f = symsum (2*n, n, [sym(1) 4]);
%! g = sym(20);
%! assert (isequal (f, g))
%! f = symsum (2, n, [sym(1) 4]);
%! g = sym(8);
%! assert (isequal (f, g))

%!test
%! % three inputs, no range
%! syms n
%! f = symsum (2*n, 1, 4);
%! g = sym(20);
%! assert (isequal (f, g))
%! f = symsum (5, sym(1), 3);
%! g = sym(15);
%! assert (isequal (f, g))

%!test
%! % ok to use double's for arguments in infinite series
%! syms n oo
%! assert(isequal(symsum(1/n^2,n,1,oo), sym(pi)^2/6))
%! assert(isequal(symsum(1/n^2,n,1,inf), sym(pi)^2/6))

%!test
%! % should be oo because 1 is real but seems to be
%! % zoo/oo depending on sympy version
%! syms n oo
%! zoo = sym('zoo');
%! assert (isequal (symsum(1/n,n,1,oo), oo) || ...
%!         isequal (symsum(1/n,n,1,oo), zoo))


% HKS_matching
clear all; close all; clc;

gptoolbox_path = ''; % complete
addpath(genpath(gptoolbox_path));

data_folder = '..\data\';
meshes = dir([data_folder,'*.o*']); % a list of all the meshes in the data folder
meshes = {meshes.name}; % access each mesh name by meshes{i}

cam_folder = [data_folder, 'cams\'];
cams = dir([cam_folder,'*.mat']); % a list of all the cam in the cams folder
cams = {cams.name};

addpath(data_folder); addpath(cam_folder);

%%
% % For dragon model:
% [V, F] = readOBJ(meshes{8});
% cam = cams{8};
% landmarks = [6921; 6827; 9683; 9710]; % right front leg, left front leg, right back leg, left back leg,
% figure; MESH_VIS.mesh(F,V,'cams',cam,'landmarks',landmarks);

% % For cat model:
[V, F] = readOFF(meshes{4});
cam = cams{4};
landmarks = [3048; 1994; 6621; 5560]; % right front leg, left front leg, right back leg, left back leg,
figure; MESH_VIS.mesh(F,V,'cams',cam,'landmarks',landmarks);

% % For xyzrgb_dragon1 model:
% [V, F] = readOBJ(meshes{14});
% cam = cams{8};
% landmarks = [91921; 58423; 51903; 52775]; % right front leg, left front leg, right back leg, left back leg,

%% Matching:
% to compute the HKS, use gptoolbox's: [K,MK] = hks(V,F)
% and to mormalize the hks use: K./MK


function model = dnetCreate(inputDim, outputDim, Y, options)

% DNETCREATE Density network model.
% FORMAT
% DESC creates a structure for a density network.
% ARG inputDimension : dimension of latent data.
% ARG outputDim : dimension of observed data.
% ARG Y : the data to be modelled in design matrix format (as many
% rows as there are data points).
% ARG options : options structure as returned by dnetCreate.
% RETURN model : model structure containing the density network
% specified.
%
% COPYRIGHT : Neil D. Lawrence, 2008
%
% SEEALSO : dnetOptions, mlpCreate, rbfCreate, kbrCreate

% MLTOOLS

model.type = 'dnet';

if size(Y, 2) ~= outputDim
  error(['Input matrix Y does not have dimension ' num2str(d)]);
end

if isstr(options.initX)
  initFunc = str2func([options.initX 'Embed']);
  model.X = initFunc(Y, inputDim);
else
  if size(options.initX, 1) == size(Y, 1) ...
        & size(options.initX, 2) == inputDim
    model.X = options.initX;
  else
    error('options.initX not in recognisable form.');
  end
end

model.q = inputDim;
model.d = outputDim;
model.N = size(Y, 1);

model.mapping = modelCreate(options.mappingType, inputDim, ...
                            outputDim, options.mappingOptions);
model.M = options.M;
model.y = Y;
model.w = repmat(1/model.M, model.N, model.M);
model.betaTransform =  optimiDefaultConstraint('positive');

model.beta = exp(-2);
model.grid = options.grid;

if ~isempty(model.grid)
  minVals = 1.2*min(model.X);
  maxVals = 1.2*max(model.X);
  x = linspace(minVals(1), maxVals(1), model.grid(1));
  y = linspace(minVals(2), maxVals(2), model.grid(2));
  [mx, my] = meshgrid(x, y);
  for i = 1:size(model.grid)
    model.X_u = [mx(:) my(:)];
  end
else
  model.X_u = randn(model.M, model.q);
end

logw = -dist2(model.X, model.X_u);
logw = logw -repmat(max(logw, [], 2), 1, model.M);
model.w = exp(logw)./repmat(sum(exp(logw), 2), 1, model.M);

model.basisStored = options.basisStored;

model.alpha = options.alpha;

params = dnetExtractParam(model);
model = dnetExpandParam(model, params);

if model.basisStored
  model = dnetUpdateOutputWeights(model);
  model = dnetUpdateBeta(model);
end

model.numParams = model.mapping.numParams + 1;
model.outputDim = model.d;
model.inputDim = model.q;


function i4_to_pascal_test ( )

%*****************************************************************************80
%
%% I4_TO_PASCAL_TEST tests I4_TO_PASCAL.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 April 2015
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'I4_TO_PASCAL_TEST\n' );
  fprintf ( 1, '  I4_TO_PASCAL converts a linear index to\n' );
  fprintf ( 1, '  Pascal triangle indices.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '     K  =>   I     J\n' );
  fprintf ( 1, '\n' );

  for k = 1 : 20

    [ i, j ] = i4_to_pascal ( k );

    fprintf ( 1, '  %4d    %4d  %4d\n', k, i, j );

  end

  return
end


clear; close all; clc;

fx = 1;
x = 0;

for i = 1:5
    x = [x, x(i)+0.5];
    fx = [fx, fx(i)*1.5];
end

stem(x, fx,'linewidth',2)
grid on;
set(gca,'ytick',round(fx,2))
xlabel('$$x$$','interpreter','latex');
ylabel('$$f(x)$$','interpreter','latex');
set(gca,'fontsize',11)

github-repos/MATLAB/angeloyeo-gongdols/gongdols-7be9fbd988dec6edab1dc881cb22d63e6f69398d/기초수학/e^x는 왜 미분해도 e^x일까/pics.m


function pass = test_uplus( pref )
% This tests the basic arithmetic operations on chebfun2 objects.

if ( nargin < 1 )
    pref = chebfunpref;
end
tol = 1e5 * pref.cheb2Prefs.chebfun2eps;
j = 1;

D = [-1 1 -1 1; -2 2 -2 2; -1 pi 0 2*pi];

for r = 1 : size(D,1)
    f = chebfun2(@(x,y) cos(x.*y), D(r,:));

    uplusF = f;
    tolr = norm(D(r,:),inf)*tol;

    pass(j) = ( norm( f - uplusF ) < tolr ); j = j + 1;
end

end


function c = u2nonucfmt(cu, p)
%U2NONUCFMT Uniform to non-uniform filterbank coefficient format
%   Usage:  c=u2nonucfmt(cu,pk)
%
%   Input parameters:
%         cu   : Uniform filterbank coefficients.
%
%   Output parameters:
%         c    : Non-uniform filterbank coefficients.
%         p    : Numbers of copies of each filter.
%
%   `c = u2nonucfmt(cu,pk)` changes the coefficient format from
%   uniform filterbank coefficients *cu* (`M=sum(p)` channels) to
%   non-uniform coefficients *c* (`numel(p)` channels)  such that each
%   channel of *c* consinst of `p(m)` interleaved channels of *cu*.
%
%   The output *c* is a cell-array in any case.
%
%   See also: nonu2ufilterbank
%
%   References: akkva2003

complainif_notenoughargs(nargin,2,mfilename);

if isempty(cu)
   error('%s: cu must be non-empty.',upper(mfilename));
end

if iscell(cu)
    if any(cellfun(@isempty,cu));
      error('%s: Elements of cu must be non-empty.',upper(mfilename));
    end

    M = numel(cu);
    W = size(cu{1},2);

    Lc = size(cu{1},1);
    if any(Lc~=cellfun(@(cEl)size(cEl,1),cu))
        error('%s: Coefficient subbands do not have an uniform length',...
              upper(mfilename));
    end
elseif isnumeric(cu)
    M = size(cu,2);
    W = size(cu,3);
    Lc = size(cu,1);
else
    error('%s: cu must be a cell array or numeric.',upper(mfilename));
end

if isempty(p) || ~isvector(p)
   error('%s: p must be a non-empty vector.',upper(mfilename));
end

if sum(p) ~= M
    error(['%s: Total number of filters in p does not comply with ',...
           'number of channels'],upper(mfilename));
end

Mnonu = numel(p);
c = cell(Mnonu,1);
p = p(:);
pkcumsum = cumsum([1;p]);
crange = arrayfun(@(pEl,pcEl)pcEl:pcEl+pEl-1,p,pkcumsum(1:end-1),'UniformOutput',0);

if iscell(cu)
    for m=1:Mnonu
        ctmp = [cu{crange{m}}].';
        c{m} = reshape(ctmp(:),W,[]).';
    end
else
    for m=1:Mnonu
        c{m} = zeros(p(m)*Lc,W,assert_classname(cu));
        for w=1:W
            c{m}(:,w) = reshape(cu(:,crange{m},w).',1,[]);
        end
    end
end

% Post check whether there is the same number of coefficients
if sum(cellfun(@(cEl) size(cEl,1),c)) ~= M*Lc
    error(['%s: Invalid number of coefficients in subbands.'],upper(mfilename));
end


function h=m_text(long,lat,varargin)
% M_TEXT Text Annotation
%    M_TEXT(LONG,LAT,'string') adds the text in the quotes to location
%    (LONG,LAT) on the currently defined map projection. If LONG and LAT
%    are vectors, M_TEXT writes the text at all locations given.
%    If 'string' is an array the same number of rows as the
%    length of LONG and LAT, M_TEXT marks each point with the
%    corresponding row of the 'string' array.
%
%    M_TEXT returns a column vector of handles to TEXT objects, one
%    handle per text object. TEXT objects are children of AXES objects.
%
%    M_TEXT(LONG,LAT,'string',property/value pairs) can be used to
%    change fontsize, weight, color, etc using the standard TEXT
%    properties.
%
%    See also TEXT.

% Rich Pawlowicz (rich@ocgy.ubc.ca) 17/Jan/1998
%
% This software is provided "as is" without warranty of any kind. But
% it's mine, so you can't sell it.

% 31/Jul/99 - changed to allow for X/Y vectors.
% 6/Nov/00 - eliminate returned stuff if ';' neglected (thx to D Byrne)

global MAP_PROJECTION

% Have to have initialized a map first

if isempty(MAP_PROJECTION)
  disp('No Map Projection initialized - call M_PROJ first!');
  return;
end

[X,Y]=m_ll2xy(long,lat,'clip','off');
%h=text('position',[X(:) Y(:)],'tag','m_text','string',varargin{:});
% Fix to allow vectors of X/Y to work
h=text(X(:),Y(:),varargin{:});
if ~isempty(h) && isempty(get(h(1),'tag'))
 set(h,'tag','m_text');
end

if nargout==0
 clear h
end


classdef TestSparsePyrLKOpticalFlow
    %TestSparsePyrLKOpticalFlow

    methods (Static)
        function test_1
            im1 = 255*uint8([...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 1 1 1 0 0 0 0;...
                0 0 0 1 0 1 0 0 0 0;...
                0 0 0 1 1 1 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
                0 0 0 0 0 0 0 0 0 0;...
            ]);
            im2 = circshift(im1, [0 1]);
            alg = cv.SparsePyrLKOpticalFlow();
            pts = alg.calc(im1, im2, {[3,3]});
        end

        function test_2
            prevImg = cv.imread(fullfile(mexopencv.root(),'test','RubberWhale1.png'), ...
                'Grayscale',true, 'ReduceScale',2);
            nextImg = cv.imread(fullfile(mexopencv.root(),'test','RubberWhale2.png'), ...
                'Grayscale',true, 'ReduceScale',2);
            prevPts = cv.goodFeaturesToTrack(prevImg, 'MaxCorners',200);
            alg = cv.SparsePyrLKOpticalFlow();
            [nextPts,status,err] = alg.calc(prevImg, nextImg, prevPts);
            validateattributes(nextPts, {'cell'}, ...
                {'vector', 'numel',numel(prevPts)});
            cellfun(@(pt) validateattributes(pt, {'numeric'}, ...
                {'vector', 'numel',2}), nextPts);
            validateattributes(status, {'uint8'}, ...
                {'vector', 'binary', 'numel',numel(nextPts)});
            validateattributes(err, {'single'}, ...
                {'vector', 'real', 'numel',numel(nextPts)});
        end
    end

end


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

%%
clear; close all; clc;

%% Syntax
% |[meshStruct]=tetMeshBox(boxDim,pointSpacing);|

%% Description
% This function generates a mesh structure containing element and node data
% for a tetrahedral element meshed box. The box dimensions in each of the 3
% directions are based on the boxDim input (1x3 vector). The number of
% elements in each direction is based on the pointSpacing input.

%% Examples

%%
% Plot settings

fontSize=20;
faceAlpha1=0.8;

%% CREATING A MESHED BOX
boxDim=[5 6 7]; % Box dimenstions
pointSpacing=1;

[meshStruct]=tetMeshBox(boxDim,pointSpacing);

%%
% Acces output fields
E=meshStruct.elements;
V=meshStruct.nodes;
F=meshStruct.faces;
Fb=meshStruct.facesBoundary;
faceBoundaryMarker=meshStruct.boundaryMarker;

%%
% Plotting model
cFigure;
title('Box boundaries faces','FontSize',fontSize);
hold on;

gpatch(Fb,V,faceBoundaryMarker,'k',faceAlpha1);
% patchNormPlot(Fb,V);

axisGeom(gca,fontSize);
colormap(gjet(6)); icolorbar;
drawnow;

%%
% Visualizing model internal mesh with |meshView|

meshView(meshStruct);

%%
%
% <<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 p02_title ( )

%*****************************************************************************80
%
%% P02_TITLE prints a title for problem 02.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    None
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'Problem 02\n' );
  fprintf ( 1, '  Name:       QuadSum\n' );
  fprintf ( 1, '              Davis, Rabinowitz, page 370, #1.\n' );
  fprintf ( 1, '  Region:     0 <= X(i) <= 1\n' );
  fprintf ( 1, '  Integrand:  F(X) = ( sum ( 2 * X(i) - 1 ) )^4\n' );

  return
end


% Compute derivative k'(x^p,x^q) of a stationary covariance k(d2) (ard or iso)
% w.r.t. to squared distance d2 = (x^p - x^q)'*inv(P)*(x^p - x^q) measure. Here
% P is either diagonal with ARD parameters ell_1^2,...,ell_D^2 where D is the
% dimension of the input space or ell^2 times the unit matrix for isotropic
% covariance.
% The derivatives can only be computed for one of the following eight
% covariance functions: cov{Matern|PP|RQ|SE}{iso|ard}.
%
% Copyright (c) by Hannes Nickisch, 2013-10-28.
%
% See also INFFITC.M, COVFITC.M.

function Kp = cov_deriv_sq_dist(cov,hyp,x,z)
  if nargin<4, z = []; end                                 % make sure, z exists
  xeqz = numel(z)==0; dg = strcmp(z,'diag') && numel(z)>0;      % determine mode

  if iscell(cov), covstr = cov{1}; else covstr = cov; end
  if ~ischar(covstr), covstr = func2str(covstr); end
  if numel([strfind(covstr,'iso'),strfind(covstr,'ard')])==0
    error('Only iso|ard covariances allowed for derivatives w.r.t. xu.')
  elseif numel([strfind(covstr,'covLIN');
                strfind(covstr,'covGabor');
                strfind(covstr,'covPER')])>0
    error('Gabor|LIN|PER covariances not allowed for derivatives w.r.t. xu.')
  end

  [n,D] = size(x);
  if numel(strfind(covstr,'iso')), id = 1:D; else id = 1; end  % *iso covariance
  ell1 = exp(hyp(1));                        % first characteristic length scale

  Kp = feval(cov{:},hyp,x,z,1);              % use derivative w.r.t. log(ell(1))
  % precompute squared distances
  if dg                                                             % vector kxx
    d2 = zeros(n,1);
  else
    if xeqz                                               % symmetric matrix Kxx
      d2 = sq_dist(x(:,id)'/ell1);
    else                                                 % cross covariances Kxz
      d2 = sq_dist(x(:,id)'/ell1,z(:,id)'/ell1);
    end
  end
  Kp = -1/2*Kp./d2; Kp(d2==0) = 0;


%% Percolation Cluster
clf
clc, clear
threshold = .63;
%
ax = axes('units','pixels','position',[1 1 500 400],'color','k');
text('units', 'pixels', 'position', [50,255,0],...
    'string','BioNB','color','w','fontname','helvetica','fontsize',100)
text('units', 'pixels', 'position', [120,120,0],...
    'string','441','color','w','fontname','helvetica','fontsize',100)
initial = getframe(gca);
[a,b,c]=size(initial.cdata);
z=zeros(a,b);
cells = double(initial.cdata(:,:,1)==255);
visit = z ;
sum = z;
imh = image(cat(3,z,cells,z));
set(imh, 'erasemode', 'none')
%return
for i=1:1000
    sum(2:a-1,2:b-1) = cells(2:a-1,1:b-2) + cells(2:a-1,3:b) + ...
    cells(1:a-2, 2:b-1) + cells(3:a,2:b-1) + ...
    cells(1:a-2,1:b-2) + cells(1:a-2,3:b) + ...
    cells(3:a,1:b-2) + cells(3:a,3:b);

    pick = rand(a,b);
    %edges only
    %cells = (cells & (sum<8)) | ((sum>=1) & (pick>=threshold) & (visit==0)) ;
    cells = cells | ((sum>=1) & (pick>=threshold) & (visit==0)) ;
    visit = (sum>=1) ;%& (pick<threshold) ;

    set(imh, 'cdata', cat(3,z,cells,z) )
    drawnow
end
return
figure(2)
image(cat(3,z,cells,z))


%function S = sampleFromMatrixNormal(M,V,K,nSamples=1)
function S = sampleFromMatrixNormal(M,sqrtV,sqrtinvK,nSamples)

if ~exist('nSamples','var'), nSamples = 1; end

[mu,sqrtsigma] = matrixNormalToNormal(M,sqrtV,sqrtinvK);

S = mu + sqrtsigma'*randn(length(mu),1);
S = reshape(S,size(M));


function [Y,XYZmm] = spm_read_vols(V,mask)
% Read in entire image volumes
% FORMAT [Y,XYZmm] = spm_read_vols(V,mask)
% V      - vector of mapped image volumes to read in (from spm_vol)
% mask   - implicit zero mask?
%
% Y      - 4D matrix of image data, fourth dimension indexes images
% XYZmm  - 3xn matrix of XYZ locations returned {mm}
%__________________________________________________________________________
%
% For image data types without a representation of NaN (see spm_type),
% implicit zero masking can be used. If mask is set, then zeros are
% treated as masked, and returned as NaN.
%__________________________________________________________________________
% Copyright (C) 1999-2016 Wellcome Trust Centre for Neuroimaging

% Andrew Holmes
% $Id: spm_read_vols.m 6918 2016-11-02 14:33:11Z guillaume $

%-Argument checks
%--------------------------------------------------------------------------
if nargin<2, mask = false; end

spm_check_orientations(V);

%-Read in image data
%--------------------------------------------------------------------------
n = numel(V);                                           %-#images
Y = zeros([V(1).dim(1:3),n]);                           %-image data matrix

for i=1:n
    for p=1:V(1).dim(3)
        Y(:,:,p,i) = spm_slice_vol(V(i),spm_matrix([0 0 p]),V(i).dim(1:2),0);
    end
end

%-Apply implicit zero mask for image datatypes without a NaNrep
%--------------------------------------------------------------------------
if mask
    %-Work out images without NaNrep
    im = false(n,1);
    for i=1:n, im(i)=~spm_type(V(i).dt(1),'NaNrep'); end
    %-Mask
    Y(Y(:,:,:,im)==0) = NaN;
end

%-Return as 3D matrix if single image
%--------------------------------------------------------------------------
if n==1, Y=Y(:,:,:,1); end

%-Compute XYZmm co-ordinates (if required)
%--------------------------------------------------------------------------
if nargout > 1
    [R,C,P] = ndgrid(1:V(1).dim(1),1:V(1).dim(2),1:V(1).dim(3));
    RCP     = [R(:)';C(:)';P(:)';ones(1,numel(R))];
    XYZmm   = V(1).mat(1:3,:)*RCP;
end


% In-paints the depth image using a cross-bilateral filter. The operation
% is implemented via several filterings at various scales. The number of
% scales is determined by the number of spacial and range sigmas provided.
% 3 spacial/range sigmas translated into filtering at 3 scales.
%
% Args:
%   imgRgb - the RGB image, a uint8 HxWx3 matrix
%   imgDepthAbs - the absolute depth map, a HxW double matrix whose values
%                 indicate depth in meters.
%   spaceSigmas - (optional) sigmas for the spacial gaussian term.
%   rangeSigmas - (optional) sigmas for the intensity gaussian term.
%
% Returns:
%    imgDepthAbs - the inpainted depth image.
function imgDepthAbs = fill_depth_cross_bfx(imgRgb, imgDepthAbs, mask, ...
    spaceSigmas, rangeSigmas)

  error(nargchk(2,4,nargin));
  assert(isa(imgRgb, 'uint8'), 'imgRgb must be uint8');
  assert(isa(imgDepthAbs, 'double'), 'imgDepthAbs must be a double');

  if nargin < 4
    spaceSigmas = [12 5 8];
  end
  if nargin < 5
    rangeSigmas = [0.2 0.08 0.02];
  end

  assert(numel(spaceSigmas) == numel(rangeSigmas));
  assert(isa(rangeSigmas, 'double'));
  assert(isa(spaceSigmas, 'double'));

  % Create the 'noise' image and get the maximum observed depth.
  maxv = max(imgDepthAbs(~mask));
  minv = min(imgDepthAbs(~mask));

  % Convert the depth image to uint8.
  imgDepth = (imgDepthAbs - minv) ./ (maxv - minv);
  imgDepth = uint8(imgDepth * 255);

  % Run the cross-bilateral filter.
  imgDepthAbs = mex_cbf(imgDepth, rgb2gray(imgRgb), mask, spaceSigmas(:), rangeSigmas(:));

  % Convert back to absolute depth (meters).
  imgDepthAbs = im2double(imgDepthAbs) .* (maxv - minv) + minv;
end


% SIN    Sine of argument in radians.
%    SIN(X) is the sine of the elements of X.
%
%    See also ASIN, SIND.
%
%    Reference page in Doc Center
%       doc sin
%
%    Other functions named sin
%
%       codistributed/sin    gpuArray/sin    sym/sin    ts/sin
%


function [X,info] = IRrrgmres(A,b,varargin)
% IRrrgmres Range Restricted GMRES for square systems
%
% options  = IRrrgmres('defaults')
% [X,info] = IRrrgmres(A,b);
% [X,info] = IRrrgmres(A,b,K);
% [X,info] = IRrrgmres(A,b,options);
% [X,info] = IRrrgmres(A,b,K,options);
%
% This function implements the Range Restricted GMRES method for solving
% a square system.
%
% With 'defaults' as input returns the default options.  Otherwise outputs
% the iterates specified in K, using max(K) as MaxIter, and using all other
% default options.  With options as input: uses the user-specified options
% and all the other default options.
%
% Inputs:
%  A : either (a) a full or sparse matrix
%             (b) a matrix object that performs the matrix*vector operation
%             (c) user-defined function handle
%  b : right-hand side vector
%  K : (optional) integer vector that specifies which iterates are returned
%      in X; the maximum number of iterations is assumed to be max(K)
%      [ positive integer | vector of positive components ]
%  options : structure with the following fields (optional)
%      x0         - initial guess for the iterations; default = zero vector
%                   [ array | {'none'} ]
%      MaxIter    - maximum allowed number of iterations
%                   [ {100} | positive integer ]
%                   NOTE: K overrules MaxIter if both are assigned
%      x_true     - true solution; allows us to returns error norms with
%                   respect to x_true at each iteration
%                   [ array | {'none'} ]
%      NoiseLevel - norm of noise in rhs divided by norm of rhs
%                   [ {'none'} | nonnegative scalar ]
%      eta        - safety factor for the discrepancy principle
%                   [ {1.01} | scalar greater than (and close to) 1 ]
%      DecompOut  - return the decomposition to the user
%                   [ 'on' | {'off'} ]
%      IterBar    - shows the progress of the outer iterations
%                   [ {'on'} | 'off' ]
%      NoStop     - specifies weather the iterations should proceed
%                   after a stopping criterion has been satisfied
%                   [ 'on' | {'off'} ]
% Note: the options structure can be created using the function IRset.
%
% Outputs:
%   X : computed solutions, stored column-wise (at the iterations listed in K)
%   info: structure with the following fields:
%      its     - number of the last computed iteration
%      saved_iterations - iteration numbers of iterates stored in X
%      StopFlag - stringg that describes the output/stopping condition:
%                   * Performed max number of iterations
%                   * Residual tolerance satisfied (discrepancy principle)
%                   * Normal equationa residual tolerance satisfied
%      Rnrm     - relative residual norms at each iteration
%      Xnrm     - solution norms at each iteration
%      Enrm     - error norms (requires x_true) at each iteration
%      V        - matrix generated by the Arnoldi algorithm: the orthonormal
%                 columns of V are a basis for the RRGMRES solution
%      Q        - orthogonal matrix in QR factorization of Hessenberg matrix
%      T        - triangular matrix in QR factorization of Hessenberg matrix
%      StopReg  - struct containing information about the solution that
%                 satisfies the stopping criterion.  Fields:
%                   It   : iteration where stopping criterion is satisfied
%                   X    : solution satisfying the stopping criterion
%                   Enrm : the corresponding relative error (requires x_true)
%      BestReg  - struct containing information about the solution that
%                 minimizes Enrm (requires x_true). Fields:
%                   It   : iteration where the minimum is attained
%                   X    : best solution
%                   Enrm : best relative error
%
% See also: IRcgls, IRhybrid_gmres, IRget, IRset

% Silvia Gazzola, University of Bath
% Per Christian Hansen, Technical University of Denmark
% James G. Nagy, Emory University
% April, 2018.

% This file is part of the IR Tools package and is distributed under the
% 3-Clause BSD License. A separate license file should be provided as part
% of the package.

% Set default values for options.
defaultopt = struct('x0','none', 'MaxIter',100, 'x_true','none', ...
    'NoiseLevel','none', 'eta',1.01, 'IterBar','on', ...
    'NoStop','off', 'DecompOut','off');

% If input is 'defaults,' return the default options in X.
if nargin==1 && nargout <= 1 && isequal(A,'defaults')
    X = defaultopt;
    return;
end

defaultopt.restart = 'off';
defaultopt.verbosity = 'on';

% Check for acceptable number of optional input arguments.
switch length(varargin)
    case 0
        K = []; options = [];
    case 1
        if isa(varargin{1}, 'double')
            K = varargin{1}; options = [];
        else
            K = []; options = varargin{1};
        end
    case 2
        if isa(varargin{1}, 'double')
            K = varargin{1}; options = varargin{2};
        else
            K = varargin{2}; options = varargin{1};
        end
        if isfield(options, 'MaxIter') && ~isempty(options.MaxIter) && (~isempty(K) && options.MaxIter ~= max(K))
            warning('The value of MaxIter is discarded; the maximum value in K is taken as MaxIter')
        end
    otherwise
        error('Too many input parameters')
end

if isempty(options)
    options = defaultopt;
end

options = IRset(defaultopt, options);

MaxIter    = IRget(options, 'MaxIter',    [], 'fast');
x_true     = IRget(options, 'x_true',     [], 'fast');
NoiseLevel = IRget(options, 'NoiseLevel', [], 'fast');
eta        = IRget(options, 'eta',        [], 'fast');
IterBar    = IRget(options, 'IterBar',    [], 'fast');
NoStop     = IRget(options, 'NoStop',     [], 'fast');
restart    = IRget(options, 'restart',    [], 'fast');
verbose    = IRget(options, 'verbosity',  [], 'fast');
DecompOut  = IRget(options, 'DecompOut',  [], 'fast');

restart = strcmp(restart, 'on');
verbose = strcmp(verbose, 'on');

% Setting K.
if isempty(K)
    K = MaxIter;
end
% Sorting the iterations (in case they are shuffled in input).
K = K(:); K = sort(K,'ascend'); K = unique(K);
if ~((isreal(K) && (all(K > 0)) && all(K == floor(K))))
    error('K must be a vector of positive real integers')
end
if K(end) ~= MaxIter
    MaxIter = K(end);
end

StopIt = MaxIter;

if isempty(NoiseLevel) || strcmp(NoiseLevel,'none')
    Rtol = 0;
else
    Rtol = eta*NoiseLevel;
end

n = length(b);
test_sq = ones(n,1);
try
    test_sq = A_times_vec(A, test_sq);
    if (length(test_sq)~=n)
        error('The matrix A shuold be square; check the length of b.')
    end
catch
    error('The matrix A must be square; check the length of b.')
end

% See if an initial guess is given; if not then use 0 as initial guess.
x0 = IRget(options, 'x0', [], 'fast');
Ab = A_times_vec(A, b);
nrmb = norm(b(:));
if strcmp(x0,'none')
    x0 = zeros(n,1);
    r = b;
    rr = Ab;
else
    try
        Ax = A_times_vec(A, x0);
        r = b - Ax;
        rr = Ab - Ax;
    catch
        error('Check the length of x')
    end
end
if restart
    ktotcount  = IRget(options, 'ktotcount', [],'fast');
    TotIterMax = IRget(options, 'TotIterMax',[],'fast');
    if strcmp(TotIterMax, 'none') || TotIterMax < MaxIter
        TotIterMax = MaxIter;
    end
    if strcmp(ktotcount, 'none')
        error('The total iteration counter must be assigned')
    end
    Ktot = IRget(options, 'Ktot', [], 'fast');
    % No checks on Ktot, it should be given from IRrestart.
end

% Declare matrices and prepare for the iterations.
X       = zeros(n,length(K));
Xnrm    = zeros(MaxIter,1);
Rnrm    = zeros(MaxIter,1);
V       = zeros(n,MaxIter); % Orthonormal vectors spanning Krylov subspace
h       = zeros(MaxIter,1); % New column of Hessenberg matrix H
Q       = zeros(MaxIter+1); % H = Q*T, Q orthogonal
T       = zeros(MaxIter);   % H = Q*T, T upper triangular
invT    = zeros(MaxIter);   % Inverse of the matrix T
coeff   = zeros(MaxIter,1); % Solution of the projected problem, i.e.,
                            % coefficient w.r.t. the Krylov basis.
rhs = zeros(MaxIter+1,1);   % Projected right-hand side

if strcmp(x_true,'none')
    errornorms = false;
else
    errornorms = true;
    Enrm = zeros(max(K),1);
    nrmtrue = norm(x_true(:));
    BestReg.It = [];
    BestReg.X = [];
    BestReg.Enrm = [];
    BestEnrm = 1e10;
    BestReg.Xnrm = [];
    BestReg.Rnrm = [];
end

NoStop = strcmp(NoStop,'on');

if restart
    saved_iterations = zeros(1, length(Ktot));
else
    saved_iterations = zeros(1, length(K));
end

% Prepare for the iterations.
alpharr  = norm(rr);
V(:,1) = rr/alpharr;
Q(1,1) = 1;
rhs(1) = V(:,1)'*r;
y = 0;

% Iterate.
noIterBar = strcmp(IterBar,{'off'});
if ~noIterBar
  h_wait = waitbar(0, 'Running iterations, please wait ...');
end
j = 0;
for k=1:MaxIter
    if restart, ktotcount = ktotcount + 1; end
    if ~noIterBar
        waitbar(k/MaxIter, h_wait)
    end
    w = A_times_vec(A, V(:,k));
    % Modified Gram-Schmidt on the new vector.
    for ll=1:k
        h(ll) = V(:,ll)'*w;
        w = w - V(:,ll)*h(ll);
    end
    alpha = norm(w);
    % Store new Arnoldi vector and update projected rhs.
    V(:,k+1) = w/alpha;
    rhs(k+1) = V(:,k+1)'*r;
    beta = rhs(1:k+1);
    % Apply previous rotations to h.
    T(1:k,k) = Q(1:k,1:k)'*h(1:k);
    % Compute Givens rotation parameters.
    rc = T(k,k);
    if alpha == 0
        c = 1; s = 0;
    elseif abs(alpha) > abs(rc)
        tau = -rc/alpha;
        s = 1 / sqrt(1 + abs(tau)^2);
        c = s*tau;
    else
        tau = -alpha/rc;
        c = 1 / sqrt(1 + abs(tau)^2);
        s = c*tau;
    end
    % Apply givens rotations.
    T(k,k) = c'*rc - s'*alpha;
    Q(1:k,[k,k+1]) = Q(1:k,k)*[c s];
    Q(k+1,[k,k+1]) = [-s c];
    if abs(T(k,k)) <= eps
        disp('Hessenberg matrix is (numerically) singular')
        X(:,j+1) = x;
        X = X(:,1:j+1);
        V = V(:,1:k+1);
        if restart
            saved_iterations(j+1) = ktotcount-1;
        else
            saved_iterations(j+1) = k-1;
        end
        saved_iterations = saved_iterations(1:j+1);
        % if k-1 < StopIt, StopIt = k-1; end
        if k>1
            Xnrm = Xnrm(1:k-1);
            Rnrm = Rnrm(1:k-1);
            if errornorms, Enrm = Enrm(1:k-1); end
        end
        % Stop because the Hessenberg matrix is (numerically) rank def.
        if StopIt == MaxIter
            StopFlag = 'Breakdown of the Arnoldi algorithm';
            StopReg.It = k-1;
            StopReg.X = x;
            if errornorms, StopReg.Enrm = Enrm(k-1); end
        end
        k = k-1;
        break
    end
    % Update the inverse of T.
    invT(1:k-1,k) = -(invT(1:k-1,1:k-1)*T(1:k-1,k))/T(k,k);
    invT(k,k) = 1/T(k,k);
    % Update the previous projected solution.
    coeff(1:k-1) = y;
    y = coeff(1:k) + (Q(1:k+1,k)'*beta)*invT(1:k,k);
    % Update solution.
    x = x0 + V(:,1:k)*y;
    % Compute norms.
    Xnrm(k)    = norm(x(:));
    if k==1
        Rnrm(k) = sqrt( abs( r'*r - abs(Q(1:k+1,k)'*beta)^2 ) )/nrmb;
    else
        Rnrm(k) = sqrt( abs( (Rnrm(k-1)*nrmb)^2 - abs(Q(1:k+1,k)'*beta)^2 ) )/nrmb;
    end
    if errornorms
        Enrm(k) = norm(x_true(:)-x(:))/nrmtrue;
        if Enrm(k)<BestEnrm
            BestReg.It = k;
            BestReg.X = x;
            BestEnrm = Enrm(k);
            BestReg.Enrm = BestEnrm;
            BestReg.Xnrm = Xnrm(k);
            BestReg.Rnrm = Rnrm(k);
        end
    end
    AlreadySaved = 0;
    if any(k==K)
        j = j+1;
        X(:,j) = x;
        saved_iterations(j) = k;
        if restart, saved_iterations(j) = ktotcount; end
        AlreadySaved = 1;
    end
    if restart
        if any(ktotcount == Ktot) && ~ AlreadySaved
            j = j+1;
            X(:,j) = x;
            saved_iterations(j) = ktotcount;
            AlreadySaved = 1;
        end
        if ktotcount == TotIterMax
            if ~ AlreadySaved
                j = j+1;
                saved_iterations(j) = ktotcount;
                X(:,j) = x;
                AlreadySaved = 1;
            end
            StopIt = k;
            StopReg.It = k;
            StopReg.X = x;
            if errornorms
                Enrm = Enrm(1:k);
                StopReg.Enrm = Enrm(k);
            end
            Xnrm     = Xnrm(1:k);
            Rnrm     = Rnrm(1:k);
            X = X(:,1:j);
            saved_iterations = saved_iterations(1:j);
            if verbose
                disp('Reached maximum number of iterations')
            end
            StopFlag = 'Reached maximum number of iterations';
            break
        end
    end
    if (Rnrm(k) <= Rtol) && (StopIt == MaxIter)
        if verbose
            disp('Residual tolerance satisfied')
        end
        StopFlag = 'Residual tolerance satisfied';
        if ~AlreadySaved && ~NoStop
            j = j+1;
            X(:,j) = x;
            if restart
                saved_iterations(j) = ktotcount;
            else
                saved_iterations(j) = k;
            end
            AlreadySaved = 1;
        end
        StopIt = k;
        StopReg.It = k;
        StopReg.X = x;
        if errornorms, StopReg.Enrm = Enrm(k); end
        if ~ NoStop
            Xnrm    = Xnrm(1:k);
            Rnrm    = Rnrm(1:k);
            if errornorms, Enrm = Enrm(1:k); end
            X = X(:,1:j);
            saved_iterations = saved_iterations(1:j);
            break
        end
    end
end
if k == MaxIter
  if StopIt == MaxIter
        % Stop because max number of iterations reached.
        if verbose
            disp('Reached maximum number of iterations')
        end
        StopFlag = 'Reached maximum number of iterations';
        if ~AlreadySaved
            j = j+1;
            X(:,j) = x;
            if restart
                saved_iterations(j) = ktotcount;
            else
                saved_iterations(j) = k;
            end
        end
        StopReg.It = k;
        StopReg.X = x;
        if errornorms, StopReg.Enrm = Enrm(k); end
        Xnrm    = Xnrm(1:k);
        Rnrm    = Rnrm(1:k);
        if errornorms, Enrm = Enrm(1:k); end
        X = X(:,1:j);
        saved_iterations = saved_iterations(1:j);
  end
end
if ~noIterBar, close(h_wait), end
if nargout==2
  info.its = k;
  if restart
      info.ktotcount = ktotcount;
  end
  info.saved_iterations = saved_iterations(1:j);
  info.StopFlag = StopFlag;
  info.StopReg = StopReg;
  info.Rnrm = Rnrm(1:k);
  info.Xnrm = Xnrm(1:k);
  if errornorms
    info.Enrm = Enrm(1:k);
    info.BestReg = BestReg;
  end
  if strcmp(DecompOut,'on')
    info.V = V;
    info.Q = Q;
    info.T = T;
  end
end


%MDL_COIL Create model of a coil manipulator
%
% MDL_COIL creates the workspace variable coil which describes the
% kinematic characteristics of a serial link manipulator with 50 joints
% that folds into a helix shape.
%
% MDL_BALL(N) as above but creates a manipulator with N joints.
%
% Also defines the workspace vectors:
%   q  joint angle vector for default helical configuration
%
% Reference::
% - "A divide and conquer articulated-body algorithm for parallel O(log(n))
%   calculation of rigid body dynamics, Part 2",
%   Int. J. Robotics Research, 18(9), pp 876-892.
%
% Notes::
% - Unlike most other mdl_xxx scripts this one is actually a function that
%   behaves like a script and writes to the global workspace.
%
% See also mdl_ball, SerialLink.

% MODEL: generic, coil, hyper redundant, 50DOF, standard_DH

% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function r = mdl_coil(N)

    if nargin == 0
        N = 50;
    end

    % create the links
    for i=1:N
        links(i) = Link('d', 0, 'a', 1/N, 'alpha', 5*pi/N);
    end

    % and build a serial link manipulator
    robot = SerialLink(links, 'name', 'coil');

    % place the variables into the global workspace
    if nargin == 1
        r = robot;
    elseif nargin == 0
        assignin('caller', 'coil', robot);
        assignin('caller', 'q', 10*pi/N*ones(1,N));
    end


function sqi = flatsqi(signal)
%flatSQI Flatline SQI
%
%
% Input:
%   signal:         single channel (F)ECG [1xN double]
%  MIN_AMP:         if the median of the filtered ECG is inferior to MINAMP
%                   then it is likely to be a flatline note the importance of
%                   the units here for the ECG (mV)
%
% Output:
%   sqi:            resulting xSQI for segment
%
% Fetal Extraction Toolbox, version 1.0, February 2014
% Released under the GNU General Public License
%
% Copyright (C) 2014 Fernando Andreotti
% Dresden University of Technology, Institute of Biomedical Engineering
% fernando.andreotti@mailbox.tu-dresden.de
%
% Last updated : 30-06-2016
%
%
% This program is free software; you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by the
% Free Software Foundation; either version 2 of the License, or (at your
% option) any later version.
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
% Public License for more details.

MIN_AMP = 0.1;
% == Flatline detection
if (sum(abs(signal-median(signal))>MIN_AMP)/length(signal))<0.05
    % this is a flat line
    sqi = 0;
else
    sqi = 1;
end
% if 20% of the samples (or more) have an absolute amplitude which is higher
% than MIN_AMP then we are good to go.