function [A,C,newcenters] = manually_refine_components(Y,A,C,centers,img,sx,options)
% function that allows to add or remove components.
% Usage:
% after runnning use left click to remove and right click to add components
% at specific locations. Hit enter when done
% Inputs
% ------
% centers: coordinates of the centers of the components
% img: image used to identify components (for instance NCA
%
% Returns:
% --------
% newcenters: updated component centers

defoptions = CNMFSetParms;
if nargin < 7 || isempty(options); options = defoptions; end
if ~isfield(options,'d1') || isempty(options.d1); options.d1 = input('What is the total number of rows? \n'); end          % # of rows
if ~isfield(options,'d2') || isempty(options.d2); options.d2 = input('What is the total number of columns? \n'); end       % # of columns
if ~isfield(options,'cont_threshold') || isempty(options.cont_threshold); cont_threshold = defoptions.cont_threshold; else cont_threshold = options.cont_threshold; end          % # of rows
if nargin < 6 || isempty(sx)
    sx = 5;
end
if nargin < 5 || isempty(img)
    img = std(Y,[],3);
end
if nargin < 4 || isempty(centers)
    centers = com(A,options.d1,options.d2);
end

min_distance_point_selection=2;
x=1;
T = size(C,2);
newcenters=[centers];
% ident_point=[0,0];
fig = figure;
imagesc(img,[min(img(:)),max(img(:))]);
    axis equal; axis tight; hold all;
    scatter(newcenters(:,2),newcenters(:,1),'mo'); hold on;
    title('Center of ROIs found from initialization algorithm');
    xlabel({'Press left click to add new component, right click to remove existing component'; 'Press enter to exit'},'fontweight','bold');
    drawnow;
    cmap = colormap;
for i = 1:size(A,2)
    a_srt = sort(A(:,i),'descend');
    ff = find(cumsum(a_srt.^2) >= cont_threshold*sum(a_srt.^2),1,'first');
    contour(reshape(A(:,i),options.d1,options.d2),[0,0]+a_srt(ff),'Linecolor',[1,0,1]/2);
    hold on;
end

while ~isempty(x)
%     scatter(ident_point(1),ident_point(2),'go');
    [x,y,button]=ginput(1);
    disp(button); hold on;
    if ~isempty(x)
        pixel=round([x y]);
        if button==1
            disp(['Adding pixel at:' num2str(fliplr(pixel))])
            newcenters=[newcenters; fliplr(pixel)];
            int_x = round(newcenters(end,1)) + (-sx:sx);
            if int_x(1)<1
                int_x = int_x + 1 - int_x(1);
            end
            if int_x(end)>options.d1
                int_x = int_x - (int_x(end)-options.d1);
            end
            int_y = round(newcenters(end,2)) + (-sx:sx);
            if int_y(1)<1
                int_y = int_y + 1 - int_y(1);
            end
            if int_y(end)>options.d2
                int_y = int_y - (int_y(end)-options.d2);
            end
            Ypatch = reshape(Y(int_x,int_y,:),(2*sx+1)^2,size(C,2));
            Ypatch = bsxfun(@minus, Ypatch, median(Ypatch,2));
            [INT_x,INT_y] = meshgrid(int_x,int_y);
            coor = sub2ind([options.d1,options.d2],INT_x(:),INT_y(:));
            Y_res = Ypatch - A(coor,:)*C;
            [atemp, ctemp, ~, ~, newcenter, ~] = greedyROI(reshape(Y_res,2*sx+1,2*sx+1,T), 1, options);
            %[atemp, ctemp] = initialize_components(reshape(Y_res,2*sx+1,2*sx+1,T), 1,sx,options);  % initialize
            % find contour
            a_srt = sort(atemp,'descend');
            ff = find(cumsum(a_srt.^2) >= cont_threshold*sum(a_srt.^2),1,'first');
            A(coor,end+1) = atemp/norm(atemp);
            C(end+1,:) = ctemp*norm(atemp);
            new_center = com(A(:,end),options.d1,options.d2);
            newcenters(end,:) = new_center;
            scatter(new_center(2),new_center(1),'mo'); hold on;
            contour(reshape(A(:,end),options.d1,options.d2),[0,0]+a_srt(ff),'Linecolor',[1,0,1]/2);
            hold on;
            colormap(fig,cmap);

            drawnow;
%             atemp = max(mean(Y_res,2),0);
%             for i = 1:10
%                ctemp = max(atemp'*Y_res,0)/norm(atemp)^2;
%                atemp = max(Y_res*ctemp',0)/norm(ctemp)^2;
%             end

        elseif button==3
            [m,id]=min(sum(bsxfun(@minus,newcenters,[y,x]).^2,2));
            ident_point=[newcenters(id,2),newcenters(id,1)];
            if m<=min_distance_point_selection
                disp(['Removing point:' num2str(ident_point)])
                newcenters(id,:)=[];
                A(:,id) = [];
                C(id,:) = [];
                % replot after removing
                clf;
                imagesc(img,[min(img(:)),max(img(:))]);
                    axis equal; axis tight; hold all;
                    scatter(newcenters(:,2),newcenters(:,1),'mo'); hold on;
                    title('Center of ROIs found from initialization algorithm');
                    xlabel({'Press left click to add new component, right click to remove existing component'; 'Press enter to exit'},'fontweight','bold');
                    drawnow;
                    cmap = colormap;
                for i = 1:size(A,2)
                    a_srt = sort(A(:,i),'descend');
                    ff = find(cumsum(a_srt.^2) >= cont_threshold*sum(a_srt.^2),1,'first');
                    contour(reshape(A(:,i),options.d1,options.d2),[0,0]+a_srt(ff),'Linecolor',[1,0,1]/2);
                    hold on;
                end
            else
                disp('Selection too far from any point')
            end
        end
    end
end

end


function nav=readerp(nav,fname)

global glc gls
flag=0; n=0; erp=gls.erp;

idx=strfind(fname,glc.sep); fname0=fname(idx(end)+1:end);
fprintf('Info:reading erp file %s...',fname0);
fid=fopen(fname);

% read data
while ~feof(fid)
    line=fgets(fid,266);

    if ~isempty(strfind(line,'MJD')),flag=1;end
    if flag==0,continue;end
    if flag==1
        line=fgets(fid); %#ok<NASGU>
        flag=2; continue;
    end
    if flag==2
        value=str2double(strsplit(line));
        erp.data(n+1).mjd    =value(1);
        erp.data(n+1).xp     =value(2)*1e-6*glc.AS2R;
        erp.data(n+1).yp     =value(3)*1e-6*glc.AS2R;
        erp.data(n+1).ut1_utc=value(4)*1e-7;
        erp.data(n+1).lod    =value(5)*1e-7;
        erp.data(n+1).xpr    =value(13)*1e-6*glc.AS2R;
        erp.data(n+1).ypr    =value(14)*1e-6*glc.AS2R;
        n=n+1;
    end
end

fclose(fid);
fprintf('over\n');

erp.n=n;
erp.nmax=n;
nav.erp=erp;

return


filename='ImprovedBridge_hexahedra';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance'};
weights = [1];
constraint = {'volume'};
optimizer = 'AlternatingPrimalDual';
optimizerUnconstrained = 'SLERP';
designVariable = 'LevelSet';
incrementFactor = 1;
filterType = 'P1';
constraint_case = 'INEQUALITY';
line_search_initiator = 'STANDARD';
showBC = true;

nsteps = 10;
Vfrac_final = 0.1;
Perimeter_target = 1;
optimality_final = 1e-3;
constr_final =1e-3;

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


function [param, names] = gpsimCandidateExtractParam(model)

% GPSIMCANDIDATEEXTRACTPARAM Extract the parameters of a GPSIM model.
% FORMAT
% DESC extracts the model parameters from a structure containing
% the information about a Gaussian process for single input motif
% modelling.
% ARG model : the model structure containing the information about
% the model.
% RETURN params : a vector of parameters from the model.
%
% SEEALSO : gpsimCreate, gpsimAddCandidate, gpsimCandidateExpandParam, modelExtractParam
%
% COPYRIGHT : Neil D. Lawrence, 2007

% SHEFFIELDML

if nargout>1
  [param, names] = kernExtractParam(model.candidate.kern);
  for i=1:length(model.candidate.mu);
    names{end+1}=['Basal transcription ' num2str(i)];
  end
else
  param = kernExtractParam(model.candidate.kern);
end
fhandle = str2func([model.candidate.bTransform 'Transform']);
param = [param fhandle(model.candidate.B, 'xtoa')];

if isfield(model, 'fix')
  for i = 1:length(model.candidate.fix)
    param(model.candidate.fix(i).index) = model.candidate.fix(i).value;
  end
end
param = real(param);

% Remove main kernel parameters.
for i = model.kern.nParams:-1:1
  if nargout>1
    names(i)=[];
  end
  param(i) = [];
end


function t_obj = parcel_stats2statistic_image(atlas_obj, tscores, pvalues, dfe, sig)
% Utility that transforms parcel-wise t-statistics and p-values into a statistic_image object in voxelwise image space
% Expands parcel values so that they are replicated for each voxel in the parcel.
%
% :Usage:
% ::
%
% t_obj = parcel_stats2statistic_image(atlas_obj, tscores, pvalues, dfe, sig)
%
% For objects: Type methods(object_name) for a list of special commands
%              Type help object_name.method_name for help on specific
%              methods.
%
% ..
%     Author and copyright information:
%
%     Copyright (C) 2021 Tor Wager
%
%     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/>.
% ..
%
% :Inputs:
%
%   **atlas_obj:**
%        An atlas-class object with k distinct regions or parcels
%
%   **tscores:**
%        n x k matrix of k t-scores for each of n parcels, where k is,
%        e.g., the number of predictors tested in a multiple regression
%
%   **pvalues:**
%        n x k matrix of k p-values for each of n parcels
%
%   **dfe:**
%        n x 1 matrix of error degrees of freedom for each of n parcels
%
%   **sig:**
%        n x k matrix of k significant tests for each of n parcels
%        This may be, e.g., corrected for multiple comparisons.
%
% :Optional Inputs:
%
% :Outputs:
%
%   **t_obj:**
%        A statistic_image object containing t-maps. .dat contains
%        t-scores, .p contains p-values. Use statistic_image methods like
%        montage(t_obj), orthviews(t_obj), threshold(t_obj) to interact
%        with this object.
%
%
% :Examples:
% ::
%
% :References:
%   None
%
% :See also:
%   parcel_data2fmri_data
%

% Create placeholder statistic image

atlas_obj = replace_empty(atlas_obj);
k = size(tscores, 2);
placeholder_vec = ones(atlas_obj.volInfo.n_inmask, k);
all_parcel_idx = double(atlas_obj.dat);
u = unique(all_parcel_idx); u(u == 0) = [];

% initialize variables with correct size

t_obj = statistic_image('dat', single(0 .* placeholder_vec), ...
    'p', placeholder_vec, ...
    'sig', logical(placeholder_vec), ...
    'type', 'T', ...
    'dfe', placeholder_vec, ...
    'volInfo', atlas_obj.volInfo);

% number of parcels

n = size(tscores, 1); % num parcels

if n ~= length(u)
        error('Parcel indices in atlas_obj and extracted parcel-wise t-values do not match. Check code.')
end

t_obj.dat = zeros(size(placeholder_vec, 1), k); % voxels x conditions

    for j = 1:length(u)
        % For each parcel, fill in statistic_image object
        % ----------------------------------------------------
        parcelidx = u(j);

        wh_vox = all_parcel_idx == parcelidx;

        % map parcels to voxels
        t_obj.dat(wh_vox, :) = repmat(tscores(j, :), sum(wh_vox), 1);
        t_obj.p(wh_vox, :) = repmat(pvalues(j, :), sum(wh_vox), 1);
        t_obj.dfe(wh_vox, :) = repmat(dfe(j, 1), sum(wh_vox), k);       % replicate dfe
        t_obj.sig(wh_vox, :) = repmat(sig(j, :), sum(wh_vox), 1);

    end

t_obj = enforce_variable_types(t_obj);  % space-saving: 5/24/17

% input_struct.t_statistic_obj = t_obj;

end % function


function plotOptTorques(model, nlp, gait, indices)

    act_joint_idx = find(arrayfun(@(x)~isempty(x.Actuator),model.Joints));

    if nargin < 4
        indices = act_joint_idx;
    else
        if isempty(indices), return; end
    end

    cont_domain_idx = find(cellfun(@(x)isa(x,'ContinuousDynamics'),{nlp.Phase.Plant}));
    joint_names = {model.Joints.Name};

    t = [];
    u_opt = []; u_lb = [];  u_ub = [];

    for j=cont_domain_idx
        t = [t,gait(j).tspan];

        u_opt = [u_opt,gait(j).inputs.u];
        u_lb  = [u_lb,[nlp.Phase(j).OptVarTable.u.LowerBound]];
        u_ub  = [u_ub,[nlp.Phase(j).OptVarTable.u.UpperBound]];
    end

    ax = [];
    for i=1:length(indices)
        idx = indices(i);
        if ~ismember(idx,act_joint_idx)
            continue;
        end
        f = figure;clf;
        set(f, 'WindowStyle', 'docked');
        %         f.Position = [680 558 560 420];
        ax = [ax, axes(f)]; %#ok<LAXES,*AGROW>
        hold on;
        plot(t, u_opt(i,:), 'b');
        plot(t, u_lb(i,:), 'r--');
        plot(t, u_ub(i,:), 'g--');

        title('Torque');
        legend('u', 'lb', 'ub');

        f.Name = [joint_names{idx},'_torque'];
    end

    linkaxes(ax, 'x');

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_funcMovie(Temp,Event,handles)
handles=guidata(handles.MU_matrix_display);

if length(handles.V.DimSize)==2
    warndlg('At least 3D matrix is needed for generating movie.');
    return;
end

dimFlag = ['[:' repmat(',:', [1 length(handles.V.DimSize)-1]) ']'];
dim = inputdlg(['Please specify dimension flag for generating movie. Use '':'' to include all content in the dimension; Use ''start:end'' to include parts of the content in the dimension.'],'Specify Dimension Flag',1,{dimFlag});
if isempty(dim)
    warndlg('Making movie was cancelled.');
    return;
end

movie = inputdlg({'Please specify the frame rate (fps).', 'Please specify the movie quality (lowest 0 - 100 highest)'},'About Movie',1,{'30' ,'75'});
if isempty(movie)
    warndlg('Making movie was cancelled.');
    return;
end

MergeM=get(handles.Matrix_name_edit,'String');
name = inputdlg(['Please input an name for the movie file.'],'Specify File Name',1,{[MergeM '_mov']});
if isempty(dim)
    warndlg('Making movie was cancelled.');
    return;
end

pause(0.1);
try
    eval(['TMatrix=handles.TMatrix(' dim{1}(2:end-1) ');']);
    TSize=size(TMatrix);
    TMatrix=TMatrix(:,:,:);
    dimSize=size(TMatrix);
    TMatrix=reshape(TMatrix,[dimSize(1) dimSize(2) 1 dimSize(3)]);

    if isempty(handles.V2.Foreground_matrix) % no overlay

        Colormap = colormap(handles.Matrix_display_axes);
        TMatrix=double(TMatrix);
        TMatrix(TMatrix<=double(handles.V.C_lower)) = double(handles.V.C_lower);
        TMatrix(TMatrix>=double(handles.V.C_upper)) = double(handles.V.C_upper);
        TMatrix=TMatrix-double(handles.V.C_lower);
        TMatrix=(TMatrix./double(handles.V.C_upper - handles.V.C_lower))*(length(Colormap(:,1))-1)+1;

        M=immovie(TMatrix,Colormap);

    else % if overlay
        BImage=double(repmat(TMatrix,[1 1 3 1]));
        BImage=max(double(handles.V.C_lower),min(BImage,double(handles.V.C_upper))); % Make sure BImage is in the range of Color Bound
        BImage=(BImage-double(handles.V.C_lower))./double((handles.V.C_upper-handles.V.C_lower));

        eval(['mask=double(handles.Mask(' dim{1}(2:end-1) '));']); % multi-dimensional mask??????
        TSize2=size(mask);
        if length(TSize)>length(TSize2) & length(TSize2)==2
            mask=repmat(mask,[1,1,prod(TSize(3:end))]);
        elseif length(TSize)>length(TSize2) & length(TSize2)==3
            mask=repmat(mask,[1,1,1,prod(TSize(4:end))]);
        end
        mask=mask(:,:,:);
        FMatrix=((max(double(handles.V2.F_lower),min(mask,double(handles.V2.F_upper)))-handles.V2.F_lower)/(handles.V2.F_upper-handles.V2.F_lower))*(64-1)+1; % Make sure FMatrix is in the range of Color Bound
        FImage=ind2rgb(round(FMatrix(:)),handles.V2.Color_map);
        if handles.V2.Include0 ~=0
            FImage(repmat(mask(:),[1 1 3])==0)=0;
        end
        FImage=reshape(FImage,[size(FMatrix) 3]);
        FImage=permute(FImage,[1 2 4 3]);
        RGBImage=BImage* handles.V2.Backgroud_F+FImage* handles.V2.Foregroud_F;
        RGBImage=max(0,min(RGBImage,1)); % Make sure RGBImage is in the range of 0 and 1

        M=immovie(RGBImage);
    end

    writerObj=VideoWriter(name{1});
    writerObj.FrameRate=str2double(movie{1});
    writerObj.Quality=str2double(movie{2});
    open(writerObj);
    writeVideo(writerObj,M);
    msgbox(['Movie file ' char(39) writerObj.Filename char(39) ' has been generated at ' char(39) writerObj.Path char(39) '.'],'Movie File');
    close(writerObj);
catch me
    error_msg{1,1}='Making movie failed! Error occured during movie generation process.';
    error_msg{2,1}=me.message;
    errordlg(error_msg);
    return;
end

% update current display matrix
handles=MU_update_image(handles.Matrix_display_axes,{handles.TMatrix,handles.Mask},handles,0);
guidata(handles.MU_matrix_display, handles);

end


function displayIVPinfo(u, isIVP, varargin)
%DISPLAYINFOIVP    Utility routine for displaying IVP solving
%
% Calling sequence:
%   DISPLAYINFO(VARARGIN)
% where
%   U:          The solution computed.
%   ISIVP:      Equal to 1 if we've just solved an IVP, 0 otherwise (FVP).
%   VARARGIN:   Various useful information passed from the Newton solver
%               to this method.
%
% See also: chebop/displayInfo.

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

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Developers note: This method was introduced to allow the IVP solver to use
% similar syntax as the BVP solver for displaying useful information about the
% solution process.
%
% At the moment, we only display information at the end of solving IVPs, rather
% than during the Newton iteration which is the case for BVPs. Thus, this method
% only gets called at the end of the solveivp method, which is why we don't need
% the 'mode' argument like we do in the BVP case.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Are we dealing with a CHEBFUN or a CHEBMATRIX?
if (isa(u, 'chebfun'))
    len = length(u);
else
    len = max(cellfun(@length, u.blocks));
end

% Did we just solve an IVP or an FVP?
if ( isIVP == 1 )
    fprintf('Initial value problem detected.\n');
else
    fprintf('Final value problem detected.\n');
end

% Show information about the number of pieces and the total length of the
% solution:
fprintf('Number of pieces of the solution: %i.\n', length(u.domain) - 1);
fprintf('Total length of solution: %i.\n', len);

end


% SYNTAX:
%    flag = flagShrink(flag, expand_size, <omit_borders = false>)
%
% DESCRIPTION:
%    shrink the flag array
%    if flag is a matrix this flagging expansion will work column by column
%
% INPUT:
%   flag          [n_obs x n_arrays]
%   expand_size   n_epochs with flags to activate at the border of a flagged interval
%   omit_borders  when true do not shrink flags at the beginning or end of the matrix

%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:       Andrea Gatti
%  Contributors:     Andrea Gatti
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   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/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

function flag = flagShrink(flag, expand_size, omit_borders)
    if nargin < 3
        omit_borders = false;
    end
    for c = 1 : size(flag, 2)
        flag(:, c) = ~conv(single(~flag(:, c)), ones(2 * expand_size + 1, 1)', 'same') > 0;
    end
    if omit_borders
        % do nothing
    else
        flag([1:expand_size (end - expand_size + 1) : end], :) = 0;
    end
end


% op_ampScale.m
% Jamie Near, McGill University 2014.
%
% USAGE:
% out=op_ampScale(in,A);
%
% DESCRIPTION:
% Scale the amplitude of a spectrum by factor A.
%
% INPUTS:
% in    = input data in matlab structure format
% A     = Amplitude scaling factor.
%
% OUTPUTS:
% out   = Output following amplitude scaling.

function out=op_ampScale(in,A);

out=in;
out.specs=in.specs*A;
out.fids=in.fids*A;


% ------------------------------------------------------------------------
%  Copyright (C)
%  Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain
%  University of California Berkeley (UCB) - USA
%
%  Jordi Pont-Tuset <jordi.pont@upc.edu>
%  Pablo Arbelaez <arbelaez@berkeley.edu>
%  June 2014
% ------------------------------------------------------------------------
% This file is part of the MCG package presented in:
%    Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J,
%    "Multiscale Combinatorial Grouping,"
%    Computer Vision and Pattern Recognition (CVPR) 2014.
% Please consider citing the paper if you use this code.
% ------------------------------------------------------------------------

function stats = get_single_hier_stats(params,hier_id,gt_set)

if nargin<3
    gt_set = params.gt_set_pareto;
    res_file = params.files.pareto_singles{hier_id};
else
    res_file = strrep(params.files.pareto_singles{hier_id},[params.gt_set_pareto '_pareto_single'],[gt_set '_pareto_single']);
end

% Sampled number of candidates from each hierarchy
n_cands = [10:10:100,200:100:1000,2000:1000:10000];

for ii=1:params.n_r_cand
    n_max_cands(ii) = max(n_cands); %#ok<*AGROW>
end

% Are the results already computed?
if exist(res_file, 'file')
    load(res_file)
    disp(['Loaded: ' res_file '.'])
    recompute = 0;
else
    disp(['RECOMPUTING: ' res_file '.'])
    recompute = 1;
end

if recompute
    % Load which images to consider from the database (train, val, etc.)
    im_ids = database_ids(params.database,gt_set);

    for ll=1:params.n_r_cand
        % Store number of regions and gt_set
        stats(ll).n_cands = n_cands;
        stats(ll).gt_set = gt_set;
        stats(ll).num_objects = 0;
        stats(ll).obj_classes = [];
    end

    % Sweep all images
    num_images = length(im_ids);
    batches = 20;
    whichOne = imresize(1:batches, [1 num_images], 'nearest');

    for iii = 1:batches,
        indIII = find(whichOne == iii);
        clear Jaccards Inters False_pos False_neg True_areas Obj_classes;

        parfor ii_i = 1:length(indIII),
            ii = indIII(ii_i);
            % Read the UCM as a hierarchy
            hier = ucm2hier(fullfile(params.hier_dirs{hier_id}, [im_ids{ii} '.mat']));
            n_regs = hier.ms_struct(end).parent;

            % Get all pairs of neighboring leave regions
            [~, idx_neighbors] = seg2gridbmap(hier.leaves_part);
            K = max(idx_neighbors.matrix_max(:)) + 1;
            neigh_pairs = unique(idx_neighbors.matrix_min+K*idx_neighbors.matrix_max);
            neigh_pairs(neigh_pairs==0) = [];
            neigh_pairs_min = mod(neigh_pairs,K);
            neigh_pairs_max = (neigh_pairs-neigh_pairs_min)/K;

            if isrow(neigh_pairs_min)
                neigh_pairs_min = neigh_pairs_min';
            end
            if isrow(neigh_pairs_max)
                neigh_pairs_max = neigh_pairs_max';
            end

            % Get the 'n_cands' top candidates from each hierarchy

            % Singletons
            all_cands = {};
            if n_regs<=n_max_cands(1)
                all_cands{1} = (n_regs:-1:1)';
            else
                all_cands{1} = (n_regs:-1:(n_regs-n_max_cands(1))+1)';
            end

            % Pairs, triplets, etc.
            all_cands(2:params.n_r_cand) = ...
            mex_get_tree_cands(double(hier.leaves_part)-1, double(hier.ms_matrix)-1,...
                                 neigh_pairs_min-1, neigh_pairs_max-1,...
                                 n_max_cands(2:end));

            % Load ground truth
            curr_gt = get_ground_truth( params.database, im_ids{ii} );
            for ll = 1:params.n_r_cand,
                [Jaccards{ii_i}{ll}, Inters{ii_i}{ll}, False_pos{ii_i}{ll}, False_neg{ii_i}{ll}, True_areas{ii_i}{ll}, Obj_classes{ii_i}{ll}] = eval_cands(hier, all_cands{ll}, curr_gt); %#ok<ASGLU>
            end
        end
        fprintf('.');

        for ii_i = 1:length(indIII),
            ii = indIII(ii_i);
            for ll = 1:params.n_r_cand,
                jaccards = Jaccards{ii_i}{ll};
                inters = Inters{ii_i}{ll};
                false_pos = False_pos{ii_i}{ll};
                false_neg = False_neg{ii_i}{ll};
                true_areas = True_areas{ii_i}{ll};
                obj_classes = Obj_classes{ii_i}{ll};

                % Get best candidate at different number of candidates
                for jj=1:length(stats(ll).n_cands)
                    curr_n_regs = min(stats(ll).n_cands(jj), size(inters,2));
                    to_consider = 1:curr_n_regs;
                    stats(ll).all_n_masks(ii,jj) = length(to_consider);
                    if (stats(ll).all_n_masks(ii,jj)>0)
                        for kk=1:size(inters,1)
                            [stats(ll).max_J(stats(ll).num_objects+kk,jj), which_one] = max(jaccards(kk,to_consider));
                            stats(ll).max_indicator(stats(ll).num_objects+kk,jj) = to_consider(which_one);
                            stats(ll).max_fp(stats(ll).num_objects+kk,jj)        = false_pos(kk,to_consider(which_one));
                            stats(ll).max_fn(stats(ll).num_objects+kk,jj)        = false_neg(kk,to_consider(which_one));
                            stats(ll).max_inters(stats(ll).num_objects+kk,jj)    = inters(kk,to_consider(which_one));
                        end
                    end
                end
                stats(ll).obj_classes = [stats(ll).obj_classes; obj_classes(1:size(inters,1))'];
                stats(ll).num_objects = stats(ll).num_objects + size(jaccards,1);
            end
        end
    end

    for ll=1:params.n_r_cand,
        stats(ll).jaccard_object = mean(stats(ll).max_J);
        stats(ll).mean_n_masks   = mean(stats(ll).all_n_masks);

        % ----- Compute jaccard at pixel level (J_p) ----
        class_ids = unique(stats(ll).obj_classes);

        % Compute per-class statistics and then mean
        for ii=1:length(class_ids)
            curr_class = class_ids(ii);
            stats(ll).per_class_results{ii}.num_objects = sum(stats(ll).obj_classes==curr_class);

            stats(ll).per_class_results{ii}.max_fp     = stats(ll).max_fp(logical(stats(ll).obj_classes==curr_class),:);
            stats(ll).per_class_results{ii}.max_fn     = stats(ll).max_fn(logical(stats(ll).obj_classes==curr_class),:);
            stats(ll).per_class_results{ii}.max_inters = stats(ll).max_inters(logical(stats(ll).obj_classes==curr_class),:);
            stats(ll).per_class_results{ii}.max_J      = stats(ll).max_J(logical(stats(ll).obj_classes==curr_class),:);
            stats(ll).per_class_results{ii}.meanmax    = mean(stats(ll).per_class_results{ii}.max_J);

            stats(ll).per_class_results{ii}.global_fp      = sum(stats(ll).per_class_results{ii}.max_fp,1);
            stats(ll).per_class_results{ii}.global_fn      = sum(stats(ll).per_class_results{ii}.max_fn,1);
            stats(ll).per_class_results{ii}.global_inters  = sum(stats(ll).per_class_results{ii}.max_inters,1);

            % Compute per-class total inters, fp, fn
            stats(ll).per_class_results{ii}.global_J = ...
                 stats(ll).per_class_results{ii}.global_inters ./...
                (stats(ll).per_class_results{ii}.global_inters+...
                 stats(ll).per_class_results{ii}.global_fp    +...
                 stats(ll).per_class_results{ii}.global_fn);
        end

        % Compute global mean
        tmp = [];
        for ii=1:length(class_ids)
            tmp = [tmp; stats(ll).per_class_results{ii}.global_J];
        end
        stats(ll).jaccard_class = mean(tmp);
    end

    % Store
    % fprintf('Done with get_single_hier_stats.\n');
    save(res_file,'stats');
end


% TOOL
%
% Files
%   findedge         - highlights edges in certain range
%   findedge3        - highlights edges in certain range in 3-D
%   findedgedof      - highlights some dofs associated to edges
%   findedgedof3     - highlights some dofs associated to edges
%   findelem         - highlights some elements
%   findelem3        - highlights the elements in the range
%   findnode         - highlights nodes in certain range.
%   findnode3        - highlights some nodes for 3-D meshes.
%   findnodedof      - highlights dof associated to nodes.
%   findquadelem     - highlights some elements
%   hg               - the interface of command hg in matlab
%   includepath      - inlcudes pathes
%   latexmatrix      - output the matrix in latex formate.
%   latexmesh        - draw a mesh using pstrick
%   latextable       - output the matrix in table formate in latex.
%   showboundary     - boundary mesh plot
%   showboundary3    - boundary surface mesh plot
%   showcoloring     - plot coloring vertices set
%   showgraph        - displays a planar graph
%   showgraphmatrix  - displays a planar graph
%   showmatrix       - displays a matrix.
%   showmesh         - displays a triangular mesh in 2-D.
%   showmesh3        - displays a tetrahedron mesh in 3-D.
%   showmeshdensity  - show the density of the mesh
%   showmeshquality  - show the qualify of the mesh
%   showquadmesh     - displays a QUAD mesh in 2-D
%   showquadsolution - plots the solution u on a quad mesh in 2-D.
%   showrate         - rate of an err sequence
%   showrate2        - rate of two error sequences
%   showrate3        - rate of two error sequences
%   showresult       - display the mesh and the solution
%   showresult3      - display the mesh and the solution in 3-D
%   showsolution     - plots the solution u on a triangular mesh in 2-D.
%   showsolution3    - plots the solution u on a tetrahedron mesh in 3-D.
%   spsub2ind        - SPARSESUB2IND find values of a sparse matrix


function Fderandomized = derandomize(F)

chanceDeclarations = find(is(F,'chance'));
randomDeclarations = find(is(F,'random'));
if isempty(randomDeclarations)
    error('Cannot derandomize, cannot find declaration of random variables');
end

keep = ones(length(F),1);
keep(randomDeclarations)=0;
keep(chanceDeclarations)=0;
randomVariables = extractRandomDefinitions(F(randomDeclarations));
groupedChanceConstraints = groupchanceconstraints(F);

Fderandomized = deriveChanceModel(groupedChanceConstraints,randomVariables)

Fderandomized = Fderandomized + F(find(keep));

function Fderandomized = deriveChanceModel(groupedChanceConstraints,randomVariables);

Fderandomized = [];
for ic = 1:length(groupedChanceConstraints)
    if length(groupedChanceConstraints{ic})>1
        error('Joint chance still not supported');
    end
    if ~is(groupedChanceConstraints{ic},'elementwise')
        error('Only elementwise chance constraints supported')
    end
    X = sdpvar(groupedChanceConstraints{ic});
    if length(X)>1
        error('Only single elementwise chance constraints supported')
    end

    % OK, simple linear inequality
    allVars = depends(X);
    wVars = [];for j = 1:length(randomVariables);wVars = [wVars getvariables(randomVariables{j}.variables)];end
    xVars = setdiff(allVars,wVars);
    x = recover(xVars);
    w = recover(wVars);

    b = [];
    A = [];
    % Some pre-calc
    xw = [x;w];
    xind = find(ismembc(getvariables(xw),getvariables(x)));
    wind = find(ismembc(getvariables(xw),getvariables(w)));
    [Qs,cs,fs,dummy,nonquadratic] = vecquaddecomp(X,xw);
    c_wTbase = [];
    AAA = [];
    ccc = [];
    for i = 1:length(X)
        Q = Qs{i};
        c = cs{i};
        f = fs{i};
        if nonquadratic
            error('Constraints can be at most quadratic, with the linear term uncertain');
        end
        Q_ww = Q(wind,wind);
        Q_xw = Q(xind,wind);
        Q_xx = Q(xind,xind);
        c_x = c(xind);
        c_w = c(wind);

        %b = [b;f + c_w'*w];
        %A = [A;-c_x'-w'*2*Q_xw'];
        % A = [A -c_x-2*Q_xw*w];
        AAA = [AAA;sparse(-2*Q_xw)];
        ccc = [ccc;-sparse(c_x)];
        b = [b;f];
        c_wTbase = [c_wTbase;c_w'];
    end
   % b = b + c_wTbase*w;
   % A = reshape(ccc + AAA*w,size(c_x,1),[]);

   j = 1;
   confidencelevel = struct(groupedChanceConstraints{ic}).clauses{1}.confidencelevel;
   theMean    = randomVariables{j}.distribution.parameters{1};
   covariance = randomVariables{j}.distribution.parameters{2};
   gamma = icdf('normal',confidencelevel,0,1);

   switch randomVariables{j}.distribution.name
       case 'normal'
           theMean    = randomVariables{j}.distribution.parameters{1};
           covariance = randomVariables{j}.distribution.parameters{2};
           gamma = icdf('normal',confidencelevel,0,1);
           if isa(covariance,'sdpvar')
               error('Covariance cannot be an SDPVAR in normal distribution. Maybe you meant to use factorized covariance in ''normalf''');
           end
           Fderandomized = [Fderandomized, b + c_wTbase*theMean - (ccc + AAA*theMean)'*x >= gamma*norm(chol(covariance)*(AAA'*x+c_wTbase'))];
       case 'normalf'
           theMean    = randomVariables{j}.distribution.parameters{1};
           covariance = randomVariables{j}.distribution.parameters{2};
           gamma = icdf('normal',confidencelevel,0,1);
           Fderandomized = [Fderandomized, b + c_wTbase*theMean - (ccc + AAA*theMean)'*x >= gamma*norm(covariance*(AAA'*x+c_wTbase'))];
       otherwise
           error('Distribution not supported');
   end

end


function [BNEW,U,EXITFLAG,OUTPUT] = genNpReg2(A,B,options,defaultopt,regDim,varargin);
%GENNPREG2 solves general nonparametric image registration problems
%using a fixed point iteration
%
%
% author: Nathan D. Cahill
% email: nathan.cahill@rit.edu
% affiliation: Rochester Institute of Technology
% date: January 2014
% licence: GNU GPL v3
%
% Copyright Nathan D. Cahill
% Code available from https://github.com/tomdoel/npReg
%
%

% check whether the combination of options is supported
[SimMeasFlag,RegularizerFlag,BoundCondFlag] = checkOptions(options,defaultopt);

% initialize similarity measure value and type of comparison
[SimMeas,simMeasComparison] = initializeSimilarityMeasure(SimMeasFlag);
SimMeasNew = SimMeas;

% get appropriate function handle for computing body force
computeBodyForce = getBodyForceFunction(SimMeasFlag);

% get appropriate function handle for solving core PDE based on regularizer
% and boundary conditions
solveCorePDE = getCorePDESolverFunction(RegularizerFlag,BoundCondFlag,regDim);

% get various fields from options structure
DisplayFlag = npRegGet(options,'Display',defaultopt,'fast');
VoxSize = [npRegGet(options,'VoxSizeX',defaultopt,'fast') ...
    npRegGet(options,'VoxSizeY',defaultopt,'fast') ...
    npRegGet(options,'VoxSizeZ',defaultopt,'fast')];
MaxIter = npRegGet(options,'MaxIter',defaultopt,'fast');
UDiffTol = npRegGet(options,'UDiffTol',defaultopt,'fast');
VDiffTol = npRegGet(options,'VDiffTol',defaultopt,'fast');
BodyForceTol = npRegGet(options,'BodyForceTol',defaultopt,'fast');
SimMeasTol = npRegGet(options,'SimMeasTol',defaultopt,'fast');
BodyForceDiffTol = npRegGet(options,'BodyForceDiffTol',defaultopt,'fast');
SimMeasDiffTol = npRegGet(options,'SimMeasDiffTol',defaultopt,'fast');
SimMeasPercentDiffTol = npRegGet(options,'SimMeasPercentDiffTol',defaultopt,'fast');
FixedPointMaxFlowDistance = npRegGet(options,'FixedPointMaxFlowDistance',defaultopt,'fast');
RegridTol = npRegGet(options,'RegridTol',defaultopt,'fast');
Mu = npRegGet(options,'Mu',defaultopt,'fast');
Lambda = npRegGet(options,'Lambda',defaultopt,'fast');
ForceFactor = npRegGet(options,'ForceFactor',defaultopt,'fast');
RegularizerFactor = npRegGet(options,'RegularizerFactor',defaultopt,'fast');
StabilityConstant = npRegGet(options,'StabilityConstant',defaultopt,'fast');

% get size of images
[NumRows,NumCols,NumPages] = size(A);

% initialize various variables
if regDim == 2 % 2-D case
    [U,V,BodyForce,BodyForceNew,DU,X,BGrad] = deal(zeros(NumRows,NumCols,2));
    DefGrad = zeros(NumRows,NumCols,2,2);
    DefJac = zeros(NumRows,NumCols);
else % 3-D case
    [U,V,BodyForce,BodyForceNew,DU,X,BGrad] = deal(zeros(NumRows,NumCols,NumPages,3));
    DefGrad = zeros(NumRows,NumCols,NumPages,3,3);
    DefJac = zeros(NumRows,NumCols,NumPages);
end
MaxDUNorm = inf;
MeanDUNorm = inf;
MedDUNorm = inf;

% initialize vectors of grid positions
if regDim == 2 % 2-D case
    [X(:,:,1),X(:,:,2)] = ndgrid((0:(NumRows-1))*VoxSize(1),...
        (0:(NumCols-1))*VoxSize(2));
else % 3-D case
    [X(:,:,:,1),X(:,:,:,2),X(:,:,:,3)] = ndgrid((0:(NumRows-1))*VoxSize(1),...
        (0:(NumCols-1))*VoxSize(2),(0:(NumPages-1))*VoxSize(3));
end

% compute gradient of floating image, as this will be needed repeatedly
% within incremental updating
[HX,HY,HZ] = constructGradientFilters(VoxSize);
if regDim == 2 % 2-D case
    %HX = imfilter(HX,fspecial('gaussian',7,2),'full');
    %HY = imfilter(HY,fspecial('gaussian',7,2),'full');
    BGrad(:,:,1) = imfilter(B,HX,'replicate','same');
    BGrad(:,:,2) = imfilter(B,HY,'replicate','same');
else % 3-D case
    BGrad(:,:,:,1) = imfilter(B,HX,'replicate','same');
    BGrad(:,:,:,2) = imfilter(B,HY,'replicate','same');
    BGrad(:,:,:,3) = imfilter(B,HZ,'replicate','same');
end

% follow general framework of Bro-Nielsen and Gramkow, but allowing for
% different body force and regularizers

if isequal(DisplayFlag,'iter')
    displayString = sprintf('Iteration\tSimilarity\tBodyForceMax\tDisplaceMax\tMean\tMedian');
    disp(displayString);
end

% fixed point iteration loop
i = 1;
while i <= MaxIter

    % compute body force
    [BodyForceNew(:),SimMeasNew(:)] = computeBodyForce(A,B,BGrad,U,X,NumRows,NumCols,NumPages,VoxSize,regDim,HX,HY,HZ);
    %%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%%%%%%% try to make robust
    %if SimMeasNew > SimMeas
    %    ForceFactor = ForceFactor./((1+sqrt(5))/2);
    %    disp('Force Factor reduced.');
    %end
    %%%%%%%%%%%%%%%%%%%%%%%%%%%
    BodyForceNew(:) = BodyForceNew*ForceFactor;

    % solve PDE at current iteration
    %DU(:) = solveCorePDE(U,BodyForceNew,StabilityConstant,VoxSize,NumRows,NumCols,NumPages,Mu,Lambda,RegularizerFactor,DU,HX,HY,HZ);  % why not -U?
    DU(2:end-1,2:end-1,:) = RegularizerFactor.*imfilter(U(2:end-1,2:end-1,:),[0 1 0;1 -4 1;0 1 0],0) - BodyForceNew(2:end-1,2:end-1,:);
    %keyboard
    % compute time step based on maximum flow distance
    [TimeStep,MaxDUNorm(:),MeanDUNorm(:),MedDUNorm(:)] = ...
        computeTimeStep(DU,FixedPointMaxFlowDistance);

    % now add back to displacement field
    U(:) = U + TimeStep.*DU;

    % display information
    if isequal(DisplayFlag,'iter')
       displayString = sprintf('%5d\t\t%g\t\t%g\t\t%g\t\t%g\t\t%g',i,SimMeasNew,max(BodyForceNew(:)),MaxDUNorm,MeanDUNorm,MedDUNorm);
       disp(displayString);
    end

    % check tolerances for convergence
    [BreakCond,BreakMsg] = checkThresholds(BodyForce,BodyForceNew,SimMeas,...
        SimMeasNew,MaxDUNorm,UDiffTol,VDiffTol,BodyForceTol,SimMeasTol,...
        BodyForceDiffTol,SimMeasDiffTol,SimMeasPercentDiffTol,simMeasComparison);
    if BreakCond
        disp(BreakMsg);
        break;
    end

    % update similarity measure and body force
    SimMeas(:) = SimMeasNew;
    BodyForce(:) = BodyForceNew;

    % finally increment counter
    i = i+1;

end

% update image B to final deformation grid
if regDim == 2 % 2-D case
    BNEW = interp2(X(:,:,2),X(:,:,1),B,X(:,:,2)-U(:,:,2),...
        X(:,:,1)-U(:,:,1),'*linear',0);
else % 3-D case
    BNEW = interp3(X(:,:,:,2),X(:,:,:,1),X(:,:,:,3),B,...
        X(:,:,:,2)-U(:,:,:,2),X(:,:,:,1)-U(:,:,:,1),...
        X(:,:,:,3)-U(:,:,:,3),'*linear',0);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% need to add some code to return collection of deformation fields
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% set EXITFLAG
if i==(MaxIter+1) % maximum number of iterations reached
    EXITFLAG = 0;
else % solution found in fewer than maximum number of iterations
    EXITFLAG = 1;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% need to add some code to catch errors thrown by any called function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% set OUTPUT
OUTPUT.fixedPointIterations = i;
switch EXITFLAG
    case 1
        OUTPUT.message = 'NPREG2D converged to a solution.';
        if isequal(DisplayFlag,'iter') | isequal(DisplayFlag,'final')
            displayString = sprintf(OUTPUT.message);
            disp(displayString);
        end
    case 0
        OUTPUT.message = 'Maximum number of iterations reached.';
        if isequal(DisplayFlag,'iter') | isequal(DisplayFlag,'final')
            displayString = sprintf('%s%s',OUTPUT.message,' Terminating.');
            disp(displayString);
        end
    otherwise
        OUTPUT.message = 'If you see this message, you''re fucked.';
end

%-----------------------------------------------------------------------------------------
function [BreakCond,BreakMsg] = checkThresholds(BodyForce,BodyForceNew,SimMeas,SimMeasNew,MaxDUNorm,UDiffTol,VDiffTol,BodyForceTol,SimMeasTol,BodyForceDiffTol,SimMeasDiffTol,SimMeasPercentDiffTol,simMeasComparison);

% initialize break condition to zero
BreakCond = false;
BreakMsg = '';

% if body force is below a threshold for all points, then stop
MaxBodyForce = max(abs(BodyForceNew(:)));
if MaxBodyForce < BodyForceTol
    BreakMsg = 'Body force threshold met.';
    BreakCond = true;
end

% if body force difference is below a threshold for all points, then stop
MaxBodyForceDiff = max(abs(BodyForceNew(:)-BodyForce(:)));
if MaxBodyForceDiff < BodyForceDiffTol
    BreakMsg = 'Body force difference threshold met.';
    BreakCond = true;
end

% if similarity measure is beneath its threshold, then stop
if simMeasComparison(SimMeasNew,SimMeasTol)
    BreakMsg = 'Similarity Measure threshold met.';
    BreakCond = true;
end

% if similarity measure difference is beneath its threshold, then stop
SimMeasDiff = SimMeasNew - SimMeas;
if simMeasComparison(SimMeasNew,SimMeas)
    if abs(SimMeasDiff) < SimMeasDiffTol
        BreakMsg = 'Similarity measure difference threshold met.';
        BreakCond = true;
    end
end

% if similarity measure percentage decrease is beneath its threshold,
% then stop
if abs(SimMeas) < eps
    SimMeasPercentDiff = inf;
else
    SimMeasPercentDiff = SimMeasDiff./SimMeas;
end
if simMeasComparison(SimMeasNew,SimMeas)
    if abs(SimMeasPercentDiff) < SimMeasPercentDiffTol
        BreakMsg = 'Similarity measure percentage decrease threshold met.';
        BreakCond = true;
    end
end

% if maximum flow (velocity or displacement) is less than tolerance, then
% stop
if MaxDUNorm < UDiffTol
    BreakMsg = 'Maximum displacement threshold met.';
    BreakCond = true;
elseif MaxDUNorm < VDiffTol % this is wrong - needs to be changed
    BreakMsg = 'Maximum velocity threshold met.';
    BreakCond = true;
end

%-----------------------------------------------------------------------------------------
function [TimeStep,MaxDUNorm,MeanDUNorm,MedDUNorm] = computeTimeStep(DU,MaxFlow);

DUNorm = sqrt(sum(DU.^2,3));
MaxDUNorm = max(DUNorm(:));
MeanDUNorm = mean(DUNorm(:));
MedDUNorm = median(DUNorm(:));

if MaxDUNorm < MaxFlow
    TimeStep = 1;
else
    TimeStep = MaxFlow/MaxDUNorm;
end

%-----------------------------------------------------------------------------------------
function [HX,HY,HZ] = constructGradientFilters(VoxSize);

HX = [-1;0;1]/(2*VoxSize(1));
HY = [-1 0 1]/(2*VoxSize(2));
HZ = cat(3,-1,0,1)/(2*VoxSize(3));

%-----------------------------------------------------------------------------------------
function Y = getCorePDESolverFunction(Regularizer,BoundCond,regDim);

RegName = lower(Regularizer);
switch lower(BoundCond)
    case 'dirichlet'
        BoundCondName = 'Dirichlet';
    case 'periodic'
        BoundCondName = 'Periodic';
    case 'neumann'
        BoundCondName = 'Neumann';
end

Y = eval(['@',RegName,BoundCondName,int2str(regDim),'D']);

%-----------------------------------------------------------------------------------------
function Y = getBodyForceFunction(SimMeasFlag);

switch SimMeasFlag
    case 'SSD'
        Y = @bodyForceSSD;
    case 'NCC'
        Y = @bodyForceNCC;
    case 'CR'
        Y = @bodyForceCR;
    case 'MI'
        Y = @bodyForceMI;
    case 'NMI'
        Y = @bodyForceNMI;
end

%-----------------------------------------------------------------------------------------
function [S,comp] = initializeSimilarityMeasure(Flag);

switch Flag
    case 'SSD'
        S = inf;
        comp = @lt; % set comparison function to less than, as we are minimizing
    case {'NCC','CR','MI','NMI'}
        S = -inf;
        comp = @gt; % set comparison function to greater than, as we are maximizing
end

%-----------------------------------------------------------------------------------------
function [simMeasFlag,regularizerFlag,boundaryCondFlag] = checkOptions(options,defaultopt);

simMeasFlag = npRegGet(options,'SimilarityMeasure',defaultopt,'fast');
regularizerFlag = npRegGet(options,'Regularizer',defaultopt,'fast');
boundaryCondFlag = npRegGet(options,'BoundaryCond',defaultopt,'fast');

% test similarity measure support
if isequal(simMeasFlag,'NCC')
    errid = 'npRegLib:genNpReg:checkOptions:NCCNotSupported';
    errmsg = 'Normalized Cross Correlation not currently supported as similarity measure.';
elseif isequal(simMeasFlag,'CR')
    errid = 'npRegLib:genNpReg:checkOptions:CRNotSupported';
    errmsg = 'Correlation ratio not currently supported as similarity measure.';
elseif isequal(simMeasFlag,'MI')
    errid = 'npRegLib:genNpReg:checkOptions:MINotSupported';
    errmsg = 'Mutual information not currently supported as similarity measure.';
elseif isequal(simMeasFlag,'NMI')
    errid = 'npRegLib:genNpReg:checkOptions:NMINotSupported';
    errmsg = 'Normalized mututal information not currently supported as similarity measure.';
else
    errid = '';
    errmsg = '';
end

% report error
error(errid,errmsg);


function [innermost, inside] = find_innermost_boundary(bnd)

% FIND_INNERMOST_BOUNDARY locates innermost compartment of a BEM model
% by looking at the containment of the triangular meshes describing
% the surface boundaries
%
% [innermost] = find_innermost_boundary(bnd)
%
% with the boundaries described by a struct-array bnd with
%   bnd(i).pnt  vertices of boundary i (matrix of size Nx3)
%   bnd(i).tri  triangles of boundary i (matrix of size Mx3)

% Copyright (C) 2003, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

ncmp = length(bnd);

if ncmp==1
  innermost = 1;
  return
end

% try to locate the innermost compartment
for i=1:ncmp
for j=1:ncmp
  % determine for a single vertex on each surface if it is inside or outside the other surfaces
  curpos1 = bnd(i).pos(1,:); % any point on the boundary is ok
  curpos  = bnd(j).pos;
  curtri  = bnd(j).tri;
  if i==j
    inside(i,j) = 0;
  else
    inside(i,j) = bounding_mesh(curpos1, curpos, curtri);
  end
end
end
% assume that the sources are in the innermost compartment
tmp = sum(inside, 2);
[i, innermost] = max(tmp);


function result = swt16rec3_GPU(dec_full, level, waveletName)
%SWT16rec3 Stationary wavelet-based 2-level frame in 3-D.
%   swt16rec3_GPU performs a multi-level 3-D stationary wavelet synthesis
%   using a specific waveletName.
%
%   result = swt16rec3_GPU(dec_full, level, waveletName) computes the
%   3-D matrix 'result' at using the coefficients in 'dec_full', level
%   'level' and using 'waveletName'. Level must be either 1 or 2. Wavelet Toolbox
%   is required to retrieve the filters using 'waveletName'. Both 'level'
%   and 'waveletName' should match those used in creating 'dec_full'.
%
%   Requires the Parallel Computing Toolbox and a compatible GPU.
%
%   See conv3DGPU and swt16dec3_GPU

%   A. Kucukelbir 12-June-2012.
%   Last Revision: 26-June-2012.

% Create filters
if ischar(waveletName)
    [~,~,LR,HR] = wfilters(waveletName);
end

% Define kernels to be used by GPU
rowsKernel    = parallel.gpu.CUDAKernel('conv3DGPU.ptx', 'conv3DGPU.cu', 'rowsKernel');
columnsKernel = parallel.gpu.CUDAKernel('conv3DGPU.ptx', 'conv3DGPU.cu', 'columnsKernel');
beamsKernel   = parallel.gpu.CUDAKernel('conv3DGPU.ptx', 'conv3DGPU.cu', 'beamsKernel');
halfSum       = parallel.gpu.CUDAKernel('conv3DGPU.ptx', 'conv3DGPU.cu', 'halfSum');

% Upsample filters and create temporary cell
x = cell(1,1);
for i = 1:level-1
   LR = dyadup(LR,1);
   HR = dyadup(HR,1);
end

% Set parameters for convolution kernels on GPU
BLOCKDIM_X = 8;
BLOCKDIM_Y = 8;
BLOCKDIM_Z = 8;

for i = 1:level

    % Grab first level of frame coeffieicents.
    dec = dec_full(1:8);
    dec_full(1:8) = [];

    % Downsample filters
    if(i==2)
        LR = dyaddown(LR,0);
        HR = dyaddown(HR,0);
    end

    % Move filters to GPU
    LR_g = gpuArray(LR);
    HR_g = gpuArray(HR);

    % Calculate kernel radius
    if( mod(length(LR),2) == 0 )
        kernelRadius = length(LR)/2;
    else
        kernelRadius = (length(LR)-1)/2;
    end

    % Ensure volume has dimensions that are a multiple of 8
    diff = 0;
    if( mod(size(dec{1,1},1),8) ~= 0 )
    diff = 8*ceil(size(dec{1,1},1)/8) - size(dec{1,1},1);
        for j=1:8
        dec{j,1} = padarray(dec{j,1},[diff diff diff],'post');
        end
    end

    % Calculate volume sizes and transfer to GPU
    volRowSize = size(dec{1,1},1);
    volColSize = size(dec{1,1},2);
    volBeaSize = size(dec{1,1},3);
    dec1_g = gpuArray(dec{1,1});
    dec2_g = gpuArray(dec{2,1});
    dec3_g = gpuArray(dec{3,1});
    dec4_g = gpuArray(dec{4,1});
    dec5_g = gpuArray(dec{5,1});
    dec6_g = gpuArray(dec{6,1});
    dec7_g = gpuArray(dec{7,1});
    dec8_g = gpuArray(dec{8,1});

    % Setup GPU grids and blocks
    rowsKernel.GridSize        = [(volRowSize / BLOCKDIM_X) * (volBeaSize / BLOCKDIM_Z) , (volColSize / BLOCKDIM_Y)];
    rowsKernel.ThreadBlockSize = [BLOCKDIM_X, BLOCKDIM_Y, BLOCKDIM_Z];

    columnsKernel.GridSize        = [(volRowSize / BLOCKDIM_X) * (volBeaSize / BLOCKDIM_Z) , (volColSize / BLOCKDIM_Y)];
    columnsKernel.ThreadBlockSize = [BLOCKDIM_X, BLOCKDIM_Y, BLOCKDIM_Z];

    beamsKernel.GridSize        = [(volRowSize / BLOCKDIM_X) * (volBeaSize / BLOCKDIM_Z) , (volColSize / BLOCKDIM_Y)];
    beamsKernel.ThreadBlockSize = [BLOCKDIM_X, BLOCKDIM_Y, BLOCKDIM_Z];

    halfSum.GridSize        = [(volRowSize / BLOCKDIM_X) * (volBeaSize / BLOCKDIM_Z) , (volColSize / BLOCKDIM_Y)];
    halfSum.ThreadBlockSize = [BLOCKDIM_X, BLOCKDIM_Y, BLOCKDIM_Z];

    % Do the SWT for this level
    tmp_g = swt3_1level(dec1_g, dec2_g, dec3_g, dec4_g, dec5_g, dec6_g, dec7_g, dec8_g,...
                      LR_g, HR_g, ...
                      volRowSize, volColSize, volBeaSize, kernelRadius,...
                      rowsKernel, columnsKernel, beamsKernel, halfSum);

    % Remove multiple of 8 padding
    tmp = gather(tmp_g);
    x{i,1} = tmp(1:end-diff, 1:end-diff, 1:end-diff);

    % Remove kernelRadius padding
    if( mod(length(LR),2) == 0 )
            x{i,1} = x{i,1}(kernelRadius:end-(kernelRadius-1)-1, kernelRadius:end-(kernelRadius-1)-1, kernelRadius:end-(kernelRadius-1)-1);
    else
            x{i,1} = x{i,1}(kernelRadius+1:end-kernelRadius, kernelRadius+1:end-kernelRadius, kernelRadius+1:end-kernelRadius);
    end

    % Take care of second level specific processing
    if (i == 2)
        x{1,1} = padarray(x{1,1},[diff diff diff],'post');
        dec1_g = gpuArray(x{1,1});
            tmp_g = swt3_1level(dec1_g, dec2_g, dec3_g, dec4_g, dec5_g, dec6_g, dec7_g, dec8_g,...
                      LR_g, HR_g, ...
                      volRowSize, volColSize, volBeaSize, kernelRadius,...
                      rowsKernel, columnsKernel, beamsKernel, halfSum);
        tmp = gather(tmp_g);
        tmp = tmp(1:end-diff, 1:end-diff, 1:end-diff);
        if( mod(length(LR),2) == 0 )
            x{1,1} = tmp(kernelRadius:end-(kernelRadius-1)-1, kernelRadius:end-(kernelRadius-1)-1, kernelRadius:end-(kernelRadius-1)-1);
        else
            x{1,1} = tmp(kernelRadius:end-kernelRadius-1, kernelRadius:end-kernelRadius-1, kernelRadius:end-kernelRadius-1);
        end
    end

end

% Combine results from all levels
result = zeros(size(x{1,1}));
for i = 1:level
    result = result + 1/level*x{i,1};
end

end

function x = swt3_1level(dec1_g, dec2_g, dec3_g, dec4_g, dec5_g, dec6_g, dec7_g, dec8_g,...
                  LR_g, HR_g, ...
                  volRowSize, volColSize, volBeaSize, kernelRadius,...
                  rowsKernel, columnsKernel, beamsKernel, halfSum)

%% FIRST PASS ALONG BEAMS
% Get the AA
aaa_Lo_Lo_Lo_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
daa_Lo_Lo_Hi_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
aa_Lo_Lo_g     = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);

aaa_Lo_Lo_Lo_g = feval( beamsKernel, aaa_Lo_Lo_Lo_g, dec1_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );
daa_Lo_Lo_Hi_g = feval( beamsKernel, daa_Lo_Lo_Hi_g, dec2_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );

aa_Lo_Lo_g = feval( halfSum, aa_Lo_Lo_g, aaa_Lo_Lo_Lo_g, daa_Lo_Lo_Hi_g, volRowSize, volColSize, volBeaSize );

% Get the DA
ada_Lo_Hi_Lo_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
dda_Lo_Hi_Hi_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
da_Lo_Hi_g     = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);

ada_Lo_Hi_Lo_g = feval( beamsKernel, ada_Lo_Hi_Lo_g, dec3_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );
dda_Lo_Hi_Hi_g = feval( beamsKernel, dda_Lo_Hi_Hi_g, dec4_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );

da_Lo_Hi_g = feval( halfSum, da_Lo_Hi_g, ada_Lo_Hi_Lo_g, dda_Lo_Hi_Hi_g, volRowSize, volColSize, volBeaSize );

% Get the AD
aad_Hi_Lo_Lo_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
dad_Hi_Lo_Hi_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
ad_Hi_Lo_g     = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);

aad_Hi_Lo_Lo_g = feval( beamsKernel, aad_Hi_Lo_Lo_g, dec5_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );
dad_Hi_Lo_Hi_g = feval( beamsKernel, dad_Hi_Lo_Hi_g, dec6_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );

ad_Hi_Lo_g = feval( halfSum, ad_Hi_Lo_g, aad_Hi_Lo_Lo_g, dad_Hi_Lo_Hi_g, volRowSize, volColSize, volBeaSize );

% Get the DD
add_Hi_Hi_Lo_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
ddd_Hi_Hi_Hi_g = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
dd_Hi_Hi_g     = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);

add_Hi_Hi_Lo_g = feval( beamsKernel, add_Hi_Hi_Lo_g, dec7_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );
ddd_Hi_Hi_Hi_g = feval( beamsKernel, ddd_Hi_Hi_Hi_g, dec8_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );

dd_Hi_Hi_g = feval( halfSum, dd_Hi_Hi_g, add_Hi_Hi_Lo_g, ddd_Hi_Hi_Hi_g, volRowSize, volColSize, volBeaSize );

%% SECOND PASS ALONG COLUMNS
% Get the A
aa_Lo_Lo_gt = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
da_Lo_Hi_gt = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
a_Lo_g      = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);

aa_Lo_Lo_gt = feval( columnsKernel, aa_Lo_Lo_gt, aa_Lo_Lo_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );
da_Lo_Hi_gt = feval( columnsKernel, da_Lo_Hi_gt, da_Lo_Hi_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );

a_Lo_g = feval( halfSum, a_Lo_g, aa_Lo_Lo_gt, da_Lo_Hi_gt, volRowSize, volColSize, volBeaSize );

% Get the D
ad_Hi_Lo_gt = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
dd_Hi_Hi_gt = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
d_Hi_g      = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);

ad_Hi_Lo_gt = feval( columnsKernel, ad_Hi_Lo_gt, ad_Hi_Lo_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );
dd_Hi_Hi_gt = feval( columnsKernel, dd_Hi_Hi_gt, dd_Hi_Hi_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );

d_Hi_g = feval( halfSum, d_Hi_g, ad_Hi_Lo_gt, dd_Hi_Hi_gt, volRowSize, volColSize, volBeaSize );

%% FIRST PASS ALONG ROWS
a_Lo_gt = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
d_Hi_gt = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);
x       = parallel.gpu.GPUArray.zeros(volRowSize, volColSize, volBeaSize);

a_Lo_gt = feval( rowsKernel, a_Lo_gt, a_Lo_g, LR_g, volRowSize, volColSize, volBeaSize, kernelRadius );
d_Hi_gt = feval( rowsKernel, d_Hi_gt, d_Hi_g, HR_g, volRowSize, volColSize, volBeaSize, kernelRadius );

x = feval( halfSum, x, a_Lo_gt, d_Hi_gt, volRowSize, volColSize, volBeaSize );

end


function model = rmGridFit_twoGaussiansToG(model,prediction,data,params,t)
% rmGridFit_twoGaussiansToG - core of ToG fit
%
% model = rmGridFit_twoGaussiansToG(model,prediction,data,params);
%
% Second gaussian can go positive or negative.
%
% 2008/01 SOD: split of from rmGridFit.

% input check
if nargin < 4,
    error('Not enough arguments');
end

% some variables we need
rssinf         = inf(size(data(1,:)),'single');
trends         = t.trends;
t_id           = t.dcid+2;

% stimulus sequence is needed because make second pRF on the fly
allstimimages = rmDecimate(params.analysis.allstimimages,...
    params.analysis.coarseDecimate);

%-----------------------------------
%--- fit different receptive fields profiles
%--- another loop --- and a slow one too
%-----------------------------------
tic; progress = 0;
for n=1:numel(params.analysis.x0),
    %-----------------------------------
    % progress monitor (10 dots) and time indicator
    %-----------------------------------
    if floor(n./numel(params.analysis.x0).*10)>progress,
        if progress==0,
            % print out estimated time left
            esttime = toc.*10;
            if floor(esttime./3600)>0,
                fprintf(1,'[%s]:Estimated processing time: %d hours.\t(%s)\n',...
                    mfilename, ceil(esttime./3600), datestr(now));
            else
                fprintf(1, '[%s]:Estimated processing time: %d minutes.\t(%s)\n',...
                    mfilename, ceil(esttime./60), datestr(now));
            end;
            fprintf(1,'[%s]:Grid (x,y,sigma) fit:',mfilename);drawnow;
        end;
        % progress monitor
        fprintf(1,'.');drawnow;
        progress = progress + 1;
    end;

    %-----------------------------------
    %--- first make all second rf profiles
    %-----------------------------------
    sigmaNew = params.analysis.sigmaRatio.*params.analysis.sigmaMajor(n);
    % limit to sigmaRatioMaxVal
    sigmaNew = sigmaNew(sigmaNew<=params.analysis.sigmaRatioMaxVal);
    % add sigmaRatioInfVal which essentially is on/off
    sigmaNew = [sigmaNew; params.analysis.sigmaRatioInfVal]; %#ok<AGROW>

    % Now we make it: slightly different call for speed reasons.
    z = zeros(size(sigmaNew));
    tmprf   = rfGaussian2d(params.analysis.X - params.analysis.x0(n),...
        params.analysis.Y - params.analysis.y0(n),...
        sigmaNew,sigmaNew, ...
        false, z, z);
    prediction2 = allstimimages*tmprf;

    %-----------------------------------
    %--- try two rf profiles, yet another loop
    %-----------------------------------
    for sr = 1:numel(sigmaNew),
        %-----------------------------------
        % Now apply GLM, see *_oneGaussian for logic.
        % New rules for this one:
        % 1. first Gaussian has to be positive
        % 2. there should be a positive response in the
        % center at all times. This
        % assumes Gaussians are unscaled (see rfGaussian2d).
        %-----------------------------------
        X     = [prediction(:,n) prediction2(:,sr) trends];
        b     = pinv(X)*data;
        rss   = rssinf;
        keep  = b(1,:)>0 & b(1,:)>-b(2,:);
        rss(keep) = sum((data(:,keep)-X*b(:,keep)).^2);

        %-----------------------------------
        %--- store data with lower rss
        %-----------------------------------
        minRssIndex = rss < model.rss;

        % now update
        model.x0(minRssIndex)       = params.analysis.x0(n);
        model.y0(minRssIndex)       = params.analysis.y0(n);
        model.s(minRssIndex)        = params.analysis.sigmaMajor(n);
        model.s_major(minRssIndex)        = params.analysis.sigmaMajor(n);
        model.s_minor(minRssIndex)        = params.analysis.sigmaMajor(n);
        model.s_theta(minRssIndex)        = params.analysis.theta(n);
        model.rss(minRssIndex)      = rss(minRssIndex);
        model.b([1:2 t_id],minRssIndex)    = b(:,minRssIndex);
        model.s2(minRssIndex)       = sigmaNew(sr);
    end;
end;

% end time monitor
et  = toc;
if floor(esttime/3600)>0,
    fprintf(1,'Done[%d hours].\t(%s)\n', ceil(et/3600), datestr(now));
else
    fprintf(1,'Done[%d minutes].\t(%s)\n', ceil(et/60), datestr(now));
end;
drawnow;
return;


function [x,y,z] = getLMpolygon3D(polygon)
%
% Utility function that gives the coordinates of the polygon's vertices

x = str2num(char({polygon.pt.x})); % get X polygon coordinates
y = str2num(char({polygon.pt.y})); % get Y polygon coordinates
z = str2num(char({polygon.pt.z})); % get Y polygon coordinates


function Ne=vertex_neighbours_double(Fa,Fb,Fc,Vx,Vy,Vz)

F=[Fa Fb Fc];
V=[Vx Vy Vz];

% Neighbourh cell array
Ne=cell(1,size(V,1));

% Loop through all faces
for i=1:length(F)
    % Add the neighbors of each vertice of a face
    % to his neighbors list.
    Ne{F(i,1)}=[Ne{F(i,1)} [F(i,2) F(i,3)]];
    Ne{F(i,2)}=[Ne{F(i,2)} [F(i,3) F(i,1)]];
    Ne{F(i,3)}=[Ne{F(i,3)} [F(i,1) F(i,2)]];
end

% Loop through all neighbor arrays and sort them (Rotation same as faces)
for i=1:size(V,1)

    Pneighf=Ne{i};
    if(isempty(Pneighf))
        Pneig=[];
    else
        start=1;
        for index1=1:2:length(Pneighf)
            found=false;
            for index2=2:2:length(Pneighf),
                if(Pneighf(index1)==Pneighf(index2))
                    found=true; break
                end
            end
            if(~found)
                start=index1; break
            end
        end
        Pneig=[];
        Pneig(1)=Pneighf(start);
        Pneig(2)=Pneighf(start+1);

        % Add the neighbours with respect to original rotation
        for j=2+double(found):(length(Pneighf)/2)
            found = false;
            for index=1:2:length(Pneighf),
                if(Pneighf(index)==Pneig(end))
                    if(sum(Pneig==Pneighf(index+1))==0)
                        found =true;
                        Pneig=[Pneig Pneighf(index+1)];
                    end
                end
            end
            if(~found) % This only happens with weird edge vertices
                for index=1:2:length(Pneighf),
                    if(sum(Pneig==Pneighf(index))==0)
                        Pneig=[Pneig Pneighf(index)];
                        if(sum(Pneig==Pneighf(index+1))==0)
                            Pneig=[Pneig Pneighf(index+1)];
                        end
                    end
                end
            end
        end
        % Add forgotten neigbours
        if(length(Pneig)<length(Pneighf))
            for j=1:length(Pneighf)
                if(sum(Pneig==Pneighf(j))==0)
                    Pneig=[Pneig Pneighf(j)];
                end
            end
        end
    end
    Ne{i}=Pneig;
end


      function h = specgram(s, T, varargin)
         %specgram - plots spectrogram of traces
         %  h = TraceSpectra.specgram(traces) Generates a spectrogram from the
         %  trace(s), overwriting the current figure.  The return value is a
         %  handle to the spectrogram, and is optional. The spectrograms will be
         %  created in the same shape as the passed traces.  ie, if W is a 2x3
         %  matrix of traces, then specgram(TraceSpectra,W) will generate a 2x3
         %  plot of spectra.
         %
         %  Many additional behaviors can be modified through the passing of
         %  additional parameters, as listed further below.  These parameters are
         %  always passed in pairs, as such:
         %
         %  TraceSpectra.specgram(traces,'PARAM1',VALUE1,...,'PARAMn',VALUEn)
         %    Any number of these parameters may be passed to specgram.
         %
         %  specgram(..., 'axis', AXIS_HANDLE)
         %    Specify the axis AXIS_HANDLE within which the spectrogram will be
         %    generated.  The boundary of the axis becomes the boundary for the
         %    entire spectra plot.  For a matrix of traces, this area is
         %    subdivided into NxM subplots, where N and M are the size of the
         %    trace matrix.
         %
         %  specgram(..., 'xunit', XUNIT)
         %    Spedifies the x-unit scale to be used with the spectrogram.  The
         %    default unit is 'seconds'.
         %    valid xunits:
         %     'seconds','minutes','hours','days','doy' (day of year),and 'date'
         %
         %  specgram(..., 'colormap', ALTERNATEMAP)
         %    Instead of using the default colormap, any colormap may be used.  An
         %    alternate way of setting the global map is by using the SETMAP
         %    function.  ALTERNATEMAP will either be a name (eg. grayscale) or an
         %    Nx3 numeric. Type HELP GRAPH3D to see additional useful colormaps.
         %
         %
         %  specgram(..., 'colorbar', COLORBAR_OPTION)
         %    Generates a spectrogram from the trace and uses a specific map
         %    valid COLORBAR_OPTION values: 'horiz' (default),'vert','none',
         %      'HORIZ' places a single colorbar below all plots
         %      'VERT' places a single colorbar to the right of all plots
         %      'NONE' supresses the colorbar placement
         %
         %  specgram(..., 'yscale', YSCALE)
         %    Choosing 'log' Allows the y-axis to be generated on a log-frequency
         %    scale, with uneven vertical cell spacing.  The default value is
         %    'normal', and provides the standard spectrogram view.
         %    valid yscales: 'normal', 'log' (see NOTE below)
         %
         %    NOTE: In order to use the log scale, UIMAGESC needs to be available on
         %    the matlab path.  This routine was created by Frederic Moisy, and may
         %    be downloaded from the maltabcentral fileexchange (File ID: 11368).
         %    If this routine is not found,then the original spectrogram will be
         %    created.
         %
         %   h = specgram(..., 'fontsize', FONTSIZE)
         %   Specify the font size for a spectrogram.  The default font size is 8.
         %
         %  specgram2(..., 'innerLabels', SHOWINNERLABELS)
         %    Suppress the labling of the inside graphs by setting SHOWINNERLABELS
         %    to false.  If this is false, then the frequency label only shows on
         %    the leftmost spectrograms, and the X-unit label only shows on the
         %    bottommost spectrograms.
         %
         %  The following plots a trace using an alternate mapping, an xunit of
         %  'hours', and with the y-axis plotted using a log scale.
         %  ex. specgram(TraceSpectra, trace,...
         %      'colormap', alternateMap,'xunit','h','yscale','log')
         %
         %
         %  Example:
         %    % create an arbitrary subplot, and then plot multiple spectra
         %    a = subplot(3,2,1);
         %    specgram(TraceSpectra,waves,'axis',a); % waves is an NxM trace
         %
         %
         %  See also SPECTRALOBJECT/SPECGRAM2, trace/PLOT, trace/FILLGAPS

         % Thanks to Jason Amundson for providing the way to do log scales

         % currFontSize = 8; % replaced in the parser
         %enforce input arguments.
         if ~isa(T,'TraceData')
            try
               T = SeismicTrace(T);
            catch er
               error('Second input argument should be a TraceData, not a %s',class(T));
            end
         end
         p = parseSpecgramInputs(s, varargin);

         %% search for relevent property pairs passed as parameters
         myaxis = p.Results.axis; % area to be used
         % position not used...
         alternateMap = p.Results.colormap;
         xChoice = p.Results.xunit; %time units for plot
         currFontSize = p.Results.fontsize; % used for all laels within plot
         colorbarpref = p.Results.colorbar; %position of colorbar
         suppressLabels = p.Results.innerlabels; %show only outside
         useXlabel = p.Results.useXlabel; % no x labels
         useYlabel = p.Results.useYlabel; % no y labels

         logscale = strcmpi(p.Results.yscale,'log');

         %% figure out exactly WHERE to plot the spectrogram(s)
         %find out area(axis) in which the spectrograms will be plotted
         clabel= 'Relative Amplitude  (dB)';

         if myaxis == 0,
            clf;
            myaxis = gca;
            get(gca,'position');
         else
            get(myaxis,'position');
         end

         %% If there are multiple traces...
         % subdivide the axis and loop through specgram2 with individual traces.

         if numel(T) > 1
            %create the colorbar if desired
            TraceSpectra.createcolorbar(s, colorbarpref, clabel, currFontSize)
            h = TraceSpectra.subdivide_axes(myaxis,size(T));
            remainingproperties = TraceSpectra.buildParameterList(p.Unmatched);
            for n=1:numel(h)
               keepYlabel =  ~suppressLabels || (n <= size(h,1));
               keepXlabel = ~suppressLabels || (mod(n,size(h,2))==0);
               specgram(s,T(n),...
                  'xunit',xChoice,...
                  'axis',h(n),...
                  'fontsize',currFontSize,...
                  'useXlabel',keepXlabel,...
                  'useYlabel',keepYlabel,...
                  'colorbar','none',...
                  remainingproperties{:});
            end
            return
         end

         axes(myaxis);

         if T.hasnan % only 1 trace guaranteed at this point...
            warning('TraceSpectra:specgram:nanValue',...
               ['This trace has at least one NaN value, which will blank',...
               'the related spectrogram segment. ',...
               'Remove NaN values by either splitting up the ',...
               'trace into non-NaN sections or by using TraceData/fillgaps',...
               ' to replace the NaN values.']);
         end

         [xunit, xfactor] = TraceSpectra.parse_xunit(xChoice);

         switch lower(xunit)
            case 'date'
               % we need the actual times...
               Xvalues = get(T,'timevector');

            case 'day of year'
               startvec = datevec(get(T,'start'));
               Xvalues = get(T,'timevector');
               dec31 = datenum(startvec(1)-1,12,31); % 12/31/xxxx of previous year in Matlab format
               Xvalues = Xvalues - dec31;
               xunit = [xunit, ' (', datestr(startvec,'yyyy'),')'];

            otherwise,
               dl= 1:T.nsamples(); %dl : DataLength
               Xvalues = dl .* T.period ./ xfactor;
         end

         %%  once was function specgram(d, NYQ, nfft, noverlap, freqmax, dBlims)

         nx = length(T.data);
         window = hanning(s.nfft);
         nwind = length(window);
         if nx < nwind    % zero-pad x if it has length less than the window length
            T.data(nwind) = 0;
            nx = nwind;
         end

         ncol = fix( (nx - s.over) / (nwind - s.over) );

         %added "floor" below
         colindex = 1 + floor(0:(ncol-1))*(nwind- s.over);
         rowindex = (1:nwind)';
         if length(T.data)<(nwind+colindex(ncol)-1)
            T.data(nwind+colindex(ncol)-1) = 0;   % zero-pad x
         end

         y = zeros(nwind,ncol);

         % put x into columns of y with the proper offset
         % should be able to do this with fancy indexing!
         A_ = colindex(  ones(nwind, 1) ,: )    ;
         B_ = rowindex(:, ones(1, ncol)    )    ;
         y(:) = T.data(fix(A_ + B_ -1));
         clear A_ B_

         for k = 1:ncol;         %  remove the mean from each column of y
            y(:,k) = y(:,k)-mean(y(:,k));
         end

         % Apply the window to the array of offset signal segments.
         y = window(:,ones(1,ncol)).*y;

         % USE FFT
         % now fft y which does the columns
         y = fft(y,s.nfft);
         if ~any(any(imag(T.data)))    % x purely real
            if rem(s.nfft,2),    % nfft odd
               select = 1:(s.nfft+1)/2;
            else
               select = 1:s.nfft/2+1;
            end
            y = y(select,:);
         else
            select = 1:s.nfft;
         end
         f = (select - 1)' * T.samplerate / s.nfft;

         NF = s.nfft/2 + 1;
         nf1=round(f(1) / T.nyquist * NF);                     %frequency window
         if nf1==0, nf1=1; end
         nf2=NF;

         y = 20*log10(abs(y(nf1:nf2,:)));

         F = f(f <= s.freqmax);

         if F(1)==0,
            F(1)=0.001;
         end

         if logscale
            t = linspace(Xvalues(1), Xvalues(end),ncol); % Replaced by TCB - 01/18/2012
            try
               h = uimagesc(t, log10(F), y(nf1:length(F),:), s.dBlims);
            catch exception
               if strcmp(exception.identifier, 'MATLAB:UndefinedFunction')
                  warning('Spectralobject:specgram:uimageNotInstalled',...
                     ['Cannot plot with log spacing because uimage, uimagesc ',...
                     ' not installed or not visible in matlab path.']);
                  h = imagesc(Xvalues,F,y(nf1:length(F),:),s.dBlims);
                  logscale = false;
               else
                  rethrow(exception)
               end
            end
         else
            h = imagesc(Xvalues, F, y(nf1:length(F),:), s.dBlims);
         end
         set(gca, 'fontsize', currFontSize);
         if strcmpi(xunit, 'date')
            datetick('x', 'keepticks');
         end
         titlename = [T.station '-' T.channel '  from:' T.start];
         title (titlename);
         axis xy;
         colormap(alternateMap);
         shading flat
         axis tight;
         if useYlabel
            if ~logscale
               ylabel ('Frequency (Hz)')
            else
               ylabel ('Log Frequency (log Hz)')
            end

         end
         if useXlabel
            xlabel(['Time - ',xunit]);
         end

         %create the colorbar if desired
         TraceSpectra.createcolorbar(s,colorbarpref, clabel, currFontSize);

         %% added a series of functions that help with argument parsing.
         % These were ported from my trace/plot function.

      end %specgram


function varargout = iszero(varargin)
%ISZERO   Check if a DISKFUN is identically zero on its domain.
%   OUT = ISZERO( F ) return 1 if the DISKFUN is exactly the zero function, and
%   0 otherwise.

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

[varargout{1:nargout}] = iszero@separableApprox(varargin{:});

end


function [y,deriv] = linTrans_adaptive(w,map,transmap)
% This is an MV2DF. See MV2DF_API_DEFINITION.readme.
%
% Applies linear transform y = map(w). It needs the transpose of map,
% transmap for computing the gradient. map and transmap are function
% handles.

if nargin==0
    test_this();
    return;
end

if isempty(w)
    y = @(w)linTrans_adaptive(w,map,transmap);
    return;
end

if isa(w,'function_handle')
    outer = linTrans_adaptive([],map,transmap);
    y = compose_mv(outer,w,[]);
    return;
end

y = map(w);
y = y(:);

deriv = @(g2) deriv_this(g2,map,transmap,numel(w));
end

function [g,hess,linear] = deriv_this(g2,map,transmap,wlen)
g = transmap(g2,wlen);
g = g(:);
%linear = false;  % use this to test linearity of map, if in doubt
linear = true;
hess = @(d) hess_this(map,d);
end

function [h,Jd] = hess_this(map,d)
h = [];
if nargout>1
    Jd = map(d);
    Jd = Jd(:);
end

end

function test_this()
first = 2;
len = 3;
map = @(w) w(first:first+len-1);
function w = transmap_test(y,sz)
    w=zeros(sz,1);
    w(first:first+len-1)=y;
end
transmap = @(y,sz) transmap_test(y,sz);
f = linTrans_adaptive([],map,transmap);
test_MV2DF(f,randn(5,1));
end


function [model, lbls] = fgplvmLoadResult(dataSet, number)

% FGPLVMLOADRESULT Load a previously saved result.
% FORMAT
% DESC loads a previously saved FGPLVM result.
% ARG dataSet : the name of the data set to load.
% ARG number : the number of the FGPLVM run to load.
% RETURN model : the saved model.
% RETURN lbls : labels of the data set (for visualisation purposes).
%
% SEEALSO : fgplvmLoadResult
%
% COPYRIGHT : Neil D. Lawrence, 2003, 2004, 2005, 2006, 2008

% FGPLVM

[Y, lbls] = lvmLoadData(dataSet);

dataSet(1) = upper(dataSet(1));
load(['dem' dataSet 'Fgplvm' num2str(number)])
model = fgplvmReconstruct(kern, noise, fgplvmInfo, X, Y);


function disp(t,name)
%DISP Command window display of a matricized tensor (tenmat).
%
%   DISP(T) displays a tensor as matrix with no name.
%
%   DISP(T,NAME) display a tensor as matrix with the given name.
%
%   See also TENMAT, TENMAT/DISPLAY.
%
%MATLAB Tensor Toolbox.
%Copyright 2012, Sandia Corporation.

% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2012) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt

if ~exist('name','var')
    name = 'ans';
end

fprintf('%s is a matrix corresponding to a tensor of size %s\n',...
        name,tt_size2str(t.tsize));
fprintf('\t%s.rindices = %s (modes of tensor corresponding to rows)\n',...
        name,['[ ' num2str(t.rindices) ' ]']);
fprintf('\t%s.cindices = %s (modes of tensor corresponding to columns)\n',...
        name,['[ ' num2str(t.cindices) ' ]']);

if isempty(t.data)
    fprintf('\t%s.data = []\n',name);
else
    fprintf('\t%s.data = \n',name);
    output = tt_matrix2cellstr(t.data);
    fprintf('\t\t%s\n',output{:});
end


function [graph,nodeNames,nodeInfo] = prtUtilReadGml(file)
%[graph,names,etc] = prtUtilReadGml(file)
%  Read graph-spec files with .gml formating.

etc = [];

fid = fopen(file,'r');
directed = false;

nodeList = [];
edgeList = [];
while ~feof(fid)
    str = fgetl(fid);
    str = lower(str);

    if ~isempty(strfind(str,'directed'))
        temp = regexp(str,'directed (?<directed>[0-9]*)','names');
        directed = logical(str2double(temp.directed));
    end

    if ~isempty(strfind(str,']')) || ~isempty(strfind(str,'['))
        continue;
    else
        if ~isempty(strfind(str,'node'))
            newNode = readNode(fid);
            if isempty(nodeList)
                nodeList = newNode;
            else
                nodeList = cat(1,nodeList,newNode);
            end
        end
        if ~isempty(strfind(str,'edge'));
            newEdge = readEdge(fid);
            if isempty(edgeList)
                edgeList = newEdge;
            else
                edgeList = cat(1,edgeList,newEdge);
            end
        end
    end
end
fclose all;

nodeNames = {nodeList.id}';
nodeVals = cat(1,nodeList.val);
edgeVals = cat(1,edgeList.connection);

edgeIndices = zeros(size(edgeVals));
for i = 1:size(edgeVals,1)
    edgeIndices(i,:) = [find(edgeVals(i,1) == nodeVals),find(edgeVals(i,2) == nodeVals)];
end

graph = sparse(edgeIndices(:,1),edgeIndices(:,2),1,length(nodeVals),length(nodeVals));
if ~directed
    graph = graph + sparse(edgeIndices(:,2),edgeIndices(:,1),1,length(nodeVals),length(nodeVals));
end
nodeInfo = nodeList;

%
function newEdge = readEdge(fid)

newEdge = struct('connection',[]);
while true
    str = fgetl(fid);
    if ~isempty(strfind(str,'['))

    elseif ~isempty(strfind(str,']'))
        return;
    elseif ~isempty(strfind(str,'source'))
        temp1 = regexp(str,'source (?<nodeNumber>[0-9].*)','names');
        int1 = str2double(temp1.nodeNumber);

        str = fgetl(fid);
        temp2 = regexp(str,'target (?<nodeNumber>[0-9].*)','names');
        int2 = str2double(temp2.nodeNumber);
        newEdge.connection = [int1,int2];
    end
end

function newNode = readNode(fid)

newNode = struct('val',[],'id','');
while true
    str = fgetl(fid);
    str = strtrim(str);
    if ~isempty(strfind(str,'['))

    elseif ~isempty(strfind(str,']'))
        return;
    elseif ~isempty(regexp(str,'^id','once'))
        temp = regexp(str,'id (?<nodeNumber>[0-9].*)','names');
        int = str2double(temp.nodeNumber);
        newNode.val = int;
        newNode.id = sprintf('Node %d',int);
    elseif ~isempty(regexp(str,'^label','once'))
        temp = regexp(str,'label (?<nodeLabel>["A-Z].*)','names');
        temp.nodeLabel = strrep(temp.nodeLabel,'"','');
        newNode.id = temp.nodeLabel;
    elseif ~isempty(regexp(str,'^value','once'))
        temp = regexp(str,'value (?<value>.*)','names');
        newNode.value = str2double(temp.value);
    else
        warning('I didnt know what to do');
    end
end


function tests = test_ft_preproc_resample

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

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

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

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

result = {};
result{end+1} = ft_preproc_resample(dat, 1000, 100, 'resample');
result{end+1} = ft_preproc_resample(dat, 1000, 250, 'resample');
result{end+1} = ft_preproc_resample(dat, 1000, 500, 'resample');
result{end+1} = ft_preproc_resample(dat, 1000, 100, 'decimate');
result{end+1} = ft_preproc_resample(dat, 1000, 250, 'decimate');
result{end+1} = ft_preproc_resample(dat, 1000, 500, 'decimate');
result{end+1} = ft_preproc_resample(dat, 1000, 100, 'downsample');
result{end+1} = ft_preproc_resample(dat, 1000, 250, 'downsample');
result{end+1} = ft_preproc_resample(dat, 1000, 500, 'downsample');
result{end+1} = ft_preproc_resample(dat, 1000, 100, 'fft');
result{end+1} = ft_preproc_resample(dat, 1000, 250, 'fft');
result{end+1} = ft_preproc_resample(dat, 1000, 500, 'fft');

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


% Copyright Mohammad SAFEEA, 17th-Aug-2017
function setJointAngleToText(anglesTextHandlesCellArray, index,angle )
%% Set the joint angle in degrees for the
    angle=180*angle/pi;
    set(anglesTextHandlesCellArray{index},'String',num2str(angle));
    %set(anglesTextHandlesCellArray{1},'BackgroundColor','red');

end


classdef SplitterInConnectedComponents < handle

    properties (Access = private)
        edges
        adjancyMatrix
        graphV
        connectedComp
    end

    properties (Access = private)
        faces
    end

    methods (Access = public)

        function obj = SplitterInConnectedComponents(cParams)
            obj.init(cParams)
        end

        function c = split(obj)
            obj.computeEdges();
            obj.computeAdjacencyMatrix();
            obj.computeGraph();
            obj.computeConnectedComponents();
            c = obj.connectedComp;
        end

    end

    methods (Access = private)

        function init(obj,cParams)
            obj.faces = cParams.faces;
        end

        function computeEdges(obj)
            s.nodesByElem = obj.faces;
            edge = EdgesConnectivitiesComputer(s);
            edge.compute();
            obj.edges = edge.nodesInEdges;
        end

        function [A] = computeAdjacencyMatrix(obj)
            nodeA = obj.edges(:,1);
            nodeB = obj.edges(:,2);
            A = sparse(nodeA,nodeB,1);
            obj.adjancyMatrix = A+A';
        end

        function computeGraph(obj)
            A = obj.adjancyMatrix;
            g = graph(A,'omitselfloops');
            obj.graphV = g;
        end

        function computeConnectedComponents(obj)
            g = obj.graphV;
            comp = conncomp(g);
            obj.connectedComp = comp;
        end

    end

end


%create_nullspace Create null-space for scene with perspective camera.
%
%  Parameters:
%    depths .. matrix of zeros and ones meaning whether corresponding element
%              in M is scaled (i.e. multiplied by known perspective depth)

function [nullspace, result] = create_nullspace(M, depths, central, opt)

if nargin < 4, opt.trial_coef = 1;
               opt.threshold  = .01; end

I = ~isnan(M(1:3:end,:)); [m n] = size(I); show_mod = 10; use_maxtuples = 0;
if opt.verbose, fprintf(1, 'Used 4-tuples (.=%d): ', show_mod); tic; end

if central,  cols_scaled(1:n) = 0; cols_scaled(find(I(central,:) > 0)) = 1;
else, cols_scaled = []; end

num_trials = round(opt.trial_coef * n);

if opt.verbose, fprintf(1,'(Allocating memory...'); end
nullspace(size(M,1),num_trials) = 0; % Memory allocation: at least this
                                     % because at least one column is
                                     % added per one 4-tuple.
width                           = 0;
if opt.verbose, fprintf(1, ')'); end

tenth = .1;  % because of the first %
result.used = 0; result.failed = 0;
for i = 1:num_trials
  % choose a 4/max-tuple
  cols = 1:n;
  rows = 1:m;

  cols_chosen = []; t=1; failed = 0;
  if central,
    scaled_ensured = 0;
  else
    scaled_ensured = 1;   % trial version: no scale controling when cutting
  end
  for t = 1:4
    % choose one column, cut useless parts etc.
    [c, cols] = random_element(cols);
    cols_chosen = [cols_chosen c];

    % check just added column
    rows = intersect(rows, find(I(:,c) > 0));

    if t < 4,
      [rows, cols, scaled_ensured] = cut_useless(I, cols_scaled, ...
                                cols_chosen, rows, cols, 4-t, scaled_ensured);
    end

    if isempty(rows), failed = 1; break; end
  end

  if ~failed
    % use the 4/max-tuple
    d = depths(rows,cols_chosen);
    % see ``debug code'' in the comment lower

    rowsbig   = k2i(rows);
    submatrix=[]; for j=1:length(cols_chosen) % 4,
      submatrix=[ submatrix ...
                  spread_depths_col(M(rowsbig,cols_chosen(j)), d(:,j)) ]; end
    debug=1; if debug, if size(submatrix, 1)<=size(submatrix,2) && opt.verbose
        fprintf(1,'-'); end;end
    subnull = nulleps(submatrix,opt.threshold); %svd(submatrix)
    if size(subnull,2)>0  &&  ( use_maxtuples || ...
       size(submatrix,1) == size(submatrix,2) + size(subnull,2))
      nulltemp            = zeros(size(M,1),size(subnull,2));
      nulltemp(rowsbig,:) = subnull; % * (length(rows)/m); % weighting
      if width+size(nulltemp,2) > size(nullspace,2) % Memory allocation:
        if opt.verbose, fprintf(1,'(Allocating memory...)'); end
        mean_added = width/i;
        nullspace(size(M,1), size(nullspace,2) ...
                  + round(mean_added * (num_trials-i))) = 0;
      end
      nullspace(:, width+1 : width+size(nulltemp,2)) = nulltemp;
      width                                          = width +size(nulltemp,2);
      result.used         = result.used +1;
      if mod(result.used, show_mod)==0 && opt.verbose, fprintf(1,'.'); end
    end
  else
    result.failed = result.failed +1;
  end

  if i/num_trials > .1*tenth
    if opt.verbose, fprintf(1,'%d%%', tenth*10); end
    if tenth < 1, tenth=0; end
    tenth = tenth + 1;
  end
end

if size(nullspace,2) > width,   % cut off unused allocated memory
  if opt.verbose, fprintf(1,'(Cutting unused memory...'); end
  nullspace = nullspace(:,1:width);
  if opt.verbose, fprintf(1, ')'); end
end
if opt.verbose, fprintf(1, ['(' num2str(toc) ' sec)\n']); end
result.tried = i;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% debug code
%    if size(d, 1) == 1, bla; end
%    if sum(d(1,:)==0) > 2, blabla; end
%    if use_maxtuples | ...
%          size(d,1)*3 > size(d,2) + sum(d(:)==0)... % i.e. size(submatrix,1)>
%          ...                                       % size(submatrix,2)
%          - sum(cols_scaled(cols_chosen)==0) % i.e. subtract 1 per each
%                                             % column full of zeros
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [rows, cols, scaled_ensured] = cut_useless( ... %)
    I, cols_scaled, ... % this is always same
    cols_chosen, rows, cols, demanded, scaled_ensured)

if ~scaled_ensured
  % check scaled columns
  if length(rows) == 2, demanded_scaled = 3; demanded_rows = 2;
  else                  demanded_scaled = 2; demanded_rows = 3; end
    cols_scaled_chosen = sum(cols_scaled(cols_chosen) > 0);

  % if no unscaled are allowed, they must be all cut
  if demanded == demanded_scaled - cols_scaled_chosen,
    cols           = intersect(cols, find(cols_scaled > 0));
    scaled_ensured = 1;
  end
else demanded_rows = 2; end

% check columns
cols = cols(find(sum(I(rows,cols)) >= demanded_rows));

% check rows
rows = rows(find(sum(I(rows,cols)') >= demanded));

function [element, rest] = random_element(set)
% Take a random element out of a set.
element = set(random_int(1, length(set)));
rest    = setdiff(set, element);

function y = random_int(from,to)
y = floor(from + (1 + to - from)*rand);

function [N,s] = nulleps(M,tol)
% Find the nullspace of M.  This is the regular nullspace, augmented by
% vectors that aren't really in the nullspace, but have low singular
% values associated with them.  tol is the threshold on these singular values.
[u,s,v] = svd(M);
sigsvs = sum(diag(s)>tol);
N = u(:,sigsvs+1:size(u,2));


%RESIZE  Resizes an image
%
%     dst = cv.resize(src, dsize)
%     dst = cv.resize(src, fx, fy)
%     dst = cv.resize(..., 'OptionName',optionValue, ...)
%
% ## Input
% * __src__ input image.
% * __dsize__ output image size `[w,h]`.
% * __fx__ Scale factors along the horizontal axis.
% * __fy__ Scale factors along the vertical axis.
%
% When scale factors are specified, the output image size is computed as:
% `dsize = round([fx*size(src,2), fy*size(src,1)])`.
%
% ## Output
% * __dst__ output image. It has the size `dsize` or the size computed from
%   `size(src)` and `fx` and `fy`. The type of `dst` is the same as of `src`.
%
% ## Options
% * __Interpolation__ interpolation method, default 'Linear'. One of:
%   * __Nearest__ a nearest-neighbor interpolation
%   * __Linear__ a bilinear interpolation (used by default)
%   * __Cubic__ a bicubic interpolation over 4x4 pixel neighborhood
%   * __Area__ resampling using pixel area relation. It may be a preferred
%     method for image decimation, as it gives moire-free results. But when
%     the image is zoomed, it is similar to the 'Nearest' method.
%   * __Lanczos4__ a Lanczos interpolation over 8x8 pixel neighborhood
%   * __LinearExact__ a bit exact bilinear interpolation
%
% The function cv.resize resizes the image `src` down to or up to the
% specified size. The size and type of `dst` are derived from `src`, `dsize`,
% `fx` and `fy`. If you want to resize `src` so that it fits a specified size,
% you may call the function as follows:
%
%     dst = cv.resize(src, [w,h], 'Interpolation',interp)
%
% If you want to decimate the image by factor of 2 in each direction, you can
% call the function this way:
%
%     dst = cv.resize(src, 0.5, 0.5, 'Interpolation',interp)
%
% To shrink an image, it will generally look best with 'Area' interpolation,
% whereas to enlarge an image, it will generally look best with 'Cubic' (slow)
% or 'Linear' (faster but still looks OK).
%
% See also: cv.warpAffine, cv.warpPerspective, cv.remap, imresize
%


% Test file for chebtech/feval.m

function pass = test_feval(pref)

% Get preferences.
if ( nargin < 1 )
    pref = chebtech.techPref();
end

% Generate a few random points to use as test values.
seedRNG(7681);
x = 2 * rand(1000, 1) - 1;

for n = 1:2
    if ( n == 1 )
        testclass = chebtech1();
    else
        testclass = chebtech2();
    end

    %%
    % Spot-check values for a couple of functions.  We can only expect
    % accuracy on % the order of the truncation level, so we use this as our
    % criterion.

    f = testclass.make(@(x) exp(x) - 1, [], pref);
    f_exact = @(x) exp(x) - 1;
    pass(n, 1) = (norm(feval(f, x) - f_exact(x), inf) < ...
        10*vscale(f)*eps);

    f = testclass.make(@(x) 1./(1 + x.^2), [], pref);
    f_exact = @(x) 1./(1 + x.^2);
    pass(n, 2) = (norm(feval(f, x) - f_exact(x), inf) < ...
        10*vscale(f)*eps);

    f = testclass.make(@(x) cos(1e4*x), [], pref);
    f_exact = @(x) cos(1e4*x);
    pass(n, 3) = (norm(feval(f, x) - f_exact(x), inf) < ...
        2e4*vscale(f)*eps);

    z = exp(2*pi*1i/6);
    f = testclass.make(@(t) sinh(t*z), [], pref);
    f_exact = @(t) sinh(t*z);
    pass(n, 4) = (norm(feval(f, x) - f_exact(x), inf) < ...
        10*vscale(f)*eps);

    %%
    % Check row vector and matrix input.

    err = feval(f, x.') - f_exact(x.');
    pass(n, 5) = (all(size(err) == [1 1000])) && (norm(err(:), inf) < ...
        10*vscale(f)*eps);

    x_mtx = reshape(x, [100 10]);
    err = feval(f, x_mtx) - f_exact(x_mtx);
    pass(n, 6) = (all(size(err) == [100 10])) && (norm(err(:), inf) < ...
        10*vscale(f)*eps);

    x_3mtx = reshape(x, [10 10 10]);
    err = feval(f, x_3mtx) - f_exact(x_3mtx);
    pass(n, 7) = (all(size(err) == [10 10 10])) && (norm(err(:), inf) < ...
        10*vscale(f)*eps);

    %%
    % Check operation for array-valued chebtech objects.

    f = testclass.make(@(x) [sin(x) x.^2 exp(1i*x)], [], pref);
    f_exact = @(x) [sin(x) x.^2 exp(1i*x)];
    err = feval(f, x) - f_exact(x);
    pass(n, 8) = all(max(abs(err)) < 10*max(vscale(f)*eps));

    %%
    % Test for evaluating array-valued chebtech objects at matrix arguments if
    % the operation makes sense.
    f = testclass.make(@(x) [sin(pi*x) cos(pi*x) exp(pi*x)], [], pref);
    x2 = [-1 0 1 ; .25 .5 .75];
    fx = feval(f, x2);
    f_exact = [0 0 0 -1 1 -1 exp(-pi) 1 exp(pi)
              [1 sqrt(2) 1 1 0 -1]/sqrt(2) exp(pi.*[.25 .5 .75])];
    pass(n, 9) = all(all(abs(fx - f_exact) < 10*max(vscale(f)*eps)));
end

end


function SetColorbar
cbar = colorbar;
% Dimensions of the colorbar
% cpos = get(cbar,'position');
% cpos(3) = cpos(3)/4 ;   % Reduce the width of colorbar by half
% cpos(2) = cpos(2)+.1 ;
% cpos(4) = cpos(4)-.2 ;
%set(cbar,'Position',cpos) ;
brighten(0.5);

% Title of the colorbar
%set(get(cbar,'title'),'string','VAL');
%locate = get(cbar,'title');
%tpos = get(locate,'position');
%tpos(3) = tpos(3)+5. ;
%set(locate,'pos',tpos);

% Setting the values on colorbar
%
% get the color limits
clim = caxis;
ylim(cbar,[clim(1) clim(2)]);
numpts = 24 ;    % Number of points to be displayed on colorbar
kssv = linspace(clim(1),clim(2),numpts);
set(cbar,'YtickMode','manual','YTick',kssv); % Set the tickmode to manual
for i = 1:numpts
    imep = num2str(kssv(i),'%+3.2E');
    vasu(i) = {imep} ;
end
set(cbar,'YTickLabel',vasu(1:numpts),'fontsize',9);