close all;
clear all;
clc;

data_file_path = 'bin/mmv_phase_transition_snr_40db_s_4.mat';
options.export = true;
options.export_dir = 'bin';
options.export_name = 'mmv_snr_40_db_s_4';
options.chosen_ks = [2, 4, 8, 16, 32, 64];
options.subtitle = 'MMV, SNR=40dB s=4';
spx.pursuit.PhaseTransitionAnalysis.print_results(data_file_path, ...
    'CoSaMP', options);


Rotation_Data = get(logsout, 'Rotation_Data');
Translation_Data = get(logsout, 'Translation_Data');
INS_Out = get(logsout, 'INS_Out');

acc_meas_O = get(logsout, 'acc_meas_O_mPs2');
acc_est_O = get(logsout, 'acc_est_O_mPs2');

mag_enable = get(logsout, 'mag_enable');
acc_meas_valid = get(logsout, 'acc_meas_valid');

%% plot attitude data
phi_deg = INS_Out.Values.phi;
phi_deg.Data = single(phi_deg.Data)*2^-12*180/pi;
theta_deg = INS_Out.Values.theta;
theta_deg.Data = single(theta_deg.Data)*2^-12*180/pi;
psi_deg = INS_Out.Values.psi;
psi_deg.Data = single(psi_deg.Data)*2^-12*180/pi;

acc_O_meas_x = acc_meas_O.Values;
acc_O_meas_x.Data = acc_O_meas_x.Data(1,:);
acc_O_meas_y = acc_meas_O.Values;
acc_O_meas_y.Data = acc_O_meas_y.Data(2,:);
acc_O_meas_z = acc_meas_O.Values;
acc_O_meas_z.Data = acc_O_meas_z.Data(3,:);
acc_O_est_x = acc_est_O.Values;
acc_O_est_x.Data = acc_O_est_x.Data(1,:);
acc_O_est_y = acc_est_O.Values;
acc_O_est_y.Data = acc_O_est_y.Data(2,:);
acc_O_est_z = acc_est_O.Values;
acc_O_est_z.Data = acc_O_est_z.Data(3,:);

figure;
ax1 = subplot(3,2,1);
plot(phi_deg, 'Color', 'r');
hold on;
grid on;
legend('\phi')

ax2 = subplot(3,2,3);
plot(theta_deg, 'Color', 'r');
hold on;
grid on;
legend('\theta')

ax3 = subplot(3,2,5);
plot(psi_deg, 'Color', 'r');
hold on;
grid on;
colorAxes(ax3, findLogicalArea(mag_enable.Values.Time, mag_enable.Values.Data > 0), 'green');
colorAxes(ax3, findLogicalArea(acc_meas_valid.Values.Time, acc_meas_valid.Values.Data > 0), 'blue');
legend('\psi')

ax4 = subplot(3,2,2);
plot(acc_O_est_x, 'Color', 'r');
hold on;
plot(acc_O_meas_x, 'Color', 'b');
grid on;
legend('acc\_est\_x', 'acc\_meas\_x')

ax5 = subplot(3,2,4);
plot(acc_O_est_y, 'Color', 'r');
hold on;
plot(acc_O_meas_y, 'Color', 'b');
grid on;
legend('acc\_est\_y', 'acc\_meas\_y')

ax6 = subplot(3,2,6);
plot(acc_O_est_z, 'Color', 'r');
hold on;
plot(acc_O_meas_z, 'Color', 'b');
grid on;
legend('acc\_est\_z', 'acc\_meas\_z')

linkaxes([ax1,ax2,ax3,ax4,ax5,ax6], 'x');


function test_bug3461

% WALLTIME 00:20:00
% MEM 3gb
% DEPENDENCY ft_sourcestatistics ft_sourcegrandaverage

%%

% this contains allSourceDiff050
load(dccnpath('/home/common/matlab/fieldtrip/data/test/bug3461.mat'));

%% Grand average

cfg = [];
cfg.parameter = 'coh';
cfg.keepindividual = 'yes';
avgSourceDiff050 = ft_sourcegrandaverage(cfg, allSourceDiff050{:});

%% Make null condition

cfg = [];
cfg.parameter = 'coh';
cfg.operation = 'multiply';
cfg.scalar = 0;
avgSourceZero = ft_math(cfg, avgSourceDiff050);

%% Run statistics

cfg = [];
cfg.parameter   = 'coh';
cfg.method      = 'montecarlo';
cfg.statistic   = 'depsamplesT';
cfg.alpha       = 0.05;
cfg.tail        = 0;
cfg.correcttail = 'alpha';
cfg.correctm    = 'cluster';
cfg.numrandomization = 1000;

Nsub = 37;
cfg.design(1,1:2*Nsub)  = [ones(1,Nsub) 2*ones(1,Nsub)];
cfg.design(2,1:2*Nsub)  = [1:Nsub 1:Nsub];
cfg.ivar                = 1; % the 1st row in cfg.design contains the independent variable
cfg.uvar                = 2; % the 2nd row in cfg.design contains the subject number

tval_diff_050 = ft_sourcestatistics(cfg, avgSourceDiff050, avgSourceZero);


function y = scaleNoiseOut(noise, mu, varSigma)

% SCALENOISEOUT A simple noise model that scales and centres the data.

% NOISE

y = zeros(size(mu));
for i = 1:size(mu, 2)
  y(:, i) = noise.bias(i) + mu(:, i)*noise.scale(i);
end


% Test file for ADCHEBFUN times

function pass = test_power

% Initialise pass vector
pass = zeros(3, 5);

% Tolerance for Taylor testing
tolOrder = 1e-2;
tolDiff = 1e-14;

% The function handle we're working with:
func = @power;

% Compare values
[err, lin] = adchebfun.valueTestingBinary(func);

% Confirm that the error returned is zero
pass(1, :) = ( err < tolDiff );

% Taylor testing
[order1, order2] = adchebfun.taylorTestingBinary(func);

% We expect all elements of ORDER1 to be close to 1. Since the methods being
% tested in this all nonlinear, ORDER2 should have entries close to 2.

% Check whether we get the expected results for linear and nonlinear
% operations.
pass(2,:) = ( (max(abs(order1 - 1)) < tolOrder) & ...
              (max(abs(order2 - 2)) < tolOrder) );

% Linearity checking. All operations should be detected as nonlinear.
pass(3,:) = ( lin == 0 );
end


function [i, j] = toindex(x, y)
global F;

j = ceil(x);
i = size(F,1) - floor(y);


function[h]=patchcontourf(varargin)
%PATCHCONTOURF  Generate filled contours using patches, with specified colors.
%
%   Frequently one wishes to make a filled contour plot of one field over
%   another with two different colormap schemes.  This is not currently
%   possible with CONTOURF because Matlab uses one colormap per axes.
%
%   For example, one may wish to plot sea surface temperature filled in
%   color with the continents filled in black.
%
%   PATCHCONTOURS gets around this problem by geneating filled contours
%   plots as patch objects, with out reference to the current colormap.
%   Colors of filled contours may be specified explicitly.
%
%   PATCHCONTOURF(Z,V) makes a filled contour plot of field Z at value V.
%   The interiors of the contour are colored black by default.
%
%   PATCHCONTOURF(Z,V,C) alternately uses color C as both the fill color
%   and the edge color.  C may be either a string, as in 'g' for green,
%   or a color array of length 3, such as [1/2 1/2 1/2] for gray.
%
%   PATCHCONTOURF(X,Y,Z,V) and PATCHCONTOURF(X,Y,Z,V,C) use vectors X and Y
%   to specify the contour locations.  X has length SIZE(X,2) while Y has
%   length SIZE(X,1).
%
%   H=PATCHCONTOURF(...) returns a handle to the patch object.
%
%   PATCHCONTOURF(...,'m_map') alternately works with R. Pawlowicz's M_MAP
%   mapping package, available at http://www.eos.ubc.ca/~rich/map.html.
%
%   'patchcontourf --f' generates a sample figure.
%
%   Usage: patchcontourf(z,v);
%          patchcontourf(z,v,c);
%          patchcontourf(x,y,z,v,c);
%          h=patchcontourf(x,y,z,v,c);
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2015 J.M. Lilly --- type 'help jlab_license' for details

if strcmp(varargin{1}, '--f')
    type makefigs_patchcontourf
    makefigs_patchcontourf;
    return
end

%Sort out string input arguments
str='k';
flag='mat';
if isstr(varargin{end})
    if length(varargin{end})>=3
        if strcmpi(varargin{end}(1:3),'m_m')||strcmpi(varargin{end}(1:3),'mat')
            flag=varargin{end};
            varargin=varargin(1:end-1);
        end
    end
end

if isstr(varargin{end})||length(varargin{end})==3
    str=varargin{end};
    varargin=varargin(1:end-1);
end

v=varargin{end};
varargin=varargin(1:end-1);

if length(varargin)==3
    x=varargin{1};
    y=varargin{2};
    z=varargin{3};
else
    x=[];
    y=[];
    z=varargin{1};
end

z1=zeros(size(z,1)+2,size(z,2)+2)+minmin(z);
z1(2:end-1,2:end-1)=z;

[ii,jj]=closedcurves(z1,v);

bool=ishold;
hold on

h=[];
if isempty(x)
    for i=1:length(ii)
        if strcmpi(flag(1:3),'m_m')
            m_patch(ii{i},jj{i},str,'edgecolor',str);
        else
            patch(ii{i},jj{i},str,'edgecolor',str);
        end
    end
else
    dx1=x(2)-x(1);
    dxN=x(end-1)-x(end);
    x=[x(1)-dx1;x(:);x(end)-dxN];

    dy1=y(2)-y(1);
    dyN=y(end-1)-y(end);
    y=[y(1)-dy1;y;y(end)-dyN];

    for i=1:length(ii)
        x1=interp1(1:length(x),x,ii{i},'linear');
        y1=interp1(1:length(y),y,jj{i},'linear');
        if strcmpi(flag(1:3),'m_m')
            %The FLIPUDs keep M_PATCH from inverting the patch
            h=m_patch(flipud(x1),flipud(y1),str,'edgecolor',str);
        else
            h=patch(x1,y1,str,'edgecolor',str);
        end
    end
end

if ~ishold
    hold off
end


function [X,Y,Z]=contourRegularise(varargin)

switch nargin
    case 2
        Vcs=varargin{1};
        np=varargin{2};
        interpMethod='pchip'; %Default method
    case 3
        Vcs=varargin{1};
        np=varargin{2};
        interpMethod=varargin{3};
    otherwise
        error('Wrong number of input arguments');
end

%%
numContours=numel(Vcs);

%Allocate coordinate matrices
X=nan(numContours,np); Y=nan(numContours,np); Z=nan(numContours,np);
startDefined=0;
for q=1:1:numContours

    %Join goups if present N.B. assumes they belong to the same curve!
    Vs=[];
    for qGroup=1:1:numel(Vcs{q})
        Vss=Vcs{q}{qGroup};
        if ~isempty(Vss)
            if isPolyClockwise(Vss)
                Vss=flipud(Vss);
            end
            Vs=[Vs; Vss];
        end
    end

    %Resample curve so they have the same number of points
    if ~isempty(Vs)
        numDigitsMerge=6-numOrder(mean(sum(diff(Vs,[],1).^2,2)));
        [~,ind1,~]=unique(pround(Vs,numDigitsMerge),'rows');

        Vs=Vs(ismember(1:size(Vs,1),ind1),:); %This maintains point order

        [Vs]=evenlySampleCurve(Vs,np,interpMethod,1);

        if startDefined==0 %After 1 contour has been added
            V_start=Vs(1,:);
            startDefined=1;
        else
            %Reorder curves so start and end points match closely
            D=sqrt(sum((Vs-V_start(ones(1,size(Vs,1),1),:)).^2,2));
            [~,indMin]=min(D);
            if indMin~=1
                Vs=[Vs(indMin:size(Vs,1),:); Vs(1:indMin-1,:)];
            end
            V_start=Vs(1,:);
        end

        %Store coordinates
        [X(q,:),Y(q,:),Z(q,:)]=getColumns(Vs);
    end
end

%%
%Remove twist
for q=2:1:size(numContours,1)
    v1=[X(q-1,:)' Y(q-1,:)' Z(q-1,:)'];
    v2=[X(q,:)' Y(q,:)' Z(q,:)'];
    [v2f,~,~]=minPolyTwist(v1,v2);
    X(q,:)=v2f(:,1);
    Y(q,:)=v2f(:,2);
    Z(q,:)=v2f(:,3);
end

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


%                                                     [lab,q,f] = eigK(x,K)
%
% EIGK  Computes the spectral values ("eigenvalues") or even the complete
%       spectral decomposition  of a vector x with respect to a self-dual
%       homogeneous cone K.
%
% > LAB = EIGK(x,K) This yield the spectral values of x with respect to
%       the self-dual homogeneous cone that you describe in the structure
%       K. Up to 3 fields can be used, called K.l, K.q and K.s, for
%       Linear, Quadratic and Semi-definite. Type `help sedumi' for more
%       details on this structure.
%
%       The length of the vector LAB is the order of the cone. Remark that
%       x in K if and only if LAB>=0, and x in int(K) if and only if LAB>0.
%
% > [LAB,Q,F] = EIGK(x,K) Also produces the eigenvectors for the symmetric and
%       Hermitian parts of x (corresponding to K.s), and the Lorentz frame F
%       for the Lorentz blocks in x (corresponding to K.q). This extended
%       version of EIGK is intended for INTERNAL USE BY SEDUMI.
%
% See also sedumi, mat, vec, eyeK.

function [lab,q,f] = eigK(x,K) %#ok

% THE M-FILE VERSION OF THIS FUNCTION IS HERE ONLY AS ILLUSTRATION.
% SEE THE C-SOURCE FOR THE MEX-VERSION.

%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
%   Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
%   CRL, McMaster University, Canada.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc.,  51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%

disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ')

lab = zeros(K.l + 2*length(K.q) + sum(K.s),1); %#ok
% ----------------------------------------
% LP: lab = x
% ----------------------------------------
lab(1:K.l) = x(1:K.l);
firstk = K.l+1;
nextlab = K.l+1;
% ----------------------------------------
% LORENTZ: (lab, f) = qeig(x)
% ----------------------------------------
if nargout < 3
    for k=1:length(K.q)
        nk = K.q(k); lastk = firstk + nk - 1;
        lab(nextlab:nextlab+1) = qeig(x(firstk:lastk));
        firstk = lastk + 1; nextlab = nextlab + 2;
    end
else
    nextf = 1;
    for k=1:length(K.q)
        nk = K.q(k); lastk = firstk + nk - 1;
        [labk, fk] = qeig(x(firstk:lastk));
        lab(nextlab:nextlab+1) = labk;
        f(nextf:nextf+nk-2) = fk;
        firstk = lastk + 1; nextlab = nextlab + 2; nextf = nextf + nk-1;
    end
end
% ----------------------------------------
% SDP: [q,lab] = eig(x)
% ----------------------------------------
offq = firstk - 1;
q = zeros(length(x)-offq,1);
for k = 1:K.rsdpN
    nk = K.s(k); lastk = firstk + nk*nk - 1;
    Xk = mat(x(firstk:lastk),nk);
    Xk = (Xk + Xk') / 2;
    [Qk, Labk] = eig(Xk);
    lab(nextlab:nextlab+nk-1) = diag(Labk);
    q(firstk-offq:lastk-offq) = Qk;
    firstk = lastk + 1; nextlab = nextlab + nk;
end
for k = (1+K.rsdpN):length(K.s)
    nk = K.s(k); ifirstk = firstk + nk*nk; lastk = ifirstk + nk*nk - 1;
    Xk = mat(x(firstk:ifirstk-1)+sqrt(-1)*x(ifirstk:lastk),nk);
    [Qk, Labk] = eig(Xk);
    lab(nextlab:nextlab+nk-1) = real(diag(Labk));
    q(firstk-offq:ifirstk-1-offq) = real(Qk);
    q(ifirstk-offq:lastk-offq) = imag(Qk);
    firstk = lastk + 1; nextlab = nextlab + nk;
end


%% Neural Art with lbfgs optimization
%% It cannot run on my laptop T^T. The error seems to be memory out.
caffe.reset_all();
caffe.set_mode_gpu();
gpu_id = 1;  % we will use the first gpu in this demo
caffe.set_device(gpu_id);

% original_file = 'D:\deepLearning\caffe-windows\matlab\demo\Inceptionism\googlenet_neuralart.prototxt';
% net_weights = 'D:\deeplearning\caffe-windows\examples\GoogLeNet\imagenet_googlenet.caffemodel';
% style_layer = {'icp2_in','icp3_out','icp5_out','icp7_out','icp9_out'};
original_file = 'D:\deepLearning\caffe-windows\matlab\demo\NeuralArt\VGG_16_nueralart.prototxt';
net_weights = 'D:\deepLearning\caffe-windows\matlab\demo\NeuralArt\VGG16_thinned_net.caffemodel';
style_layer = {'conv1_1','conv2_1','conv3_1','conv4_1','conv5_1'};
content_layer = {'conv4_2'};

style_weights = [1 1 1 1 1 0.05];
tv_norm = 0.001;
use_color_prior = false;
num_cluster=6;
color_prior = 0.5;
long_size = 512;

style_image = imread('d:\starry_night.jpg');
if size(style_image,1) > size(style_image,2)
    style_image = imresize(style_image,[long_size, size(style_image,2) / size(style_image,1) * long_size]);
else
    style_image = imresize(style_image,[size(style_image,1) / size(style_image,2) * long_size, long_size]);
end;
content_image = imread('d:\hoovertowernight.jpg');
if size(content_image,1) > size(content_image,2)
    content_image = imresize(content_image,[long_size, size(content_image,2) / size(content_image,1) * long_size]);
else
    content_image = imresize(content_image,[size(content_image,1) / size(content_image,2) * long_size, long_size]);
end;
figure(1);
imshow(style_image);
title('style image');
figure(2);
imshow(content_image);
title('content image');
[style_generate_prototxt, style_pattern, content_pattern,colorObj] = MakeStylePrototxt(original_file, net_weights, style_layer, style_weights, content_layer, style_image, content_image,num_cluster);
if use_color_prior
colorObj
num_cluster = colorObj.NComponents;
end;
if use_color_prior
    gaussian_net = caffe.Net('gaussian_net.prototxt','test');

    W = single(zeros(1,1,3,3*num_cluster));
    b = single(zeros(3*num_cluster,1));

    for i=1:num_cluster
        W(:,:,:,(i-1)*3+1:i*3) = inv(colorObj.Sigma(:,:,i));
        b((i-1)*3+1:i*3) = -1 * colorObj.Sigma(:,:,i) \ colorObj.mu(i,:)';
    end;

    nth_layer = gaussian_net.layer_vec(gaussian_net.name2layer_index('gaussian_prior'));
    nth_layer.params(1).set_data(W);
    nth_layer.params(2).set_data(b);
end;

forward_input = cell(length(style_pattern)+2,1);
forward_input(3:end) = style_pattern;
forward_input(2) = {content_pattern};

mean_file = [];
vgg_mean =  [103.939, 116.779, 123.68];
[height, width, channel] = size(content_image);

%%%%%%%%%extract the train features
stylegen_net = caffe.Net(style_generate_prototxt,net_weights,'test');
mean_image = permute(repmat(vgg_mean',[1,size(content_image,2),size(content_image,1)]),[2,3,1]);
input_data = randn(size(mean_image,1), size(mean_image,2), 3, 1, 'single')*50;

lr = 10;
max_lr = 50;
momentum = 0.8;
lastgrad = zeros(size(mean_image));
last_cost = 9999999999999;

for iter = 1:2000
    bak_data = input_data;
    bak_grad = lastgrad;
    [cost, grad] = NeuralArtCost(input_data,[],stylegen_net,forward_input,style_weights);

    if tv_norm > 0
        I = input_data(:,:,:,1);
        Gx = (I(2:end-1,:,:) - I(1:end-2,:,:)) - (I(3:end,:,:) - I(2:end-1,:,:));
        Gx = [(I(1,:,:) - I(2,:,:)); Gx; (I(end,:,:) - I(end-1,:,:))];
        Gy = (I(:,2:end-1,:) - I(:,1:end-2,:)) - (I(:,3:end,:) - I(:,2:end-1,:));
        Gy = [(I(:,1,:) - I(:,2,:)) Gy (I(:,end,:) - I(:,end-1,:))];
        grad = grad + tv_norm * (Gx+Gy);
    end;

    if use_color_prior
        gmm_prior = gaussian_net.forward({input_data});
        sum_gp = zeros(size(mean_image,1),size(mean_image,2));
        sum_prob_gradient = zeros(size(mean_image));
        for i=1:num_cluster
            gp = bsxfun(@minus,input_data(:,:,:,1),reshape(colorObj.mu(i,:),[1 1 3])) .* gmm_prior{1}(:,:,(i-1)*3+1:i*3);
            gp = sum(gp,3);
            gp = colorObj.PComponents(i) * exp(-gp);
            sum_prob_gradient = sum_prob_gradient + bsxfun(@times,gp,gmm_prior{1}(:,:,(i-1)*3+1:i*3));
            sum_gp = sum_gp + gp;
        end;
        sum_prob_gradient = bsxfun(@rdivide,sum_prob_gradient,sum_gp);
        sum_prob_gradient(isnan(sum_prob_gradient)) = 0;
        input_data(:,:,:,1) = input_data(:,:,:,1) - lr * color_prior * sum_prob_gradient;
    end;
    %%%%%%%%%%%%%%%%%%%%%%%%gd linear search
    lastgrad = (1 - momentum) * lr * grad   + momentum * lastgrad;%/ norm(res(:))
    input_data(:,:,:,1) = input_data(:,:,:,1) - lastgrad;
    if cost>last_cost
        lr = lr * 0.9;
%         input_data = bak_data;%why...
%         last_grad = bak_grad;
    end;
    if cost<last_cost&&lr<max_lr%&& (this_prob-last_prob) / this_prob < 0.001
        lr = lr * 1.1;
    end;
    if cost<last_cost
        last_cost = cost;
    end;
    fprintf('iter=%d,lr=%f,this_cost=%f,last_cost=%f\n',iter,lr,cost, last_cost);
    %%%%%%%%%%%%%%%%%%%%%%gd

    if mod(iter,10)==0
        figure(3);
        output = mean_image + input_data(:,:,:,1);
        output = output(:, :, [3, 2, 1]);
        output = permute(output, [2 1 3]);
        imshow(uint8(output));
        I = output;
        title('generated image');
    end;
end;


function DoFSERecon(Simuh)

global VSig;
global VCtl;
global VObj;
global VCoi;
global VImg;

SX=reshape(VSig.Sx,VCtl.ResFreq * VCtl.FSE_ETL,VCtl.FSE_ShotNum,VCtl.SliceNum,VCoi.RxCoilNum,VObj.TypeNum); % matlab col priority
SY=reshape(VSig.Sy,VCtl.ResFreq * VCtl.FSE_ETL,VCtl.FSE_ShotNum,VCtl.SliceNum,VCoi.RxCoilNum,VObj.TypeNum);

SX=sum(SX, 5); % sum signal from all spin types
SY=sum(SY, 5);
%% FSE k-space recon
% sort k-space & row flipping
Sx=zeros(VCtl.ResFreq,VCtl.FSE_ETL*VCtl.FSE_ShotNum,VCtl.SliceNum,VCoi.RxCoilNum);
Sy=zeros(VCtl.ResFreq,VCtl.FSE_ETL*VCtl.FSE_ShotNum,VCtl.SliceNum,VCoi.RxCoilNum);
for e = 1: VCtl.FSE_ETL
    Sx(:,(e-1)*VCtl.FSE_ShotNum+1: e*VCtl.FSE_ShotNum, :,:) = reshape(SX((e-1)*VCtl.ResFreq+1: e*VCtl.ResFreq, :,:,:), [VCtl.ResFreq ,VCtl.FSE_ShotNum ,VCtl.SliceNum,VCoi.RxCoilNum]);
    Sy(:,(e-1)*VCtl.FSE_ShotNum+1: e*VCtl.FSE_ShotNum, :,:) = reshape(SY((e-1)*VCtl.ResFreq+1: e*VCtl.ResFreq, :,:,:), [VCtl.ResFreq ,VCtl.FSE_ShotNum ,VCtl.SliceNum,VCoi.RxCoilNum]);
end

% default -KxMax -> KxMax, -KyMax -> KyMax
% remove the most positive Kx point for making even number of Kx sample points (used for Matlab default fft)
Sx(end,:,:,:)=[];
Sy(end,:,:,:)=[];
ResFreq = VCtl.ResFreq - 1;

if isfield(VCtl,'ZF_Kx') % Zero Filling of k-space for increasing matrix size, no increae of resolution
    Sx2=zeros(str2double(VCtl.ZF_Kx),str2double(VCtl.ZF_Ky),str2double(VCtl.ZF_Kz(2:end))*VCtl.SliceNum,VCoi.RxCoilNum);
    Sy2=zeros(str2double(VCtl.ZF_Kx),str2double(VCtl.ZF_Ky),str2double(VCtl.ZF_Kz(2:end))*VCtl.SliceNum,VCoi.RxCoilNum);
    for i = 1:VCoi.RxCoilNum
        Sx2(str2double(VCtl.ZF_Kx)/2-ResFreq/2+1:str2double(VCtl.ZF_Kx)/2-ResFreq/2+1+ResFreq-1, ...
            str2double(VCtl.ZF_Ky)/2-(VCtl.FSE_ETL*VCtl.FSE_ShotNum)/2+1:str2double(VCtl.ZF_Ky)/2-(VCtl.FSE_ETL*VCtl.FSE_ShotNum)/2+1+(VCtl.FSE_ETL*VCtl.FSE_ShotNum)-1, ...
            str2double(VCtl.ZF_Kz(2:end))*floor(VCtl.SliceNum/2)-floor(VCtl.SliceNum/2)+1:str2double(VCtl.ZF_Kz(2:end))*floor(VCtl.SliceNum/2)-floor(VCtl.SliceNum/2)+1+VCtl.SliceNum-1,i)=Sx(:,:,:,i);
        Sy2(str2double(VCtl.ZF_Kx)/2-ResFreq/2+1:str2double(VCtl.ZF_Kx)/2-ResFreq/2+1+ResFreq-1, ...
            str2double(VCtl.ZF_Ky)/2-(VCtl.FSE_ETL*VCtl.FSE_ShotNum)/2+1:str2double(VCtl.ZF_Ky)/2-(VCtl.FSE_ETL*VCtl.FSE_ShotNum)/2+1+(VCtl.FSE_ETL*VCtl.FSE_ShotNum)-1, ...
            str2double(VCtl.ZF_Kz(2:end))*floor(VCtl.SliceNum/2)-floor(VCtl.SliceNum/2)+1:str2double(VCtl.ZF_Kz(2:end))*floor(VCtl.SliceNum/2)-floor(VCtl.SliceNum/2)+1+VCtl.SliceNum-1,i)=Sy(:,:,:,i);
    end
    Sx=Sx2;
    Sy=Sy2;
    clear Sx2 Sy2;
end
Sx=permute(Sx,[2 1 3 4]);
Sy=permute(Sy,[2 1 3 4]);

% match XYZ orientation
switch VCtl.ScanPlane
    case 'Axial'
        if  strcmp(VCtl.FreqDir,'A/P')
            Sx=permute(Sx,[2 1 3 4]);
            Sy=permute(Sy,[2 1 3 4]);
        else
            Sx=permute(Sx,[1 2 3 4]);
            Sy=permute(Sy,[1 2 3 4]);
        end
    case 'Sagittal'
        if  strcmp(VCtl.FreqDir,'S/I')
            Sx=permute(Sx,[2 1 3 4]);
            Sy=permute(Sy,[2 1 3 4]);
        else
            Sx=permute(Sx,[1 2 3 4]);
            Sy=permute(Sy,[1 2 3 4]);
        end
    case 'Coronal'
        if  strcmp(VCtl.FreqDir,'L/R')
            Sx=permute(Sx,[1 2 3 4]);
            Sy=permute(Sy,[1 2 3 4]);
        else
            Sx=permute(Sx,[2 1 3 4]);
            Sy=permute(Sy,[2 1 3 4]);
        end
end

S=Sx+1i*Sy;
for i = 1: VCoi.RxCoilNum
    VImg.Real(:,:,:,i)=real(fftshift(ifftn(fftshift(S(:,:,:,i)))));
    VImg.Imag(:,:,:,i)=imag(fftshift(ifftn(fftshift(S(:,:,:,i)))));
    VImg.Mag(:,:,:,i)=abs(VImg.Real(:,:,:,i)+1i*VImg.Imag(:,:,:,i));
    VImg.Phase(:,:,:,i)=angle(VImg.Real(:,:,:,i)+1i*VImg.Imag(:,:,:,i));
end
VImg.Sx(:,:,:,:)=Sx;
VImg.Sy(:,:,:,:)=Sy;

guidata(Simuh.SimuPanel_figure, Simuh);

end


function sVF1 = plus(sVF1, sVF2)
%
% Syntax
%   sVF = sVF1 + sVF2
%   sVF = sVF + v
%
% Input
%  sVF1 - @S2VectorFieldTri
%  sVF2 - @S2VectorField
%  v    - @vector3d
%
% Output
%  sF - @S2FunTri
%

% first should be S2VectorFieldTri
if ~isa(sVF1,'S2VectorFieldTri'), [sVF1,sVF2] = deal(sVF2,sVF1); end

if isa(sVF2,'vector3d')
  sVF1.values = sVF1.values +  a;
elseif isa(sVF2,'S2VectorFieldTri')
  sVF1.values = sVF1.values + sVF2.values;
else
  sVF1.values = sVF1.values + sVF2.eval(SVF.vertices);
end

end


function clqs = compute_minimal_interface(intra, inter)

int = compute_fwd_interface(intra, inter);
ss  = length(intra);
Z = zeros(ss);
dag = [intra inter;
       Z     intra];
G = moralize(dag);
intra2 = G(1:ss,1:ss);
inter2 = G(1:ss,(1:ss)+ss);
G = unroll_dbn_topology(intra2, inter2, ss);
T = ss;
last_slice = (1:ss) + (T-1)*ss;
G = (G + G')/2; % mk symmetric
G2 = (expm(full(G)) > 0); % closure of graph
G3 = G2(last_slice, last_slice);
[c,v] = scc(G3); % connected components
ncomp = size(v,1);
clqs = cell(1,ncomp);
for i=1:ncomp
  ndx = find(v(i,:)>0);
  clqs{i} = v(i,ndx);
  clqs{i} = myintersect(clqs{i}, int);
end


function net = compact(net)

% COMPACT
%
% Remove duplicate support vectors, adjusting Lagrange multipliers of
% remaining support vectors to compensate.
%
% net = compact(net);

%
% File        : @svc/compact.m
%
% Date        : Tuesday 12th September 2000
%
% Author      : Dr Gavin C. Cawley
%
% Description : Remove duplicate support vectors, adjusting Lagrange
%               multipliers of remaining support vectors to compensate.
%               Part of an object-oriented implementation of Vapnik's Support
%               Vector Machine, as described in [1].
%
% References  : [1] V.N. Vapnik,
%                   "The Nature of Statistical Learning Theory",
%                   Springer-Verlag, New York, ISBN 0-387-94559-8,
%                   1995.
%
% History     : 07/07/2000 - v1.00
%               12/09/2000 - v1.01 minor improvements to comments and help
%                                  messages
%               13/09/2000 - v1.10 zeta (pattern replication factors) and C
%                                  fields removed from svc objects
%
% Copyright   : (c) Dr Gavin C. Cawley, September 2000
%
%    This program is free software; you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation; either version 2 of the License, or
%    (at your option) any later version.
%
%    This program is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this program; if not, write to the Free Software
%    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%

[sv, i, j] = unique(net.sv, 'rows');

w = zeros(1, length(i));

for i=1:length(j)

   w(j(i)) = w(j(i)) + net.w(i);

end

net.sv   = sv;
net.w    = w;

% bye bye...


function a = i4vec_permute ( n, a, p )

%*****************************************************************************80
%
%% I4VEC_PERMUTE permutes an I4VEC in place.
%
%  Discussion:
%
%    This routine permutes an array of integer "objects", but the same
%    logic can be used to permute an array of objects of any arithmetic
%    type, or an array of objects of any complexity.  The only temporary
%    storage required is enough to store a single object.  The number
%    of data movements made is N + the number of cycles of order 2 or more,
%    which is never more than N + N/2.
%
%  Example:
%
%    Input:
%
%      N = 5
%      P = (   2,   4,   5,   1,   3 )
%      A = (   1,   2,   3,   4,   5 )
%
%    Output:
%
%      A    = (   2,   4,   5,   1,   3 ).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of objects.
%
%    Input, integer A(N), the array to be permuted.
%
%    Input, integer P(N), the permutation.  P(I) = J means
%    that the I-th element of the output array should be the J-th
%    element of the input array.  Pmust be a legal permutation
%    of the integers from 1 to N, otherwise the algorithm will
%    fail catastrophically.
%
%    Output, integer A(N), the permuted array.
%
  base = 1;

  missing = perm_check ( n, p, base );

  if ( missing ~= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4VEC_PERMUTE - Fatal error!\n' );
    fprintf ( 1, '  The input array does not represent\n' );
    fprintf ( 1, '  a proper permutation.  In particular, the\n' );
    fprintf ( 1, '  array is missing the value %d\n', missing );
    error ( 'I4VEC_PERMUTE - Fatal error!' );
  end
%
%  Search for the next element of the permutation that has not been used.
%
  for istart = 1 : n

    if ( p(istart) < 0 )

      continue;

    elseif ( p(istart) == istart )

      p(istart) = -p(istart);
      continue;

    else

      a_temp = a(istart);
      iget = istart;
%
%  Copy the new value into the vacated entry.
%
      while ( 1 )

        iput = iget;
        iget = p(iget);

        p(iput) = -p(iput);

        if ( iget < 1 | n < iget )
          fprintf ( 1, '\n' );
          fprintf ( 1, 'I4VEC_PERMUTE - Fatal error!\n' );
          fprintf ( 1, '  A permutation index is out of range.\n' );
          fprintf ( 1, '  P(%d) = %d\n', iput, iget );
          error ( 'I4VEC_PERMUTE - Fatal error!' );
        end

        if ( iget == istart )
          a(iput) = a_temp;
          break;
        end

        a(iput) = a(iget);

      end

    end

  end
%
%  Restore the signs of the entries.
%
% p(1:n) = -p(1:n);

  return
end


function neq = sys_init(params)

global N problem

% Here is a list of the different system information paramters.
% neq = 1  : number of state variables.
% neq = 2  : number of inputs.
% neq = 3  : number of parameters.
% neq = 4  : reserved.
% neq = 5  : reserved.
% neq = 6  : number of objective functions.
% neq = 7  : number of nonlinear trajectory constraints.
% neq = 8  : number of linear trajectory constraints.
% neq = 9  : number of nonlinear endpoint inequality constraints.
% neq = 10 : number of linear endpoint inequality constraints.
% neq = 11 : number of nonlinear endpoint equality constraints.
% neq = 12 : number of linear endpoint equality constraints.
% neq = 13 : 0 => nonlinear, 1 => linear, 2 => LTI, 3 => LQR, 4 => LQR and LTI.

% The default value is 0 for all except neq = 6 which defaults to 1.

% if params == [] then setup neq.  Otherwise the system parameters are
% getting passed.

if isempty(params),
    if problem == 1
        %LTI
        neq = [1, 2*N+1; 2, 1; 3, 4];
    elseif problem == 2
        %LTV
        neq = [1, 2*N+1; 2, 1; 3, 4];
    elseif problem == 3
        %Bang-bang
        neq = [1, 2*N+3; 2, 1; 3, 4; 12 2];
    end
else
    global sys_params
    sys_params = params;
end


function [overlaps, score, class_ids, avg_cube, avg_cube_per_class] = detector_wiggle_rcnn(filename)
  ld = load(filename);
  scoremaps = ld.scoremaps;

  n = numel(scoremaps);
  all_overlap_scores = cell(n,1);
  for i = 1:n, s = scoremaps(i);
    gt = double(s.gt_box);
    boxes = double(s.boxes);
    invalid = isinf(boxes(:,5)) | isnan(boxes(:,5));
    boxes = boxes(~invalid,:);

    t_overlap = overlap(gt, boxes);
    t_class_ids = repmat(s.class, size(t_overlap));
    all_overlap_scores{i} = cat(2, t_overlap, boxes(:,5), double(t_class_ids));
  end

  all_overlap_scores = cat(1, all_overlap_scores{:});
  overlaps = all_overlap_scores(:,1);
  score = all_overlap_scores(:,2);
  class_ids = all_overlap_scores(:,3);

  avg_cube = [];
  avg_cube_per_class = [];
  if isfield(scoremaps, 'score_map') && ~isempty(scoremaps(1).score_map)
    all_maps = cat(4,scoremaps.score_map);
    avg_cube = nanmean(all_maps, 4);

    classes = unique([scoremaps.class]);
    avg_cube_per_class = cell(1, numel(classes));
    for c = 1:numel(classes)
      t_scoremaps = scoremaps([scoremaps.class] == classes(c));
      avg_cube_per_class{c} = nanmean(cat(4,t_scoremaps.score_map), 4);
    end
  end
end


function latin_random_test ( )

%*****************************************************************************80
%
%% LATIN_RANDOM_TEST tests the LATIN_RANDOM library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 November 2014
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'LATIN_RANDOM_TEST:\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the LATIN_RANDOM library.\n' );

  seed = 123456789;

  for test = 1 : 3

    seed = latin_random_test01 ( seed );

  end
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'LATIN_RANDOM_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


function Dcross(sel)
    % Calculate the Dvalue for a volume around a grid points.
    %
    % see DCPARAIN.
    %
    %   Stefan Wiemer 1/95
    % turned into function by Celso G Reyes 2017

    ZG=ZmapGlobal.Data; % used by get_zmap_globals

    global eq0p

    % the new data vector to be analysed is called Da, relative to the center of the x-section and already in km
    % D = [x,y,z ]
    catalog=ZG.primeCatalog; % points to same thing
    Da = [eq0p(1,:)' eq0p(2,:)' catalog.Date catalog.Date.Month catalog.Date.Day catalog.Magnitude catalog.Depth];
    Da = Da.subset(-2.99 < Da(:,7));
    if exist('sel','var')
        switch sel
            case 'ca'
                my_calculate();
            case 'lo'
                my_load();
        end
        % get the grid parameter
        % initial values
        %
        dd = 1.00;
        dx = 1.00 ;
        ni = 600;
        Nmin = 600; %on line 303 it has been replaced by ni
        stan2 = nan;
        stan = nan;
        prf = nan;
        av = nan;

        % make the interface
        %
        figure_w_normalized_uicontrolunits(...
            'Name','Grid Parameters',...
            'NumberTitle','off', ...
            'units','points',...
            'Visible','on', ...
            'Position',[ 100 200 500 200]);
        axis off
        % Francesco ...

        % creates a dialog box to input grid parameters
        %
        freq_field=uicontrol('Style','edit',...
            'Position',[.32 .57 .12 .08],...
            'Units','normalized','String',num2str(ni),...
            'callback',@callbackfun_001);

        freq_field0=uicontrol('Style','edit',...
            'Position',[.80 .57 .12 .08],...
            'Units','normalized','String',num2str(ra),...
            'callback',@callbackfun_002);

        freq_field2=uicontrol('Style','edit',...
            'Position',[.32 .44 .12 .08],...
            'Units','normalized','String',num2str(dx),...
            'callback',@callbackfun_003);

        freq_field3=uicontrol('Style','edit',...
            'Position',[.32 .31 .12 .08],...
            'Units','normalized','String',num2str(dd),...
            'callback',@callbackfun_004);

        tgl1 = uicontrol('Backgroundcolor', [0.8 0.8 0.8], 'Fontweight','bold',...
            'FontSize', 10, 'Style','checkbox',...
            'string','Number of Events:',...
            'Position',[.05 .56 .2 .10],...
            'callback',@callbackfun_005,...
            'Units','normalized');

        set(tgl1,'value',1);

        tgl2 =  uicontrol('BackGroundColor', [0.8 0.8 0.8],'Style','checkbox',...
            'string','Constant Radius:','Fontweight','bold','FontSize', 10,...
            'Position',[.55 .56 .2 .1],...
            'callback',@callbackfun_006,...
            'Units','normalized');

        set(tgl2, 'ForegroundColor', 'w');

        close_button=uicontrol('Style','Pushbutton',...
            'Position',[.45 .05 .15 .13 ],...
            'Units','normalized', 'Callback', @callbackfun_007,'String','Cancel');

        help_button=uicontrol('Style','Pushbutton',...
            'Position',[.70 .05 .15 .13 ],...
            'Units','normalized', 'Callback', @callbackfun_008,'String','Help');

        go_button1=uicontrol('Style','Pushbutton',...
            'Position',[.20 .05 .15 .13 ],...
            'Units','normalized',...
            'callback',@callbackfun_009,...
            'String','Go');

        txt3 = text(...
            'Position',[0.35 0.9 0 ],...
            'FontSize',ZmapGlobal.Data.fontsz.l ,...
            'FontWeight','bold',...
            'String',' Grid Parameters');
        txt5 = text(...
            'Position',[-0.07 0.46 0 ],...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'FontWeight','bold',...
            'String','Horizontal Spacing [km]:');

        txt6 = text(...
            'Position',[-0.07 0.30 0 ],...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'FontWeight','bold',...
            'String','Depth spacing [km]:');

        txt7 = text(...
            'Position',[0.45 0.62 0 ],...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'FontWeight','bold',...
            'Color', 'r',...
            'String','OR');

        set(gcf,'visible','on');
        watchoff

        % get the grid-size interactively and
        % calculate the b-value in the grid by sorting
        % the seismicity and selectiong the ni neighbors
        % to each grid point

        functin my_calculate()

        figure(xsec_fig);
        figure;
        ax = plot(Da(:,1),-Da(:,7),'o');
        xlabel('Distance in [km]')
        ylabel('Depth in [km]')

        set(gca,'NextPlot','add')
        ax=findobj(gcf,'Tag','mainmap_ax');
        [x,y, mouse_points_overlay] = select_polygon(ax);

        plos2 = plot(x,y,'b-', 'Color', 'r');        % plot outline
        sum3 = 0.;
        pause(0.3)

        %create a rectangular grid
        xvect=[min(x):dx:max(x)];
        yvect=[min(y):dd:max(y)];
        gx = xvect;gy = yvect;
        tmpgri=zeros((length(xvect)*length(yvect)),2);
        n=0;

        for i=1:length(xvect)
            for j=1:length(yvect)
                n=n+1;
                tmpgri(n,:)=[xvect(i) yvect(j)];
            end
        end

        %extract all gridpoints in chosen polygon
        XI=tmpgri(:,1);
        YI=tmpgri(:,2);

        ll = polygon_filter(x,y, XI, YI, 'inside');
        %grid points in polygon
        newgri=tmpgri(ll,:);

        % Plot all grid points
        plot(newgri(:,1),newgri(:,2),'+k')

        if length(xvect) < 2  ||  length(yvect) < 2
            errordlg('Selection too small! (not a matrix)');
            return
        end

        itotal = length(newgri(:,1));
        if length(gx) < 4  ||  length(gy) < 4
            errordlg('Selection too small! ');
            return
        end

        %  make grid, calculate start- endtime etc.  ...
        %
        [t0b, teb] = bounds(newa.Date) ;
        n = newa.Count;
        tdiff = round((teb-t0b)/ZG.bin_dur);
        loc = zeros(3, length(gx)*length(gy));

        % loop over  all points
        %
        i2 = 0.;
        i1 = 0.;
        bvg = [];
        allcount = 0.;
        wai = waitbar(0,' Please Wait ...  ');
        set(wai,'NumberTitle','off','Name','D-value grid - percent done', 'position', [250 80 270 50]);
        drawnow;
        %

        %
        for i= 1:length(newgri(:,1))
            x = newgri(i,1);y = newgri(i,2);
            allcount = allcount + 1.;
            i2 = i2+1;

            % calculate distance from center point and sort wrt distance

            l = sqrt(((Da(:,1) - x)).^2 + ((Da(:,7) + y)).^2 + (Da(:,2).^2)) ;
            [s,is] = sort(l);
            b = Da(is(:,1),:) ;       % re-orders matrix to agree row-wise

            if tgl1 == 0   % take point within r
                l3 = l <= ra;
                b = Da.subset(l3);      % new data per grid point (b) is sorted in distanc
                rd = ra;
            else
                % take first ni points
                b = b(1:ni,:);      % new data per grid point (b) is sorted in distance
                l2 = sort(l);
                rd = l2(ni);

            end

            %estimate the completeness and b-value, and take the zero depth events away.
            %ZG.newt2 = [b.Longitude b.Latitude zeros(size(b,1),1) zeros(size(b,1),1) zeros(size(b,1),1) zeros(size(b,1),1) b.Date];
            %
            ZG.newt2  = b;
            E = ZG.newt2;

            if b.Count >= ni  % enough events?

                dtokm = 0;
                [bv magco0 stan av pr] =  bvalca3(b.Magnitude,McAutoEstimate.auto);

                if range == 1 | range == 2

                    pdc3nofig(E);

                elseif range == 3

                    pdc3;
                    pause;

                end %if range = 1|2

                D = coef(1,1);
                fdallfig;

            else
                D = nan;
                bv = nan;

            end %if length >= ni

            bvg = [bvg ; D x y rd bv deltar];
            waitbar(allcount/itotal)

        end  % for  newgri

        figure(HCIfig);
        cb = colorbar('horiz');
        set(cb, 'position', [0.32 0.08 0.4 0.03], 'XTickLabel', col);
        axes('pos',[0 0 1 1]); axis off; set(gca,'NextPlot','add');
        te= text('string','D-value','pos',[0.49,0.01], 'fontsize',8,'FontWeight','bold')
        set(gcf,'visible','on');
        % save data
        %
        %  set(txt1,'String', 'Saving data...')

        drawnow
        gx = xvect;gy = yvect;

        catsave3('Dcross');
        %corrected the window positioning error
        close(wai)
        watchoff

        %
        % reshape a few matrices
        %
        normlap2=nan(length(tmpgri(:,1)),1)

        reshaper=@(v)reshape(v,length(yvect),length(xvect));
        normlap2(ll)= bvg(:,1);
        valueMap=reshaper(normlap2);

        normlap2(ll)= bvg(:,4);
        reso = reshaper(normlap2);

        normlap2(ll)= bvg(:,5);
        BM=reshaper(normlap2);

        old = valueMap;

        % View the b-value map
        view_Dv(valueMap, lab1, Da)

    end

    % Load exist D-grid
    function my_load()
        [file1,path1] = uigetfile(['*.mat'],'b-value gridfile');
        if length(path1) > 1

            load([path1 file1])
            xsecx = newa(:,end)';
            xsecy = newa(:,7);
            xvect = gx; yvect = gy;
            tmpgri=zeros((length(xvect)*length(yvect)),2);

            normlap2=nan(length(tmpgri(:,1)),1)
            normlap2(ll)= bvg(:,1);
            valueMap=reshape(normlap2,length(yvect),length(xvect));

            normlap2(ll)= bvg(:,4);
            r=reshape(normlap2,length(yvect),length(xvect));

            old = valueMap;

            nlammap
            [xsecx xsecy,  inde] =mysect(catalog.Latitude',catalog.Longitude',catalog.Depth,ZG.xsec_defaults.WidthKm,0,lat1,lon1,lat2,lon2);
            % Plot all grid points
            set(gca,'NextPlot','add')
            plot(newgri(:,1),newgri(:,2),'+k')
            view_Dv(valueMap, lab1, Da)
        else
            return
        end
    end

    function callbackfun_001(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ni=str2double(freq_field.String);
        freq_field.String=num2str(ni);
        tgl2.Value=0;
        tgl1.Value=1;
    end

    function callbackfun_002(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ra=str2double(freq_field0.String);
        freq_field0.String=num2str(ra);
        tgl2.Value=1;
        tgl1.Value=0;
    end

    function callbackfun_003(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        dx=str2double(freq_field2.String);
        freq_field2.String=num2str(dx);
    end

    function callbackfun_004(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        dd=str2double(freq_field3.String);
        freq_field3.String=num2str(dd);
    end

    function callbackfun_005(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        set(tgl2,'Value',0, 'ForegroundColor', 'w');
        set(tgl1, 'ForegroundColor', 'k');
    end

    function callbackfun_006(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        set(tgl1,'Value',0,'ForegroundColor', 'w');
        set(tgl2, 'ForegroundColor', 'k');
    end

    function callbackfun_007(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        close;

    end

    function callbackfun_008(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        close;

    end

    function callbackfun_009(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        tgl1=tgl1.Value;
        tgl2=tgl2.Value;
        close;
        gobut = 3;
        org = 1;
        startfd(1, gobut);
    end

end


function cavity_flow_movie ( )

%*****************************************************************************80
%
%% CAVITY_FLOW_MOVIE creates an animation from flow data.
%
%  Discussion:
%
%    This MATLAB script file reads the Cavity flow data:
%
%      geometry (XY values at nodes, assumed to be in 'xy.txt')
%      flow (UV values at nodes, in a sequence of files starting with 'up001.txt')
%
%    and plots the velocity vectors (U,V)(X,Y), saving each plot and
%    making an animation.
%
%    The file plots either the velocity vector field, or the velocity
%    direction field, depending on the value of the internal logical
%    parameter "normalized".
%
%    The MATLAB routine quiver internally scales the vectors, but this
%    can be adjusted by using a value of SCALE that is not 1.
%
%    For the unnormalized case, the velocity field is computed to a fixed
%    scale determined by finding the largest velocity vector over time.
%
%    This routine requires some auxiliary routines in order to "increment"
%    the name of the current velocity data file to get the name of the next
%    one, with the main such routine being called FILE_NAME_INC.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    05 July 2003
%
%  Author:
%
%    John Burkardt
%
  FALSE = 0;
  TRUE = 1;
  scale = 1.0;
  normalized = TRUE;

  nframes = 500;
%
%  Get the XY coordinates of the nodes.
%
  load xy.txt;

  x = xy(:,1);
  y = xy(:,2);
%
%  Thin the data.
%
  thin_factor = 2;
  thin_dex = thin_index ( x, y, thin_factor );
  thin_num = length ( thin_dex );
  x = x(thin_dex);
  y = y(thin_dex);
%
%  For unnormalized plots, you need to make sure that a fixed scale is preserved from
%  step to step.  The only way I can see to do this requires that I determine the
%  maximum velocity over all time, and then append one extract node and velocity
%  to the data structure.
%
  if ( normalized == FALSE )

    upfile = 'up000.txt';
    vnorm_max = 0.0;

    for ( i = 1 : nframes )
      i
      upfile = file_name_inc ( upfile );
      uv = load ( upfile );
      u = uv(thin_dex,1);
      v = uv(thin_dex,2);
      norm = sqrt ( u.^2 + v.^2 );
      vnorm_max = max ( vnorm_max, max ( norm ) );
    end

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Maximum visible velocity magnitude is %f\n', vnorm_max );

  end
%
%  Set the coordinates of the boundary lines, and an extra set of
%  lines that will be invisible, but which make some space for the
%  file name to be displayed within the plot area.
%
  bx1 = [ 0.00, 0.00, 1.00, 1.00, 0.99, 0.99, 0.01, 0.01, 0.00 ];
  by1 = [ 1.00, 0.00, 0.00, 1.00, 1.00, 0.01, 0.01, 1.00, 1.00 ];

  bx2 = [ -0.10,  1.10, 1.10, -0.10, -0.10 ];
  by2 = [ -0.10, -0.10, 1.10,  1.10, -0.10 ];
%
%  Set the name of the 0th (nonexistent) velocity file.
%  All the velocity files with have this format, with the
%  numeric part of the name incremented to get the next one.
%  In particular, the first velocity file is called UP001.TXT.
%
  upfile = 'up000.txt';

  for ( i = 1 : nframes )
    i
    upfile = file_name_inc ( upfile );
    uv = load ( upfile );
    u = uv(thin_dex,1);
    v = uv(thin_dex,2);

    if ( normalized == TRUE )
      norm = sqrt ( u.^2 + v.^2 );
      nonzero = find ( norm ~= 0.0 );
      u(nonzero) = u(nonzero) ./ norm(nonzero);
      v(nonzero) = v(nonzero) ./ norm(nonzero);
      vnorm_max = 1.0;
    end

    x(thin_num+1) = 0.00;
    y(thin_num+1) = 1.05;
    u(thin_num+1) = vnorm_max;
    v(thin_num+1) = 0.0;

    quiver ( x, y, u, v, scale )
%
%  Draw the boundary lines, and the invisible bounding line.
%
    line ( bx1, by1, 'color', 'r' )
    line ( bx2, by2, 'color', 'w' )
    axis equal
    if ( normalized == TRUE )
      title ( 'Cavity Direction Field' )
    else
      title ( 'Cavity Flow Field' )
    end
    text ( 0.420, 1.03, upfile )

    my_frames(:,i) = getframe;

  end
%
%  Display the movie a given number of times.
%
  movie ( my_frames, 2 )

  return
end
function file_name = file_name_inc ( file_name )

%*****************************************************************************80
%
%% FILE_NAME_INC generates the next filename in a series.
%
%  Discussion:
%
%    It is assumed that the digits in the name, whether scattered or
%    connected, represent a number that is to be increased by 1 on
%    each call.  If this number is all 9's on input, the output number
%    is all 0's.  Non-numeric letters of the name are unaffected..
%
%    If the name is empty, then the routine stops.
%
%    If the name contains no digits, the empty string is returned.
%
%  Example:
%
%      Input            Output
%      -----            ------
%      'a7to11.txt'     'a7to12.txt'  (typical case.  Last digit incremented)
%      'a7to99.txt'     'a8to00.txt'  (last digit incremented, with carry.)
%      'a9to99.txt'     'a0to00.txt'  (wrap around)
%      'cat.txt'        ' '           (no digits in input name.)
%      ' '              STOP!         (error.)
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 September 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string FILE_NAME, the string to be incremented.
%
%    Output, string FILE_NAME, the incremented string.
%
  lens = length ( file_name );

  if ( lens <= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'FILE_NAME_INC - Fatal error!\n' );
    fprintf ( 1, '  The input filename is empty.\n' );
    error ( 'FILE_NAME_INC - Fatal error!' );
  end

  change = 0;

  for i = lens : -1 : 1

    c = file_name(i);

    if ( '0' <= c & c <= '8' )

      change = change + 1;

      c = c + 1;

      file_name(i) = c;

      return

    elseif ( c == '9' )

      change = change + 1;

      c = '0';

      file_name(i) = c;

    end

  end

  if ( change == 0 )
    file_name = ' ';
  end

  return
end
function thin_dex = thin_index ( x, y, thin_factor )

%*****************************************************************************80
%
%%  THIN_INDEX determines thinning indices for a X, Y data.
%
%  Discussion:
%
%    A set of X, Y data is given, that is presumably, not too far off
%    from being on a rectangular grid.
%
%    The input value of THIN_FACTOR indicates by how much the data should
%    be thinned.
%
%    The X and Y ranges are computed, and only those data points are
%    retained for which both X and Y lie in an appropriate subrange.
%
%    For instance, a THIN_FACTOR of 2 would essentially save data
%    that lay in the black squares of a checkerboard.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 June
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X(NODE_NUM), Y(NODE_NUM), the X and Y coordinates
%    of the nodes.
%
%    Input, integer THIN_FACTOR, the thinning factor.
%
%    Output, integer THIN_DEX(NODE_NUM), contains in (1:THIN_NUM) the
%    indices into X and Y of the vectors to be retained after thinning.
%
  TRUE = 1;
  FALSE = 0;

  node_num = length ( x );

  x_unique_num = 0;

  for ( i = 1 : node_num )

    unique = TRUE;

    for ( j = 1 : x_unique_num )
      if ( x(i) == x_unique(j) )
        unique = FALSE;
        break;
      end
    end

    if ( unique )
      x_unique_num = x_unique_num + 1;
      x_unique(x_unique_num) = x(i);
    end

  end

  sort ( x_unique );

  y_unique_num = 0;

  for ( i = 1 : node_num )

    unique = TRUE;

    for ( j = 1 : y_unique_num )
      if ( y(i) == y_unique(j) )
        unique = FALSE;
        break;
      end
    end

    if ( unique )
      y_unique_num = y_unique_num + 1;
      y_unique(y_unique_num) = y(i);
    end

  end

  sort ( y_unique );

  thin_num = 0;

  for ( i = 1 : node_num )

    for ( j = 1 : x_unique_num-1 )
      if ( x_unique(j) <= x(i) & x(i) <= x_unique(j+1) )
        x_bin = j;
        break;
      end
    end

    for ( j = 1 : y_unique_num-1 )
      if ( y_unique(j) <= y(i) & y(i) <= y_unique(j+1) )
        y_bin = j;
        break;
      end
    end

    if ( mod ( y_bin, thin_factor ) == thin_factor / 2 & ...
         mod ( x_bin, thin_factor ) == thin_factor / 2 )

      thin_num = thin_num + 1;
      thin_dex(thin_num) = i;

    end

  end

  return
end


function [pdc, pdcvar, n] = ft_connectivity_pdc(inputdata, varargin)

% FT_CONNECTIVITY_PDC computes partial directed coherence. This function implements
% the metrices described in Baccala et al., Biological Cybernetics 2001, 84(6),
% 463-74. and in Baccala et al., 15th Int.Conf.on DSP 2007, 163-66.
%
% The implemented algorithm has been tested against the implementation in the
% SIFT-toolbox. It yields numerically identical results to what is known there as
% 'nPDC' (for PDC) and 'GPDC' for generalized pdc.
%
% Use as
%   [p, v, n] = ft_connectivity_pdc(inputdata, ...)
%
% The input data should be a spectral transfer matrix organized as
%   Nrpt x Nchan x Nchan x Nfreq (x Ntime),
% where Nrpt can be 1.
%
% Additional optional input arguments come as key-value pairs:
%   'hasjack'   = 0 (default) is a boolean specifying whether the input
%                 contains leave-one-outs, required for correct variance
%                 estimate
%   'invfun'    = 'inv' (default) or 'pinv', the function used to invert the
%                 transfer matrix to obtain the fourier transform of the
%                 MVAR coefficients. Use 'pinv' if the data are
%                 poorly-conditioned.
%   'noisecov'  = matrix containing the covariance of the residuals of the
%                 MVAR model. If this matrix is defined, the function
%                 returns the generalized partial directed coherence.
%   'feedback'  = 'none', 'text', 'textbar', 'dial', 'etf', 'gui' type of feedback showing progress of computation, see FT_PROGRESS
%
% Output arguments:
%   p = partial directed coherence matrix Nchan x Nchan x Nfreq (x Ntime).
%       If multiple observations in the input, the average is returned.
%   v = variance of p across observations.
%   n = number of observations.
%
% Typically, nrpt should be 1 (where the spectral transfer matrix is
% computed across observations. When nrpt>1 and hasjack is true the input
% is assumed to contain the leave-one-out estimates of H, thus a more
% reliable estimate of the relevant quantities.
%
% See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS

% Copyright (C) 2009-2017, Jan-Mathijs Schoffelen
%
% 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$

hasjack  = ft_getopt(varargin, 'hasjack', 0);
feedback = ft_getopt(varargin, 'feedback', 'none');
invfun   = ft_getopt(varargin, 'invfun', 'inv');
noisecov = ft_getopt(varargin, 'noisecov');

switch invfun
  case {'inv' 'pinv'}
    invfun = str2func(invfun);
  otherwise
    ft_error('unknown specification of inversion-function for the transfer matrix');
end

% crossterms are described by chan_chan_therest
siz = [size(inputdata) 1];
n   = siz(1);

if ~isempty(noisecov)
  ft_progress('init', feedback, 'computing generalized partial directed coherence...');
  scale = diag(sqrt(1./diag(noisecov))); % get the 1./sqrt(var) of the signals
else
  ft_progress('init', feedback, 'computing partial directed coherence...');
  scale = eye(siz(2));
end

% pre-allocate some variables
outsum = zeros(siz(2:end));
outssq = zeros(siz(2:end));

% the mathematics for pdc is most straightforward using the inverse of the
% transfer function
pdim     = prod(siz(4:end));
tmpinput = reshape(inputdata, [siz(1:3) pdim]);
ft_progress('init', feedback, 'inverting the transfer function...');
for k = 1:n
  ft_progress(k/n, 'inverting the transfer function for replicate %d from %d\n', k, n);
  tmp = reshape(tmpinput(k,:,:,:), [siz(2:3) pdim]);
  for m = 1:pdim
    tmp(:,:,m) = scale*invfun(tmp(:,:,m));
  end
  tmpinput(k,:,:,:) = tmp;
end
ft_progress('close');
inputdata = reshape(tmpinput, siz);

for j = 1:n
  ft_progress(j/n, 'computing metric for replicate %d from %d\n', j, n);
  invh   = reshape(inputdata(j,:,:,:,:), siz(2:end));

  den    = sum(abs(invh).^2,1);
  tmppdc = abs(invh)./sqrt(repmat(den, [siz(2) 1 1 1 1]));

  outsum = outsum + tmppdc;
  outssq = outssq + tmppdc.^2;
end
ft_progress('close');

pdc = outsum./n;

if n>1
  if hasjack
    bias = (n-1).^2;
  else
    bias = 1;
  end
  pdcvar = bias*(outssq - (outsum.^2)./n)./(n - 1);
else
  pdcvar = [];
end

% this is to achieve the same convention for all connectivity metrics:
% row -> column
for k = 1:prod(siz(4:end))
  pdc(:,:,k)    = transpose(pdc(:,:,k));
  if ~isempty(pdcvar)
    pdcvar(:,:,k) = transpose(pdcvar(:,:,k));
  end
end


%
% Removes graph nodes that are within one pixel of eachother
%
% Input
%   T: graph struct that is the output of the tracer
%
% Output
%   T:
%
function T = graph_merge(T)

    % make all merge moves
    tormv = true;
    while tormv
       [T,tormv] = remove_conncomp(T);
    end

end

% make one removal
function [M,tormv] = remove_conncomp(M)

    G = M.G;
    D = squareform(pdist(G));
    EE = D < 1.1; % make an edge between two nodes that are very close
    [S,C] = graphconncomp(sparse(EE),'Directed',false);
    % C indicates which component each node belongs to

    tormv= false;
    for i=1:S
       sel = C==i;
       ns = sum(sel);
       if ns > 1
          tormv = true;
          break
       end
    end

    % break when necessary
    if ~tormv, return; end

    %E_sel_to_sel = M.E(sel,sel);
    E_sel_to_not = M.E(sel,~sel);
    EI_sel_to_sel = M.EI(sel,sel);
    EI_sel_to_not = M.EI(sel,~sel);

    % create the new row in adjacency matrix, which
    % includes all the nodes connected to the selected set/pair
    new_row_E = any(E_sel_to_not,1);
    new_row_EI = cell(size(new_row_E));
    for i=1:size(EI_sel_to_not,2);
        new_row_EI{i} = tovec(EI_sel_to_not(:,i));
    end

    % list_ei_sel_to_not = tovec(EI_sel_to_not);
    list_ei_sel_to_sel = tovec(EI_sel_to_sel);
    list_ei_sel_to_sel = unique(list_ei_sel_to_sel);

    % see which of the edges, from sel to sel, should be removed.
    % we don't want to remove edges that make a long arc and then return
    nss = length(list_ei_sel_to_sel);
    rmv_edge = false(nss,1);
    for i=1:nss
       indx = list_ei_sel_to_sel(i);
       edge_length = size(M.S{indx},1);
       if edge_length == 2
          rmv_edge(i) = true;
       end
    end
    keep_ei_sel_to_sel =  list_ei_sel_to_sel(~rmv_edge);
    rmv_ei_sel_to_sel = list_ei_sel_to_sel(rmv_edge);

    % remove node positions
    G_sel = M.G(sel,:);
    new_node = mean(G_sel,1);
    Grmv = M.G(sel,:);
    M.G(sel,:) = [];
    M.G = [M.G; new_node];
    M.n = M.n - sum(sel) + 1;

    % modify adjacency matrix with the new row
    M.E(sel,:) = [];
    M.E(:,sel) = [];
    M.E(end+1,:) = new_row_E;
    M.E(:,end+1) = [new_row_E,false];
    if ~isempty(keep_ei_sel_to_sel)
        M.E(end,end) = true;
    end

    % modify the list of edges with each cell
    M.EI(sel,:) = [];
    M.EI(:,sel) = [];
    M.EI(end+1,:) = new_row_EI;
    M.EI(:,end+1) = [new_row_EI, {keep_ei_sel_to_sel} ];

    % modify the paths
    M.S(rmv_ei_sel_to_sel) = [];
    for i=1:numel(M.EI)
       mycell = M.EI{i};

       % update counts in adjacency matrix
       for j=1:length(mycell)
          el = mycell(j);
          M.EI{i}(j) = el - sum(rmv_ei_sel_to_sel < el);
       end
    end

    % update the paths, stored in M.S, such that all
    % nodes we have now replaced are updated with their
    % new coordinates
    for i=1:length(M.S)
        for j=1:size(Grmv,1);
            node_rmv = Grmv(j,:);
            d = pdist2(node_rmv,M.S{i});
            swap = d < .001;
            nswap = sum(swap);
            M.S{i}(swap,:) = repmat(new_node,[nswap 1]);
        end
    end

    assert_valid_graph(M);
end


function p03_header ( )

%*****************************************************************************80
%
%% P03_HEADER prints some information about problem 03.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Per-Olof Persson and Gilbert Strang,
%    A Simple Mesh Generator in MATLAB,
%    SIAM Review,
%    Volume 46, Number 2, June 2004, pages 329-345.
%
%  Parameters:
%
%    None.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'P03:\n' );
  fprintf ( 1, '  Strang and Persson example #3\n' );
  fprintf ( 1, '  The unit square, with a hole.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  The hole is a concentric circle of radius 0.4.\n' );
  fprintf ( 1, '  A uniform mesh density is requested.\n' );
  fprintf ( 1, '  Element sizes tried were 0.4, 0.2, 0.1.\n' );

  fprintf ( 1, '\n' );
  boundary_segment_num = p03_boundary_segment_num ( );
  fprintf ( 1, '  Number of boundary segments = %d\n', boundary_segment_num );
  fixed_num = p03_fixed_num ( );
  fprintf ( 1, '  Number of fixed points = %d\n', fixed_num );
  hole_num = p03_hole_num ( );
  fprintf ( 1, '  Number of holes = %d\n', hole_num );

  return
end


filename='Cantilever_quad_fine';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance'};
weights = [1, 0.1];
constraint = {'volumeConstraint'};
optimizer = 'PROJECTED GRADIENT';
incrementFactor = 1;
designVariable = 'Density';
filterType = 'P1';

nsteps = 1;
Vfrac_final = 0.4;
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 [n1,val]=zerotest(y,m,w)
[m,n1]=min(abs(y-m));
if sum(w)==0
val=1;
else
val=w(n1);
end


function [CV,CE,I,CN,GD,D] = polygonize(V,F,fun,varargin)
  % Polygonize (contour) an implicit function in the spirit of "An Implicit
  % Surface Polygonizer" [Bloomenthal 1994]
  %
  % [CV,CE] = polygonize(V,F,fun)
  %
  % Inputs:
  %   V  #V by dim list of vertex positions of original mesh
  %   F  #F by dim+1 list of element indices into V
  %   fun  function handle so that zero is the desired level set
  % Outputs:
  %   CV  #CV by dim list of contour mesh vertices
  %   CE  #CE by dim list of facet indices into CV
  %   I  #CE list of indices into F
  %   CN  #CN by dim list of unit normal vectors at vertices
  %

  % default values
  delta = [];
  % Map of parameter names to variable names
  params_to_variables = containers.Map( ...
    {'Delta'}, ...
    {'delta'});
  v = 1;
  while v <= numel(varargin)
    param_name = varargin{v};
    if isKey(params_to_variables,param_name)
      assert(v+1<=numel(varargin));
      v = v+1;
      % Trick: use feval on anonymous funtion to use assignin to this workspace
      feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));
    else
      error('Unsupported parameter: %s',varargin{v});
    end
    v=v+1;
  end

  flipped_order = flipped_tet_orders();

  max_iters = 10;
  D = fun(V);
  interval = @(DF) any(DF>0.0,2) & any(DF<=0.0,2);
  crosses = @(DE) ...
    (DE(:,1)>0 & DE(:,2)<= 0)*-1 + ...
    (DE(:,2)>0 & DE(:,1)<= 0)*1;
  crossing_F = find(interval(D(F)));
  FF = F(crossing_F,:);
  % simplex size
  ss = size(F,2);
  switch ss
  case 3
    allE = [FF(:,[2 3]);FF(:,[3 1]);FF(:,[1 2])];
  case 4
    allE = ...
      [FF(:,1) FF(:,2); ...
       FF(:,1) FF(:,3); ...
       FF(:,1) FF(:,4); ...
       FF(:,2) FF(:,3); ...
       FF(:,2) FF(:,4); ...
       FF(:,3) FF(:,4) ...
       ];
  end
  sE = sort(allE,2);
  [E,~,EMAP] = unique(sE,'rows');
  cross_dir = crosses(D(E));
  crossing = cross_dir ~= 0;
  J = (1:size(E,1))';
  EE = E(crossing,:);
  J(crossing) = 1:size(EE,1);
  % Blasphemy
  switch ss
  case 3
    CE = sort(reshape(crossing(EMAP),[],3).*reshape(J(EMAP),[],3),2);
    CE = CE(:,2:end);
  case 4
    % CE(f,i) = 0 if ith edge of element f does not cross, otherwise
    % CE(f,i) is the index of the unique edge that does cross
    CE = reshape(crossing(EMAP),[],6).*reshape(J(EMAP),[],6);
    % If 3 edges cross then we can surface with a single triangle
    crossE = reshape(cross_dir(EMAP),[],6);
    IT = find(sum(CE>0,2)==3);
    crossT = crossE(IT,:);
    [CT,ST] = sort(CE(IT,:),2);
    CT = CT(:,end-2:end);
    flippedT = [
      -1 -1 -1 0 0 0 4 5 6 1 3 2
      -1 -1 -1 0 0 0 4 5 6 2 1 3
      -1 0 0 1 1 0 2 3 6 1 5 4
      0 -1 0 -1 0 -1 1 3 5 2 4 6
      0 -1 0 -1 0 1 1 3 5 2 4 6
      0 -1 0 1 0 1 1 3 5 2 4 6
      0 0 -1 0 -1 -1 1 2 4 3 6 5
      0 0 -1 0 1 -1 1 2 4 3 6 5
      0 0 1 0 1 -1 1 2 4 3 5 6
      0 0 1 0 1 1 1 2 4 3 5 6
      0 1 0 -1 0 -1 1 3 5 2 6 4
      1 0 0 -1 -1 0 2 3 6 1 4 5
      1 0 0 1 -1 0 2 3 6 1 4 5
      1 0 0 1 1 0 2 3 6 1 4 5
      1 1 1 0 0 0 4 5 6 1 2 3
      1 1 1 0 0 0 4 5 6 2 3 1
    ];
    fT = ismember([crossT ST],flippedT,'rows');
    CT(fT,:) = fliplr(CT(fT,:));

    IQ = find(sum(CE>0,2)==4);
    crossQ = crossE(IQ,:);
    [CQ,SQ] = sort(CE(IQ,:),2);
    CQ = CQ(:,end-3:end);
    flippedQ = [
      -1 -1 0 0 -1 1 3 4 2 1 6 5
      -1 -1 0 0 1 1 3 4 2 1 6 5
      -1 0 -1 -1 0 -1 2 5 1 3 4 6
      -1 0 -1 1 0 -1 2 5 1 3 4 6
      -1 0 -1 1 0 1 2 5 1 3 4 6
      0 -1 -1 -1 -1 0 1 6 3 2 5 4
      0 1 1 -1 -1 0 1 6 2 3 4 5
      0 1 1 -1 1 0 1 6 2 3 4 5
      0 1 1 1 1 0 1 6 2 3 4 5
      1 0 1 1 0 1 2 5 3 1 6 4
      1 1 0 0 -1 -1 3 4 1 2 5 6
      1 1 0 0 -1 1 3 4 1 2 5 6
    ];
    fQ = ismember([crossQ SQ],flippedQ,'rows');
    %% huh. Need to flip _after_ creating triangles.
    %CQT([fQ;fQ],:) = fliplr(CQT([fQ;fQ],:));
    % or switch the middle two...
    CQ(fQ,:) = CQ(fQ,[1 3 2 4]);
    I = [IT;IQ;IQ];
    I = crossing_F(I);
  end
  % Upper and lower bound on barycenteric coordinate locating =0.5
  EEl= zeros(size(EE,1),1);
  EElV = V(EE(:,1),:);
  Dl = D(EE(:,1));
  EEu= ones(size(EE,1),1);
  Du = D(EE(:,2));
  EEuV = V(EE(:,2),:);
  for iter = 1:max_iters
    EEm = (EEl+EEu)/2;
    CV = 0.5*(EElV+EEuV);
    if iter < max_iters
      Dm = fun(CV);
      front = interval([Dl Dm]);
       EEu(front,:) =  EEm(front,:);
      EEuV(front,:) = CV(front,:);
       Du(front,:) =  Dm(front,:);
       EEl(~front,:) =  EEm(~front,:);
      EElV(~front,:) = CV(~front,:);
       Dl(~front,:) =  Dm(~front,:);
    end
  end

  switch ss
  case 4
    % Flip non-deluanay edges in quads... at least.
    CQT = [CQ(:,[3 1 4]);CQ(:,[2 4 1])];
    A = reshape(internalangles(CV,CQT),[],6);
    % Quads with Non-delaunay diagonals.
    nd = (A(:,1)+A(:,4))>pi;
    CQ(nd,:) = CQ(nd,[3 4 1 2]);
    CQ1 = CQ(:,[3 1 4]);
    CQ2 = CQ(:,[2 4 1]);
    CQ1(nd,:) = fliplr(CQ1(nd,:));
    CQ2(nd,:) = fliplr(CQ2(nd,:));
    CQT = [CQ1;CQ2];
    %% Double check: sum should be zero
    % A = reshape(internalangles(CV,CQT),[],6);
    % % Non-delaunay
    % nd = (A(:,1)+A(:,4))>pi;
    % sum(nd)
    CE = fliplr([CT;CQT]);
    assert(size(CE,2) == ss-1);

    %% How I determined what should be flipped:
    % S = sum(normals(CV,CT).*barycenter(CV,CT),2);
    % A = unique([crossT(S<0,:) ST(S<0,:)],'rows');
    % B = unique([crossT(S>0,:) ST(S>0,:)],'rows');
    % intersect(A,B,'rows');
    % fprintf('    flippedT = [\n');
    % fprintf('      %d %d %d %d %d %d %d %d %d %d %d %d\n',A');
    % fprintf('    ];\n');
    %S = sum(normals(CV,CQ(:,[1 4 3])).*barycenter(CV,CQ(:,[1 4 3])),2);
    %A = unique([crossQ(S<0,:) SQ(S<0,:)],'rows');
    %B = unique([crossQ(S>0,:) SQ(S>0,:)],'rows');
    %intersect(A,B,'rows')
    %fprintf('    flippedQ = [\n');
    %fprintf('      %d %d %d %d %d %d %d %d %d %d %d %d\n',A');
    %fprintf('    ];\n');
  end

  if nargout>=4
    if isempty(delta)
      %  following Bloomenthal's "An Implicit Surface Polygonizer" 1994
      %
      delta = avgedge(V,F)/max_iters^2;
      % More accurate...
      delta = delta*0.0001;
    end
    % Approximate the gradient with finite differences (it'd be cool if fun
    % could also provide the gradient)
    %
    % Combine FD calls into a single call to fun in case fun has a lot of
    % per-call precomputation.
    order = 2
    switch order
    case 1
      % Wasn't computed on the last iteration
      D = fun(CV);
      switch ss
      case 3
        GD = ...
          reshape(fun([CV+[1 0]*delta;CV+[0 1]*delta]),[],2);
      case 4
        GD = reshape( ...
          fun([CV+[1 0 0]*delta;CV+[0 1 0]*delta;CV+[0 0 1]*delta]), ...
          size(CV,1),3);
      end
      % Don't bother dividing by delta (we're normalizing anyway)
      G = GD-D;
    case 2
      delta = delta/2;
      switch ss
      case 3
        GD = ...
          reshape(fun([CV+[1 0]*delta;CV+[0 1]*delta;CV-[1 0]*delta;CV-[0 1]*delta]),[],2,2);
      case 4
        GD = reshape( ...
          fun([ ...
            CV+[1 0 0]*delta;CV+[0 1 0]*delta;CV+[0 0 1]*delta; ...
            CV-[1 0 0]*delta;CV-[0 1 0]*delta;CV-[0 0 1]*delta; ...
            ]), ...
          size(CV,1),3,2);
      end
      G = GD(:,:,1)-GD(:,:,2);
    end

    CN = -normalizerow(G);
  end

end


function ll = gpsimLogLikelihood(model)

% GPSIMLOGLIKELIHOOD Compute the log likelihood of a GPSIM model.
% FORMAT
% DESC computes the log likelihood of the given Gaussian process
% for use in a single input motif protein network.
% ARG model : the model for which the log likelihood is computed.
% RETURN ll : the log likelihood of the data set.
%
% SEEALSO : gpsimCreate, gpsimLogLikeGradient, gpsimObjective
%
% COPYRIGHT : Neil D. Lawrence, 2006

% SHEFFIELDML

dim = size(model.y, 1);
ll = -dim*log(2*pi) - model.logDetK - model.m'*model.invK*model.m;
ll = ll*0.5;

% In case we need priors in.
if isfield(model, 'bprior'),
  ll = ll + kernPriorLogProb(model.kern);
  ll = ll + priorLogProb(model.bprior, model.B);
end


function pool_forward()
    global config mem;
    curr_layer_idx = config.misc.current_layer;
    mem.activations{curr_layer_idx} = bsxfun(@plus, bsxfun(@times, mem.layer_inputs{curr_layer_idx}, config.weights{curr_layer_idx}'), ...
                                                      config.weights{config.layer_num+curr_layer_idx}');
    config.misc.current_layer = curr_layer_idx + 1;
end


DO_TRAIN = 0;
DO_TEST = 1;

%% Training

if DO_TRAIN

datadir = '~/data/eccv08/msrc21/';

if 0
    load(fullfile(datadir, 'msSegmentFeatures_tu_tmp.mat'));
    load(fullfile(datadir, 'trainTestFn_tu.mat'));
    %train = train(randperm(numel(train)));
end

maxdata = 1000000;
maxtree = 1000;
bagsize = 25000;

% good vs bad segment classifier
if 1

[data, lab, w] = msFormatClassifierData(...
    segfeatures(train, :), seggood(train, :), trainw(train, :), maxdata);
nfs = [1 2 4 8 16 32 48 64 94];
valset = (ceil(0.1*(numel(lab))):ceil(0.4*numel(lab)));
ntrees = 100;
bagfract = bagsize / (numel(lab)-numel(valset));
[segnf, segerr] = rfSelectPoolSize(data, (lab+1)/2+1, bagfract, ntrees, ...
    maxtree, nfs, valset, w);
end
ntrees = 200;
[dt_seg, segoob] = rfTrainForest(data, (lab+1)/2+1, ...
    bagfract, ntrees, maxtree, segnf, [], w);

% label classifier
[data, lab, w] = msFormatClassifierData(...
    segfeatures(train, :), seglabel(train, :), trainw(train, :), maxdata);
%valset = (1:ceil(0.2*numel(lab)));
ntrees = 100;
bagfract = bagsize / (numel(lab)-numel(valset));
[labnf, laberr] = rfSelectPoolSize(data, lab, bagfract, ntrees, ...
    maxtree, nfs, valset, w);

ntrees = 500;
[dt_lab, laboob] = rfTrainForest(data, lab, ...
    bagfract, ntrees, maxtree, labnf, [], w);

save('~/data/rfexperiments/msrcRandForestJointClassifiers.mat', ...
    'maxdata', 'maxtree', 'nfs', 'segnf', 'segerr', 'labnf', 'laberr', ...
    'dt_seg', 'segoob', 'dt_lab', 'laboob');

end

%% Testing

if DO_TEST

if 0
    load(fullfile(datadir, 'msrc_imsegs.mat'));
    load(fullfile(datadir, 'testLabels.mat'));
    load(fullfile(datadir, 'msMultipleSegmentations_tu_tmp.mat'));
end

pg = msTestRf(imsegs(test), segfeatures(test, :), smaps(test), dt_lab, dt_seg, 0);
ignore = [5 8];
DO_SP = 1;
[acc, cm, classcount] = msAnalyzeResult(imsegs(test), labels(test), pg, DO_SP, ignore);
cm(ignore, :) = []; cm(:, ignore) = [];

save('~/data/rfexperiments/msrcResult_rf.mat', 'pg', 'acc', 'cm');

end


function [ colorspace ] = get_colorspace( im, fparam, gparam )

    [im_height, im_width, num_im_chan, num_images] = size(im);

    single_im = single(im)/255;

    if strcmp(fparam.colorspace,'gray')
        if num_im_chan == 3
            if num_images == 1
                t_colorspace = rgb2gray(single_im) - 0.5;
            else
                t_colorspace = zeros(im_height, im_width, 1, num_images, 'single');
                for k = 1:num_images
                    t_colorspace(:,:,:,k) = rgb2gray(single_im(:,:,:,k)) - 0.5;
                end
            end
        elseif num_im_chan == 1
            t_colorspace = single_im - 0.5;
        else
            except = MException('get_colorspace','Invalid input data, must have 1 or 3 dimensions');
            throw(except);
        end;
    elseif strcmp(fparam.colorspace,'rgb')
        if num_im_chan == 3
            t_colorspace = single_im - 0.5;
        else
            except = MException('get_colorspace','Invalid input data, must have 3 dimensions for rgb');
            throw(except);
        end;
    end;

    if gparam.use_gpu
        t_colorspace = gpuArray(t_colorspace);
    end

    if gparam.cell_size > 1
        colorspace = average_feature_region(t_colorspace,gparam.cell_size);
    else
        colorspace = t_colorspace;
    end;
end


function [modelCoupled] = coupleRxnList2Rxn(model, rxnList, rxnC, c, u)
% This function adds coupling constraints to the fluxes `vi` of a given list of reactions
% (`RxnList`).The constraints are proportional to the flux `v` of a specified
% reaction `rxnC`, so that for all reactions in `RxnList` `vi ~ vrxnC`.
% For all reactions, a threshold `u` on flux is set (default value: 0.01).
%
% To add a coupling constraint to a reaction, a coupling vector `c` is
% determined (default value 1000). `c` is multiplied by `vrxnC`, so that for
% all irreversible reactions in `RxnList vi - c * vrxnC <= u`.
%
% For all reversible reactions, the following equation holds true for the
% reverse direction: `vi + c * vrxnC >= u`.
%
% The output is a coupled model (`modelCoupled`), in which for every new
% entry in `modelCoupled.b` a "slack" variable has been added
% to `modelCoupled.mets`.
%
% USAGE:
%
%    [modelCoupled] = coupleRxnList2Rxn(model, rxnList, rxnC, c, u)
%
% INPUTS:
%    model:           model structure
%    rxnList:         array of reaction names
%    rxnC:            reaction that should be coupled with each reaction in the
%                     reaction list
%    c:               vector of coupling factors for each rxn in rxnList (default c = 1000)
%    u:               vector of lower bounds one reaction couples (default u = 0.01)
%
% OUTPUT:
%    modelCoupled:    coupled model
%
% .. Authors:
%    - Sept 2011 AH/IT
%    - May 2012: Added a warning if the coupled reaction is not in model. AH

if ~exist('rxnList', 'var') || isempty(rxnList)
    rxnList = model.rxns;
end

if ischar(rxnC)
    rxnC = {rxnC};
end

if ~exist('c', 'var') || isempty(c)
    c = 1000;
end

if ~exist('u', 'var') || isempty(u)
    u = 0.01;
end

nRxnList = numel(rxnList);
% create the constraint IDs.
ctrs = [strcat('slack_',rxnList)';strcat('slack_',rxnList,'_R')'];
ctrs = ctrs(:);
% get those reactions which are not reversible.
[pres,pos] = ismember(rxnList,model.rxns);
revs = model.lb(pos(pres)) < 0;
toRemove = [false(1,nRxnList);~revs'];
toRemove = toRemove(:);

% if rxnC is not part of the rxnList, we add it to the end for constraint
% addition.
if isempty(intersect(rxnList,rxnC))
    rxnList(end+1) = rxnC;
end
% get the rxnC Position;
rxnCID = find(ismember(rxnList,rxnC));

plusminus = [ones(1,nRxnList);-ones(1,nRxnList)];
plusminus = plusminus(:);

% generate the coefficient matrix
coefs = sparse(2*nRxnList,nRxnList + numel(setdiff(rxnC,rxnList)));
% determine the indices for the coefficients.
rxnInd =  [1:nRxnList;1:nRxnList];
rxnInd = rxnInd(:);
constInd = 1:2*nRxnList;
coefs(sub2ind(size(coefs),constInd',rxnInd)) = 1;
% set the coupling coefficients
cs = - plusminus * c;
coefs(:,rxnCID ) = cs;
% determine the senses for the indices
dsenses = [repmat('L',1,nRxnList);repmat('G',1,nRxnList)];
dsenses = dsenses(:);
ds = plusminus * u;

% remove non reversible reactions
ds = ds(~toRemove);
ctrs = ctrs(~toRemove);
coefs = coefs(~toRemove,:);
dsenses = dsenses(~toRemove);

modelCoupled = addCOBRAConstraints(model,rxnList,ds,'c', coefs,'dsense',dsenses, 'ConstraintID',ctrs);


function Map = createMap(Rob,Sen,Opt)

% CREATEMAP Create an empty Map structure.
%   Map = CREATEMAP(Rob,Sen,Lmk,Opt) creates the structure Map from the
%   information contained in Rob, Sen and Lmk, using options Opt. The
%   resulting structure is an EKF map with all empty spaces, able to host
%   all states necessary for Rob, Sen and Lmk. It contains the fields:
%       .used   flags vector to used states in the map
%       .x      state vector
%       .P      covariances matrix
%       .t      current time - used to control time updates

%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.
%   Copyright 2015 Joan Sola @ IRI-UPC-CSIC.

switch lower(Opt.map.type)
    case 'ekf'
        % Help: Map has state and covariances matrix.
        % The state has:
        % - state of each robot
        % - state of each sensor being estimated
        % - state of each landmark
        % The covariances matrix has all cross-variances of the above.

        Map.type = 'ekf';

        RobStates = [Rob.state];
        SenStates = [Sen.state];

        % overall number of states needed to allocate robots, sensors and landmarks
        n = sum([RobStates.size SenStates.size Opt.map.lmkSize*Opt.map.numLmks]);

        Map.used = false(n,1);

        Map.x = zeros(n,1);
        Map.P = zeros(n,n);

    case 'graph'
        % Help: Map has nominal and manifold states.
        % The state has:
        % - state of each pose of the trajectory of each robot
        % - state of each landmark
        % The manifold state has the same, but manifold states.
        % The true state is not stored, but obtained by composing nominal
        % and manifold states.

        % TODO: sensor in map not supported yet.

        Map.type = 'graph';

        RobStates = [Rob.state];

        % overall number of states needed to allocate frames and landmarks
        nf = sum([RobStates.dsize].*Opt.map.numFrames); % number of states for frames
        nl = Opt.map.lmkDSize*Opt.map.numLmks;  % number of states for landmarks
        n = nf + nl;    % total number of states

        % Map occupancy
        Map.used = false(n,1);

        % State and manifold
        Map.x = zeros(n,1);
        Map.P = zeros(n,n);

        switch Opt.solver.decomposition

            case 'Cholesky'
                % Hessian matrix in the manifold
                Map.H  = sparse(n,n);
                Map.R  = sparse(n,n);
                Map.b  = zeros(n,1); % rhs vector.
                Map.mr = []; % range of used states in H

            case 'QR'
                m = 1000;
                Map.A  = sparse(m,n);
                Map.R  = sparse(n,n);
                Map.b  = zeros(m,1); % rhs vector.
                Map.d  = zeros(n,1); % rhs vector.
                Map.mr = []; % range of used states in A
                Map.fr = []; % range of used factors in A
                Map.pr = []; % permutation of re-ordered states in A

            case 'Schur'
                % Hessian matrix in the manifold
                Map.H    = sparse(n,n);
                Map.b    = zeros(n,1); % rhs vector.
                Map.sSff = sparse(nf,nf); % sqrt of the Schur complement
                Map.iHll = sparse(nl,nl); % Inverse of the landmarks Hessian
                Map.mr   = []; % range of used states in H

            otherwise
                error('??? Unknown graph solver ''%s''.', Opt.solver.decomposition)
        end

    otherwise

        error('??? Unknown Map type. Please use ''ekf'' or ''graph''.')

end

Map.t = 0; % Current Map's time

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   SLAMTB is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License
%   along with SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE


function [nodes, edges] = Connections2Graph(uniqueSparse,vertices);
%
%  [nodes, edges] = Connections2Graph(uniqueSparse,vertices);
%
% AUTHOR:  MK/BW
% DATE:    09.06.99
% PURPOSE:
%
%   Compute nodes and edges for gray graph data.  The graph is
% computed from the uniqueSparse matrix created in
% Mesh2GrayGraph, along with the mesh vertices (floats).
% In this routine, the vertices are rounded to be integer
% valued "nodes."
%
% TODO:
% 1.  Figure out which routines break if nodes are not integers.
%
% Vertices must be integers in mrGray and other places.  But,
% the mesh falls on float values.  When we round, some of the
% mesh vertices that are close, fall on the same integer
% node.  This may not happen if we use cube faces.
%
% Possibly, we should scale up the precision by 10 or so.
% Or, possibly, we can keep the precision. I am not sure what
% consequences this will have for mapping data from gLocs3d
% ...  Needs to be thought through.  Who breaks if nodes are
% not integers?
%
% BW 09.05.99
%

% Convert the mrGray format vertices to mrLoadRet format
% Perhaps the rounding has already happened, but that shouldn't
% matter.  If it is arounded by now, then this won't hurt.
%
vertices = mrGray2mrLoadRet(round(vertices));

% The rounding now collapses some of the nodes to the same
% position.  What should we do to remove the case of multiple
% nodes at the same position?
%
% One possibility is to keep them all, say by scaling the
% positions by 10 and holding things as integers.  Another
% possibility is to collapse the vertices once more and combine
% their connections
%
disp('Connections2Graph isn't right yet.');

% NEW numNodes
%
numNodes = size(uniqueSparse,1);

nodes = zeros(8,numNodes);
nodes(1,:) = vertices(:,1)';
nodes(2,:) = vertices(:,2)';
nodes(3,:) = vertices(:,3)';
nodes(4,:) = full(sum(uniqueSparse,2))';
nodes(5,:) = [0 cumsum(nodes(4,1:(numNodes-1)))] +1;
nodes(6,:) = ones(1,numNodes);
%% 7,8 are junk.  No need to fill them.

% The edges are defined with Matlab uses numbering from 1 to N.
%
% This code performs the conversion for all nodes all at once.
% We use the mod operation to find the column number.
% We first subtracting 1 and then mod by numNodes.  This produces
% a column number that runs between ([0,numNodes-1]).  We add 1
% to get back to Matlab numbering.
%
edges = mod((find(uniqueSparse)-1),numNodes)+1;

% keepNodes, and other mrGray functions want the edges to be a
% row, not a column.
%
edges = edges(:)';

return;


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

nsteps = 15;
Vfrac_final = 0.15;
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 [C,u,IA,IC] = randcycle(A)
  % RANDCYCLE Randomly reindexs a list a indices
  %
  % Inputs:
  %   A  #A list of indices with unique values u
  % Outputs:
  %   C  #C list of indices with same unique values u
  %   u,IA,IC  output of unique(A);
  %

  [u,IA,IC] = unique(A);
  % scramble u
  u = u(randperm(end));
  C = u(IC);
end


function testFinalModelsAerts_HN(pathExperiment,fSetNames)
% - paramCells: One cell of parameters for each fSet
% - nameCells: One cell of names for each fSet

startpath = pwd;

cd(pathExperiment), load('training'), load('testing')
cd('FINAL_MODELS'), pathFinalModels = pwd;
nameOutcomes = fieldnames(training); nOutcomes = numel(nameOutcomes);
nFset = numel(fSetNames);

for o = 1:nOutcomes
    for f = 1:nFset
        results = []; results = struct;
        cd(fullfile(pathFinalModels,nameOutcomes{o},[fSetNames{f},'sign']))
        load('finalModel'), load('coeff'), load('response'), order = 4;
        results.model.Name = finalModel.Name; results.model.coeff = coeff; results.model.order = order;
        results.trainData.data = finalModel.Data; results.trainData.response = response; results.trainData.outcome = training.(nameOutcomes{o}).outcome;

        % TESTING MODEL
        outcome = testing.(nameOutcomes{o}).outcome;
        resp = zeros(numel(outcome),1);
        data = zeros(numel(outcome),order);
        for n = 1:order
            data(:,n) = testing.(nameOutcomes{o}).sign.(fSetNames{f})(:,n);
            resp = resp + coeff(n)*data(:,n);
        end
        resp = resp + coeff(end);
        results.testData.data = data; results.testData.response = resp; results.testData.outcome = outcome;
        [AUC,sensitivity,specificity,accuracy] = calcPerformMetrics(resp,outcome,0);
        results.AUC = AUC;
        results.Sensitivity = sensitivity;
        results.Specificity = specificity;
        results.Accuracy = accuracy;
        cd(pathExperiment), save(['testResultsLR_',[fSetNames{f},'sign'],'_',nameOutcomes{o}],'results')
    end
end

cd(startpath)
end


function S = mysign(A)
%MYSIGN True sign function with MYSIGN(0) = 1.

%   Called by various matrices in elmat/private.
%
%   Nicholas J. Higham
%   Copyright 1984-2005 The MathWorks, Inc.
%   $Revision: 1.4.4.1 $  $Date: 2005/11/18 14:15:15 $

S = sign(A);
S(find(S==0)) = 1;


function [flag] = VBA_isBinary (X)
% // VBA toolbox //////////////////////////////////////////////////////////
%
% [flag] = VBA_isBinary (X)
% check if X only contains 0 or 1 values
%
% IN:
%   - X: matrix, cell array of matrices, or structure to be checked
% OUT:
%   - flag: - true if all elements of X are binary (0 or 1)
%           - false otherwise
%           - NaN if any element or field is not numeric
%
% /////////////////////////////////////////////////////////////////////////

switch class (X)
    case 'logical'
        flag = true;

    case 'double'
        flag = all (ismember (X(:), [0, 1]));

    case 'cell'
        flag = all (cellfun (@VBA_isBinary, X));

    case 'struct'
        flag = all (structfun (@VBA_isBinary, X));

    otherwise
        flag = NaN;
end


%% Copyright (C) 2015-2022 Colin B. Macdonald
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy is free software; you can redistribute it and/or modify
%% it under the terms of the GNU General Public License as published
%% by the Free Software Foundation; either version 3 of the License,
%% or (at your option) any later version.
%%
%% This software is distributed in the hope that it will be useful,
%% but WITHOUT ANY WARRANTY; without even the implied warranty
%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
%% the GNU General Public License for more details.
%%
%% You should have received a copy of the GNU General Public
%% License along with this software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @defmethod @@sym cbrt (@var{x})
%% Symbolic cbrt function.
%%
%% Example:
%% @example
%% @group
%% syms x
%% y = cbrt (x)
%%   @result{} y = (sym)
%%       3 ___
%%       ╲╱ x
%% @end group
%% @end example
%%
%% Note: this file is autogenerated: if you want to edit it, you might
%% want to make changes to 'generate_functions.py' instead.
%%
%% @end defmethod

function y = cbrt(x)
  if (nargin ~= 1)
    print_usage ();
  end
  y = elementwise_op ('cbrt', x);
end

%!error cbrt (sym(1), 2)
%!assert (isequaln (cbrt (sym(nan)), sym(nan)))

%!shared x, d
%! d = 2;
%! x = sym('2');

%!test
%! f1 = cbrt(x);
%! f2 = 1.2599210498948731647;
%! assert( abs(double(f1) - f2) < 1e-15 )

%!test
%! D = [d d; d d];
%! A = [x x; x x];
%! f1 = cbrt(A);
%! f2 = 1.2599210498948731647;
%! f2 = [f2 f2; f2 f2];
%! assert( all(all( abs(double(f1) - f2) < 1e-15 )))

%!test
%! % round trip
%! y = sym('y');
%! if (exist ('OCTAVE_VERSION', 'builtin'))
%!   A = cbrt (d);
%! else
%!   % Issue #742
%!   A = d^(1/3);
%! end
%! f = cbrt (y);
%! h = function_handle (f);
%! B = h (d);
%! assert (A, B, -eps)


function [ know, x ] = p30_sol ( n )

%*****************************************************************************80
%
%% P30_SOL returns the solution for problem 30.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 January 2001
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of the problem.  This value
%    is only needed for those problems with variable N.
%
%    Output, integer KNOW.
%    If KNOW is 0, then the solution is not known.
%    If KNOW is positive, then the solution is known, and is returned in X.
%
%    Output, real X(N), the solution, if known.
%
  know = 3;

  r = rand ( ) * 3;

  if ( r <= 1 )
    x = [ -pi, 12.275 ]';
  elseif ( r <= 2 )
    x = [  pi,  2.275 ]';
  else
    x = [ 9.42478, 2.475 ]';
  end

  return
end


function pfplot(X,Factors,Weights,Option);
%PFPLOT plot parafac model
%
% See also:
% 'parafac'
%
%
% pfplot(X,Factors,Weights,Option);
% Different aspects for evaluation of the solution.
%
% Option # = 1
% 1	NOT ACCESIBLE
% 2	NOT ACCESIBLE
% 3	DIAGONALITY PLOT
% 4	PLOTS OF RESIDUAL VARIANCE
% 5	PLOTS OF LEVERAGE
% 6	RESIDUALS (STANDARD DEVIATION) VERSUS LEVERAGE
% 7	NORMAL PROBABILITY PLOT
% 8	LOADING PLOT
%
% You HAVE to input all four inputs. If you have no weights, just input [].
% The last input must be an 8-vector with ones if you want the plot and
% zeros else. E.g.
%
% pfplot(X,factors,[],[0 0 1 0 0 0 0 1]);
%
% to have the diagonality and the loading plot
%

% $ Version 1.02 $ Date 28. July 1998 $ Not compiled $
% $ Version 1.03 $ Date 6. October 1999 $ Changed to handle missing values correctly$
% $ Version 2.00 $ May 2001 $ Changed to array notation $ RB $ Not compiled $

% Copyright (C) 1995-2006  Rasmus Bro & Claus Andersson
% Copenhagen University, DK-1958 Frederiksberg, Denmark, rb@life.ku.dk
%
% This program is free software; you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation; either version 2 of the License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
% You should have received a copy of the GNU General Public License along with
% this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
% Street, Fifth Floor, Boston, MA  02110-1301, USA.

warning off

DimX = size(X);
X = reshape(X,DimX(1),prod(DimX(2:end)));

% Convert to old format
NewLoad = Factors;
ff = [];
for f=1:length(Factors)
  ff=[ff;Factors{f}(:)];
end
Factors = ff;

factors = Factors;
ord=length(DimX);
Fac=length(factors)/sum(DimX);
lidx(1,:)=[1 DimX(1)*Fac];
for i=2:ord
  lidx=[lidx;[lidx(i-1,2)+1 sum(DimX(1:i))*Fac]];
end
if Option(3)==1
  % ESTIMATE DIAGONALITY OF T3-CORE
  diagonality=corcond(reshape(X,DimX),NewLoad,Weights,1);
end
model=nmodel(NewLoad);
model = reshape(model,DimX(1),prod(DimX(2:end)));
if Option(4)==1
  % PLOTS OF RESIDUAL VARIANCE
  figure,eval(['set(gcf,''Name'',''Residual variance'');']);
  aa=ceil(sqrt(ord));bb=ceil(ord/aa);
  for i=1:ord
    r=nshape(reshape(X-model,DimX),i)';
    varian=stdnan(r).^2;
    subplot(aa,bb,i)
    plot(varian)
    if DimX(i)<30
      hold on
      plot(varian,'r+')
    end
    eval(['xlabel(''Mode ', num2str(i),''');']);
    ylabel('Residual variance');
  end
end
if Option(5)==1
  % PLOTS OF LEVERAGE
  figure
  eval(['set(gcf,''Name'',''Leverage'');']);
  aa=ceil(sqrt(ord));
  bb=ceil(ord/aa);
  for i=1:ord
    A=reshape(factors(lidx(i,1):lidx(i,2)),DimX(i),Fac);
    lev=diag(A*pinv(A'*A)*A');
    subplot(aa,bb,i)
    if std(lev)>eps
      plot(lev+100*eps,'+')
      for j=1:DimX(i)
        text(j,lev(j),num2str(j))
      end
    else
      warning('Leverage is constant')
    end
    eval(['xlabel(''Mode ', num2str(i),''');']);
    ylabel('Leverage');
  end
end
if Option(6)==1
  % RESIDUALS (STANDARD DEVIATION) VERSUS LEVERAGE
  figure
  eval(['set(gcf,''Name'',''Residuals vs. Leverages'');']);
  aa=ceil(sqrt(ord));
  bb=ceil(ord/aa);
  for i=1:ord
    subplot(aa,bb,i)
    A=reshape(factors(lidx(i,1):lidx(i,2)),DimX(i),Fac);
    lev=diag(A*pinv(A'*A)*A')'+100*eps;
    r=nshape(reshape(X-model,DimX),i)';
    stand=stdnan(r);
    if std(lev)>eps
      plot(lev,stand,'+')
      for j=1:DimX(i)
        text(lev(j),stand(j),num2str(j))
      end
      eval(['xlabel(''Leverage in mode ', num2str(i),''');']);
      ylabel('Standard deviation');
    else
      warning('Leverage is constant')
    end
  end
end
if Option(7)==1
  % NORMAL PROBABILITY PLOT
  if exist('normplot')
    disp(' ')
    disp(' Normal probability plots are time-consuming')
    disp(' They are made in the statistics toolbox though, so we can''t change that!')
    figure,
    eval(['set(gcf,''Name'',''Normal probability of residuals'');']);
    aa=ceil(sqrt(ord));
    bb=ceil(ord/aa);
    r=nshape(reshape(X-model,DimX),i)';
    r=r(:);
    normplot(r(find(~isnan(r))))
  end
end
if Option(8)==1
  % LOADING PLOT
  if sum(Option)>1
    figure
  end
  eval(['set(gcf,''Name'',''Loadings'');']);
  aa=ceil(sqrt(ord));
  bb=ceil(ord/aa);
  for i=1:ord
    subplot(aa,bb,i)
    A=reshape(factors(lidx(i,1):lidx(i,2)),DimX(i),Fac);
    plot(A)
    eval(['xlabel(''Mode ', num2str(i),''');']);
    ylabel('Loading');
  end
end
drawnow


function P = putcolor00(A00, sizeP)
%------------------------------------------------------------------------------
%
% Gridfunction A00 is upsampled.
%
%
% Design and implementation by:
% Dr. Paul M. de Zeeuw <Paul.de.Zeeuw@cwi.nl>  http://homepages.cwi.nl/~pauldz/
% Last Revision: June 6, 1999.
% (c) 1999-2002 Stichting CWI, Amsterdam
%------------------------------------------------------------------------------
[n, m] = size(A00);
if nargin == 2
  nP = sizeP(1);
  mP = sizeP(2);
  if nP < 2*n-1
    error(' putcolor00 - 1st dimension of P too small ')
  end
  if mP < 2*m-1
    error(' putcolor00 - 2nd dimension of P too small ')
  end
elseif nargin == 1
  nP = 2*n-1;
  mP = 2*m-1;
else
  error(' putcolor00 - wrong number of arguments ')
end
P=reshape(linspace(0,0,nP*mP),nP,mP);
P(1:2:nP, 1:2:mP)=A00;
%------------------------------------------------------------------------------


function [A] = cm2A(cm)
% Convert length from centimeters to angstroms.
% Chad A. Greene 2012
A = cm*100000000;


function g = ceil(f)
%CEIL   Pointwise ceiling of a CHEBFUN.
%   G = CEIL(F) returns the CHEBFUN G such that G(x) = CEIL(F(x)) for each x in
%   F.domain.
%
%   If F is complex, then the G = CEIL(REAL(F)) + 1i*CEIL(IMAG(F)).
%
% See also FLOOR, ROUND, FIX.

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

% Deal with unbounded functions:
if ( ~isfinite(f) )
    error('CHEBFUN:CHEBFUN:ceil:inf', ...
        'Ceil is not defined for functions which diverge to infinity.');
end

g = -floor(-f);

end