function [A, W] = fpica(X, whiteningMatrix, dewhiteningMatrix, approach, ...
    numOfIC, g, finetune, a1, a2, myy, stabilization, ...
    epsilon, maxNumIterations, maxFinetune, initState, ...
    guess, sampleSize, displayMode, displayInterval, ...
    s_verbose);
%FPICA - Fixed point ICA. Main algorithm of FASTICA.
%
% [A, W] = fpica(whitesig, whiteningMatrix, dewhiteningMatrix, approach,
%        numOfIC, g, finetune, a1, a2, mu, stabilization, epsilon,
%        maxNumIterations, maxFinetune, initState, guess, sampleSize,
%        displayMode, displayInterval, verbose);
%
% Perform independent component analysis using Hyvarinen's fixed point
% algorithm. Outputs an estimate of the mixing matrix A and its inverse W.
%
% whitesig                              :the whitened data as row vectors
% whiteningMatrix                       :can be obtained with function whitenv
% dewhiteningMatrix                     :can be obtained with function whitenv
% approach      [ 'symm' | 'defl' ]     :the approach used (deflation or symmetric)
% numOfIC       [ 0 - Dim of whitesig ] :number of independent components estimated
% g             [ 'pow3' | 'tanh' |     :the nonlinearity used
%                 'gaus' | 'skew' ]
% finetune      [same as g + 'off']     :the nonlinearity used in finetuning.
% a1                                    :parameter for tuning 'tanh'
% a2                                    :parameter for tuning 'gaus'
% mu                                    :step size in stabilized algorithm
% stabilization [ 'on' | 'off' ]        :if mu < 1 then automatically on
% epsilon                               :stopping criterion
% maxNumIterations                      :maximum number of iterations
% maxFinetune                           :maximum number of iteretions for finetuning
% initState     [ 'rand' | 'guess' ]    :initial guess or random initial state. See below
% guess                                 :initial guess for A. Ignored if initState = 'rand'
% sampleSize    [ 0 - 1 ]               :percentage of the samples used in one iteration
% displayMode   [ 'signals' | 'basis' | :plot running estimate
%                 'filters' | 'off' ]
% displayInterval                       :number of iterations we take between plots
% verbose       [ 'on' | 'off' ]        :report progress in text format
%
% EXAMPLE
%       [E, D] = pcamat(vectors);
%       [nv, wm, dwm] = whitenv(vectors, E, D);
%       [A, W] = fpica(nv, wm, dwm);
%
%
% This function is needed by FASTICA and FASTICAG
%
%   See also FASTICA, FASTICAG, WHITENV, PCAMAT

% @(#)$Id: fpica.m,v 1.7 2005/06/16 12:52:55 jarmo Exp $

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Global variable for stopping the ICA calculations from the GUI
global g_FastICA_interrupt;
if isempty(g_FastICA_interrupt)
    clear global g_FastICA_interrupt;
    interruptible = 0;
else
    interruptible = 1;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Default values

if nargin < 3, error('Not enough arguments!'); end
[vectorSize, numSamples] = size(X);
if nargin < 20, s_verbose = 'on'; end
if nargin < 19, displayInterval = 1; end
if nargin < 18, displayMode = 'on'; end
if nargin < 17, sampleSize = 1; end
if nargin < 16, guess = 1; end
if nargin < 15, initState = 'rand'; end
if nargin < 14, maxFinetune = 100; end
if nargin < 13, maxNumIterations = 1000; end
if nargin < 12, epsilon = 0.0001; end
if nargin < 11, stabilization = 'on'; end
if nargin < 10, myy = 1; end
if nargin < 9, a2 = 1; end
if nargin < 8, a1 = 1; end
if nargin < 7, finetune = 'off'; end
if nargin < 6, g = 'pow3'; end
if nargin < 5, numOfIC = vectorSize; end     % vectorSize = Dim
if nargin < 4, approach = 'defl'; end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Checking the data

if ~isreal(X)
    error('Input has an imaginary part.');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Checking the value for verbose

switch lower(s_verbose)
    case 'on'
        b_verbose = 1;
    case 'off'
        b_verbose = 0;
    otherwise
        error(sprintf('Illegal value [ %s ] for parameter: ''verbose''\n', s_verbose));
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Checking the value for approach

switch lower(approach)
    case 'symm'
        approachMode = 1;
    case 'defl'
        approachMode = 2;
    otherwise
        error(sprintf('Illegal value [ %s ] for parameter: ''approach''\n', approach));
end
if b_verbose, fprintf('Used approach [ %s ].\n', approach); end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Checking the value for numOfIC

if vectorSize < numOfIC
    error('Must have numOfIC <= Dimension!');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Checking the sampleSize
if sampleSize > 1
    sampleSize = 1;
    if b_verbose
        fprintf('Warning: Setting ''sampleSize'' to 1.\n');
    end
elseif sampleSize < 1
    if (sampleSize * numSamples) < 1000
        sampleSize = min(1000/numSamples, 1);
        if b_verbose
            fprintf('Warning: Setting ''sampleSize'' to %0.3f (%d samples).\n', ...
                sampleSize, floor(sampleSize * numSamples));
        end
    end
end
if b_verbose
    if  b_verbose & (sampleSize < 1)
        fprintf('Using about %0.0f%% of the samples in random order in every step.\n',sampleSize*100);
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Checking the value for nonlinearity.

switch lower(g)
    case 'pow3'
        gOrig = 10;
    case 'tanh'
        gOrig = 20;
    case {'gaus', 'gauss'}
        gOrig = 30;
    case 'skew'
        gOrig = 40;
    otherwise
        error(sprintf('Illegal value [ %s ] for parameter: ''g''\n', g));
end
if sampleSize ~= 1
    gOrig = gOrig + 2;
end
if myy ~= 1
    gOrig = gOrig + 1;
end

if b_verbose,
    fprintf('Used nonlinearity [ %s ].\n', g);
end

finetuningEnabled = 1;
switch lower(finetune)
    case 'pow3'
        gFine = 10 + 1;
    case 'tanh'
        gFine = 20 + 1;
    case {'gaus', 'gauss'}
        gFine = 30 + 1;
    case 'skew'
        gFine = 40 + 1;
    case 'off'
        if myy ~= 1
            gFine = gOrig;
        else
            gFine = gOrig + 1;
        end
        finetuningEnabled = 0;
    otherwise
        error(sprintf('Illegal value [ %s ] for parameter: ''finetune''\n', ...
            finetune));
end

if b_verbose & finetuningEnabled
    fprintf('Finetuning enabled (nonlinearity: [ %s ]).\n', finetune);
end

switch lower(stabilization)
    case 'on'
        stabilizationEnabled = 1;
    case 'off'
        if myy ~= 1
            stabilizationEnabled = 1;
        else
            stabilizationEnabled = 0;
        end
    otherwise
        error(sprintf('Illegal value [ %s ] for parameter: ''stabilization''\n', ...
            stabilization));
end

if b_verbose & stabilizationEnabled
    fprintf('Using stabilized algorithm.\n');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Some other parameters
myyOrig = myy;
% When we start fine-tuning we'll set myy = myyK * myy
myyK = 0.01;
% How many times do we try for convergence until we give up.
failureLimit = 5;

usedNlinearity = gOrig;
stroke = 0;
notFine = 1;
long = 0;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Checking the value for initial state.

switch lower(initState)
    case 'rand'
        initialStateMode = 0;
    case 'guess'
        if size(guess,1) ~= size(whiteningMatrix,2)
            initialStateMode = 0;
            if b_verbose
                fprintf('Warning: size of initial guess is incorrect. Using random initial guess.\n');
            end
        else
            initialStateMode = 1;
            if size(guess,2) < numOfIC
                if b_verbose
                    fprintf('Warning: initial guess only for first %d components. Using random initial guess for others.\n', size(guess,2));
                end
                guess(:, size(guess, 2) + 1:numOfIC) = ...
                    rand(vectorSize,numOfIC-size(guess,2))-.5;
            elseif size(guess,2)>numOfIC
                guess=guess(:,1:numOfIC);
                fprintf('Warning: Initial guess too large. The excess column are dropped.\n');
            end
            if b_verbose, fprintf('Using initial guess.\n'); end
        end
    otherwise
        error(sprintf('Illegal value [ %s ] for parameter: ''initState''\n', initState));
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Checking the value for display mode.

switch lower(displayMode)
    case {'off', 'none'}
        usedDisplay = 0;
    case {'on', 'signals'}
        usedDisplay = 1;
        if (b_verbose & (numSamples > 10000))
            fprintf('Warning: Data vectors are very long. Plotting may take long time.\n');
        end
        if (b_verbose & (numOfIC > 25))
            fprintf('Warning: There are too many signals to plot. Plot may not look good.\n');
        end
    case 'basis'
        usedDisplay = 2;
        if (b_verbose & (numOfIC > 25))
            fprintf('Warning: There are too many signals to plot. Plot may not look good.\n');
        end
    case 'filters'
        usedDisplay = 3;
        if (b_verbose & (vectorSize > 25))
            fprintf('Warning: There are too many signals to plot. Plot may not look good.\n');
        end
    otherwise
        error(sprintf('Illegal value [ %s ] for parameter: ''displayMode''\n', displayMode));
end

% The displayInterval can't be less than 1...
if displayInterval < 1
    displayInterval = 1;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if b_verbose, fprintf('Starting ICA calculation...\n'); end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SYMMETRIC APPROACH
if approachMode == 1,

    % set some parameters more...
    usedNlinearity = gOrig;
    stroke = 0;
    notFine = 1;
    long = 0;

    A = zeros(vectorSize, numOfIC);  % Dewhitened basis vectors.
    if initialStateMode == 0
        % Take random orthonormal initial vectors.
        B = orth (randn (vectorSize, numOfIC));
    elseif initialStateMode == 1
        % Use the given initial vector as the initial state
        B = whiteningMatrix * guess;
    end

    BOld = zeros(size(B));
    BOld2 = zeros(size(B));

    % This is the actual fixed-point iteration loop.
    for round = 1:maxNumIterations + 1,
        if round == maxNumIterations + 1,
            fprintf('No convergence after %d steps\n', maxNumIterations);
            fprintf('Note that the plots are probably wrong.\n');
            if ~isempty(B)
                % Symmetric orthogonalization.
                B = B * real(inv(B' * B)^(1/2));

                W = B' * whiteningMatrix;
                A = dewhiteningMatrix * B;
            else
                W = [];
                A = [];
            end
            return;
        end

        if (interruptible & g_FastICA_interrupt)
            if b_verbose
                fprintf('\n\nCalculation interrupted by the user\n');
            end
            if ~isempty(B)
                W = B' * whiteningMatrix;
                A = dewhiteningMatrix * B;
            else
                W = [];
                A = [];
            end
            return;
        end

        % Symmetric orthogonalization.
        B = B * real(inv(B' * B)^(1/2));

        % Test for termination condition. Note that we consider opposite
        % directions here as well.
        minAbsCos = min(abs(diag(B' * BOld)));
        minAbsCos2 = min(abs(diag(B' * BOld2)));

        if (1 - minAbsCos < epsilon)
            if finetuningEnabled & notFine
                if b_verbose, fprintf('Initial convergence, fine-tuning: \n'); end;
                notFine = 0;
                usedNlinearity = gFine;
                myy = myyK * myyOrig;
                BOld = zeros(size(B));
                BOld2 = zeros(size(B));

            else
                if b_verbose, fprintf('Convergence after %d steps\n', round); end

                % Calculate the de-whitened vectors.
                A = dewhiteningMatrix * B;
                break;
            end
        elseif stabilizationEnabled
            if (~stroke) & (1 - minAbsCos2 < epsilon)
                if b_verbose, fprintf('Stroke!\n'); end;
                stroke = myy;
                myy = .5*myy;
                if mod(usedNlinearity,2) == 0
                    usedNlinearity = usedNlinearity + 1;
                end
            elseif stroke
                myy = stroke;
                stroke = 0;
                if (myy == 1) & (mod(usedNlinearity,2) ~= 0)
                    usedNlinearity = usedNlinearity - 1;
                end
            elseif (~long) & (round>maxNumIterations/2)
                if b_verbose, fprintf('Taking long (reducing step size)\n'); end;
                long = 1;
                myy = .5*myy;
                if mod(usedNlinearity,2) == 0
                    usedNlinearity = usedNlinearity + 1;
                end
            end
        end

        BOld2 = BOld;
        BOld = B;

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % Show the progress...
        if b_verbose
            if round == 1
                fprintf('Step no. %d\n', round);
            else
                fprintf('Step no. %d, change in value of estimate: %.3g \n', round, 1 - minAbsCos);
            end
        end

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % Also plot the current state...
        switch usedDisplay
            case 1
                if rem(round, displayInterval) == 0,
                    % There was and may still be other displaymodes...
                    % 1D signals
                    icaplot('dispsig',(X'*B)');
                    drawnow;
                end
            case 2
                if rem(round, displayInterval) == 0,
                    % ... and now there are :-)
                    % 1D basis
                    A = dewhiteningMatrix * B;
                    icaplot('dispsig',A');
                    drawnow;
                end
            case 3
                if rem(round, displayInterval) == 0,
                    % ... and now there are :-)
                    % 1D filters
                    W = B' * whiteningMatrix;
                    icaplot('dispsig',W);
                    drawnow;
                end
            otherwise
        end

        switch usedNlinearity
            % pow3
            case 10
                B = (X * (( X' * B) .^ 3)) / numSamples - 3 * B;
            case 11
                % optimoitu - epsilonin kokoisia eroja
                % t�m� on optimoitu koodi, katso vanha koodi esim.
                % aikaisemmista versioista kuten 2.0 beta3
                Y = X' * B;
                Gpow3 = Y .^ 3;
                Beta = sum(Y .* Gpow3);
                D = diag(1 ./ (Beta - 3 * numSamples));
                B = B + myy * B * (Y' * Gpow3 - diag(Beta)) * D;
            case 12
                Xsub=X(:, getSamples(numSamples, sampleSize));
                B = (Xsub * (( Xsub' * B) .^ 3)) / size(Xsub,2) - 3 * B;
            case 13
                % Optimoitu
                Ysub=X(:, getSamples(numSamples, sampleSize))' * B;
                Gpow3 = Ysub .^ 3;
                Beta = sum(Ysub .* Gpow3);
                D = diag(1 ./ (Beta - 3 * size(Ysub', 2)));
                B = B + myy * B * (Ysub' * Gpow3 - diag(Beta)) * D;

                % tanh
            case 20
                hypTan = tanh(a1 * X' * B);
                B = X * hypTan / numSamples - ...
                    ones(size(B,1),1) * sum(1 - hypTan .^ 2) .* B / numSamples * ...
                    a1;
            case 21
                % optimoitu - epsilonin kokoisia
                Y = X' * B;
                hypTan = tanh(a1 * Y);
                Beta = sum(Y .* hypTan);
                D = diag(1 ./ (Beta - a1 * sum(1 - hypTan .^ 2)));
                B = B + myy * B * (Y' * hypTan - diag(Beta)) * D;
            case 22
                Xsub=X(:, getSamples(numSamples, sampleSize));
                hypTan = tanh(a1 * Xsub' * B);
                B = Xsub * hypTan / size(Xsub, 2) - ...
                    ones(size(B,1),1) * sum(1 - hypTan .^ 2) .* B / size(Xsub, 2) * a1;
            case 23
                % Optimoitu
                Y = X(:, getSamples(numSamples, sampleSize))' * B;
                hypTan = tanh(a1 * Y);
                Beta = sum(Y .* hypTan);
                D = diag(1 ./ (Beta - a1 * sum(1 - hypTan .^ 2)));
                B = B + myy * B * (Y' * hypTan - diag(Beta)) * D;

                % gauss
            case 30
                U = X' * B;
                Usquared=U .^ 2;
                ex = exp(-a2 * Usquared / 2);
                gauss =  U .* ex;
                dGauss = (1 - a2 * Usquared) .*ex;
                B = X * gauss / numSamples - ...
                    ones(size(B,1),1) * sum(dGauss)...
                    .* B / numSamples ;
            case 31
                % optimoitu
                Y = X' * B;
                ex = exp(-a2 * (Y .^ 2) / 2);
                gauss = Y .* ex;
                Beta = sum(Y .* gauss);
                D = diag(1 ./ (Beta - sum((1 - a2 * (Y .^ 2)) .* ex)));
                B = B + myy * B * (Y' * gauss - diag(Beta)) * D;
            case 32
                Xsub=X(:, getSamples(numSamples, sampleSize));
                U = Xsub' * B;
                Usquared=U .^ 2;
                ex = exp(-a2 * Usquared / 2);
                gauss =  U .* ex;
                dGauss = (1 - a2 * Usquared) .*ex;
                B = Xsub * gauss / size(Xsub,2) - ...
                    ones(size(B,1),1) * sum(dGauss)...
                    .* B / size(Xsub,2) ;
            case 33
                % Optimoitu
                Y = X(:, getSamples(numSamples, sampleSize))' * B;
                ex = exp(-a2 * (Y .^ 2) / 2);
                gauss = Y .* ex;
                Beta = sum(Y .* gauss);
                D = diag(1 ./ (Beta - sum((1 - a2 * (Y .^ 2)) .* ex)));
                B = B + myy * B * (Y' * gauss - diag(Beta)) * D;

                % skew
            case 40
                B = (X * ((X' * B) .^ 2)) / numSamples;
            case 41
                % Optimoitu
                Y = X' * B;
                Gskew = Y .^ 2;
                Beta = sum(Y .* Gskew);
                D = diag(1 ./ (Beta));
                B = B + myy * B * (Y' * Gskew - diag(Beta)) * D;
            case 42
                Xsub=X(:, getSamples(numSamples, sampleSize));
                B = (Xsub * ((Xsub' * B) .^ 2)) / size(Xsub,2);
            case 43
                % Uusi optimoitu
                Y = X(:, getSamples(numSamples, sampleSize))' * B;
                Gskew = Y .^ 2;
                Beta = sum(Y .* Gskew);
                D = diag(1 ./ (Beta));
                B = B + myy * B * (Y' * Gskew - diag(Beta)) * D;

            otherwise
                error('Code for desired nonlinearity not found!');
        end
    end

    % Calculate ICA filters.
    W = B' * whiteningMatrix;

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Also plot the last one...
    switch usedDisplay
        case 1
            % There was and may still be other displaymodes...
            % 1D signals
            icaplot('dispsig',(X'*B)');
            drawnow;
        case 2
            % ... and now there are :-)
            % 1D basis
            icaplot('dispsig',A');
            drawnow;
        case 3
            % ... and now there are :-)
            % 1D filters
            icaplot('dispsig',W);
            drawnow;
        otherwise
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DEFLATION APPROACH
if approachMode == 2

    B = zeros(vectorSize);

    % The search for a basis vector is repeated numOfIC times.
    round = 1;

    numFailures = 0;

    while round <= numOfIC,
        myy = myyOrig;
        usedNlinearity = gOrig;
        stroke = 0;
        notFine = 1;
        long = 0;
        endFinetuning = 0;

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % Show the progress...
        if b_verbose, fprintf('IC %d ', round); end

        % Take a random initial vector of lenght 1 and orthogonalize it
        % with respect to the other vectors.
        if initialStateMode == 0
            w = randn (vectorSize, 1);
        elseif initialStateMode == 1
            w=whiteningMatrix*guess(:,round);
        end
        w = w - B * B' * w; %orthogonalization - B is the previous w
        w = w / norm(w);

        wOld = zeros(size(w));
        wOld2 = zeros(size(w));

        % This is the actual fixed-point iteration loop.
        %    for i = 1 : maxNumIterations + 1
        i = 1;
        gabba = 1;
        while i <= maxNumIterations + gabba
            if (usedDisplay > 0)
                drawnow;
            end
            if (interruptible & g_FastICA_interrupt)
                if b_verbose
                    fprintf('\n\nCalculation interrupted by the user\n');
                end
                return;
            end

            % Project the vector into the space orthogonal to the space
            % spanned by the earlier found basis vectors. Note that we can do
            % the projection with matrix B, since the zero entries do not
            % contribute to the projection.
            w = w - B * B' * w;
            w = w / norm(w);

            if notFine
                if i == maxNumIterations + 1
                    if b_verbose
                        fprintf('\nComponent number %d did not converge in %d iterations.\n', round, maxNumIterations);
                    end
                    round = round - 1;
                    numFailures = numFailures + 1;
                    if numFailures > failureLimit
                        if b_verbose
                            fprintf('Too many failures to converge (%d). Giving up.\n', numFailures);
                        end
                        if round == 0
                            A=[];
                            W=[];
                        end
                        return;
                    end
                    % numFailures > failurelimit
                    break;
                end
                % i == maxNumIterations + 1
            else
                % if notFine
                if i >= endFinetuning
                    wOld = w; % So the algorithm will stop on the next test...
                end
            end
            % if notFine

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            % Show the progress...
            if b_verbose, fprintf('.'); end;

            % Test for termination condition. Note that the algorithm has
            % converged if the direction of w and wOld is the same, this
            % is why we test the two cases.
            if norm(w - wOld) < epsilon | norm(w + wOld) < epsilon
                if finetuningEnabled & notFine
                    if b_verbose, fprintf('Initial convergence, fine-tuning: '); end;
                    notFine = 0;
                    gabba = maxFinetune;
                    wOld = zeros(size(w));
                    wOld2 = zeros(size(w));
                    usedNlinearity = gFine;
                    myy = myyK * myyOrig;

                    endFinetuning = maxFinetune + i;

                else
                    numFailures = 0;
                    % Save the vector
                    B(:, round) = w;

                    % Calculate the de-whitened vector.
                    A(:,round) = dewhiteningMatrix * w;
                    % Calculate ICA filter.
                    W(round,:) = w' * whiteningMatrix;

                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                    % Show the progress...
                    if b_verbose, fprintf('computed ( %d steps ) \n', i); end

                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                    % Also plot the current state...
                    switch usedDisplay
                        case 1
                            if rem(round, displayInterval) == 0,
                                % There was and may still be other displaymodes...
                                % 1D signals
                                temp = X'*B;
                                icaplot('dispsig',temp(:,1:numOfIC)');
                                drawnow;
                            end
                        case 2
                            if rem(round, displayInterval) == 0,
                                % ... and now there are :-)
                                % 1D basis
                                icaplot('dispsig',A');
                                drawnow;
                            end
                        case 3
                            if rem(round, displayInterval) == 0,
                                % ... and now there are :-)
                                % 1D filters
                                icaplot('dispsig',W);
                                drawnow;
                            end
                    end
                    % switch usedDisplay
                    break; % IC ready - next...
                end
                %if finetuningEnabled & notFine
            elseif stabilizationEnabled
                if (~stroke) & (norm(w - wOld2) < epsilon | norm(w + wOld2) < ...
                        epsilon)
                    stroke = myy;
                    if b_verbose, fprintf('Stroke!'); end;
                    myy = .5*myy;
                    if mod(usedNlinearity,2) == 0
                        usedNlinearity = usedNlinearity + 1;
                    end
                elseif stroke
                    myy = stroke;
                    stroke = 0;
                    if (myy == 1) & (mod(usedNlinearity,2) ~= 0)
                        usedNlinearity = usedNlinearity - 1;
                    end
                elseif (notFine) & (~long) & (i > maxNumIterations / 2)
                    if b_verbose, fprintf('Taking long (reducing step size) '); end;
                    long = 1;
                    myy = .5*myy;
                    if mod(usedNlinearity,2) == 0
                        usedNlinearity = usedNlinearity + 1;
                    end
                end
            end

            wOld2 = wOld;
            wOld = w;

            switch usedNlinearity
                % pow3
                case 10
                    w = (X * ((X' * w) .^ 3)) / numSamples - 3 * w;
                case 11
                    EXGpow3 = (X * ((X' * w) .^ 3)) / numSamples;
                    Beta = w' * EXGpow3;
                    w = w - myy * (EXGpow3 - Beta * w) / (3 - Beta);
                case 12
                    Xsub=X(:,getSamples(numSamples, sampleSize));
                    w = (Xsub * ((Xsub' * w) .^ 3)) / size(Xsub, 2) - 3 * w;
                case 13
                    Xsub=X(:,getSamples(numSamples, sampleSize));
                    EXGpow3 = (Xsub * ((Xsub' * w) .^ 3)) / size(Xsub, 2);
                    Beta = w' * EXGpow3;
                    w = w - myy * (EXGpow3 - Beta * w) / (3 - Beta);
                    % tanh
                case 20
                    hypTan = tanh(a1 * X' * w);
                    w = (X * hypTan - a1 * sum(1 - hypTan .^ 2)' * w) / numSamples;
                case 21
                    hypTan = tanh(a1 * X' * w);
                    Beta = w' * X * hypTan;
                    w = w - myy * ((X * hypTan - Beta * w) / ...
                        (a1 * sum((1-hypTan .^2)') - Beta));
                case 22
                    Xsub=X(:,getSamples(numSamples, sampleSize));
                    hypTan = tanh(a1 * Xsub' * w);
                    w = (Xsub * hypTan - a1 * sum(1 - hypTan .^ 2)' * w) / size(Xsub, 2);
                case 23
                    Xsub=X(:,getSamples(numSamples, sampleSize));
                    hypTan = tanh(a1 * Xsub' * w);
                    Beta = w' * Xsub * hypTan;
                    w = w - myy * ((Xsub * hypTan - Beta * w) / ...
                        (a1 * sum((1-hypTan .^2)') - Beta));
                    % gauss
                case 30
                    % This has been split for performance reasons.
                    u = X' * w;
                    u2=u.^2;
                    ex=exp(-a2 * u2/2);
                    gauss =  u.*ex;
                    dGauss = (1 - a2 * u2) .*ex;
                    w = (X * gauss - sum(dGauss)' * w) / numSamples;
                case 31
                    u = X' * w;
                    u2=u.^2;
                    ex=exp(-a2 * u2/2);
                    gauss =  u.*ex;
                    dGauss = (1 - a2 * u2) .*ex;
                    Beta = w' * X * gauss;
                    w = w - myy * ((X * gauss - Beta * w) / ...
                        (sum(dGauss)' - Beta));
                case 32
                    Xsub=X(:,getSamples(numSamples, sampleSize));
                    u = Xsub' * w;
                    u2=u.^2;
                    ex=exp(-a2 * u2/2);
                    gauss =  u.*ex;
                    dGauss = (1 - a2 * u2) .*ex;
                    w = (Xsub * gauss - sum(dGauss)' * w) / size(Xsub, 2);
                case 33
                    Xsub=X(:,getSamples(numSamples, sampleSize));
                    u = Xsub' * w;
                    u2=u.^2;
                    ex=exp(-a2 * u2/2);
                    gauss =  u.*ex;
                    dGauss = (1 - a2 * u2) .*ex;
                    Beta = w' * Xsub * gauss;
                    w = w - myy * ((Xsub * gauss - Beta * w) / ...
                        (sum(dGauss)' - Beta));
                    % skew
                case 40
                    w = (X * ((X' * w) .^ 2)) / numSamples;
                case 41
                    EXGskew = (X * ((X' * w) .^ 2)) / numSamples;
                    Beta = w' * EXGskew;
                    w = w - myy * (EXGskew - Beta*w)/(-Beta);
                case 42
                    Xsub=X(:,getSamples(numSamples, sampleSize));
                    w = (Xsub * ((Xsub' * w) .^ 2)) / size(Xsub, 2);
                case 43
                    Xsub=X(:,getSamples(numSamples, sampleSize));
                    EXGskew = (Xsub * ((Xsub' * w) .^ 2)) / size(Xsub, 2);
                    Beta = w' * EXGskew;
                    w = w - myy * (EXGskew - Beta*w)/(-Beta);

                otherwise
                    error('Code for desired nonlinearity not found!');
            end

% TEST % % % % % % % % % % % % % % % % % % % % % % % % %
interval = 1;
if mod(i,interval)==0
    modifyA =1; %for now...
    nx = 20;
    ny = 20;
    sigfix = 3.7/4; % sig of PSF...

    if exist ('modifyA','var')
        if modifyA == 1
            %                     fprintf ('Modifying matrix conevrgence of w...')
            Atemp = dewhiteningMatrix * w;
%             signum = 1;
%             if abs(min(Atemp))>max(Atemp) %or sum(Atemp)<0...?
%                 signum = -1;
%             end
%             if abs(min(Atemp))>max(Atemp) %or sum(Atemp)<0...?
%                 Atemp = -Atemp;
%             end
            absA = abs(Atemp);
            maxA = max(absA);

            gf = (gauss2d([nx ny],[nx/2,ny/2],sigfix,maxA));
            Aconv = (conv2(gf, reshape (Atemp, nx, ny),'same')).^5;
            Atemp = reshape(Aconv,ny*ny,1);

%             [x_mu, y_mu, sig] = fitgauss2d(reshape(absA, nx, ny),sigfix); %fit to abs...
%             Atemp = (Atemp + signum * reshape(gauss2d([nx ny],[x_mu,y_mu],sig,maxA),nx*ny,1))/2;
            % Atemp = reshape(gauss2d([nx ny],[x_mu,y_mu],sig,maxA),nx*ny,1);
        end
    end
    w = whiteningMatrix*Atemp;
end

% TEST % % % % % % % % % % % % % % % % % % % % % % % % %

% %%% TEST version old %%%%%%%%%
% if mod(i,5)==0
%     modifyA =1; %for now...
%     nx = 20;
%     ny = 20;
%     sigfix = 3.7/4; % sig of PSF...
%
%     if exist ('modifyA','var')
%         if modifyA == 1
%             %                     fprintf ('Modifying matrix conevrgence of w...')
%             Atemp = dewhiteningMatrix * w;
%             if abs(min(Atemp))>max(Atemp) %or sum(Atemp)<0...?
%                 Atemp = -Atemp;
%             end
%             [x_mu, y_mu, sig] = fitgauss2d(reshape(Atemp, nx, ny),sigfix);
%             maxA = max(abs(Atemp));
%             Atemp = (Atemp + reshape(gauss2d([nx ny],[x_mu,y_mu],sig,maxA),nx*ny,1))/2;
%             % Atemp = reshape(gauss2d([nx ny],[x_mu,y_mu],sig,maxA),nx*ny,1);
%         end
%     end
%     w = whiteningMatrix*Atemp;
%
% %%% TEST version old %%%%%%%%%

% Normalize the new w.
            w = w / norm(w);
            i = i + 1;
        end
        round = round + 1;
    end
    if b_verbose, fprintf('Done.\n'); end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Also plot the ones that may not have been plotted.
    if (usedDisplay > 0) & (rem(round-1, displayInterval) ~= 0)
        switch usedDisplay
            case 1
                % There was and may still be other displaymodes...
                % 1D signals
                temp = X'*B;
                icaplot('dispsig',temp(:,1:numOfIC)');
                drawnow;
            case 2
                % ... and now there are :-)
                % 1D basis
                icaplot('dispsig',A');
                drawnow;
            case 3
                % ... and now there are :-)
                % 1D filters
                icaplot('dispsig',W);
                drawnow;
            otherwise
        end
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% In the end let's check the data for some security
if ~isreal(A)
    if b_verbose, fprintf('Warning: removing the imaginary part from the result.\n'); end
    A = real(A);
    W = real(W);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Subfunction
% Calculates tanh simplier and faster than Matlab tanh.
function y=tanh(x)
y = 1 - 2 ./ (exp(2 * x) + 1);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Samples = getSamples(max, percentage)
Samples = find(rand(1, max) < percentage);


function m = gpComputeM(model)

% GPCOMPUTEM Compute the matrix m given the model.
% FORMAT
% DESC computes the matrix m (the scaled, bias and mean function
% removed matrix of the targets), given the model.
% ARG model : the model for which the values are to be computed.
% RETURN m : the scaled, bias and mean function removed values.
%
% SEEALSO : gpCreate, gpComputeAlpha, gpUpdateAD
%
% COPYRIGHT : Neil D. Lawrence, 2006

% GP

% Remove mean function value from m (if mean function present).
if isfield(model, 'meanFunction') && ~isempty(model.meanFunction)
  m = model.y - modelOut(model.meanFunction, model.X);
else
  m = model.y;
end

% Remove bias and apply scale.
for i = 1:model.d
  m(:, i) = m(:, i) - model.bias(i);
  if model.scale(i)
    m(:, i) = m(:, i)/model.scale(i);
  end
end


function inputs = getBatch_LapSRN(opts, imdb, batch, mode)
% -------------------------------------------------------------------------
%   Description:
%       get one batch for training LapSRN
%
%   Input:
%       - opts  : options generated from init_opts()
%       - imdb  : imdb file generated from make_imdb()
%       - batch : array of ID to fetch
%       - mode  : 'train' or 'val'
%
%   Output:
%       - inputs: input for dagnn (include LR and HR images)
%
%   Citation:
%       Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution
%       Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang
%       IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017
%
%   Contact:
%       Wei-Sheng Lai
%       wlai24@ucmerced.edu
%       University of California, Merced
% -------------------------------------------------------------------------

    %% get images
    image_batch = imdb.images.img(batch);

    %% crop patches
    HR = zeros(opts.patch_size, opts.patch_size, 1, length(batch), 'single');

    for i = 1:length(batch)

        img = image_batch{i};

        ratio = 1;

        if( opts.scale_augmentation && strcmp(mode, 'train') )
            % randomly resize between 0.5 ~ 1.0
            ratio = randi([5, 10]) * 0.1;

        end

        eps = 1e-3;

        % min width/height should be larger than patch size
        if size(img, 1) < size(img, 2)
            if size(img, 1) * ratio < opts.patch_size
                ratio = opts.patch_size / size(img, 1) + eps;
            end
        else
            if size(img, 2) * ratio < opts.patch_size
                ratio = opts.patch_size / size(img, 2) + eps;
            end
        end

        img = imresize(img, ratio);

        % random crop
        H = size(img, 1);
        W = size(img, 2);

        y = randi(H - opts.patch_size + 1);
        x = randi(W - opts.patch_size + 1);
        HR(:, :, :, i) = img(y : y + opts.patch_size - 1, x : x + opts.patch_size - 1, :);

    end

    %% data augmentation
    if( opts.data_augmentation && strcmp(mode, 'train') )

        % rotate
        rotate = rand;
        if( rotate < 0.25 )
            HR = rot90(HR, 1);
        elseif( rotate < 0.5 )
            HR = rot90(HR, 2);
        elseif( rotate < 0.75 )
            HR = rot90(HR, 3);
        end

        % horizontally flip
        if( rand > 0.5 )
            HR = fliplr(HR);
        end

    end % end of data augmentation

    %% dagnn input
    inputs = {};
    inputs{end+1} = 'level1_HR';
	inputs{end+1} = HR;

    for i = 2 : opts.level
        ratio = 1 / 2^(i - 1);
        inputs{end+1} = sprintf('level%d_HR', i);
        inputs{end+1} = imresize(HR, ratio);
    end

    inputs{end+1} = 'LR';
	inputs{end+1} = imresize(HR, 1 / opts.scale);

    %% convert to GPU array
    if( opts.gpu > 0 )
        for i = 2:2:length(inputs)
            inputs{i} = gpuArray(inputs{i});
        end
    end

end


function t_auction_minopf(quiet)
%T_AUCTION_MINOPF  Tests for code in auction.m, using MINOPF solver.

%   MATPOWER
%   Copyright (c) 2004-2016, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

if nargin < 1
    quiet = 0;
end

n_tests = 183;

t_begin(n_tests, quiet);

[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...
    VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;
[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...
    MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...
    QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;

if ~have_feature('smartmarket')
    t_skip(n_tests, 'smartmarket code not available');
elseif ~have_feature('minopf')
    t_skip(n_tests, 't_auction_minopf requires MINOPF');
else
    mpopt = mpoption('opf.ac.solver', 'MINOPF', 'out.lim.all', 1, 'out.branch', 0, 'out.sys_sum', 0, 'out.all', 0, 'verbose', 0);
    q = [
        12 24 24;
        12 24 24;
        12 24 24;
        12 24 24;
        12 24 24;
        12 24 24;
        10 10 10;
        10 10 10;
        10 10 10;
    ];

    %%-----  one offer block marginal @ $50  -----
    p = [
        20 50 60;
        20 40 70;
        20 42 80;
        20 44 90;
        20 46 75;
        20 48 60;
        100 70 60;
        100 50 20;
        100 60 50;
    ];

    t = 'one marginal offer @ $50, auction_type = 5';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1150, 100, [], [], mpopt);
    cq5 = cq;
    cp5 = cp;
    i2e = bus(:, BUS_I);
    e2i = sparse(max(i2e), 1);
    e2i(i2e) = (1:size(bus, 1))';
    G = find( ~isload(gen) );   %% real generators
    L = find(  isload(gen) );   %% dispatchable loads
    Gbus = e2i(gen(G,GEN_BUS));
    Lbus = e2i(gen(L,GEN_BUS));
    Qfudge =  zeros(size(p));
    Qfudge(L,:) = diag(gen(L,QG) ./ gen(L,PG) .* bus(Lbus, LAM_Q)) * ones(size(p(L,:)));

    t_is( cq(G(1),2:3), [23.32 0], 2, t );
    t_is( cp(G(1),:), 50, 4, t );
    t_is( cq(L(2),1:2), [10 0], 2, t );
    t_is( cp(L(2),:), 54.0312, 4, t );
    t_is( cp(G,1), bus(Gbus, LAM_P), 8, [t ' : gen prices'] );
    t_is( cp(L,1), bus(Lbus, LAM_P) + Qfudge(L,1), 8, [t ' : load prices'] );

    lao_X = p(G(1),2)/bus(Gbus(1), LAM_P);
    fro_X = p(G(6),3)/bus(Gbus(6), LAM_P);
    lab_X = p(L(3),2)/(bus(Lbus(3), LAM_P) + Qfudge(L(3),1));
    frb_X = p(L(2),2)/(bus(Lbus(2), LAM_P) + Qfudge(L(2),1));

    t_is( lao_X, 1, 4, 'lao_X');
    t_is( fro_X, 1.1324, 4, 'fro_X');
    t_is( lab_X, 1.0787, 4, 'lab_X');
    t_is( frb_X, 0.9254, 4, 'frb_X');

    t = 'one marginal offer @ $50, auction_type = 1';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1110, 100, [], [], mpopt);
    cp1 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp5, 8, [t ' : prices'] );

    t = 'one marginal offer @ $50, auction_type = 2';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1120, 100, [], [], mpopt);
    cp2 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G,:), cp5(G,:)*fro_X, 8, [t ' : gen prices'] );
    t_is( cp(L(1:2),:), cp5(L(1:2),:)*fro_X, 8, [t ' : load 1,2 prices'] );
    t_is( cp(L(3),:), 60, 5, [t ' : load 3 price'] );   %% clipped by accepted bid

    t = 'one marginal offer @ $50, auction_type = 3';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1130, 100, [], [], mpopt);
    cp3 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp5*lab_X, 8, [t ' : prices'] );

    t = 'one marginal offer @ $50, auction_type = 4';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1140, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G(1),:), p(G(1),2), 8, [t ' : gen 1 price'] );
    t_is( cp(G(2:6),:), cp5(G(2:6),:)*frb_X, 8, [t ' : gen 2-6 prices'] );
    t_is( cp(L,:), cp5(L,:)*frb_X, 8, [t ' : load prices'] );

    t = 'one marginal offer @ $50, auction_type = 6';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1160, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp3, 8, [t ' : prices'] );
    p2 = p;
    p2(L,:) = [ 100 100 100;
                100   0   0;
                100 100   0 ];
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1160, 100, [], [], mpopt);
    t_is( cq, cq5, 5, [t ' : quantities'] );
    t_is( cp(G,:), cp5(G,:)*fro_X, 4, [t ' : gen prices'] );
    t_is( cp(L,:), cp5(L,:)*fro_X, 4, [t ' : load prices'] ); %% load 3 not clipped as in FRO

    t = 'one marginal offer @ $50, auction_type = 7';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1170, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp5 * (lao_X+lab_X)/2, 8, [t ' : prices'] );
    t_is( cp, (cp1 + cp3) / 2, 8, [t ' : prices'] );

    t = 'one marginal offer @ $50, auction_type = 8';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1180, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G,:), cp1(G,:), 8, [t ' : gen prices'] );
    t_is( cp(L,:), cp3(L,:), 8, [t ' : load prices'] );

    t = 'one marginal offer @ $50, auction_type = 0';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1100, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, p, 8, [t ' : prices'] );

    %%-----  one bid block marginal @ $55  -----
    p(L(2),2) = 55;
    t = 'one marginal bid @ $55, auction_type = 5';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1150, 100, [], [], mpopt);
    cq5 = cq;
    cp5 = cp;
    Qfudge =  zeros(size(p));
    Qfudge(L,:) = diag(gen(L,QG) ./ gen(L,PG) .* bus(Lbus, LAM_Q)) * ones(size(p(L,:)));

    t_is( cq(G(1),2:3), [24 0], 2, t );
    t_is( cp(G(1),:), 50.016, 3, t );
    t_is( cq(L(2),1:2), [10 0.63], 2, t );
    t_is( cp(L(2),:), 55, 4, t );
    t_is( cp(G,1), bus(Gbus, LAM_P), 8, [t ' : gen prices'] );
    t_is( cp(L,1), bus(Lbus, LAM_P) + Qfudge(L,1), 8, [t ' : load prices'] );

    lao_X = p(G(1),2)/bus(Gbus(1), LAM_P);
    fro_X = p(G(6),3)/bus(Gbus(6), LAM_P);
    lab_X = p(L(2),2)/(bus(Lbus(2), LAM_P) + Qfudge(L(2),1));
    frb_X = p(L(3),3)/(bus(Lbus(3), LAM_P) + Qfudge(L(3),1));

    t_is( lao_X, 0.9997, 4, 'lao_X');
    t_is( fro_X, 1.1111, 4, 'fro_X');
    t_is( lab_X, 1, 4, 'lab_X');
    t_is( frb_X, 0.8960, 4, 'frb_X');

    t = 'one marginal bid @ $55, auction_type = 1';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1110, 100, [], [], mpopt);
    cp1 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp5*lao_X, 8, [t ' : prices'] );

    t = 'one marginal bid @ $55, auction_type = 2';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1120, 100, [], [], mpopt);
    cp2 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G,:), cp5(G,:)*fro_X, 8, [t ' : gen prices'] );
    t_is( cp(L(1),:), cp5(L(1),:)*fro_X, 8, [t ' : load 1 price'] );
    t_is( cp(L(2),:), 55, 5, [t ' : load 2 price'] );
    t_is( cp(L(3),:), 60, 5, [t ' : load 3 price'] );

    t = 'one marginal bid @ $55, auction_type = 3';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1130, 100, [], [], mpopt);
    cp3 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp5, 8, [t ' : prices'] );

    t = 'one marginal bid @ $55, auction_type = 4';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1140, 100, [], [], mpopt);
    cp4 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G(1),:), 50, 5, [t ' : gen 1 price'] );
    t_is( cp(G(2:6),:), cp5(G(2:6),:)*frb_X, 8, [t ' : gen 2-6 prices'] );
    t_is( cp(L,:), cp5(L,:)*frb_X, 8, [t ' : load prices'] );

    t = 'one marginal bid @ $55, auction_type = 6';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1160, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp1, 8, [t ' : prices'] );

    p2 = p;
    p2(G,:) = [ 0 0 100;
                0 0 100;
                0 0 100;
                0 0 100;
                0 0 100;
                0 0 100 ];
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1160, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G,:), cp5(G,:)*frb_X, 4, [t ' : gen prices'] );  %% gen 1, not clipped this time
    t_is( cp(L,:), cp4(L,:), 4, [t ' : load prices'] );

    t = 'one marginal bid @ $55, auction_type = 7';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1170, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp5 * (lao_X+lab_X)/2, 8, [t ' : prices'] );
    t_is( cp, (cp1 + cp3) / 2, 8, [t ' : prices'] );

    t = 'one marginal bid @ $55, auction_type = 8';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1180, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G,:), cp1(G,:), 8, [t ' : gen prices'] );
    t_is( cp(L,:), cp3(L,:), 8, [t ' : load prices'] );

    t = 'one marginal bid @ $55, auction_type = 0';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1100, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, p, 8, [t ' : prices'] );

    %%-----  one bid block marginal @ $54.50 and one offer block marginal @ $50  -----
    p(L(2),2) = 54.5;
    t = 'marginal offer @ $50, bid @ $54.50, auction_type = 5';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1150, 100, [], [], mpopt);
    cq5 = cq;
    cp5 = cp;
    Qfudge =  zeros(size(p));
    Qfudge(L,:) = diag(gen(L,QG) ./ gen(L,PG) .* bus(Lbus, LAM_Q)) * ones(size(p(L,:)));

    t_is( cq(G(1),2:3), [23.74 0], 2, t );
    t_is( cp(G(1),:), 50, 4, t );
    t_is( cq(L(2),1:2), [10 0.39], 2, t );
    t_is( cp(L(2),:), 54.5, 4, t );
    t_is( cp(G,1), bus(Gbus, LAM_P), 8, [t ' : gen prices'] );
    t_is( cp(L,1), bus(Lbus, LAM_P) + Qfudge(L,1), 8, [t ' : load prices'] );

    lao_X = p(G(1),2)/bus(Gbus(1), LAM_P);
    fro_X = p(G(6),3)/bus(Gbus(6), LAM_P);
    lab_X = p(L(2),2)/(bus(Lbus(2), LAM_P) + Qfudge(L(2),1));
    frb_X = p(L(3),3)/(bus(Lbus(3), LAM_P) + Qfudge(L(3),1));

    t_is( lao_X, 1, 4, 'lao_X');
    t_is( fro_X, 1.1221, 4, 'fro_X');
    t_is( lab_X, 1, 4, 'lab_X');
    t_is( frb_X, 0.8976, 4, 'frb_X');

    t = 'marginal offer @ $50, bid @ $54.50, auction_type = 1';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1110, 100, [], [], mpopt);
    cp1 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp5, 4, [t ' : prices'] );

    t = 'marginal offer @ $50, bid @ $54.50, auction_type = 2';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1120, 100, [], [], mpopt);
    cp2 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G,:), cp5(G,:)*fro_X, 5, [t ' : gen prices'] );
    t_is( cp(L(1),:), cp5(L(1),:)*fro_X, 5, [t ' : load 1 price'] );
    t_is( cp(L(2),:), 54.5, 5, [t ' : load 2 price'] );
    t_is( cp(L(3),:), 60, 5, [t ' : load 3 price'] );

    t = 'marginal offer @ $50, bid @ $54.50, auction_type = 3';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1130, 100, [], [], mpopt);
    cp3 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp5, 8, [t ' : prices'] );

    t = 'marginal offer @ $50, bid @ $54.50, auction_type = 4';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1140, 100, [], [], mpopt);
    cp4 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G(1),:), 50, 5, [t ' : gen 1 price'] );
    t_is( cp(G(2:5),:), cp5(G(2:5),:)*frb_X, 8, [t ' : gen 2-5 prices'] );
    t_is( cp(G(6),:), 48, 5, [t ' : gen 6 price'] );
    t_is( cp(L,:), cp5(L,:)*frb_X, 8, [t ' : load prices'] );

    t = 'marginal offer @ $50, bid @ $54.50, auction_type = 6';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1160, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp5, 4, [t ' : prices'] );

    t = 'marginal offer @ $50, bid @ $54.50, auction_type = 7';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1170, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp5, 4, [t ' : prices'] );

    t = 'marginal offer @ $50, bid @ $54.50, auction_type = 8';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1180, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp5, 4, [t ' : prices'] );

    t = 'marginal offer @ $50, bid @ $54.50, auction_type = 0';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1100, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, p, 8, [t ' : prices'] );

    %%-----  gen 1 at Pmin, load 3 block 2 marginal @ $60  -----
    t = 'gen 1 @ Pmin, marginal bid @ $60, auction_type = 5';
    p(L(2),2) = 50;     %% undo previous change
    p2 = p;
    p2(G(1),2:3) = [65 65];
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1150, 100, [], [], mpopt);
    Qfudge =  zeros(size(p));
    Qfudge(L,:) = diag(gen(L,QG) ./ gen(L,PG) .* bus(Lbus, LAM_Q)) * ones(size(p(L,:)));

    t_is( cp(G(1),:), 65, 4, [t ' : gen 1 price'] );
    t_is( cp(G(2),:), 54.2976, 4, [t ' : gen 2 price'] );
    cq5 = cq;
    cp5 = cp;
    cp_lam = cp5;
    cp_lam(1,:) = bus(Gbus(1), LAM_P);  %% unclipped

    lao_X = p2(G(6),2)/bus(Gbus(6), LAM_P);
    fro_X = p2(G(6),3)/bus(Gbus(6), LAM_P);
    lab_X = p2(L(3),2)/(bus(Lbus(3), LAM_P) + Qfudge(L(3),1));
    frb_X = p2(L(2),2)/(bus(Lbus(2), LAM_P) + Qfudge(L(2),1));

    t_is( lao_X, 0.8389, 4, 'lao_X');
    t_is( fro_X, 1.0487, 4, 'fro_X');
    t_is( lab_X, 1, 4, 'lab_X');
    t_is( frb_X, 0.8569, 4, 'frb_X');

    t = 'gen 1 @ Pmin, marginal bid @ $60, auction_type = 1';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1110, 100, [], [], mpopt);
    cp1 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G(1),:), 65, 8, [t ' : gen 1 price'] );
    t_is( cp(G(2:6),:), cp_lam(G(2:6),:)*lao_X, 8, [t ' : gen 2-6 prices'] );
    t_is( cp(L,:), cp_lam(L,:)*lao_X, 8, [t ' : load prices'] );

    t = 'gen 1 @ Pmin, marginal bid @ $60, auction_type = 2';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1120, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G(1),:), 65, 8, [t ' : gen 1 price'] );
    t_is( cp(G(2:6),:), cp_lam(G(2:6),:)*fro_X, 8, [t ' : gen 2-6 prices'] );
    t_is( cp(L(1:2),:), cp_lam(L(1:2),:)*fro_X, 8, [t ' : load 1-2 prices'] );
    t_is( cp(L(3),:), 60, 8, [t ' : load 3 price'] );

    t = 'gen 1 @ Pmin, marginal bid @ $60, auction_type = 3';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1130, 100, [], [], mpopt);
    cp3 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G(1),:), 65, 8, [t ' : gen 1 price'] );
    t_is( cp(G(2:6),:), cp_lam(G(2:6),:), 8, [t ' : gen 2-6 prices'] );
    t_is( cp(L,:), cp_lam(L,:), 8, [t ' : load prices'] );

    t = 'gen 1 @ Pmin, marginal bid @ $60, auction_type = 4';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1140, 100, [], [], mpopt);
    cp4 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G(1),:), 65, 5, [t ' : gen 1 price'] );
    t_is( cp(G(2:6),:), cp5(G(2:6),:)*frb_X, 8, [t ' : gen 2-6 prices'] );
    t_is( cp(L,:), cp5(L,:)*frb_X, 8, [t ' : load prices'] );

    t = 'gen 1 @ Pmin, marginal bid @ $60, auction_type = 6';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1160, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp4, 8, [t ' : prices'] );

    t = 'gen 1 @ Pmin, marginal bid @ $60, auction_type = 7';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1170, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G(1),:), 65, 4, [t ' : gen 1 price'] );
    t_is( cp(G(2:6),:), cp_lam(G(2:6),:) * (lao_X+lab_X)/2, 8, [t ' : gen 2-6 prices'] );
    t_is( cp(L,:), cp_lam(L,:) * (lao_X+lab_X)/2, 8, [t ' : load prices'] );
    t_is( cp, (cp1 + cp3) / 2, 8, [t ' : prices'] );

    t = 'gen 1 @ Pmin, marginal bid @ $60, auction_type = 8';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1180, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G,:), cp1(G,:), 8, [t ' : prices'] );
    t_is( cp(L,:), cp3(L,:), 8, [t ' : prices'] );

    t = 'gen 1 @ Pmin, marginal bid @ $60, auction_type = 0';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1100, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, p2, 8, [t ' : prices'] );

    %%-----  gen 1 at Pmin, gen 6 block 3 marginal @ $60  -----
    t = 'gen 1 @ Pmin, marginal offer @ $60, auction_type = 5';
    p2(L,:) = [ 100 100 100;
                100   0   0;
                100 100   0 ];
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1150, 100, [], [], mpopt);
    Qfudge =  zeros(size(p));
    Qfudge(L,:) = diag(gen(L,QG) ./ gen(L,PG) .* bus(Lbus, LAM_Q)) * ones(size(p(L,:)));

    t_is( cp(G(1),:), 65, 4, [t ' : gen 1 price'] );
    t_is( cp(G(2),:), 57.1616, 4, [t ' : gen 2 price'] );
    cq5 = cq;
    cp5 = cp;
    cp_lam = cp5;
    cp_lam(1,:) = bus(Gbus(1), LAM_P);  %% unclipped

    lao_X = p2(G(6),3)/bus(Gbus(6), LAM_P);
    fro_X = p2(G(1),3)/bus(Gbus(1), LAM_P);
    lab_X = p2(L(3),2)/(bus(Lbus(3), LAM_P) + Qfudge(L(3),1));
    frb_X = p2(L(2),2)/(bus(Lbus(2), LAM_P) + Qfudge(L(2),1));

    t_is( lao_X, 1, 4, 'lao_X');
    t_is( fro_X, 1.1425, 4, 'fro_X');
    t_is( lab_X, 1.5813, 4, 'lab_X');
    t_is( frb_X, 0, 4, 'frb_X');

    t = 'gen 1 @ Pmin, marginal offer @ $60, auction_type = 1';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1110, 100, [], [], mpopt);
    cp1 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp5, 8, [t ' : prices'] );

    t = 'gen 1 @ Pmin, marginal offer @ $60, auction_type = 2';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1120, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp_lam*fro_X, 8, [t ' : prices'] );

    t = 'gen 1 @ Pmin, marginal offer @ $60, auction_type = 3';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1130, 100, [], [], mpopt);
    cp3 = cp;
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp_lam*lab_X, 8, [t ' : prices'] );

    t = 'gen 1 @ Pmin, marginal offer @ $60, auction_type = 4';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1140, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G,1), [65;40;42;44;46;60], 4, [t ' : gen prices'] );
    t_is( cp(L,:), cp_lam(L,:)*frb_X, 8, [t ' : prices'] );

    t = 'gen 1 @ Pmin, marginal offer @ $60, auction_type = 6';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1160, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp_lam*fro_X, 8, [t ' : prices'] );

    t = 'gen 1 @ Pmin, marginal offer @ $60, auction_type = 7';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1170, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, cp_lam * (lao_X+lab_X)/2, 8, [t ' : prices'] );
    t_is( cp, (cp_lam + cp3) / 2, 8, [t ' : prices'] );

    t = 'gen 1 @ Pmin, marginal offer @ $60, auction_type = 8';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1180, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp(G,:), cp5(G,:), 8, [t ' : prices'] );
    t_is( cp(L,:), cp3(L,:), 8, [t ' : prices'] );

    t = 'gen 1 @ Pmin, marginal offer @ $60, auction_type = 0';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p2, 1100, 100, [], [], mpopt);
    t_is( cq, cq5, 8, [t ' : quantities'] );
    t_is( cp, p2, 8, [t ' : prices'] );

    %%-----  gen 2 decommitted, one offer block marginal @ $60  -----
    p(G(2),:) = p(G(2),:) + 100;

    t = 'price of decommited gen, auction_type = 5';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1150, 200, [], [], mpopt);
    cp5 = cp;
    Qfudge =  zeros(size(p));
    Qfudge(L,:) = diag(gen(L,QG) ./ gen(L,PG) .* bus(Lbus, LAM_Q)) * ones(size(p(L,:)));
    t_is(sum(cq(2,:)), 0, 8, t);
    t_is(cp(2,1), 59.194, 3, t);

%     Xo = p(1:6, :) ./ (diag(bus(Gbus, LAM_P)) * ones(size(p(G,:))));
%     ao = (cq(1:6, :) ~= 0);
%     ro = (cq(1:6, :) == 0);
%     Xb = p(7:9, :) ./ (diag(bus(Lbus, LAM_P) + gen(L,QG) ./ gen(L,PG) .* bus(Lbus, LAM_Q)) * ones(size(p(L,:))));
%     ab = (cq(7:9, :) ~= 0);
%     rb = (cq(7:9, :) == 0);
%     aXo = ao .* Xo
%     rXo = ro .* Xo
%     aXb = ab .* Xb
%     rXb = rb .* Xb

    lao_X = p(G(6),3)/bus(Gbus(6), LAM_P);
    fro_X = p(G(1),3)/bus(Gbus(1), LAM_P);
    lab_X = p(L(1),2)/(bus(Lbus(1), LAM_P) + Qfudge(L(1),1));
    frb_X = p(L(1),3)/(bus(Lbus(1), LAM_P) + Qfudge(L(1),1));

    t_is( lao_X, 1, 4, 'lao_X');
    t_is( fro_X, 1.0212, 4, 'fro_X');
    t_is( lab_X, 1.1649, 4, 'lab_X');
    t_is( frb_X, 0.9985, 4, 'frb_X');

    t = 'price of decommited gen, auction_type = 1';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1110, 200, [], [], mpopt);
    t_is(cp(2,1), 59.194, 3, t);

    t = 'price of decommited gen, auction_type = 2';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1120, 200, [], [], mpopt);
    t_is(cp(2,1), cp5(2,1)*fro_X, 3, t);

    t = 'price of decommited gen, auction_type = 3';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1130, 200, [], [], mpopt);
    t_is(cp(2,1), cp5(2,1)*lab_X, 3, t);

    t = 'price of decommited gen, auction_type = 4';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1140, 200, [], [], mpopt);
    t_is(cp(2,1), cp5(2,1)*frb_X, 3, t);

    t = 'price of decommited gen, auction_type = 6';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1160, 200, [], [], mpopt);
    t_is(cp(2,1), cp5(2,1)*fro_X, 3, t);

    t = 'price of decommited gen, auction_type = 7';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1170, 200, [], [], mpopt);
    t_is(cp(2,1), cp5(2,1)*(lao_X+lab_X)/2, 3, t);

    t = 'price of decommited gen, auction_type = 0';
    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1100, 200, [], [], mpopt);
    t_is(cp(2,1), 120, 3, t);

    t = 'single block, marginal offer @ $50, auction_type = 5';
    q = [
        60;
        36;
        36;
        36;
        36;
        36;
        30;
        10;
        20;
    ];

    p = [
        50;
        40;
        42;
        44;
        46;
        48;
        100;
        100;
        100;
    ];

    [MVAbase, cq, cp, bus, gen, gencost, branch, f, dispatch, success, et] = ...
        runmkt('t_auction_case', q, p, 1150, 100, [], [], mpopt);
    t_is( cq(G(1)), 35.32, 2, t );
    t_is( cq(G(2:6)), q(G(2:6)), 8, [t ' : gen qtys'] );
    t_is( cp(G(1)), 50, 4, t );
    t_is( cq(L), q(L), 8, [t ' : load qtys'] );
    t_is( cp(L(2),:), 54.03, 2, t );
    t_is( cp(G), bus(Gbus, LAM_P), 8, [t ' : gen prices'] );
    Qfudge =  zeros(size(p));
    Qfudge(L,:) = diag(gen(L,QG) ./ gen(L,PG) .* bus(Lbus, LAM_Q)) * ones(size(p(L,:)));
    t_is( cp(L), bus(Lbus, LAM_P) + Qfudge(L,1), 8, [t ' : load prices'] );
end

t_end;


function plotRelaxedFBA(sol, model,tol)

if sol.stat ~= 1
    disp('relaxedFBA did not complete successfully, nothing to display');
    disp('relaxedFBA problem infeasible, check relaxOption fields');
    return
end

if ~exist('tol','var')
    %Set the tolerance to distinguish between zero and non-zero flux
    feasTol = getCobraSolverParams('LP', 'feasTol');
    tol=feasTol*100;
end

%useful for numerical debugging
if 0
    tol=0;
end

optTol = getCobraSolverParams('LP', 'optTol');
sol.p(abs(sol.p)<optTol*10)=0;
sol.q(abs(sol.q)<optTol*10)=0;

if norm(model.S*sol.v-model.b)>optTol*10
    warning(['relaxedFBA relaxed steady state constraints too much, norm(S*v-b)= ' num2str(norm(model.S*sol.v-model.b))])
end

[v,r,p,q] = deal(sol.v,sol.r,sol.p,sol.q);

p(p<tol) = 0;%lower bound relaxation
q(q<tol) = 0;%upper bound relaxation
r(abs(r)<tol) = 0;%steady state constraint relaxation

%Summarise the proposed relaxation sol
printFlag=0;
lineChangeFlag=0;

[nMet,nRxn]=size(model.S);

%totals
fprintf('%u%s\n',nnz(r),' steady state constraints relaxed');
fprintf('%u%s\n',nnz(p & q & model.SIntRxnBool),' internal lower and upper bounds relaxed');
fprintf('%u%s\n',nnz(p & q & ~model.SIntRxnBool),' external lower and upper bounds relaxed');
fprintf('%u%s\n',nnz(p | q & ~model.SIntRxnBool),' external lower or upper bounds relaxed');
maxUB = max(max(model.ub),-min(model.lb));
minLB = min(-max(model.ub),min(model.lb));
intRxnFiniteBound = ((model.ub < maxUB) & (model.lb > minLB));
fprintf('%u%s\n',nnz(p & intRxnFiniteBound),' finite lower bounds relaxed');
exRxn00 = ((model.ub == 0) & (model.lb == 0));
fprintf('%u%s\n',nnz(p & exRxn00),' lower bounds relaxed on fixed reactions (lb=ub=0)');
fprintf('\n');

bool=r~=0;
if any(bool)
    fprintf('%u%s\n',nnz(r),' steady state constraints relaxed');
    fprintf('%-20s%12s%12s\n','mets{n}','r','dxdt')
    for m=1:nMet
        if bool(m)
            fprintf('%-20s%12.4g%12.4g\n',...
                model.mets{m},sol.r(m),model.b(m));
        end
    end
else
    fprintf('%s\n','No steady state constraints relaxed');
end
fprintf('\n');

bool=p~=0 & q==0 & model.SIntRxnBool;
if any(bool)
    fprintf('%u%s\n',nnz(bool),' internal reaction lower bounds relaxed...');
    fprintf('%-20s%12.4s%12.4s%12.4s%12.4s%12.4s%12.8s\n','rxns','p','lb','v','ub','q','formula');
    for n=1:nRxn
        if bool(n)
            rxnAbbrList=model.rxns(n);
            formulas = printRxnFormula(model, rxnAbbrList, printFlag, lineChangeFlag);
            fprintf('%-20s%12.4g%12.4g%12.4g%12.4g%12.4g%6g%-100s\n',...
            model.rxns{n},sol.p(n),model.lb(n),sol.v(n),model.ub(n),sol.q(n),formulas{1});
        end
    end
else
    fprintf('%s\n','No internal reaction lower bounds relaxed');
end
fprintf('\n');

bool=p==0 & q~=0 & model.SIntRxnBool;
if any(bool)
    fprintf('%u%s\n',nnz(bool),' internal reaction lower bounds relaxed...');
    fprintf('%-20s%12.4s%12.4s%12.4s%12.4s%12.4s%12.8s\n','rxns','p','lb','v','ub','q','formula');
    for n=1:nRxn
        if bool(n)
            rxnAbbrList=model.rxns(n);
            formulas = printRxnFormula(model, rxnAbbrList, printFlag, lineChangeFlag);
            fprintf('%-20s%12.4g%12.4g%12.4g%12.4g%12.4g%6g%-100s\n',...
            model.rxns{n},sol.p(n),model.lb(n),sol.v(n),model.ub(n),sol.q(n),formulas{1});
        end
    end
else
    fprintf('%s\n','No internal reaction lower bounds relaxed');
end
fprintf('\n');

bool=p~=0 & q==0 & ~model.SIntRxnBool;
if any(bool)
    fprintf('%u%s\n',nnz(bool),' external reaction lower bounds relaxed...');
    fprintf('%-20s%12.4s%12.4s%12.4s%12.4s%12.4s%12.8s\n','rxns','p','lb','v','ub','q','formula');
     for n=1:nRxn
        if bool(n)
            rxnAbbrList=model.rxns(n);
            formulas = printRxnFormula(model, rxnAbbrList, printFlag, lineChangeFlag);
            fprintf('%-20s%12.4g%12.4g%12.4g%12.4g%12.4g%6g%-100s\n',...
            model.rxns{n},sol.p(n),model.lb(n),sol.v(n),model.ub(n),sol.q(n),formulas{1});
        end
    end
else
    fprintf('%s\n','No external reaction lower bounds relaxed');
end
fprintf('\n');

bool=p==0 & q~=0 & ~model.SIntRxnBool;
if any(bool)
    fprintf('%u%s\n',nnz(bool),' external reaction lower bounds relaxed...');
    fprintf('%-20s%12.4s%12.4s%12.4s%12.4s%12.4s%12.8s\n','rxns','p','lb','v','ub','q','formula');
     for n=1:nRxn
        if bool(n)
            rxnAbbrList=model.rxns(n);
            formulas = printRxnFormula(model, rxnAbbrList, printFlag, lineChangeFlag);
            fprintf('%-20s%12.4g%12.4g%12.4g%12.4g%12.4g%6g%-100s\n',...
            model.rxns{n},sol.p(n),model.lb(n),sol.v(n),model.ub(n),sol.q(n),formulas{1});
        end
    end
else
    fprintf('%s\n','No external reaction lower bounds relaxed');
end
fprintf('\n');


function [status, results] = mrtrix_csdeconv(dwi_file, response_file, lmax, ...
                                   out_file, grad_file, mask_file, verbose)

%function [status, results] = mrtrix_csdeconv(dwi_file, response_file, lmax, ...
%           out_file, grad_file, [mask_file=entire volume], [verbose=true])
%
% Fit the constrained spherical deconvolution model to dwi data
%
% Parameters
% ----------
% dwi_file: The name of a dwi file in .mif format.
% response_file: The name of a .txt fiber response function file.
% lmax: The maximal harmonic order.
% out_file: The resulting .mif file.
% grad_file: a file containing gradient information in the mrtrix format.
% mask_file: a .mif file containing a mask. Default: the entire volume.
% verbose: Whether to display stdout to the command window.
%
% Returns
% -------
% status: whether (0) or not (1) the operation succeeded
% results: the results of the operation in stdout
%
% Notes
% -----
% http://www.brain.org.au/software/mrtrix/tractography/preprocess.html
%

if notDefined('verbose')
    verbose = true;
end

if notDefined('bkgrnd')
    bkgrnd = false;
end

if notDefined('mask_file')
cmd_str = sprintf('csdeconv %s %s -lmax %d %s -grad %s',...
    dwi_file, response_file, lmax, out_file, grad_file);

else
cmd_str = sprintf('csdeconv %s %s -lmax %d -mask %s %s -grad %s',...
    dwi_file, response_file, lmax, mask_file, out_file, grad_file);
end

[status,results] = mrtrix_cmd(cmd_str, bkgrnd, verbose);


report_this_filefun(mfilename('fullpath'));

l = isnan(tmap);
tmap(l) = 1;

[lat,lon] = meshgrat(tmap,tmapleg);
%[lat,lon] = meshgrat(vlat,vlon);

%[smap,smapleg] = country2mtx('switzerland',100);
%[lat0, lon0] = meshgrat(smap,smapleg);

% tmap = km2deg(tmap/1);
[X , Y]  = meshgrid(gx,gy);

%sw = interp2(lon0,lat0,smap,lon,lat);

ren = interp2(X,Y,re4,lon,lat);

mi = min(min(ren));
l =  isnan(ren);
ren(l) = mi-0.05;

figure_w_normalized_uicontrolunits('pos',[150 500 1000 700])

hold on; axis off
axesm('MapProjection','eqaconic','MapParallels',[],...
    'MapLatLimit',[s4_south s3_north],'MapLonLimit',[s2_west s1_east])

meshm(ren,tmapleg,size(tmap),tmap);

daspectm('m',50);
tightmap
view([0 90])
camlight; lighting phong
set(gca,'projection','perspective');

% load usalo
% h = displaym(usalo('state'));

%set(h(1),'color',[0.9 0.9 0.9],'Linewidth',2)
% h = displaym(gtlakevec); set(h(1),'color',[0.9 0.9 0.9],'Linewidth',2)

% h2 = displaym(PPpoint);
%h = displaym(PPtext); trimcart(h);

%pl = plotm(lima(:,2),lima(:,1),'hw');
%set(pl,'LineWidth',1.5,'MarkerSize',12,...
% 'MarkerFaceColor','y','MarkerEdgeColor','k')

pl = plotm(dam(:,2),dam(:,1),'^w');
set(pl,'LineWidth',1.5,'MarkerSize',12,...
    'MarkerFaceColor','w','MarkerEdgeColor','k')
pl = plotm(coastline(:,2), coastline(:,1),'w','Linewidth',2);
set(pl,'LineWidth',2);
zdatam(handlem('allline'),10000) % keep line on surface
%zdatam(handlem('alltext'),10000) % keep line on surface

j = jet;
%j = j(64:-1:1,:);
j = [ [ 0.85 0.9 0.9] ; j];

colormap(j); brighten(0.1);

axis off; set(gcf,'color','k')

setm(gca,'ffacecolor','k')
setm(gca,'fedgecolor','y','flinewidth',3);

setm(gca,'mlabellocation',2)
setm(gca,'meridianlabel','on')
setm(gca,'plabellocation',2)
setm(gca,'parallellabel','on')
setm(gca,'Fontcolor','w','Fontweight','bold','FontSize',12,'Labelunits','dm')

h5 = colorbar;
set(h5,'position',[0.82 0.35 0.01 0.3],'TickDir','out','Ycolor','w','Xcolor','w',...
    'Fontweight','FontSize',12);
set(gcf,'Inverthardcopy','off');


function make_roi_paths(pial, outersmoothed, radius, stepsize, outdir, flagf)

% Original Author: Marie Schaer
% Date: 2007/11/15
%
% This function creates multiple circular regions of interest on the outer
% surface, measures their area (saved in matlab format) and save path file
% containing a set of
% corresponding points on the pial surface. The path files are required as
% an input to the mri_path2label function
%
% Parameters:
% radius: radius of the circular region of interest on the outer surface.
% Most appropriate values between 20 and 25 mm, further documentation
% available in the validation publication: "A surface-based approach to
% quantify local cortical gyrification" by Schaer M, Bach Cuadra M,
% Tamarit L, Eliez E, Thiran JP, IEEE Transactions on Medical Imaging, 2007
%
% Utilities to transfer points on the pial surface calls "mesh_vertex_nearest",
% a function written by Darren Weber. Utilities to compute matrix adjacency
% for the pial surface calls "mesh_adjacency", a program first written by
% Darren Weber, then modified by G. Peyre (source: toolbox_graph on
% mathworks)
%
% Example: make_roi_paths('lh.pial','lh.outer-pial-smoothed',25,100,/tmp)

t0 = cputime;

disp('loading datas ...')
[mesh_total.vertices, mesh_total.faces]=freesurfer_read_surf(pial);
[mesh_outer.vertices, mesh_outer.faces]=freesurfer_read_surf(outersmoothed);

disp('preparing outer mesh structure ...')
mesh_outer = createMeshFacesOfVertex (mesh_outer.vertices, mesh_outer.faces)

disp('preparing pial mesh structure ...')
A = mesh_adjacency(mesh_total);

% Keep track of the area for each individual region of interest on the
% outer surface:
nbVertices = size(mesh_outer.vertices,1);
areasOuterROI = zeros(nbVertices,1);
areasOuterROI = sparse (areasOuterROI);
clear nbVertices

% Circular regions of interest are defined each 100 vertex on the outer
% surface. Due to the high resolution of the outer mesh (average face area
% of ~0.3mm2), calculations are computed each 1 on 100 vertex, to avoid
% high redundancies and optimize calculation time.

for iV = 1:stepsize: length(mesh_outer.vertices)

    disp(['... creating path file for vertex ',num2str(iV),' / ',num2str(length(mesh_outer.vertices))])

    % ------ Part 1: find the ROI on the enveloppe --------------

    [verticesInROI, facesInROI] = getVerticesAndFacesInSphere(mesh_outer, iV, radius);

    % In rare case, the intersection of the enveloppe with the sphere result
    % in two regions of interest: the one that we expect, circular and
    % centered in iV; and an aberrant one at the bottom of the sphere
    % (e.g. near the superior sagittal vault). The next step is used to
    % control for that and keep only the radial region centered at iV.
    facesListOuterGeo = MakeGeodesicOuterROI (mesh_outer, iV, facesInROI);

    % Find the perimeter of the outer ROI
    verticesOuterGeo=unique(facesListOuterGeo(:));
    perim=setdiff(verticesOuterGeo,verticesInROI);

    % Measure its area
    areaOuterROI = getFacesArea(mesh_outer,facesListOuterGeo);

    areasOuterROI(iV) = areaOuterROI;

    if (mod(iV,50*stepsize) == 1)
        fname = [outdir '/' pial '.area_intermed.mat'];
        save(fname, 'areasOuterROI') ;
        disp(['area file for outer ROIs saved at ',num2str(iV)])
    end

    clear verticesInROI facesInROI facesListOuterGeo verticesOuterGeo areaOuterROI

    % ----- Part2: Define the corresponding set of points on the pial surface:
    % Transfer a few points of the perimeter of the hulls ROI from
    % the envelope to the pial surface, and save them as path file.
    step = 7;
    [verticeslist] = SearchProjectionOnPial(mesh_total, mesh_outer, perim, step);

    % reorganize the set of points in the right order to input them to
    % mri_path2label
    reorglist = reorganize_verticeslist (mesh_total, A, mesh_outer, perim, verticeslist, step);
    lindex = reorglist';
    lxyz = mesh_total.vertices(lindex,:); lindex= lindex-1;

    p = sprintf ('%06d', iV);
    write_path(lxyz, lindex,[outdir '/' pial '.' p '.path']);

    clear verticeslist lindex lxyz

end

disp(['saving area file in matlab format... '])
fname = [outdir '/' pial '.outer_ROIs_area.mat'];
save(fname, 'areasOuterROI')

disp('DONE.')
deltaT = cputime - t0

% indicate successful completion by deleting flagfile
delete(flagf);


function [UTC1,UTC2]=UT12UTC(UT11,UT12,deltaUTCUT1)
%%UT12UTC Convert from UT1, which is a nonuniform timescale based on the
%         rotation rate of the Earth, to Coordinated Universal Time (UTC),
%         which is the "standard" time that pretty much every country uses
%         (the time zone is that of the United Kingdom) including
%         leapseconds. Due to the use of leapseconds, UT1 is always within
%         0.9 seconds of UTC.
%
%INPUTS: Jul1,Jul2 Two parts of a Julian date given in UTC. The units of
%                  the date are days. The full date is the sum of both
%                  terms. The date is broken into two parts to provide
%                  more bits of precision. It does not matter how the date
%                  is split.
%      deltaUTCUT1 An optional parameter specifying the offset between UTC
%                  and UT1 in seconds. If this parameter is omitted, then
%                  the value of the function getEOP will be used and
%                  iterations will be performed, because the correct
%                  tabulated value is given in UTC, not UT1.
%
%OUTPUTS: Jul1,Jul2 Two parts of a pseudo-Julian date in UTC with units of
%                   Julian days.
%
%This essentially just adds deltaUTCUT1 from the given UTC date, or
%looks up deltaUTCUT1 using the getEOP function and then adds
%deltaUTCUT1. The "looking up" step involves an interation, since the value
%of deltaUTCUT1 is tabulated by UTC, which is unknown. To know the peroper
%amount to subtract from the pseudo-Julian day, the function leapSecsOnDay
%is used to determine whether the day contains a leapsecond. As that
%function is also tabulated by UTC, an iteration is necessary even if
%deltaUTCUT1 is given. Unlike the function iauUtcut1 in the International
%Astronomical Union's Standards of Fundamental Astronomy library, this does
%not try to deal with deltaUTCUT1 being off by a second near a leapsecond
%as it was noticed that the "corrections" made in the library make the pair
%of UTC2UT1 and UT12UTC inconsistent by a second when it is near a
%leapsecond.
%
%Many temporal coordinate systems standards are compared in [1].
%
%REFERENCES:
%[1] D. F. Crouse, "An Overview of Major Terrestrial, Celestial, and
%    Temporal Coordinate Systems for Target Tracking," Formal Report, Naval
%    Research Laboratory, no. NRL/FR/5344--16-10,279, 10 Aug. 2016, 173
%    pages.
%
%April 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

%The initial estimate of UTC is just UT1. This will be within 0.9 seconds
%of the correct value.
UTC1=UT11;
UTC2=UT12;

for curIter=1:2
    if(nargin<3)
        [~,~,deltaUTCUT1]=getEOP(UTC1,UTC2);
    end

    %Find the number of seconds in the day.
    [year,month,day]=UTC2Cal(UTC1,UTC2,true);
    numSecInDay=24*60*(60+leapSecsOnDay(year,month,day));

    %Add preserving precision.
    if(UTC1<UTC2)
        UTC2=UT11+deltaUTCUT1/numSecInDay;
        UTC1=UT12;
    else
        UTC2=UT12+deltaUTCUT1/numSecInDay;
        UTC1=UT11;
    end

    %Put the fractional part into UTC2 and the integer part into UTC1.
    frac1=UTC1-fix(UTC1);
    frac2=UTC2-fix(UTC2);
    sumVal=frac1+frac2;
    sumInt=fix(sumVal);
    sumFrac=sumVal-sumInt;
    UTC1=fix(UTC2)+fix(UTC1)+sumInt;
    UTC2=sumFrac;
end
end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.


% Function to derive audio features for silence and unvoiced regions
%
% Description
% Function to derive audio features for silence and unvoiced regions
%
%
% Inputs
%  x        : [samples] [Nx1]  Speech signal
%  fs       : [Hz]      [1x1]  Sampling frequency
%  frame_len_ms: [ms] [1x1]  Window length
%
% Outputs
%  Ts       : [samples] [Px1]  Locations of parameter values
%  Es       : [dB]      [Mx1]  Energy contour
%
% Example
%  Please see the HOWTO_glottalsource.m example file.
%
% References
%  [1] Drugman, T., Kane, J., Gobl, C., `Automatic Analysis of Creaky
%       Excitation Patterns', Submitted to Computer Speech and
%       Language.
%  [2] Kane, J., Drugman, T., Gobl, C., (2013) `Improved automatic
%       detection of creak', Computer Speech and Language 27(4), pp.
%       1028-1047.
%  [3] Drugman, T., Kane, J., Gobl, C., (2012) `Resonator-based creaky
%       voice detection', Interspeech 2012, Portland, Oregon, USA.
%
% Copyright (c) 2013 University of Mons, FNRS & 2013 Trinity College Dublin
%
% License
%  This code is a part of the GLOAT toolbox with the following
%  licence:
%  This program is free software: you can redistribute it and/or modify
%  it under the terms of the GNU General Public License as published by
%  the Free Software Foundation, either version 3 of the License, or
%  (at your option) any later version.
%  This program is distributed in the hope that it will be useful,
%  but WITHOUT ANY WARRANTY; without even the implied warranty of
%  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%  GNU General Public License for more details.
%
% This function is part of the Covarep project: http://covarep.github.io/covarep
%
% Authors
%  Thomas Drugman <thomas.drugman@umons.ac.be> & John Kane <kanejo@tcd.ie>

function [Ts,Es,ZCs_ms,Xpos,pos] = sil_unv_features(x,fs,frame_len_ms)

if nargin < 3
    frame_len_ms=10;
end
frame_len=frame_len_ms/1000*fs;
frame_shift_ms=5;
Shift=frame_shift_ms/1000*fs;

Start=1; % intialise
Stop=Start+frame_len-1;
pos=mean([Start Stop]);

[ZCs,Xpos] = get_zero_x_rate(x,frame_len,Shift);
ZCs_ms=ZCs/1000*fs;

Ind=1;

Es=zeros(1,floor((length(x)-Stop+1)/Shift)+1);
Ts=zeros(size(Es));

win = hanning(Stop-Start+1);

while Stop<length(x)

    Mid=round((Start+Stop)/2);
    Ts(Ind)=Mid;

    Sig=x(Start:Stop); % Select frame segment
    Sig=Sig(:).*win; % Window segment

    Es(Ind)=mean(Sig.^2); % Get energy value

    Start=Start+Shift;
    Stop=Stop+Shift;
    pos(Ind)=mean([Start Stop]);
    Ind=Ind+1;
end

Es=log(Es);


function cS = kyanite

%
cs_Ky = crystalSymmetry('-1',[0.907 1 0.71], [90, 101.2, 106]*degree);
N = Miller({1,0,0},{0,1,0},{0,0,1},{1,-1,0},{1,1,0},cs_Ky);
dist = [0.4, 1, 2.4, 1.05, 1.2];
cS = crystalShape(N./dist);


function tests = test_spm_dcm_bmr_all
% Unit Tests for test_spm_dcm_bmr_all
%__________________________________________________________________________
% Copyright (C) 2016 Wellcome Trust Centre for Neuroimaging

% $Id: test_spm_dcm_bmr_all.m 6915 2016-11-01 17:38:08Z peter $

tests = functiontests(localfunctions);

% -------------------------------------------------------------------------
function test_bmr_all(testCase)

data_path = get_data_path();

% Load PEB of full DCM
PEB = load(fullfile(data_path,'PEB_test.mat'));
PEB = PEB.PEB;
PEB = PEB(1);

% Load DCMs
GCM = load(fullfile(data_path,'models','GCM_simulated.mat'));
GCM = GCM.GCM;

% Prune connections on the B-matrix only
[rPEB,BMR,BMA] = spm_dcm_bmr_all(PEB,{'B'});

% Check the only surviving B-matrix (group difference) parameter is R1->R2
b_reduced = BMA.Cp(:,2);
expected  = logical([0 0 0 0 1 0]);
testCase.assertTrue(all(b_reduced(~expected) < 1e-4));
testCase.assertTrue(all(b_reduced(expected) > 1e-4));

% -------------------------------------------------------------------------
function data_path = get_data_path()

data_path = fullfile( spm('Dir'), 'tests', ...
    'data', 'fMRI', 'simulated_2region');


function [y] = cellcolremove(x, cols)

% [Y] = CELLCOLREMOVE(X, COLS) outputs cell-array Y with the same dimensionality as X
% Each cell in Y has the indexed columns COLS removed from the original corresponding cell in X
%
% X (and Y) should be linear cell-array(s) of matrices for which the number of rows
% should be the same for all cells

nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
  error('incorrect input for cellrows');
end

y = cellfun(@colr, x, repmat(mat2cell(cols(:),length(cols),1),nx), 'UniformOutput', 0);

function [y] = colr(x, cols)

if ischar(cols)
  if strcmp(cols(1),'r')
    % remove n columns on the right
    cols = str2double(cols(2:end));
    cols = size(x,2)-((cols-1):-1:0);
  elseif strcmp(cols(1),'l')
    % remove n columns on the left
    cols = str2double(cols(2:end));
    cols = 1:cols;
  else
    % numeric
  end
end

x(:,cols) = [];
y         = x;


function varargout = drawVertices(varargin)
%DRAWVERTICES Draw the vertices of a polygon or polyline.
%
%   drawVertices(POLY)
%   Draws the vertices of the given polygon, using pre-defined style.
%   Default is to draw vertices as squares, with the first vertex filled.
%
%   Example
%     poly = circleToPolygon([20 30 40], 16);
%     drawPolygon(poly);
%     hold on; axis equal;
%     drawVertices(poly);
%
%   See also
%   drawPoint, drawPolygon, drawPolyline

% ------
% Author: David Legland
% E-mail: david.legland@grignon.inra.fr
% Created: 2011-12-11, using Matlab 7.9.0.529 (R2009b)
% Copyright 2011-2022 INRA - Cepia Software Platform

% extract handle of axis to draw on
if isAxisHandle(varargin{1})
    ax = varargin{1};
    varargin(1) = [];
else
    ax = gca;
end

var = varargin{1};

%% Manage cell arrays of polygons / polylines

% case of a set of polygons stored in a cell array
if iscell(var)
    N = length(var);
    h = zeros(N, 1);
    for i = 1:N
        state = ishold(gca);
        hold on;
        % check for empty polygons
        if ~isempty(var{i})
            h(i) = drawVertices(ax, var{i}, varargin{2:end});
        end
        if ~state
            hold off
        end
    end

    if nargout > 0
        varargout = {h};
    end

    return;
end

%% Parse coordinates and options

% Extract coordinates of vertices
if size(var, 2) > 1
    % first argument is a vertex array
    px = var(:, 1);
    py = var(:, 2);
    varargin(1) = [];

elseif length(varargin) >= 2 && isnumeric(varargin{1}) && isnumeric(varargin{2})
    % arguments 1 and 2 correspond to x and y coordinate respectively
    px = varargin{1};
    py = varargin{2};
    varargin(1:2) = [];

else
    % unknow input format
    error('Should specify either a N-by-2 array, or 2 N-by-1 vectors');
end

% concatenate input argument(s) with default options
defaults = {'MarkerSize', 6};
if length(varargin) == 1
    varargin = [varargin defaults];
else
    varargin = [{'ks'} defaults varargin];
end

%% Draw the vertices

% draw the vertices
h = plot(ax, px, py, varargin{:});

% draw the first vertex with a different style
plot(ax, px(1), py(1), 'ks', 'MarkerFaceColor', 'k', 'MarkerSize', 8);

% format output arg
if nargout > 0
    varargout = {h};
end


function varargout = plotcoeffs(f, varargin)
%PLOTCOEFFS   Display coefficients graphically.
%   PLOTCOEFFS(F) plots the absolute values of the coefficients underlying the
%   representation of a CHEBFUN F on a semilogy scale. If F is an array-valued
%   CHEBFUN or has breakpoints, then a curve is plotted for each FUN of each
%   component (column) of F.
%
%   PLOTCOEFFS(F, S) allows further plotting options, such as linestyle,
%   linecolor, etc, as in the standard MATLAB manner. If S contains a string
%   'LOGLOG', the coefficients will be displayed on a log-log scale.
%
%   H = PLOTCOEFFS(F) returns a column vector of handles to lineseries objects.
%
%   As of Chebfun version 5, the coefficients plotted by 'plotcoeffs' are either
%   Chebyshev coefficients for Chebyshev-based chebfuns or Fourier coefficients
%   for periodic chebfuns ('trigfuns').
%
% See also CHEBFUN/PLOT.

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

% Deal with an empty input:
if ( isempty(f) )
    if ( nargout == 1 )
        varargout{1} = plot([]);
    end
    return
end

dom = f(1).domain([1,end]);

% We can only plot the coefficients of one CHEBFUN at a time:
if ( any(cellfun(@(f) isa(f, 'chebfun'), varargin)) )
    error('CHEBFUN:CHEBFUN:plotcoeffs:multipleChebfuns', ...
        'Calls of the form PLOTCOEFFS(F, ''b'',  G, ''r'') are not supported.');
end

% Store the hold state of the current axis:
holdState = ishold;

% Grab some colours:
col = [];
if ( nargin > 1 && ischar(varargin{1}) && numel(varargin{1}) < 4 )
    % (Note. LineStyle definitions have at most 4 characters. Other plotting
    % parameters have more than characters.)
    col = regexp(varargin{1}, '[bgrcmykw]', 'match');
    if ( numel(col) > 1 )
        error('CHEBFUN:plotcoeffs:color', ...
            'Error in color/linetype argument.');
    elseif ( ~isempty(col) )
        col = col{:};
%         varargin(1) = []; % Don't remove as we need marker information.
    end
end
if ( isempty(col) )
    colIdx = find(cellfun(@(arg) all(ischar(arg)) && ...
        any(strfind(arg, 'color')), varargin));
    if ( colIdx )
        col = varargin{colIdx+1};
        varargin(colIdx+(0:1)) = [];
    else
        col = get(0, 'DefaultAxesColorOrder');
        col = repmat(col, ceil(numColumns(f)/7), 1);
    end
end

% Deal with 'LogLog' and input:
doLogLog = any(cellfun(@(s) strcmpi(s, 'loglog'), varargin));

% Convert to a cell array for easy handling:
f = mat2cell(f);

% Initialise the output:
h = cell(1, numel(f));

% Loop over the columns in a quasimatrix:
for k = 1:numel(f)
    % Colours for this columns:
    if ( ischar(col) )
        colk = col;
    else
        colk = col(k,:);
    end
    % Call the column version:
    h{k} = columnPlotCoeffs(f{k}, colk, varargin{:}, 'domain', dom);
end

% Return hold state to what it was before:
if ( ~holdState )
    hold off
end

% Set xScale to logarithmic if requested:
if ( doLogLog )
    set(gca, 'xScale', 'Log');
end

% Give an output if one was requested:
if ( nargout > 0 )
    try
        h = cell2mat(h);
    catch
        % shrug
    end
    varargout = {h};
end

end

function h = columnPlotCoeffs(f, col, varargin)
numFuns = numel(f.funs);

% Initialise handle storage:
h = zeros(numFuns, 1);

% Call plotcoeffs at the tech level:
for j = 1:numFuns
    h(j) = plotcoeffs(f.funs{j}, varargin{:}, 'color', col); hold on
end

end


%% REW_city
% %{
imfolder = 'images\REW_city';
im_n = 5;
imfile = cell(im_n,1);
for ii = 1:im_n
    imfile{ii} = sprintf('%s\\%01d.jpg', imfolder, ii);
end

im = cell(im_n,1);
for ii = 1:im_n
    im{ii} = imread(imfile{ii});
end

edge_list = zeros(im_n-1,2);
for ei = 1:im_n-1
    edge_list(ei,:) = [ei,ei+1];
end

imsize = zeros(im_n,3);

for ii = 1:im_n
    imsize(ii,:) = size(im{ii});
    if imsize(ii,1) > 720
        scale = 720/size(im{ii}, 1);
        im{ii} = imresize(im{ii}, scale);

        imsize(ii,:) = size(im{ii});
    end
end

mosaic = REW_mosaic( im, edge_list, 0, 'equi', 0, imfolder );
%}


function colormap = BF_MakeBrightenedColorMap(rgb,numGrads)
% BF_MakeBrightenedColorMap  Given an rgb vector, progressively brightens into a colormap

% ------------------------------------------------------------------------------
% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite the following two papers:
%
% (1) B.D. Fulcher and N.S. Jones, "hctsa: A Computational Framework for Automated
% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).
% DOI: 10.1016/j.cels.2017.10.001
%
% (2) B.D. Fulcher, M.A. Little, N.S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2013).
% DOI: 10.1098/rsif.2013.0048
%
% This function is free software: you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation, either version 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
% ------------------------------------------------------------------------------

if nargin < 2
    numGrads = 8;
end

colormap = zeros(numGrads,3);

brightenRange = linspace(0,1,numGrads);
for i = 1:numGrads
    colormap(i,:) = brighten(rgb,brightenRange(i));
end

end