function bestp = faceGA
%
% A silly face example of a genetic algorithm.
% By Tor Wager, June 2002
%
% calls functions:
% drawFace.m
% breedorgs.m   (from OptimizeDesign10)

gensize = 100;
numgens = 100;
numopt = 17;
change_every = 30;

% ------------------------------------------
% * set up figures
% ------------------------------------------

fgen = figure;set(gcf,'MenuBar','none');set(gcf,'Name','Faces in This Generation')
set(gcf,'Position',[30          70         975        1040])
set(gcf,'NumberTitle','off');set(gcf,'Color','w')

% for movie single figure
for i = 1:30, h(i) = subplot(6,5,i);, mypos(i,:) = get(h(i),'Position');,end
mypos(:,1) = mypos(:,1) - .1;
mypos(:,3) = mypos(:,3) * .7;
mypos(:,1) = mypos(:,1) * .7;
clf
for i = 1:30, nh(i) = axes('position',mypos(i,:));, end
set(gcf,'Position',[30          70        1514        1040])
hgen = axes('position',[.591 .5347 .36 .36]);
hideal = axes('position',[.591 .11 .36 .36]);

mov = avifile('facega.avi','Quality',75,'Compression','none','Fps',10);

%bgen = figure;set(gcf,'MenuBar','none');set(gcf,'Name','Best of This Generation')
%set(gcf,'Position',[1021         719         516         393])
%set(gcf,'NumberTitle','off');set(gcf,'Color','w')
%tgen = figure;set(gcf,'MenuBar','none');set(gcf,'Name','Target Face')
%set(gcf,'Position',[1024         195         516         393])
%set(gcf,'NumberTitle','off');set(gcf,'Color','w')

% ------------------------------------------
% * set up lists
% ------------------------------------------
p = rand(gensize,20);
idealface = [1.0000    1.0000    1.0000    1.0000         0    0.4486    0.5244    0.1715    0.5000    1.0000    0.2000    0.1414    0.4570    1.0000 0.8000    0.2248    0.9089    0.0073    0.5887    0.5421];
idealfit = repmat(idealface,gensize,1);
%figure(tgen); drawFace(idealface)
axes(hideal); cla; drawFace(idealface); title('Face To Match','FontSize',14)

for gen = 1:numgens

    if mod(gen,change_every) == 0
        idealface = rand(1,20);
        idealfit = repmat(idealface,gensize,1);
        axes(hideal); cla; drawFace(idealface)
    end

    for g = 1:gensize

        if g < 31

            axes(nh(g))
            %figure(fgen)
            %subplot(6,5,g)
            drawFace(p(g,:))
            H = gcf; mov = addframe(mov,H);
        end

    end

    % compute fitness and save best
    f = -1 * (sum(((idealfit(:,1:numopt) - p(:,1:numopt)) .^ 2),2));
    bestp = p(f == max(f),:); bestp = bestp(1,:);
    %figure(bgen); clf; drawFace(bestp)
    axes(hgen); cla; drawFace(bestp); title('Best of This Generation','FontSize',14)

    fm = f(f == max(f));
    text(.8,.8,1,num2str(round(fm(1)*1000)),'FontSize',18)

    f = (f - mean(f)) ./ std(f);

    % crossbreed
    p = breedorgs(f',p',2.1)';

    H = gcf; mov = addframe(mov,H);
end

mov = close(mov);


function grad = B_beamforming_power(future_layer, curr_layer, prev_layer)
% we don't implement this function now, as it will be used with
% beamforming. We will implement the joint gradient of Power spectrum and
% frequency domain beamforming.
% X is the multichannel complex spectrum inputs
future_grad = future_layer{1}.grad;
[X, weight] =  prepareBeamforming(prev_layer);
[C,T,N] = size(X);
% Y is the beamforming's output
Y = curr_layer.a;

if 0
    for i=1:C
        cross_term = future_grad .* Y .* squeeze(conj(X(i,:,:)))';
        grad(:,i) = 2*sum(cross_term,2);
    end
else
    future_grad_Y = future_grad .* Y;
    X_tmp = permute(X, [3 2 1]);
    cross_term = bsxfun(@times, X_tmp, future_grad_Y);
    grad = 2*squeeze(sum(cross_term,2));
end

end


%Copyright 2013 The MathWorks, Inc
if ii==1,
    %% Global Coordinate System
    figure('WindowStyle','docked');
    hold on; grid on
    antT = nan(3,N);      % Array trajectory
    tgtT = nan(3,N);      % Target trajectory
    antT = [antT(:,2:end) antpos/1e3];
    tgtT = [tgtT(:,2:end) tgtpos/1e3];
    hant = plot3(antT(1,:),antT(2,:),antT(3,:),'LineWidth',2);
    htgt = plot3(tgtT(1,:),tgtT(2,:),tgtT(3,:),'LineWidth',2,'Color','red');
    axis([-100 100 -100 50 0 50])
    xlabel('X'), ylabel('Y'), zlabel('Z')
    title('Global Coordinate System','FontWeight','bold')
    view(40,48)
    legend('Antenna','Target')
    %% Target Trajectory in Local Coordinate System (from antenna perspective)
    h2 = figure('WindowStyle','docked');
    hold on; grid on
    axis([-130 0 6 13 0 50])
    xlabel('Azimuth'), ylabel('Range'), zlabel('Elevation')
    title('Local Coordinate System','FontWeight','bold')
    view(-40,48)
    %% Array visualization
    figure('WindowStyle','docked');
    viewArray(sAnt,'ShowSubarray','None')
    bx = get(gca,'Children');
    hdots = bx(8);
    ndots = numel(get(hdots,'XData'));
    green = ones(ndots,1)*[0 1 0];
    view(40,48)
else
    %% Highlight active arrays
    mn=face(:)*ones(1,ndots);
    hlgt=repmat([mn(1,1:16) mn(2,17:32) mn(3,33:48) mn(4,49:64)],3,1);
    set(hdots,'CData',green.*hlgt');
    %% Update global trajectories
    antT = [antT(:,2:end) antpos/1e3];
    tgtT = [tgtT(:,2:end) tgtpos/1e3];
    set(hant,'XData',antT(1,:),'YData',antT(2,:),'ZData',antT(3,:))
    set(htgt,'XData',tgtT(1,:),'YData',tgtT(2,:),'ZData',tgtT(3,:))
end
%% Update local trajectory
figure(h2)
plot3(AzEl(1),range/1e4,AzEl(2),'ro','MarkerSize',20-round(range/1e4))


classdef omegaSections < pfSections

  methods

    function oS = omegaSections(CS1,CS2,varargin)

      oS = oS@pfSections(CS1,CS2);

      oS.maxOmega = 2*pi / CS1.nfold(oS.h1);

      % get sections
      oS.omega = linspace(0,oS.maxOmega,1+get_option(varargin,'sections',6));
      oS.omega(end) = [];
      oS.omega = get_option(varargin,'omega',oS.omega,'double');

      oS.updateTol(oS.omega);

      oS.referenceField = S2VectorField.sigma;
      %if nargin < 4, r_ref = xvector; end
      %oS.referenceField = S2VectorField.polar(r_ref);

    end
  end
end


% The COBRAToolbox: testTheoretMaxProd.m
%
% Purpose:
%     - test the theoretMaxProd function
%
% Authors:
%     - Jacek Wachowiak
global CBTDIR
% save the current path
currentDir = pwd;

% initialize the test
fileDir = fileparts(which('testTheoretMaxProd'));
cd(fileDir);

% test variables
model = getDistributedModel('ecoli_core_model.mat');

% change solver since qpng is unstable - to be changed after installation of gurobi
% TODO: test this for multiple solvers.
changeCobraSolver('pdco', 'QP');

%Get the molecular weights of the compounds in the model.
[mw,EMatrix,elements] = computeMW(model, [], false);

%lets calc a simple optimization
tempModel = model;
acExPos = ismember(model.rxns,'EX_ac(e)');
tempModel.c = double(acExPos);
FBAsol = optimizeCbModel(tempModel);

% function calls
[ExRxns, MaxTheoOut] = theoretMaxProd(model, 'EX_glc(e)'); % Max 'EX_ac(e)' flux (unique)
allExPos = ismember(model.rxns,ExRxns);
%Determine the Exchangers and their respective exchanged metabolite +
%Weights
exWeights = cellfun(@(x) mw(find(model.S(:,ismember(model.rxns,x)))),ExRxns);
carbEx = cellfun(@(x) EMatrix(find(model.S(:,ismember(model.rxns,x))),ismember(elements,'C')) > 0 ,ExRxns);
carbExPos = ismember(model.rxns, ExRxns(carbEx));
acPosInExch = ismember(ExRxns,'EX_ac(e)');

%Alternative calls
[ExRxns1, MaxTheoOut1] = theoretMaxProd(model, 'EX_glc(e)', '', true, findExcRxns(model,0,0)); % Scaled to 0-1
[ExRxns2, MaxTheoOut2] = theoretMaxProd(model, 'EX_glc(e)', 'pr_mw'); %Compared to other mw
[ExRxns3, MaxTheoOut3] = theoretMaxProd(model, 'EX_glc(e)', 'pr_other_mol');
[ExRxns4, MaxTheoOut4] = theoretMaxProd(model, 'EX_glc(e)', 'pr_other_mw');
[ExRxns5, MaxTheoOut5] = theoretMaxProd(model, 'EX_glc(e)', 'x'); % bad criterion

% We assume, that the solver is deterministic, i.e. the solution found for
% the basic call is the same as for all the other calls.
assert(abs(MaxTheoOut(1) - 20) < 1e-4); % 'EX_ac(e)'
assert(abs(MaxTheoOut1(1) - 2) < 1e-4); % the same but scaled to glucose uptake flux (10)

assert(abs(MaxTheoOut2(1) - FBAsol.x(acExPos)*exWeights(1)) < 1e-4); % 'EX_ac(e)' in weight
%All (molar) exports (>0) without acetate and with
assert(abs(MaxTheoOut3(1) - sum(FBAsol.x(allExPos & ~acExPos & FBAsol.x > 0 & carbExPos) )) < 1e-4); % 'EX_ac(e)'
% Sum of Molecular weights of all Carbon Exporters ( > 0) without Acetate
assert(abs(MaxTheoOut4(1) - sum(FBAsol.x(allExPos).*(FBAsol.x(allExPos)>0).*exWeights.*carbEx.*~acPosInExch)) < 1e-4); % 'EX_ac(e)' in weight yield
assert(isequal(MaxTheoOut5, zeros(20, 1))); % bad criterion returns only 0s

% change to old directory
cd(currentDir);


function lik = lik_inputdependentweibull(varargin)
%LIK_INPUTDEPENDENTWEIBULL  Create a (right censored) input dependent Weibull likelihood structure
%
%  Description
%    LIK = LIK_INPUTDEPENDENTWEIBULL('PARAM1',VALUE1,'PARAM2,VALUE2,...)
%    creates a likelihood structure for a right censored input dependent
%    Weibull survival model in which the named parameters have the
%    specified values. Any unspecified parameters are set to default
%    values.
%
%    LIK = LIK_INPUTDEPENDENTWEIBULL(LIK,'PARAM1',VALUE1,'PARAM2,VALUE2,...)
%    modify a likelihood structure with the named parameters
%    altered with the specified values.
%
%    Parameters for Weibull likelihood [default]
%      shape       - shape parameter r [1]
%      shape_prior - prior for shape [prior_logunif]
%
%    Note! If the prior is 'prior_fixed' then the parameter in
%    question is considered fixed and it is not handled in
%    optimization, grid integration, MCMC etc.
%
%    The likelihood is defined as follows:
%                       __ n
%      p(y|f1, f2, z) = || i=1 [ r_i^(1-z_i) exp( (1-z_i)*(-f1_i)
%                           +(1-z_i)*(r_i-1)*log(y_i)
%                           -exp(-f1_i)*y_i^r_i) ]
%
%    where r_i=r*exp(f2_i) is the shape parameter of Weibull distribution.
%    z is a vector of censoring indicators with z = 0 for uncensored event
%    and z = 1 for right censored event. Here the second latent variable f2
%    implies the input dependance to the shape parameter in the original
%    Weibull likelihood.
%
%    When using the Weibull likelihood you can give the
%    vector z as an extra parameter to each function that requires
%    also y. For example, you can call gp_optim as follows:
%      gp_optim(gp, x, y, 'z', z)
%    If z is not given or it is empty, then usual likelihood for
%    uncensored data is used
%
%  See also
%    GP_SET, LIK_*, PRIOR_*
%
% Copyright (c) 2011 Jaakko Riihimäki
% Copyright (c) 2011 Aki Vehtari
% Copyright (c) 2012 Ville Tolvanen

% 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 = 'LIK_INPUTDEPENDENTWEIBULL';
  ip.addOptional('lik', [], @isstruct);
  ip.addParamValue('shape',1, @(x) isscalar(x) && x>0);
  ip.addParamValue('shape_prior',prior_logunif(), @(x) isstruct(x) || isempty(x));
  ip.parse(varargin{:});
  lik=ip.Results.lik;

  if isempty(lik)
    init=true;
    lik.nondiagW=true;
    lik.type = 'Inputdependent-Weibull';
  else
    if ~isfield(lik,'type') || ~isequal(lik.type,'Weibull')
      error('First argument does not seem to be a valid likelihood function structure')
    end
    init=false;
  end

  % Initialize parameters
  if init || ~ismember('shape',ip.UsingDefaults)
    lik.shape = ip.Results.shape;
  end
  % Initialize prior structure
  if init
    lik.p=[];
  end
  if init || ~ismember('shape_prior',ip.UsingDefaults)
    lik.p.shape=ip.Results.shape_prior;
  end

  if init
    % Set the function handles to the subfunctions
    lik.fh.pak = @lik_inputdependentweibull_pak;
    lik.fh.unpak = @lik_inputdependentweibull_unpak;
    lik.fh.lp = @lik_inputdependentweibull_lp;
    lik.fh.lpg = @lik_inputdependentweibull_lpg;
    lik.fh.ll = @lik_inputdependentweibull_ll;
    lik.fh.llg = @lik_inputdependentweibull_llg;
    lik.fh.llg2 = @lik_inputdependentweibull_llg2;
    lik.fh.llg3 = @lik_inputdependentweibull_llg3;
    lik.fh.invlink = @lik_inputdependentweibull_invlink;
    lik.fh.predy = @lik_inputdependentweibull_predy;
    lik.fh.recappend = @lik_inputdependentweibull_recappend;
  end

end

function [w,s,h] = lik_inputdependentweibull_pak(lik)
%LIK_INPUTDEPENDENTWEIBULL_PAK  Combine likelihood parameters into one vector.
%
%  Description
%    W = LIK_INPUTDEPENDENTWEIBULL_PAK(LIK) takes a likelihood structure LIK and
%    combines the parameters into a single row vector W. This is a
%    mandatory subfunction used for example in energy and gradient
%    computations.
%
%       w = log(lik.shape)
%
%   See also
%   LIK_INPUTDEPENDENTWEIBULL_UNPAK, GP_PAK

  w=[];s={};h=[];
  if ~isempty(lik.p.shape)
    w = log(lik.shape);
    s = [s; 'log(weibull.shape)'];
    h = [h 0];
    [wh, sh, hh] = lik.p.shape.fh.pak(lik.p.shape);
    w = [w wh];
    s = [s; sh];
    h = [h hh];
  end
end

function [lik, w] = lik_inputdependentweibull_unpak(lik, w)
%LIK_INPUTDEPENDENTWEIBULL_UNPAK  Extract likelihood parameters from the vector.
%
%  Description
%    [LIK, W] = LIK_INPUTDEPENDENTWEIBULL_UNPAK(W, LIK) takes a likelihood
%    structure LIK and extracts the parameters from the vector W
%    to the LIK structure. This is a mandatory subfunction used
%    for example in energy and gradient computations.
%
%   Assignment is inverse of
%       w = log(lik.shape)
%
%   See also
%   LIK_INPUTDEPENDENTWEIBULL_PAK, GP_UNPAK

  if ~isempty(lik.p.shape)
    lik.shape = exp(w(1));
    w = w(2:end);
    [p, w] = lik.p.shape.fh.unpak(lik.p.shape, w);
    lik.p.shape = p;
  end
end

function lp = lik_inputdependentweibull_lp(lik, varargin)
%LIK_INPUTDEPENDENTWEIBULL_LP  log(prior) of the likelihood parameters
%
%  Description
%    LP = LIK_INPUTDEPENDENTWEIBULL_LP(LIK) takes a likelihood structure LIK and
%    returns log(p(th)), where th collects the parameters. This
%    subfunction is needed when there are likelihood parameters.
%
%  See also
%    LIK_INPUTDEPENDENTWEIBULL_LLG, LIK_INPUTDEPENDENTWEIBULL_LLG3, LIK_INPUTDEPENDENTWEIBULL_LLG2, GPLA_E

% If prior for shape parameter, add its contribution
  lp=0;
  if ~isempty(lik.p.shape)
    lp = lik.p.shape.fh.lp(lik.shape, lik.p.shape) +log(lik.shape);
  end

end

function lpg = lik_inputdependentweibull_lpg(lik)
%LIK_INPUTDEPENDENTWEIBULL_LPG  d log(prior)/dth of the likelihood
%                parameters th
%
%  Description
%    E = LIK_INPUTDEPENDENTWEIBULL_LPG(LIK) takes a likelihood structure LIK and
%    returns d log(p(th))/dth, where th collects the parameters.
%    This subfunction is needed when there are likelihood parameters.
%
%  See also
%    LIK_INPUTDEPENDENTWEIBULL_LLG, LIK_INPUTDEPENDENTWEIBULL_LLG3, LIK_INPUTDEPENDENTWEIBULL_LLG2, GPLA_G

  lpg=[];
  if ~isempty(lik.p.shape)
    % Evaluate the gprior with respect to shape
    ggs = lik.p.shape.fh.lpg(lik.shape, lik.p.shape);
    lpg = ggs(1).*lik.shape + 1;
    if length(ggs) > 1
      lpg = [lpg ggs(2:end)];
    end
  end
end

function ll = lik_inputdependentweibull_ll(lik, y, ff, z)
%LIK_INPUTDEPENDENTWEIBULL_LL  Log likelihood
%
%  Description
%    LL = LIK_INPUTDEPENDENTWEIBULL_LL(LIK, Y, F, Z) takes a likelihood
%    structure LIK, survival times Y, censoring indicators Z, and
%    latent values F. Returns the log likelihood, log p(y|f,z).
%    This subfunction is needed when using Laplace approximation
%    or MCMC for inference with non-Gaussian likelihoods. This
%    subfunction is also used in information criteria (DIC, WAIC)
%    computations.
%
%  See also
%    LIK_INPUTDEPENDENTWEIBULL_LLG, LIK_INPUTDEPENDENTWEIBULL_LLG3, LIK_INPUTDEPENDENTWEIBULL_LLG2, GPLA_E

  if numel(z)==0
    % no censoring by default
    z=0;
  end

  f=ff(:);
  n=size(y,1);
  f1=f(1:n);
  f2=f((n+1):2*n);
  expf2=exp(f2);
  expf2(isinf(expf2))=realmax;
  a = lik.shape;
  ll = sum((1-z).*(log(a*expf2) + (a*expf2-1).*log(y)-f1) - exp(-f1).*y.^(a*expf2));

end

function llg = lik_inputdependentweibull_llg(lik, y, ff, param, z)
%LIK_INPUTDEPENDENTWEIBULL_LLG  Gradient of the log likelihood
%
%  Description
%    LLG = LIK_INPUTDEPENDENTWEIBULL_LLG(LIK, Y, F, PARAM) takes a likelihood
%    structure LIK, survival times Y, censoring indicators Z and
%    latent values F. Returns the gradient of the log likelihood
%    with respect to PARAM. At the moment PARAM can be 'param' or
%    'latent'. This subfunction is needed when using Laplace
%    approximation or MCMC for inference with non-Gaussian likelihoods.
%
%  See also
%    LIK_INPUTDEPENDENTWEIBULL_LL, LIK_INPUTDEPENDENTWEIBULL_LLG2, LIK_INPUTDEPENDENTWEIBULL_LLG3, GPLA_E

  if numel(z)==0
    % no censoring by default
    z=0;
  end

  f=ff(:);
  n=size(y,1);
  f1=f(1:n);
  f2=f((n+1):2*n);
  expf2=exp(f2);
  expf2(isinf(expf2))=realmax;
  a = lik.shape;
  switch param
    case 'param'
      llg = sum((1-z).*(1./a + expf2.*log(y)) - exp(-f1).*y.^(a.*expf2).*log(y).*expf2);
      % correction for the log transformation
      llg = llg.*lik.shape;
    case 'latent'
      llg1 = -(1-z) + exp(-f1).*y.^(a.*expf2);
      llg2 = (1-z).*(1 + a.*expf2.*log(y)) - exp(-f1).*y.^(a.*expf2).*log(y).*a.*expf2;
      llg = [llg1; llg2];
  end
end

function llg2 = lik_inputdependentweibull_llg2(lik, y, ff, param, z)
%LIK_INPUTDEPENDENTWEIBULL_LLG2  Second gradients of the log likelihood
%
%  Description
%    LLG2 = LIK_INPUTDEPENDENTWEIBULL_LLG2(LIK, Y, F, PARAM) takes a
%    likelihood structure LIK, survival times Y, censoring indicators Z,
%    and latent values F. Returns the hessian of the log likelihood with
%    respect to PARAM. LLG2 is a (2*length(y)) x 2 matrix containing the
%    non-zero elements of the Hessian matrix. This subfunction is needed
%    when using Laplace approximation or EP for  inference with
%    non-Gaussian likelihoods.
%
%  See also
%    LIK_INPUTDEPENDENTWEIBULL_LL, LIK_INPUTDEPENDENTWEIBULL_LLG,
%    LIK_INPUTDEPENDENTWEIBULL_LLG3, GPLA_E

  if numel(z)==0
    % no censoring by default
    z=0;
  end

  a = lik.shape;
  f=ff(:);
  n=size(y,1);
  f1=f(1:n);
  f2=f((n+1):2*n);
  expf2=exp(f2);
  expf2(isinf(expf2))=realmax;
  switch param
    case 'param'

    case 'latent'
      t1=exp(-f1).*y.^(a.*expf2);
      t2=log(y).*a.*expf2;
      t3=t1.*t2;

      llg2_11 = -t1;
      llg2_12 = t3;
      llg2_22 = (1-z).*t2 - (t2 + 1).*t3;

      llg2 = [llg2_11 llg2_12; llg2_12 llg2_22];

    case 'latent+param'
      t1=expf2.*log(y);
      t2=exp(-f1).*y.^(a.*expf2);
      t3=t1.*t2;
      llg2_1 = t3;
      llg2_2 = (1-z).*t1 - (t1.*a + 1).*t3;
      llg2 = [llg2_1; llg2_2];
      % correction due to the log transformation
      llg2 = llg2.*lik.shape;
  end
end

function llg3 = lik_inputdependentweibull_llg3(lik, y, ff, param, z)
%LIK_INPUTDEPENDENTWEIBULL_LLG3  Third gradients of the log likelihood
%
%  Description
%    LLG3 = LIK_INPUTDEPENDENTWEIBULL_LLG3(LIK, Y, F, PARAM) takes a likelihood
%    structure LIK, survival times Y, censoring indicators Z and
%    latent values F and returns the third gradients of the log
%    likelihood with respect to PARAM. At the moment PARAM can be
%    only 'latent'. LLG3 is a vector with third gradients. This
%    subfunction is needed when using Laplace approximation for
%    inference with non-Gaussian likelihoods.
%
%  See also
%    LIK_INPUTDEPENDENTWEIBULL_LL, LIK_INPUTDEPENDENTWEIBULL_LLG, LIK_INPUTDEPENDENTWEIBULL_LLG2, GPLA_E, GPLA_G

  if numel(z)==0
    % no censoring by default
    z=0;
  end

  a = lik.shape;
  f=ff(:);
  n=size(y,1);
  f1=f(1:n);
  f2=f((n+1):2*n);
  expf2=exp(f2);
  expf2(isinf(expf2))=realmax;
  switch param
    case 'param'

    case 'latent'
      t1=a.*expf2.*log(y);
      t2=exp(-f1).*y.^(a.*expf2);
      t3=t2.*t1;
      t4=t3.*t1;

      nl=2;
      llg3=zeros(nl,nl,nl,n);

      llg3(1,1,1,:) = t2;

      llg3(2,2,1,:) = t4 + t3;
      llg3(2,1,2,:) = llg3(2,2,1,:);
      llg3(1,2,2,:) = llg3(2,2,1,:);

      llg3(2,1,1,:) = -t3;
      llg3(1,2,1,:) = llg3(2,1,1,:);
      llg3(1,1,2,:) = llg3(2,1,1,:);

      llg3(2,2,2,:) = (1-z).*t1 - t4.*t1 - 3.*t4 - t3;

    case 'latent2+param'
      t1 = log(y).*expf2;
      t2 = exp(-f1).*y.^(a*expf2);
      t3 = t2.*t1;
      t4 = t3.*t1;
      llg3_11 = -t3;
      llg3_12 = a.*t4 + t3;
      llg3_22 = (1-z).*t1 - a.^2.*t4.*t1 - 3.*a.*t4 - t3;

      llg3 = [diag(llg3_11) diag(llg3_12); diag(llg3_12) diag(llg3_22)];
      % correction due to the log transformation
      llg3 = llg3.*lik.shape;
  end
end

function [lpy, Ey, Vary] = lik_inputdependentweibull_predy(lik, Ef, Varf, yt, zt)
%LIK_INPUTDEPENDENTWEIBULL_PREDY  Returns the predictive mean, variance and density of y
%
%  Description
%    LPY = LIK_INPUTDEPENDENTWEIBULL_PREDY(LIK, EF, VARF YT, ZT)
%    Returns logarithm of the predictive density PY of YT, that is
%        p(yt | zt) = \int p(yt | f, zt) p(f|y) df.
%    This requires also the survival times YT, censoring indicators ZT.
%    This subfunction is needed when computing posterior predictive
%    distributions for future observations.
%
%    [LPY, EY, VARY] = LIK_INPUTDEPENDENTWEIBULL_PREDY(LIK, EF, VARF) takes a
%    likelihood structure LIK, posterior mean EF and posterior
%    Variance VARF of the latent variable and returns the
%    posterior predictive mean EY and variance VARY of the
%    observations related to the latent variables. This subfunction
%    is needed when computing posterior predictive distributions for
%    future observations.
%
%
%  See also
%    GPLA_PRED, GPEP_PRED, GPMC_PRED

  if numel(zt)==0
    % no censoring
    zt=zeros(size(yt));
  end

  yc = 1-zt;
  r = lik.shape;

  Ef = Ef(:);
  ntest = 0.5*size(Ef,1);
  Ef1=Ef(1:ntest); Ef2=Ef(ntest+1:end);
  %     Varf1=squeeze(Varf(1,1,:)); Varf2=squeeze(Varf(2,2,:));
  if size(Varf,2) == size(Varf,1)
    Varf1=diag(Varf(1:ntest,1:ntest));Varf2=diag(Varf(ntest+1:end,ntest+1:end));
  else
    Varf1=Varf(:,1); Varf2=Varf(:,2);
  end

  Ey=[];
  Vary=[];

  % Evaluate the posterior predictive densities of the given observations
  lpy = zeros(length(yt),1);

  for i2=1:ntest
    m1=Ef1(i2); m2=Ef2(i2);
    s1=sqrt(Varf1(i2)); s2=sqrt(Varf2(i2));
    % Function handle for Weibull * Gaussian_f1 * Gaussian_f2
    pd=@(f1,f2) exp(yc(i2).*((log(r) + f2) + (r.*exp(f2)-1).*log(yt(i2))-f1) - exp(-f1).*yt(i2).^(r*exp(f2))) ...
      .*norm_pdf(f1,Ef1(i2),sqrt(Varf1(i2))).*norm_pdf(f2,Ef2(i2),sqrt(Varf2(i2)));
    % Integrate over latent variables
    lpy(i2) = log(dblquad(pd, m1-6.*s1, m1+6.*s1, m2-6.*s2, m2+6.*s2));
  end

end

function p = lik_inputdependentweibull_invlink(lik, f, z)
%LIK_INPUTDEPENDENTWEIBULL Returns values of inverse link function
%
%  Description
%    P = LIK_INPUTDEPENDENTWEIBULL_INVLINK(LIK, F) takes a likelihood structure LIK and
%    latent values F and returns the values of inverse link function P.
%    This subfunction is needed when using function gp_predprctmu.
%
%     See also
%     LIK_INPUTDEPENDENTWEIBULL_LL, LIK_INPUTDEPENDENTWEIBULL_PREDY

p = exp(f);
end

function reclik = lik_inputdependentweibull_recappend(reclik, ri, lik)
%RECAPPEND  Append the parameters to the record
%
%  Description
%    RECLIK = LIK_INPUTDEPENDENTWEIBULL__RECAPPEND(RECLIK, RI, LIK) takes a
%    likelihood record structure RECLIK, record index RI and
%    likelihood structure LIK with the current MCMC samples of
%    the parameters. Returns RECLIK which contains all the old
%    samples and the current samples from LIK. This subfunction
%    is needed when using MCMC sampling (gp_mc).
%
%  See also
%    GP_MC

  if nargin == 2
    % Initialize the record
    reclik.type = 'Inputdependent-Weibull';
    reclik.nondiagW=true;

    % Initialize parameter
%     reclik.shape = [];

    % Set the function handles
    reclik.fh.pak = @lik_inputdependentweibull_pak;
    reclik.fh.unpak = @lik_inputdependentweibull_unpak;
    reclik.fh.lp = @lik_t_lp;
    reclik.fh.lpg = @lik_t_lpg;
    reclik.fh.ll = @lik_inputdependentweibull_ll;
    reclik.fh.llg = @lik_inputdependentweibull_llg;
    reclik.fh.llg2 = @lik_inputdependentweibull_llg2;
    reclik.fh.llg3 = @lik_inputdependentweibull_llg3;
    reclik.fh.invlink = @lik_inputdependentweibull_invlink;
    reclik.fh.predy = @lik_inputdependentweibull_predy;
    reclik.fh.recappend = @lik_inputdependentweibull_recappend;
    reclik.p=[];
    reclik.p.shape=[];
    if ~isempty(ri.p.shape)
      reclik.p.shape = ri.p.shape;
    end
  else
    % Append to the record
    reclik.shape(ri,:)=lik.shape;
    if ~isempty(lik.p.shape)
      reclik.p.shape = lik.p.shape.fh.recappend(reclik.p.shape, ri, lik.p.shape);
    end
  end
end


clear all; close all;
I=imread('pout.tif');
M=stretchlim(I);
J=imadjust(I, M, [ ]);
figure;
subplot(121);
imshow(uint8(I));
subplot(122);
imshow(uint8(J));


function [ Detect ] = Truelabel2Trueframe( TrueLabel_bin,wsize,wstep )

iidx=1;
Frame_iidx=1;
Frame_len=Frame_Length( TrueLabel_bin,wstep,wsize );
Detect=zeros(Frame_len,1);

while(1)

    %% Windowing
    if(iidx+wsize<length(TrueLabel_bin))
        TrueLabel_frame=TrueLabel_bin(iidx:iidx+wsize-1)*10; % Because the size of TrueLabel_bin is 0.1 in TrueLabel function
    else
        TrueLabel_frame=TrueLabel_bin(iidx:end)*10; % Because the size of TrueLabel_bin is 0.1 in TrueLabel function
    end

    if(sum(TrueLabel_frame)>=wsize/2)
        TrueLabel_frame=1;
    else
        TrueLabel_frame=0;
    end
    if(Frame_iidx>length(Detect))
        break;
    end
    Detect(Frame_iidx)=TrueLabel_frame;
    iidx=iidx+wstep;
    Frame_iidx=Frame_iidx+1;
    if(iidx>length(TrueLabel_bin))
        break;
    end

end

end


% same as demo.m and demo_1p.m but using the MotionCorrection object. Scroll at the end
% to the 1p example

clear
gcp;

name = 'granule_love2.tif';         % two photon dataset
if ~exist(name,'file')  % download file if it doesn't exist in the directory
    url = 'https://www.dropbox.com/s/mjmtwn4pdgydkny/granule_love2.tif.zip?dl=1';
    filename = 'granule_love2.tif.zip';
    fprintf('downloading the file...');
    outfilename = websave(filename,url);
    fprintf('...done. Now unzipping...')
    unzip(filename);
    fprintf('done.');
end

%% rigid motion correction

MC_rigid = MotionCorrection(name);
options_rigid = NoRMCorreSetParms('d1',MC_rigid.dims(1),'d2',MC_rigid.dims(2),'bin_width',50,'max_shift',15,'us_fac',50,'init_batch',200);
MC_rigid.motionCorrectSerial(options_rigid);  % can also try parallel

%% pw-rigid motion correction (in parallel)

MC_nonrigid = MotionCorrection(name);
options_nonrigid = NoRMCorreSetParms('d1',MC_nonrigid.dims(1),'d2',MC_nonrigid.dims(2),'grid_size',[32,32],'mot_uf',4,'bin_width',50,'max_shift',15,'max_dev',3,'us_fac',50,'init_batch',200);
MC_nonrigid.motionCorrectSerial(options_nonrigid);

%% compute metrics

MC_rigid.correlationMean(10);
MC_rigid.crispness(10);
MC_nonrigid.correlationMean(10);
MC_nonrigid.crispness(10);

%% do some plotting
nnY = quantile(MC_rigid.meanY(:),0.005);
mmY = quantile(MC_rigid.meanY(:),0.995);
T = MC_rigid.T;
cY = MC_rigid.corrY;
cM1 = MC_rigid.corrM;
cM2 = MC_nonrigid.corrM;
figure;
    ax1 = subplot(2,3,1); imagesc(MC_rigid.meanY,[nnY,mmY]);  axis equal; axis tight; axis off; title('mean raw data','fontsize',14,'fontweight','bold')
    ax2 = subplot(2,3,2); imagesc(MC_rigid.meanM,[nnY,mmY]);  axis equal; axis tight; axis off; title('mean rigid corrected','fontsize',14,'fontweight','bold')
    ax3 = subplot(2,3,3); imagesc(MC_nonrigid.meanM,[nnY,mmY]); axis equal; axis tight; axis off; title('mean non-rigid corrected','fontsize',14,'fontweight','bold')
    subplot(2,3,4); plot(1:T,cY,1:T,cM1,1:T,cM2); legend('raw data','rigid','non-rigid'); title('correlation coefficients','fontsize',14,'fontweight','bold')
    subplot(2,3,5); scatter(cY,cM1); hold on; plot([0.9*min(cY),1.05*max(cM1)],[0.9*min(cY),1.05*max(cM1)],'--r'); axis square;
        xlabel('raw data','fontsize',14,'fontweight','bold'); ylabel('rigid corrected','fontsize',14,'fontweight','bold');
    subplot(2,3,6); scatter(cM1,cM2); hold on; plot([0.9*min(cY),1.05*max(cM1)],[0.9*min(cY),1.05*max(cM1)],'--r'); axis square;
        xlabel('rigid corrected','fontsize',14,'fontweight','bold'); ylabel('non-rigid corrected','fontsize',14,'fontweight','bold');
    linkaxes([ax1,ax2,ax3],'xy')

%% plot shifts

patch_id = 1:size(MC_nonrigid.shifts_x,2);
str = strtrim(cellstr(int2str(patch_id.')));
str = cellfun(@(x) ['patch # ',x],str,'un',0);

figure;
    ax1 = subplot(311); plot(1:T,cY,1:T,cM1,1:T,cM2); legend('raw data','rigid','non-rigid'); title('correlation coefficients','fontsize',14,'fontweight','bold')
            set(gca,'Xtick',[])
    ax2 = subplot(312); plot(MC_nonrigid.shifts_x); hold on; plot(MC_rigid.shifts_x,'--k','linewidth',2); title('displacements along x','fontsize',14,'fontweight','bold')
            set(gca,'Xtick',[])
    ax3 = subplot(313); plot(MC_nonrigid.shifts_y); hold on; plot(MC_rigid.shifts_y,'--k','linewidth',2); title('displacements along y','fontsize',14,'fontweight','bold')
            xlabel('timestep','fontsize',14,'fontweight','bold')
    linkaxes([ax1,ax2,ax3],'x'); legend(str)

%%
%%%%%% 1p example following demo_1p.m  %%%%%%%%

clear;
gcp;

name = '/Users/epnevmatikakis/Documents/Ca_datasets/Miniscope/msCam13.avi';
MC_1p = MotionCorrection(name);
MC_1p.HPF(7,17);                                        % high pass filter
options_1p = NoRMCorreSetParms('d1',MC_1p.dims(1),'d2',MC_1p.dims(2),'bin_width',50,'max_shift',20,'iter',1,'correct_bidir',false);
MC_1p.motionCorrectParallel(options_1p);                % correct the high pass filtered file
MC_1p.M = MC_1p.applyShifts(MC_1p.file_orig);           % apply shifts to the original file

%% plot mean images
figure;subplot(121); imagesc(mean(MC_1p.file_orig,3)); title('Mean image (raw)'); axis tight; axis equal;
       subplot(122); imagesc(mean(MC_1p.M,3)); title('Mean image (corrected)'); axis tight; axis equal;


function res = gt(a,b)
%GT           Implements  a > b  for gradients, compares only a.x and b.x
%

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

  if ~isa(a,'gradient')
    if isreal(a) & isreal(b.x)
      res = ( a>b.x );
    else
      res = ( real(a)>real(b.x) ) & ( imag(a)>imag(b.x) );
    end
  elseif ~isa(b,'gradient')
    if isreal(a.x) & isreal(b)
      res = ( a.x>b );
    else
      res = ( real(a.x)>real(b) ) & ( imag(a.x)>imag(b) );
    end
  else
    if isreal(a.x) & isreal(b.x)
      res = ( a.x>b.x );
    else
      res = ( real(a.x)>real(b.x) ) & ( imag(a.x)>imag(b.x) );
    end
  end


classdef TREE2 < PROBLEM
% <multi> <real> <large/none> <constrained> <expensive/none>
% The time-varying ratio error estimation problem
% T --- 1000 --- Length of data (related to the number of variables)

%------------------------------- Reference --------------------------------
% C. He, R. Cheng, C. Zhang, Y. Tian, Q. Chen, and X. Yao, Evolutionary
% large-scale multiobjective optimization for ratio error estimation of
% voltage transformers, IEEE Transactions on Evolutionary Computation,
% 2020, 24(5): 868-881.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    properties(Access = private)
        Data;   % Dataset
        Mean;   % Mean values of the dataset
    end
    methods
        %% Default settings of the problem
        function Setting(obj)
            % Load data
            T = obj.ParameterSet(1000);
            CallStack = dbstack('-completenames');
            load(fullfile(fileparts(CallStack(1).file),'Dataset_TREE.mat'),'Dataset');
            obj.Data = Dataset.TREE2(1:min(max(T,10),end),:);
            % Set the numbers of objectives and decision variables
            K = 3;
            obj.M = 2;
            obj.D = T*K;
            % Set the upper and lower boundaries
            Lower    = zeros(T,K);
            Upper    = zeros(T,K);
            obj.Mean = zeros(T,K);
            for i = 1 : 3
                Lower(:,i)    = min(obj.Data(:,i:3:end),[],2)/1.01;
                Upper(:,i)    = max(obj.Data(:,i:3:end),[],2)/0.99;
                obj.Mean(:,i) = mean(obj.Data(:,i:3:end),2);
            end
            % The decision variables are the offset of the mean values of
            % the dataset
            obj.lower    = reshape(Lower-obj.Mean,1,[]);
            obj.upper    = reshape(Upper-obj.Mean,1,[]);
            obj.encoding = ones(1,obj.D);
        end
        %% Generate initial solutions
        function Population = Initialization(obj,N)
            if nargin < 2; N = obj.N; end
            PopDec = obj.Mean(:)'.*(rand(N,obj.D)*0.008-0.004);
            PopDec = min(max(PopDec,repmat(obj.lower,N,1)),repmat(obj.upper,N,1));
            Population = obj.Evaluation(PopDec);
        end
        %% Calculate objective values
        function PopObj = CalObj(obj,PopDec)
            N      = size(PopDec,1);
            KP     = size(obj.Data,2);
            [T,K]  = size(obj.Mean);
            PopDec = reshape(PopDec,N,T,K) + repmat(reshape(obj.Mean,1,T,K),N,1,1);
            PopObj = zeros(N,obj.M);
            % First objective
            eA = abs(repmat(reshape(obj.Data,1,T,KP),N,1,1)./repmat(PopDec(:,:,1:3),1,1,KP/3)-1);
            PopObj(:,1) = sum(sum(eA,3),2);
            % Second objective
            Delta = std(eA(:,2:end,:)-eA(:,1:end-1,:),0,2);
            PopObj(:,2) = sum(reshape(Delta,N,[]),2);
        end
        %% Calculate constraint violations
        function PopCon = CalCon(obj,PopDec)
            N      = size(PopDec,1);
            [T,K]  = size(obj.Mean);
            PopDec = reshape(PopDec,N,T,K) + repmat(reshape(obj.Mean,1,T,K),N,1,1);
            PopCon = TREE_CalCon(PopDec,1);
        end
        %% Generate a point for hypervolume calculation
        function R = GetOptimum(obj,~)
            X = zeros(1,obj.D);
            X(1:2:end) = obj.lower(1:2:end);
            X(2:2:end) = obj.upper(2:2:end);
            R = obj.CalObj(X);
        end
    end
end


% Program by Krish Mangal, R Harsha Vardhan and R Umesh Reddy, this program
% will be available for download in MATLAB central forever, on the Harsha's
% Account( http://goo.gl/cd7c ) along with other interesting programs we have
% developed or will develop in future.
%
% This program identifies all of the moving objects in a recorded video and
% shows those objects in color while displaying the other stationary
% objects in grayscale. This is a basic program which may be used with
% other programs which use applications of Motion Detection. Details of
% this technique are expained in the project report which comes along with
% this Program. We have used the function mmread also available on matlab
% central in our program, you must download this program also and add its
% location to MATLAB's path.
%
% see also DSBAM SSBAM Kirsch
%

clc
disp('Program by Krish Mangal, R Harsha Vardhan and R Umesh Reddy, IIT Patna');
clear all
close all
tic
h = waitbar(0,'Running......');
mov = (mmread('Input.wmv'));clc
disp('Program by Krish Mangal, R Harsha Vardhan and R Umesh Reddy, IIT Patna');
movi = mov.frames;
clear mov;
for i = 2:length(movi)
    movc = movi(i).cdata;
    waitbar(i/length(movi),h);
    movp = movi(i-1).cdata;
    u = motion(movc,movp);
    diff_img(i-1,:,:) = u;

end
close(h)

disp('Step 1 is completed Going for step 2 now!!!');
h = waitbar(0,'Running......');

movo = movi;
[a b c] = size(diff_img);
for k = 1:a
for i = 1:int32(b/5)
    for j = 1:int32(c/5)
        s = diff_img(k,(5*(i-1)+1):(5*(i-1)+5),(5*(j-1)+1):(5*(j-1)+5));
        s1(:,:) = s;
        q(i,j) = sum(sum(s1));
        if q(i,j)<500
            p(k,i,j) = false;
        else
            p(k,i,j) = true;
        end
        if(~p(k,i,j))
           temp = rgb2gray( movo(k).cdata((5*(i-1)+1):(5*(i-1)+5),(5*(j-1)+1):(5*(j-1)+5),1:3));
           for w = 1:3
           movo(k).cdata((5*(i-1)+1):(5*(i-1)+5),(5*(j-1)+1):(5*(j-1)+5),w) = temp;
           end
        end
    end
end
waitbar(k/a,h);
end
close(h)
clear movc movp diff_img temp q w  b u
disp('Step 2 is completed Going for final step now!!! This step takes a lot of time ');

for b = 1:a+1
movds(:,:,:,b) = movo(b).cdata;
end

[d e f ] = size(p);
t = 1;
img_path = movi(1).cdata;
for k = 1:d
    for i = 1:e
       for j = 1:f
        if(p(k,i,j))
            x_coe(t) = i;
            y_coe(t) = j;
            t = t+1;
        end
       end
    end
    xavg = int32(round((min(x_coe)+max(x_coe))/2));
    yavg = int32(round((min(y_coe)+ max(y_coe))/2));
    xcor = (2*xavg-1)*5/2;
    ycor = (2*yavg-1)*5/2;
   if k>1
    if xcor<xprev
        xsm = xcor;
        xlr = xprev;
    else

        xlr = xcor;
        xsm = xprev;
    end
    if ycor<yprev
        ysm = ycor;
        ylr = yprev;
    else

        ylr = ycor;
        ysm = yprev;
    end
    img_path(xsm:xlr,ysm:ylr,1) = 255;
    img_path(xsm:xlr,ysm:ylr,2) = 0;
    img_path(xsm:xlr,ysm:ylr,3) = 0;
    t=1;
    clear x_coe y_coe
   end
    xprev = xcor;
    yprev = ycor;

end
imshow(img_path)
disp('Execution Complete');
toc


function [V,F,V0,F0] = text_to_mesh(str,varargin)
  % TEXT_TO_MESH Create an 3D mesh the given text
  %
  % [V,F] = text_to_mesh(str)
  % [V,F] = text_to_mesh(str,'ParameterName',ParameterValue, ...)
  %
  % Inputs:
  %   str  string of text
  %   Optional:
  %     'Dilation'  followed by amount to dilate text image
  %     'FontName  followed by name of font. List available fonts using
  %       `/usr/local/bin/convert -list font | sed -n "s/^ *Font: //p"`
  %       {[]} (see `text_to_image`)
  %     'PointSize'  followed by height of font (in pixels) {200}
  % Outputs:
  %   V  #V by 3 list of mesh vertices
  %   F  #F by 3 list of face indices into V
  %
  % Example:
  %   im = text_to_image('Zapfino','FontName','Zapfino');imshow(im)
  %

  % Defaults
  fontname = [];
  pointsize = 200;
  filename = 'text_to_image-tmp.png';
  r = 1;
  triangle_flags = '';
  siters=10;
  tol = 0.2;
  levels = 1;
  % Map of parameter names to variable names
  params_to_variables = containers.Map( ...
    {'Dilation','FontName','PointSize','SmoothingIters','Tol','TriangleFlags'}, ...
    {'r','fontname','pointsize','siters','tol','triangle_flags'});
  v = 1;
  while v <= numel(varargin)
    param_name = varargin{v};
    if isKey(params_to_variables,param_name)
      assert(v+1<=numel(varargin));
      v = v+1;
      % Trick: use feval on anonymous function to use assignin to this workspace
      feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));
    else
      error('Unsupported parameter: %s',varargin{v});
    end
    v=v+1;
  end

  im = text_to_image(str,'FontName',fontname,'PointSize',pointsize);
  [V0,F0] = bwmesh( ...
    imdilate(padarray(~im,[r,r]),strel('disk',r)), ...
    'Tol',tol, ...
    'SmoothingIters',siters, ...
    'TriangleFlags',triangle_flags);
  [V,F] = extrude(V0,F0,'Levels',levels);

end


function [ a, b ] = p03_ab ( m )

%*****************************************************************************80
%
%% P03_AB evaluates the limits of the optimization region for problem 03.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 December 2011
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Marcin Molga, Czeslaw Smutnicki,
%    Test functions for optimization needs.
%
%  Parameters:
%
%    Input, integer M, the spatial dimension.
%
%    Output, real A(M), B(M), the lower and upper bounds.
%
  a(1:m) = - 65.536;
  b(1:m) = + 65.536;

  return
end


function roisArray=dtiCreateRoisFromNifti(niftiFile)

%Create an array of ROIs corresponding to unique values in niftiFile.
%niftiFile should contain integer values labeling the voxels from the list
%of ROIs.

%ER 11/2009 wrote it

roiNii = niftiRead(niftiFile);

        % Find all unique, non-zero indices, each distinct index will be a
        % mask for a distinct ROI
        roiNii.data(isnan(roiNii.data))=0;
        roisToMake=unique(uint8(roiNii.data));
        roisToMake=roisToMake(roisToMake~=0);

        % For each distinct index, create a distinct ROI
        for jj=1:length(roisToMake)

            thisRoi = find(roiNii.data==roisToMake(jj));
            [x1,y1,z1] = ind2sub(size(roiNii.data), thisRoi);
            roisArray(jj) = dtiNewRoi([roiNii.fname '_' num2str(roisToMake(jj))], rand(1, 3));
            roisArray(jj).coords = mrAnatXformCoords(roiNii.qto_xyz, [x1,y1,z1]);
            roisArray(jj).name=[roiNii.fname '_' num2str(jj)];

        end
        if ~exist('roisArray', 'var')
            roisArray=[];
        end


function x = p41_start ( n )

%*****************************************************************************80
%
%% P41_START returns a starting point for optimization for problem 41.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 January 2001
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of variables X.
%
%    Output, real X(N), a starting point for the optimization.
%
  x = [ 0.5, 1.0, -0.5, -1.0 ]';

  return
end


%kklocxform 'Rotate, Translate, and Scale Location Data'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros klocxform.pane file
%
% Parameters:
% InputFile: i 'Input ', required: 'the input object to be processed'
% Double: xrot ' X ', default: 0: 'rotate around x axis'
% Double: yrot ' Y ', default: 0: 'rotate around y axis'
% Double: zrot ' Z ', default: 0: 'rotate around z axis'
% Toggle: fx 'Flip X', default: 0: 'flip x coordinates'
% Double: xtrans ' X ', default: 0: 'translate in x direction'
% Toggle: fy 'Flip Y', default: 0: 'flip y coordinates'
% Double: ytrans ' Y ', default: 0: 'translate in y direction'
% Toggle: fz 'Flip Z', default: 0: 'flip z coordinates'
% Double: ztrans ' Z ', default: 0: 'translate in z direction'
% OutputFile: o 'Output', required: 'the output object'
% Double: scale ' XYZ ', default: 1: 'orthogonal scale factor'
% Double: xscale ' X ', default: 1: 'scale x coordinates'
% Double: yscale ' Y ', default: 1: 'scale y coordinates'
% Double: zscale ' Z ', default: 1: 'scale z coordinates'
%
% Example: o = kklocxform(i, {'i','';'xrot',0;'yrot',0;'zrot',0;'fx',0;'xtrans',0;'fy',0;'ytrans',0;'fz',0;'ztrans',0;'o','';'scale',1;'xscale',1;'yscale',1;'zscale',1})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% klocxform - Rotate, Translate, and Scale Location Data
%
%  DESCRIPTION
% This routine performs a homogeneous coordinate
% transformation on the location data in the source
% object, and saves the transformed location data into
% the destination object.
%
% The source object must have location data, and the
% destination object must not have location data for
% this routine to function properly.  This routine will
% create location data of the proper grid type in the
% destination.
%
% The coordinate transformation can be specfied by nine
% parameters which specify an x-y-z rotation, an x-y-z
% translation, and an x-y-z scaling.  The rotations are
% all performed with respect to the (0,0,0) origin.  A
% scaling matrix, a translation matrix, and three
% rotation matrices are constructed from these
% specified parameters and composited into a single
% transformation matrix in the following order :
%
%    [1] Scaling
%    [2] X Rotation
%    [3] Y Rotation
%    [4] Z Rotation
%    [5] Translation
%
% A value of 1.0 should be used for any scaling
% parameters where no scaling is desired.  A value of
% 0.0 should be used for any rotation parameters where
% no rotation is desired or for any translation
% parameters where no translation is desired.
%
% The location points are interpreted to be in
% three-space for the transformations.  Explicit
% location data located in dimensions higher than three
% will be lost during the transformation.  The
% transformation will be performed using the datatype
% KFLOAT.
%
% In general, the grid type of the source object will
% be preserved in the destination object.  For example,
% uniform location data, when transformed and stored in
% the destination object, will still be uniform
% location data.  The exception to this rule is
% rectilinear data, which must be converted to
% curvilinear data in the event of a rotation.  In this
% case the destination location data will be stored as
% explicit curvilinear data points.
%
% Reference : Foley & VanDam "Computer Graphics :
% Principles and Practice", Second Edition, 1990,
% Chapter 5.
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kklocxform(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kklocxform(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'xrot', 0;'yrot', 0;'zrot', 0;'fx', 0;'xtrans', 0;'fy', 0;'ytrans', 0;'fz', 0;'ztrans', 0;'o', '__output';'scale', 1;'xscale', 1;'yscale', 1;'zscale', 1};
maxval={0,360,360,360,0,0,0,0,0,0,0,2,2,2,2};
minval={0,-360,-360,-360,0,0,0,0,0,0,0,2,2,2,2};
istoggle=[0,1,1,1,1,1,1,1,1,1,0,1,1,1,1];
was_set=istoggle * 0;
paramtype={'InputFile','Double','Double','Double','Toggle','Double','Toggle','Double','Toggle','Double','OutputFile','Double','Double','Double','Double'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(1,1);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
[varargout{:}]=callKhoros([w 'klocxform"  '],Inputs,narglist);


function [x, f, eflag, output, lambda] = miqps_glpk(H, c, A, l, u, xmin, xmax, x0, vtype, opt)
%MIQPS_GLPK  Mixed Integer Linear Program Solver based on GLPK - GNU Linear Programming Kit.
%   [X, F, EXITFLAG, OUTPUT, LAMBDA] = ...
%       MIQPS_GLPK(H, C, A, L, U, XMIN, XMAX, X0, VTYPE, OPT)
%   [X, F, EXITFLAG, OUTPUT, LAMBDA] = MIQPS_GLPK(PROBLEM)
%   A wrapper function providing a standardized interface for using
%   GLKP to solve the following LP (linear programming) problem:
%
%       min C'*X
%        X
%
%   subject to
%
%       L <= A*X <= U       (linear constraints)
%       XMIN <= X <= XMAX   (variable bounds)
%
%   Inputs (all optional except H, C, A and L):
%       H : dummy matrix (possibly sparse) of quadratic cost coefficients
%           for QP problems, which GLPK does not handle
%       C : vector of linear cost coefficients
%       A, L, U : define the optional linear constraints. Default
%           values for the elements of L and U are -Inf and Inf,
%           respectively.
%       XMIN, XMAX : optional lower and upper bounds on the
%           X variables, defaults are -Inf and Inf, respectively.
%       X0 : optional starting value of optimization vector X (NOT USED)
%       VTYPE : character string of length NX (number of elements in X),
%               or 1 (value applies to all variables in x),
%               allowed values are 'C' (continuous), 'B' (binary) or
%               'I' (integer).
%       OPT : optional options structure with the following fields,
%           all of which are also optional (default values shown in
%           parentheses)
%           verbose (0) - controls level of progress output displayed
%               0 = no progress output
%               1 = some progress output
%               2 = verbose progress output
%           skip_prices (0) - flag that specifies whether or not to
%               skip the price computation stage, in which the problem
%               is re-solved for only the continuous variables, with all
%               others being constrained to their solved values
%           price_stage_warn_tol (1e-7) - tolerance on the objective fcn
%               value and primal variable relative match required to avoid
%               mis-match warning message
%           glpk_opt - options struct for GLPK, value in verbose
%                   overrides these options
%       PROBLEM : The inputs can alternatively be supplied in a single
%           PROBLEM struct with fields corresponding to the input arguments
%           described above: H, c, A, l, u, xmin, xmax, x0, vtype, opt
%
%   Outputs:
%       X : solution vector
%       F : final objective function value
%       EXITFLAG : exit flag, 1 - optimal, <= 0 - infeasible, unbounded or other
%       OUTPUT : struct with errnum and status fields from GLPK output args
%       LAMBDA : struct containing the Langrange and Kuhn-Tucker
%           multipliers on the constraints, with fields:
%           mu_l - lower (left-hand) limit on linear constraints
%           mu_u - upper (right-hand) limit on linear constraints
%           lower - lower bound on optimization variables
%           upper - upper bound on optimization variables
%
%   Note the calling syntax is almost identical to that of GLPK. The main
%   difference is that the linear constraints are specified with A, L, U
%   instead of A, B, Aeq, Beq.
%
%   Calling syntax options:
%       [x, f, exitflag, output, lambda] = ...
%           miqps_glpk(H, c, A, l, u, xmin, xmax, x0, vtype, opt)
%
%       x = miqps_glpk(H, c, A, l, u)
%       x = miqps_glpk(H, c, A, l, u, xmin, xmax)
%       x = miqps_glpk(H, c, A, l, u, xmin, xmax, x0)
%       x = miqps_glpk(H, c, A, l, u, xmin, xmax, x0, vtype)
%       x = miqps_glpk(H, c, A, l, u, xmin, xmax, x0, vtype, opt)
%       x = miqps_glpk(problem), where problem is a struct with fields:
%                       H, c, A, l, u, xmin, xmax, x0, vtype, opt
%                       all fields except 'c', 'A' and 'l' or 'u' are optional
%       x = miqps_glpk(...)
%       [x, f] = miqps_glpk(...)
%       [x, f, exitflag] = miqps_glpk(...)
%       [x, f, exitflag, output] = miqps_glpk(...)
%       [x, f, exitflag, output, lambda] = miqps_glpk(...)
%
%
%   Example: (problem from from https://v8doc.sas.com/sashtml/iml/chap8/sect12.htm)
%       H = [   1003.1  4.3     6.3     5.9;
%               4.3     2.2     2.1     3.9;
%               6.3     2.1     3.5     4.8;
%               5.9     3.9     4.8     10  ];
%       c = zeros(4,1);
%       A = [   1       1       1       1;
%               0.17    0.11    0.10    0.18    ];
%       l = [1; 0.10];
%       u = [1; Inf];
%       xmin = zeros(4,1);
%       x0 = [1; 0; 0; 1];
%       opt = struct('verbose', 2);
%       [x, f, s, out, lambda] = miqps_glpk(H, c, A, l, u, xmin, [], x0, vtype, opt);
%
%   See also MIQPS_MASTER, GLPK.

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

%% check for Optimization Toolbox
% if ~have_feature('quadprog')
%     error('miqps_glpk: requires the MEX interface to GLPK');
% end

%%----- input argument handling  -----
%% gather inputs
if nargin == 1 && isstruct(H)       %% problem struct
    p = H;
    if isfield(p, 'opt'),   opt = p.opt;    else,   opt = [];   end
    if isfield(p, 'vtype'), vtype = p.vtype;else,   vtype = []; end
    if isfield(p, 'x0'),    x0 = p.x0;      else,   x0 = [];    end
    if isfield(p, 'xmax'),  xmax = p.xmax;  else,   xmax = [];  end
    if isfield(p, 'xmin'),  xmin = p.xmin;  else,   xmin = [];  end
    if isfield(p, 'u'),     u = p.u;        else,   u = [];     end
    if isfield(p, 'l'),     l = p.l;        else,   l = [];     end
    if isfield(p, 'A'),     A = p.A;        else,   A = [];     end
    if isfield(p, 'c'),     c = p.c;        else,   c = [];     end
    if isfield(p, 'H'),     H = p.H;        else,   H = [];     end
else                                %% individual args
    if nargin < 10
        opt = [];
        if nargin < 9
            vtype = [];
            if nargin < 8
                x0 = [];
                if nargin < 7
                    xmax = [];
                    if nargin < 6
                        xmin = [];
                    end
                end
            end
        end
    end
end

%% define nx, set default values for missing optional inputs
if isempty(H) || ~any(any(H))
    if isempty(A) && isempty(xmin) && isempty(xmax)
        error('miqps_glpk: LP problem must include constraints or variable bounds');
    else
        if ~isempty(A)
            nx = size(A, 2);
        elseif ~isempty(xmin)
            nx = length(xmin);
        else    % if ~isempty(xmax)
            nx = length(xmax);
        end
    end
else
    error('miqps_glpk: GLPK handles only LP problems, not QP problems');
    nx = size(H, 1);
end
if isempty(c)
    c = zeros(nx, 1);
end
if isempty(A) || (~isempty(A) && (isempty(l) || all(l == -Inf)) && ...
                                 (isempty(u) || all(u == Inf)))
    A = sparse(0,nx);           %% no limits => no linear constraints
end
nA = size(A, 1);                %% number of original linear constraints
if isempty(u)                   %% By default, linear inequalities are ...
    u = Inf(nA, 1);             %% ... unbounded above and ...
end
if isempty(l)
    l = -Inf(nA, 1);            %% ... unbounded below.
end
if isempty(xmin)                %% By default, optimization variables are ...
    xmin = -Inf(nx, 1);         %% ... unbounded below and ...
end
if isempty(xmax)
    xmax = Inf(nx, 1);          %% ... unbounded above.
end
if isempty(x0)
    x0 = zeros(nx, 1);
end

%% default options
if ~isempty(opt) && isfield(opt, 'verbose') && ~isempty(opt.verbose)
    verbose = opt.verbose;
else
    verbose = 0;
end

%% split up linear constraints
ieq = find( abs(u-l) <= eps );          %% equality
igt = find( u >=  1e10 & l > -1e10 );   %% greater than, unbounded above
ilt = find( l <= -1e10 & u <  1e10 );   %% less than, unbounded below
ibx = find( (abs(u-l) > eps) & (u < 1e10) & (l > -1e10) );
AA = [ A(ieq, :); A(ilt, :); -A(igt, :); A(ibx, :); -A(ibx, :) ];
bb = [ u(ieq);    u(ilt);    -l(igt);    u(ibx);    -l(ibx)];

%% grab some dimensions
nlt = length(ilt);      %% number of upper bounded linear inequalities
ngt = length(igt);      %% number of lower bounded linear inequalities
nbx = length(ibx);      %% number of doubly bounded linear inequalities
neq = length(ieq);      %% number of equalities
nie = nlt+ngt+2*nbx;    %% number of inequalities

ctype = [repmat('S', neq, 1); repmat('U', nlt+ngt+2*nbx, 1)];

if isempty(vtype) || isempty(find(vtype == 'B' | vtype == 'I'))
    mi = 0;
    vtype = repmat('C', nx, 1);
else
    mi = 1;
    %% expand vtype to nx elements if necessary
    if length(vtype) == 1 && nx > 1
        vtype = char(vtype * ones(nx, 1));
    elseif size(vtype, 2) > 1   %% make sure it's a col vector
        vtype = vtype';
    end
end
%% convert 'B' variables to 'I' and clip bounds to [0, 1]
k = find(vtype == 'B');
if ~isempty(k)
    kk = find(xmax(k) > 1);
    xmax(k(kk)) = 1;
    kk = find(xmin(k) < 0);
    xmin(k(kk)) = 0;
    vtype(k) = 'I';
end

%% set options struct for GLPK
if ~isempty(opt) && isfield(opt, 'glpk_opt') && ~isempty(opt.glpk_opt)
    glpk_opt = glpk_options(opt.glpk_opt);
else
    glpk_opt = glpk_options;
end
glpk_opt.msglev = verbose;

%% call the solver
[x, f, errnum, extra] = ...
    glpk(c, AA, bb, xmin, xmax, ctype, vtype, 1, glpk_opt);

%% set exit flag
if isfield(extra, 'status')             %% status found in extra.status
    output.errnum = errnum;
    output.status = extra.status;
    eflag = -errnum;
    if eflag == 0 && extra.status == 5
        eflag = 1;
    end
else                                    %% status found in errnum
    output.errnum = [];
    output.status = errnum;
    if have_feature('octave')
        if errnum == 180 || errnum == 151 || errnum == 171
            eflag = 1;
        else
            eflag = 0;
        end
    else
        if errnum == 5
            eflag = 1;
        else
            eflag = 0;
        end
    end
end

%% repackage lambdas
if isempty(extra) || ~isfield(extra, 'lambda') || isempty(extra.lambda)
    lambda = struct( ...
        'mu_l', zeros(nA, 1), ...
        'mu_u', zeros(nA, 1), ...
        'lower', zeros(nx, 1), ...
        'upper', zeros(nx, 1) ...
    );
else
    lam.eqlin = extra.lambda(1:neq);
    lam.ineqlin = extra.lambda(neq+(1:nie));
    lam.lower = extra.redcosts;
    lam.upper = -extra.redcosts;
    lam.lower(lam.lower < 0) = 0;
    lam.upper(lam.upper < 0) = 0;
    kl = find(lam.eqlin > 0);   %% lower bound binding
    ku = find(lam.eqlin < 0);   %% upper bound binding

    mu_l = zeros(nA, 1);
    mu_l(ieq(kl)) = lam.eqlin(kl);
    mu_l(igt) = -lam.ineqlin(nlt+(1:ngt));
    mu_l(ibx) = -lam.ineqlin(nlt+ngt+nbx+(1:nbx));

    mu_u = zeros(nA, 1);
    mu_u(ieq(ku)) = -lam.eqlin(ku);
    mu_u(ilt) = -lam.ineqlin(1:nlt);
    mu_u(ibx) = -lam.ineqlin(nlt+ngt+(1:nbx));

    lambda = struct( ...
        'mu_l', mu_l, ...
        'mu_u', mu_u, ...
        'lower', lam.lower(1:nx), ...
        'upper', lam.upper(1:nx) ...
    );
end

if mi && eflag == 1 && (~isfield(opt, 'skip_prices') || ~opt.skip_prices)
    if verbose
        fprintf('--- Integer stage complete, starting price computation stage ---\n');
    end
    if isfield(opt, 'price_stage_warn_tol') && ~isempty(opt.price_stage_warn_tol)
        tol = opt.price_stage_warn_tol;
    else
        tol = 1e-7;
    end
    k = find(vtype == 'I' | vtype == 'B');
    x(k) = round(x(k));
    xmin(k) = x(k);
    xmax(k) = x(k);
    x0 = x;
    opt.glpk_opt.lpsolver = 1;      %% simplex
    opt.glpk_opt.dual = 0;          %% primal simplex
    if have_feature('octave') && have_feature('octave', 'vnum') >= 3.007
        opt.glpk_opt.dual = 1;      %% primal simplex
    end

    [x_, f_, eflag_, output_, lambda] = qps_glpk(H, c, A, l, u, xmin, xmax, x0, opt);
    if eflag ~= eflag_
        error('miqps_glpk: EXITFLAG from price computation stage = %d', eflag_);
    end
    if abs(f - f_)/max(abs(f), 1) > tol
        warning('miqps_glpk: relative mismatch in objective function value from price computation stage = %g', abs(f - f_)/max(abs(f), 1));
    end
    xn = x;
    xn(abs(xn)<1) = 1;
    [mx, k] = max(abs(x - x_) ./ xn);
    if mx > tol
        warning('miqps_glpk: max relative mismatch in x from price computation stage = %g (%g)', mx, x(k));
    end
    output.price_stage = output_;
end


function [acc, cm, classcount, passthresh] = ...
    msAnalyzeResult(imsegs, labels, pg, DO_SP, ignore, thresh, niter)

nclasses = size(pg{1}, 2);
cm = zeros(nclasses, nclasses);
total = 0;
acc = 0;

passthresh = 0;
pttotal = 0;

if ~exist('thresh', 'var') || isempty(thresh)
    thresh = 0;
end

for f = 1:numel(pg)

    if exist('niter', 'var') && ~isempty(niter)
        pg{f} = mean(pg{f}(:, :, 1:niter), 3);
    end

    lab = labels{f}(:);

    if ~isempty(imsegs)
        npixels = imsegs(f).npixels(:) / sum(imsegs(f).npixels);
    end

    pg{f}(:, ignore) = 0;

    ind = false(size(lab));
    for k = 1:numel(ignore)
        ind(lab==ignore(k)) = true;
    end
    lab(ind) = 0;
    [maxval, maxlab] = max(pg{f}, [], 2);

    if DO_SP

        pttotal = pttotal + sum(npixels.*(lab>0));
        lab(maxval<thresh) = 0; %ignore labels assigned below threshold confidence
        passthresh = passthresh + sum(npixels.*(lab>0));

        acc = acc + sum((lab==maxlab).*npixels);
        total = total + sum(npixels((lab>0)));

        for s = 1:numel(maxlab)
            if lab(s)~=0
                cm(lab(s), maxlab(s)) = cm(lab(s), maxlab(s)) + npixels(s);
            end
        end
    else

        if ~isempty(imsegs)
            maxlab = maxlab(imsegs(f).segimage);
            maxval = maxval(imsegs(f).segimage);
        end

        pttotal = pttotal + sum((lab>0)/numel(lab));
        lab(maxval<thresh) = 0; %ignore labels assigned below threshold confidence
        passthresh = passthresh + sum((lab>0)/numel(lab));

%           maxlab2 = maxlab; maxlab2(maxval<0.5) = 0;
%         figure(2), hold off, imagesc(maxlab2, [0 21]), axis image
%         figure(3), imagesc(maxlab, [0 21]), axis image
%         figure(4), imagesc(reshape(lab, size(maxlab)), [0 21]), axis image, colormap jet
%         pause

        acc = acc + sum(lab==maxlab(:))/numel(lab);
        total = total + sum(lab(:)>0)/numel(lab);
        for y1 = 1:nclasses
            ind = lab==y1;
            if any(ind)
                for y2 = 1:nclasses
                    ind2 = ind & (maxlab(:)==y2);
                    cm(y1, y2) = cm(y1, y2) + sum(ind2)/numel(lab);
                end
            end
        end
    end
end

acc = acc / total;

classcount = sum(cm, 2)';
classcount = classcount / sum(classcount);

cm = cm ./ max(repmat(sum(cm, 2), 1, size(cm, 2)), 1E-9);

passthresh = passthresh / pttotal;

%disp(['vacc: ' num2str(vacc) '   hacc: ' num2str(hacc)])
%disp(num2str(sum(ny, 1) / sum(totalv)))


function [x,zo]=estnoiseg_orig(yf,tz,pp)
%ESTNOISEG - estimate MMSE noise spectrum [x,zo]=(yf,tz,pp)
%
% Usage:    ninc=round(0.016*fs);   % frame increment [fs=sample frequency]
%           ovf=2;                  % overlap factor
%           f=rfft(enframe(s,hanning(ovf*ninc,'periodic'),ninc),ovf*ninc,2);
%           f=f.*conj(f);           % convert to power spectrum
%           x=estnoiseg(f,ninc/fs); % estimate the noise power spectrum
%
% Inputs:
%   yf      input power spectra (one row per frame)
%   tz      frame increment in seconds
%           Alternatively, the input state from a previous call (see below)
%   pp      algorithm parameters [optional]
%
% Outputs:
%   x       estimated noise power spectra (one row per frame)
%   zo      output state
%
% The algorithm parameters are defined in reference [1] from which equation
% numbers are given in parentheses. They are as follows:
%
%        pp.tax      % smoothing time constant for noise power estimate [0.0717 seconds](8)
%        pp.tap      % smoothing time constant for smoothed speech prob [0.152 seconds](23)
%        pp.psthr    % threshold for smoothed speech probability [0.99] (24)
%        pp.pnsaf    % noise probability safety value [0.01] (24)
%        pp.pspri    % prior speech probability [0.5] (18)
%        pp.asnr     % active SNR in dB [15] (18)
%        pp.psini    % initial speech probability [0.5] (23)
%        pp.tavini   % assumed speech absent time at start [0.064 seconds]
%
% If convenient, you can call estnoiseg in chunks of arbitrary size. Thus the following are equivalent:
%
%                   (a) dp=estnoiseg(yp(1:300),tinc);
%
%                   (b) [dp(1:100,:),z]=estnoiseg(yp(1:100,:),tinc);
%                       [dp(101:200,:),z]=estnoiseg(yp(101:200,:),z);
%                       [dp(201:300,:),z]=estnoiseg(yp(201:300,:),z);

% This is intended to be a precise implementation of [1] for a frame rate of 62.5 Hz.
% Time constants are adjusted for other frame rates.
%
% Refs:
%    [1] Gerkmann, T. & Hendriks, R. C.
%        Unbiased MMSE-Based Noise Power Estimation With Low Complexity and Low Tracking Delay
%        IEEE Trans Audio, Speech, Language Processing, 2012, 20, 1383-1393

%	   Copyright (C) Mike Brookes 2012
%      Version: $Id: estnoiseg.m 3387 2013-08-23 12:32:47Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   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 can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[nr,nrf]=size(yf);          % number of frames and freq bins
x=zeros(nr,nrf);            % initialize output arrays
if isempty(yf) && isstruct(tz)             % no real data
    zo=tz;                  % just keep the same state
else
    if isstruct(tz)         % take parameters from a previous call
        nrcum=tz.nrcum;     % cumulative number of frames
        xt=tz.xt;           % smoothed power spectrum
        pslp=tz.pslp;       % correction factor (9)
        tinc=tz.tinc;       % frame increment
        qq=tz.qq;           % parameter structure
    else
        tinc = tz;          % second argument is frame increment
        nrcum=0;            % no frames so far
        % default algorithm constants
        qq.tax=0.0717;      % noise output smoothing time constant = -tinc/log(0.8) (8)
        qq.tap=0.152;       % speech prob smoothing time constant = -tinc/log(0.9) (23)
        qq.psthr=0.99;      % threshold for smoothed speech probability [0.99] (24)
        qq.pnsaf=0.01;      % noise probability safety value [0.01] (24)
        qq.pspri=0.5;       % prior speech probability [0.5] (18)
        qq.asnr=15;         % active SNR in dB [15] (18)
        qq.psini=0.5;       % initial speech probability [0.5] (23)
        qq.tavini=0.064;        % assumed speech absent time at start [64 ms]

        if nargin>=3 && ~isempty(pp)  % update fields from pp input
            qqn=fieldnames(qq);
            for i=1:length(qqn)
                if isfield(pp,qqn{i})
                    qq.(qqn{i})=pp.(qqn{i});
                end
            end
        end
        pslp=repmat(qq.psini,1,nrf); % initialize smoothed speech presence prob
        xt=[];                       % initialize just in case the first call has no data
    end

    % unpack parameters needed within the loop

    psthr=qq.psthr;     % threshold for smoothed speech probability [0.99] (24)
    pnsaf=qq.pnsaf;     % noise probability safety value [0.01] (24)

    % derived algorithm constants

    ax=exp(-tinc/qq.tax); % noise output smoothing factor = 0.8 (8)
    axc=1-ax;
    ap=exp(-tinc/qq.tap); % noise output smoothing factor = 0.9 (23)
    apc=1-ap;
    xih1=10^(qq.asnr/10); % speech-present SNR
    xih1r=1/(1+xih1)-1;
    pfac=(1/qq.pspri-1)*(1+xih1); % p(noise)/p(speech) (18)

    if nrcum==0 && nr>0       % initialize values for first frame
        xt=qq.psini*mean(yf(1:max(1,min(nr,round(1+qq.tavini/tinc))),:),1);  % initial noise estimate
    end

    % loop for each frame
    for t=1:nr
        yft=yf(t,:);        % noisy speech power spectrum
        ph1y=(1+pfac*exp(xih1r*yft./xt)).^(-1); % a-posteriori speech presence prob (18)
        pslp=ap*pslp+apc*ph1y; % smoothed speech presence prob (23)
        ph1y=min(ph1y,1-pnsaf*(pslp>psthr)); % limit ph1y (24)
        xtr=(1-ph1y).*yft+ph1y.*xt; % estimated raw noise spectrum (22)
        xt=ax*xt+axc*xtr;  % smooth the noise estimate (8)
        x(t,:)=xt;  % save the noise estimate
    end
    if nargout>1    % we need to store the state for next time
        zo.nrcum=nrcum+nr;      % number of frames so far
        zo.xt=xt;          % smoothed power spectrum
        zo.pslp=pslp;               % correction factor (9)
        zo.tinc=tinc;     % must be the last one
        zo.qq=qq;
    end
    if ~nargout
        clf;
        subplot(212);
        plot((1:nr)*tinc,10*log10([sum(yf,2) sum(x,2)]))
        ylabel('Frame Energy (dB)');
        xlabel(sprintf('Time (s)   [%d ms frame incr]',round(tinc*1000)));
        axisenlarge([-1 -1.05]);
        legend('input','noise','Location','Best');
        subplot(211);
        plot(1:nrf,10*log10([sum(yf,1)'/nr sum(x,1)'/nr]))
        ylabel('Power (dB)');
        xlabel('Frequency bin');
        axisenlarge([-1 -1.05]);
        legend('input','noise','Location','Best');
    end
end


%GRIDGEN Grid and mesh generation for geometry objects.
%
%   [ GRID, STATS ] = GRIDGEN( SIN, VARARGIN ) Generates a grid/mesh
%   for the geometry defined by the objects in SIN by calling an
%   external grid generation algorithm. SIN can be either a valid fea
%   problem struct with geometry defined in SIN.geom.objects, a cell
%   array of multiple geometry objects, or a single geometry
%   object. Accepts the following property/value pairs are available
%   with the default grid generation algorithm.
%
%       Property    Value/{Default}           Description
%       -----------------------------------------------------------------------------------
%       gridgen     string {default}          Grid generation algorithm: default, gmsh
%                                                robust (3D), gridgen2d, or triangle (2D)
%       dprim       logical    {true}         Structrured meshing of primitives
%       hmax        scalar/arr {0.1}          Target grid size for subdomains
%       hmaxb       scalar/arr {[]}           Target grid size for boundaries
%       hmaxe       scalar/arr {[]}           Target grid size for edges (3D)
%       grading     scalar     0.3            Mesh grading/growth rate
%       eledge      scalar     1              Elements per edge
%       quad        logical    {false}        Use quad meshing (2D)
%       intb        logical    {true}         Output interior/internal boundaries
%       waitbar     scalar     {0}            Show/hide waitbar
%       fid         scalar     {1}            File identifier for output ([]=no output)
%
%   GRIDGEN specifies which grid generation algorithm to use and calls
%   the corresponding grid generation code (default, gmsh, robust
%   (3D), gridgen2d (2D), or triangle (2D)). Enabling DPRIM with the
%   default grid generator enables structured meshing of single
%   geometry object primitives (and no differing boundary/edge mesh
%   sizing).
%
%   HMAX indicates target grid cell diameters, and is either a numeric
%   scalar prescribing the grid size for the entire geometry, or an
%   array with HMAX values corresponding to individual
%   subdomains. Positive HMAX values uses the minimum mesh size for
%   shared boundaries, while negative applys the mean value.
%
%   HMAXB is analogous to HMAX but related to boundaries
%   (edges/faces). HMAXB can be a single scalar applicable to all
%   boundaries, a numeric array with entries corresponding to
%   individual boundaries.
%
%   HMAXE is analogous to HMAXB but related to 3D edges (only
%   applicable to default grid generator for 3D geometries).
%
%   GRADING specifies the rate at which smaller cells will grow to
%   larger (0 - 1), and ELEDGE optionally prescribes the minimum
%   elements per edge.
%
%   INTB toggels interior/internal boundaries on (default) or off.
%
%
%   The following additional property/value pairs are available with
%   and specific to the GMSH mesh generator.
%
%       Property    Value/{Default}            Description
%       -----------------------------------------------------------------------------------
%       hmaxp       scal/arr {[]}              Target grid size for vertices
%       nref        scalar   {0}               Number of uniform grid refinements
%       algo2       scalar   {2}               2D mesh algorithm (1=MeshAdapt, 2=Automatic,
%                                              5=Delaunay, 6=Frontal, 7=BAMG, 8=DelQuad)
%       algo3       scalar   {1}               3D mesh algorithm (1=Del, 2=New Del, 4=Front
%                                              5=Front Del, 6=Front Hex, 7=MMG3D, 9=R-tree)
%       blayer      struct   {[]}              Data struct for Gmsh 2D boundary layers
%       quad        logical  {false}           Use quad meshing (for 2D)
%       intb        logical  {true}            Output interior/internal boundaries
%       avhb        logical  {true}            Average hmax to boundaries
%       nsm         scalar   {3}               Number of (post) grid smoothing steps
%       palign      scalar   {eps}             Distance tolerance to align point objects
%       tol         scalar   {eps*1e3}         Deduplication tolerance
%       compound    logical  {true}            Use Gmsh compound boundaries
%       mshopt      cell     {}                Cell array of additional Gmsh options
%       mshall      logical  {true}            Output/save all meshed entities
%       mshver      integer  {2}               Gmsh msh file version (1/2/4)
%       verbosity   integer  {5}               Gmsh verbosity/output level
%       syscmd      string   {'default'}       Gmsh system call command
%                                              (default 'gmsh fdir/fname.geo -')
%       fname       string   {'featool_gmsh_UID'}  Gmsh imp/exp file name (root)
%       fdir        string   {tempdir}         Directory to write help files
%       clean       logical  {true}            Delete (clean) Gmsh help files
%
%   NREF (default 0) the number of post uniform grid refinement steps.
%
%   ALGO2 and ALGO3 the Gmsh 2D and 3D mesh generation algorithms.
%
%   QUAD (default 0) toggles Blossom-Quad conversion for 2D geometries.
%
%   The BLAYER flag enables boundary layers for boundaries. May
%   optionally given as array of structs where each entry corresponds
%   to a boundary layer field entry.
%
%   The AVHB logical flag toggles if internal boundaries inheriting
%   HMAX values (when HMAXB is unspecified) should be assigned the
%   smallest HMAX value from neighbouring subdomains, or the mean value
%   (default).
%
%   NSM (default 3) the number of GRIDSMOOTH smoothing steps to perform.
%
%   PALIGN sets a minimum distance over which to re-align mesh
%   vertices to point objects.
%
%   Additional Gmsh options can be provided with the cell array
%   MSHOPT. For example to set the "CharacteristicLengthMax" and "AnisoMax"
%   Gmsh options, MSHOPT could be given as
%
%       {{'Mesh', 'CharacteristicLengthMax', '1'}, {'Mesh', 'AnisoMax', '10'}}
%
%
%   The following additional property/value pairs are available with
%   and specific to the GRIDGEN2D mesh generator.
%
%       Property    Value/{Default}            Description
%       -----------------------------------------------------------------------------------
%       q           scalar   {0.65}            Target quality
%       blayer      logical  {false}           Enable boundary layers
%       avhb        logical  {true}            Average hmax to boundaries
%       nsm         scalar   {3}               Number of (post) grid smoothing steps
%       palign      scalar   {eps}             Distance tolerance to align point objects
%
%   Q (default 0.65) specifies a quality target [0 < q < 1.0].
%
%   The BLAYER flag enables boundary layers for internal boundaries
%   (holes). May optionally given as a vector where the 1st entry
%   specifies relative thickness of stretched layer.
%
%   PALIGN sets a minimum distance over which to re-align mesh
%   vertices to point objects.
%
%
%   The following additional property/value pairs are available with
%   and specific to the TRIANGLE mesh generator.
%
%       Property    Value/{Default}            Description
%       -----------------------------------------------------------------------------------
%       q           scalar   {28}              Minimum target angle (quality)
%       syscmd      string   {'default'}       Triangle system call command (default
%                                              'triangle -I -q%f -j -e -a -A %s.poly')
%       fname       string   {'featool_tri_UID'}  Triangle imp/exp file name (root)
%       fdir        string   {tempdir}         Directory to write help files
%       clean       logical  {true}            Delete (clean) Triangle help files
%
%   Q (default 28 degrees) specifies a minimum target angle (values less than 33 are
%   generally acceptable, while higher values might prevent Triangle convergence).
%
%
%   Examples:
%
%      1) Unit circle with uniform global grid size set to 0.1.
%
%      grid = gridgen( gobj_cone, 'hmax', 0.1 );
%      plotgrid( grid )
%
%      2) Unit square with a finer grid along the top boundary (using Triangle).
%
%      grid = gridgen( gobj_rectangle, 'hmax', 0.5, ...
%                      'hmaxb', [0.5 0.5 0.01 0.5], 'gridgen', 'triangle' );
%      plotgrid( grid )
%
%      3) Domain with curved boundaries meshed with quadrilaterals (using Gmsh).
%
%      geom.objects = {gobj_rectangle() gobj_circle([0 0],.6) gobj_circle([1 1],.3,'C2')};
%      geom = geom_apply_formula( geom, 'R1-C1-C2' );
%      grid = gridgen( geom, 'hmax', 0.1, 'gridgen', 'gmsh', 'quad', true, 'verbosity', 3 );
%      plotgrid( grid )
%
%      4) Two connected subdomains with a shared boundary (using Gridgen2D).
%
%      geom.objects = { gobj_polygon([-2e-3 -8e-3;0 -8e-3;0 -6e-3;0 6e-3;0 8e-3;-2e-3 8e-3]), ...
%      gobj_polygon([0 -6e-3;2e-3 -5e-3;2e-3 4e-3;0 6e-3]) };
%      hmax  = 5e-4;
%      hmaxb = hmax*ones(1,4);
%      hmaxb(9) = hmax/5;
%      grid  = gridgen( geom, 'hmax', hmax, 'hmaxb', hmaxb, 'gridgen', 'gridgen2d' );
%      plotgrid( grid )
%
%      5) Composite component with two subdomains (using Gridgen2D).
%
%      r1 = gobj_rectangle( 0, 0.11, 0, 0.12,  'R1' );
%      c1 = gobj_circle( [ 0.065 0 ],   0.015, 'C1' );
%      c2 = gobj_circle( [ 0.11 0.12 ], 0.035, 'C2' );
%      c3 = gobj_circle( [ 0 0.06 ],    0.025, 'C3' );
%      r2 = gobj_rectangle( 0.065, 0.16, 0.05, 0.07, 'R2' );
%      c4 = gobj_circle( [ 0.065 0.06 ], 0.01, 'C4' );
%      geom.objects = { r1 c1 c2 c3 r2 c4 };
%      geom = geom_apply_formula( geom, 'R1-C1-C2-C3' );
%      geom = geom_apply_formula( geom, 'R2+C4' );
%
%      grid  = gridgen( geom, 'hmax', [0.0025 0.01 0.0025], 'gridgen', 'gridgen2d' );
%      plotgrid( grid )
%
%      6) Complex geometry with several holes and subdomains (using Gridgen2D).
%
%      w = 10e-4; L = 3*w; H = 5*w;
%      p1  = gobj_polygon( [w/10 0;(L-w/4)/2 0;(L-w/4)/2 H;0 H;0 H/3], 'P1' );
%      p2  = gobj_polygon( [(L+w/4)/2 0;L 0;L H-H/3;L H;(L+w/4)/2 H], 'P2' );
%      r1  = gobj_rectangle( (L-w/4)/2, (L+w/4)/2, 0, H, 'R1' );
%      c1  = gobj_circle( [2*w/3 3*w], w/3, 'C1' );
%      c2  = gobj_circle( [2*w/3 2*w], w/3, 'C2' );
%      c3  = gobj_circle( [2*w/3 1*w], w/3, 'C3' );
%      c4  = gobj_circle( [L-w/2 4.5*w], w/8, 'C4' );
%      c5  = gobj_circle( [L-w   4.5*w], w/8, 'C5' );
%      c6  = gobj_circle( [L-w/2 4*w], w/8, 'C6' );
%      c7  = gobj_circle( [L-w   4*w], w/8, 'C7' );
%      c8  = gobj_circle( [L-w/2 3.5*w], w/8, 'C8' );
%      c9  = gobj_circle( [L-w   3.5*w], w/8, 'C9' );
%      c10 = gobj_circle( [L-w/2 3*w], w/8, 'C10' );
%      c11 = gobj_circle( [L-w   3*w], w/8, 'C11' );
%
%      geom.objects = { p1 p2 r1 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 };
%      geom = geom_apply_formula( geom, 'P1-C1-C2-C3' );
%      geom = geom_apply_formula( geom, 'P2-C4-C5-C6-C7-C8-C9-C10-C11' );
%
%      hmax = w./[5 5 20];     % Set finer mesh size in subdomain 3.
%      hmaxb = zeros(1,21);
%      hmaxb([6 21]) = w/50;   % Set finer mesh size on the in and outlets, boundaries 6 and 21.
%      grid = gridgen( geom, 'hmax', hmax, 'hmaxb', hmaxb, 'gridgen', 'gridgen2d' );
%      plotgrid( grid )
%
%      7) Cone showing the interior y>0 and z<0 (using Gmsh).
%
%      grid = gridgen( gobj_cone, 'hmax', 0.25, 'gridgen', 'gmsh' );
%      plotgrid( grid, 'facecolor', 'none', 'edgecolor', [.7 .7 .7] )
%      plotgrid( grid, 'selcells', '(y>0)&(z<0)' )

% Copyright 2013-2022 Precise Simulation, Ltd.


function out=cumprod(x,dim)

if ~isempty(x)

 precision=x(1).precision;
 % can only handle up to 2 dimensions
 s=size(x);
 out=x;
 if nargin==1
  if any(s==1)
   for ii=2:numel(x)
    out(ii)=out(ii-1)*x(ii);
   end
  else
   for j=1:s(2)
    for i=2:s(1)
     out(i,j)=out(i-1,j)*x(i,j);
    end
   end
  end
 elseif nargin==2
  if dim==1
   for j=1:s(2)
    for i=2:s(1)
     out(i,j)=out(i-1,j)*x(i,j);
    end
   end
  elseif dim==2
   for j=2:s(2)
    for i=1:s(1)
     out(i,j)=out(i,j-1)*x(i,j);
    end
   end
  else
   error('mp cumprod can only handle up to 2-D arrays (11/04)');
  end
 end

else
 out=x;
end


function H = PlotSwathe(bar,swathe,col,transp,nticks,fo,frequency,swatheonly)
% =========================================================================
% Plot a line with a shaded swathe
% =========================================================================
% H = PlotSwathe(bar,swathe,col,transp,nticks,fo,frequency,swatheonly)
% -------------------------------------------------------------------------
% INPUT
%   - bar: line to plot
%   - swathe: if a vector, draws symmetric errorbars. Otherwise draws
%     	asymmetric error bars, with first columnn being the upper bar and
%       second column being the lower bar
%--------------------------------------------------------------------------
% OPTIONAL INPUT
%   - col: color of the line/patch, can be rgb number (e.g. [1 0 0]
%       or string (e.g. 'blue')
%   - transp: 'transparent' for transparency, [empty] otherwise.
%       Default is [empty]
%   - nticks: number ticks on the horizontal axis
%   - fo: first observation (convention: 1987.00 = 1987Q1)
%   - frequency: quarterly ('q') or annual ('y') frequency. Default: 'q'
%   - swatheonly: set to 1 to plot only the swathe. Default: 0
%--------------------------------------------------------------------------
% OUPUT
%   - H.bar: handle for the median
%   - H.patch: handle for the patch
%   - H.swathe: H.swathe(1) handle for upp , H.swathe(2) handle for low
%   - H.ax: hande for the axis
%   - H.nobs: number of observations
% =========================================================================
% EXAMPLE
% x = 3*sin(1:50);
% PlotSwathe(x,1,'dark blue','transparent',2,1970)
% hold on
% y = cos(1:50);
% PlotSwathe(y,1,'light red','transparent',2,1970)
% =========================================================================
% Ambrogio Cesa Bianchi, March 2015
% ambrogio.cesabianchi@gmail.com

%% INITIALIZE VARIABLES
if ~exist('col','var')
    colrgb = rgb('dark grey');
else
    if isnumeric(col) % in case user provides already the rgb code
        colrgb = col;
    else % otherwise use rgb to get the code
        colrgb = rgb(col);
    end
end

if ~exist('transp','var')
    transp = '';
end

if ~exist('fo','var')
    do_dates=0;
else
    do_dates=1;
    if ~exist('frequency','var')
        frequency = 'q';
    end
end

if ~exist('swatheonly','var')
    swatheonly = 0;
end

% Number of observations
nobs = length(bar); H.nobs = nobs;

% Make sure data is row-vector
if size(bar,1)>1
    bar =bar';
end

% Check if swathe is vector and set error bands
if isvector(swathe)
    % Check if swathe has the right dimension [1 x T]
    if size(swathe,1)>1
        swathe = swathe';
        low = bar - swathe;
        upp = bar + swathe;
    else
        low = bar - swathe;
        upp = bar + swathe;
    end
else
    % Check if i has the right dimension [2 x T]
    if size(swathe,1)>2
        swathe = swathe';
        upp = swathe(1,:);
        low = swathe(2,:);
    else
        upp = swathe(1,:);
        low = swathe(2,:);
    end
end

% Create the x axis
xaxis = 1:nobs;

%% PLOT
% Initialize patch
edgeColor = colrgb+(1-colrgb)*0.55;
patchSaturation = 0.15; %How de-saturated or transp to make the patch
if strcmp(transp,'transparent')==1
    faceAlpha = patchSaturation;
    patchColor = colrgb;
    set(gcf,'renderer','openGL')
else
    faceAlpha = 1;
    patchColor = colrgb+(1-colrgb)*(1-patchSaturation);
    set(gcf,'renderer','painters')
end

% Plot the 'bar' line
if swatheonly==0
    H.bar = plot(xaxis,bar,'LineWidth',2,'Color',colrgb);
end

%Add the error-bar plot elements
holdStatus = ishold;
if ~holdStatus, hold on,  end

% Make the cordinats for the patch
yP = [low,fliplr(upp)];
xP = [xaxis,fliplr(xaxis)];

% Remove any nans otherwise patch won't work
xP(isnan(yP))=[];
yP(isnan(yP))=[];
H.patch=patch(xP,yP,1,'facecolor',patchColor,'edgecolor','none','facealpha',faceAlpha);

%Make nice edges around the patch.
H.swathe(1)=plot(xaxis,low,'-','color',edgeColor);
H.swathe(2)=plot(xaxis,upp,'-','color',edgeColor);
if swatheonly==0
    delete(H.bar)
end
if swatheonly==0
    H.bar=plot(xaxis,bar,'LineWidth',2,'Color',colrgb);
end
if ~holdStatus, hold off, end

% Make smart x labels
if do_dates==1
    DatesPlot(fo,nobs,nticks,frequency)
end
H.ax = gca;


function deri = deri_softmax(deri_cost)
    global config;
    deri = deri_cost / config.batch_size;
end