function value = hex_digit_to_i4 ( c )

%*****************************************************************************80
%
%% HEX_DIGIT_TO_I4 converts a hexadecimal digit to an I4.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, character C, the hexadecimal digit, '0'
%    through '9', or 'A' through 'F', or also 'a' through 'f'
%    are allowed.
%
%    Output, integer VALUE, the corresponding integer, or -1 if C was illegal.
%
  if ( '0' <= c && c <= '9' )
    value = c - '0';
  elseif ( 'a' <= c && c <= 'f' )
    value = 10 + c - 'a';
  elseif ( 'A' <= c && c <= 'F' )
    value = 10 + c - 'A';
  elseif ( c == ' ' )
    value = 0;
  else
    value = -1;
  end

  return
end


function pop = crossoverOp(opt, pop, state)
% Function: pop = crossoverOp(opt, pop, state)
% Description: Crossover operator. All of the individuals would be do crossover, but
%   only "crossoverFraction" of design variables of an individual would changed.
%
%         LSSSSWC, NWPU
%    Revision: 1.1  Data: 2011-07-13
%*************************************************************************

%*************************************************************************
% 1. Check for the parameters
%*************************************************************************
% determine the crossover method
strfun = lower(opt.crossover{1});
numOptions = length(opt.crossover) - 1;
[crossoverOpt{1:numOptions}] = opt.crossover{2:end};

switch( strfun )
    case 'intermediate'
        fun = @crsIntermediate;
    otherwise
        error('NSGA2:CrossoverOpError', 'No support crossover operator!');
end

nVar = opt.numVar;

% "auto" crossover fraction
if( ischar(opt.crossoverFraction) )
    if( strcmpi(opt.crossoverFraction, 'auto') )
        fraction = 2.0 / nVar;
    else
        error('NSGA2:CrossoverOpError', 'The "crossoverFraction" parameter should be scalar or "auto" string.');
    end
else
    fraction = opt.crossoverFraction;
end

for ind = 1:2:length(pop)    % Popsize should be even number
        % Create children
        [child1, child2] = fun( pop(ind), pop(ind+1), fraction, crossoverOpt );

        % Round
        for v = 1:nVar
            if( opt.vartype(v) == 2)
                child1.var(v) = round( child1.var(v) );
                child2.var(v) = round( child2.var(v) );
            end
        end

        % Bounding limit
        child1.var = varlimit(child1.var, opt.lb, opt.ub);
        child2.var = varlimit(child2.var, opt.lb, opt.ub);

        pop(ind)     = child1;
        pop(ind+1)   = child2;

end

function [child1, child2] = crsIntermediate(parent1, parent2, fraction, options)
% Function: [child1, child2] = crsIntermediate(parent1, parent2, fraction, options)
% Description: (For real coding) Intermediate crossover. (Same as Matlab's crossover
%   operator)
%       child = parent1 + rand * Ratio * ( parent2 - parent1)
% Parameters:
%   fraction : crossover fraction of variables of an individual
%   options = ratio
%
%         LSSSSWC, NWPU
%    Revision: 1.1  Data: 2011-07-13
%*************************************************************************

if( length(options)~=1 || ~isnumeric(options{1}))
    error('NSGA2:CrossoverOpError', 'Crossover operator parameter error!');
end

ratio = options{1};

child1 = parent1;
child2 = parent2;

nVar = length(parent1.var);
crsFlag = rand(1, nVar) < fraction;

randNum = rand(1,nVar);     % uniformly distribution

child1.var = parent1.var + crsFlag .* randNum .* ratio .* (parent2.var - parent1.var);
child2.var = parent2.var - crsFlag .* randNum .* ratio .* (parent2.var - parent1.var);


function gl = spm_get_volumes(P)
% Compute total volumes from tissue segmentations
% FORMAT gl = spm_get_volumes(P)
% P  - a matrix of image filenames
% gl - a vector of volumes (in litres)
%__________________________________________________________________________
% Copyright (C) 2006-2011 Wellcome Trust Centre for Neuroimaging

% John Ashburner
% $Id: spm_get_volumes.m 5670 2013-10-04 16:48:38Z ged $

warning('spm:deprecated', ...
    ['spm_get_volumes will be removed in the future, please use ' ...
    'the Tissue Volumes Utility in the Batch interface, or:\n\t' ...
    'spm_summarise(P, ''all'', ''litres'')']);

if ~nargin
    [P,sts] = spm_select(Inf,'image','Select images');
    if ~sts, gl = []; return; end
end

V = spm_vol(P);
if spm_check_orientations(V, false)
    gl = spm_summarise(V, 'all', 'litres');
else
    N = numel(V);
    gl = nan(N, 1);
    for n = 1:N
        gl(n) = spm_summarise(V(n), 'all', 'litres');
    end
end


%SETCOST Reset classification cost matrix of mapping
%
%   W = SETCOST(W,COST,LABLIST)
%
% The classification cost matrix of the dataset W is reset to COST.
% W has to be a trained classifier. COST should have size [C,C+1],
% if C is the number of classes assigned by W.
% COST(I,J) are the costs of classifying an object of class I
% as class J. Column C+1 generates an alternative reject class and
% may be omitted, yielding a size of [C,C].
% An empty cost matrix, COST = [] (default) is interpreted as
% COST = ONES(C) - EYE(C) (identical costs of misclassification).
%
% In LABLIST the corresponding class labels may be supplied.
% LABLIST may have only class names of the existing labels assigned
% by W, stored in W.LABELS.


function [zipped,info] = norm2huff(vector)
%NORM2HUFF   Huffman codification (encoder)
%   For vectors, NORM2HUFF(X) returns a Huffman coded version of the input vector.
%   For matrices, X(:) is used as input.
%
%   Input must be of uint8 type, while the output is a uint8 array.
%
%   [...,INFO] = ... returns also a structure with data required to convert it back
%   to normal vector:
%
%      INFO.pad        = eventually added bits at the end of bit sequence;
%      INFO.huffcodes  = Huffman codewords;
%      INFO.ratio      = compression ratio;
%      INFO.length     = original data length;
%      INFO.maxcodelen = max codeword length;
%
%   Codewords are stored in the 52 available bits of a double. To avoid anbiguities,
%   after the last codeword bit, a "1" bit is added to terminate the codeword.
%   I.e. the max codeword length can be 51 bits.
%
%   See also HUFF2NORM

%   $Author: Giuseppe Ridino' $
%   $Revision: 1.0 $  $Date: 10-May-2004 15:03:04 $

% ensure to handle uint8 input vector
if ~isa(vector,'uint8'),
	error('input argument must be a uint8 vector')
end

% vector as a row
vector = vector(:)';

% frequency
f = frequency(vector);

% simbols presents in the vector are
simbols = find(f~=0); % first value is 1 not 0!!!
f = f(simbols);

% sort using the frequency
[f,sortindex] = sort(f);
simbols = simbols(sortindex);

% generate the codewords as the 52 bits of a double
len = length(simbols);
simbols_index = num2cell(1:len);
codeword_tmp = cell(len,1);
while length(f)>1,
	index1 = simbols_index{1};
	index2 = simbols_index{2};
	codeword_tmp(index1) = addnode(codeword_tmp(index1),uint8(0));
	codeword_tmp(index2) = addnode(codeword_tmp(index2),uint8(1));
	f = [sum(f(1:2)) f(3:end)];
	simbols_index = [{[index1 index2]} simbols_index(3:end)];
	% resort data in order to have the two nodes with lower frequency as first two
	[f,sortindex] = sort(f);
	simbols_index = simbols_index(sortindex);
end

% arrange cell array to have correspondance simbol <-> codeword
codeword = cell(256,1);
codeword(simbols) = codeword_tmp;

% calculate full string length
len = 0;
for index=1:length(vector),
	len = len+length(codeword{double(vector(index))+1});
end

% create the full 01 sequence
string = repmat(uint8(0),1,len);
pointer = 1;
for index=1:length(vector),
	code = codeword{double(vector(index))+1};
	len = length(code);
	string(pointer+(0:len-1)) = code;
	pointer = pointer+len;
end

% calculate if it is necessary to add padding zeros
len = length(string);
pad = 8-mod(len,8);
if pad>0,
	string = [string uint8(zeros(1,pad))];
end

% now save only usefull codewords
codeword = codeword(simbols);
codelen = zeros(size(codeword));
weights = 2.^(0:51);
maxcodelen = 0;
for index = 1:length(codeword),
	len = length(codeword{index});
	if len>maxcodelen,
		maxcodelen = len;
	end
	if len>0,
		code = sum(weights(codeword{index}==1));
		code = bitset(code,len+1);
		codeword{index} = code;
		codelen(index) = len;
	end
end
codeword = [codeword{:}];

% calculate zipped vector
cols = length(string)/8;
string = reshape(string,8,cols);
weights = 2.^(0:7);
zipped = uint8(weights*double(string));

% store data into a sparse matrix
huffcodes = sparse(1,1); % init sparse matrix
for index = 1:numel(codeword),
	huffcodes(codeword(index),1) = simbols(index);
end

% create info structure
info.pad = pad;
info.huffcodes = huffcodes;
info.ratio = cols./length(vector);
info.length = length(vector);
info.maxcodelen = maxcodelen;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function codeword_new = addnode(codeword_old,item)
codeword_new = cell(size(codeword_old));
for index = 1:length(codeword_old),
	codeword_new{index} = [item codeword_old{index}];
end


%% Compile MatConvNet
% TODO

%% Setup classifier
setup_path = 'D:\Users\sim0629\matconvnet-1.0-beta20\matlab';
% need to be called
run(fullfile(setup_path, 'vl_setupnn.m'));
load('imdb.mat');
load('net-epoch-57.mat');

%% Detection and Classification
close all;
[filename, pathname, ~] = uigetfile({'*.jpg;*.tif;*.png;*.gif','All Image Files'});
im = imread(fullfile(pathname, filename));

[ellipses, resized_im] = detectEllipses(im, true);
num_of_ellipses = length(ellipses);
features = zeros(50 * num_of_ellipses, 100, 3, 'uint8');
scoreses = zeros(num_of_ellipses, 8);

for i = 1 : num_of_ellipses
    feature = extractFeatureImage(resized_im, ellipses, i, false);
    scoreses(num_of_ellipses+1-i,:) = classifyFeature(feature, images, net)';
    features((num_of_ellipses-i)*50+1 : (num_of_ellipses+1-i)*50, :, :) = feature(52:101,1:100,:);
end

figure;

subplot('position', [0, 0.3, 0.3, 0.7]);
imshow(features);

subplot('position', [0.3, 0, 0.7, 0.3]);
imshow('labels.jpg');

subplot('position', [0.3, 0.3, 0.7, 0.7]);
colormap('jet');
imagesc(scoreses);


function scores = calc_scores(input_dir,GT_dir,shave_width,verbose)

addpath(genpath(fullfile(pwd,'utils')));

%% Loading model
load modelparameters.mat
blocksizerow    = 96;
blocksizecol    = 96;
blockrowoverlap = 0;
blockcoloverlap = 0;

%% Reading file list
file_list = dir([input_dir,'/*.png']);
im_num = length(file_list);

%% Calculating scores
scores = struct([]);

for ii=1:im_num
    if verbose
        fprintf(['\nCalculating scores for image ',num2str(ii),' / ',num2str(im_num)]);
    end

    % Reading and converting images
    input_image_path = fullfile(input_dir,file_list(ii).name);
    input_image = convert_shave_image(imread(input_image_path),shave_width);
    GD_image_path = fullfile(GT_dir,file_list(ii).name);
    GD_image = convert_shave_image(imread(GD_image_path),shave_width);

    % Calculating scores
    scores(ii).name = file_list(ii).name;
    scores(ii).MSE = immse(input_image,GD_image);
    scores(ii).Ma = quality_predict(input_image);
    scores(ii).NIQE = computequality(input_image,blocksizerow,blocksizecol,...
        blockrowoverlap,blockcoloverlap,mu_prisparam,cov_prisparam);
end

end


% pdfbclassify_texture.m
% written by: Duncan Po
% Date: December 3, 2002
% perform texture classification based on contourlets
%
% Usage:    kld = pdfbclassify_texture(qimage, qformat, tdb, tdir, mdir, firsttime)
% Inputs:   qimage      - query texture image file name
%           qformat     - format of the query texture image file
%           tdb         - texture database: vector (using cell structure)
%                           of the names of all the texture images
%                           e.g. {'texture1', 'texture2', 'texture3'}
%           tdir        - texture directory: full path of the directory
%                           that contains the texture images
%           mdir        - model directory: full path of the directory that
%                           either contains the texture models, or that is
%                           for saving of the texture models
%           firsttime   - set to 1 if this is the first time that this
%                           algorithm is run and no model is available
%                           for the database images, set to 0 otherwise
% Output:   kld         - the Kublick Liebler distance between the trees

function kld = pdfbclassify_texture(qimage, qformat, tdb, tdir, mdir, firsttime)

N = 8;
NN = 16;
if tdir(end) ~= '/'
    tdir = strcat(tdir, '/');
end;
if mdir(end) ~= '/'
    mdir = strcat(mdir, '/');
end;

mdir = strcat(mdir, '/');

[kld, kld2] = pdfbtestall_imagekld(qimage, qformat, tdb, tdir, mdir, N, firsttime);

[skld2, ind2] = sort(kld2);

ind2 = ind2(1:NN-1);
original = imread(qimage, qformat);
figure;
subplot(4,4,1);
imshow(original);

for ploti = 2:NN
    dbimagenum = floor((ind2(ploti-1)-1)/N)+1;
    dbimage = tdb{dbimagenum};
    dbimagenum = mod(ind2(ploti-1)-1, N)+1;
    file = sprintf('%s%s%02d', tdir, dbimage, dbimagenum);
    qresult = imread(file, 'bmp');
    subplot(4,4,ploti);
    imshow(qresult);
end;


function mColormap = gui_Colormap_Rastafari(nSize)

% If size is not specified, set it to 256
if nargin < 1
  nSize = 256;
end

mColormap = [];

nSteps = floor(nSize * 0.1);
mColormap = [mColormap; gui_Interpolate([0.036578, 0.159091, 0.015374], [0.022239, 0.234849, 0.007687], nSteps)];

nSteps = floor(nSize * 0.05);
mColormap = [mColormap; gui_Interpolate([0.022239, 0.234849, 0.007687], [0.007899, 0.310606, 0.000000], nSteps)];

nSteps = floor(nSize * 0.09);
mColormap = [mColormap; gui_Interpolate([0.007899, 0.310606, 0.000000], [0.101896, 0.443182, 0.042827], nSteps)];

nSteps = floor(nSize * 0.09);
mColormap = [mColormap; gui_Interpolate([0.101896, 0.443182, 0.042827], [0.195893, 0.575758, 0.085655], nSteps)];

nSteps = floor(nSize * 0.09);
mColormap = [mColormap; gui_Interpolate([0.195893, 0.575758, 0.085655], [0.560068, 0.663178, 0.139025], nSteps)];

nSteps = floor(nSize * 0.08);
mColormap = [mColormap; gui_Interpolate([0.560068, 0.663178, 0.139025], [0.924242, 0.750598, 0.192395], nSteps)];

nSteps = floor(nSize * 0.1);
mColormap = [mColormap; gui_Interpolate([0.924242, 0.750598, 0.192395], [0.939393, 0.495226, 0.162308], nSteps)];

nSteps = floor(nSize * 0.1);
mColormap = [mColormap; gui_Interpolate([0.939393, 0.495226, 0.162308], [0.954545, 0.239854, 0.132221], nSteps)];

nSteps = floor(nSize * 0.2);
mColormap = [mColormap; gui_Interpolate([0.954545, 0.239854, 0.132221], [0.742424, 0.279602, 0.184117], nSteps)];

nSteps = floor(nSize * 0.1);
mColormap = [mColormap; gui_Interpolate([0.742424, 0.279602, 0.184117], [0.530303, 0.319349, 0.236012], nSteps)];

mColormap(mColormap < 0) = 0;


% Some example for running the sinusoidal and harmonic estimators
%
% Please find the path management in the startup.m script in the root directory
% of this repository. Note that by starting matlab in the root directory, this
% script should automatically run. If it is not the case, you can also move to the
% root directory and run this script manually.
%
% Copyright (c) 2012 University of Crete - Computer Science Department
%
% License
%  This file is under the LGPL license,  you can
%  redistribute it and/or modify it under the terms of the GNU Lesser General
%  Public License as published by the Free Software Foundation, either version 3
%  of the License, or (at your option) any later version. This file is
%  distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
%  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
%  PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
%  details.
%
% This function is part of the Covarep project: http://covarep.github.io/covarep
%
% Author
%  Gilles Degottex <degottex@csd.uoc.gr>
%

clear all;

% Load the waveform
fname = '0011.arctic_bdl1';
[wav, fs] = audioread([fname '.wav']);
times = (0:length(wav)-1)'/fs;

% Load a rough f0 curve
% Can be replaced by any f0 estimate which is robust to octave jumps
f0s = load([fname '.f0.txt']);

disp(['Compute: Sinusoidal Model (SM) using Peak Picking']);
opt = sin_analysis();
opt.fharmonic  = false;
opt.use_ls     = false;
opt.resyn      = true; % Use the internal OLA method for the resynthesis
[frames syn_sm] = sin_analysis(wav, fs, f0s, opt);
audiowrite([fname '.sm.wav'], syn_sm, fs);

disp(['Compute: Harmonic Model (HM)']);
opt = sin_analysis();
opt.fharmonic  = true;
opt.fadapted   = false;
opt.use_ls     = true;
frames = sin_analysis(wav, fs, f0s, opt);
syn_hm = hm_synthesis4(frames, length(wav), fs); % Use the harmonic resynthesis
audiowrite([fname '.hm.wav'], syn_hm, fs);

disp(['Compute: Adaptive Harmonic Model (aHM) using the Adaptive Iterative Refinment (AIR)']);
optair = ahm_air_analysis2();
optair.do_final_ahm_step = false;
[f0sair, frames] = ahm_air_analysis2(wav, fs, f0s, optair);

disp('Compute the last step with uniform analysis instants');
f0sair = interp1td(f0sair, f0s(:,1));
opt = sin_analysis();
opt.fharmonic  = true;
opt.fadapted   = true;
opt.use_ls     = true;
frames = sin_analysis(wav, fs, f0sair, opt);
syn_ahm = hm_synthesis4(frames, length(wav), fs); % Use the harmonic resynthesis
audiowrite([fname '.ahm-air.wav'], syn_ahm, fs);
%  save([fname '.ahm_frames.mat'], 'frames');

figure
fig(1) = subplot(211);
    plot(times, wav, 'k');
    hold on;
    plot(times, syn_sm, 'g');
    plot(times, syn_hm, 'b');
    plot(times, syn_ahm, 'r');
    xlabel('Time [s]');
    legend({'Waveform', 'Sinusoidal Model (SM)', 'Harmonic Model (HM)', 'Adaptive Harmonic Model (aHM)'});
fig(2) = subplot(212);
    plot(f0s(:,1), log2(f0s(:,2)), '--k');
    hold on;
    plot(f0sair(:,1), log2 (f0sair(:,2)), 'r');
    xlabel('Time [s]');
    legend({'Input f_0 [log_2 Hz]', 'AIR refined f_0 [log_2 Hz]'});
linkaxes(fig, 'x');


function [whitestats PCstats stabilitystats residualstats] = est_validateMVAR(varargin)
%
% Validate a fitted VAR model. With two inputs, this function generates a
% GUI where the validation scheme can be specified. Validation consists of
% statistical tests for "whiteness" of fitted VAR model residuals [1,2],
% consistency of the fitted model [1,3] and stability of fitted model [1-3]
%
% Input:
%
%   ALLEEG:     Array of EEGLAB data structures containing fitted MODEL
%   typeproc:   reserved for future use. Use 0
%
% Optional:
%
%     'whitenessCriteria':    Cell array containing names of residual whiteness
%                             test criteria to evaluate. See [1, 2] for details.
%                             Possible Values: {'Ljung-Box','ACF','Box-Pierce','Li-McLeod'}
%                             Default Value  : all
%                             Data Input Type: cell array
%
%
%     'checkWhiteness':       Whether or not to check whiteness.
%                             Default Value  : true
%                             Data Input Type: boolean
%
%     'checkConsistency':     Whether or not to check consistency. See [1,3]
%                             for details.
%                             Default Value  : true
%                             Data Input Type: boolean
%
%     'checkStability':       Whether or not to check stability. See
%                             [1-3] for details.
%                             Default Value  : true
%                             Data Input Type: boolean
%
%     'alpha':                significance level for determining whiteness
%                             Data Input Range: [0 1]
%                             Default Value   : 0.05
%                             Data Input Type : real number (double)
%
%     'prctWinToSample':      percent of time windows to randomly select
%                             Data Input Range: [0 100]
%                             Default Value   : 100
%                             Data Input Type : real number (double)
%
%     'verb':                 verbosity level (0=no output, 1=text, 2=gui)
%
%
% Output:
%
%     whitestats:             Structure containing whiteness statistics.
%                             See est_checkMVARWhiteness() for details on
%                             structure format
%
%     PC:                     Vector of percent consistency estimates for
%                             each window.
%
%     stability:              Vector of stability estimates for each window
%
% See Also: est_checkMVARWhiteness(), est_checkMVARStability(),
%           est_checkMVARConsistency, pop_est_fitMVAR()
%
%
% References:
%
% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):
%   Theoretical Handbook and User Manual. Chapter 3.6 and 6.
%   Available at: http://www.sccn.ucsd.edu/wiki/Sift
%
% [2] Lutkepohl, H. (2007) New Introduction to Time Series Analysis.
%   Springer.
%
% [3] Ding M, Bressler SL, Yang W, Liang H (2000) Short-window spectral
%   analysis of cortical event-related potentials by adaptive multivariate
%   autoregressive modeling: data preprocessing, model validation, and
%   variability assessment. Biol. Cybern. 83:35-45
%
% Author: Tim Mullen, 2010, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

% This function is part of the Source Information Flow Toolbox (SIFT)
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

verb = arg_extract(varargin,{'verb','VerbosityLevel'},[],0);
prctWinToSample = arg_extract(varargin,{'prctWinToSample','WindowSamplePercent'},[],100);

g = arg_define([0 1],varargin, ...
    arg_norep({'EEG','ALLEEG'},mandatory,[],'EEGLAB dataset'), ...
    arg_subtoggle({'checkWhiteness','CheckResidualWhiteness'},{'verb',verb,'prctWinToSample',prctWinToSample},@est_checkMVARWhiteness,sprintf('Check residual whiteness. \nResiduals are "white" if they are uncorrelated.'),'cat','Validation Methods','suppress',{'prctWinToSample','VerbosityLevel'}), ...
    arg_subtoggle({'checkResidualVariance','CheckResidualVariance'},{'verb',verb,'prctWinToSample',prctWinToSample,'whitenessCriteria',{}},@est_checkMVARWhiteness,'Compute residual autocorrelation and variance','cat','Validation Methods','suppress',{'WhitenessCriteria','MultipleComparisonsCorrection','SignificanceLevel','prctWinToSample','VerbosityLevel'}), ...
    arg_subtoggle({'checkConsistency','CheckConsistency'},{'verb',verb,'prctWinToSample',prctWinToSample},@est_checkMVARConsistency,sprintf('Check model consistency. \nA "consistent" model is able to generate data with similar covariance structure as the original data'),'cat','Validation Methods','suppress',{'prctWinToSample','VerbosityLevel'}), ...
    arg_subtoggle({'checkStability','CheckStability'},{'verb',verb},@est_checkMVARStability,sprintf('Check model stability. \nA stable model is one that cannot "blow up" (e.g. generate data that increases to infinity) -- this is a requirement for causal modeling.'),'cat','Validation Methods','suppress',{'prctWinToSample','VerbosityLevel'}), ...
    arg({'prctWinToSample','WindowSamplePercent'},100,[1 100],'Percent of windows to sample','cat','Data Reduction'), ...
    arg_nogui({'winStartIdx','WindowStartIndices'},[],[],'Starting indices for windows. This is a vector of sample points (start of windows) at which to estimate windowed VAR model. Default is empty (use all windows)','cat','Data Reduction'), ...
    arg({'verb','VerbosityLevel'},2,{int32(0) int32(1) int32(2)},'Verbosity level. 0 = no output, 1 = text, 2 = graphical'), ...
    arg({'plot','PlotResults'},true,[],'Plot results') ...
    );

% commit EEG variable to workspace
% [data g] = hlp_splitstruct(g,{'g.EEG'});
% arg_toworkspace(data);
% clear data;

% initialize default output
[whitestats PCstats stabilitystats residualstats] = deal([]);

if ~isfield(g.EEG.CAT,'MODEL')
    error('est_validateMVAR:NoModel','g.EEG.CAT.MODEL must be present in the dataset');
else
    MODEL = g.EEG.CAT.MODEL;
end

% determine which windows to use
if isempty(g.winStartIdx)
    % starting point of each window (points)
    g.winStartIdx  = round(MODEL.winStartTimes*g.EEG.srate)+1;
end

if g.prctWinToSample<100
    % randomly select percentage of windows to work with
    randwin = randperm(length(g.winStartIdx));
    randwin = sort(randwin(1:ceil(length(g.winStartIdx)*g.prctWinToSample/100)));
    g.winStartIdx = g.winStartIdx(randwin);
    g.prctWinToSample = 100;
end

if g.verb==2
    % create waitbar
    waitbarTitle = sprintf('Validating Model %s...', ...
        fastif(isempty(g.EEG.condition),'',['for ' g.EEG.condition]));

    multiWaitbar(waitbarTitle,'Reset');
    multiWaitbar(waitbarTitle,'ResetCancel',true);
    multiWaitbar(waitbarTitle, ...
        'Color', hlp_getNextUniqueColor('reset'), ...
        'CanCancel','on', ...
        'CancelFcn',@(a,b) disp('[Cancel requested. Please wait...]'));
    %     wb_cleanup = onCleanup(@() multiWaitbar(waitbarTitle,'Close'));
end

% determine number of checks we'll do (for progbar)
numchecks = sum([g.checkConsistency.arg_selection  ...
    g.checkWhiteness.arg_selection    ...
    g.checkStability.arg_selection    ...
    g.checkResidualVariance.arg_selection]);
curcheck  = 0;

% check residual whiteness
% -------------------------------------------------------------------------
if g.checkWhiteness.arg_selection
    [whitestats residualstats] = est_checkMVARWhiteness(...
                                    'EEG',g.EEG,                        ...
                                    'MODEL',MODEL,                      ...
                                     g.checkWhiteness,                  ...
                                    'winStartIdx',g.winStartIdx,        ...
                                    'prctWinToSample',g.prctWinToSample,...
                                    'verb',g.verb);
    if isempty(whitestats)
        % whiteness checks cancelled
        g.checkWhiteness.arg_selection = false;
        numchecks = numchecks - 1;
        curcheck  = curcheck  - 1;
    else
        winTimes = whitestats.winStartTimes;
    end
    if g.verb==2 && ~updateWaitbar(), return; end
end

% check residual variance
% -------------------------------------------------------------------------
if g.checkResidualVariance.arg_selection
    if ~g.checkWhiteness.arg_selection
        [~, residualstats] = est_checkMVARWhiteness(...
                                'EEG',g.EEG,                            ...
                                'MODEL',MODEL,                          ...
                                 g.checkResidualVariance,               ...
                                'whitenessCriteria',{},                 ...
                                'winStartIdx',g.winStartIdx,            ...
                                'prctWinToSample',g.prctWinToSample,    ...
                                'verb',g.verb);
    end
    % bookeeping
    if isempty(residualstats)
        % whiteness checks cancelled
        g.checkResidualVariance.arg_selection = false;
        numchecks = numchecks - 1;
        curcheck  = curcheck  - 1;
    else
        winTimes = residualstats.winStartTimes;
    end
    if g.verb==2 && ~updateWaitbar(), return; end
end

% check model consistency
% -------------------------------------------------------------------------
if g.checkConsistency.arg_selection
    PCstats = est_checkMVARConsistency(...
                    'EEG',g.EEG,                        ...
                    'MODEL',MODEL,                      ...
                     g.checkConsistency,                ...
                    'winStartIdx',g.winStartIdx,        ...
                    'prctWinToSample',g.prctWinToSample,...
                    'verb',g.verb);
    % bookeeping
    if isempty(PCstats)
        % consistency checks cancelled
        g.checkConsistency.arg_selection = false;
        numchecks = numchecks - 1;
        curcheck  = curcheck  - 1;
    else
        winTimes = PCstats.winStartTimes;
    end
    if g.verb==2 && ~updateWaitbar(), return; end
end

% check model stability
% -------------------------------------------------------------------------
if g.checkStability.arg_selection
    stabilitystats = est_checkMVARStability(...
                        'EEG',g.EEG,                        ...
                        'MODEL',MODEL,                      ...
                         g.checkStability,                  ...
                        'winStartIdx',g.winStartIdx,        ...
                        'prctWinToSample',g.prctWinToSample,...
                        'verb',g.verb);
    % bookeeping
    if isempty(stabilitystats)
        % consistency checks cancelled
        g.checkStability.arg_selection = false;
        numchecks = numchecks - 1;
        curcheck  = curcheck  - 1;
    else
        winTimes = stabilitystats.winStartTimes;
    end
    if g.verb==2 && ~updateWaitbar(), return; end
end

% plot results
% -------------------------------------------------------------------------
if g.plot && numchecks > 0
    if g.checkWhiteness.arg_selection
        whitenessCriteria = g.checkWhiteness.whitenessCriteria;
    else
        whitenessCriteria = {};
    end
    vis_plotModelValidation({whitestats},{PCstats},{stabilitystats}, ...
        'whitenessCriteria',whitenessCriteria,                       ...
        'checkWhiteness',g.checkWhiteness.arg_selection,             ...
        'checkConsistency',g.checkConsistency.arg_selection,         ...
        'checkStability',g.checkStability.arg_selection,             ...
        'conditions',{g.EEG.condition},                              ...
        'windowTimes',winTimes);
end

% % clean up
if g.verb==2
    multiWaitbar(waitbarTitle,'Close');
end

    % subfunction updateWaitbar
    % ---------------------------------------------------------------------
    function nocancel = updateWaitbar()
        nocancel = true;
        curcheck = curcheck + 1;
        drawnow;
        cancel = multiWaitbar(waitbarTitle,curcheck/numchecks);
        if cancel && hlp_confirmWaitbarCancel(waitbarTitle, ...
                     'Are you sure you want to cancel all validation?')
            nocancel = false;
            return;
        end
    end

end


% .*  Array multiply.
%    X.*Y denotes element-by-element multiplication. X and Y must have
%    compatible sizes. In the simplest cases, they can be the same size or
%    one can be a scalar. Two inputs have compatible sizes if, for every
%    dimension, the dimension sizes of the inputs are either the same or one
%    of them is 1.
%
%    C = TIMES(A,B) is called for the syntax 'A .* B' when A or B is an
%    object.
%
%    See also MTIMES.
%
%    Reference page in Doc Center
%       doc times
%
%    Other functions named times
%
%       calendarDuration/times    fints/times       tall/times
%       categorical/times         gpuArray/times    timeseries/times
%       codistributed/times       sym/times         ts/times
%       duration/times
%


function pstruct = tapas_hgf_ar1_binary_namep(pvec)
% --------------------------------------------------------------------------------------------------
% Copyright (C) 2012-2013 Christoph Mathys, TNU, UZH & ETHZ
%
% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public
% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version). For further details, see the file
% COPYING or <http://www.gnu.org/licenses/>.

pstruct = struct;

l = (length(pvec)+1)/6;

if l ~= floor(l)
    error('tapas:hgf:UndetNumLevels', 'Cannot determine number of levels');
end

pstruct.mu_0      = pvec(1:l);
pstruct.sa_0      = pvec(l+1:2*l);
pstruct.phi       = pvec(2*l+1:3*l);
pstruct.m         = pvec(3*l+1:4*l);
pstruct.ka        = pvec(4*l+1:5*l-1);
pstruct.om        = pvec(5*l:6*l-1);

return;


function xyzankurAnim(X, fps)

% XYZANKURANIM Animate point cloud of stick man from Agarwal & Triggs dataset.
% FORMAT
% DESC animates a matrix of x,y,z point clound positions representing the
% motion of the figure used to generate the silhouttes for Agarwal &
% Triggs silhouette data.
% ARG y : the data to animate.
% ARG fps : the number of frames per second to animate (defaults to 24).
%
% SEEALSO : xyzankurVisualise, xyzankurModify
%
% COPYRIGHT : Carl Henrik Ek and Neil Lawrence, 2008

% MOCAP

if(nargin<3)
  fps = 24;
  if(nargin<2)
    fid = 1;
    if(nargin<1)
      error('Too few arguments');
    end
  end
end

for(i = 1:1:size(X,1))
  if(i==1)
    handle = xyzankurVisualise(X(i,:),1);
  else
    xyzankurModify(handle,X(i,:));
  end
  pause(1/fps);
end


function [ vid_locs, bboxes, gts_all, invalid_frames ] = CollectTestData( db_root, bb_root, extra_dir )
%COLLECTTESTDATA Summary of this function goes here
%   Detailed explanation goes here

    cat_1 = [ 114, 124, 125, 126, 150, 158, 401, 402, 505, 506, 507, 508, 509, 510, 511, 514, 515, 518, 519, 520, 521, 522, 524, 525, 537, 538, 540, 541, 546, 547, 548];
    cat_2 = [203, 208, 211, 212, 213, 214, 218, 224, 403, 404, 405, 406, 407, 408, 409, 412, 550, 551, 553];
    cat_3 = [410, 411, 516, 517, 526, 528, 529, 530, 531, 533, 557, 558, 559, 562];

    all_test = cat(2, cat_1, cat_2, cat_3);

    vid_locs = cell(numel(all_test),1);
    bboxes = cell(numel(all_test),1);
    gts_all = cell(numel(all_test),1);
    invalid_frames = cell(numel(all_test),1);
    for i=1:numel(all_test)
        vid_locs{i} = [db_root '/', num2str(all_test(i)), '/vid.avi'];
        bboxes{i} = dlmread([bb_root,  num2str(all_test(i)), '_dets.txt'], ',');

        %% Grab the ground truth
        fps_all = dir([db_root, '/', num2str(all_test(i)), '/annot/*.pts']);
        gt_landmarks = zeros([68, 2, size(fps_all)]);
        for k = 1:size(fps_all)
            gt_landmarks_frame = dlmread([db_root, '/', num2str(all_test(i)), '/annot/', fps_all(k).name], ' ', 'A4..B71');
            gt_landmarks(:,:,k) = gt_landmarks_frame;
        end
        % Remove unreliable frames
        if(exist([extra_dir, '/', num2str(all_test(i)), '.mat'], 'file'))
            inv_frames = load([extra_dir, '/', num2str(all_test(i)), '.mat']);

            gt_landmarks(:,:,int32(inv_frames.error)) = [];
            invalid_frames{i} = inv_frames.error;
        end
        gts_all{i} = gt_landmarks;
    end

end


function proposals = calcselective_searchForIm( input,ssconfig)

colorTypes=ssconfig.params.colorTypes;
simFunctionHandles=ssconfig.params.simFunctionHandles;
ks=ssconfig.params.ks;
im_width=ssconfig.params.imWidth;
sigma=ssconfig.params.sigma;
minBoxWidth =ssconfig.params.minBoxWidth;

if(isstr(input))
        im = im2uint8(imread(input));
else
        im = im2uint8(input); % Just to make input consistent
end
if(size(im, 3) == 1)
        im=repmat(im,[1,1,3]);
end
if ~isfield(ssconfig.params, 'imWidth')
	im_width = [];
        scale = 1;
else
        scale = size(im, 2) / im_width;
end

if scale ~= 1
        im = imresize(im, [NaN im_width]);
end
idx = 1;
for j = 1:length(ks)
        k = ks(j); % Segmentation threshold k
        minSize = k; % We set minSize = k
        for n = 1:length(colorTypes)
        	colorType = colorTypes{n};
                [boxesT{idx} blobIndIm blobBoxes hierarchy priorityT{idx}] = ...
                Image2HierarchicalGrouping(im, sigma, k, minSize, colorType, simFunctionHandles);
                idx = idx + 1;
        end
end
boxes = cat(1, boxesT{:}); % Concatenate boxes from all hierarchies
priority = cat(1, priorityT{:}); % Concatenate priorities

% Do pseudo random sorting as in paper
priority = priority .* rand(size(priority));
[priority sortIds] = sort(priority, 'ascend');
boxes = boxes(sortIds,:);

boxes = FilterBoxesWidth(boxes, minBoxWidth);
boxes = BoxRemoveDuplicates(boxes);

if scale ~= 1
	boxes = (boxes - 1) * scale + 1;
end

if(isfield(ssconfig.opts,'numProposals'))
        numProposals=ssconfig.opts.numProposals;
        if(size(boxes,1)>=numProposals)
        	boxes=boxes(1:numProposals,:);
        else
                fprintf('Only %d proposals were generated for input image \n',size(boxes,1));
        end
end

% reset boxes to xmin ymin xmax ymnx
boxes=[boxes(:,2) boxes(:,1) boxes(:,4) boxes(:,3)];
proposals.boxes=boxes;


%MDL_UR5 Create model of Universal Robotics UR3 manipulator
%
% MDL_UR5 is a script that creates the workspace variable ur3 which
% describes the kinematic characteristics of a Universal Robotics UR3 manipulator
% using standard DH conventions.
%
% Also define the workspace vectors:
%   qz         zero joint angle configuration
%   qr         arm along +ve x-axis configuration
%
% Reference::
% - https://www.universal-robots.com/how-tos-and-faqs/faq/ur-faq/actual-center-of-mass-for-robot-17264/
%
% Notes::
% - SI units of metres are used.
% - Unlike most other mdl_xxx scripts this one is actually a function that
%   behaves like a script and writes to the global workspace.
%
% See also mdl_ur5, mdl_ur10, mdl_puma560, SerialLink.

% MODEL: Universal Robotics, UR3, 6DOF, standard_DH

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

function r = mdl_ur3()

    deg = pi/180;

    % robot length values (metres)
    a = [0, -0.24365, -0.21325, 0, 0, 0]';

    d = [0.1519, 0, 0, 0.11235, 0.08535, 0.0819]';

    alpha = [1.570796327, 0, 0, 1.570796327, -1.570796327, 0]';

    theta = zeros(6,1);

    DH = [theta d a alpha];

    mass = [2, 3.42, 1.26, 0.8, 0.8, 0.35];

    center_of_mass = [
        0,-0.02, 0
        0.13, 0, 0.1157
        0.05, 0, 0.0238
        0, 0, 0.01
        0, 0, 0.01
        0, 0, -0.02 ];

    % and build a serial link manipulator

    % offsets from the table on page 4, "Mico" angles are the passed joint
    % angles.  "DH Algo" are the result after adding the joint angle offset.

    robot = SerialLink(DH, ...
        'name', 'UR3', 'manufacturer', 'Universal Robotics');

    % add the mass data, no inertia available
    links = robot.links;
    for i=1:6
        links(i).m = mass(i);
        links(i).r = center_of_mass(i,:);
    end

    % place the variables into the global workspace
    if nargin == 1
        r = robot;
    elseif nargin == 0
        assignin('caller', 'ur3', robot);
        assignin('caller', 'qz', [0 0 0 0 0 0]); % zero angles
        assignin('caller', 'qr', [180 0 0 0 90 0]*deg); % vertical pose as per Fig 2
    end
end


function whl = Find_RB_LED(file)

% This code tests an approximate median filter for separating out the red
% and blue leds mounted on top of the subjects head
% I was using the DataMax system, which was synced using a red LED. Hence,
% I am tracking the x,y position of the animal as well as when the sync
% light comes on.

%file       = 'Mouse12-120808-01.mpg';
%[~,name,~] = fileparts(file);
% Create Text file for writing out LED locations and sync trigger
%fid        = fopen(sprintf('%s.whl',name),'w+');
% Creater readerobj of file
readerobj  = VideoReader(file);
width      = readerobj.Width;
height     = readerobj.Height;
threshF    = 150;    % threshold on foreground pixel intensity
% Initial frame
Fint       = 1;

% Initialize grid for locating centroid of LED
[X,Y] = meshgrid(1:width,1:height);

% Initialize background as a grayscale image of the first frame
bg_bw     = rgb2gray(read(readerobj,Fint));

% Initialize foreground image and difference image
fg          = zeros(size(bg_bw));
fr_diff     = zeros(size(bg_bw));

% Initialize color mask
rmask  = zeros(height,width,3,'uint8');
bmask  = zeros(height,width,3,'uint8');

% Initialize fr in case first frame reading returns error
fr  = zeros(height,width,3,'uint8');

% Initialize whl matrix
whl = zeros(readerobj.NumberOfFrames,4);

for i = Fint:readerobj.NumberOfFrames
%     % Initialize red and blue LEDS as missing (=> -1)
    Red = [-1 -1];
    Blue = [-1 -1];

    %fprintf('%i',i);

    % Access frame of interest - if error (mostly for the last frames,
    % don't know why), will analyze previous frame...
    try
        fr    = read(readerobj,i);
    end

    % Spatial filter
    filt = fspecial('average',50);
    frs = imfilter(fr,filt);
    fr2 = fr-frs;

    filt = fspecial('average',10);
    fr3 = imfilter(fr2, filt);

    % convert frame to thresholdable
%     fr_bw = rgb2gray(fr);
    fr_r = double(fr2(:,:,1));
    fr_b = double(fr2(:,:,3));
    template = zthreshimage(rgb2gray(fr2),0.1);%pixels that aren't too dim after filtering... ie worth paying attention to
    fr_r_ok = fr_r;
    fr_b_ok = fr_b;
    fr_b_ok(find(~template)) = 0;
    fr_r_ok(find(~template)) = 0;

    rbdiff = fr_r-fr_b;
    brdiff = fr_b-fr_r;
    %would have to brightness threshold first
    rbratio = log(fr_r_ok./fr_b_ok);
    brratio = log(fr_b_ok./fr_r_ok);

    % bright enough in each color
    zbright_r = zthreshimage(fr_r,1);
    zbright_b = zthreshimage(fr_b,1);
    absbright_r = threshimage(fr_r,60);
    absbright_b = threshimage(fr_b,60);

    % color selective enough by diff
    zdiffsel_r = zthreshimage(rbdiff,3);% diff above z score
    zdiffsel_b = zthreshimage(brdiff,3);
    absdiffsel_r = threshimage(rbdiff,20);% diff above absolute level
    absdiffsel_b = threshimage(brdiff,20);

    % color selective enough by ratio
    zratsel_r = zthreshimage(rbratio,1);% diff above z score
    zratsel_b = zthreshimage(brratio,1);

%     ratsel_r = im2bw(rbratio,.51);% above 55st %ile ratio
%     ratsel_b = im2bw(brratio,.51);% above 51st %ile ratio

    % bright and selective enough
%     combo_r = diffsel_r.*ratsel_r.*bright_r;
%     combo_b = diffsel_b.*ratsel_r.*bright_b;
    combo_r = zbright_r.*absbright_r.*zdiffsel_r.*absdiffsel_r.*zratsel_r;
    combo_b = zbright_b.*absbright_b.*zdiffsel_b.*absdiffsel_b.*zratsel_b;

% keep only the largest object in each thresholded image
    % blue
    [l,numobjs] = bwlabel(combo_b);
    if numobjs>0
        numeach = zeros(1,numobjs);
        for a = 1:numobjs
            numeach(a) = sum(l(:)==a);
        end
        [~,bgroup] = max(numeach);
        pl = regionprops(l,'PixelList');
        Blue = round(mean(pl(bgroup).PixelList,1));
    end
    % red
    [l,numobjs] = bwlabel(combo_r);
    if numobjs>0
        numeach = zeros(1,numobjs);
        for a = 1:numobjs
            numeach(a) = sum(l(:)==a);
        end
        [~,rgroup] = max(numeach);
        pl = regionprops(l,'PixelList');
        Red = round(mean(pl(rgroup).PixelList,1));
    end

    whl(i,:) = [Red(1),Red(2),Blue(1),Blue(2)];

    % End processing time, now outputting/plotting
    if mod(i,100)==0 & i<1000
        ixr = whl(i-99:i,1);
        ixr = ixr>-1;
        ixb = whl(i-99:i,3);
        ixb = ixb>-1;
        ok = ixr.*ixb;
        figure(1),clf,
        subplot(3,1,1);imshow(uint8(fr));title('If looks wrong, Ctrl+C and change threshold \!!')

        subplot(3,3,5);imagesc(cat(3,combo_r,zeros(size(combo_r)),combo_b));
        xlim([0 size(fr,1)])
        ylim([0 size(fr,2)])
        axis tight

        subplot(3,3,8)
            plot(whl(i-99:i,1),whl(i-99:i,2),'r.')
            hold on
            plot(whl(i-99:i,3),whl(i-99:i,4),'b.')
            mx = mean([whl(i-100+find(ok),1) whl(i-100+find(ok),3)],2);
            my = mean([whl(i-100+find(ok),2) whl(i-100+find(ok),4)],2);
            plot(mx,my,'Marker','.','color',[0.5 0.5 0.5],'LineStyle','none')
            xlim([0 size(fr,1)])
            ylim([0 size(fr,2)])
            axis ij
        fprintf('Detection of Red LED failed %i times (%i times for the blue LED) in the last 100 frames\n',sum(~ixr),sum(~ixb));
    end
    if i == 1;
        h = waitbar(i/readerobj.NumberOfFrames);
    else
        waitbar(i/readerobj.NumberOfFrames,h);
    end

end
close(h)


function addAllenCtxOutlines(bregma, lambda, lineColor, pixSize)
% to get bregma/lambda, do:
% >> figure; imagesc(myImg); axis image;
% then use the cursor to click on bregma, then swap the coords (if cursor
% says X=xx and Y=yy, then bregma is [yy, xx]).
% or leave blank to get prompted with ginput.
% lambda just needs to be on the midline posterior to bregma.
if isempty(bregma)
    fprintf(1, 'click bregma\n');
    [x,y] = ginput(1);
    bregma = [y,x]
    fprintf(1, 'click lambda\n');
    [x,y] = ginput(1);
    lambda = [y,x]
end

apDir = lambda-bregma; apDir = apDir./norm(apDir);

if nargin<4
    pixSize = 0.0217; % mm/pix. This is for PCO edge 5.5 with 0.6x mag (as kilotrode)
end

ccfbregma = allenCCFbregma()/100/pixSize;

load(fullfile(fileparts(mfilename('fullpath')), 'ctxOutlines.mat'));

hold on;
for q = 1:numel(coords) % coords is from ctxOutlines.mat

    % these are in 10um voxel coordinates, so first convert to mm, then to
    % pixels
    cx = coords(q).x/100/pixSize;
    cy = coords(q).y/100/pixSize;

    % to do this transformation, first subtract bregma to zero, then
    % rotate, then add back the other bregma
    cx = cx-ccfbregma(3); cy = cy-ccfbregma(1);

    T = affineMat.rot(-atan(apDir(2)/apDir(1)));

    newc = T*[cx cy ones(size(cx))]';
    cx = newc(1,:)'; cy = newc(2,:)';

    cx = cx+bregma(2); cy = cy+bregma(1);

    plot(cx,cy, 'LineWidth', 1.0, 'Color', lineColor);
    hold on;
end