AU_dir = 'D:/Databases/DISFA/ActionUnit_Labels/';

aus = [1,2,4,5,6,9,12,15,17,20,25,26];

subjects = dir([AU_dir, 'SN*']);

% Store all of the AU directories in a cell
input_label_dirs = cell(numel(subjects), 1);
for i=1:numel(subjects)
    input_label_dirs{i} = [AU_dir, subjects(i).name, '/', subjects(i).name];
end

for user=1:numel(subjects)

    testing_label_files = input_label_dirs(user);

    training_label_files = setdiff(input_label_dirs, testing_label_files);

    training_labels_all = [];

    testing_labels_all = [];

    % First extract AU information
    for au=aus

        % Extract all of the AUs from the current user
        [training_labels, training_vid_inds_all, training_frame_inds_all] = extract_au_labels(training_label_files, au);
        [testing_labels, testing_vid_inds_all, testing_frame_inds_all] = extract_au_labels(testing_label_files, au);

        training_labels_all = cat(2, training_labels_all, training_labels);
        testing_labels_all = cat(2, testing_labels_all, testing_labels);

    end

    % File lists for each of the AUs
    for au_ind=1:numel(aus)

        % extract the interesting frames for training, the interesting ones
        % are the AU

        positive_samples = training_labels_all(:,au_ind) > 0;

        active_samples = sum(training_labels_all,2) > 10;

        % Remove neighboring images as they are not very informative
        negative_samples = sum(training_labels_all,2) == 0;
        neg_inds = find(negative_samples);
        neg_to_use = randperm(numel(neg_inds));
        % taking a number of neutral samples that bring the positive and
        % negative samples to a balanced level
        neg_to_use = neg_inds(neg_to_use(1:(2*sum(positive_samples) - sum(active_samples | positive_samples))));
        negative_samples(:) = false;
        negative_samples(neg_to_use) = true;

        % Collect all the data for training now
        training_samples = positive_samples | active_samples | negative_samples;

        % Create a training file list file
        f_train_file_list = fopen(sprintf('%s/%s_au%02d_filelist_train.txt', 'single_au_class', subjects(user).name, aus(au_ind)), 'w');

        sample_inds_train = find(training_samples);

        for sample_ind = sample_inds_train'

            img_file_l = sprintf('../../LeftVideo%s_comp/frame_det_%06d.png', training_vid_inds_all{sample_ind}, training_frame_inds_all(sample_ind));
            img_file_r = sprintf('../../RightVideo%s_comp/frame_det_%06d.png', training_vid_inds_all{sample_ind}, training_frame_inds_all(sample_ind));

            au_class = training_labels_all(sample_ind, au_ind) > 1;

            fprintf(f_train_file_list, '%s %d\r\n', img_file_l, au_class);
            fprintf(f_train_file_list, '%s %d\r\n', img_file_r, au_class);

        end
        fclose(f_train_file_list);

         % Create a testing file list file
        f_train_file_list = fopen(sprintf('%s/%s_au%02d_filelist_test.txt', 'single_au_class', subjects(user).name, aus(au_ind)), 'w');

        testing_samples = true(size(testing_labels_all,1),1);
        sample_inds_test = find(testing_samples);

        for sample_ind = sample_inds_test'

            img_file_l = sprintf('../../LeftVideo%s_comp/frame_det_%06d.png', testing_vid_inds_all{sample_ind}, testing_frame_inds_all(sample_ind));
            img_file_r = sprintf('../../RightVideo%s_comp/frame_det_%06d.png', testing_vid_inds_all{sample_ind}, testing_frame_inds_all(sample_ind));

            au_class = testing_labels_all(sample_ind, au_ind) > 1;

            fprintf(f_train_file_list, '%s %d\r\n', img_file_l, au_class);
            fprintf(f_train_file_list, '%s %d\r\n', img_file_r, au_class);

        end
        fclose(f_train_file_list);

    end

end


function inpu2()
%inpu2
    %  This scriptfile ask for several selection parameters that can be set
    %  for part of the analysis. The original input parameters can be reset using
    %  the  Reset button in the main figure map
    %  Changes ZG.newt2
    %
    % make the interface
    %
    ZG=ZmapGlobal.Data;
    report_this_filefun(mfilename('fullpath'));
    ZG.newt2 = catalog_overview(ZG.newt2);
end
%{
h=zmap_message_center();
message_window_candidates = findobj('Name','Message Window');

mess = max([message_window_candidates.Number]);
clear message_window_candidates
if isempty(mess) == 1; mess = 1 ; end
figure_w_normalized_uicontrolunits(mess)

mint = min(ZG.newt2.Date);
maxt = max(ZG.newt2.Date);
clf
set(gca,'visible','off');
set(gcf,'Units','pixel','pos',[20 fipo(4)-350 400 300])
set(gcf,'Name','Selection Parameters');

inp5t=uicontrol('Style','edit','Position',[.70 .70 .22 .06],...
    'Units','normalized','String',char(min(ZG.newt2.Date)),...
    'Callback','mint=str2double(inp5t.String); inp5t.String=num2str(mint,6);');

inp6t=uicontrol('Style','edit','Position',[.70 .60 .22 .06],...
    'Units','normalized','String',char(max(ZG.newt2.Date)),...
    'Callback','maxt=str2double(inp6t.String); inp6t.String=num2str(maxt,6);');

inp5=uicontrol('Style','edit','Position',[.70 .50 .22 .06],...
    'Units','normalized','String',num2str(minma2),...
    'Callback','minma2=str2double(inp5.String); inp5.String=num2str(minma2);');

inp6=uicontrol('Style','edit','Position',[.70 .40 .22 .06],...
    'Units','normalized','String',num2str(maxma2),...
    'Callback','maxma2=str2double(inp6.String); inp6.String=num2str(maxma2);');

inp7=uicontrol('Style','edit','Position',[.30 .20 .10 .06],...
    'Units','normalized','String',num2str(minde),...
    'Callback','minde=str2double(inp7.String); inp7.String=num2str(minde);');

inp8=uicontrol('Style','edit','Position',[.60 .20 .10 .06],...
    'Units','normalized','String',num2str(maxde),...
    'Callback','maxde=str2double(inp8.String); inp8.String=num2str(maxde);');

close_button=uicontrol('Style','Pushbutton',...
    'Position',[.65 .02 .20 .10 ],...
    'Units','normalized','Callback',@(~,~)zmap_Message_center(),'String','cancel');

go_button=uicontrol('Style','Pushbutton',...
    'Position',[.35 .02 .20 .10 ],...
    'Units','normalized',...
    'Callback','zmap_message_center(); magcumu',...
    'String','Go');

txt6 = text(...
    'Color',[0 0 0 ],...
    'EraseMode','normal',...
    'Position',[0.02 0.76 0 ],...
    'Rotation',0 ,...
    'FontSize',ZmapGlobal.Data.fontsz.s ,...
    'FontWeight','bold',...
    'String','Minimum Time: ');

txt6 = text(...
    'Color',[0 0 0 ],...
    'EraseMode','normal',...
    'Position',[0.02 0.64 0 ],...
    'Rotation',0 ,...
    'FontSize',ZmapGlobal.Data.fontsz.s ,...
    'FontWeight','bold',...
    'String','Maximum Time: ');

txt3 = text(...
    'Color',[0 0 0 ],...
    'EraseMode','normal',...
    'Position',[0.15 0.98 0 ],...
    'Rotation',0 ,...
    'FontSize',ZmapGlobal.Data.fontsz.m ,...
    'FontWeight','bold',...
    'String','Cut the catalog');

txt6 = text(...
    'Color',[0 0 0 ],...
    'EraseMode','normal',...
    'Position',[0.02 0.52 0 ],...
    'Rotation',0 ,...
    'FontSize',ZmapGlobal.Data.fontsz.s ,...
    'FontWeight','bold',...
    'String','Minimum Magnitude: ');

txt6 = text(...
    'Color',[0 0 0 ],...
    'EraseMode','normal',...
    'Position',[0.02 0.39 0 ],...
    'Rotation',0 ,...
    'FontSize',ZmapGlobal.Data.fontsz.s ,...
    'FontWeight','bold',...
    'String','Maximum Magnitude: ');

txt7 = text(...
    'Color',[0 0 0 ],...
    'EraseMode','normal',...
    'Position',[0.02 0.22 0 ],...
    'Rotation',0 ,...
    'FontSize',ZmapGlobal.Data.fontsz.s ,...
    'FontWeight','bold',...
    'String','                 Min Depth                    Max Depth   ');

set(gcf,'visible','on')
%}


function [msh, lights] = meshVisualize(msh,id)
% Visualize a VTK mesh of the cortical surface using mrMesh
%
%  [msh] = meshVisualize(msh,[id]);
%
% This mesh structure must contain vertices and faces.
%
% A msh is input and the mesh is displayed in mrMesh window number id.  If
% no id number is sent in a new window is opened.
%
% If the input is an old style mesh, it is changed updated the best we can.
%
% Questions:
%    What are the minimal fields required for this msh to run with mrMesh?
%    Can we pass in a modified gifti mesh and convert it to the proper
%    fields and have this run?
%
% Example:
%  fName ='X:\anatomy\nakadomari\left\20050901_fixV1\left.Class';
%  fName ='/biac1/wandell/data/anatomy/dougherty/t1_class_left.nii.gz';
%  msh = meshBuildFromClass(fName);
%  msh = meshSmooth(msh);
%  meshVisualize(msh);
%
% (c) Stanford Vista Team

backColor = [1,1,1];

if notDefined('msh'), error('The mesh is required.'); end
% if ieNotDefined('mmPerVox'), mmPerVox = [1 1 1]; end
if notDefined('host'), host = 'localhost'; end
if notDefined('id'), id = -1; end

% Set initial parameters for the mesh.
if isempty(meshGet(msh,'host')), msh = meshSet(msh,'host',host); end
if isempty(meshGet(msh,'id')),   msh = meshSet(msh,'id',id); end

% If the window is already open, no harm is done.
if mrmCheckServer, mrMesh(meshGet(msh,'host'),meshGet(msh,'id'),'close'); end
msh = mrmInitHostWindow(msh);

% Initializes the mesh
[msh, lights] = mrmInitMesh(msh,backColor);

return;


function colorbarDataIndex = findColorbarData(obj, colorbarIndex, colorbarData)

    if nargin == 2

        %locate index of data associated with colorbar
        colorbarDataIndex = find( ...
            arrayfun( @(x)eq(x.AssociatedAxis, ...
                            obj.State.Colorbar(colorbarIndex).AssociatedAxis), ...
                            obj.State.Plot ...
                    ), ...
            1 );

        %if no matching data index found
        if isempty(colorbarDataIndex)
            colorbarDataIndex = max(min(colorbarIndex,obj.State.Figure.NumPlots),1);
        end

    elseif nargin == 3
        c = 1; a = 1;
        allAxesIndex = zeros(length(colorbarData.Parent.Children), 1);

        for n = 1:length(colorbarData.Parent.Children)
            if strcmp(colorbarData.Parent.Children(n).Type, 'colorbar')
                allColorbarIndex(c) = n;
                c = c + 1;
            elseif strcmp(colorbarData.Parent.Children(n).Type, 'axes')
                allAxesIndex(n) = a;
                a = a + 1;
            end
        end

        colorbarAxisIndex = allColorbarIndex(colorbarIndex) + 1;
        colorbarAxisIndex = allAxesIndex(colorbarAxisIndex);
        colorbarDataIndex = obj.State.Figure.NumAxes - colorbarAxisIndex + 1;

        colorbarDataIndex = colorbarDataIndex;
    end

end


function [retDat] = set_y(dat,outp,ind,fInd)

%   data=set_y(DATA,Y) sets the Y matrix of data
%   data=set_y(DATA,Y,INDEXES) sets the Y matrix of data for given indexes

if nargin==2 | (isempty(ind)&isempty(fInd)),
  dat.Y=outp;
else
    if isempty(ind),
        ind = [1:size(outp,1)];
    end;
    if (nargin<4)|isempty(fInd),
        fInd = [1:size(outp,2)];
    end;
    dat.Y(ind,fInd)=outp;
end
retDat=dat;


function isdir_or_mkdir(p)

% ISDIR_OR_MKDIR Checks that a directory exists, or if not, creates the directory and
% all its parent directories.
%
% See also FOPEN_OR_ERROR

tok = tokenize(p, filesep);
if isempty(tok{1})
  tok{1} = filesep;
end
for i=1:numel(tok)
  d = fullfile(tok{1:i});
  if ~isfolder(d)
    ft_notice('creating directory %s', d);
    mkdir(d);
  end
end


function [ret]=realTime_startDirectServoCartesian( t_Kuka )
%% Syntax:
% realTime_startDirectServoCartesian( t_Kuka )

%% About:
% This function is used to turn on the direct servo function on the robot
% This function is for direct-servoing in Cartesian space, i.e. controlling the
% robot at EEF level.
% After starting the direct servo, using this function, you have to send
% the EEF target postitions using the function,
% ((sendEEfPosition)), refer also to the function
% ((realTime_stopDirectServoCartesian)).

%% Arreguments
% t_Kuka: is the TCP/IP connection object

% Copy right, Mohammad SAFEEA, 1st of April 2018

theCommand='stDcEEf_';
fprintf(t_Kuka, theCommand);
message=fgets(t_Kuka);

[ret]=checkAcknowledgment(message);
if ret==true
    disp('Acknowledge, realtime control turned on');
end

delay(0.5); % introduce some time delay, so the robot turns on the direct servo before starting the motion
end


function [ schema_struct ] = parse_sicd_schema( filename )
% PARSE_SICD_SCHEMA Parse SICD/CPHD schema XSD into a MATLAB structure
% It is MUCH faster to traverse through a MATLAB structure than DOM nodes,
% so we want to convert the schema info into a MATLAB structure before
% traversing through the SICD/CPHD XML.
%
% Author: Wade Schwartzkopf, NGA/IDT
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

% Open file
schema_root = xmlread(filename);
schema_root = schema_root.getDocumentElement;
schema_struct.ns = char(schema_root.getAttribute('xmlns'));

% Separate type definitions and master structure definition
for i=1:schema_root.getLength
    child=schema_root.item(i-1);
    if child.getNodeType == child.ELEMENT_NODE
        switch char(child.getNodeName)
            case {'xs:simpleType','xs:complexType','xs:group'} % Type definitions
                schema_struct.types.(char(child.getAttribute('name'))) = recursfun_schema(child);
            case 'xs:element' % Master node (should be onle one)
                schema_struct.master = recursfun_schema(child);
            otherwise
                % Should not be in other types of nodes in top level
                error('SICDXML2STRUCT:UNEXPECTED_NODE_TYPE','Unexpected node type in top level of XSD.');
        end
    end
end

    function output_struct = recursfun_schema(current_node)
        output_struct = struct();
        for j=1:current_node.getLength
            current_child=current_node.item(j-1);
            if current_child.getNodeType == current_child.ELEMENT_NODE
                switch char(current_child.getNodeName)
                    case 'xs:element'
                        name_str = char(current_child.getAttribute('name'));
                        type_str = char(current_child.getAttribute('type'));
                        if ~isempty(type_str)
                            output_struct.(name_str).SCHEMA_type = type_str;
                        else % Element with empty type.  Should have a structure defined within it.
                            output_struct.(name_str) = recursfun_schema(current_child);
                        end
                    case {'xs:restriction','xs:extension'}
                        output_struct = recursfun_schema(current_child); % Adds any attributes
                        output_struct.SCHEMA_type = char(current_child.getAttribute('base'));
                    case {'xs:simpleType','xs:simpleContent',...
                            'xs:complexType','xs:complexContent','xs:group'}
                        output_struct = recursfun_schema(current_child);
                    case {'xs:sequence','xs:choice','xs:all'}
                        output_struct = setstructfields(output_struct, recursfun_schema(current_child));
                    case {'xs:attribute'}
                        if isfield(output_struct,'SCHEMA_attributes')
                            output_struct.SCHEMA_attributes = ...
                                [output_struct.SCHEMA_attributes, ...
                                char(current_child.getAttribute('name'))];
                        else
                            output_struct.SCHEMA_attributes = ...
                                {char(current_child.getAttribute('name'))};
                        end
                    case {'xs:minInclusive','xs:maxInclusive',...
                            'xs:minExclusive','xs:maxExclusive',...
                            'xs:enumeration','xs:pattern'}
                        % These fields are expected, but we don't use them
                        % for anything.
                    otherwise
                        error('SICDXML2STRUCT:UNRECOGNIZED_NODE_TYPE','Unrecognized node type in XSD.');
                end
            end
        end
    end
end

% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////


function MimSaveAsMatlab(image_data, path, filename, reporting)
    % MimSaveAsMatlab. Saves an image as a Matlab matrix
    %
    %     Syntax
    %     ------
    %
    %         MimSaveAsMatlab(image_data, path, filename, reporting)
    %
    %             image_data      is a PTKImage (or PTKDicomImage) class containing the image
    %                             to be saved
    %             path, filename  specify the location to save the files.
    %             reporting       an object implementing CoreReportingInterface
    %                             for reporting progress and warnings
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    if ~isa(image_data, 'PTKImage')
        reporting.Error('MimSaveAsMatlab:InputMustBePTKImage', 'Requires a PTKImage as input');
    end

    full_filename = fullfile(path, filename);
    value = [];
    value.image = image_data.RawImage;
    MimDiskUtilities.Save(full_filename, value);
end


function X = expanded(F,state)

F = flatten(F);
if nargin == 1
    if length(F.LMIid) == 0
        X = [];
    else
        for i = 1:length(F.clauses)
            X(i,1) = F.clauses{i}.expanded;
        end
    end
else
    X = F;
    for i = 1:length(F.clauses)
        X.clauses{i}.expanded = state;
    end
end


function PrepareTrainData()

global param;

sceneFolder = param.trainingScenes;
outputFolder = param.trainingData;

[sceneNames, scenePaths, numScenes] = GetFolderContent(sceneFolder, [], true);

MakeDir(outputFolder);

for i = 1 : numScenes

    count = fprintf('Started working on scene %d of %d', i, numScenes);

    %%% reading input data
    curExpo = ReadExpoTimes(scenePaths{i});
    [curImgsLDR, curLabel] = ReadImages(scenePaths{i});

    %%% processing data
    [inputs, label] = ComputeTestExamples(curImgsLDR, curExpo, curLabel);

    %%% writing data
%     label=[];
%     inputs = ((curImgsLDR{1}));
%     inputs = cat(3, inputs, (curImgsLDR{2}));
%     inputs = cat(3, inputs, (curImgsLDR{3}));
    WriteTestExamples(inputs, label, [outputFolder, '/', sceneNames{i}, '.h5']);
%     WriteTestExamples(inputs, label, [outputFolder, '/', 'TrainSequence', num2str(i) '.h5']);

    fprintf(repmat('\b', [1, count]));
end

fprintf('Done\n\n');


function [opts, imdb] = os_setup(varargin)

global is_iasonas
if (exist('is_iasonas', 'var') ||isempty(is_iasonas) || ~is_iasonas)
    setup ;
end

opts.transf = {};
opts.seed = 1 ;
opts.batchSize = 128 ;
opts.useGpu = true ;
opts.regionBorder = 0.05 ;
opts.numDCNNWords = 64 ;
opts.numDSIFTWords = 256 ;
opts.numSamplesPerWord = 1000 ;
opts.printDatasetInfo = false ;
opts.excludeDifficult = true ;
opts.encoders = {struct('type', 'rcnn', 'opts', {})} ;
opts.dataset = 'os' ;
opts.osDir = 'data/os' ;
opts.fmdDir = 'data/fmd' ;
opts.dtdDir = 'data/dtd';
opts.kthDir = 'data/kth';
opts.alotDir = 'data/alot';
opts.mitDir = 'data/mit_indoor';
opts.msrcDir = 'data/msrc_c';
opts.cubDir = 'data/cub';
opts.vocDir = 'data/VOC2007';
opts.vocDir12 = 'data/VOC2012';
opts.writeResults = false;
opts.compid = 'comp2';
opts.suffix = 'baseline' ;
opts.prefix = 'v22' ;
opts.model = 'imagenet-vgg-m.mat';
opts.layer = 13 ; % for D-CNN (R-CNN is the penultimate)
opts.segProposalType = 'crisp' ;
opts.gpuId = 1;
opts.crf = [];
[opts, varargin] = vl_argparse(opts,varargin) ;

opts.expDir = sprintf('data/%s/%s-seed-%02d', opts.prefix, opts.dataset, opts.seed) ;
opts.imdbDir = fullfile(opts.expDir, 'imdb') ;
if ~iscell(opts.suffix)
  opts.resultPath = fullfile(opts.expDir, sprintf('result-%s.mat', opts.suffix)) ;
  opts.segResultPath = fullfile(opts.expDir, sprintf('%s/result-%s-seg.mat', opts.segProposalType, opts.suffix)) ;
  opts.segPublishDir = fullfile(opts.expDir, sprintf('%s/result-%s-seg-figures', opts.segProposalType, opts.suffix)) ;
  vl_xmkdir(opts.segPublishDir);
  if opts.writeResults
      opts.vocResultPath = fullfile(opts.expDir, [sprintf('result-%s/Main/%s_cls_', opts.suffix, opts.compid) '%s_%s.txt']);
  end
else
  for s = 1:numel(opts.suffix)
    opts.resultPath{s} = fullfile(opts.expDir, sprintf('result-%s.mat', opts.suffix{s})) ;
    opts.segResultPath{s} = fullfile(opts.expDir, sprintf('%s/result-%s-seg.mat', opts.segProposalType, opts.suffix{s})) ;
    opts.segPublishDir{s} = fullfile(opts.expDir, sprintf('%s/result-%s-seg-figures', opts.segProposalType, opts.suffix{s})) ;
    vl_xmkdir(opts.segPublishDir{s});
  end
end
opts = vl_argparse(opts,varargin) ;

if nargout <= 1, return ; end

% Setup GPU if needed
if opts.useGpu
  gpuDevice(opts.gpuId) ;
end

% -------------------------------------------------------------------------
%                                                            Setup encoders
% -------------------------------------------------------------------------

models = {} ;
for i = 1:numel(opts.encoders)
  if isstruct(opts.encoders{i})
    name = opts.encoders{i}.name ;
    opts.encoders{i}.path = fullfile(opts.expDir, [name '-encoder.mat']) ;
    opts.encoders{i}.codePath = fullfile(opts.expDir, [name '-codes.mat']) ;
    models = horzcat(models, get_cnn_model_from_encoder_opts(opts.encoders{i})) ;
  else
    for j = 1:numel(opts.encoders{i})
      name = opts.encoders{i}{j}.name ;
      opts.encoders{i}{j}.path = fullfile(opts.expDir, [name '-encoder.mat']) ;
      opts.encoders{i}{j}.codePath = fullfile(opts.expDir, [name '-codes.mat']) ;
      models = horzcat(models, get_cnn_model_from_encoder_opts(opts.encoders{i}{j})) ;
    end
  end
end

% -------------------------------------------------------------------------
%                                                       Download CNN models
% -------------------------------------------------------------------------

for i = 1:numel(models)
    crt_model_path = fullfile('data/models', models{i});
    vl_xmkdir('data/models');
    if ~exist(crt_model_path, 'file')
        fprintf('downloading model %s\n', models{i});
        urlwrite(fullfile('http://www.vlfeat.org/matconvnet/models', ...
            models{i}), crt_model_path);
        % backwards compatibility for the model:
        fix_load_nn(crt_model_path);
    end
end

% -------------------------------------------------------------------------
%                                                              Load dataset
% -------------------------------------------------------------------------

vl_xmkdir(opts.expDir) ;
vl_xmkdir(opts.imdbDir) ;

imdbPath = fullfile(opts.imdbDir, sprintf('imdb-seed-%d.mat', opts.seed)) ;
if exist(imdbPath)
  imdb = load(imdbPath) ;
  return ;
end

switch opts.dataset
  case 'os'
    imdb = os_get_database(opts.osDir) ;
  case 'os-a'
    imdb = os_attr_get_database(opts.osDir);
  case 'fmd'
    imdb = fmd_get_database(opts.fmdDir, 'seed', opts.seed) ;
  case 'dtd'
    imdb = dtd_get_database(opts.dtdDir, 'seed', opts.seed);
  case 'kth'
    imdb = kth_get_database(opts.kthDir, 'seed', opts.seed);
  case 'voc07'
    imdb = voc_get_database(opts.vocDir, 'seed', opts.seed);
  case 'voc12'
    imdb = voc_get_database(opts.vocDir12, 'seed', opts.seed);
  case 'voc12s'
    imdb = voc_get_seg_database(opts.vocDir12, 'seed', opts.seed);
  case 'mit'
    imdb = mit_indoor_get_database(opts.mitDir);
  case 'msrc'
    imdb = msrc_c_get_database(opts.msrcDir);
  case 'cubcrop'
    imdb = cub_get_database(opts.cubDir, true);
  case 'cub'
    imdb = cub_get_database(opts.cubDir, false);
  case 'alot'
    imdb = alot_get_database(opts.alotDir, 'seed', opts.seed);
  otherwise
    serror('Unknown dataset %s', opts.dataset) ;
end

save(imdbPath, '-struct', 'imdb') ;

if opts.printDatasetInfo
  print_dataset_info(imdb) ;
end

% -------------------------------------------------------------------------
function model = get_cnn_model_from_encoder_opts(encoder)
% -------------------------------------------------------------------------
p = find(strcmp('model', encoder.opts)) ;
if ~isempty(p)
  [~,m,e] = fileparts(encoder.opts{p+1}) ;
  model = {[m e]} ;
else
  model = {} ;
end


clear; close all; clc;

% add required libraries to the path
addpath(genpath('baseline'));
addpath(genpath('LFCC'));
addpath(genpath('CQCC_v1.0'));
addpath(genpath('GMM'));
addpath(genpath('bosaris_toolkit'));
addpath(genpath('tDCF_v1'));

% set here the experiment to run (access and feature type)
access_type = 'LA'; % LA for logical or PA for physical
feature_type = 'CQCC'; % LFCC or CQCC

% set paths to the wave files and protocols

% TODO: in this code we assume that the data follows the directory structure:
%
% ASVspoof_root/
%   |- data_physical
%      |- ASVspoof2019_LA_dev_asv_scores_v1.txt
% 	   |- ASVspoof2019_LA_dev_v1/
% 	   |- ASVspoof2019_LA_protocols_v1/
% 	   |- ASVspoof2019_LA_train_v1/
%   |- data_physical
%      |- ASVspoof2019_PA_dev_asv_scores_v1.txt
%      |- ASVspoof2019_PA_dev_v1/
%      |- ASVspoof2019_PA_protocols_v1/
%      |- ASVspoof2019_PA_train_v1/

% pathToASVspoof2019Data = '/path/to/ASVspoof_root/';
pathToASVspoof2019Data = './';
if strcmp(access_type, 'LA')
    pathToDatabase = fullfile(pathToASVspoof2019Data, 'data_logical');
else
    pathToDatabase = fullfile(pathToASVspoof2019Data, 'data_physical');
end

trainProtocolFile = fullfile(pathToDatabase, horzcat('ASVspoof2019_', access_type, '_protocols'), horzcat('ASVspoof2019.', access_type, '.cm.train.trn.txt'));
devProtocolFile = fullfile(pathToDatabase, horzcat('ASVspoof2019_', access_type, '_protocols'), horzcat('ASVspoof2019.', access_type, '.cm.dev.trl.txt'));

%% Feature extraction for training data

% read train protocol
fileID = fopen(trainProtocolFile);
protocol = textscan(fileID, '%s%s%s%s%s');
fclose(fileID);

% get file and label lists
filename = protocol{2};
sys_id = protocol{4};
key = protocol{5};

% get indices of genuine and spoof files
% bonafideIdx = find(strcmp(key,'bonafide'));
% spoofIdx = find(strcmp(key,'spoof'));

disp('Extracting features for training data...');
dset_name = 'train';
cache_file_name = fullfile(['cache_' dset_name '_' access_type '_cqcc.mat']);

parfor i=1:length(filename)
    % extract CQCC feature
    filePath = fullfile(pathToDatabase,['ASVspoof2019_' access_type '_train/flac'],[filename{i} '.flac']);
    [x,fs] = audioread(filePath);

    % padding to make data-length = 64000(4s)
    x_len = size(x,1);
    max_len = 64000;
    if x_len >= max_len
        x = x(1:max_len);
    else % need to pad
        num_repeats = floor(max_len / x_len)+1;
        x_repeat = repmat(x,num_repeats,1);
        x= x_repeat(1:max_len);
    end

    if strcmp(feature_type,'LFCC')
        [stat,delta,double_delta] = extract_lfcc(x,fs,20,512,20);
        trainFeatureCell{i} = [stat delta double_delta]';
    elseif strcmp(feature_type,'CQCC')
        trainFeatureCell{i} = cqcc(x, fs, 96, fs/2, fs/2^10, 16, 29, 'ZsdD');
    end

    % convert sys_id
    switch sys_id{i}
        case '-'
            sys_id{i} = 0;
        case 'SS_1'
            sys_id{i} = 1;
        case 'SS_2'
            sys_id{i} = 2;
        case 'SS_4'
            sys_id{i} = 3;
        case 'US_1'
            sys_id{i} = 4;
        case 'VC_1'
            sys_id{i} = 5;
        case 'VC_4'
            sys_id{i} = 6;
        %For PA:
        case 'AA'
            sys_id{i} = 7;
        case 'AB'
            sys_id{i} = 8;
        case 'AC'
            sys_id{i} = 9;
        case 'BA'
            sys_id{i} = 10;
        case 'BB'
            sys_id{i} = 11;
        case 'BC'
            sys_id{i} = 12;
        case 'CA'
            sys_id{i} = 13;
        case 'CB'
            sys_id{i} = 14;
        case 'CC'
            sys_id{i} = 15;
        otherwise
            disp('error converting system id!')
    end
end

% convert key
data_y = strcmp(key,'bonafide');
data_x = transpose(trainFeatureCell);
save(cache_file_name, 'filename', 'data_x', 'data_y', 'sys_id', '-v7.3')

%% Feature extraction and scoring of development data

% read dev protocol
fileID = fopen(devProtocolFile);
protocol = textscan(fileID, '%s%s%s%s%s');
fclose(fileID);

% get file and label lists
filename = protocol{2};
sys_id = protocol{4};
key = protocol{5};

% get indices of genuine and spoof files
% bonafideIdx = find(strcmp(key,'bonafide'));
% spoofIdx = find(strcmp(key,'spoof'));

disp('Extracting features for development data...');
dset_name = 'dev';
cache_file_name = fullfile(['cache_' dset_name '_' access_type '_cqcc.mat']);

parfor i=1:length(filename)
    % extract CQCC feature
    filePath = fullfile(pathToDatabase,['ASVspoof2019_' access_type '_dev/flac'],[filename{i} '.flac']);
    [x,fs] = audioread(filePath);

    % padding to make data-length = 64000(4s)
    x_len = size(x,1);
    max_len = 64000;
    if x_len >= max_len
        x = x(1:max_len);
    else % need to pad
        num_repeats = floor(max_len / x_len) + 1;
        x_repeat = repmat(x,num_repeats,1);
        x= x_repeat(1:max_len);
    end

    if strcmp(feature_type,'LFCC')
        [stat,delta,double_delta] = extract_lfcc(x,fs,20,512,20);
        devFeatureCell{i} = [stat delta double_delta]';
    elseif strcmp(feature_type,'CQCC')
        devFeatureCell{i} = cqcc(x, fs, 96, fs/2, fs/2^10, 16, 29, 'ZsdD');
    end

    % convert sys_id
    switch sys_id{i}
        case '-'
            sys_id{i} = 0;
        case 'SS_1'
            sys_id{i} = 1;
        case 'SS_2'
            sys_id{i} = 2;
        case 'SS_4'
            sys_id{i} = 3;
        case 'US_1'
            sys_id{i} = 4;
        case 'VC_1'
            sys_id{i} = 5;
        case 'VC_4'
            sys_id{i} = 6;
         %For PA:
        case 'AA'
            sys_id{i} = 7;
        case 'AB'
            sys_id{i} = 8;
        case 'AC'
            sys_id{i} = 9;
        case 'BA'
            sys_id{i} = 10;
        case 'BB'
            sys_id{i} = 11;
        case 'BC'
            sys_id{i} = 12;
        case 'CA'
            sys_id{i} = 13;
        case 'CB'
            sys_id{i} = 14;
        case 'CC'
            sys_id{i} = 15;
        otherwise
            disp('error converting system id!')
    end
end
% convert key
data_y = strcmp(key,'bonafide');
data_x = transpose(devFeatureCell);
save(cache_file_name, 'filename', 'data_x', 'data_y', 'sys_id', '-v7.3')


function [vw, ok] = loadParameterMap(vw, mapPath)
% function [vw, ok] = loadParameterMap(vw, [mapPath])
%
% load and set parameter map in a user specified file
%
% mapPath: optional path to parameter map file. Default: prompt user
%
% rmk, 1/12/99
% djh, 2/21/2001, modified to use dataDir and getPathStrDialog
% ras, 02/04, creates an estimated co, amp, and ph fields if they don't
% exist, b/c mrLoadRet is snotty about using parameter maps alone.
%
% ras, 03/11/04: In working with contrast maps, I've found it useful to have
%  independent statistical threshold and effect size maps -- to restrict
% the map overlay according to the threshold, but to color-code according
% to the effect size. This is analgous to thresholding by coherence, but
% color-coding by amplitude. In this way, for instance, one could leave the
% mapWin at full range, slide the cothresh sliand see both highly correlated
% and anticorrelated regions for a given contrast.
% So, I've made some param map files that have a 'co' field saved with the
% map and mapName vars. This field, when loaded, would replace the co field
% for the corAnal.
% ARW: It didn't seem right that we estimated co (or had it saved in the
% param file). Instead, we fill co with ones so that it behaves correctly
% ras: Yeah, it's a hack, b/c the variable doesn't generally represent coherence,
% but for event-related analyses, it's often pretty useful to have the
% two different ways of thresholding. While a long-term solution is to have
% a more generalized display method (which is in the nascent mrVista2
% viewer), it's still nice to have it for now.
%
% ras, 11/15/05: added ability to load map parameters, such as the color
% map and clip modes, which may be saved along with the map.
%
% rkl, 04/17/17: Fixed a bug: the UI display mode did not get set to 'map'
% when loading a nifti as a parameter map (though everything works smoothly
% when loading a .mat file as parameter map). This resulted in the slider not
% displaying the full range of values.
if ~exist('mapPath','var')
    mapPath = getPathStrDialog(dataDir(vw),'Choose parameter map file name',{'*.mat; *.nii; *.nii.gz'});
    if isempty(mapPath), ok = false; return; end
end

% if the map path doesn't exist, but a map file exists in the view's
% data dir with that name, modify the path accordingly:
if ~check4File(mapPath)
    if check4File( fullfile(dataDir(vw), mapPath) )
        mapPath = fullfile(dataDir(vw), mapPath);
    end
end

[~,name,extension] = fileparts(mapPath);

if strcmp(extension, '.mat')
    % check4File only works with .mat files:
    if ~check4File(mapPath)
        warning(['No ',mapPath,' file']) %#ok<WNTAG>
        ok = 0;
        return
    end

else
    % We still need to check whether the file exists:
    if ~exist(mapPath, 'file')
        warning(['No ',mapPath,' file']) %#ok<WNTAG>
        ok = 0;
        return
    end
end

verbose = prefsVerboseCheck;
if verbose
    fprintf('[%s]: Loading Parameter Map: %s \n', mfilename, mapPath);
end

% If it's a nifti file:
if strcmp(extension, '.nii') || strcmp(extension,'.gz')

    % Read in the nifti
    nii = niftiRead(mapPath);

    % Apply the canonical xform for nifti data
    switch lower(viewGet(vw, 'viewType'))
        case 'inplane'
            nii = niftiApplyAndCreateXform(nii,'Inplane');

            % Set the data into the view structure, converting a 4D array
            % into a cell array of 3D arrays
            niData = niftiGet(nii,'Data');
            n = size(niData,4);
            mapData = cell(1,n);
            for ii = 1:n
                mapData{ii} = niData(:,:,:,ii);
            end
            vw = viewSet(vw, 'map', mapData);

            % To deal with with the double-extension in .nii.gz files
            dot_idx = find(name=='.', 1);
            if ~isempty(dot_idx), name = name(1:find(name=='.')-1); end

            % It will be named according to the name of the nifti file:
            vw = viewSet(vw, 'map Name', name);

            % Save it in the right place for the DATATYPE:
            saveParameterMap(vw)

            mapPath = fullfile(dataDir(vw),[vw.mapName,'.mat']);

            load(mapPath);

            vw = setParameterMap(vw,map,mapName);

        case {'gray' 'volume'}
            vw = nifti2functionals(vw, mapPath);

            % refresh (if this isn't a hidden view -- no ui struct)
            if isfield(vw, 'ui')
                vw = setDisplayMode(vw,'map');
            end

            return;
        otherwise

    end

end

% Load it
load(mapPath);

% Set the parameters
vw = setParameterMap(vw,map,mapName);

nScans = viewGet(vw, 'numScans');
if exist('co','var')
    for scan = 1:nScans
        if length(co) >= scan && ~isempty(co{scan}) %#ok<USENS>
            vw.co{scan} = co{scan};
        end
    end
end

% are the units for the map saved?
% (due to inconsistent coding, there are 2 possible variable names.
%  'units' or 'mapUnits'. 'mapUnits' is preferred, but for
%  back-compatibility, I leave in a check for 'units' as well.)
if exist('mapUnits', 'var')
    vw = viewSet(vw, 'mapUnits', mapUnits);
elseif exist('units', 'var')
    vw = viewSet(vw, 'mapUnits', units);
else
        vw = viewSet(vw, 'mapUnits', ''); % reset to empty
end

% if parameters about the view mode are saved, load these in as well
if exist('cmap','var'),     vw.ui.mapMode.cmap = cmap; end
if exist('clipMode','var'), vw.ui.mapMode.clipMode = clipMode; end
if exist('numColors','var'),vw.ui.mapMode.numColors = numColors; end
if exist('numGrays','var'), vw.ui.mapMode.numGrays = numGrays; end

ok = 1;

% refresh (if this isn't a hidden view -- no ui struct)
if isfield(vw, 'ui')
    vw = setDisplayMode(vw,'map');
end

return


% BV_READ  Reads BrainVision data over existing TCP socket.
%     DATA = BV_READ(H)
%     In:
%     h : handle to a BrainVision connection (previously opened via bv_open)
%     Out:
%     data : a block of new data, [#Channels x #Samples]

% Author: Hal Greenwald, The MITRE Corporation, 29-NOV-2011
% This software incorporates portions of the BrainVision Recorder RDA Client.  Used with permission of Brain Products GmbH.

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

function data = bv_read(h)
data = [];
if (~h.initialized)
    return;
end

header_size = 24;
try
    % check for existing data in socket buffer
    tryheader = pnet(h.handle, 'read', header_size, 'byte', 'network', 'view', 'noblock');
    while ~isempty(tryheader)

        % Read header of RDA message
        hdr = ReadHeader(h.handle);

        % Perform some action depending on the type of the data package
        switch hdr.type
            case 1       % Start message
                % Reset block counter to check overflows
                h.lastBlock = -1;
                pnet(h.handle, 'read', hdr.size - header_size);

            case 4       % 32Bit Data block
                % Read data and markers from message
                [datahdr, eegdata, markers] = ReadDataMessage(h.handle, hdr, h.channelCount);
                data = cat(2, data, eegdata);

                % check tcpip buffer overflow
                if h.lastBlock ~= -1 && datahdr.block > h.lastBlock + 1
                    disp(['******* Overflow with ' int2str(datahdr.block - h.lastBlock) ' blocks ******']);
                end
                h.lastBlock = datahdr.block;

                % Edit the following lines to process marker information
%                 for m = 1:datahdr.markerCount
%                     disp(markers(m));
%                 end

            case 3       % Stop message
                disp('Received STOP signal from Recorder');
                pnet(h.handle, 'read', hdr.size - header_size);
                bv_close(h);
                h.initialized = false;
                data = [];

            otherwise    % ignore all unknown types, but read the package from buffer
                pnet(h.handle, 'read', hdr.size - header_size);
        end
        if h.initialized
            tryheader = pnet(h.handle, 'read', header_size, 'byte', 'network', 'view', 'noblock');
        else
            tryheader = [];
        end
    end
catch er
    disp(er.message);
end

if ~isempty(data)
    % scale the data to uV (consistent with the pop_loadbv plugin)
    data = bsxfun(@times,data,h.resolutions');
end

%% ***********************************************************************
% Read the message header
function hdr = ReadHeader(con)
% con    tcpip connection object

% define a struct for the header
hdr = struct('uid',[],'size',[],'type',[]);

% read id, size and type of the message
% swapbytes is important for correct byte order of MATLAB variables
hdr.uid = pnet(con,'read', 16);
hdr.size = swapbytes(pnet(con,'read', 1, 'uint32', 'network'));
hdr.type = swapbytes(pnet(con,'read', 1, 'uint32', 'network'));

%% ***********************************************************************
% Read a data message
function [datahdr, data, markers] = ReadDataMessage(con, hdr, channelCount)
% con       tcpip connection object
% hdr       message header
% datahdr   data header with information on datalength and number of markers
% data      data as one dimensional arry
% markers   markers as array of marker structs

% Define data header struct and read data header
datahdr = struct('block',[],'points',[],'markerCount',[]);

datahdr.block = swapbytes(pnet(con,'read', 1, 'uint32', 'network'));
datahdr.points = swapbytes(pnet(con,'read', 1, 'uint32', 'network'));
datahdr.markerCount = swapbytes(pnet(con,'read', 1, 'uint32', 'network'));

% Read data in float format
data = swapbytes(pnet(con,'read', channelCount * datahdr.points, 'single', 'network'));
data = reshape(data,channelCount,datahdr.points);

% Define markers struct and read markers
markers = struct('size',[],'position',[],'points',[],'channel',[],'type',[],'description',[]);
for m = 1:datahdr.markerCount
    marker = struct('size',[],'position',[],'points',[],'channel',[],'type',[],'description',[]);

    % Read integer information of markers
    marker.size = swapbytes(pnet(con,'read', 1, 'uint32', 'network'));
    marker.position = swapbytes(pnet(con,'read', 1, 'uint32', 'network'));
    marker.points = swapbytes(pnet(con,'read', 1, 'uint32', 'network'));
    marker.channel = swapbytes(pnet(con,'read', 1, 'int32', 'network'));

    % type and description of markers are zero-terminated char arrays
    % of unknown length
    c = pnet(con,'read', 1);
    while c ~= 0
        marker.type = [marker.type c];
        c = pnet(con,'read', 1);
    end

    c = pnet(con,'read', 1);
    while c ~= 0
        marker.description = [marker.description c];
        c = pnet(con,'read', 1);
    end

    % Add marker to array
    markers(m) = marker;
end


function opennii(nii)
imtool3D_nii_3planes(nii)


function options = dsdpset(varargin)
%DSDPSET  Create or alter the options for Optimization with DSDP
%
% options = dsdpset('param1',value1,'param2',value2,...) creates an DSDP
% options structure with the parameters 'param' set to their corresponding
% values in 'value'. Parameters not specified will be set to the DSDP
% default.
%
% options = dsdpset(oldopts,'param1',value1,...) creates a copy of the old
% options 'oldopts' and then fills in (or writes over) the parameters
% specified by 'param' and 'value'.
%
% options = dsdpset() creates an options structure with all fields set to
% dsdpset defaults.
%
% dsdpset() prints a list of all possible fields and their function.
%
% See supplied DSDP Documentation for further details of these options.

%   Copyright (C) 2013 Jonathan Currie (IPL)

% Print out possible values of properties.
if (nargin == 0) && (nargout == 0)
    printfields();
    return
end
%Names and Defaults
Names = {'drho';'rpos';'r0';'penalty';'rho';'dbound';'gaptol';'rtol';'mu0';'maxtrust';...
         'steptol';'ptol';'pnormtol';'reuse';'zbar';'dlbound';'ybound';'fixed'};
Defaults = {1;0;-1;1e8;5;1e20;1e-7;1e-6;-1;1e10;0.05;1e-4;1e30;4;[];[];[];[]};

%Enter and check user args
try
    options = opticheckset(Names,Defaults,@checkfield,varargin{:});
catch ME
    throw(ME);
end

function checkfield(field,value)
%Check a field contains correct data type
switch lower(field)
    %Scalar double
    case {'r0','penalty','rho','mu0','dbound','pnormtol','zbar','dlbound','ybound'}
        err = opticheckval.checkScalarDbl(value,field);
    %Scalar non negative double
    case {'rtol','ptol','maxtrust','gaptol','steptol'}
        err = opticheckval.checkScalarNonNeg(value,field);
    %Scalar 0/1
    case {'rpos','drho'}
        err = opticheckval.checkScalar01(value,field);
    %Scalar non-negative integer
    case 'reuse'
        err = opticheckval.checkScalarIntNonNeg(value,field);
    %Double column vector
    case 'fixed'
        err = opticheckval.checkDualCol(value,field);
    otherwise
        err = MException('OPTI:SetFieldError','Unrecognized parameter name ''%s''.', field);
end
if(~isempty(err)), throw(err); end

function printfields()
%Print out fields with defaults
fprintf('          rpos: [ Use Penalty Parameter to enforce Feasibility {0}, 1 ] \n');
fprintf('          drho: [ Use Dynamic Strategy to choose Rho: 0, {1} ] \n');
fprintf('            r0: [ Set initial value for variable r in Dual {-1} ] \n');
fprintf('       penalty: [ Penalty Parameter Gamma {1e8} \n');
fprintf('           rho: [ Potential Parmater: {5} ] \n');
fprintf('           mu0: [ Barrier Parameter: {-1} ] \n');
fprintf('          rtol: [ Classify Dual as feasible if r is less than this tolerance: {1e-6} ] \n');
fprintf('          ptol: [ Classify Primal as feasible if infeasibility is less than this tolerance: {1e-4} ] \n');
fprintf('      maxtrust: [ Maximum Trust Radius on Step Direction: {1e10} ] \n');
fprintf('        gaptol: [ Convergence Gap Tolerance: {1e-7} ] \n');
fprintf('       steptol: [ Terminate solver if step length in Dual is below this tolerance: {0.05} ] \n');
fprintf('        dbound: [ Terminate solver if Dual Objective greater than this Value {1e20} ] \n');
fprintf('      pnormtol: [ Terminate the solver when duality gap is sufficiently small and pnorm is less than this quantity: {1e30} ] \n');
fprintf('         reuse: [ Number of times the Hessian of the Barrier Function will be reused {4} ] \n');
fprintf('          zbar: [ Upper bound on objective value at the solution {[]} ] \n');
fprintf('       dlbound: [ Lower bound on dual value {[]} ] \n');
fprintf('        ybound: [ Bound on the dual variables y {[]} ] \n');
fprintf('         fixed: [ Matrix of fixed variables, column 1 variable indices, column 2, fixed values {[]} ] \n');
fprintf('\n');


function sct_merge_nii(flist,output)
% sct_merge_nii(flist,output)
% merge niftis in the 4th dimenstion.
% sct_merge_nii(sct_tools_ls('*dwi.nii'),'DWI.nii.gz') --> always .nii.gz

sct_unix(['fslmerge -t ' output ' ' strjoin(flist)])


function generateDoc
%generateDoc Publish the example scripts in the doc directory

%   Steven L. Eddins
%   Copyright 2008-2009 The MathWorks, Inc.

doc_dir = fullfile(fileparts(which('runtests')), '..', 'doc');
addpath(doc_dir);
cd(doc_dir)
mfiles = dir('*.m');
for k = 1:numel(mfiles)
    publish(mfiles(k).name);
    cd(doc_dir)
end


% Standard test images
classdef standard_images

methods(Static)

    function image_dir = test_image_dir()
        here = which('spx.data.standard_images');
        data = fileparts(here);
        spx = fileparts(data);
        library = fileparts(spx);
        spx = fileparts(library);
        image_dir = fullfile(spx, 'data', 'images');
    end

    function image = barbara_gray_512x512()
        % Returns the Barbara image
        filepath = fullfile(spx.data.standard_images.test_image_dir(), 'barbara_gray_512x512.png');
        image = spx.image.read_gray_image(filepath);
    end

    function image = cameraman_gray_512x512()
        % Returns the Barbara image
        filepath = fullfile(spx.data.standard_images.test_image_dir(), 'cameraman_gray_512x512.tif');
        image = spx.image.read_gray_image(filepath);
    end

    function image = jetplane_gray_512x512()
        % Returns the Barbara image
        filepath = fullfile(spx.data.standard_images.test_image_dir(), 'jetplane_gray_512x512.tif');
        image = spx.image.read_gray_image(filepath);
    end

    function image = lake_gray_512x512()
        % Returns the Barbara image
        filepath = fullfile(spx.data.standard_images.test_image_dir(), 'lake_gray_512x512.tif');
        image = spx.image.read_gray_image(filepath);
    end

    function image = lena_gray_512x512()
        % Returns the Barbara image
        filepath = fullfile(spx.data.standard_images.test_image_dir(), 'lena_gray_512x512.tif');
        image = spx.image.read_gray_image(filepath);
    end

    function image = peppers_gray_512x512()
        % Returns the Barbara image
        filepath = fullfile(spx.data.standard_images.test_image_dir(), 'peppers_gray_512x512.tif');
        image = spx.image.read_gray_image(filepath);
    end

    function image = pirate_gray_512x512()
        % Returns the Barbara image
        filepath = fullfile(spx.data.standard_images.test_image_dir(), 'pirate_gray_512x512.tif');
        image = spx.image.read_gray_image(filepath);
    end

end

end


%% changeFileExtensions
% Below is a demonstration of the features of the |changeFileExtensions| function

%%
clear; close all; clc;

%% Syntax
% |changeFileExtensions(pathName,extOld,extNew);|

%% Description
% The |changeFileExtensions| function changes the file extensions for all
% files in the folder pathName, and with the extension extOld, to have the
% extension extNew.

%% Examples
%

%%
%Create example files in the data/temp directory. Here a set of files with
%the txt extension are created. Later these are changed to have a csv
%file extension.

%Create .txt files
defaultFolder = fileparts(fileparts(mfilename('fullpath')));
pathName=fullfile(defaultFolder,'data','temp','renameCheck');
mkdir(pathName)

n=5;
for q=1:1:n %Create n files
    fileID=fopen(fullfile(pathName,['temp',num2str(q),'.txt']),'w');
    fprintf(fileID,'%d\n',pi);
    fclose(fileID);
end

% Add one additional file with a different extension to show this file will
% not be effected.
fileID=fopen(fullfile(pathName,'temp.txp'),'w');
fprintf(fileID,'%d\n',pi);
fclose(fileID);

%%
% Show current folder content
disp('Old folder content:')
ls(pathName)

%%
% Change file extensions
extOld='txt'; %Old extension
extNew='csv'; %New extension
changeFileExtensions(pathName,extOld,extNew)

%%
% Show current folder content
disp('New folder content:')
ls(pathName)

%%
% remove the temporary folder created for this example
rmdir(pathName,'s')

%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


%% patchEdgeCollapse
% Below is a demonstration of the features of the |patchEdgeCollapse| function

%%
clear; close all; clc;

%% Syntax
% |[F,V,logicValid,indFix2]=patchEdgeCollapse(F,V,E,logicKeep,meanOption);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


function imdb = setup_voc07_ssw(varargin)
% setup_voc07_ssw  Initialize PASCAL VOC2007 data with selective
% search windows

% Warning! boxes are in the format of ([y1 x1 y2 x2])

opts.dataDir = fullfile('data') ;
opts.proposalDir = fullfile(opts.dataDir,'SSW');
opts.loadTest = 1;
opts = vl_argparse(opts, varargin) ;

% -------------------------------------------------------------------------
%                                                 Load selective search win
% -------------------------------------------------------------------------
%% get selective search windows
files = {'SelectiveSearchVOC2007trainval.mat', ...
  'SelectiveSearchVOC2007test.mat'} ;

if ~exist(opts.proposalDir, 'dir')
  mkdir(opts.proposalDir) ;
end

for i=1:numel(files)
  if ~exist(fullfile(opts.proposalDir, files{i}), 'file')
    url = sprintf('http://koen.me/research/downloads/%s',files{i}) ;
    fprintf('downloading %s\n', url) ;
    urlwrite(url,[opts.proposalDir filesep files{i}]);
  end
end

if ~isempty(opts.proposalDir)
  t1 = load([opts.proposalDir,filesep,files{1}]);
  if opts.loadTest
    t2 = load([opts.proposalDir,filesep,files{2}]);
    ssw.id = [str2double(t1.images);str2double(t2.images)]';
    ssw.boxes = cat(2,t1.boxes,t2.boxes);
  else
    ssw.id = str2double(t1.images)';
    ssw.boxes = t1.boxes;
  end

  [~,si] = sort(ssw.id);
  ssw.id = ssw.id(si);
  ssw.boxes = ssw.boxes(si);
end

% -------------------------------------------------------------------------
%                                                  Load categories metadata
% -------------------------------------------------------------------------
cats = {'aeroplane','bicycle','bird','boat','bottle','bus','car',...
  'cat','chair','cow','diningtable','dog','horse','motorbike','person',...
  'pottedplant','sheep','sofa','train','tvmonitor'};

if ~exist(opts.dataDir,'dir')
  error('wrong data folder!');
end

if ~exist(opts.dataDir,'dir')
  error('wrong data folder!');
end

% Download VOC Devkit and data
if ~exist(fullfile(opts.dataDir,'VOCdevkit'),'dir')
  files = {'VOCtest_06-Nov-2007.tar',...
           'VOCtrainval_06-Nov-2007.tar',...
           'VOCdevkit_08-Jun-2007.tar'} ;
  for i=1:numel(files)
    if ~exist(fullfile(opts.dataDir, files{i}), 'file')
      outPath = fullfile(opts.dataDir,files{i}) ;
      url = sprintf('http://host.robots.ox.ac.uk/pascal/VOC/voc2007/%s',files{i}) ;
      fprintf('Downloading %s to %s\n', url, outPath) ;
      urlwrite(url,outPath) ;
      untar(outPath,opts.dataDir);
    end
  end
end
addpath(fullfile(opts.dataDir, 'VOCdevkit', 'VOCcode'));

traindata = importdata(fullfile(opts.dataDir,'VOCdevkit','VOC2007','ImageSets','Main','train.txt'));
valdata = importdata(fullfile(opts.dataDir,'VOCdevkit','VOC2007','ImageSets','Main','val.txt'));
testdata = importdata(fullfile(opts.dataDir,'VOCdevkit','VOC2007','ImageSets','Main','test.txt'));

assert(numel(traindata)==2501);
assert(numel(valdata)==2510);
assert(numel(testdata)==4952);

imdb.classes.name = cats ;
imdb.classes.description = cats ;
imdb.imageDir = fullfile(opts.dataDir, fullfile('VOCdevkit','VOC2007','JPEGImages')) ;

% -------------------------------------------------------------------------
%                                                           Training images
% -------------------------------------------------------------------------%
names = cell(1,numel(traindata));
labels = zeros(numel(traindata),numel(cats));

% load image names
for t=1:numel(traindata)
  names{t} = sprintf('%06d.jpg',traindata(t));
%   data{t} = imread(sprintf('%s/%s',imdb.imageDir,names{t}));
end

% load binary labels
for c=1:numel(cats)
  t = importdata(fullfile(opts.dataDir,'VOCdevkit','VOC2007','ImageSets','Main',[cats{c},'_train.txt']));
  labels(:,c) = t(:,2);
end

imdb.images.id = traindata';
imdb.images.name = names ;
imdb.images.set = ones(1, numel(names)) ;
imdb.images.label = labels' ;
% imdb.images.data = data;

% -------------------------------------------------------------------------
%                                                         Validation images
% -------------------------------------------------------------------------

names = cell(1,numel(valdata));
labels = zeros(numel(valdata),numel(cats));
% data = cell(1,numel(valdata));

% load image names
for t=1:numel(valdata)
  names{t} = sprintf('%06d.jpg',valdata(t));
%   data{t} = imread(sprintf('%s/%s',imdb.imageDir,names{t}));
end

% load binary labels
for c=1:numel(cats)
  t = importdata(fullfile(opts.dataDir,'VOCdevkit','VOC2007','ImageSets','Main',[cats{c},'_val.txt']));
  labels(:,c) = t(:,2);
end

imdb.images.id = horzcat(imdb.images.id, valdata') ;
imdb.images.name = horzcat(imdb.images.name, names) ;
imdb.images.set = horzcat(imdb.images.set, 2*ones(1,numel(names))) ;
imdb.images.label = horzcat(imdb.images.label, labels') ;
% imdb.images.data = horzcat(imdb.images.data, data) ;

% % -------------------------------------------------------------------------
% %                                                               Test images
% % -------------------------------------------------------------------------
%
%
if opts.loadTest
  names = cell(1,numel(testdata));
  labels = zeros(numel(testdata),numel(cats));
  % data = cell(1,numel(testdata));

  % load image names
  for t=1:numel(testdata)
    names{t} = sprintf('%06d.jpg',testdata(t));
  %   data{t} = imread(sprintf('%s/%s',imdb.imageDir,names{t}));
  end

  % load binary labels
  for c=1:numel(cats)
    t = importdata(fullfile(opts.dataDir,'VOCdevkit','VOC2007','ImageSets','Main',[cats{c},'_test.txt']));
    labels(:,c) = t(:,2);
  end

  imdb.images.id = horzcat(imdb.images.id, testdata') ;
  imdb.images.name = horzcat(imdb.images.name, names) ;
  imdb.images.set = horzcat(imdb.images.set, 3 * ones(1,numel(names))) ;
  imdb.images.label = horzcat(imdb.images.label, labels') ;
  % imdb.images.data = horzcat(imdb.images.data, data) ;
end
% -------------------------------------------------------------------------
%                                                            Postprocessing
% -------------------------------------------------------------------------
[~,sorti] = sort(imdb.images.id);

imdb.images.id = imdb.images.id(sorti);
imdb.images.name = imdb.images.name(sorti) ;
imdb.images.set = imdb.images.set(sorti) ;
imdb.images.label = single(imdb.images.label(:,sorti)) ;
imdb.images.size = zeros(numel(imdb.images.name),2);

if ~isempty(opts.proposalDir)
  imdb.images.boxes = ssw.boxes;
  assert(all(ssw.id==imdb.images.id));
end

% this is zero as scores of selective search windows are not much
% informative
if ~isempty(opts.proposalDir)
imdb.images.boxScores = cell(size(imdb.images.boxes));
for i=1:numel(imdb.images.boxes)
  imdb.images.boxes{i} = int16(imdb.images.boxes{i});
  imdb.images.boxScores{i} = zeros(size(imdb.images.boxes{i},1),1,'single');
  imf = imfinfo(fullfile(imdb.imageDir,imdb.images.name{i}));
  imdb.images.size(i,:) = [imf.Height,imf.Width];
end
end
end


% FGPLVM toolbox
% Version 0.132		Friday 24 Feb 2006 at 19:26
% Copyright (c) 2006 Neil D. Lawrence
%
% CMDSROADDATA This script uses classical MDS to visualise some road distance data.
% DEMOIL1 Oil data with fully independent training conditional.
% DEMOIL2 Oil data with fully independent training conditional, and MLP back constraints.
% DEMOIL3 Oil data with deterministic training conditional.
% DEMOIL4 Oil data with deterministic training conditional, and MLP back constraints.
% DEMOIL5 Oil data with partially independent training conditional.
% DEMOIL6 Oil data with partially independent training conditional, and MLP back constraints.
% DEMROBOTWIRELESSNAVIGATE Take some test data for the robot and navigate with it.
% DEMROBOTTRACES1 Wireless Robot data from University of Washington, with tailored dynamics.
% DEMROBOTWIRELESS1 Wireless Robot data from University of Washington, without dynamics and without back constraints.
% DEMROBOTWIRELESS2 Wireless Robot data from University of Washington, without dynamics and without back constraints.
% DEMROBOTWIRELESS4 Wireless Robot data from University of Washington with dynamics and no back constraints.
% DEMROBOTWIRELESS4 Wireless Robot data from University of Washington with dynamics and back constraints.
% DEMROBOTWIRELESSNAVIGATE Take some test data for the robot and navigate with it.
% DEMSPGP1D1 Do a simple 1-D regression after Snelson & Ghahramani's example.
% DEMSPGP1D2 Do a simple 1-D regression after Snelson & Ghahramani's example.
% DEMSPGP1D3 Do a simple 1-D regression after Snelson & Ghahramani's example.
% DEMSPGP1D4 Do a simple 1-D regression after Snelson & Ghahramani's example.
% DEMSPGP1DPLOT Plot results from 1-D sparse GP.
% DEMSTICK1 Model the stick man using an RBF kernel.
% DEMSTICK2 Model the stick man using an RBF kernel and dynamics.
% DEMSTICK3 Model the stick man using an RBF kernel and mlp back constraints.
% DEMSTICK4 Model the stick man using an RBF kernel and 3-D latent space.
% DEMVOWELS1 Model the vowels data with a 2-D FGPLVM using RBF kernel.
% DEMVOWELS2 Model the vowels data with a 2-D FGPLVM using RBF kernel and back constraints.
% DEMVOWELS3 Model the vowels data with a 2-D FGPLVM using RBF kernel and back constraints, but without PCA initialisation.
% DEMVOWELSISOMAP Model the vowels data with a 2-D FGPLVM using RBF kernel.
% DEMVOWELSLLE Model the vowels data with a 2-D FGPLVM using RBF kernel.
% DEMWALKSITJOG1 Model the stick man using an RBF kernel.
% DEMWALKSITJOG2 Model the stick man using an RBF kernel.
% DEMWALKSITJOG3 Model the stick man using an RBF kernel.
% DEMWALKSITJOG4 Model the stick man using an RBF kernel.
% DEMWALKSITJOGDYNAMICSLEARN Learn the stick man dynamics.
% DYNAMICSTEST Run some tests on the specified dynamics model.
% FGPLVMADDDYNAMICS Add a dynamics kernel to the model.
% FGPLVMCLASSVISUALISE Callback function for visualising data in 2-D.
% FGPLVMCOVGRADSTEST Test the gradients of the covariance.
% FGPLVMCREATE Create a GPLVM model with inducing varibles.
% FGPLVMDISPLAY Display an FGPLVM model.
% FGPLVMDYNAMICSFIELDPLOT 2-D field plot of the dynamics.
% FGPLVMDYNAMICSPLOT 2-D scatter plot of the latent points.
% FGPLVMDYNAMICSPOSTERIORMEANVAR Mean and variances of the posterior at points given by X.
% FGPLVMDYNAMICSRUN Visualise the manifold.
% FGPLVMDYNAMICSSAMPLE Sample a field from the GP.
% FGPLVMEXPANDPARAM Expand a parameter vector into a GP-LVM model.
% FGPLVMEXTRACTPARAM Extract a parameter vector from a GP-LVM model.
% FGPLVMFIELDPLOT 2-D field plot of the dynamics.
% FGPLVMGRADIENT GP-LVM gradient wrapper.
% FGPLVMKERNDYNAMICSSAMPLE Sample a field from a given kernel.
% FGPLVMLOADRESULT Load a previously saved result.
% FGPLVMLOGLIKEGRADIENTS Compute the gradients of the EZFT sparse covariance.
% FGPLVMLOGLIKELIHOOD Log-likelihood for a GP-LVM.
% FGPLVMNEARESTNEIGHBOUR Give the number of errors in latent space for 1 nearest neighbour.
% FGPLVMOBJECTIVE Wrapper function for GPLVM objective.
% FGPLVMOPTIMISE Optimise the inducing variable based kernel.
% FGPLVMOPTIMISEPOINT Optimise the postion of a point.
% FGPLVMOPTIONS Return default options for FGPLVM model.
% FGPLVMPOINTGRADIENT Wrapper function for gradient of a single point.
% FGPLVMPOINTLOGLIKEGRADIENT Log-likelihood gradient for of a point of the GP-LVM.
% FGPLVMPOINTLOGLIKELIHOOD Log-likelihood of a point for the GP-LVM.
% FGPLVMPOINTOBJECTIVE Wrapper function for objective of a single point.
% FGPLVMPOSTERIORMEANVAR Mean and variances of the posterior at points given by X.
% FGPLVMPRINTPLOT Print latent space for learnt model.
% FGPLVMREADFROMFID Load from a FID produced by the C++ implementation.
% FGPLVMREADFROMFILE Load a file produced by the c++ implementation.
% FGPLVMRESULTSDYNAMIC Load a results file and visualise them.
% FGPLVMTEST Test the gradients of the gpCovGrads function and the fgplvm models.
% FGPLVMVISUALISE Visualise the manifold.
% GPBLOCKINDICES Return indices of given block.
% GPCOMPUTEALPHA Update the vector `alpha' for computing posterior mean quickly.
% GPCOMPUTEM Compute the matrix m given the model.
% GPCOVGRADS Sparse objective function gradients wrt Covariance functions for inducing variables.
% GPCOVGRADSTEST Test the gradients of the covariance.
% GPCREATE Create a GP model with inducing varibles/pseudo-inputs.
% GPDATAINDICES Return indices of present data.
% GPDISPLAY Display a Gaussian process model.
% GPDYNAMICSCREATE Create the dynamics model.
% GPDYNAMICSDISPLAY Display a GP dynamics model.
% GPDYNAMICSEXPANDPARAM Place the parameters vector into the model for GP dynamics.
% GPDYNAMICSEXTRACTPARAM Extract parameters from the GP dynamics model.
% GPDYNAMICSLATENTGRADIENTS Gradients of the X vector given the dynamics model.
% GPDYNAMICSLOGLIKEGRADIENTS Gradients of the GP dynamics wrt parameters.
% GPDYNAMICSLOGLIKELIHOOD Give the log likelihood of the dynamics part.
% GPDYNAMICSSAMP Sample from the dynamics for a given input.
% GPDYNAMICSSETLATENTVALUES Set the latent values inside the model.
% GPEXPANDPARAM Expand a parameter vector into a GP model.
% GPEXTRACTPARAM Extract a parameter vector from a GP model.
% GPGRADIENT Gradient wrapper for a GP model.
% GPLOGLIKEGRADIENTS Compute the gradients for the parameters and X.
% GPLOGLIKELIHOOD Compute the log likelihood of a GP.
% GPOBJECTIVE Wrapper function for GP objective.
% GPOPTIMISE Optimise the inducing variable based kernel.
% GPOPTIONS Return default options for GP model.
% GPOUT Evaluate the output of an Gaussian process model.
% GPPOSTERIORGRADMEANVAR Gadient of the mean and variances of the posterior at points given by X.
% GPPOSTERIORMEANCOVAR Mean and covariances of the posterior at points given by X.
% GPPOSTERIORMEANVAR Mean and variances of the posterior at points given by X.
% GPREVERSIBLEDYNAMICSCREATE Create the dynamics model.
% GPREVERSIBLEDYNAMICSDISPLAY Display a GP dynamics model.
% GPREVERSIBLEDYNAMICSEXPANDPARAM Place the parameters vector into the model for GP dynamics.
% GPREVERSIBLEDYNAMICSEXTRACTPARAM Extract parameters from the GP reversible dynamics model.
% GPREVERSIBLEDYNAMICSLATENTGRADIENTS Gradients of the X vector given the dynamics model.
% GPREVERSIBLEDYNAMICSLOGLIKEGRADIENTS Gradients of the GP reversible dynamics wrt parameters.
% GPREVERSIBLEDYNAMICSLOGLIKELIHOOD Give the log likelihood of the dynamics part.
% GPREVERSIBLEOPTIONS Return default options for GP reversible dynamics model.
% GPREVERSIBLEDYNAMICSSAMP Sample from the dynamics for a given input.
% GPREVERSIBLEDYNAMICSSETLATENTVALUES Set the latent values inside the model.
% GPSCALEBIASGRADIENT Compute the gradient of the scale and bias.
% GPUPDATEKERNELS Update the kernels that are needed.
% MODELLATENTGRADIENTS Gradients of the latent variables for dynamics models in the GPLVM.
% MODELSETLATENTVALUES Set the latent variables for dynamics models in the GPLVM.
% ROBONEDYNAMICSCREATE Create the dynamics model.
% ROBONEDYNAMICSDISPLAY Display the robot dynamics model.
% ROBONEDYNAMICSEXPANDPARAM Place the parameters vector into the model for first robot dynamics.
% ROBONEDYNAMICSEXTRACTPARAM Extract parameters from the robot one dynamics model.
% ROBONEDYNAMICSLATENTGRADIENTS Gradients of the X vector given the dynamics model.
% ROBONEDYNAMICSLOGLIKEGRADIENTS Gradients of the robot one dynamics wrt parameters.
% ROBONEDYNAMICSLOGLIKELIHOOD Give the log likelihood of the robot one dynamics part.
% ROBONEDYNAMICSSETLATENTVALUES Set the latent values inside the model.
% ROBTHREEDYNAMICSCREATE Create the dynamics model.
% ROBTHREEDYNAMICSDISPLAY Display the robot dynamics model.
% ROBTHREEDYNAMICSEXPANDPARAM Place the parameters vector into the model for first robot dynamics.
% ROBTHREEDYNAMICSEXTRACTPARAM Extract parameters from the robot three dynamics model.
% ROBTHREEDYNAMICSLATENTGRADIENTS Gradients of the X vector given the dynamics model.
% ROBTHREEDYNAMICSLOGLIKEGRADIENTS Gradients of the robot three dynamics wrt parameters.
% ROBTHREEDYNAMICSLOGLIKELIHOOD Give the log likelihood of the robot three dynamics part.
% ROBTHREEDYNAMICSSETLATENTVALUES Set the latent values inside the model.
% ROBTHREEDYNAMICSSETLATENTVALUES Set the latent values inside the model.
% ROBTWODYNAMICSCREATE Create the dynamics model.
% ROBTWODYNAMICSDISPLAY Display the robot dynamics model.
% ROBTWODYNAMICSEXPANDPARAM Place the parameters vector into the model for first robot dynamics.
% ROBTWODYNAMICSEXTRACTPARAM Extract parameters from the robot two dynamics model.
% ROBTWODYNAMICSLATENTGRADIENTS Gradients of the X vector given the dynamics model.
% ROBTWODYNAMICSLOGLIKEGRADIENTS Gradients of the robot two dynamics wrt parameters.
% ROBTWODYNAMICSLOGLIKELIHOOD Give the log likelihood of the robot one dynamics part.
% ROBTWODYNAMICSSETLATENTVALUES Set the latent values inside the model.


function isShown = node_show_parents(iSearch)
% NODE_SHOW_PARENTS: Checks whether parent nodes are to be shown in the database tree
%
% INPUT:
%    - iSearch: ID of the search to apply, or root of a search structure
%
% OUTPUT:
%    - isShown: Whether the parent nodes are to be shown (1) or not (0)

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Martin Cousineau, 2020

if isnumeric(iSearch)
    % If no filter applied, show the parent nodes
    if iSearch == 0
        isShown = 1;
        return;
    end
    % Get the active search
    searchRoot = panel_protocols('ActiveSearch', 'get', iSearch);
    if isempty(searchRoot)
        error(sprintf('Could not find active search #%d', iSearch));
    end
else
    % Search structure provided in arguments
    searchRoot = iSearch;
end

if searchRoot.Type == 3 && ~isempty(searchRoot.Value) && searchRoot.Value == 1
    isShown = 0;
else
    isShown = 1;
end


function parcel_cl_nmds_plots(parcel_cl_avgs, NMDS, varargin)
% Plot: data panel
%
% case 'save', dosave = 1;
% case {'savedir', 'mysavedir'}, mysavedir = varargin{i+1};
% case {'figs', 'dotfigs'}, savedotfigs = 1;
%
% Doc not complete yet.  Please update me!
%
% See parcel_clusters.m
% See parcel_cl_nmds.m
%
% load Parcellation_info/parcellation.mat
%
% :Examples:
% ::
%
%    parcel_cl_nmds_plots(parcel_cl_avgs, NMDS, 'save')
%    parcel_cl_nmds_plots(parcel_cl_avgs, NMDS, 'save', 'savedir', 'Parcellation_info')
%    parcel_cl_nmds_plots(parcel_cl_avgs, NMDS, 'save', 'savedir', 'Parcellation_info_tor_mask_try1', 'savedotfig')

    % ..
    %    SETUP
    % ..

    dosave = 0;
    mysavedir = [];
    savedotfigs = 0;

    for i = 1:length(varargin)
        if ischar(varargin{i})
            switch varargin{i}

                % functional commands
                case 'save', dosave = 1;

                case {'savedir', 'mysavedir'}, mysavedir = varargin{i+1};

                case {'figs', 'dotfigs'}, savedotfigs = 1;

                otherwise, warning(['Unknown input string option:' varargin{i}]);
            end
        end
    end

    N = length(parcel_cl_avgs(1).timeseries);

    if ~isfield(NMDS, 'basecolors')
        NMDS.basecolors = {[1 0 0] [0 1 0] [0 0 1] [1 1 0] [0 1 1] [1 0 1] ...
            [1 .5 0] [.5 1 0] [.5 0 1] [1 0 .5] [0 1 .5] [0 .5 1]};
    end

    basecolors = NMDS.basecolors;

    % NMDS plot
    % --------------------------------------------------
    % Make figure
    disp('Visualizing results')
    create_figure('nmdsfig');

    nmdsfig(NMDS.stats_mds.GroupSpace,'classes',NMDS.stats_mds.ClusterSolution.classes, ...
        'names', [],'sig',NMDS.stats.fdrsig, 'fill', 'colors', basecolors);
    % --------------------------------------------------

    % --------------------------------------------------
    % Get class clusters (convenient format)
    % --------------------------------------------------

    % re-define class clusters
    clear class_clusters
    for i = 1:max(NMDS.stats_mds.ClusterSolution.classes)
        wh = find(NMDS.stats_mds.ClusterSolution.classes == i);
        class_clusters{i} = parcel_cl_avgs(wh);

        % refine class (network) membership
        [parcel_cl_avgs(wh).from_class] = deal(i);
    end

    nclasses = length(class_clusters); % redefine based on results

    % --------------------------------------------------
    % get index of which parcels (clusters) are in which classes
    % --------------------------------------------------

    parcelindx = cat(1, parcel_cl_avgs.from_class);
    [parcelindx, ivals] = sort(parcelindx);
    cl = parcel_cl_avgs(ivals);

    % --------------------------------------------------
    % Get data
    % --------------------------------------------------

    data = [];
    for i = 1:length(cl)

        % zscore within, or at least center to avoid individual diffs in
        % baseline driving correlations
        for s = 1:N
            cl(i).timeseries{s} = scale(cl(i).timeseries{s});
        end

        data(:, i) = cat(1, cl(i).timeseries{:});
    end

    for s = 1:N-1, len(s) = length(cl(1).timeseries{s}); end
    len = cumsum([1 len]);

    % --------------------------------------------------
    % Panel TS figure
    % --------------------------------------------------

    create_figure('Panel_timeseries', nclasses, 1);
    for i = 1:nclasses
        subplot(nclasses, 1, i);
        hold on;
        mycolor = basecolors{i};

        [lh, fh] = plot_error(data(:, parcelindx == i)');
        mymean = mean(data(:, parcelindx == i)');

        set(lh, 'Color', mycolor);
        set(fh, 'FaceColor', mycolor);
        set(gca, 'YLim', [min(mymean) max(mymean)]);
        axis tight
        hold on
        plot_vertical_line(len);

        if i == 1
            for j = 1:length(len), text(len(j), max(mymean), ['Subj' num2str(j)]); end
        end

        axis off
        drawnow
    end

    % --------------------------------------------------
    % Correlation figure
    % --------------------------------------------------

    % get within-parcel correlations
    %-----------------------------------
    for i = 1:length(cl)
        dd = cat(1, cl(i).all_data{:});
        rr = corrcoef(dd);
        rr = rr .* (1 - eye(size(rr)));
        within_corr(i) = mean(squareform(rr));
    end

    create_figure('Correlations');
    [r, p] = corrcoef(data);

    % put withins on diagonal
    r = r .* (1 - eye(size(r)));
    r = r + diag(within_corr);
    %r(p > .05) = NaN;

    % put spaces in to mark off classes
    %-----------------------------------
    %wh_spaces = [0; diff(parcelindx)];
    rnew = [];
    pinew = [];
    for i = 1:nclasses
        rnew = [rnew; r(parcelindx == i, :)];
        rnew(end + 1, :) = NaN;

        pinew = [pinew; parcelindx(parcelindx == i)];
        pinew(end+1) = NaN;

    end

    rnew2 = [];
    for i = 1:nclasses
        rnew2 = [rnew2 rnew(:, parcelindx == i)];
        rnew2(:, end + 1) = NaN;
    end
    r = rnew2;

    % Image the correlation matrix
    %-----------------------------------
    imagesc(r); colorbar
    set(gca,'YDir', 'Reverse')
    axis tight
    newcm = colormap_tor([0 0 .7], [1 1 0], [1 .5 0]);
    colormap(newcm)
    title('Correlations among parcels');
    xlabel('Parcel index number');

    % Color bars for class ID
    %-----------------------------------
    axpos = get(gca, 'Position');
    axh = axes('Position', [.05 axpos(2) .04 axpos(4)]);
    set(axh, 'YDir', 'Reverse', 'YLim', [1 length(pinew)]);
    hold on;
    for i = 1:nclasses

        yy = find(pinew == i);
        plot(.7 * ones(size(yy)), yy, '-', 'Color', basecolors{i}, 'LineWidth', 10);

        text(-2, round(median(yy)), num2str(i), 'FontSize', 18, 'Color', 'k');

    end
    axis off
    drawnow

    % --------------------------------------------------
    % Orthviews of parcels
    % --------------------------------------------------

    nclasses = length(class_clusters); % redefine based on results

    while length(basecolors) < nclasses
        basecolors{end+1} = basecolors{end - 11} + basecolors{end - 6} ./ 2;
    end

    parcelindx = cat(1, parcel_cl_avgs.from_class);

    colors = nmdsfig_tools('class_colors',parcelindx,basecolors);

    addstr = 'noadd';

    for i = 1:length(parcel_cl_avgs)

        cluster_orthviews(parcel_cl_avgs(i), colors(i), addstr, 'solid');

        addstr = 'add';
    end

    % --------------------------------------------------
    % Montages of parcels
    % --------------------------------------------------

    disp(['Saving montages in ' mysavedir])

    for i = 1:length(class_clusters)

        mycolor = basecolors(i);

        montage_clusters([], class_clusters{i}, mycolor);
        drawnow

        savename = fullfile(mysavedir, ['Montage_class' num2str(i)]);
        saveas(gcf, savename,'png')

    end

    if dosave
        save_figures(1, savedotfigs, mysavedir);
    end

    % --------------------------------------------------
    % Glass brains
    % --------------------------------------------------
    for i = 1:length(class_clusters)
        create_figure('glass');

        mysig = NMDS.stats.fdrsig;
        mysig = mysig(:, parcelindx == i);
        mysig = mysig(parcelindx == i, :);

        cluster_nmdsfig_glassbrain( ...
            class_clusters{i}, ...
            ones(length(class_clusters{i}), 1), ...
            NMDS.basecolors(i), ...
            mysig, [], 'blobs');

        if dosave
           saveas(gcf, fullfile(mysavedir, ['glass_network_' num2str(i)]), 'png');
           if savedotfigs
               saveas(gcf, fullfile(mysavedir, ['glass_network_' num2str(i)]), 'fig');
           end
        end

    end

end

% -------------------------------------------------------------------------
% Save all figures
% -------------------------------------------------------------------------
function save_figures(verbose, savedotfigs, mysavedir)

    if nargin == 0, verbose = 1; end
    if nargin == 1, savedotfigs = 0; end
    if nargin == 2 || isempty(mysavedir), mysavedir = '.'; end

    fignames = {'nmdsfig' 'Panel_timeseries' 'Correlations'};

    for i = 1:length(fignames)
        name = fignames{i};

        h = findobj('Tag', name);
        if ~isempty(h)

            if length(h) > 1
                if verbose, disp(['Warning: More than one plot with tag ' name '. Saving highest-numbered figure.']); end
                h = max(h);
            end

            figure(h)
            scn_export_papersetup(500);

            if savedotfigs
                if verbose
                    fprintf('Saving: %s%s\n', fullfile(mysavedir, name), '.fig');
                end

                saveas(h, fullfile(mysavedir, name), 'fig');
            end

            if verbose
                fprintf('Saving: %s%s\n', fullfile(mysavedir, name), '.png');
            end
            saveas(h, fullfile(mysavedir, name), 'png');
        end
    end

end


function y = cvx_isconstant( x, full ) %#ok
narginchk(1,2);
if nargin == 1,
    y = true;
else
    y = true( size( x ) );
end

% Copyright 2005-2016 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.