function writePLY(filename,V,F,mode)
  % WRITEPLY wrapper for write_ply
  %
  % Inputs:
  %   filename  path to output .ply file
  %   V  #V by 3 list of mesh vertex positions
  %   F  #F by 3 list of mesh triangle indices
  %   mode  followed by
  %      'ascii'                ASCII text data
  %      {'binary_little_endian'}   binary data, little endian
  %      'binary_big_endian'      binary data, big endian
  %
  %

  if nargin < 4
    mode = 'binary_little_endian';
  end

  fid = fopen(filename,'wt');
  fprintf(fid,'ply\nformat %s 1.0\n',mode);
  fprintf(fid,'element vertex %d\n',size(V,1));
  fprintf(fid,'property double x\n');
  fprintf(fid,'property double y\n');
  fprintf(fid,'property double z\n');
  fprintf(fid,'element face %d\n',size(F,1));
  fprintf(fid,'property list int int vertex_indices\n');
  fprintf(fid,'end_header\n');
  FF = [size(F,2)*ones(size(F,1),1) F-1];
  switch mode
  case 'ascii'
    % do nothing
    fprintf(fid,'%0.17f %0.17f %0.17f\n',V');
    format = [repmat('%d ',1,size(FF,2)) '\n'];
    fprintf(fid,format,FF');
  case {'binary_little_endian','binary_big_endian'}
    fclose(fid);
    switch mode
    case 'binary_little_endian'
      fid = fopen(filename,'a','ieee-le');
    case 'binary_big_endian'
      fid = fopen(filename,'a','ieee-be');
    end
    fwrite(fid,V','double');
    fwrite(fid,FF','int');
  otherwise
    error('Unsupported format: %s',mode);
  end
  fclose(fid);

  %% OLD 200x slower way (possible to produce slightly smaller files and control
  %% over precision)
  %write_ply(V,F,filename,mode);
end


function rs=surrogate_test(s1,ntests,method,func)

%tstoolbox/@signal/surrogate_test
%   Syntax:
%     * rs=surrogate_test(s, ntests, method,func)
%
%   Input Arguments:
%     * s - has to be a real, scalar signal
%     * ntests - is the number of surrogate data sets to create
%     * method - method to generate surrogate data sets:
%          + 1: surrogate1
%          + 2: surrogate2
%          + 3: surrogate3
%     * func - string with matlab-code, have to return a signal object
%       with a scalar time series. The data to process is a signal object
%       referred by the qualifier s (see example).
%
%   Output Arguments:
%     * rs is a signal object with a three dimensional time series. The
%       first component is the result of the func function applied to the
%       original data set s. The second component is the mean of the
%       result of the func function applied to the ntests surrogate data
%       sets. The third component is the standard deviation. There is a
%       special plothint ('surrerrorbar') for the view function to show
%       this result in the common way.
%
%   surrogate_test runs an automatic surrogate data test task. It
%   generates ntests surrogate data sets an performs the func function to
%   each set. func is a string with matlab-code who returns a signal s
%   with a scalar time series.
%
%   Example:
%st = surrogate_test(s, 10, 1, 1, 'largelyap(embed(s,3,1,1), 128,20,10);');
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt

s=s1;
s=eval(func);
x=[data(s)];
for tests=1:ntests
  switch(method)
   case 1
    s=surrogate1(s1);
   case 2
    s=surrogate2(s1);
   case 3
    s=surrogate3(s1);
   otherwise
    s=surrogate1(s1);
  end
  s=eval(func);
  x=[x data(s)];
end

a=[];
for test=1:length(x(:,1))
  a=[a; mean(x(test,2:end)) std(x(test,2:end))];
end

a=[x(:,1) a];

rs = signal(core(a),s1);	% special constructor calling syntax for working routines
%rs=setaxis(rs,1,a);
rs = addhistory(rs, ['Computed ' num2str(ntests) ' surrogate data function values']);
rs = setplothint(rs, 'surrerrorbar');
rs = addcommandlines(rs, 's = surrogate_test(s', ntests,method,func);

return


% NDIMS - number of dimension of memory mapped underlying array
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008

% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

function res = ndims(obj)

    if length(obj.dimensions) <= 2 || all(obj.dimensions(3:end) == 1), res = 2;
    else                                                               res = length(obj.dimensions);
    end


function [m,n] = size(a,dim)
%SIZE         Implements  size(a)  for intervals
%
%   [m,n] = size(a,dim)
%
% functionality as Matlab function size, second argument dim optional
%

% written  10/16/98     S.M. Rump
% modified 04/04/04     S.M. Rump  set round to nearest for safety
% modified 04/06/05     S.M. Rump  rounding unchanged
%

  if a.complex
    if nargout==2
      [m n] = size(a.mid);
    else
      if nargin==1
        m = size(a.mid);
      else
        m = size(a.mid,dim);
      end
    end
  else
    if nargout==2
      [m n] = size(a.inf);
    else
      if nargin==1
        m = size(a.inf);
      else
        m = size(a.inf,dim);
      end
    end
  end


function result = UTCtimestamp()

time_unix = java.lang.System.currentTimeMillis;

% http://stackoverflow.com/questions/12661862/converting-epoch-to-date-in-matlab

time_reference = datenum('1970', 'yyyy');
time_matlab = time_reference + time_unix / 8.64e7;
result = datestr(time_matlab, 'yyyy-mm-ddTHH:MM:SSZ');


function [vor, dist] = spm_voronoi(img, seeds, distance)
% Geodesic Discrete Voronoi Diagram - a compiled routine
% FORMAT [vor, dist] = spm_voronoi(img, seeds, distance)
%
% img       - binary image:  > 0  : inside
%                            <= 0 : outside
% seeds     - {n x 3} array of the n seeds positions [in voxels]
% distance  - type of chamfer distance to use ('d4', 'd8', 'd34' or 'd5711')
%             (default is 'd34')
%
% vor       - Geodesic Discrete Voronoi diagram
%             (label is equal to the index of the seed in 'seeds')
% dist      - Geodesic Distance map of img with seeds as objects
%
% Compute the geodesic discrete Voronoi Diagram of an image of labelled
% objects using front propagation. The distance map is also available
% on output.
%__________________________________________________________________________
% Copyright (C) 2008-2014 Wellcome Trust Centre for Neuroimaging

% Guillaume Flandin
% $Id: spm_voronoi.m 6079 2014-06-30 18:25:37Z spm $

%-This is merely the help file for the compiled routine
error('spm_voronoi.c not compiled - see Makefile')


function Y = log(X)
    %  Symbolic matrix element-wise natural logarithm.

    % Convert inputs to SymExpression
    % X = SymExpression(X);

    % construct the operation string
    sstr = ['Log[' X.s ']'];

    % create a new object with the evaluated string
    Y = SymExpression(sstr);
end


% Monopole Point Source In A Homogeneous Propagation Medium Example
%
% This example provides a simple demonstration of using k-Wave for the
% simulation and detection of a time varying pressure source within a
% two-dimensional homogeneous propagation medium.  It builds on the
% Homogeneous Propagation Medium and Recording The Particle Velocity
% examples.
%
% author: Bradley Treeby
% date: 2nd December 2009
% last update: 2nd September 2012
%
% This function is part of the k-Wave Toolbox (http://www.k-wave.org)
% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox

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

clear all;

% =========================================================================
% SIMULATION
% =========================================================================

% create the computational grid
Nx = 128;           % number of grid points in the x (row) direction
Ny = 128;           % number of grid points in the y (column) direction
dx = 50e-3/Nx;    	% grid point spacing in the x direction [m]
dy = dx;            % grid point spacing in the y direction [m]
kgrid = makeGrid(Nx, dx, Ny, dy);

% define the properties of the propagation medium
medium.sound_speed = 1500;  % [m/s]
medium.alpha_coeff = 0.75;  % [dB/(MHz^y cm)]
medium.alpha_power = 1.5;

% create the time array
[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed);

% define a single source point
source.p_mask = zeros(Nx, Ny);
source.p_mask(end - Nx/4, Ny/2) = 1;

% define a time varying sinusoidal source
source_freq = 0.25e6;   % [Hz]
source_mag = 2;         % [Pa]
source.p = source_mag*sin(2*pi*source_freq*kgrid.t_array);

% filter the source to remove high frequencies not supported by the grid
source.p = filterTimeSeries(kgrid, medium, source.p);

% define a single sensor point
sensor.mask = zeros(Nx, Ny);
sensor.mask(Nx/4, Ny/2) = 1;

% define the acoustic parameters to record
sensor.record = {'p', 'p_final'};

% run the simulation
sensor_data = kspaceFirstOrder2D(kgrid, medium, source, sensor);

% =========================================================================
% VISUALISATION
% =========================================================================

% plot the final wave-field
figure;
imagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, sensor_data.p_final + source.p_mask + sensor.mask, [-1 1]);
colormap(getColorMap);
ylabel('x-position [mm]');
xlabel('y-position [mm]');
axis image;

% plot the simulated sensor data
figure;
[t_sc, scale, prefix] = scaleSI(max(kgrid.t_array(:)));

subplot(2, 1, 1), plot(kgrid.t_array*scale, source.p, 'k-');
xlabel(['Time [' prefix 's]']);
ylabel('Signal Amplitude');
axis tight;
title('Input Pressure Signal');

subplot(2, 1, 2), plot(kgrid.t_array*scale, sensor_data.p, 'r-');
xlabel(['Time [' prefix 's]']);
ylabel('Signal Amplitude');
axis tight;
title('Sensor Pressure Signal');


function y=design(x)
% DESIGN
% DESIGN(x) creates a matrix of 1 and 0 corresponding to x
% y: Rows(x) x Max(x)
  i=1:1:rows(x);
  k=ones(rows(x),1);
  s=sparse(i,x,k,rows(x),max(x));
  y=full(s);


function [c,r] = interactive()
%INTERACTIVE Illustrates inputs from keyboard and mouse.
%   [C,R] = INTERACTIVE() accepts from the keyboard an image filename of
%   the form 'filename.ext' (with single or double quotes). Upon typing
%   Enter (Return), the function displays the image, and activates
%   crosshairs superimposed on the image. The mouse is used to control
%   the location of the crosshairs. The coordinates [C,R] of the center
%   of the crosshairs are captured by a left click from the mouse. Data
%   acquisition is terminated by typing Enter (Return) on the keyboard.
%   The output, [C,R], consists of two column vectors of size K-by-1,
%   containing the column and corresponding row coordinates,
%   respectively. K is the number of samples taken. This function
%   assumes that the image file is in the MATLAB path.
%
%   Copyright 2002-2020 Gatesmark
%
%   This function, and other functions in the DIPUM Toolbox, are based
%   on the theoretical and practical foundations established in the
%   book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark
%   Press, 2020.
%
%   Book website: http://www.imageprocessingplace.com
%   License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt

% Get image.
disp(' '); % Blank separator line.
imageName = input('Type image file name, then Enter (Return): ');

% Read the image from disk.
f = imread(imageName);

% Display instructions.
disp(' '); % Blank separator line.
disp('Image and crosshairs will be displayed next. Use the mouse')
disp('to control the location of the crosshairs, and left-click to')
disp('sample the coordinates.')
disp(' '); % Blank separator line.

% Message to user:
input('Type Enter (Return) to start AND to stop when finished:');
% Wait for user to type Enter (Return).

% Display the image and activate the crosshairs.
figure, imshow(f)
[c,r] = ginput;
close % Close the image window.


function p = prior_loggaussian(varargin)
%PRIOR_LOGGAUSSIAN  Log-Gaussian prior structure
%
%  Description
%    P = PRIOR_LOGGAUSSIAN('PARAM1', VALUE1, 'PARAM2', VALUE2, ...)
%    creates Log-Gaussian prior structure in which the named
%    parameters have the specified values. Any unspecified
%    parameters are set to default values.
%
%    P = PRIOR_LOGGAUSSIAN(P, 'PARAM1', VALUE1, 'PARAM2', VALUE2, ...)
%    modify a prior structure with the named parameters altered
%    with the specified values.
%
%    Parameters for Log-Gaussian prior [default]
%      mu       - location [0]
%      s2       - scale squared (variance) [1]
%      mu_prior - prior for mu [prior_fixed]
%      s2_prior - prior for s2 [prior_fixed]
%
%  See also
%    PRIOR_*
%
% Copyright (c) 2000-2001,2010 Aki Vehtari
% Copyright (c) 2010 Jaakko Riihimäki

% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.

  ip=inputParser;
  ip.FunctionName = 'PRIOR_LOGGAUSSIAN';
  ip.addOptional('p', [], @isstruct);
  ip.addParamValue('mu',0, @(x) isscalar(x));
  ip.addParamValue('mu_prior',[], @(x) isstruct(x) || isempty(x));
  ip.addParamValue('s2',1, @(x) isscalar(x) && x>0);
  ip.addParamValue('s2_prior',[], @(x) isstruct(x) || isempty(x));
  ip.parse(varargin{:});
  p=ip.Results.p;

  if isempty(p)
    init=true;
    p.type = 'Log-Gaussian';
  else
    if ~isfield(p,'type') && ~isequal(p.type,'Log-Gaussian')
      error('First argument does not seem to be a valid prior structure')
    end
    init=false;
  end

  % Initialize parameters
  if init || ~ismember('mu',ip.UsingDefaults)
    p.mu = ip.Results.mu;
  end
  if init || ~ismember('s2',ip.UsingDefaults)
    p.s2 = ip.Results.s2;
  end
  % Initialize prior structure
  if init
    p.p=[];
  end
  if init || ~ismember('mu_prior',ip.UsingDefaults)
    p.p.mu=ip.Results.mu_prior;
  end
  if init || ~ismember('s2_prior',ip.UsingDefaults)
    p.p.s2=ip.Results.s2_prior;
  end

  if init
    % set functions
    p.fh.pak = @prior_loggaussian_pak;
    p.fh.unpak = @prior_loggaussian_unpak;
    p.fh.lp = @prior_loggaussian_lp;
    p.fh.lpg = @prior_loggaussian_lpg;
    p.fh.recappend = @prior_loggaussian_recappend;
  end

end

function [w, s, h] = prior_loggaussian_pak(p)

  w=[];
  s={};
  h=[];
  if ~isempty(p.p.mu)
    w = p.mu;
    s=[s; 'Log-Gaussian.mu'];
    h = 1;
  end
  if ~isempty(p.p.s2)
    w = [w log(p.s2)];
    s=[s; 'log(Log-Gaussian.s2)'];
    h = [h 1];
  end
end

function [p, w] = prior_loggaussian_unpak(p, w)

  if ~isempty(p.p.mu)
    i1=1;
    p.mu = w(i1);
    w = w(i1+1:end);
  end
  if ~isempty(p.p.s2)
    i1=1;
    p.s2 = exp(w(i1));
    w = w(i1+1:end);
  end
end

function lp = prior_loggaussian_lp(x, p)

  lJ = -log(x);    % =log(1/x)=log(|J|) of transformation
  xt  = log(x);    % transformed x
  lp = 0.5*sum(-log(2*pi) -log(p.s2)- 1./p.s2 .* sum((xt-p.mu).^2,1)) +sum(lJ);

  if ~isempty(p.p.mu)
    lp = lp + p.p.mu.fh.lp(p.mu, p.p.mu);
  end
  if ~isempty(p.p.s2)
    lp = lp + p.p.s2.fh.lp(p.s2, p.p.s2) + log(p.s2);
  end
end

function lpg = prior_loggaussian_lpg(x, p)

  lJg = -1./x;     % gradient of log(|J|) of transformation
  xt   = log(x);   % transformed x
  xtg  = 1./x;     % derivative of transformation
  lpg = xtg.*(1./p.s2).*(p.mu-xt) + lJg;

  if ~isempty(p.p.mu)
    lpgmu = sum((1./p.s2).*(xt-p.mu)) + p.p.mu.fh.lpg(p.mu, p.p.mu);
    lpg = [lpg lpgmu];
  end
  if ~isempty(p.p.s2)
    lpgs2 = (sum(-0.5*(1./p.s2-1./p.s2.^2.*(xt-p.mu).^2 )) + p.p.s2.fh.lpg(p.s2, p.p.s2)).*p.s2 + 1;
    lpg = [lpg lpgs2];
  end
end

function rec = prior_loggaussian_recappend(rec, ri, p)
% The parameters are not sampled in any case.
  rec = rec;
  if ~isempty(p.p.mu)
    rec.mu(ri,:) = p.mu;
  end
  if ~isempty(p.p.s2)
    rec.s2(ri,:) = p.s2;
  end
end


% take the covariance matrix of input trajectories

function output = F_logdet(input)

precision = class(gather(input(1)));
if ~strcmpi(precision, 'double')    % we need to use double precision
    input = double(input);
end

[D,M,N] = size(input);
if N==1
    output = log(det(input));
else
    % to be implemented
end

if strcmpi(precision, 'single')
    output = single(output);
end

end


%
%
% DIFFERENTIAL SEARCH ALGORITHM (DSA) (in MATLAB)
% STANDARD VERSION of DSA (16.July.2013)
%
%
% usage : > ds(method,fnc,mydata,popsize,dim,low,up,maxcycle)
%
% method
%--------------------------------------------------------------
% 1: Bijective DSA (B-DSA)
% 2: Surjective DSA (S-DSA)
% 3: Elitist DSA (strategy 1) (E1-DSA)
% 4: Elitist DSA (strategy 2) (E2-DSA)
% if method=[. . . ...],   Hybrid-DSA (H-DSA)
%--------------------------------------------------------------
% example :
% ds(1,'circlefit',mydata,10,3,-10,10,2000) ; % B-DSA
% ds(2,'circlefit',mydata,10,3,-10,10,2000) ; % S-DSA
% ds(3,'circlefit',mydata,10,3,-10,10,2000) ; % E1-DSA
% ds(4,'circlefit',mydata,10,3,-10,10,2000) ; % E2-DSA
% ds([1 2],'circlefit',mydata,10,3,-10,10,2000) ; % Hybrid-DSA, in this case B-DSA and S-DSA are hybridized.
%--------------------------------------------------------------
% Please cite this article as;
% P.Civicioglu, "Transforming geocentric cartesian coordinates to geodetic coordinates by using differential search algorithm",  Computers & Geosciences, 46 (2012), 229-247.
% P.Civicioglu, "Understanding the nature of evolutionary search algorithms", Additional technical report for the project of 110Y309-Tubitak,2013, Ankara, Turkey.
%
%
%
%
%--------------------------------------------------------------
%{
19.March.2013
Copyright Notice
Copyright (c) 2012, Pinar Civicioglu
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%}

function ds(method,fnc,mydata,size_of_superorganism,size_of_one_clan,low_habitat_limit,up_habitat_limit,epoch)

% size_of_superorganism ; size of population.
% size_of_one_clan ; size of problem dimension (1,2,3,...,d), where each clan (i.e. sub-superorganism) includes d-individuals.
% mydata ; additional parameters for objective function, use mydata=[], if it is not needed. See Best-Fit Circle example (circlefit.m) for usage of mydata.

%Initialization

% control of habitat limits
if numel(low_habitat_limit)==1,
    low_habitat_limit=low_habitat_limit*ones(1,size_of_one_clan);
    up_habitat_limit=up_habitat_limit*ones(1,size_of_one_clan);
end

% generate initial individuals, clans and superorganism.
superorganism=genpop(size_of_superorganism,size_of_one_clan,low_habitat_limit,up_habitat_limit);
% success of clans/superorganism
fit_superorganism=feval(fnc,superorganism,mydata);

for epk=1:epoch

    % SETTING OF ALGORITHMIC CONTROL PARAMETERS
    % Trial-pattern generation strategy for morphogenesis; 'one-by-one morphogenesis'.
    % p1=0.0*rand;  % i.e.,  0.0 <= p1 <= 0.0
    % p2=0.0*rand;  % i.e.,  0.0 <= p2 <= 0.0

    % Trial-pattern generation strategy for morphogenesis; 'one-or-more morphogenesis'. (DEFAULT)
    p1=0.3*rand;  % i.e.,  0.0 <= p1 <= 0.3
    p2=0.3*rand;  % i.e.,  0.0 <= p2 <= 0.3

    %-------------------------------------------------------------------

   [direction,msg]=generate_direction(method(randi(numel(method))),superorganism,size_of_superorganism,fit_superorganism);

   map=generate_map_of_active_individuals(size_of_superorganism,size_of_one_clan,p1,p2);

  %-------------------------------------------------------------------
    % Recommended Methods for generation of Scale-Factor; R
    % R=4*randn;  % brownian walk
    % R=4*randg;  % brownian walk
    % R=lognrnd(rand,5*rand);  % brownian walk
     R=1./gamrnd(1,0.5);   % pseudo-stable walk
    % R=1/normrnd(0,5);    % pseudo-stable walk

    %-------------------------------------------------------------------

    % bio-interaction (morphogenesis)
    stopover=superorganism+(R.*map).*(direction-superorganism);

   % Boundary Control
    stopover=update(stopover,low_habitat_limit,up_habitat_limit);

    % Selection-II
    fit_stopover=feval(fnc,stopover,mydata);
    ind=fit_stopover<fit_superorganism;
    fit_superorganism(ind)=fit_stopover(ind);
    superorganism(ind,:)=stopover(ind,:);

   % update results
    [globalminimum,indexbest]=min(fit_superorganism);
    globalminimizer=superorganism(indexbest,:);

    % export results
    assignin('base','globalminimum',globalminimum);
    assignin('base','globalminimizer',globalminimizer);
    fprintf('%s  | %5.0f   --->   %10.16f\n',msg,epk,globalminimum)

end

function pop=genpop(a,b,low,up)
pop=ones(a,b);
for i=1:a
    for j=1:b
        pop(i,j)=rand*(up(j)-low(j))+low(j);
    end
end

function p=update(p,low,up)
[popsize,dim]=size(p);
for i=1:popsize
    for j=1:dim
        % first (standard)-method
        if p(i,j)<low(j), if rand<rand, p(i,j)=rand*(up(j)-low(j))+low(j); else p(i,j)=low(j); end, end
        if p(i,j)>up(j),  if rand<rand, p(i,j)=rand*(up(j)-low(j))+low(j); else p(i,j)=up(j); end, end

        %{
       %  second-method
        if rand<rand,
            if p(i,j)<low(j) || p(i,j)>up(j), p(i,j)=rand*(up(j)-low(j))+low(j); end
        else
            if p(i,j)<low(j), p(i,j)=low(j); end
            if p(i,j)>up(j),  p(i,j)=up(j); end
        end
        %}
    end
end

function [direction,msg]=generate_direction(method,superorganism,size_of_superorganism,fit_superorganism);
 switch method
        case 1,
            % BIJECTIVE DSA  (B-DSA) (i.e., go-to-rnd DSA);
            % philosophy: evolve the superorganism (i.e.,population) towards to "permuted-superorganism (i.e., random directions)"
            direction=superorganism(randperm(size_of_superorganism),:); msg=' B-DSA';
        case 2,
            % SURJECTIVE DSA (S-DSA) (i.e., go-to-good DSA)
            % philosophy: evolve the superorganism (i.e.,population) towards to "some of the random top-best" solutions
            ind=ones(size_of_superorganism,1);
            [null_,B]=sort(fit_superorganism);
            for i=1:size_of_superorganism, ind(i)=B(randi(ceil(rand*size_of_superorganism),1)); end;
            direction=superorganism(ind,:);  msg=' S-DSA';
        case 3,
            % ELITIST DSA #1 (E1-DSA) (i.e., go-to-best DSA)
            % philosophy: evolve the superorganism (i.e.,population) towards to "one of the random top-best" solution
            [null,jind]=sort(fit_superorganism); ibest=jind(ceil(rand*size_of_superorganism)); msg='E1-DSA';
            direction=repmat(superorganism(ibest,:),[size_of_superorganism 1]);
        case 4,
            % ELITIST DSA #2 (E2-DSA) (i.e., go-to-best DSA)
            % philosophy: evolve the superorganism (i.e.,population) towards to "the best" solution
            [null_,ibest]=min(fit_superorganism); msg='E2-DSA';
            direction=repmat(superorganism(ibest,:),[size_of_superorganism 1]);
 end
return

function map=generate_map_of_active_individuals(size_of_superorganism,size_of_one_clan,p1,p2);
    % strategy-selection of active/passive individuals
    map=zeros(size_of_superorganism,size_of_one_clan);
        if rand<rand,
            if rand<p1,
                % Random-mutation #1 strategy
                for i=1:size_of_superorganism
                    map(i,:)=rand(1,size_of_one_clan) < rand;
                end
            else
                % Differential-mutation strategy
                for i=1:size_of_superorganism
                    map(i,randi(size_of_one_clan))=1;
                end
            end
        else
             % Random-mutation #2 strategy
            for i=1:size_of_superorganism
                map(i,randi(size_of_one_clan,1,ceil(p2*size_of_one_clan)))=1;
            end
        end
return


function [favar]=favar_irf(favar,IRFperiods,endo,IRFt,strctident,pref)

% we arranged everything before including transformation
    % pick the relevant shocks (plotXshock)
    favar_irf_estimates=favar.irf_estimates(:,favar.IRF.plotXshock_index);

    % save in favar structure, ready to plot
    favar.IRF.favar_irf_estimates=favar_irf_estimates;

    % plot the IRFs of the factors
    if favar.IRF.plot==1
    irf_favar=figure;
    set(irf_favar,'name','approximate impulse response functions (FAVAR)');
    numIRFs=favar.npltX*favar.IRF.npltXshck; %total number of IRFs to print
    numcol=5;
    numrow=ceil(numIRFs/numcol); % maximum number of rows

    for ii=1:numIRFs
        subplot(numrow,numcol,ii);
        hold on
        Xpatch=[(1:IRFperiods) (IRFperiods:-1:1)];
        Ypatch=[favar.IRF.favar_irf_estimates{ii}(1,:) fliplr(favar.IRF.favar_irf_estimates{ii}(3,:))];
        IRFpatch=patch(Xpatch,Ypatch,[0.7 0.78 1]);
        set(IRFpatch,'facealpha',0.5);
        set(IRFpatch,'edgecolor','none');
        plot(favar.IRF.favar_irf_estimates{ii}(2,:),'Color',[0.4 0.4 1],'LineWidth',2);
        plot([1,IRFperiods],[0 0],'k--');
        hold off
%         minband=min(favar.IRF.irf_factors_final_plotX{ii}(1,:));
%         maxband=max(favar.IRF.irf_factors_final_plotX{ii}(3,:));
%         space=maxband-minband;
%         Ymin=minband-0.2*space;
%         Ymax=maxband+0.2*space;
        set(gca,'XLim',[1 IRFperiods],'FontName','Times New Roman'); %,'YLim',[Ymin Ymax]
        % top labels
   if ii<=favar.IRF.npltXshck
       if IRFt==1||IRFt==2||IRFt==3
       printlabels=endo{favar.IRF.plotXshock_index(1,ii),1};
       elseif IRFt==4||IRFt==5||IRFt==6
       printlabels=strctident.signreslabels{strctident.signreslabels_shocksindex(ii,1)};
        end
   title(printlabels,'FontWeight','normal','interpreter','none');
   end
% side labels
   if rem((ii-1)/favar.IRF.npltXshck,1)==0
   ylabel(favar.informationvariablestrings{1,favar.plotX_index((ii-1)/favar.IRF.npltXshck+1)},'FontWeight','normal','interpreter','none');
   end
    end
    % top supertitle
    ax=axes('Units','Normal','Position',[.11 .075 .85 .88],'Visible','off');
    set(get(ax,'Title'),'Visible','on')
    title('Shock:','FontSize',11,'FontName','Times New Roman','FontWeight','normal');
    % side supertitle
    ylabel('approximate response of:','FontSize',12,'FontName','Times New Roman','FontWeight','normal');
    set(get(ax,'Ylabel'),'Visible','on')
    end

    %% save in excel
    excelrecord4favar


function test_suite = test_expandPolygon
%TESTEXPANDPOLYGON  One-line description here, please.
%   output = testExpandPolygon(input)
%
%   Example
%   testExpandPolygon
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2009-06-17,    using Matlab 7.7.0.471 (R2008b)
% Copyright 2009 INRA - Cepia Software Platform.
% Licensed under the terms of the LGPL, see the file "license.txt"

test_suite = functiontests(localfunctions);

function testSquare(testCase) %#ok<*DEFNU>
p1 = [10 10];
p2 = [20 10];
p3 = [20 20];
p4 = [10 20];
square = [p1;p2;p3;p4];

expanded5 = [5 5;25 5;25 25;5 25];
expanded = expandPolygon(square, 5);
testCase.assertTrue(length(expanded)==1);
testCase.assertTrue(distancePolygons(expanded{1}, expanded5)<1e-14);

function testOverlap(testCase)

% a polygon whose expansion overlaps at critical distance 10
poly = [10 10;190 10;190 140;110 140;110 120;150 120;150 50;50 50;50 100;90 100;90 160;10 160];

% small value: only one outline
expanded = expandPolygon(poly, 5);
testCase.assertTrue(length(expanded)==1);

% value>10: two outlines
expanded = expandPolygon(poly, 20, 'cleanupLoops', true);
testCase.assertTrue(length(expanded)==2);

% value>30: the inner outline disappear
expanded = expandPolygon(poly, 35, 'cleanupLoops', true);
testCase.assertTrue(length(expanded)==1);


%compute dratioarealength

function [data,units]=compute_dratioarealength(trx,n)

larvae=trx.exp2flies{n};
numlarvae=numel(larvae);
dratioarealength=cell(1,numlarvae);
for i=1:numlarvae
    larva=larvae(i);
    dratioarealength{1,i}=(trx(larva).ratioarealength(2:end)-trx(larva).ratioarealength(1:end-1))./trx(larva).dt;
end

units=parseunits('mm/s');
data=dratioarealength;


function M = modelDiagnostics2(finput,varargin)
% M = modelDiagnostics2(finput,optional arguments)
%
% M = modelDiagnostics(stimList,'stimList','all','ISI',1.2,'TR',2,'contrasts',[1 1 -1 -1;1 -1 1 -1],'screen')
%
%M =
%        stimlist: your original list of conditions
%           delta: delta matrix sampled at .01 seconds
%           model: model sampled at .01 seconds
%       modelatTR: model sampled at TR
%        smoothed: temporally smoothed model at TR
%        conmodel: predictors for contrasts
%       consmooth: temporally smoothed predictors for contrasts
%           power: power (abs(fft)) matrix for smoothed model
%        conPower: power matrix for smoothed contrasts
%          energy: sum of squared deviations from mean for each predictor
%       conEnergy: sum of squared deviations from mean for each contrast
%             eff: efficiency of design.  1/trace(xtxi)
%  resampleeffinf: efficiency loss due to resampling compared to TR = 1 s.  eff(TR=1) / eff(TR)
%    smootheffinf: loss of efficiency due to smoothing; eff(nosmooth) / eff(smooth)
%         varbeta: variance of each individual beta
%          coneff: efficiency of contrast set
%      convarbeta: efficiency of each contrast beta
%             vif: variance inflation factors for predictors
%          conVif: variance inflation factors for contrasts
%            cond: condition number of model; larger is worse, > 30 is bad
%         conCond: condition number for contrast set
%           colin: correlation coefficients between individual predictors
%        conColin: correlation coefficients between contrasts
%       cbalfreqs: counterbalancing frequencies up to 3rd order
%            freq: frequencies with which each stimulus type occurs
%
% options: inptType is 'stimList', 'sampledModel','plot' (plot only)
%          outptType is 'all', 'short'
%
%
% More examples:
% M = modelDiagnostics(M.stimlist,'stimList','all','ISI',.85,'TR',2,'contrasts',[1 1 -1 -1],'screen')
% M2 = modelDiagnostics(M,'plot')
%
% Tor Wager, 11/17/01

%------------------------------------------------------------------------------
% Set up arguments and default values
%------------------------------------------------------------------------------
print2screen = 1;
outptType = 'all';
isfilt = 'n';
doverb = 0;
xc = [];

for i = 1:length(varargin)
    if isstr(varargin{i})
        switch varargin{i}
        case 'ISI', ISI = varargin{i+1};
        case 'TR', TR = varargin{i+1};
        case 'HRF', HRF = varargin{i+1};
        case 'HPlength', HPlength = varargin{i+1};
        case 'LPsmooth',LPsmooth = varargin{i+1};
        case 'contrasts',contrasts = varargin{i+1};
		case 'saturate',satval = varargin{i+1};
		case 'contrastweights',contrastweights = varargin{i+1};
		case 'maxOrder',maxOrder = varargin{i+1};
		case 'xc',xc = varargin{i+1};
		case 'screen',print2screen = 1;
		case 'noplot',print2screen = 0;
		case 'brief',outptType = 'brief';
		case 'plot',outptType = 'plot';
		case 'verbose',doverb = 1;
        end
    end
end

if doverb,disp('Computing model descriptives.'),end

% -----------------------------------------------------------------------------------
% * determine output type and just plot if only plot is specified
% -----------------------------------------------------------------------------------

switch outptType
case 'all'
    dopower = 1;doenergy = 1;doeff = 1;dovif = 1;docondnum = 1; dohrf = 1;,
    docolin = 1; docbal = 1;dofreq = 1;dotimes = 0;
case 'brief'
    if doverb,disp('Brief output selected.'),end
    dopower = 0; doenergy = 0; doeff = 0; dovif = 0; docondnum = 0; docolin = 1;
    docbal = 0; dofreq = 1; dotimes = 0; dohrf = 0;
case 'plot'
	M = finput;,if doverb,disp('Using already-computed M and plotting.'),end

	if ~isfield(M.ga,'TR'),M.ga.TR = input('M.ga.TR not found: Enter TR in s: ');,end
	if ~isfield(M.ga,'HPlength'),M.ga.HPlength = input('M.ga.HPlength not found: Enter HPlength in s: ');,end

	% plot predictors
    plotvarious(M,M.ga.TR,'Predictors')

	% make Q structure with contrast information
    Q.model = M.model * M.contrasts';
    try,Q.smoothed = M.consmooth;,catch,disp('Error: contrasts should be empty but they''re not?'),contrasts,end
	Q.modelatTR = resample(Q.model,1,M.ga.TR*10);

	if isempty(M.ga.HPlength), specstring = 'none';,else specstring = 'specify';,end
	[S,KL,KH] = use_spm_filter(M.ga.TR,size(Q.modelatTR,1),'hrf',specstring,M.ga.HPlength);
	if isempty(KH),KH = eye(size(Q.modelatTR));,end
    Q.filtered = Q.modelatTR - KH*(KH'*Q.modelatTR);
    Q.delta = M.delta * M.contrasts(:,1:end-1)';

	% plot contrasts
	plotvarious(Q,M.ga.TR,'Contrasts')

    return

otherwise eval(['help modelDiagnostics']),error('unknown output type')
end         % end switch

% 1. get every finput type to the stage of model at TR

% -----------------------------------------------------------------------------------
% * determine input type and set up.
% -----------------------------------------------------------------------------------
if 		isstruct(finput),inptType = 'Mstruct';
elseif 	size(finput,2) == 1, inptType = 'stimList';
elseif 	size(finput,2) > 1, inptType = 'model'
else	error('Illegal input.')
end

switch inptType
case 'Mstruct'
	if isfield(finput,'ga'),opt = finput.ga;
	else opt = finput;
	end

	M = finput;

    if isfield(M,'contrasts'), contrasts = M.contrasts;, end

    N = fieldnames(opt);
    for i = 1:length(N)
        eval([N{i} ' = opt.' N{i} ';'])
    end

	if ~isfield(M,'stimlist'), error('M must have stimlist field.'), end
	%if isfield(opt,'ISI'), ISI = opt.ISI;, end
	%if isfield(opt,'TR'), TR = opt.TR;, end
	%if isfield(opt,'nonlinthreshold'), satval = opt.nonlinthreshold;, end
	%if isfield(opt,'HPlength'), HPlength = opt.HPlength;, end
	%if isfield(opt,'LPsmooth'), LPsmooth = opt.LPsmooth;, end
	%if isfield(opt,'contrastweights'), contrastweights = opt.contrastweights;, end
	%if isfield(opt,'maxOrder'), maxOrder = opt.maxOrder;, end
	%if isfield(opt,'xc'), xc = opt.xc;, end
	%if isfield(opt,'contrasts'), contrasts = opt.contrasts;, end

    M.stimlist = double(M.stimlist);
	numsamps = ceil(size(M.stimlist,1) * ISI ./ TR);

case 'model'
	M.model = finput;
	M.modelatTR = M.model;
	if ~(sum(M.model(:,size(M.model,2))) == size(M.model,1))
		disp('No intercept detected in last column:  Adding intercept.')
		M.model(:,size(M.model,2)+1) = 1;
		M.modelatTR(:,size(M.modelatTR,2)+1) = 1;
        isfilt = input('Is the model filtered? (y/n) ','s');
        if strcmp(isfilt,'y')
            M.smoothed = M.modelatTR;
        end
	end
    numsamps = size(M.modelatTR,1);
    dohrf = 0;      % can''t do hrf without delta function input
    dofreq = 0;
    docbal = 0;

case 'stimList'

	numsamps = ceil(size(finput,1) * ISI ./ TR);
	M.stimlist = finput;
	M.stimlist = double(M.stimlist);

end 	% end switch

% -----------------------------------------------------------------------------------
% * build X model matrix, if necessary
% -----------------------------------------------------------------------------------
if ~strcmp(inptType,'model')
	if ~exist('ISI') == 1, ISI = input('Enter ISI in s: ');,end
	if ~exist('TR') == 1, TR = input('Enter TR in s: ');,end
	if ~exist('satval') == 1, satval = 2; ,end    % satval = input('Enter saturation threshold in s: ');,end
	if ~exist('HRF') == 1,
    	HRF = spm_hrf(.1);
    	HRF = HRF / max(HRF);
	end

	[M.modelatTR,M.model,M.delta] = rna2model(M.stimlist,ISI,HRF,TR,numsamps,satval,[]);
end

% 2. set up contrast and smoothing matrices

% -----------------------------------------------------------------------------------
% * set up filtering/smoothing and contrasts, do filtering
% -----------------------------------------------------------------------------------
if ~exist('TR') == 1, TR = input('Enter TR in s: ');,end
if ~exist('HPlength') == 1, HPlength = input('Enter HPlength in s: ');,end
if ~exist('LPsmooth') == 1, LPsmooth = input('Enter LPsmooth value (1,0): ');,end
if ~exist('contrasts') == 1, contrasts = input('Enter contrast matrix: ');,end
if ~exist('contrastweights') == 1, contrasts, contrastweights = input('Enter contrast weight vector: ');,end

if doverb,fprintf(1,'setting up filtering...'),end

% get smoothing matrix
[S,Vi,svi] = getSmoothing(HPlength,LPsmooth,TR,numsamps,xc);

% set up contrast weights
if isempty(contrastweights),contrastweights = ones(1,size(contrasts,1));,end

% set up contrasts for testing individual predictors (contrasts empty)
if isempty(contrasts),
	contrasts = eye(size(M.model,2) - 1);
	contrasts(:,end+1) = 0;
end

% make sure contrasts are the right length
if size(M.model,2) > size(contrasts,2)
		% warning('Model is larger than contrasts - extra intercept?  Adding to contrasts...')
		contrasts = [contrasts zeros(size(contrasts,1),size(M.model,2) - size(contrasts,2))];
end

if size(M.model,2) < size(contrasts,2)
    warning('Model is smaller than contrasts - extra zero in contrasts?  Truncating...')
	contrasts = contrasts(:,1:size(M.model,2));
end

if isempty(S), S = 1;,end
if ~(strcmp(inptType,'model')) | strcmp(isfilt,'n')
    M.smoothed = S * M.modelatTR;
end

% -----------------------------------------------------------------------------------
% * assign other output values to M structure
% -----------------------------------------------------------------------------------

M.contrasts = contrasts;
M.ga.contrasts = contrasts;
M.ga.TR = TR;
if exist('ISI') == 1, M.ga.ISI = ISI;, end
M.ga.HPlength = HPlength;
M.ga.LPsmooth = LPsmooth;
M.ga.contrastweights = contrastweights;
M.ga.xc = xc;

% -----------------------------------------------------------------------------------
% * make contrast-space predictors
% -----------------------------------------------------------------------------------
if isempty(contrasts)
    contrasts = eye(size(M.model,2));
end

try
	M.conmodel = M.modelatTR * contrasts';
catch
		whos contrasts
		M
		warning('Contrasts are different size from modelatTR.  This should not happen.  Adding intercept 0 to contrast and trying again...')
		contrasts = [contrasts zeros(size(contrasts,1),1)];
		M.contrasts = contrasts;
end

M.conmodel = M.modelatTR * contrasts';
M.consmooth = M.smoothed * contrasts';

% -----------------------------------------------------------------------------------
% * calculate individual field values
% -----------------------------------------------------------------------------------

if doenergy
    M.energy = var(M.smoothed) * size(M.smoothed,1);
    M.conEnergy = var(M.consmooth) * size(M.consmooth,1);
end

if doeff                                                        		% calculate efficiency
    if doverb,fprintf(1,'eff...'),end
	xtxitx = pinv(M.smoothed);                                       	% inv(X'S'SX)*(SX)'; pseudoinv of (S*X)
	[M.eff_fitness,M.eff] = calcEfficiency(M.ga.contrastweights,contrasts,xtxitx,svi);
    M.eff = M.eff';
	M.se_contrasts = 1 ./ M.eff;

    % ========= calc inefficiency of sampling and smoothing ===============
	myeff = 1/trace(inv(M.smoothed'*M.smoothed));                 % brief form of model efficiency, not considering autocorrelation
    noresampeff = 1/trace(inv(M.model'*M.model));                 % what would have happened at TR = .1?
    nosmootheff = 1/trace(inv(M.modelatTR'*M.modelatTR));
    M.resample_eff_loss = noresampeff / nosmootheff;
    M.smoothing_eff_loss = nosmootheff / myeff;

end

if dohrf
    if doverb,fprintf(1,'DX...'),end
    delta = [];
    for i = 1:max(M.stimlist(:,1))
        delta(:,i) = (M.stimlist == i);
    end
    %[M.DX] = tor_make_deconv_mtx2(M.delta,round(12 / M.ga.TR),10 * M.ga.TR);
    [M.DX] = tor_make_deconv_mtx2(delta,round(12 / M.ga.TR),M.ga.TR / M.ga.ISI);
    if ~isempty(S), M.DX = S * M.DX;,end
    xtxitx = pinv(M.DX);                                       		% inv(X'S'SX)*(SX)'; pseudoinv of (S*X)
    [M.hrf_eff_fitness,M.hrf_eff] = calcEfficiency([],[],xtxitx,svi);
    M.hrf_eff_avg = mean(M.hrf_eff(1:end-1));
end

if dovif
    if doverb,fprintf(1,'VIFs...'),end
	warning off
    M.vif = getvif(M.smoothed);
    if ~isempty(M.consmooth)
        M.conVif = getvif(M.consmooth);
    end
	warning on
end

if docondnum                                                    % calculate condition numbers
    M.cond = cond(M.smoothed);
    if ~isempty(M.consmooth)
        M.conCond = cond(M.consmooth);
    end
end
warning off
if docolin                                                      %   calculate predictor colinearity
    if doverb,fprintf(1,'colin...'),end
    % sqrt of average squared correlation
      colin = corrcoef(M.smoothed);
      M.colin = colin;
      if ~isempty(M.consmooth)
        colin = corrcoef(M.consmooth);
        M.conColin = colin;
      end
end
warning on
% calculate counterbalancing
if docbal
    if doverb,fprintf(1,'cbal...'),end
	if ~exist('maxOrder') == 1, maxOrder = input('Enter max counterbalancing order: ');,end

	conditions = 1:max(M.stimlist);
	freqConditions = ones(1,size(conditions,2)) / size(conditions,2);
    [M.cBal M.cbalfreqs] = getCounterBal(M.stimlist, maxOrder,conditions,freqConditions);
    % M.cbalfreqs = round(M.cbalfreqs * 100);
end

if dofreq
    for i = 1:size(conditions,2)
         M.freq(i) = sum(M.stimlist == conditions(i)) / size(M.stimlist,1);
    end
end

% calculate average time between stimulus repetitions in each trial type
if isfield(M,'stimlist')
    for i = 1:max(M.stimlist),M.timeBtwn(i) = mean(diff(find(M.stimlist==i))) .* M.ga.ISI;, end
end

if print2screen
    format short g
    format compact

    plotvarious(M,TR,'Predictors')
    if ~isempty(M.consmooth)
        Q.model = M.model * contrasts';
		Q.modelatTR  = M.modelatTR * contrasts';
        Q.smoothed = M.consmooth;
        Q.delta = M.delta * contrasts(:,1:end-1)';
        plotvarious(Q,TR,'Contrasts')
    end
end

if doverb
    disp(' ')
    disp('Correlated columns:')
    [x,y] = find(abs(corrcoef(xX.X)) > .5 & abs(corrcoef(xX.X)) < 1); [x y]
end
return

% subfunctions
% ================================================================== %
function plotvarious(M,TR,textlbl)

    if strcmp(textlbl,'Contrasts'), contit = 1;, else, contit = 0;, end

    % image the model
    % --------------------------------------

   figure; set(gcf,'Color','w')
    imagesc(M.modelatTR);colormap(copper)
    numsamp = size(M.smoothed,1);

    if contit
        title('Optimized Contrasts Heatmap, after filtering','FontSize',14)
    else
        title('Optimized Model Heatmap, after filtering','FontSize',14)
    end

    if isfield(M,'delta')
    	numregs = size(M.delta,2);
	% subtract one b/c last one is assumed to be intercept? sometimes...not always.

    else
	numregs = size(M.smoothed,2);	% subtract one b/c last one is assumed to be intercept? sometimes...not always.
    end

    nummodel = size(M.model,1);
    numsecs = numsamp * TR;
    deltascale = .1;
    x = 1:deltascale:numsecs+1;
    x = x(1:nummodel);
    x2 = 1:TR:numsecs+1;
    x2 = x2(1:numsamp);
    ymin = min(min(M.smoothed));
    ymax = max(max(M.smoothed));

    % Plot all columns in model after resampling and smoothing
    % --------------------------------------

    figure;set(gcf,'Color','w')
    for i = 1:numregs
  	  subplot(numregs,1,i)
      hold on
      plot(x,M.model(:,i),'k','LineWidth',1.5)
      plot(x2,M.modelatTR(:,i),'b','LineWidth',1.5)
      plot(x2,M.smoothed(:,i),'r','LineWidth',1.5)
      if isfield(M,'delta')
        for j = 1:size(M.delta,1)
            if M.delta(j,i) == 1
                plot([j*deltascale j*deltascale],[ymin 0],'k')
            end
        end
      end
      set(gca,'Ylim',[ymin ymax]);
      %axis([0 100 ymin ymax])
      set(gca,'XColor',[0 0 1])
      set(gca,'YColor',[0 0 1])
    end
    subplot(numregs,1,1);
    if contit
        title('Optimized Model Contrasts and Onsets','FontSize',14)
    else
        title('Optimized Model Regressors and Onsets','FontSize',14)
    end

    legend({'high-resolution' 'sampled at TR' 'filtered'})
    %title(textlbl,'FontSize',14)
    %title([textlbl ' Green: high-resolution   Blue: resampled at TR   Red: sampled and HP/LP filtered (smoothed)'])
    drawnow

    % Plot first column at various stages
    % --------------------------------------

    figure;set(gcf,'Color','w')
        subplot(3,1,1)
        ymin = min(min(M.model));
        ymax = max(max(M.model));
        plot(x,M.model(:,1),'k','LineWidth',2)
        title([textlbl '(#1): Original model - high samp rate'])
        set(gca,'Ylim',[ymin ymax]);
        if contit
            title('Optimized Model - first Contrast','FontSize',14)
        else
            title('Optimized Model - first Regressor','FontSize',14)
        end

        %axis([0 100 -1 2])
        subplot(3,1,2)
        plot(x2,M.modelatTR(:,1),'k','LineWidth',2)
        title('Resampled at TR')
        set(gca,'Ylim',[ymin ymax]);
        %axis([0 100 -1 2])
        subplot(3,1,3)
        plot(x2,M.smoothed(:,1),'k','LineWidth',2)
        title('Filtered')
        set(gca,'Ylim',[ymin ymax]);
        % axis([0 100 -1 2])

    drawnow

return


% Extended Kalman Filter.
%
% Files
%   innovation      - Innovation of an observation.
%   correctBlockEkf - Correct in block-defined EKF.
%   predictBlockEkf - Covariance predict in block-defined EKF.


function p = obj2pnts(obj)

% OBJ2PNTS Get points matrix from 3D object.
%   OBJ2PNTS(OBJ) returns the 3-by-N matrix of points in the structure OBJ,
%   stored in the N-by-3 matrix OBJ.vert.

%   Copyright 2009 Joan Sola @ LAAS-CNRS.

p = obj.vert';

% ========== 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 [i,pC,pE,Np] = spm_find_pC(varargin)
% Utility routine that finds the indices of non-zero covariance
% FORMAT [i,pC,pE,Np] = spm_find_pC(pC,pE,fields)
% FORMAT [i,pC,pE,Np] = spm_find_pC(DCM,fields)
% FORMAT [i,pC,pE,Np] = spm_find_pC(DCM)
%
% pC     - covariance matrix or variance stucture
% pE     - parameter structure
% fields - desired fields of pE
%
% or
%
% DCM    - DCM structure
%
% i      - find(diag(pC) > TOL)
% rC     - reduced covariances
% rE     - reduced expectation
%
%__________________________________________________________________________
% Copyright (C) 2015-2019 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_find_pC.m 7714 2019-11-26 11:25:50Z spm $

%-parse input arguments
%--------------------------------------------------------------------------
if nargin > 2
    pC     = varargin{1};
    pE     = varargin{2};
    fields = varargin{3};
elseif numel(varargin) > 1
    DCM    = varargin{1};
    fields = varargin{2};
else
    DCM    = varargin{1};
end

%-get prior density from DCM
%--------------------------------------------------------------------------
if nargin < 3
    if ischar(DCM)
        DCM = load(DCM,'DCM');
        DCM = DCM.DCM;
    end
    if any(isfield(DCM,{'options','M'}))
        try, [pC,pE] = spm_find_rC(DCM); end
    end
end

%-Deal with variance structures
%--------------------------------------------------------------------------
if isstruct(pC)
    q = spm_vec(pC);
else
    q = diag(pC);
end

%-Get indices
%--------------------------------------------------------------------------
i  = find(q > mean(q(q < 1024))/1024);
Np = numel(q);

%-subsample fields if necessary
%--------------------------------------------------------------------------
if nargin > 1
    if ischar(fields), fields = {fields}; end
    if isstruct(pE)
        j = spm_fieldindices(pE,fields{:});
        if isempty(j) && ~(~isempty(fields) && strcmp(fields{1},'none'))
            warning('%s not found. Returning all fields',...
                strjoin(cellstr(fields),','));
        else
            i = j(ismember(j,i));
        end
    end
end

return

function [pC,pE] = spm_find_rC(DCM)
% FORMAT [pC,pE] = spm_find_rC(DCM)
% model priors
%__________________________________________________________________________

% Get full priors and posteriors
%--------------------------------------------------------------------------
try
    pC  = DCM.M.pC;
    pE  = DCM.M.pE;
    return
end

% get priors from model specification
%--------------------------------------------------------------------------
if isfield(DCM.options,'spatial')

    % EEG or MEG
    %----------------------------------------------------------------------
    if strcmpi(DCM.options.analysis,'IND')
        [pE,dummy,pC] = spm_ind_priors(DCM.A,DCM.B,DCM.C,DCM.Nf);
    else
        [pE,  pC] = spm_dcm_neural_priors(DCM.A,DCM.B,DCM.C,DCM.options.model);

        try                                                     %#ok<TRYNC>
            try model   = DCM.options.model;   catch, model    = 'NMM'; end
            try spatial = DCM.options.spatial; catch, spatial  = 'LFP'; end
            DCM.M.dipfit.model = model;
            DCM.M.dipfit.type  = spatial;
            [pE,  pC] = spm_L_priors(DCM.M.dipfit,pE,pC);
            [pE,  pC] = spm_ssr_priors(pE,pC);
        end
    end

else

    % fMRI
    %----------------------------------------------------------------------
    if ~isfield(DCM,'d')
        DCM.d = zeros(size(DCM.a,1),size(DCM.a,1),0);
    end
    [pE,pC]   = spm_dcm_fmri_priors(DCM.a,DCM.b,DCM.c,DCM.d,DCM.options);
end


function [paramtransformsettings, names] = nddisimKernExtractParamTransformSettings(kern)

% NDDISIMKERNEXTRACTPARAMTRANSFORMSETTINGS Extract parameter transform settings from the NDDISIM kernel structure.
% FORMAT
% DESC Extract parameters from the single input motif kernel structure
% into a vector of parameters for optimisation.
% ARG kern : the kernel structure containing the parameters to be
% extracted.
% RETURN param : vector of parameters extracted from the kernel. If
% the field 'transforms' is not empty in the kernel matrix, the
% parameters will be transformed before optimisation (for example
% positive only parameters could be logged before being returned).
%
% FORMAT
% DESC Extract parameters and their names from the single input
% motif kernel structure.
% ARG kern : the kernel structure containing the parameters to be
% extracted.
% RETURN param : vector of parameters extracted from the kernel. If
% the field 'transforms' is not empty in the kernel matrix, the
% parameters will be transformed before optimisation (for example
% positive only parameters could be logged before being returned).
% RETURN names : cell array of strings containing parameter names.
%
% SEEALSO disimKernParamInit, disimKernExpandParam, kernExtractParam, scg, conjgrad
%
% COPYRIGHT : Neil D. Lawrence, 2006
%
% COPYRIGHT : Antti Honkela, 2007-2009
%
% COPYRIGHT : Jaakko Peltonen, 2011
%
% KERN

paramtransformsettings = {kern.transforms(1).transformsettings,kern.transforms(2).transformsettings,kern.transforms(3).transformsettings,kern.transforms(4).transformsettings,kern.transforms(5).transformsettings};

if nargout > 1
  names = {'inverse width', 'di_variance', 'decay', 'variance', 'delay'};
end

%fprintf(1, 'disimKern parameters physical values:\n');
%params
%names


function y_one_hot = one_hot(y)

y_one_hot = zeros(size(y, 1), 30);
for i = 1:30 % TODO: 30 3D models in the graph
    rows = y == i;
    y_one_hot( rows, i ) = 1;
end


% Calibrate camera counts for the number of detected photons.
pathfile = './';
dark = readtimeseries([pathfile 'R_20110413/Dark_2/img_000000*__000.tif']);
bright = readtimeseries([pathfile 'R_20110413/Bright_2/img_000000*__000.tif']);
sv= size(bright);
out_cal = cal_readnoise(bright, dark(0:sv(1)-1,0:sv(2)-1,:));


function[]=xoffset(i1,i2)
%XOFFSET  Offsets lines in the x-direction after plotting.
%
%   XOFFSET allows data to be manipulated after it has been plotted, by
%   operating on the data stored in the figure itself.  This may be used
%   only with 2-D line plots (not symbol plots, contour plots, etc.).
%
%   XOFFSET offsets all lines in the current axes a specified amount.
%
%   XOFFSET(N) or XOFFSET N, where N is a *real* number, offsets each
%   column of the X-data by an amount N from the previous column.  N must
%   be a number, not a variable whose value is a number.
%
%   XOFFSET(N) or XOFFSET N, where N is an *imaginary* number, offsets
%   each column of the X-data by an amount imag(N)*DX from the previous
%   column, where DX is the X-axis length of the original (unoffset) plot.
%
%   XOFFSET(M,N) or XOFFSET M N, applies the same offsets to each of M
%   groups of lines. For example, for complex-valued data Z use UVPLOT(Z)
%   followed by XOFFSET 2 N.
%
%   XOFFSET with no arguments returns the data to its original (unoffset)
%   orientation [as do XOFFSET(0) and XOFFSET(0i)].
%
%   XOFFSET also allow multiple axes to be manipulated simultaneously.
%
%   XOFFSET LOCK and XOFFSET UNLOCK lock and unlock all Y-data in the
%   current figure. When LOCK is on, calls to XOFFSET are applied to each
%   subplot individually.
%
%   See also YOFFSET, LINESTYLE.
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2000--2015 J.M. Lilly --- type 'help jlab_license' for details

if strcmpi(i1,'--t')
    return
end

if nargin==1;
  N=10000;  %Very large number of lines
end
if nargin==2
  N=i1;
  i1=i2;
  if ischar(N)
    N=str2double(N);
  end
end

bcontinue=1;
if nargin>0
   if ischar(i1)
      if isempty(str2double(i1))
           i1=deblank(i1);
           i1=fliplr(deblank(fliplr(i1)));
           if strcmpi(i1,'lock')
                if isappdata(gca,'lastxoffset')
                    lastoff=getappdata(gca,'lastxoffset');
                    setappdata(gcf,'xoffsetlock',1)
                    xoffsetloop(0,N);
                    xoffsetloop(lastoff,N);
                else
                    setappdata(gcf,'xoffsetlock',1)
                end
                bcontinue=0;
            end
            if strcmpi(i1,'unlock')
                setappdata(gcf,'xoffsetlock',0)
                bcontinue=0;
            end
      end
   end
end

if bcontinue
   if nargin>0
      delta=i1;
   else
      delta=0;
   end

   h=linehandles;
   if plotmodified(h)
   %If the plot has been changed, the old "lastxoffset" may no
   %longer be correct.  If so, we set it to zero
       setappdata(gca,'lastxoffset',0)
   end
   xoffsetloop(delta,N);
end

function[]=xoffsetloop(delta,N)
h=gca;
if isappdata(gcf,'xoffsetlock')
   if getappdata(gcf,'xoffsetlock')
      h=axeshandles(gcf);
   end
end

for i=1:length(h)
    axes(h(i))
    if isappdata(gca,'lastxoffset')
       lastdelta=getappdata(gca,'lastxoffset');
       xoffsetapply(-1*lastdelta,N);
       setappdata(gca,'lastxoffset',0)
    end
    xoffsetapply(delta,N);
end

axes(h(1))

function[]=xoffsetapply(delta,N)
h=linehandles;

if ischar(delta),delta=str2double(delta);end
xx=get(h,{'xdata'});

if length(delta)==1 && ~isreal(delta)
   ax=axis;
   dx=ax(2)-ax(1);
   delta=dx.*imag(delta)/100;
end

if length(delta)==1
   for i=length(xx):-1:1
       xx{i}=xx{i}+delta*(mod(length(xx)-i,round(length(xx)/N)));
   end
elseif length(delta)==length(h)
   for i=length(xx):-1:1
       xx{i}=xx{i}+delta(i);
   end
else
   error('Number of line handles does not equal offset array length.')
end

set(h,{'xdata'},xx);
setappdata(gca,'lastxoffset',delta)
setappdata(gca,'lasthandles',h)

function[b]=plotmodified(h)
b=0;
if isappdata(gca,'lasthandles')
  b=1;
  h2=getappdata(gca,'lasthandles');
  if length(h2)==length(h)
      if all(h2==h)
          b=0;
      end
  end
end


function [MStitch, result] = GrayListMain_Process(file)
for i = 1 : length(file)-1
    if i == 1
        file1 = file{i};
        im1 = imread(file1);
        im1 = rgb2gray(im1);
        MStitch.im1 = double(im1);

        [Pheight, Pwidth] = size(im1);

        MStitch.Pwidth = Pwidth;
        MStitch.Pheight = Pheight;

        MStitch.W_min = round(0.60*Pwidth);
        MStitch.W_max = round(0.83*Pwidth);
        MStitch.H_min = round(0.98*Pheight);
        MStitch.minval = 255;

        im1 = imread(file1);
        MStitch.imrgb1 = double(im1);
        im1 = rgb2gray(im1);
        MStitch.im1 = double(im1);
    else
        MStitch.im1 = double(result1);
    end
    file2 = file{i+1};
    im2 = imread(file2);
    MStitch.imrgb2 = double(im2);
    im2 = rgb2gray(im2);
    im2 = double(im2);
    [W_box, H_box, bdown, MStitch] = Fun_Match(im2, MStitch);
    [MStitch, result1] = Fun_Stitch(im2, W_box, H_box, bdown, MStitch);
end
result = result1;


function pcut = addEvalVariableCuts(p)

pcut = p;
if ~isempty(p.evalMap)
    pcut = emptyNumericalModel;
    for i = 1:length(p.evalMap)
        y = p.evalVariables(i);
        x = p.evalMap{i}.variableIndex;
        xL = p.lb(x);
        xU = p.ub(x);

        % Generate a convex hull polytope
        if xL<xU
            % If there is no convex hull method available, we might
            % generate one if we are in a a region where convexity is known
            if isempty(p.evalMap{i}.properties.convexhull)
                p.evalMap{i}.properties.convexhull = createConvexHullMethod(p.evalMap{i},xL,xU);
                remove_auto_generated_convexhull = 1;
            else
                remove_auto_generated_convexhull = 0;
            end
            if ~isempty(p.evalMap{i}.properties.convexhull)
                % A convex hull generator function is available!
                % Might be able to reuse hull from last run node
                if isfield(p.evalMap{i},'oldhull') && isequal(p.evalMap{i}.oldhull.xL,xL) && isequal(p.evalMap{i}.oldhull.xU,xU)
                    [Ax,Ay,b,K] = getOldHull(p,i);
                else
                    [Ax,Ay,b,K,p] = updateHull(xL,xU,p,i);
                    if isempty(Ax)
                        % Operator bounder does not cover this interval so
                        % use the sample-based instead
                        [Ax,Ay,b,K,p] = convexhullSampled(xL,xU,p,i);
                    end
                end
                if remove_auto_generated_convexhull
                    p.evalMap{i}.properties.convexhull = [];
                end
            elseif ~(any(isinf(xL)) | any(isinf(xU)))
                [Ax,Ay,b,K] = convexhullSampled(xL,xU,p,i);
            else
                Ax = [];
                Ay = [];
                b = [];
                K = [];
            end
            if ~isempty(b)
                removeThese = find(any(isnan([Ax Ay b]),2) | any(isinf([Ax Ay b]),2));
                if any(removeThese)
                    Ax(removeThese,:) = [];
                    Ay(removeThese,:) = [];
                    b(removeThese) = [];
                    K.l = K.l - nnz(removeThese > K.f);
                    K.f = K.f - nnz(removeThese <= K.f);
                end
                F_structemp = zeros(size(b,1),length(p.c)+1);
                F_structemp(:,1+y) = -Ay;
                F_structemp(:,1+x) = -Ax;
                F_structemp(:,1) = b;
                localModel = createNumericalModel(F_structemp,K);
                pcut = mergeNumericalModels(pcut,localModel);
            end
        end
    end

    pcut = mergeNumericalModels(p,pcut);
end

function [Ax,Ay,b,K] = getOldHull(p,i)

Ax = p.evalMap{i}.oldhull.Ax;
Ay = p.evalMap{i}.oldhull.Ay;
b = p.evalMap{i}.oldhull.b;
K = p.evalMap{i}.oldhull.K;

function [Ax,Ay,b,K,p] = updateHull(xL,xU,p,i)

if strcmpi(p.evalMap{i}.fcn,'blackbox')
    [Ax,Ay,b,K]=feval(p.evalMap{i}.properties.convexhull,xL,xU);
else
    [Ax,Ay,b,K]=feval(p.evalMap{i}.properties.convexhull,xL,xU, p.evalMap{i}.arg{2:end-1});
end
if ~isempty(Ax)
    removeThese = find(any(isinf([Ax Ay b]),2) | any(isnan([Ax Ay b]),2));
    if any(removeThese)
        Ax(removeThese,:) = [];
        Ay(removeThese,:) = [];
        b(removeThese) = [];
        K.l = K.l - nnz(removeThese > K.f);
        K.f = K.f - nnz(removeThese <= K.f);
    end
end
p = saveOldHull(xL,xU,Ax,Ay,b,K,p,i);

function p = saveOldHull(xL,xU,Ax,Ay,b,K,p,i)
p.evalMap{i}.oldhull.xL = xL;
p.evalMap{i}.oldhull.xU = xU;
p.evalMap{i}.oldhull.Ax = Ax;
p.evalMap{i}.oldhull.Ay = Ay;
p.evalMap{i}.oldhull.b = b;
p.evalMap{i}.oldhull.K = K;

function [Ax,Ay,b,K,p] = convexhullSampled(xL,xU,p,i)

if length(xL)>1
    Ax = [];
    Ay = [];
    b = [];
    K = [];
    return
end
% sample function
z = linspace(xL,xU,100);

if isequal(p.evalMap{i}.fcn,'power_internal2')
    % Special code for automatically converting sigmonial
    % terms to be solvable with bmibnb
    fz = feval(p.evalMap{i}.fcn,z,p.evalMap{i}.arg{2});
else
    arg = p.evalMap{i}.arg;
    arg{1} = z;
    vectorized = 1;
    fz = real(feval(p.evalMap{i}.fcn,arg{1:end-1}));
    if length(fz) ~= length(z)
        % Operator is not vectorized?
        vectorized = 0;
        fz = [];
        for k = 1:length(z)
            arg{1} = z(k);
            fz = [fz real(feval(p.evalMap{i}.fcn,arg{1:end-1}))];
        end
    end
    if length(fz) ~= length(z)
        Ax = [];
        Ay = [];
        b = [];
        K = [];
        return
    end
    if isa(p.evalMap{i}.properties.stationary,'function_handle')
        [xS,fS] = feval(p.evalMap{i}.properties.stationary,xL,xU);
        if ~isempty(xS)
            % Add stationary points to the list of samples
            z = [z xS(:)'];
            fz = [fz fS(:)'];
        end
    end
    [minval,minpos] = min(fz);
    [maxval,maxpos] = max(fz);
    xtestmin = linspace(z(max([1 minpos-5])),z(min([100 minpos+5])),100);
    xtestmax = linspace(z(max([1 maxpos-5])),z(min([100 maxpos+5])),100);
    if vectorized
        arg{1} = xtestmin;
        fz1 = real(feval(p.evalMap{i}.fcn,arg{1:end-1}));
        arg{1} = xtestmax;
        fz2 = real(feval(p.evalMap{i}.fcn,arg{1:end-1}));
        z = [z(:);xtestmin(:);xtestmax(:)];
        fz = [fz(:);fz1(:);fz2(:)];
    else
        fz1 = [];
        for k = 1:length(xtestmin)
            arg{1} = xtestmin(k);
            fz1 = [fz1 real(feval(p.evalMap{i}.fcn,arg{1:end-1}))];
        end
        fz2 = [];
        for k = 1:length(xtestmax)
            arg{1} = xtestmax(k);
            fz2 = [fz2 real(feval(p.evalMap{i}.fcn,arg{1:end-1}))];
        end
    end
    [z,sorter] = sort(z);
    fz = fz(sorter);
    [z,ii,jj]=unique(z);
    fz = fz(ii);
end
if max(fz)-min(fz) < 1e-4
    Ax = [];
    Ay = [];
    b = [];
    K = [];
    return
end
[Ax,Ay,b,K] = convexhullFromSampled(z,fz,xL,xU);
removeThese = find(any(isnan([Ax Ay b]),2) | any(isinf([Ax Ay b]),2));
Ax(removeThese,:) = [];
Ay(removeThese,:) = [];
b(removeThese) = [];
K.l = K.l - length(removeThese);%[];
p = saveOldHull(xL,xU,Ax,Ay,b,K,p,i);


%%*****************************************************************
%% NTrhsfun: compute the right-hand side vector of the
%%           Schur complement equation for the NT direction.
%%*****************************************************************
%% SDPT3: version 4.0
%% Copyright (c) 1997 by
%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************

    function [rhs,EinvRc,hRd] = NTrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ);

    spdensity = par.spdensity;
    m = length(rp);
    if (nargin > 8)
       corrector = 1;
    else
       corrector = 0;
       hRd = zeros(m,1);
    end
    hEinvRc = zeros(m,1);
    EinvRc  = cell(size(blk,1),1);
    rhsfree = [];
%%
    for p = 1:size(blk,1)
        pblk = blk(p,:);
        n = sum(pblk{2});  numblk = length(pblk{2});
        if strcmp(pblk{1},'l')
	   if iscell(sigmu)
              EinvRc{p} = sigmu{p}./Z{p} -X{p};
	   else
              EinvRc{p} = sigmu./Z{p} -X{p};
           end
           Rq = sparse(n,1);
           if (corrector) & (norm(par.parbarrier{p})==0)
              Rq = dX{p}.*dZ{p}./Z{p};
           else
              tmp  = par.dd{p}.*Rd{p};
              tmp2 = mexMatvec(At{p},tmp,1);
              hRd = hRd + tmp2;
           end
	   EinvRc{p} = EinvRc{p} - Rq;
           tmp2 = mexMatvec(At{p},EinvRc{p},1);
           hEinvRc = hEinvRc + tmp2;
	elseif strcmp(pblk{1},'q')
	   if iscell(sigmu)
              EinvRc{p} = qops(pblk,-sigmu{p}./(par.gamz{p}.*par.gamz{p}),Z{p},4) -X{p};
	   else
              EinvRc{p} = qops(pblk,-sigmu./(par.gamz{p}.*par.gamz{p}),Z{p},4) -X{p};
           end
           Rq = sparse(n,1);
   	   if (corrector) & (norm(par.parbarrier{p})==0)
              w = sqrt(par.gamz{p}./par.gamx{p});
              hdx = qops(pblk,w,par.ff{p},5,dX{p});
              hdz = qops(pblk,w,par.ff{p},6,dZ{p});
              hdxdz = Arrow(pblk,hdx,hdz);
              vv = qops(pblk,w,par.ff{p},5,X{p});
              Vihdxdz = Arrow(pblk,vv,hdxdz,1);
              Rq = qops(pblk,w,par.ff{p},6,Vihdxdz);
           else
              tmp  = par.dd{p}.*Rd{p} + qops(pblk,qops(pblk,Rd{p},par.ee{p},1),par.ee{p},3);
              tmp2 = mexMatvec(At{p},tmp,1);
              hRd = hRd + tmp2;
           end
	   EinvRc{p} = EinvRc{p} - Rq;
           tmp2 = mexMatvec(At{p},EinvRc{p},1);
           hEinvRc = hEinvRc + tmp2;
        elseif strcmp(pblk{1},'s')
           n2 = pblk{2}.*(pblk{2}+1)/2;
	   if iscell(sigmu)
     	      %%ss = [0,cumsum(pblk{2})];
              %%sigmuvec = zeros(n,1);
              %%for k = 1:length(pblk{2});
              %%   sigmuvec(ss(k)+1:ss(k+1)) = sigmu{p}(k)*ones(pblk{2}(k),1);
              %%end
              sigmuvec = mexexpand(pblk{2},sigmu{p});
              tmp = spdiags(sigmuvec./par.sv{p} -par.sv{p},0,n,n);
           else
              tmp = spdiags(sigmu./par.sv{p} -par.sv{p},0,n,n);
           end
           EinvRc{p} = Prod3(pblk,par.G{p}',tmp,par.G{p},1);
           Rq = sparse(n,n);
           if (corrector) & (norm(par.parbarrier{p})==0)
              hdZ = Prod3(pblk,par.G{p},dZ{p},par.G{p}',1);
              hdX = spdiags(qops(pblk,par.parbarrier{p}',1./par.sv{p},3)-par.sv{p},0,n,n)-hdZ;
              tmp = Prod2(pblk,hdX,hdZ,0);
              tmp = 0.5*(tmp+tmp');
              if (numblk == 1)
                 d = par.sv{p};
                 e = ones(pblk{2},1);
                 Rq = 2*tmp./(d*e'+e*d');
                 if (nnz(Rq) <= spdensity*n2); Rq = sparse(Rq); end
              else
                 Rq = sparse(n,n);
                 ss = [0, cumsum(pblk{2})];
                 for i = 1:numblk
                    pos = [ss(i)+1 : ss(i+1)];
                    d = par.sv{p}(pos); e = ones(length(pos),1);
                    Rq(pos,pos) = 2*tmp(pos,pos)./(d*e' + e*d');
                 end
              end
              Rq = Prod3(pblk,par.G{p}',Rq,par.G{p},1);
           else
              tmp = Prod3(pblk,par.W{p},Rd{p},par.W{p},1,par.nzlistAy{p});
              tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),{tmp});
              hRd = hRd + tmp2;
           end
           EinvRc{p} = EinvRc{p} - Rq;
           tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p));
           hEinvRc = hEinvRc + tmp2;
        elseif strcmp(pblk{1},'u')
           rhsfree = [rhsfree; Rd{p}];
        end
    end
%%
    rhs = rp + hRd - hEinvRc;
    rhs = full([rhs; rhsfree]);
%%*******************************************************************


classdef prtClusterKmodes < prtCluster %prtClass %prtAction %should extent prtCluster
    %
    %   Example:
    %
    %   ds = prtDataGenMoon;                 % Load a prtDataSet
    %   clusterAlgo = prtClusterKmodes;      % Create a prtClusterKmeans object
    %   clusterAlgo.nClusters = 3;           % Set the number of desired clusters
    %
    %   % Set the internal decision rule to be MAP. Not required for
    %   % clustering, but necessary to plot the results.
    %   clusterAlgo.internalDecider = prtDecisionMap;
    %   clusterAlgo = clusterAlgo.train(ds); % Train the cluster algorithm
    %   plot(clusterAlgo);                   % Plot the results
    %
    %   See also prtCluster, prtClusterKMeans, prtClusterGmm

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

    properties (SetAccess=private)
        name = 'K-Modes Clustering' % K-Means Clustering
        nameAbbreviation = 'K-ModesCluster' % K-MeansCluster
    end

    properties
        nClusters = 3;  % The number of clusters to find

        kdeRv = prtRvKde;

        handleEmptyClusters = 'remove';  % Action to take when an empty cluster occurs
        distanceMetricFn = @prtDistanceEuclidean;  % The distance metric; should be a function like D = prtDistanceEuclidean(dataSet1,dataSet2)
        initialClusterCenters = 'plusplus';
        trainingPlotVisualization = false;
    end

    properties (SetAccess = protected)
        clusterCenters = [];   % The cluster centers
    end
    properties (SetAccess = private, Hidden = true)
        uY = [];
    end

    methods

        function self = set.nClusters(self,value)
            if ~prtUtilIsPositiveScalarInteger(value)
                error('prt:prtClusterKmodes:nClusters','value (%s) must be a positive scalar integer',mat2str(value));
            end
            self.nClusters = value;
        end

        function self = set.handleEmptyClusters(self,value)
            if ~isa(value,'char') || ~any(strcmpi(value,{'exit','regularize'}))
                error('prt:prtClusterKmodes:handleEmptyClusters','value (%s) must be one of ''remove'', or ''random''',mat2str(value));
            end
            self.kmeansHandleEmptyClusters = value;
        end
        function self = set.initialClusterCenters(self,value)
            if isa(value,'char')
                if ~any(strcmpi(value,{'random','plusplus'}))
                    error('prt:prtClusterKmodes:initialClusterCenters','If specified as a string initialClusterCenters must be one of ''random'', or ''plusplus''');
                end
            else
                % initialMeans were specified as a matrix. Assume
                % everything will be ok and let prtUtilKMeans catch errors
            end
            self.initialClusterCenters = value;
        end

        function self = set.distanceMetricFn(self,value)
            if ~isa(value,'function_handle')
                error('prt:prtClusterKmeans:distanceMetricFn','distanceMetricFn must be a function handle');
            elseif nargin(value) ~= 2
                error('prt:prtClusterKmeans:distanceMetricFn','distanceMetricFn must be a function handle that takes two input arguments');
            end
            self.distanceMetricFn = value;
        end
        function self = prtClusterKmodes(varargin)
            % Allow for string, value pairs
            self = prtUtilAssignStringValuePairs(self,varargin{:});
        end
    end

    methods (Access=protected, Hidden = true)

        function self = trainAction(self,ds)
            %self.clusterCenters = prtUtilKmeans(ds.getObservations,slf.nClusters,'distanceMetricFn',Obj.distanceMetricFn,'handleEmptyClusters',Obj.kmeansHandleEmptyClusters,'initialMeans',Obj.initialMeans);

            if ischar(self.initialClusterCenters)
                nInitializeKMeansIterations = 1;
                self.clusterCenters = prtUtilKmeans(ds.getObservations,self.nClusters,'distanceMetricFn',self.distanceMetricFn,'handleEmptyClusters',self.handleEmptyClusters,'initialMeans',self.initialClusterCenters,'maxIterations',nInitializeKMeansIterations);
            else
                self.clusterCenters = self.initialClusterCenters;e
            end

            data = ds.data;

            [nSamples,nDimensions] = size(data);
            clusterIndexOld = nan(nSamples,1);

            nMaxIterations = 100;
            for iteration = 1:nMaxIterations

                distanceMat = self.distanceMetricFn(data,self.clusterCenters);
                [twiddle,clusterIndex] = min(distanceMat,[],2); %#ok<ASGLU>

                if self.trainingPlotVisualization
                    self.trainingIterationPlotVisualization(data,self.clusterCenters,clusterIndex,iteration);
                end
                %Handle empty clusters:
                nMaxFixSteps = 10;
                for iFix = 1:nMaxFixSteps
                    if length(unique(clusterIndex)) ~= self.nClusters
                        invalidClusters = setdiff(1:self.nClusters,clusterIndex);
                        validClusters = intersect(1:self.nClusters,clusterIndex);
                        switch lower(inputStructure.handleEmptyClusters)
                            case 'remove'
                                classMeans = classMeans(validClusters,:);
                                self.nClusters = self.nClusters - length(invalidClusters);
                                distanceMat = distanceMat(:,validClusters);
                                [twiddle,clusterIndex] = min(distanceMat,[],2); %#ok<ASGLU>
                            case 'random'
                                randInds = max(1,ceil(rand(1,length(invalidClusters))*nSamples));
                                classMeans(invalidClusters,:) = data(randInds,:);
                                distanceMat =  inputStructure.distanceMetricFn(data,classMeans);
                                [twiddle,clusterIndex] = min(distanceMat,[],2); %#ok<ASGLU>
                            otherwise
                                error('invalid');
                        end
                    else
                        break
                    end
                end
                nSamplesForCdf = 1000;
                newClusters = zeros(self.nClusters,nDimensions);
                for clusterInd = 1:self.nClusters

                    cData = data(clusterIndex == clusterInd,:);
                    for iDim = 1:nDimensions
                        % newClusters(clusterInd,iDim) = % mode(cData(:,iDim)); % would work for discrete data only

                        cRv = mle(self.kdeRv,cData(:,iDim));

                        cXSamples = sort(cat(1,linspace(min(cData(:,iDim)), max(cData(:,iDim)),nSamplesForCdf)',cData(:,iDim)),'ascend');
                        cCdf = cRv.cdf(cXSamples);

                        %cModeInd = find(cCdf >= 0.5,1,'first');
                        [~,cModeInd] = max(cCdf);
                        if isempty(cModeInd)
                            % Something went horribly wrong
                            cMode = mean(cData(:,iDim));
                        else
                            cMode = cXSamples(cModeInd);
                        end

                        newClusters(clusterInd,iDim) = cMode;
                    end
                end
                self.clusterCenters = newClusters;

                if iFix == nMaxFixSteps
                    %maxIterReached = true;
                    return
                end

                %Check convergence:
                if all(clusterIndexOld == clusterIndex)
                    %maxIterReached = false;
                    return;
                else
                    clusterIndexOld = clusterIndex;
                end
            end

            % maxIterReached = iteration == nMaxIterations;

        end

        function ds = runAction(self,ds)

            fn = self.distanceMetricFn;
            distance = fn(ds.getObservations,self.clusterCenters);

            if size(distance,1) ~= ds.nObservations || size(distance,2) ~= size(self.clusterCenters,1)
                error('prt:prtClusterKmodes:badDistanceMetric','Expected a matrix of size %s from the distance metric, but distance metric function output a matrix of size %s',mat2str([DataSet.nObservations, size(Obj.clusterCenters,1)]),mat2str(size(distance)));
            end

            %The smallest distance is the expected class:
            [dontNeed,clusters] = min(distance,[],2);  %#ok<ASGLU>

            binaryMatrix = zeros(size(clusters,1),self.nClusters);
            for i = 1:self.nClusters
                binaryMatrix(i == clusters,i) = 1;
            end
            ds = ds.setObservations(binaryMatrix);
        end
        end
    methods (Hidden)
        function trainingIterationPlotVisualization(~, data,classMeans,clusterIndex,iter)

            [nSamples,nDimensions] = size(data); %#ok<ASGLU>

            if nDimensions > 3
                warning('prt:prtClusterKmods:iterationPlot','plotVisualization is true, but dimensionality of data (%d) is > 3',nDimensions);
                return;
            end
            ds = prtDataSetClass(data,clusterIndex);

            plot(ds);
            hold on;
            switch nDimensions
                case 1
                    plot(classMeans,'b.');
                case 2
                    plot(classMeans(:,1),classMeans(:,2),'b.');
                case 3
                    plot3(classMeans(:,1),classMeans(:,2),classMeans(:,3),'b.');
            end
            hold off;
            title(sprintf('Iteration %d',iter));
            drawnow; %pause;

        end
    end
end


function [acc pred softpred]  = testBNB(model, allSNumBi, labels, params)

nbsenttst = allSNumBi;
nblbltst = labels;

pred = zeros(size(labels));

for i = 1:length(nbsenttst)
    %words(nbsenttst{i})
    nbsentraw = nbsenttst{i};
    nbsentraw=nbsentraw(nbsentraw>0);
    ind = zeros(params.dictsize, 1);
%     updates = unique(nbsentraw);
%     counts = power(histc(nbsentraw, updates)', params.testp);

    ind(nbsentraw) = 1;
    ind = logical(ind);
    neglog = sum(model.lpwneg(ind)) + sum(model.mlpwneg(~ind));
    poslog = sum(model.lpwpos(ind)) + sum(model.mlpwpos(~ind));
    if neglog + model.pneg  > poslog + model.ppos
        pred(i) = 0;
    else
        pred(i) = 1;
    end
    softpred(i) = poslog - neglog;
end

acc = sum(pred == labels) / length(labels);
acc = acc*100


function value = i8_btest ( i, pos )

%*****************************************************************************80
%
%% I8_BTEST returns TRUE if bit #POS of I is 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 June 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    MIL-STD 1753
%
%  Parameters:
%
%    Input, integer I, the integer to be tested.
%
%    Input, integer POS, the bit position, between 0 and 63.
%
%    Output, logical VALUE, is TRUE if the POS-th bit of I is 1.
%
  if ( pos < 0 )

    fprintf ( 1, '\n' );
    fprintf ( 1, 'I8_BTEST - Fatal error!\n' );
    fprintf ( 1, '  POS < 0.\n' );
    error ( 'I8_BTEST - Fatal error!' );

  elseif ( pos < 63 )

    j = i;
    for k = 1 : pos
      j = floor ( j / 2 );
    end

    if ( mod ( j, 2 ) == 0 )
      value = 0;
    else
      value = 1;
    end

  elseif ( pos == 63 )

    if ( i < 0 )
      value = 1;
    else
      value = 0;
    end

  elseif ( 63 < pos )

    fprintf ( 1, '\n' );
    fprintf ( 1, 'I8_BTEST - Fatal error!\n' );
    fprintf ( 1, '  63 < POS.\n' );
    error ( 'I8_BTEST - Fatal error!' );

  end

  return
end


function my_stokes_GUI(nr,ntheta)
% close all;
% DEFINE function
r = linspace(0,1,100);
theta = linspace(0,2*pi,100);

[R,T]=meshgrid(r,theta);
x = R.*cos(T);
y = R.*sin(T);

% figure;
plot_curls(nr,ntheta,3);
camlight
caxis([-3 3])
zlim([-3 3])
grid on;
hold on;

% slider
set(gcf,'position',[410 150 560 626]);
figsize= get(gcf,'position');
SliderH = uicontrol('style','slider','position',[figsize(3)*0.95, figsize(4)*0.1 20 300],...
    'min', -3, 'max', 3,'SliderStep',[0.001, 0.01],'Value',3);

btn_on = uicontrol('style','pushbutton','String','LIGHT ON',...
    'position',[20 45 70 20],...
    'callback',@light_button_press);

btn_off = uicontrol('style','pushbutton','String','LIGHT OFF',...
    'position',[20 20 70 20],...
    'callback',@light_off_button_press);

addlistener(SliderH, 'Value','PostSet',@callbackfn);

    function callbackfn(source, eventdata)
        [az,el]=view;
        num = get(eventdata.AffectedObject, 'Value');
        cla
        plot_curls(nr,ntheta,num)
        view([az,el]);
        zlim([-3 3])

        caxis([-3 3])
        camlight
        grid on;
    end

    function light_off_button_press(source,event)
        delete(findall(gcf,'Type','light'))

    end

    function light_button_press(source,event)
        camlight;
    end
end


function seq = sample_dbn(bnet, varargin)
% SAMPLE_DBN Generate a random sequence from a DBN.
% seq = sample_dbn(bnet, ...)
%
% seq{i,t} contains the values of the i'th node in the t'th slice.
%
% Optional arguments:
%
% length - length of sequence  to be generated (can also just use sample_dbn(bnet,T))
% stop_test - name of a function which is used to decide when to stop;
%   This will be called as feval(stop_test, seq(:,t))
%   i.e., stop_test is passed a cell array containing all the nodes in the current slice.
% evidence - initial evidence; if evidence{i,t} is non-empty, this node won't be sampled.

args = varargin;
nargs = length(args);

if (nargs == 1) & ~isstr(args{1})
  % Old syntax: sample_dbn(bnet, T)
  T = args{1};
else
  % get length
  T = 1;
  for i=1:2:nargs
    switch args{i},
     case 'length',      T = args{i+1};
     case 'evidence',    T = size(args{i+1}, 2);
    end
  end
end

ss = length(bnet.intra);
% set default arguments
seq = cell(ss, T);
stop_test = [];
for i=1:2:nargs
  switch args{i},
   case 'evidence',    seq = args{i+1}; % initialise observed nodes
   case 'stop_test',  stop_test = args{i+1};
  end
end

t = 1;
for i=1:ss
  if ~isempty(stop_test) | isempty(seq{i,t})
    ps = parents(bnet.dag, i);
    e = bnet.equiv_class(i,1);
    pvals = seq(ps);
    seq{i,t} = sample_node(bnet.CPD{e}, pvals);
    %fprintf('sample i=%d,t=%d,val=%d,ps\n', i, t, seq(i,t)); pvals(:)'
  end
end
t = 2;
done = 0;
while ~done
  for i=1:ss
    if ~isempty(stop_test) | isempty(seq{i,t})
      ps = parents(bnet.dag, i+ss) + (t-2)*ss;
      e = bnet.equiv_class(i,2);
      pvals = seq(ps);
      seq{i,t} = sample_node(bnet.CPD{e}, pvals);
      %fprintf('sample i=%d,t=%d,val=%d,ps\n', i, t, seq(i,t)); pvals(:)'
    end
  end
  if ~isempty(stop_test)
    done = feval(stop_test, seq(:,t));
  else
    if t==T
      done = 1;
    end
  end
  t = t + 1;
end


function varargout = size(F, dim)
%SIZE   Size of a SPHEREFUNV object
%   D = SIZE(F) returns a three-element vector D = [K, M, N]. If F is a column
%   SPHEREFUNV object then K is the number of components in F, N and M are INF.
%   If F is a row vector then K and M are INF and N is the number of components
%   of F.
%
%   [K, M, N] = SIZE(F) returns the dimensions of F as separate output
%   variables.
%
%   D = SIZE(F, DIM) returns the dimensions specified by the dimension DIM.
%

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

% Empty check:
if ( isempty(F) )
    varargout = {[], []};
    return
end

nF = 3;
tr = F.isTransposed;

% Manually work out the size:
if ( ~tr )
    K = nF;
    M = inf;
    N = inf;
else
    N = nF;
    K = inf;
    M = inf;
end

% Default to vector:
if ( nargin == 1 )
    dim = 0;
end

% Manually work out what should be displayed:
if ( dim == 1 )
    varargout = { K };
elseif ( dim == 2 )
    varargout = { M };
elseif ( dim == 3 )
    varargout = { N };
elseif ( ( dim == 0 ) && ( nargin == 1 ) )
    if ( nargout <= 1 )
        varargout = { [K, M, N] };
    else
        varargout = { K, M, N };
    end
else
    error('SPHEREFUN:SPHEREFUNV:size:dim', 'Unrecognised dimension.');
end

end


function testConvolutionalFilters
% testConvolutionalFilters.m This script compares convolutional filter
% responses as currently implemented to those submitted to IBSI-2 to
% ensure continued compliance.
%
% AI 12/09/22

init_ML_DICOM

%Path to "gold standard" response maps
CERRPath = getCERRPath;
CERRPathSlashes = strfind(getCERRPath,filesep);
topLevelCERRDir = CERRPath(1:CERRPathSlashes(end-1));
stdDir = fullfile(topLevelCERRDir,'Unit_Testing','data_for_cerr_tests',...
    'IBSI2_synthetic_phantoms','Results');

%Create temp output dir
testDir = fullfile(topLevelCERRDir,'Unit_Testing','tests_for_cerr');
tmpDir = fullfile(testDir,'IBSI2');
mkdir(tmpDir)

%Compute filter response maps (IBSI 2 -phase1)
runIBSI2benchmarkFilters(tmpDir,'all');

%Assess deviation from standard
configC = { '1a1','1a2','1a3','1a4','1b1','2a1','2b1','2c1','3a1','3a2',...
    '3a3','3b1','3b2','3b3','3c1','3c2','3c3','4a1','4a2','4b1','4b2',...
    '5a1','5a2','6a1','6a2'};
assertTOL = 1e-5;

disp(['========= Maximum difference for filt config. =========='])
for n = 1:length(configC)
    currResponse3M = niftiread(fullfile(tmpDir,[configC{n},'.nii']));
    stdResponse3M = niftiread(fullfile(stdDir,[configC{n},'.nii']));
    diff3M = currResponse3M - stdResponse3M;
    maxDiff = max(diff3M(:));
    assertAlmostEqual(currResponse3M,stdResponse3M,assertTOL);
    disp([configC{n},': ', sprintf('%0.1g',maxDiff)])

end

rmdir(tmpDir,'s')

disp('========= testConvolutionalFilters succeeded. ==========')

end


% plotmesh() - plot mesh defined by faces and vertex
%
% Usage:
%     plotmesh(faces, vertex);
%
% Input:
%   faces   - array of N x 3. Each row defines a triangle. The 3 points
%             in each row are row indices in the matrix below.
%   vertex  - array of M x 3 points, (x = first colum; y=second colum
%             z=3rd column). Each row defines a point in 3-D.
%
% Optional input:
%   normal  - normal orientation for each face (for better lighting)
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, 2003

% Copyright (C) May 6, 2003 Arnaud Delorme, SCCN/INC/UCSD,
% arno@sccn.ucsd.edu
%
% 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

function p1 = plotmesh(faces, vertex, normal, newfig)

    if nargin < 2
        help plotmesh;
        return;
    end;

    FaceColor  = [.8 .55 .35]*1.1; % ~= ruddy Caucasian - pick your complexion!

    if any(any(faces == 0)), faces = faces+1; end;
    %vertex(:,3) = -vertex(:,3);
    %FCmap = [jet(64); FaceColor; FaceColor; FaceColor];
    %colormap(FCmap)
    %W = ones(1,size(vertex,1))*(size(FCmap,1)-1);
    %W = ones(1,size(vertex,1))' * FaceColor;
    %size(W)
    if nargin < 4
        figure;
    end;
    if nargin < 3
        normal = [];
    end;
    if isempty(normal)
        p1 = patch('vertices', vertex, 'faces', faces, ...
                   'facecolor', [1,.75,.65]);
    else
        p1 = patch('vertices', vertex, 'faces', faces, ...
                   'facecolor', [1,.75,.65], 'vertexnormals', normal);
    end;
        %           'FaceVertexCdata',W(:), 'FaceColor','interp', 'vertexnormals', normal);
    set(p1,'EdgeColor','none')

    % Lights
    %Lights = [-125  125  80; ...
    %          125  125  80; ...
    %          125 -125 125; ...
    %          -125 -125 125];    % default lights at four corners
    %for i = 1:size(Lights,1)
    %    hl(i) = light('Position',Lights(i,:),'Color',[1 1 1],...
    %                  'Style','infinite');
    %end
    %camlight left;
    lightangle(45,30);
    lightangle(45+180,30);
    %set(gcf, 'renderer', 'zbuffer'); % cannot use alpha then
    %set(hcap, 'ambientstrength', .6);
    set(p1, 'specularcolorreflectance', 0, 'specularexponent',50);

    set(p1,'DiffuseStrength',.6,'SpecularStrength',0,...
           'AmbientStrength',.4,'SpecularExponent',5);
    axis equal
    view(18,8);
    rotate3d
    axis off;
    lighting phong;


function outn=le(x,y)

precAndSize

for ii=1:max(ex,ey)
 imag=false;
 if ex==1
  [xrval,xival]=getVals(x,1);
  [yrval,yival]=getVals(y,ii);
 elseif ey==1
  [xrval,xival]=getVals(x,ii);
  [yrval,yival]=getVals(y,1);
 else
  [xrval,xival]=getVals(x,ii);
  [yrval,yival]=getVals(y,ii);
 end
  outn(ii)=mpfr_le(precision,xrval,yrval);
  if outn(ii)~=0, outn(ii)=1; end
end % for ii=1:max(ex,


function M = esvm_perform_calibration(grid, val_set, models, params)
% 1. Perform LABOO calibration procedure and 2. Learn a combination
% matrix M which multiplexes the detection results (by compiling
% co-occurrence statistics on true positives)
%
% Copyright (C) 2011-12 by Tomasz Malisiewicz
% All rights reserved.
%
% This file is part of the Exemplar-SVM library and is made
% available under the terms of the MIT license (see COPYING file).
% Project homepage: https://github.com/quantombone/exemplarsvm

%% Perform calibration
betas = esvm_perform_platt_calibration(grid, val_set, models, ...
                                       params);

%% Estimate the co-occurrence matrix M
if ~(isfield(params,'SKIP_M') && params.SKIP_M==1)
  M = esvm_estimate_M(grid, models, params);
end

%concatenate results
M.betas = betas;


function hBodySurf = rts_initOrbPlot(hFig, orbitDispAxes, bodyInfo)
%rts_initOrbPlot Summary of this function goes here
%   Detailed explanation goes here

    hold(orbitDispAxes,'on');
    set(orbitDispAxes,'XTickLabel',[]);
    set(orbitDispAxes,'YTickLabel',[]);
    set(orbitDispAxes,'ZTickLabel',[]);
    grid(orbitDispAxes,'on');
    view(orbitDispAxes,3);

    if(~isempty(bodyInfo))
        dRad = bodyInfo.radius;
        [X,Y,Z] = sphere(30);
        hold(orbitDispAxes,'on');
        hBodySurf = surf(orbitDispAxes, dRad*X,dRad*Y,dRad*Z);
        hold(orbitDispAxes,'on');
        colormap(orbitDispAxes,bodyInfo.bodycolor);
    else
        hBodySurf = [];
    end
    axis(orbitDispAxes, 'equal');
    hold(orbitDispAxes,'off');
end


%High speed MATLAB codes

%This program use SCL with small list size as a "filter", i.e., under the
%same noise realization, If CRC-SCL with smaller L is correct, then CRC-SCL
%with larger L must be correct. You may not believe in this conjecture, but you can have
%a try, This is true with high probability (almost 1)

%This program has another accelerator. If in lower snr, CRC-SCL is correct, then at higher snr,
%the same CRC-SCL must be correct.  You may not believe in this conjecture, but you can have
%a try, This is true with high probability (almost 1).

%I know above methods sound dangerous, but it is safe under following 4
%conditions

%1. The same code word
%2. The same AWGN noise realization with distribution N(0, 1)
%3. CRC must be used (Only SCL is not permitted)
%4. The same code construction in all SNR range.

%This program satisfies above 4 conditions. You can verify the bler performance by comparisons with existing results.

%Since MATLAB is not good at recursive function (too many parameters to be passed)
%I cancel the well-known recursiveCalcP() and recursiveCalcB() proposed by
%I. Tal
%Instead, 'For' function is used. You may argue that we can use objective
%oriented (OO) style. However, OO in matlab is also slow.

%Besides, the algorithms of following papers are provided.

%How to Construct Polar Codes
%Fast Successive-Cancellation Decoding of Polar Codes: Identification and Decoding of New Nodes
%beta-expansion: A Theoretical Framework for Fast and Recursive Construction of Polar Codes

%Above three algorithms are made by myself so the correctness is not guaranteed.

clear
addpath('GA/')
% addpath('HowToConstructPolarCode/')
addpath('NodeProcess/')
% addpath('BECconstruction/')
% addpath('PolarizaedChannelsPartialOrder/')
%adding above folders will take round 2 seconds

design_epsilon = 0.32;
crc_length = 16;
[gen, det, g] = get_crc_objective(crc_length);
n = 10;
N = 2^n;
K = N/2 + crc_length;
ebno_vec = [2 2.5]; %row vec, you can write it like [1 1.5 2 2.5 3]
list_vec = [1 16];  %row vec, you can write it like [1 4 16 32 ...]. The first element is always 1 for acceleration purpose. The ramaining elements are power of two.
max_runs = 1e7;
max_err = 100;
resolution = 1e4;%the results are shown per max_runs/resolution.
[bler, ber] = simulation(N, K, design_epsilon, max_runs, max_err, resolution,  ebno_vec, list_vec, gen, det, g, crc_length);


function test_suite = test_angle3Points
% One-line description here, please.
%   output = testAngle3Points(input)
%
%   Example
%   testAngle3Points
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2009-04-22,    using Matlab 7.7.0.471 (R2008b)
% Copyright 2009 INRA - Cepia Software Platform.

test_suite = functiontests(localfunctions);

function testSimple(testCase) %#ok<*DEFNU>
% all points inside window, possibly touching edges

p1 = [10 0];
p2 = [0 0];
p3 = [0 10];
angle = angle3Points(p1, p2, p3);
testCase.assertEqual(pi/2, angle, 'AbsTol', .01);

function testBundledInput(testCase)
% all points inside window, possibly touching edges

p1 = [10 0];
p2 = [0 0];
p3 = [0 10];
angle = angle3Points([p1; p2; p3]);
testCase.assertEqual(pi/2, angle, 'AbsTol', .01);

function testArray(testCase)
% all points inside window, possibly touching edges

p1 = [10 0; 20 0];
p2 = [0 0;0 0];
p3 = [0 10; 0 20];
angle = angle3Points(p1, p2, p3);

testCase.assertEqual(2, size(angle, 1));
testCase.assertEqual([pi/2;pi/2], angle, 'AbsTol', .01);