function [f,residuals] = corelucydenoiseNew(Y,H,DAMPAR22,wI,READOUT,SUBSMPL,idx,vec,num)
%CORELUCY Accelerated Damped Lucy-Richarson Operator.
%  Calculates function that when used with the scaled projected array
%  produces the next iteration array that maximizes the likelihood that
%  the entire suite satisfies the Poisson statistics.
%
% See also DECONVLUCY and DECONVBLIND.

%  Copyright 1993-2003 The MathWorks, Inc.
%  $Revision: 1.2.4.2 $

%   References
%   ----------
%   "Acceleration of iterative image restoration algorithms, by D.S.C. Biggs
%   and M. Andrews, Applied Optics, Vol. 36, No. 8, 1997.
%   "Deconvolutions of Hubble Space Telescope Images and Spectra",
%   R.J. Hanisch, R.L. White, and R.L. Gilliland. in "Deconvolution of Images
%   and Spectra", Ed. P.A. Jansson, 2nd ed., Academic Press, CA, 1997.

ReBlurred = real(ifftn(H.*fftn(Y)));

% 1. Resampling if needed
if SUBSMPL ~= 1,% Bin ReBlurred back to the sizeI for non-singleton dims

  %1.Reshape so that the-to-binned dimension separates into two
  %dimensions, with one of them consisting of elements of a single bin.
  ReBlurred = reshape(ReBlurred,vec);

  %2. Bin (==calculate mean) along the first of the-to-binned dimension,
  %that dimension consists of the bin elements. Reshape to get rid off
  for k = num,% new appeared singleton.
    vec(k) = [];
    ReBlurred = reshape(mean(ReBlurred,k),vec);
  end

end;

% Define Residual (This part we added, Andre Diamant)

Residual=wI-ReBlurred;
%fprintf('Residual calculated and mean equals %.5f \n',mean(Residual(:)))

% Apply the wavelet xform denoising method

Residual=denoise(Residual,3);
fprintf('DONE: Mean residual equals %.5f \n',mean(Residual(:)))

% 2. An Estimate for the next step
ReBlurred = ReBlurred + READOUT;
ReBlurred(ReBlurred == 0) = eps;
AnEstim = (ReBlurred+Residual)./ReBlurred + eps;

% 3. Damping if needed
if DAMPAR22 == 0,% No Damping
  ImRatio = AnEstim(idx{:});
else % Damping of the image relative to DAMPAR22 = (N*sigma)^2
  gm = 10;
  g = (wI.*log(AnEstim)+ ReBlurred - wI)./DAMPAR22;
  g = min(g,1);
  G = (g.^(gm-1)).*(gm-(gm-1)*g);
  ImRatio = 1 + G(idx{:}).*(AnEstim(idx{:}) - 1);
end;

f = fftn(ImRatio);
residuals = sum(Residual(:));


function [Es,Vs]=subTet(E,V,splitMethod)

% function [Es,Vs]=subTet(E,V,splitMethod)
% ------------------------------------------------------------------------
% Sub devides the input tetrahedral mesh into a denser mesh by splitting
% the elements. Two methods are available. If splitMethod==1 then the faces
% are split similar to what is expected for [Fs,Vs]=subtri(F,V,1,1). I.e.
% for side faces mid-edge nodes are introduced so edges are split. This
% yields 4 new corner tetrahedral elements which could inherit shape
% quality from the original tetrahedral element. However the entire
% tetrahedron cannot me split this way and a central octahedron remains.
% This octahedron is split using its Delaunay tesselation representation
% and yields 4 new tetrahedrons which differ in shape quality from the
% original tetrahedron. If splitMethod==2 the tetrahedron is split into 4
% tetrahedra by introducing a single new central node for each element and
% by connecting the side faces
%
%
% Kevin Mattheus Moerman
% kevinmoerman@hotmail.com
% 2014/03/04
% ------------------------------------------------------------------------

switch splitMethod
    case 1 %Split faces + central delaunay of octahedron
        edgeMat=[E(:,[1 2]); E(:,[2 3]);  E(:,[3 1]); E(:,[1 4]); E(:,[3 4]); E(:,[2 4])]; %Edges matrix
        E_sort=sort(edgeMat,2); %Sorted edges matrix
        [~,ind1,~]=unique(E_sort,'rows');
        edgeMat=edgeMat(ind1,:);

        numPoints = size(V,1);
        numEdges = size(edgeMat,1);

        % Get indices of the three edges associated with each face
        A = sparse(edgeMat(:,1),edgeMat(:,2),(1:numEdges)+numPoints,numPoints,numPoints,numEdges);
        A = max(A,A'); %Copy symmetric

        %Indices for A matrix
        indA_12=E(:,1)+(E(:,2)-1)*numPoints;
        indA_23=E(:,2)+(E(:,3)-1)*numPoints;
        indA_31=E(:,3)+(E(:,1)-1)*numPoints;
        indA_14=E(:,1)+(E(:,4)-1)*numPoints;
        indA_24=E(:,2)+(E(:,4)-1)*numPoints;
        indA_34=E(:,3)+(E(:,4)-1)*numPoints;

        %Get indices for vertex array
        indV_12=full(A(indA_12));
        indV_23=full(A(indA_23));
        indV_31=full(A(indA_31));
        indV_14=full(A(indA_14));
        indV_24=full(A(indA_24));
        indV_34=full(A(indA_34));

        %Create element array
        Es=[E(:,1)  indV_12 indV_31 indV_14;... %Corner tet 1
            indV_12 indV_23 indV_24 E(:,2);... %Corner tet 2
            E(:,3)  indV_31 indV_23 indV_34;... %Corner tet 3
            indV_14 indV_24 indV_34 E(:,4);... %Corner tet 4
            indV_34 indV_31 indV_23 indV_24;... %Octahedral tet 1
            indV_31 indV_12 indV_23 indV_24;... %Octahedral tet 2
            indV_31 indV_12 indV_24 indV_14;... %Octahedral tet 3
            indV_34 indV_31 indV_24 indV_14;... %Octahedral tet 4
            ];

        %Create vertex array
        Vn=0.5*(V(edgeMat(:,1),:)+V(edgeMat(:,2),:)); %new mid-edge points
        Vs = [V; Vn]; %Join point sets

    case 2 %Add central point and connect all faces to central point to yield elements
        %Get faces
        [F,faceInd]=element2patch(E,(1:size(E,1))');

        %Create element array
        Es=[F faceInd+size(V,1)];

        %Create vertex array
        X=V(:,1); Y=V(:,2); Z=V(:,3);
        if size(E,1)==1 %Indexing behaviour (e.g. X(E)) differs for a single element
            Vn=[mean(X(E),1) mean(Y(E),1) mean(Z(E),1)]; %new mid-element points
        else
            Vn=[mean(X(E),2) mean(Y(E),2) mean(Z(E),2)]; %new mid-element points
        end
        Vs = [V; Vn]; %Join point sets
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/>.


function uvPixValidInd = sr_get_uvpix(img, opt)

% SR_GET_UVPIX
%
%

if(ndims(img) == 3)
    img = rgb2gray(img);
end

% Gradient
[imgGx, imgGy] = gradient(img);
imgGx2 = imgGx.^2;
imgGy2 = imgGy.^2;
imgGxy = imgGx.*imgGy;

% Blur
h = fspecial('gaussian',[5 1], 1.5);
imgGx2 = conv2(h, h', imgGx2, 'same');
imgGy2 = conv2(h, h', imgGy2, 'same');

imgGradEng = imgGx2 + imgGy2;
% figure(1); imagesc(imgGradEng > opt.gradThres);
imgGradEng = imgGradEng(opt.pRad+1:end-opt.pRad ,opt.pRad+1:end-opt.pRad);

uvPixValidInd = imgGradEng(:) > opt.gradThres;

end


% Approximates X = INV(A)*Y by a truncated series.
function x = linsolve_neumann(A,y,D,n)

if nargin < 3 && isnumeric(A)
  tol = 1e-6;
  D = (1+tol)*normest(A,tol); % this is probably veeeery bad...
end
if nargin < 4
  n = 100;
end

if isnumeric(D)
  if numel(D) == 1
    D = D*speye(length(y));
  end
  D = @(x) D\x;
end

if isnumeric(A)
  A = @(x) A*x;
end

z = D(y);
x = z;
for i=1:n
  z = z - D(A(z));
  x = x + z;
end


function [h, hdata] = hbayes(net, hdata)
%HBAYES	Evaluate Hessian of Bayesian error function for network.
%
%	Description
%	H = HBAYES(NET, HDATA) takes a network data structure NET together
%	the data contribution to the Hessian for a set of inputs and targets.
%	It returns the regularised Hessian using any zero mean Gaussian
%	priors on the weights defined in NET.  In addition, if a MASK is
%	defined in NET, then the entries in H that correspond to weights with
%	a 0 in the mask are removed.
%
%	[H, HDATA] = HBAYES(NET, HDATA) additionally returns the data
%	component of the Hessian.
%
%	See also
%	GBAYES, GLMHESS, MLPHESS, RBFHESS
%

%	Copyright (c) Ian T Nabney (1996-2001)

if (isfield(net, 'mask'))
  % Extract relevant entries in Hessian
  nmask_rows = size(find(net.mask), 1);
  hdata = reshape(hdata(logical(net.mask*(net.mask'))), ...
     nmask_rows, nmask_rows);
  nwts = nmask_rows;
else
  nwts = net.nwts;
end
if isfield(net, 'beta')
  h = net.beta*hdata;
else
  h = hdata;
end

if isfield(net, 'alpha')
  if size(net.alpha) == [1 1]
    h = h + net.alpha*eye(nwts);
  else
    if isfield(net, 'mask')
      nindx_cols = size(net.index, 2);
      index = reshape(net.index(logical(repmat(net.mask, ...
         1, nindx_cols))), nmask_rows, nindx_cols);
    else
      index = net.index;
    end
    h = h + diag(index*net.alpha);
  end
end


% dbm_get_hidden_raw
% Copyright (C) 2011 KyungHyun Cho, Tapani Raiko, Alexander Ilin
%
%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.
%
function [h_mf] = dbm_get_hidden_raw(x0, binary, layers, ...
    W, biases, sigmas, ...
    max_iter, tol, reg, ...
    do_centering, centers)

layers = layers;
n_layers = length(layers);

h_mf = cell(n_layers, 1);
h_mf{1} = x0;

for l = 2:n_layers
    if l == n_layers
        mult = 1;
    else
        mult = 2;
    end
    if l == 2
        if binary == 1
            h_mf{l} = sigmoid(bsxfun(@plus, mult * h_mf{l-1} * W{l-1}, biases{l}'));
        else
            h_mf{l} = sigmoid(bsxfun(@plus, mult * bsxfun(@rdivide, h_mf{l-1}, sigmas.^2') * W{l-1}, biases{l}'));
        end
    else
        h_mf{l} = sigmoid(bsxfun(@plus, mult * h_mf{l-1} * W{l-1}, biases{l}'));
    end
end

h_mf_prev = h_mf;

for iter = 1:max_iter
    diff_err = 0;
    for oddeven = [0 1]
        for l = 2:n_layers
            if mod(l, 2) == oddeven
                continue;
            end
            h_mf{l} = h_mf{l} * 0;
            if do_centering
                if l > 1
                    if l == 2
                        if binary == 1
                            h_mf{l} = h_mf{l} + bsxfun(@minus, h_mf{l-1}, centers{l-1}') * W{l-1};
                        else
                            h_mf{l} = h_mf{l} + bsxfun(@rdivide, h_mf{l-1}, sigmas.^2') * W{l-1};
                        end
                    else
                        h_mf{l} = h_mf{l} + bsxfun(@minus, h_mf{l-1}, centers{l-1}') * W{l-1};
                    end
                end

                if l < n_layers
                    h_mf{l} = h_mf{l} + bsxfun(@minus, h_mf{l+1}, centers{l+1}') * W{l}';
                end
            else
                if l > 1
                    if l == 2
                        if binary == 1
                            h_mf{l} = h_mf{l} + h_mf{l-1} * W{l-1};
                        else
                            h_mf{l} = h_mf{l} + bsxfun(@rdivide, h_mf{l-1}, sigmas.^2') * W{l-1};
                        end
                    else
                        h_mf{l} = h_mf{l} + h_mf{l-1} * W{l-1};
                    end
                end

                if l < n_layers
                    h_mf{l} = h_mf{l} + h_mf{l+1} * W{l}';
                end
            end

            h_mf{l} = sigmoid(bsxfun(@plus, h_mf{l}, biases{l}'));

            if reg > 0
                h_mf{l} = max(h_mf{l} - reg, 0);
            end

            diff_err = diff_err + sum(sum((h_mf_prev{l} - h_mf{l}).^2));
        end
    end

    %fprintf(2, '%d\n', diff_err);

    if diff_err < tol
        break;
    end

    h_mf_prev = h_mf;
end

clear h_mf_prev;


function kern = linKernParamInit(kern)

% LINKERNPARAMINIT LIN kernel parameter initialisation.
% The linear kernel (LIN) is the simple inner product
% kernel. Sampling from this kernel produces linear functions.
%
% k(x_i, x_j) = sigma2 * x_i'*x_j
%
% There is one parameter, sigma2, which is stored in the field
% kern.variance.
%
% SEEALSO : linardKernParamInit
%
% FORMAT
% DESC initialises the linear
%  kernel structure with some default parameters.
% ARG kern : the kernel structure which requires initialisation.
% RETURN kern : the kernel structure with the default parameters placed in.
%
% SEEALSO : kernCreate, kernParamInit
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006

% KERN

kern.variance = 1;
kern.nParams = 1;

kern.transforms.index = 1;
kern.transforms.type = optimiDefaultConstraint('positive');

kern.isStationary = false;


function a = reshape(a,new_size,old_modes)
%RESHAPE Reshape sparse tensor.
%
%  RESHAPE(X,SIZ) reshapes the sparse tensor to the given size. PROD(SIZ)
%  must be the same as PROD(SIZE(X)).
%
%  RESHAPE(X,SIZ,MODES) reshapes only the specifies modes and appends the
%  new reshaped modes to the end of the indices.
%
%  See also SPTENSOR, SPTENSOR/PERMUTE, RESHAPE.
%
%MATLAB Tensor Toolbox.
%Copyright 2012, Sandia Corporation.

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

if ~exist('old_modes','var')
    old_modes = 1:ndims(a);
    keep_modes = [];
else
    keep_modes = setdiff(1:ndims(a),old_modes);
end
old_size = a.size(old_modes);
keep_size = a.size(keep_modes);

if prod(new_size) ~= prod(old_size)
    error('prod(SIZ) must be the same size of prod(SIZE(X,MODES))');
end

inds = tt_sub2ind(old_size,a.subs(:,old_modes));
new_subs = tt_ind2sub(new_size,inds);

a.size = [keep_size new_size];
a.subs = [a.subs(:,keep_modes) new_subs];


function mdsfig_3d(X,names,clus,linemat,cordir)
% ::
%
%    mdsfig_3d(X,names,clus,linemat,cordir)
%
% 3-D MDS figure
%
% Subfunction of mdsfig used if 3+ dims are available

numel=size(X,1); %%% define scaling %%%%%%%
a=X(:,1);b=X(:,2);c=X(:,3);
axa=ones(numel,1)*mean(a);
axb=ones(numel,1)*mean(b);
axc=ones(numel,1)*mean(c);
axa1=min(a):(max(a)-min(a))/(numel-1):max(a);
axb1=min(b):(max(b)-min(b))/(numel-1):max(b);
axc1=min(c):(max(c)-min(c))/(numel-1):max(c);

%%% plotting defaults %%%%
f1=figure('Color','w');
hold on;
set(gca,'FontSize',12);
colors = {'ro' 'go' 'bo' 'yo' 'co' 'mo' 'ko' 'r^' 'g^' 'b^' 'y^' 'c^' 'm^' 'k^'};
while max(clus) > length(colors), colors = [colors colors];,end

%draw central axes & scale
plot3(axa,axb,axc1,'color','k','linewidth',2);
plot3(axa,axb1,axc,'color','k','linewidth',2);
plot3(axa1,axb,axc,'color','k','linewidth',2);
axis([min(a) max(a) min(b) max(b) min(c) max(c)]);

%%% plot lines %%%%%%

drawlines(X,linemat,0,{'Positive' 'Negative'});

%%%% plot points %%%%
for j = 1:size(X,1);
    plot3(a(j),b(j),c(j),colors{clus(j)},'MarkerFaceColor',colors{clus(j)}(1),'Markersize',8);
end

if ~isempty(names);
for i = 1:size(X,1)
    text(X(i,1)+.025*[max(X(:,1))-min(X(:,1))],X(i,2)+.0,X(i,3)+.0,names{i},'Color','k','FontSize',12,'FontWeight','bold');
end
end

rotate=1;
if rotate
% rotate until closed
for v=1:45;
    if ishandle(f1);
        view(v,35);
        drawnow;
        pause (0.2)
        if v==44
            v==1;
            continue
        end
    else
        break
    end
end
end

% Second Figure -- different dims

tor_fig(2,2);hold off;
subplot(2,2,1);
mdsfig(X(:,[1 2]),names,clus,linemat);
subplot(2,2,2);
mdsfig(X(:,[1 3]),names,clus,linemat);
subplot(2,2,3);
mdsfig(X(:,[2 3]),names,clus,linemat);

subplot(2,2,4);
if size(X,2) > 3,
    mdsfig(X(:,[1 4]),names,clus,linemat);
else
    axis off
end

return

function [hhp,hhn] = drawlines(pc,sigmat,sigcol,legmat,varargin)

% sigcol is a scalar between zero and one, lower is 'more salient'
hold on

% linew
lw = 3;

color(1,:) = [0 0 0];   % first line color, 'positive'
color(2,:) = [0 .7 1];   % second line color, 'negative'
style{1} = '-';         % first line style
style{2} = '-';         % second line style

if length(varargin) > 0, color = varargin{1}; end
if length(varargin) > 1, style = varargin{2}; sigcol = 0; end

hhp=[];hhn=[];
for i=1:size(pc,1);
     for j=1:size(pc,1);
         if sigmat(i,j) > 0
             hhp = line([pc(i,1) pc(j,1)],[pc(i,2) pc(j,2)]);
             set(hhp,'Color',color(1,:) + [1 1 1] * abs(sigcol),'LineStyle',style{1},'LineWidth',lw - (lw*sigcol)-1)
         elseif sigmat(i,j) < 0
             hhn = line([pc(i,1) pc(j,1)],[pc(i,2) pc(j,2)]);
             set(hhn,'Color',color(2,:) + abs([sigcol sigcol 0]),'LineStyle',style{2},'LineWidth',lw - (lw*sigcol)-1)
         end
     end
end
legend ([hhp hhn],legmat);
return


function test_suite = test_survival_weibull

%   Run specific demo and save values for comparison.
%
%   See also
%     TEST_ALL, DEMO_SURVIVAL_WEIBULL

% Copyright (c) 2011-2012 Ville Tolvanen

initTestSuite;

function testDemo
% Set random number stream so that failing isn't because randomness. Run
% demo & save test values.
prevstream=setrandstream(0);

disp('Running: demo_survival_weibull')
demo_survival_weibull;
path = which('test_survival_weibull.m');
path = strrep(path,'test_survival_weibull.m', 'testValues');
if ~(exist(path, 'dir') == 7)
    mkdir(path)
end
path = strcat(path, '/testSurvival_weibull');
save(path, 'Ef1', 'Ef2', 'Varf1', 'Varf2');

% Set back initial random stream
setrandstream(prevstream);
drawnow;clear;close all

% Compare test values to real values.

function testPredictionsWeibull
values.real = load('realValuesSurvival_weibull', 'Ef1', 'Varf1', 'Ef2', 'Varf2');
values.test = load(strrep(which('test_survival_weibull.m'), 'test_survival_weibull.m', 'testValues/testSurvival_weibull'), 'Ef1', 'Varf1', 'Ef2', 'Varf2');
assertElementsAlmostEqual(values.real.Ef1, values.test.Ef1, 'relative', 0.10);
assertElementsAlmostEqual(values.real.Ef2, values.test.Ef2, 'relative', 0.10);
assertElementsAlmostEqual(values.real.Varf1, values.test.Varf1, 'relative', 0.10);
assertElementsAlmostEqual(values.real.Varf2, values.test.Varf2, 'relative', 0.10);


function [Y, X] = max2( f )
%MAX2   Global maximum of a SEPARABLEAPPROX.
%   Y = MAX2(F) returns the global maximum of F over its domain.
%
%   [Y, X] = MAX2(F) returns the global maximum in Y and its location X.
%
%  This command may be faster if the OPTIMIZATION TOOLBOX is installed.
%
% See also MIN2, MINANDMAX2.

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

% Check for empty:
if ( isempty( f ) )
    return
end

% Call MINANDMAX2:
[Y, X] = minandmax2(f);

% Extract out maximum:
Y = Y(2);
X = X(2,:);

end


% Copyright 2009 - 2010 The MathWorks, Inc.
function ObjTrack01(position)
%#eml
% Figure setup
numPts = 300;
figure;hold;grid;

% Kalman filter loop
for idx = 1: numPts
    % Get the input data
    z = position(:,idx);

    % Use Kalman filter to estimate the location
    y = kalman01(z);

    % Plot the results
    plot_trajectory(z,y);
end
hold;
end


function shepard_sr_x3_configure()
    global config;
    % general configurations for both training and testing
    config.input_size = [48 48];
    config.chs = 1;
    config.forward_pass_scheme = {'conv_v_mask_norm', 'conv_v', 'conv_v', 'conv_f', 'out'};
    config.mask_for_SR = 'true';
    config.misc.mask_type = 9; % 3x super-resolution

    config.nonlinearity = 'relu';   % 'relu', 'tanh', 'sigmoid'
    config.output_activation = 'nil';   % 'softmax', 'inherit', 'nil'
    config.cost_function = 'L2 norm'; % 'cross entropy', 'L2 norm'
    config.kernel_size = [8 8; 9 9; 1 1; 8 8];
    config.conv_hidden_size = [16 512 512];
    config.full_hidden_size = [];
    config.output_size = [40 40 1];
    config.batch_size = 10;
    config.compute_device = 'GPU';

    % the following items are only for training
    config.learning_rate = 0.001;
    config.weight_range = 0.03;
    config.decay = 5e-7 / 10;
    config.normalize_init_weights = 0;
    config.dropout_full_layer = 0;
    config.optimization = 'adagrad';
end


function e = p2e (u)
e = u(1:2,:) ./ ([1;1] * u(3,:));
return


function generator_order1_norad_no(filenameout,GeneratedYears,TempScheme,idistr,...
    ap00,ap10,alambda,nu,A,B,aC0,aC1,aC2,aD1,aD2,sC0,sC1,sC2,sD1,...
    sD2,PrecipThreshold,MarkovChainOrder)
%
%  THIS PROGRAM GENERATES DAILY TIME SERIES OF PRECIPITATION, MAX AND MIN
%  TEMPERATURES. PARAMETERS OF THE MODEL HAVE BEEN CALCULATED BY THE
%  WEATHER ANALYZER PROGRAM. A RANDOM GENERATOR APPROACH IS USED TO CREATE
%  SYNTHETIC TIME SERIES

% the preciptiation occurrence is generated using the first order markov
% chain and the parameters are not smoothed from 14 days to daily scale with
% this weather generator

% 'filenameinter' is a string and is the filename that contains all variables
% saved from the analyzer (analyzer_order1_norad.m).
%
% this version uses a first order Markov chain for precipitation occurence
%
% 'filenameout' is the filename (string) to save the generated variables
% gP, gTmax, gTmin

Y=GeneratedYears;
h = waitbar(0,'Initialisation...');

A=A';
B=B';
waitbar(0.1,h);
%
% generation of time series

% time series for precipitation
%
%  create vectors of daily p00, p10, lbd values from Fourier series
%
day=1:365;
tot=365*Y;
t=1:tot;
T=365/(2*pi);
waitbar(0.2,h);
p00=zeros(Y,356);
p10=zeros(Y,365);
mm=1;
nn=1;
for i=1:14:364
    p00(1,mm:mm+13)=ap00(nn);
    p10(1,mm:mm+13)=ap10(nn);
    mm=mm+14;
    nn=nn+1;
end
p00(1,365)=ap00(26);
p10(1,365)=ap10(26);

for i=2:Y
    p00(i,:)=p00(1,:);
    p10(i,:)=p10(1,:);
end
p00=p00';
p00=reshape(p00,1,[]);

p10=p10';
p10=reshape(p10,1,[]);

waitbar(0.5,h);
p01=1-p00;

waitbar(0.8,h);
p11=1-p10;
%
% add one element to vectors p00, p01, p10 and p11 to avoid putting an if
% statement in the loop to generate time series of wet dry days
%
p00(tot+1)=0;
p01(tot+1)=p00(tot+1);
p10(tot+1)=p00(tot+1);
p11(tot+1)=p00(tot+1);

lbd=zeros(Y,356);
mm=1;
nn=1;
for i=1:14:364
    lbd(1,mm:mm+13)=alambda(nn);
    mm=mm+14;
    nn=nn+1;
end
lbd(1,365)=alambda(26);

for i=2:Y
    lbd(i,:)=lbd(1,:);
end
lbd=lbd';
lbd=reshape(lbd,1,[]);

if idistr == 2
    anu=nu;
    nu=zeros(Y,356);
    mm=1;
    nn=1;
    for i=1:14:364
        nu(1,mm:mm+13)=anu(nn);
        mm=mm+14;
        nn=nn+1;
    end
    nu(1,365)=anu(26);
    for i=2:Y
        nu(i,:)=nu(1,:);
    end
    nu=nu';
    nu=reshape(nu,1,[]);
end
waitbar(1,h);
close(h);
%
% generate time series of dry (X=0) and wet (X=1) days
% pn is the marginal distribution of X on day n
%
% assume that day 0 is dry.  state=0 when day is dry,  state=1 when day is wet
%
state=0;
%
% loop to generate time series
%
n=Y*365;
% iwet=0; % fbri7
X=zeros(1,n); % fbri7

h = waitbar(0,'Generation of precipitation occurrence...');
wbt=round(n/100);

for i=1:n
   % generate random number from uniform distribution
    Ru(i,1)=rand(1);
	% establish which of p00 or p10 tu use
    if state == 0
        % day i-1 is dry, use p00
        Pr=p00(i);
    else
        % day i-1 is wet, use p10
        Pr=p10(i);
    end
    % establish if day i is dry or wet
   if Ru(i,1) <= Pr;
      % dry day
      state=0;
   else
      % wet day
      X(i)=1;
      state=1;
   end
   if i/wbt - round(i/wbt) == 0   % update waitbar at every 100th interval
       waitbar(i/n,h);
   end
end

close(h);
clear p00 p01 p10 p11;

XX=find(X==1);
nw=length(XX);
%
% generate time series of precipitation amounts
%
tol=0.00001;    % tolerance criteria for iteration
r=zeros(1,n);

h = waitbar(0,'Generation of precipitation quantity...');
wbt=round(nw/100);

if idistr == 1
    %
    % assuming exponential distribution
    %
    for i=1:nw
       P=rand(1);
       r(XX(i))=-log(1-P)/lbd(XX(i));
       if i/wbt - round(i/wbt) == 0   % update waitbar every 1/100th
            waitbar(i/(nw*1.1),h);  % waitbar at 90% after this step
       end
    end
else
    %
    % assuming 2-parameter gamma distribution
    %
    for i=1:nw  % for each wet day, draw a random number and get precip using
                % inverse of gamma CDF
       % Px=rand(1);
       Px(i,1)=rand(1);
       r(XX(i))=gaminv(Px(i,1),nu(XX(i)),1/lbd(XX(i)));
       if i/wbt - round(i/wbt) == 0   % update waitbar every 1/100th
           waitbar(i/(nw*1.1),h);      % waitbar at 90% after this step
       end
    end
end

clear lbd;
%
%  time series of min temperature and max temperature
%
%  we first generate the fourier estimates of average and standard deviations
%  of the time series
%
for j=1:4
   ay(j,:)=aC0(j)+aC1(j)*sin(t/T+aD1(j))+aC2(j)*sin(2*t/T+aD2(j));
   sy(j,:)=sC0(j)+sC1(j)*sin(t/T+sD1(j))+sC2(j)*sin(2*t/T+sD2(j));
   waitbar(0.9+j*0.025,h);
end
clear t;
%
%  procedure is started by assuming that the residuals are equal to 0
%  random component eps is normally distributed N(0,1)
%
res=[0; 0];
ksi=zeros(2,n);  % fbri7

close(h);
h = waitbar(0,'Generation of Tmin, Tmax...');
wbt=round(n/100);

for i=1:n
   eps=randn(2,1);
   res=A*res+B*eps;
   ksi(:,i)=res;
   if i/wbt - round(i/wbt) == 0   % update waitbar every 1/100th
       waitbar(i/(n*1.33),h);          % waitbar at 75% when this step is over
   end
end
%
% the means and standard deviations obtained by Fourier time series are conditioned
% on the wet or dry status of the day determined by using the Markov chain model
%
v=ones(2,1);
XX=kron(v,X);
waitbar(0.78,h);
clear X;

cay=XX.*ay(1:2,:)+(1-XX).*ay(3:4,:);
waitbar(0.83,h);
clear ay;
csy=XX.*sy(1:2,:)+(1-XX).*sy(3:4,:);
waitbar(0.86,h);
clear sy XX;
%
if TempScheme==1;
    % the daily values of the three weather variables are found by multiplying the
    % residuals by the standard deviation and adding the mean
    %
    Xp=ksi.*csy+cay;
    clear cay csy ksi;
    Tmax=Xp(1,:);
    Tmin=Xp(2,:);
    clear Xp;
    % insure that Tmin is always smaller than Tmax (diff arbitrarily set up at 1)
    t0=find(Tmax-Tmin < 1);
    Tmin(t0)=Tmax(t0)-1;
elseif TempScheme==2;
    % the Tmax and Tmin are generated conditioned on each other (Jie Chen modified)
    % the smaller standard deviation of Tmax or Tmin is used as a base, and the
    % other parameter is generated conditioned on the chosen parameter. If the
    % standard deviation of Tmax is larger than or equal to the standard
    % deviation of Tmin, daily temperatures are generated by:
    % Tmin=Mean(min)+Std(min)*rand
    % Tmax=Tmin+(Mean(max)-Mean(min))+(Std(max)^2-Std(min)^2)^0.5*rand
    % If the standard deviation of Tmax is less than those of Tmin, daily
    % temperatures are genareted by:
    % Tmax=Mean(max)+Std(max)*rand
    % Tmin=Tmax-(Mean(max)-Mean(min))-(Std(min)^2-Std(max)^2)^0.5*rand

    for i=1:length(ksi)
        if csy(1,i)>=csy(2,i)
            Xp(2,i)=ksi(2,i)*csy(2,i)+cay(2,i);
            Xp(1,i)=ksi(1,i)*(csy(1,i)^2-csy(2,i)^2)^(1/2)+(cay(1,i)-cay(2,i))+Xp(2,i);
        else
            Xp(1,i)=ksi(1,i)*csy(1,i)+cay(1,i);
            Xp(2,i)=ksi(2,i)*(csy(2,i)^2-csy(1,i)^2)^(1/2)-(cay(1,i)-cay(2,i))+Xp(1,i);
        end
    end

    % range control the Tmin, insure that Tmin is always small than Tmax
    for i=1:length(ksi)
        if Xp(1,i)<=Xp(2,i)
            Xp(2,i)=Xp(1,i)-abs(Xp(1,i))*0.2;
        end
    end
    Tmax=Xp(1,:);
    Tmin=Xp(2,:);
end

waitbar(0.9,h);
%
% store results in matrices of size [nYears 365]
%
gP=reshape(r,365,Y);
gP=gP';
clear r;
waitbar(0.93,h);

jj=find(gP>0);   % add precipitation threshold
gP(jj)=gP(jj)+PrecipThreshold;
clear jj;

gTmax=reshape(Tmax,365,Y);
gTmax=gTmax';
waitbar(0.96,h);
clear Tmax;
gTmin=reshape(Tmin,365,Y);
gTmin=gTmin';
clear Tmin;
%
% plot the first year results
figure
subplot(2,1,1)
bar(day,gP(1,:))
ylabel('daily precip. mm')
titre=['Generated daily precip of the first year'];
title(titre)
subplot(2,1,2)
plot(day,gTmax(1,:),day,gTmin(1,:),'r-')
ylabel('air temp,oC')
titre=['Generated daily Tmax and Tmin of the first year'];
title(titre)
legend('Tmax','Tmin','Location','Best')
%
% store results in files
%
save(filenameout,'gP','gTmax','gTmin');    % results stores in matrices [nYears 365]

waitbar(1,h);

close(h);


d = 500;
A = randn(d);
b = randn(d,1);
niter = 100;
fprintf('cols:')
tic; for i = 1:niter scale_cols(A,b); end; toc
fprintf('rows:')
tic; for i = 1:niter scale_rows(A,b); end; toc


function [ftH2O] = MPa2ftH2O(MPa)
% Convert pressure from megapascals to feet of water column.
% Chad Greene 2012
ftH2O = MPa*334.553;


function [M, inliers] = RANSAC2(x, fittingfn, distfn, degenfn, s, t, index, validMask)

    maxTrials = 1000;
    maxDataTrials = 100;

    [rows, npts] = size(x);

    % Desired probability of choosing at least one sample free from outliers (probably should be a parameter)
    p = 0.99;

    bestM = NaN;
    trialcount = 0;
    bestscore =  0;
    N = 1;

    while N > trialcount

        % Select at random s datapoints to form a trial model, M.
        degenerate = 1;
        count = 1;
        while degenerate
            % Generate s random indicies in the range 1..npts
            ind = zeros(s, 1);
%             ind = randsample(npts, s);
            for i = 1:s
                pick = randsample(npts, 1);
                while validMask(index(pick)) == 0 || any(ind == pick) || any(index(ind(ind > 0)) == index(pick))
                    pick = randsample(npts, 1);
                end
                ind(i) = pick;
            end

            % Test that these points are not a degenerate configuration.
            degenerate = feval(degenfn, x(:,ind));

            if ~degenerate
                M = feval(fittingfn, x(:,ind));
                if isempty(M)
                    degenerate = 1;
                end
            end

            % Safeguard against being stuck in this loop forever
            count = count + 1;
            if count > maxDataTrials
                disp('Unable to select a nondegenerate data set');
                break
            end
        end

%         if scoreX1 ~= 0
%             l = min([scoreX1(ind) scoreX2(ind)]);
%             t = (l + 0.6) * t;
%         end

        [inliers, score, M] = feval(distfn, M, x, t, index, validMask);

        % Find the number of inliers to this model.
        ninliers = length(inliers);

        if score >= bestscore
            bestscore = score;
            bestinliers = inliers;
            bestM = M;

            % Update estimate of N
            fracinliers =  ninliers/npts;
            pNoOutliers = 1 -  fracinliers^s;
            pNoOutliers = max(eps, pNoOutliers);
            pNoOutliers = min(1-eps, pNoOutliers);
            N = log(1-p)/log(pNoOutliers);
        end

        trialcount = trialcount+1;

        % Safeguard against being stuck in this loop forever
        if trialcount > maxTrials
            fprintf('ransac reached the maximum number of %d trials\n', maxTrials);
            break
        end

        %fprintf('Iter: %d \n', trialcount);
    end

    if ~isnan(bestM)
        M = bestM;
        inliers = bestinliers;
    else
        M = [];
        inliers = [];
        disp('ransac was unable to find a useful solution');
    end
end


function c8_le_li_test ( )

%*****************************************************************************80
%
%% C8_LE_LI_TEST tests C8_LE_LI.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2015
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'C8_LE_LI_TEST\n' );
  fprintf ( 1, '  C8_LE_LI evalues (C1 <= C2) using the Loo norm.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '        C1=C8_UNIFORM_01          C2=C8_UNIFORM_01         L3=C8_LE_LI(C1,C2)\n' );
  fprintf ( 1, '     ---------------------     ---------------------     ---------------------\n' );
  fprintf ( 1, '\n' );

  seed = 123456789;

  for test = 1 : 10

    [ c1, seed ] = c8_uniform_01 ( seed );
    [ c2, seed ] = c8_uniform_01 ( seed );
    l3 = c8_le_li ( c1, c2 );

    fprintf ( 1, '  %12.4f,%12.4f  %12.4f,%12.4f          %d\n', ...
      real ( c1 ), imag ( c1 ), real ( c2 ), imag ( c2 ), l3 );

  end

  return
end


function visualizeCellVectors2D(phi_cell)
%VISUALIZECELLS plots the values of cell variable phi
%
% SYNOPSIS:
%   visualizeCellVectors2D(phi_cell)
%
% PARAMETERS:
%   phi_cell: CellVector
%
% RETURNS:
%   None
%
% EXAMPLE:
%
% SEE ALSO:
%

% Written by Ali A. Eftekhari
% See the license file

x = phi_cell.domain.cellcenters.x;
y = phi_cell.domain.cellcenters.y;

quiver(x,y,phi_cell.xvalue', phi_cell.yvalue');
axis equal tight
xlabel('Cell centers [x values]');
ylabel('Cell centers [y values]');
%colorbar


function varargout=nmf_classic(v,winit,hinit,peval,verbose)
%
% Jean-Philippe Brunet
% Cancer Genomics
% The Broad Institute
% brunet@broad.mit.edu
%
% This software and its documentation are copyright 2004 by the
% Broad Institute/Massachusetts Institute of Technology. All rights are reserved.
% This software is supplied without any warranty or guaranteed support whatsoever.
% Neither the Broad Institute nor MIT can not be responsible for its use, misuse,
% or functionality.
%
% NMF divergence update equations :
% Lee, D..D., and Seung, H.S., (2001), 'Algorithms for Non-negative Matrix
% Factorization', Adv. Neural Info. Proc. Syst. 13, 556-562.
%
% v (n,m) : N (genes) x M (samples) original matrix
%           Numerical data only.
%           Must be non negative.
%           Not all entries in a row can be 0. If so, add a small constant to the
%           matrix, eg.v+0.01*min(min(v)),and restart.
%
% r       : number of desired factors (rank of the factorization)
%
% verbose : prints iteration count and changes in connectivity matrix elements
%           unless verbose is 0
%
% Note : NMF iterations stop when connectivity matrix has not changed
%        for 10*stopconv interations. This is experimental and can be
%        adjusted.
%
% w    : N x r NMF factor
% h    : r x M NMF factor
%
% winit - initial value for w
% hinit - initial value for h
% peval.h_fixvec & peval.w_fixvec:
% fixvec - vector which component should be fixed: eg [2 3] will
% fix second and third component while varying the first...
fprintf('Classic NMF iterations\n')

if ~isfield(peval, 'ddterm'); peval.ddterm = 1; end %termination criterion
if ~isfield(peval, 'maxiter'); peval.maxiter = 1000; end

% test for negative values in v
if min(min(v)) < 0
    error('matrix entries can not be negative');
    return
end
if min(sum(v,2)) == 0
    error('not all entries in a row can be zero');
    return
end

[n,m]=size(v);

if ~isempty(peval.w_fixvec)
    fprintf('Fixing [ ');
    fprintf('%g ', peval.w_fixvec);
    fprintf('] component of ''w''\n');
end

if ~isempty(peval.h_fixvec)
    fprintf('Fixing [ ');
    fprintf('%g ', peval.h_fixvec);
    fprintf('] component of ''h''\n');
end

w = winit;
h = hinit;

d(1) = ddivergence(v, w*h);
htrace(1,:,:) = hinit;

w_vec = 1:size(w,2);
peval.w_dovec = find(~(w_vec==peval.w_fixvec));

h_vec = 1:size(h,1);
peval.h_dovec = find(~(h_vec==peval.h_fixvec));

for ii=2:peval.maxiter

    w_old = w;
    h_old = h;

    sumH_t = sum(h(peval.h_dovec,:),2);
    sumH_t_sq = sum(sumH_t.^2);
    sumH= sum(sumH_t);
    nh = length(peval.h_dovec);
    sparsity_h = (sqrt(nh) - sumH/sqrt(sumH_t_sq))/(sqrt(nh)-1); % [Hoyer 2004]

    gradspars=(1/(sqrt(nh)-1))*(sumH/(sumH_t_sq)^1.5*sumH_t - 1/(sqrt(sumH_t_sq)));
    gradspars_kt = repmat(gradspars, 1, m);

    x1=repmat(sum(w,1)',1,m);
    y1=w'*(v./(w*h));
    h(peval.h_dovec,:)=h(peval.h_dovec,:).*(y1(peval.h_dovec,:))./x1(peval.h_dovec,:)+peval.alpha_sparsity*gradspars_kt;
    h=max(h,eps); % adjust small values to avoid undeflow

    x2=repmat(sum(h,2)',n,1);
    y2=(v./(w*h))*h';
    w(:,peval.w_dovec)=w(:,peval.w_dovec).*(y2(:,peval.w_dovec))./x2(:,peval.w_dovec);
    w=max(w,eps); % adjust small values to avoid undeflow

    % normalization of all h:
    sumw = sum(w,1);
    w = w./repmat(sumw,n,1); %normalization of each component
%     h = h.*repmat(sumw',1,m); %to keep the multiplication equal

    %     wtrace(:,:,ii) = w;
    %     htrace(:,:,ii) = h;

    d(ii) = ddivergence(v, w*h) + peval.alpha_sparsity*sparsity_h;
    dd(ii) = abs(d(ii)-d(ii-1));
    htrace(ii,:,:)=h;
    if dd(ii) < peval.ddterm
        break
    end
    if verbose
        fprintf('Cycle %g D-divergence %g\n',ii-1,d(ii))
    end
end

peval.numiter = ii;
peval.maxiter_reached_flag = 0;
if ii == peval.maxiter
    fprintf('\nMAximum number of iteration (%g) reached! \n', peval.maxiter)
    peval.maxiter_reached_flag = 1;
end

varargout{1}=w;
varargout{2}=h;
varargout{3}=peval;
varargout{4}=d;
varargout{5}=htrace;


function [AngData] = fft_angle(Xcube,fft_Ang,Is_Windowed)

Nr=size(Xcube,1);   %%%length of Chirp
Ne=size(Xcube,2);   %%%length of receiver
Nd=size(Xcube,3);   %%%length of chirp loop

% win = taylorwin(Ne,5,-60);
% win = win/norm(win);
for i = 1:Nd
    for j = 1:Nr
        if Is_Windowed
            win_xcube = reshape(Xcube(j,:,i),Ne,1).*taylorwin(Ne);
        else
            win_xcube = reshape(Xcube(j,:,i),Ne,1).*1;
        end
        AngData(j,:,i) = fftshift(fft(win_xcube,fft_Ang));
    end
end
end


function [regions] = selectRegions(image_data)

BND_THRESH = 0.010;
AREA_THRESH = 20*20;

pb1 = image_data.occ.pb1;
pb2 = image_data.occ.pb2;
bndinfo = image_data.occ.bndinfo_all{1};

hier = boundaries2hierarchy(pb1+pb2, bndinfo.edges.spLR, 'mean');
cost = [hier.init_cost ; hier.cost];
stats = regionprops(bndinfo.wseg, 'Area');
area = cat(1, stats.Area);
keep = false(size(hier.regions));

for r = 1:numel(keep)
   keep(r) = ((sum(area(hier.regions{r}))>AREA_THRESH) && (cost(r)>BND_THRESH));
end
regions = hier.regions(keep);


	function f=def_funct(t,t1,a1,t2,a2,a3)
			% **************************************************
			% Functie MATLAB destinata generarii
			% unei functii de forma
			%
			%        a1, pentru t<t1
			% f(t)=  a2, pentru t>t2
			%        a3, pentru t>=t1 si t<=t2
			%
			% Variabile de intrare:
			% - t intervalul total de definitie al functiei
			% - t1, t2 limitele de definitie
			% - a1, a2, a3 valorile functiei
			%   in diferitele intervale
			% Variabila de iesire: vectorul f
			% **************************************************

			% Determinarea indicilor pentru care t<t1
	k1=find(t<t1);
			% Determinarea indicilor pentru care t>t2
	k3=find(t>t2);
			% Generarea tuturor indicilor
	k2=1:length(t);
			% Generarea indicilor din mijloc
			% prin extragerea celor pentru care t<t1 si t>t2
	k2([k1 k3])=[];
			% Incarcarea vectorului rezultat
			% (utilizand tricul lui Tony):
			% - prima parte cu valorile a1
	f(k1)=a1(1,ones(1,length(k1)));
			% - partea din mijloc cu valorile a3
	f(k2)=a3(1,ones(1,length(k2)));
			% - ultima parte cu valorile a2
	f(k3)=a2(1,ones(1,length(k3)));


function [ point, seed ] = p14_sample ( m, n, seed )

%*****************************************************************************80
%
%% P14_SAMPLE samples points from the region in problem 14.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the spatial dimension.
%
%    Input, integer N, the number of points.
%
%    Input, integer SEED, a seed for the random number generator.
%
%    Output, real POINT(M,N), the coordinates of the points.
%
%    Output, integer SEED, a seed for the random number generator.
%
  box = [ ...
    100.0,  145.0; ...
   +634.0, +799.0 ]';

  reject = 0;

  for j = 1 : n

    while ( 1 )

      [ x, seed  ] = r8mat_uniform_01 ( m, 1, seed );
      x(1:m,1) = ( 1.0 - x(1:m,1) ) .* box(1:m,1) + x(1:m,1) .* box(1:m,2);

      inside = p14_inside ( m, 1, x );

      if ( inside )
        break
      end

      reject = reject + 1;

      if ( 30 * n + 10 <= reject )
        fprintf ( 1, '\n' );
        fprintf ( 1, 'P14_SAMPLE - Fatal error!\n' );
        fprintf ( 1, '  Trying to generate point J = %d\n', j );
        fprintf ( 1, '  Number of rejections = %d\n', reject );
        fprintf ( 1, '  Rejection percentage = %f\n', ...
          ( 100 * reject ) / ( reject + j - 1 ) );
        r8vec_print ( m, x, '  Most recent rejected point: ' );
        error ( 'P14_SAMPLE - Fatal error!' );
      end

    end

    point(1:m,j) = x(1:m,1);

  end

  return
end


function cvt_3d_sampling ( g_num, it_num, s_num )

%*****************************************************************************80
%
%% CVT_3D_SAMPLING carries out the Lloyd algorithm in a 3D unit box.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 June 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer G_NUM, the number of generators.
%    A value of 50 is reasonable.
%
%    Input, integer IT_NUM, the number of CVT iterations.
%    A value of 20 or 50 might be reasonable.
%
%    Input, integer S_NUM, the number of sample points to use
%    when estimating the Voronoi regions.
%    A value of 1,000 is too low.  A value of 1,000,000 is somewhat high.
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CVT_3D_SAMPLING\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Use sampling to approximate Lloyd''s algorithm\n' );
  fprintf ( 1, '  in the 3D unit cube.\n' );

  if ( nargin < 1 )
    g_num = input ( '  Enter number of generators, G_NUM: ' );
  elseif ( ischar ( g_num ) )
    g_num = str2num ( g_num );
  end

  if ( nargin < 2 )
    it_num = input ( '  Enter number of iterations, IT_NUM: ' );
  elseif ( ischar ( it_num ) )
    it_num = str2num ( it_num );
  end

  if ( nargin < 3 )
    s_num = input ( '  Enter number of sample points, S_NUM: ' );
  elseif ( ischar ( s_num ) )
    s_num = str2num ( s_num );
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of generators is %d\n', g_num );
  fprintf ( 1, '  Number of iterations is %d\n', it_num );
  fprintf ( 1, '  Number of samples is %d\n', s_num );
%
%  Initialize the generators.
%  Choice 1: RAND
%
  g = rand ( g_num, 3 );
%
%  Carry out the iteration.
%
  step = 1 : it_num;
  e = nan ( it_num, 1 );
  gm = nan ( it_num, 1 );

  for it = 1 : it_num

    figure ( 1 )
    scatter3 ( g(:,1), g(:,2), g(:,3), 'filled' )
    xlabel ( '<---X--->' )
    ylabel ( '<---Y--->' )
    zlabel ( '<---Z--->' )
    title ( sprintf ( 'Generator locations before iteration %d', it ) );
%
%  Compute the Delaunay triangle information T for the current nodes.
%
    t = DelaunayTri ( g );
%
%  Generate sample points.
%
    s = rand ( s_num, 3 );
%
%  For each sample point, find K, the index of the nearest generator.
%  We do this efficiently by using the Delaunay information with
%  Matlab's DSEARCH command, rather than a brute force nearest neighbor
%  computation.
%
    k = nearestNeighbor ( t, s );

    m(:,1) = accumarray ( k, ones(s_num,1) );

    g_new(:,1) = accumarray ( k, s(:,1) ) ./ m(:,1);
    g_new(:,2) = accumarray ( k, s(:,2) ) ./ m(:,1);
    g_new(:,3) = accumarray ( k, s(:,3) ) ./ m(:,1);
%
%  Compute the average energy.
%
    e(it,1) = sum ( ( s(:,1) - g(k(:,1),1) ).^2 ...
                  + ( s(:,2) - g(k(:,1),2) ).^2 ...
                  + ( s(:,3) - g(k(:,1),3) ).^2 ) / s_num;
%
%  Display the energy.
%
    figure ( 3 )
    plot ( step, log ( e ), 'm-*' )
    title ( 'Log (Energy)' )
    xlabel ( 'Step' )
    ylabel ( 'Energy' )
    grid
%
%  Compute the generator motion.
%
    gm(it,1) = sum ( ( g_new(:,1) - g(:,1) ).^2 ...
                   + ( g_new(:,2) - g(:,2) ).^2 ...
                   + ( g_new(:,3) - g(:,3) ).^2 ) / g_num;
%
%  Display the generator motion.
%
    figure ( 4 )
    plot ( step, log ( gm ), 'm-*' )
    title ( 'Log (Average generator motion)' )
    xlabel ( 'Step' )
    ylabel ( 'Motion' )
    grid
%
%  Continue?
%
    s = input ( 'RETURN, or Q to quit: ', 's' );

    if ( s == 'q' | s == 'Q' )
      break
    end
%
%  Update the generators.
%
    g = g_new;

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

  return
end
function timestamp ( )

%*****************************************************************************80
%
%% TIMESTAMP prints the current YMDHMS date as a timestamp.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  t = now;
  c = datevec ( t );
  s = datestr ( c, 0 );
  fprintf ( 1, '%s\n', s );

  return
end


function [rRelmTest] = relm_LTest(vRatesH, vRatesN, nNumberSimulation, fMagThreshold, bOptimized, bDrawFigure)
% function [rRelmTest] = relm_LTest(vRatesH, vRatesN, nNumberSimulation, fMagThreshold, bOptimized, bDrawFigure)
% --------------------------------------------------------------------------------------------------------------
% Computation of the L-test for the RELM framework
%
% Input parameters:
%   vRatesH                       Matrix with rates of the test hypothesis
%   vRatesN                       Matrix with rates of the null hypothesis
%   nNumberSimulation             Number of random simulations
%   fMagThreshold                 Magnitude threshold (Use only bins with magnitude >= threshold
%   bOptimized                    0 (default): use a for loop, 1: matrix-wise calculation (needs a lot of memory)
%   bDrawFigure                   Draw the cumulative density plot after testing (default: off)
%
% Output paramters:
%   rRelmTest.fAlpha              Alpha-value of the cumulative density
%   rRelmTest.fBeta               Beta-value of the cumulative density
%   rRelmTest.vSimValues_H        Vector containing the sorted simulated numbers of events for the test hypothesis
%   rRelmTest.vSimValues_N        Vector containing the sorted simulated numbers of events for the null hypothesis
%   rRelmTest.nNumberSimulation   Number of random simulations
%   rRelmTest.fObservedData       Observed total number of events
%
% Copyright (C) 2002-2006 by Danijel Schorlemmer
%
% 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.

% Exit on empty rate matrices
if isempty(vRatesH)  ||  isempty(vRatesN)
  rRelmTest.fAlpha = nan;
  rRelmTest.fBeta = nan;
  rRelmTest.vSimValues_H = nan;
  rRelmTest.vSimValues_N = nan;
  rRelmTest.nNumberSimulation = nan;
  rRelmTest.fObservedData = nan;
  return;
end

if ~exist('bDrawFigure')
  bDrawFigure = 0;
end

if ~exist('bOptimized')
  bOptimized = 0;
end

% Get the necessary data from the rate matrices and weight them properly
[vLambdaH, vLambdaN, vNumberQuake] = relm_PrepareData(vRatesH, vRatesN, fMagThreshold);
nNumberQuake = sum(vNumberQuake);

fLikelihood_H = sum(calc_logpoisspdf(vNumberQuake, vLambdaH));
fLikelihood_N = sum(calc_logpoisspdf(vNumberQuake, vLambdaN));

% Get the number of bins (rows)
[nRow, nColumn] = size(vLambdaH);

if bOptimized
  % Create the random numbers for the simulation
  vRandom = rand(nRow, nNumberSimulation);

  % Replicate the rate vectors
  vLambdaH = repmat(vLambdaH, 1, nNumberSimulation);
  vLambdaN = repmat(vLambdaN, 1, nNumberSimulation);

  % Compute the simulated number of events and sum them up
  vNum_H = poissinv(vRandom, vLambdaH);
  vNum_N = poissinv(vRandom, vLambdaN);
  vSimNum_H = sum(calc_logpoisspdf(vNum_H, vLambdaH)) - fLikelihood_H;
  vSimNum_N = sum(calc_logpoisspdf(vNum_N, vLambdaN)) - fLikelihood_N;
else
  % Create empty vectors for the total number of events
  vSimNum_H = [];
  vSimNum_N = [];

  % Loop over the simulations
  for nCnt = 1:nNumberSimulation
    % Create the random numbers for the simulation
    vRandom = rand(nRow, 1);

    % Compute the simulated number of events and sum them up
    vNum_H = poissinv(vRandom, vLambdaH);
    vNum_N = poissinv(vRandom, vLambdaN);
    vSimNum_H = [vSimNum_H; (sum(calc_logpoisspdf(vNum_H, vLambdaH)) - fLikelihood_H)];
    vSimNum_N = [vSimNum_N; (sum(calc_logpoisspdf(vNum_N, vLambdaN)) - fLikelihood_N)];
  end
end

% Sort them for the cumulative density plot
rRelmTest.vSimValues_H = sort(vSimNum_H);
rRelmTest.vSimValues_N = sort(vSimNum_N);

% Compute Alpha and Beta and store the important parameters
rRelmTest.fAlpha = sum(rRelmTest.vSimValues_N > 0)/nNumberSimulation;
rRelmTest.fBeta = sum(rRelmTest.vSimValues_H < 0)/nNumberSimulation;
rRelmTest.nNumberSimulation = nNumberSimulation;
rRelmTest.fObservedData = 0;

if bDrawFigure
  relm_PaintCumPlot(rRelmTest, 'Log-likelihood');
end


sphere(30);
title('a sphere: x^2+y^2+z^2');
xlabel('x');
ylabel('y');
zlabel('z');
axis equal


function [u_new, V, exitflag, output] = solveOptimalControlProblem (fst, varargin)

% fst.horizon, fst.xmeasure, fst.u0, fst.opt_option, fst.price, fst.net_load, battery
%SOLVEOPTIMALCONTROLPROBLEM Summary of this function goes here
%   solves the optimal control problem of the

    %x = computeOpenloopSolution(fst); %For linear constraints

    % Set control and linear bounds
    A = [];
    b = [];
    Aeq = [];
    beq = [];
    lb = [];
    ub = [];
    for k=1:fst.horizon  %Aggregation
        [Anew, bnew, Aeqnew, beqnew, lbnew, ubnew] = fst.l_constraints( fst, k );

        A = blkdiag(A,Anew);
        b = [b, bnew];
        Aeq = blkdiag(Aeq,Aeqnew);
        beq = [beq, beqnew];
        lb = [lb, lbnew];
        ub = [ub, ubnew];
    end

    % Solve optimization problem
    [u_new, V, exitflag, output] = fmincon( @(u) fst.costfunction( fst, u ), fst.u0 , ...    % Objective
         A, b, Aeq, beq, lb, ub, ...                                            % Linear Constarints
        @(u) fst.nonlinearconstraints(fst, u ), fst.option);                    % Nonlinear Constraints
end


function pass = test_iszero()
% Test spherefun iszero() command.

f = spherefun( @(x,y,z) 0 + 0*x );
pass(1) = iszero( f );

f = spherefun( @(x,y,z) cos(x) );
pass(2) = ~iszero( f );

end


function ms=zz_flood_fill_movie(r,tol)
global hi I
% this just make move
% flood fill, scan line algoritm
% ms=flood_fill(RR,GG,BB,r,tol)
% % ms - pixels numbers that flooded
% numbering: number=y+szy*(x-1), x y - pixels coordinaties
% szx szy - image size
% I - RGB image
% r- first point of selection
% tol - tolerance

clear F;
fc=1;

R=int32(I(:,:,1));
G=int32(I(:,:,2));
B=int32(I(:,:,3));

[szy szx]=size(R); % imae size

% stek, where seed will be stored:
stm=10000;
st=zeros(stm,2,'int32');
st(1,1)=r(1);
st(1,2)=r(2); % r - is start seed
stL=1; % stack length

hp=plot(r(1),r(2),'.r');
set(hp,'MarkerSize',10);

set(hp,'XData',st(1:stL,1),'YData',st(1:stL,2));
drawnow;

% found pixel store:
ms0m=1e6; % margin
ms0=zeros(ms0m,1,'int32'); % predifined array to increase speed
ms0L=0; % 0 points initially

% initial point color:
R0=R(r(2),r(1));
G0=G(r(2),r(1));
B0=B(r(2),r(1));

% to pixel number
tn=@(xx,yy) yy+szy*(xx-1);

while true;
    % get seed from stack:
    xt=st(stL,1);
    yt=st(stL,2);
    stL=stL-1;

    % line:
    % to right
    sku=false; % seed key, true if seed added, up
    skd=false; % same for down
    sku1=false; % this key is need to prewnt extra seed when move to left, up
    skd1=false; % same for left
    for xtt=xt:szx
        drawnow;
        F(fc)=getframe(gcf);
        fc=fc+1;

        if max(abs([(R(yt,xtt)-R0), (G(yt,xtt)-G0), (B(yt,xtt)-B0)]))<=tol
            % add pixel
            ms0L=ms0L+1;
            ms0(ms0L)=tn(xtt,yt);
            I(yt,xtt,1)=0;
            set(hi,'Cdata',I);
        else
            break;
        end

        % try to add seed up:
        if yt~=szy
            if max(abs([(R(yt+1,xtt)-R0), (G(yt+1,xtt)-G0), (B(yt+1,xtt)-B0)]))<=tol
                if ~sku
                    if all(tn(xtt,yt+1)~=ms0(1:ms0L)) % if free space
                        % add to stack
                        stL=stL+1;
                        st(stL,1)=xtt;
                        st(stL,2)=yt+1;
                        sku=true;
                    end
                end
            else
                sku=false;
            end
            if xtt==xt
                sku1=sku; % memorize, will be used when to left
            end
        end

        % try to add down
        if yt~=1
            if max(abs([(R(yt-1,xtt)-R0), (G(yt-1,xtt)-G0), (B(yt-1,xtt)-B0)]))<=tol
                if ~skd
                    if all(tn(xtt,yt-1)~=ms0(1:ms0L)) % if free space
                        % add to stack
                        stL=stL+1;
                        st(stL,1)=xtt;
                        st(stL,2)=yt-1;
                        skd=true;
                    end
                end
            else
                skd=false;
            end
            if xtt==xt
                skd1=skd; % memorize, will be used when to left
            end
        end
    end

    % to left
    %sku=false; % seed key, true if seed added
    %skd=false;
    sku=sku1;
    skd=skd1;
    if xt~=1
        for xtt=(xt-1):-1:1
            drawnow;
            F(fc)=getframe(gcf);
            fc=fc+1;

            if max(abs([(R(yt,xtt)-R0), (G(yt,xtt)-G0), (B(yt,xtt)-B0)]))<=tol
                % add pixel
                ms0L=ms0L+1;
                ms0(ms0L)=tn(xtt,yt);
                I(yt,xtt,1)=0;
                set(hi,'Cdata',I);
            else
                break;
            end

            % try to add seed up:
            if yt~=szy
                if max(abs([(R(yt+1,xtt)-R0), (G(yt+1,xtt)-G0), (B(yt+1,xtt)-B0)]))<=tol
                    if ~sku
                        if all(tn(xtt,yt+1)~=ms0(1:ms0L)) % if free space
                            % add to stack
                            stL=stL+1;
                            st(stL,1)=xtt;
                            st(stL,2)=yt+1;
                            sku=true;
                        end
                    end
                else
                    sku=false;
                end
            end

            % try to add down
            if yt~=1
                if max(abs([(R(yt-1,xtt)-R0), (G(yt-1,xtt)-G0), (B(yt-1,xtt)-B0)]))<=tol
                    if ~skd
                        if all(tn(xtt,yt-1)~=ms0(1:ms0L)) % if free space
                            % add to stack
                            stL=stL+1;
                            st(stL,1)=xtt;
                            st(stL,2)=yt-1;
                            skd=true;
                        end
                    end
                else
                    skd=false;
                end
            end
        end
    end

    set(hp,'XData',st(1:stL,1),'YData',st(1:stL,2));
    drawnow;
    %pause(1);

    if stL==0 % no more seed
        break; % stop
    end

end

ms=ms0(1:ms0L);

% save as avi file:
movie2avi(F(1:4:end),'flood_fill_movie','fps',20,'compression','Cinepak');

% save as animated gif
[im,map] = rgb2ind(F(20).cdata,256,'nodither');
im(1,1,1,20) = 0;
k=1;
for fc1=1:4:(fc-1)
    im(:,:,1,k) = rgb2ind(F(fc1).cdata,map,'nodither');
    k=k+1;
end
imwrite(im,map,'flood_fill_gif.gif','DelayTime',0,'LoopCount',inf) %g443800


function r8_power_fast_test ( )

%*****************************************************************************80
%
%% R8_POWER_FAST_TEST tests R8_POWER_FAST.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 April 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8_POWER_FAST_TEST\n' );
  fprintf ( 1, '  R8_POWER_FAST computes R^P, economizing on\n' );
  fprintf ( 1, '  multiplications.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      R          P       R^P        Mults\n' );
  fprintf ( 1, '\n' );

  for i = -10 : 40

    r = 2.0;
    p = i;
    [ rp, mults ] = r8_power_fast ( r, p );
    fprintf ( 1, '  %12f  %5d  %12f  %5d\n', r, p, rp, mults );

  end

  return
end


function calpak_test79 ( )

%*****************************************************************************80
%
%% CALPAK_TEST79 tests YMDF_TO_WEEKDAY_HEBREW.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 April 2013
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALPAK_TEST79\n' );
  fprintf ( 1, '  For the HEBREW calendar:\n' );
  fprintf ( 1, '  YMDF_TO_WEEKDAY_HEBREW\n' );
  fprintf ( 1, '  returns the day of the week.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  JED   YMDF           Day of the week\n' );
  fprintf ( 1, '\n' );

  jed_epoch = epoch_to_jed_hebrew ( );

  i = 0;

  while ( 1 )

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

    if ( jed1 < 0 )
      break
    end

    if ( jed_epoch <= jed1 )

      jed2 = jed_to_next_noon ( jed1 );

      [ y1, m1, d1, f1 ] = jed_to_ymdf_hebrew ( jed2 );
      s1 = ymdf_to_s_hebrew ( y1, m1, d1, f1 );

      w2 = ymdf_to_weekday_hebrew ( y1, m1, d1, f1 );
      s2 = weekday_to_name_hebrew ( w2 );

      fprintf ( 1, '  %11.2f  %20s  %d  %20s\n', jed2, s1, w2, s2 );

    end

  end

  return
end


function varargout = nleqs_master(fcn, x0, opt)
%NLEQS_MASTER  Nonlinear Equation Solver wrapper function.
%   [X, F, EXITFLAG, OUTPUT, JAC] = NLEQS_MASTER(FCN, X0, OPT)
%   [X, F, EXITFLAG, OUTPUT, JAC] = NLEQS_MASTER(PROBLEM)
%   A common wrapper function for various nonlinear equation solvers.
%   Solves the nonlinear equation f(x) = 0, beginning from a starting
%   point x0.
%
%   Inputs:
%       FCN : handle to function that evaluates the function f(x) to
%           be solved and its (optionally, depending on the selected
%           solver) Jacobian, J(x). Calling syntax for this function is:
%               f = FCN(x)
%               [f, J] = FCN(x)
%           If f and x are n x 1, then J is the n x n matrix of partial
%           derivatives of f (rows) w.r.t. x (cols).
%       X0 : starting value, x0, of vector x
%       OPT : optional options structure with the following fields,
%           all of which are also optional (default values shown in
%           parentheses)
%           alg ('DEFAULT') : determines which solver to use
%               'DEFAULT' : automatic, current default is NEWTON
%               'NEWTON'  : standard, full-Jacobian Newton's method
%               'CORE'    : core algorithm, with arbitrary update function
%               'FD'      : fast-decoupled Newton's method
%               'FSOLVE'  : FSOLVE, MATLAB Optimization Toolbox
%               'GS'      : Gauss-Seidel method
%           verbose (0) - controls level of progress output displayed
%               0 = no progress output
%               1 = some progress output
%               2 = verbose progress output
%           max_it (0) - maximum number of iterations
%                       (0 means use solver's own default)
%           tol (0) - termination tolerance on f(x)
%                       (0 means use solver's own default)
%           core_sp - solver parameters struct for NLEQS_CORE, required
%               when alg = 'CORE' (see NLEQS_CORE for details)
%           fd_opt - options struct for fast-decoupled Newton, NLEQS_FD_NEWTON
%           fsolve_opt - options struct for FSOLVE
%           gs_opt - options struct for Gauss-Seidel method, NLEQS_GAUSS_SEIDEL
%           newton_opt - options struct for Newton's method, NLEQS_NEWTON
%       PROBLEM : The inputs can alternatively be supplied in a single
%           PROBLEM struct with fields corresponding to the input arguments
%           described above: fcn, x0, opt
%
%   Outputs (all optional, except X):
%       X : solution vector x
%       F : final function value, f(x)
%       EXITFLAG : exit flag
%           1 = converged
%           0 or negative values = solver specific failure codes
%       OUTPUT : output struct with the following fields:
%           alg - algorithm code of solver used
%           (others) - algorithm specific fields
%       JAC : final Jacobian matrix, J(x)
%
%   Note the calling syntax is almost identical to that of FSOLVE from
%   MathWorks' Optimization Toolbox. The function for evaluating the
%   nonlinear function and Jacobian is identical.
%
%   Calling syntax options:
%       [x, f, exitflag, output, jac] = nleqs_master(fcn, x0);
%       [x, f, exitflag, output, jac] = nleqs_master(fcn, x0, opt);
%       x = nleqs_master(problem);
%               where problem is a struct with fields: fcn, x0, opt
%               and all fields except 'fcn' and 'x0' are optional
%       x = nleqs_master(...);
%       [x, f] = nleqs_master(...);
%       [x, f, exitflag] = nleqs_master(...);
%       [x, f, exitflag, output] = nleqs_master(...);
%       [x, f, exitflag, output, jac] = nleqs_master(...);
%
%   Example: (problem from https://www.chilimath.com/lessons/advanced-algebra/systems-non-linear-equations/)
%       function [f, J] = f1(x)
%       f = [  x(1)   + x(2) - 1;
%             -x(1)^2 + x(2) + 5    ];
%       if nargout > 1
%           J = [1 1; -2*x(1) 1];
%       end
%
%       problem = struct( ...
%           'fcn',    @(x)f1(x), ...
%           'x0',       [0; 0], ...
%           'opt',      struct('verbose', 2) ...
%       );
%       [x, f, exitflag, output, jac] = nleqs_master(problem);
%
%   See also NLEQS_NEWTON, NLEQS_CORE, NLEQS_FD_NEWTON, NLEQS_FSOLVE,
%   NLEQS_GAUSS_SEIDEL, FSOLVE.

%   MP-Opt-Model
%   Copyright (c) 2010-2020, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MP-Opt-Model.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://github.com/MATPOWER/mp-opt-model for more info.

%%----- input argument handling  -----
%% gather inputs
if nargin == 1 && isstruct(fcn) %% problem struct
    p = fcn;
    fcn = p.fcn;
    x0 = p.x0;
    if isfield(p, 'opt'),   opt = p.opt;    else,   opt = [];   end
else                            %% individual args
    if nargin < 3
        opt = [];
    end
end

%% default options
if ~isempty(opt) && isfield(opt, 'alg') && ~isempty(opt.alg)
    alg = opt.alg;
else
    alg = 'DEFAULT';
end
if strcmp(alg, 'DEFAULT')
    alg = 'NEWTON';
end

%%----- call the appropriate solver  -----
switch alg
    case 'NEWTON'               %% use Newton's method solver
        nleqs_fcn = @nleqs_newton;
    case 'FD'                   %% use fast-decoupled Newton's method solver
        nleqs_fcn = @nleqs_fd_newton;
    case 'FSOLVE'               %% use fsolve
        nleqs_fcn = @nleqs_fsolve;
    case 'GS'                   %% use Gauss-Seidel solver
        nleqs_fcn = @nleqs_gauss_seidel;
    case 'CORE'                 %% use core solver
        nleqs_fcn = @(f, x, o)nleqs_core(opt.core_sp, f, x, o);
    otherwise
        error('nleqs_master: ''%s'' is not a valid algorithm code', alg);
end
[varargout{1:nargout}] = nleqs_fcn(fcn, x0, opt);


function flood_fill(xc,yc,x,y,new,old,width,height)
% flood fills area of matrix
% (xc,yc) = start point of flood fill
% (x,y) = current test location
% new = new value to be filled
% old = old value to replace
%
% example use:
% global fill
% width = 20;
% height = 20;
% fill = zeros(width,height);
% new = 1;
% old = 0;
% xc = 10;
% yc = 10;
% flood_fill(xc,yc,xc,yc,new,old,width,height);
%
% Results:
% The flood fill will alter all values of 0 to one flood filling from a
% start point (xc,yc)
% If the flood fill starts in an enclosed space it will fill up to the
% boundary
%
% Author: James Goodwin, June 2003
% email: JamesRichardGoodwin@lyocs.com

global fill;
global call;

call = call + 1;

if (x<2 || x>=width)
    x = xc;
end

if (y<2 || y>=height)
    y = yc;
end

if (fill(y,x) == old)
    fill(y,x) = new;
    flood_fill(xc,yc,x+1,y,new,old,width,height);
    flood_fill(xc,yc,x,y+1,new,old,width,height);
    flood_fill(xc,yc,x-1,y,new,old,width,height);
    flood_fill(xc,yc,x,y-1,new,old,width,height);
end


function IW = get_BMS_capacity(W)
%This function is employed here to verify the correctness of the program
%that is being writen
HYX = sum(W(1, :).*log2(W(1, :)));
PY = (W(1, :) + W(2, :))/2;
HY = sum(-PY.*log2(PY));
IW = HY + HYX;
end


function z = daxpy ( n, sa, x, incx, y, incy )

%*****************************************************************************80
%
%% DAXPY adds a constant times one vector to another.
%
%  Modified:
%
%    25 February 2004
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Author:
%
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Lawson, Hanson, Kincaid, Krogh,
%    Basic Linear Algebra Subprograms for Fortran Usage,
%    Algorithm 539,
%    ACM Transactions on Mathematical Software,
%    Volume 5, Number 3, September 1979, pages 308-323.
%
%  Parameters:
%
%    Input, integer N, the number of entries in the vector.
%
%    Input, real SA, the multiplier.
%
%    Input, real X(*), the vector to be scaled and added to Y.
%
%    Input, integer INCX, the increment between successive entries of X.
%
%    Input, real Y(*), the vector to which a multiple of X is to be added.
%
%    Input, integer INCY, the increment between successive entries of Y.
%
%    Output, real Z(*), the vector Y(*) + SA * X(*).
%
  if ( n <= 0 )

    z = [];

  elseif ( sa == 0.0 )

    ny = length ( y );
    z(1:ny) = y(1:ny);

  elseif ( incx == 1 & incy == 1 )

    z(1:n) = y(1:n) + sa * x(1:n);

  else

    ny = length ( y );
    z(1:ny) = y(1:ny);

    if ( 0 <= incx )
      ix = 1;
    else
      ix = ( - n + 1 ) * incx + 1;
    end if

    if ( 0 <= incy  )
      iy = 1;
    else
      iy = ( - n + 1 ) * incy + 1;
    end

    for i = 1 : n
      z(iy) = z(iy) + sa * x(ix);
      ix = ix + incx;
      iy = iy + incy;
    end

  end

  return
end


function a = wilson_eigen_right ( )

%*****************************************************************************80
%
%% WILSON_EIGEN_RIGHT returns the right eigenvectors of the WILSON matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 March 2015
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real A(4,4), the right eigenvector matrix.
%

%
%  Note that the matrix entries are listed by row.
%
  a = [ ...
   0.380262074390714, ...
   0.396305561186082, ...
   0.093305039089285, ...
   0.830443752841578; ...
   0.528567849528642, ...
   0.614861280394151, ...
  -0.301652326903523, ...
  -0.501565058582058; ...
   0.551954849631663, ...
  -0.271601039711768, ...
   0.760318430013036, ...
  -0.208553600252039; ...
   0.520924780743657, ...
  -0.625396181050490, ...
  -0.567640668325261, ...
   0.123697458332363 ];

  return
end


function [cm] = m2cm(m)
% Convert length from meters to centimeters.
% Chad A. Greene 2012
cm = m*100;


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

function MU_func3DRender(Temp,Event,handles)
handles = guidata(handles.MU_matrix_display);

MU_3D_Render(handles);

end


function r8r8vec_index_insert_unique_test ( )

%*****************************************************************************80
%
%% R8R8VEC_INDEX_INSERT_UNIQUE_TEST tests R8R8VEC_INDEX_INSERT_UNIQUE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 April 2009
%
%  Author:
%
%    John Burkardt
%
  n_max = 30;

  x_max = 4.0;
  x_min = 1.0;
  y_max = 3.0;
  y_min = 1.0;

  n = 0;
  x = [];
  y = [];
  indx = [];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8R8VEC_INDEX_INSERT_UNIQUE_TEST\n' );
  fprintf ( 1, '  R8R8VEC_INDEX_INSERT_UNIQUE inserts unique values into an\n' );
  fprintf ( 1, '    index sorted array.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Generate %d random values:\n', n_max );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Index    XVAL    YVAL\n' );
  fprintf ( 1, '\n' );

  seed = 123456789;

  for i = 1 : n_max

    [ xval, seed ] = r8_uniform_ab ( x_min, x_max, seed );
    xval = round ( xval );
    [ yval, seed ] = r8_uniform_ab ( y_min, y_max, seed );
    yval = round ( yval );

    [ n, x, y, indx, ival, ierror ] = r8r8vec_index_insert_unique ( ...
      n, x, y, indx, xval, yval );

    fprintf ( 1, '    %6d  %6f  %6f\n', ival, xval, yval );

  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Vector of unique X Y values:\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  I  X(I)   Y(I)\n' );
  fprintf ( 1, '\n' );
  for i = 1 : n
    fprintf ( 1, '    %6d  %6f  %6f\n', i, x(i), y(i) );
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '  X, Y sorted by index\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  I  INDX(I)  X(INDX(I))  Y(INDX(I))\n' );
  fprintf ( 1, '\n' );
  for i = 1 : n
    fprintf ( 1, '    %6d  %6f  %6f\n', i, indx(i), x(indx(i)), y(indx(i)) );
  end

  return
end


function numdiff = ndiff(A)
%
% Accounts for the number of different elements that compose the matrix A

B = A(1);
for i=2:numel(A)
    if isempty(find(A(i) == B))
        B = [B A(i)];
    end
end
numdiff = length(B);


function geometry_test227 ( )

%*****************************************************************************80
%
%% TEST227 tests VOXELS_STEP_3D.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 February 2009
%
%  Author:
%
%    John Burkardt
%
  dim_num = 3;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST227\n' );
  fprintf ( 1, '  VOXELS_STEP_3D steps along a line from\n' );
  fprintf ( 1, '    one voxel to another.\n' );

  v1(1:dim_num) = [ 1, 1, 5 ];
  v2(1:dim_num) = v1(1:dim_num);

  inc = 7;
  jnc = 3;
  knc = -1;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  %4d  %4d  %4d  %4d\n', 0, v2(1:dim_num) );

  for i = 1 : 10
    v3 = voxels_step_3d ( v1, v2, inc, jnc, knc );
    fprintf ( 1, '  %4d  %4d  %4d  %4d\n', i, v3(1:dim_num) );
    v2(1:dim_num) = v3(1:dim_num);
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Now, as a check, reverse direction and return.\n' );
  fprintf ( 1, '\n' );

  v1(1:dim_num) = v2(1:dim_num);

  inc = -inc;
  jnc = -jnc;
  knc = -knc;

  v2(1:dim_num) = v1(1:dim_num);

  fprintf ( 1, '  %4d  %4d  %4d  %4d\n', 0, v2(1:dim_num) );
  for i = 1 : 10
    v3 = voxels_step_3d ( v1, v2, inc, jnc, knc );
    fprintf ( 1, '  %4d  %4d  %4d  %4d\n', i, v3(1:dim_num) );
    v2(1:dim_num) = v3(1:dim_num);
  end

  return
end