function obj = updateBoxplot(obj, boxIndex)

% y: ...[DONE]
% x0: ...[DONE]
% x: ...[DONE]
% name: ...[DONE]
% boxmean: ...[NOT SUPPORTED IN MATLAB]
% boxpoints: ...[NOT SUPPORTED IN MATLAB]
% jitter: ...[NOT SUPPORTED IN MATLAB]
% pointpos: ...[NOT SUPPORTED IN MATLAB]
% whiskerwidth: ........................[TODO]
% fillcolor: ...[DONE]
% opacity: ---[TODO]
% xaxis: ...[DONE]
% yaxis: ...[DONE]
% showlegend: ...[DONE]
% stream: ...[HANDLED BY PLOTLY STREAM]
% visible: ...[DONE]
% type: ...[DONE]

% MARKER
% color: ...[NA]
% width: ...[NA]
% dash: ...[NA]
% opacity: ...[NA]
% shape: ...[NA]
% smoothing: ...[NA]
% outliercolor: ...[NOT SUPPORTED IN MATLAB]
% outlierwidth: ...[NOT SUPPORTED IN MATLAB]

% LINE
% color: ...[DONE]
% width: ...[DONE]
% dash: ...[DONE]
% opacity: ---[TODO]
% shape: ...[DONE]
% smoothing: ...[NOT SUPPORTED IN MATLAB]

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

%-AXIS INDEX-%
axIndex = obj.getAxisIndex(obj.State.Plot(boxIndex).AssociatedAxis);

%-BOX DATA STRUCTURE-%
box_data = get(obj.State.Plot(boxIndex).Handle);

%-BOX CHILDREN-%
box_child = box_data.Children;

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

%-CONFIRM PROPER BOXPLOT STRUCTURE-%

% check for compact boxplot
isCompact = ~isempty(findobj(obj.State.Plot(boxIndex).Handle,'Tag','Whisker'));

% number of boxplots
if isCompact
    bpcompnum = 6;
    bpnum = length(box_child)/bpcompnum;
    % check for assumed box structure
    if mod(length(box_child), bpcompnum)~=0
        updateAlternativeBoxplot(obj, boxIndex);
        return
    end
else
    bpcompnum = 8;
    bpnum = length(box_child)/bpcompnum;
    % check for assumed box structure
    if mod(length(box_child),bpcompnum)~=0
        updateAlternativeBoxplot(obj, boxIndex);
        return
    end
end

% initialize ydata
ydata = [];

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

%-box groupgap-%
obj.layout.bargroupgap = 1/bpnum;

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

%-box name-%
obj.data{boxIndex}.name = box_data.DisplayName;

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

% iterate through box plot children in reverse order
for bp = bpnum:-1:1

    %-CHECK FOR MULTIPLE AXES-%
    [xsource, ysource] = findSourceAxis(obj,axIndex);

    %-AXIS DATA-%
    eval(['xaxis = obj.layout.xaxis' num2str(xsource) ';']);
    eval(['yaxis = obj.layout.yaxis' num2str(ysource) ';']);

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

    %-box xaxis-%
    obj.data{boxIndex}.xaxis = ['x' num2str(xsource)];

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

    %-box yaxis-%
    obj.data{boxIndex}.yaxis = ['y' num2str(ysource)];

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

    %-box type-%
    obj.data{boxIndex}.type = 'box';

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

    %-box visible-%
    obj.data{boxIndex}.visible = strcmp(box_data.Visible,'on');

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

    %-box fillcolor-%
    obj.data{boxIndex}.fillcolor = 'rgba(0, 0, 0, 0)';

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

    %-box showlegend-%
    leg = get(box_data.Annotation);
    legInfo = get(leg.LegendInformation);

    switch legInfo.IconDisplayStyle
        case 'on'
            showleg = true;
        case 'off'
            showleg = false;
    end

    obj.data{boxIndex}.showlegend = showleg;

    %-boxplot components-%
    Q1 = [];
    Q3 = [];
    median = [];
    outliers = [];
    uwhisker = [];
    lwhisker = [];

    % iterate through boxplot components
    for bpc = 1:bpcompnum

        %get box child data
        box_child_data = get(box_child(bp+bpnum*(bpc-1)));

        %box name
        if strcmp(box_child_data.Type,'text')
            if iscell(box_child_data.String)
                boxname =  box_child_data.String{1};
            else
                boxname =  box_child_data.String;
            end
        end

        % parse boxplot tags
        switch box_child_data.Tag

            %-median-%
            case 'Median'

                median =  box_child_data.YData(1);

                %-upper whisker-%
            case 'Upper Whisker'

                uwhisker = box_child_data.YData(2);

                %-boxplot whisker width-%
                obj.data{boxIndex}.whiskerwidth = 1;

                %-lower whisker-%
            case 'Lower Whisker'

                lwhisker = box_child_data.YData(1);

            case 'Box'

                %-Q1-%
                Q1 = min(box_child_data.YData);

                %-Q3-%
                Q3 = max(box_child_data.YData);

                %-boxplot line style-%

                if isCompact
                    col = 255*box_child_data.Color;
                    obj.data{boxIndex}.fillcolor = ['rgb(' num2str(col(1)) ',' num2str(col(2)) ',' num2str(col(3)) ')'];
                else
                    obj.data{boxIndex}.line = extractLineLine(box_child_data);
                end

                %-outliers-%
            case 'Outliers'

                if ~isnan(box_child_data.YData)
                    %-outlier marker data-%
                    outliers = box_child_data.YData;

                    %-outlier marker style-%
                    obj.data{boxIndex}.marker = extractLineMarker(box_child_data);
                end

                %-compact whiskers-%
            case 'Whisker'

                %-boxplot line style-%
                obj.data{boxIndex}.line = extractLineLine(box_child_data);

                %-boxplot whisker width-%
                obj.data{boxIndex}.whiskerwidth = 0;

                %-whisker data-%
                uwhisker = box_child_data.YData(2);
                lwhisker = box_child_data.YData(1);

                %-compact median-%
            case 'MedianInner'

                median = box_child_data.YData(1);

        end
    end

    %-generate boxplot data-%
    gendata = generateBoxData(outliers, lwhisker, Q1, median, Q3, uwhisker);

    %-boxplot y-data-%
    obj.data{boxIndex}.y(length(ydata)+1:length(ydata)+length(gendata)) = ...
        generateBoxData(outliers, lwhisker, Q1, median, Q3, uwhisker);

    %-boxplot x-data-%
    if (bpnum > 1)
        for n = (length(ydata)+1):(length(ydata)+length(gendata))
            obj.data{boxIndex}.x{n} = boxname;
        end
    end

    %-update ydata-%
    ydata = obj.data{boxIndex}.y;

end

%----------------------------!AXIS UPDATE!--------------------------------%

% take first text object as prototype for axis tick style/layout
text_child = findobj(obj.State.Plot(boxIndex).Handle,'Type','text');

%-STANDARDIZE UNITS-%
fontunits = get(text_child(1),'FontUnits');
set(text_child(1),'FontUnits','points');

%-text data -%
text_data = get(text_child(1));

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

%-xaxis tick font size-%
xaxis.tickfont.size = text_data.FontSize;

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

%-xaxis tick font family-%
xaxis.tickfont.family = matlab2plotlyfont(text_data.FontName);

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

%-xaxis tick font color-%
xaxis.tickfont.color = text_data.Color;

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

%-axis type-%
xaxis.type = 'category';

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

%-show tick labels-%
xaxis.showticklabels = true;

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

%-autorange-%
xaxis.autorange = true;

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

%-set the layout axis field-%
obj.layout = setfield(obj.layout,['xaxis' num2str(xsource)],xaxis);

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

%-REVERT UNITS-%
set(text_child(1),'FontUnits',fontunits);

end


function [] = ReSaveInfoWithGroundTruth( jobID, taskIDs )

data = readSeqDataFromPlainText( '../data/mocap6/' );
data = ARSeqData( 1, data);

for tt = 1:length( taskIDs )
   INFO = loadSamplerInfo( jobID, taskIDs(tt) );

   INFO.data = data;

   outpath = getUserSpecifiedPath( 'SimulationResults' );
   outpath = fullfile( outpath, num2str(jobID), num2str(taskIDs(tt)), 'Info.mat'  );
   save( outpath, '-struct', 'INFO' );

end


function y = triu(varargin)
% When matrix is empty and there's a non-zero second argument it should give [] (that's what Matlab does), not error
if nargin==2 && isempty(varargin{1})
    y = [];
else
    y = builtin('triu', varargin{:});
end
end


function [last] = filepartsLast(fname)
% filepartsLast Return the last part of a filename (strip off directory and suffix)
% function filepartsLast(fname)
%
% Examples
% filepartsLast('C:/foo/bar') = 'bar'
% filepartsLast('C:/foo/bar.mat') = 'bar'
% filepartsLast('C:/foo/bar.mat.gz') = 'bar.mat'
% filepartsLast('bar.mat') = 'bar'

[pathstr,name,ext,versn] = fileparts(fname);
last = name;


function vl_setupnn()
%VL_SETUPNN Setup the MatConvNet toolbox.
%   VL_SETUPNN() function adds the MatConvNet toolbox to MATLAB path.

% Copyright (C) 2014-15 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

root = vl_rootnn() ;
addpath(fullfile(root, 'matlab')) ;
addpath(fullfile(root, 'matlab', 'mex')) ;
addpath(fullfile(root, 'matlab', 'simplenn')) ;
addpath(fullfile(root, 'matlab', 'xtest')) ;
addpath(fullfile(root, 'examples')) ;

if ~exist('gather')
  warning('The MATLAB Parallel Toolbox does not seem to be installed. Activating compatibility functions.') ;
  addpath(fullfile(root, 'matlab', 'compatibility', 'parallel')) ;
end

if numel(dir(fullfile(root, 'matlab', 'mex', 'vl_nnconv.mex*'))) == 0
  warning('MatConvNet is not compiled. Consider running `vl_compilenn`.');
end


function exclude = getLvdGAExcludeList()
    exclude = {};
    exclude{end+1} = 'Distance to Ref. Spacecraft';
    exclude{end+1} = 'Distance to Ref. Station';
    exclude{end+1} = 'Relative Vel. to Ref. Spacecraft';
    exclude{end+1} = 'Relative Pos. of Ref. Spacecraft (In-Track)';
    exclude{end+1} = 'Relative Pos. of Ref. Spacecraft (Cross-Track)';
    exclude{end+1} = 'Relative Pos. of Ref. Spacecraft (Radial)';
    exclude{end+1} = 'Relative Pos. of Ref. Spacecraft (In-Track; Ref. SC-centered)';
    exclude{end+1} = 'Relative Pos. of Ref. Spacecraft (Cross-Track; Ref. SC-centered)';
    exclude{end+1} = 'Relative Pos. of Ref. Spacecraft (Radial; Ref. SC-centered)';
    exclude{end+1} = 'Relative SMA of Ref. Spacecraft';
    exclude{end+1} = 'Relative Eccentricity of Ref. Spacecraft';
    exclude{end+1} = 'Relative Inclination of Ref. Spacecraft';
    exclude{end+1} = 'Relative RAAN of Ref. Spacecraft';
    exclude{end+1} = 'Relative Argument of Periapsis of Ref. Spacecraft';
    exclude{end+1} = 'Elevation Angle w.r.t. Ref. Station';
    exclude{end+1} = 'Line of Sight to Ref. Spacecraft';
    exclude{end+1} = 'Line of Sight to Ref. Station';
    exclude{end+1} = 'Sun-centric Position (X)';
    exclude{end+1} = 'Sun-centric Position (Y)';
    exclude{end+1} = 'Sun-centric Position (Z)';
    exclude{end+1} = 'Body-centric Position (X)';
    exclude{end+1} = 'Body-centric Position (Y)';
    exclude{end+1} = 'Body-centric Position (Z)';
    exclude{end+1} = 'Body-centric Velocity (X)';
    exclude{end+1} = 'Body-centric Velocity (Y)';
    exclude{end+1} = 'Body-centric Velocity (Z)';
    exclude{end+1} = 'Body-Fixed Velocity (X)';
    exclude{end+1} = 'Body-Fixed Velocity (Y)';
    exclude{end+1} = 'Body-Fixed Velocity (Z)';
    exclude{end+1} = 'Body-Fixed Velocity';
    exclude{end+1} = 'Semi-major Axis';
    exclude{end+1} = 'Eccentricity';
    exclude{end+1} = 'Inclination';
    exclude{end+1} = 'Right Asc. of the Asc. Node';
    exclude{end+1} = 'Argument of Periapsis';
    exclude{end+1} = 'True Anomaly';
    exclude{end+1} = 'Mean Anomaly';
    exclude{end+1} = 'Orbital Period';
    exclude{end+1} = 'Radius of Periapsis';
    exclude{end+1} = 'Radius of Apoapsis';
    exclude{end+1} = 'Radius of Spacecraft';
    exclude{end+1} = 'Altitude of Apoapsis';
    exclude{end+1} = 'Altitude of Periapsis';
    exclude{end+1} = 'Speed of Spacecraft';
    exclude{end+1} = 'Flight Path Angle';
    exclude{end+1} = 'Equinoctial H1';
    exclude{end+1} = 'Equinoctial K1';
    exclude{end+1} = 'Equinoctial H2';
    exclude{end+1} = 'Equinoctial K2';
    exclude{end+1} = 'Altitude';
    exclude{end+1} = 'Longitude (East)';
    exclude{end+1} = 'Latitude (North)';
    exclude{end+1} = 'Longitudinal Drift Rate';
    exclude{end+1} = 'Surface Velocity';
    exclude{end+1} = 'Vertical Velocity';
    exclude{end+1} = 'Central Body ID';
    exclude{end+1} = 'C3 Energy';
    exclude{end+1} = 'Hyperbolic Velocity Unit Vector X';
    exclude{end+1} = 'Hyperbolic Velocity Unit Vector Y';
    exclude{end+1} = 'Hyperbolic Velocity Unit Vector Z';
    exclude{end+1} = 'Hyperbolic Velocity Vector Right Ascension';
    exclude{end+1} = 'Hyperbolic Velocity Vector Declination';
    exclude{end+1} = 'Hyperbolic Velocity Magnitude';
    exclude{end+1} = 'Distance to Ref. Celestial Body';
    exclude{end+1} = 'Elevation Angle of Ref. Celestial Body';
    exclude{end+1} = 'Liquid Fuel/Ox Mass';
    exclude{end+1} = 'Monopropellant Mass';
    exclude{end+1} = 'Xenon Mass';
end


function [img,nr,nc] = getframe_invisible_nocheck(gfdata,sz,removeborder,doresize)

if nargin < 3,
  removeborder = true;
end
if nargin < 4,
  doresize = true;
end

if isfield(gfdata,'grayborder'),
  GRAYBORDER = gfdata.grayborder;
else
  GRAYBORDER = 204;
end

hfig = gfdata.hfig;

% img = hardcopy(gfdata.hardcopy_args{:});
img = print(hfig,'-RGBImage');
set(hfig,'Units',gfdata.units,'Position',gfdata.pos);
if numel(img) == 1,
  fprintf('Could not grab invisible figure. Making visible temporarily.\n');
  set(hfig,'visible','on');
  pause(.1);
  img = hardcopy(gfdata.hardcopy_args{:});
  pause(.1);
  set(hfig,'visible','off');
end

% crop off the extra border
if removeborder,
  isallgray = all(img==GRAYBORDER,3);
end

[nr,nc,tmp] = size(img);
if ~doresize,
  sz(1) = nr; sz(2) = nc;
end

maxfirstcol = nc - sz(2) + 1;
maxfirstrow = nr - sz(1) + 1;
if maxfirstcol <= 0 || maxfirstrow <= 0,
  error('image has size [%d,%d] smaller than input sz = [%d,%d]',nr,nc,sz(1),sz(2));
end
if removeborder,
  firstcol = min(find(~all(isallgray,1),1),maxfirstcol);
  firstrow = min(find(~all(isallgray,2),1),maxfirstrow);
else
  firstcol = 1;
  firstrow = 1;
end
lastcol = firstcol + sz(2) - 1;
lastrow = firstrow + sz(1) - 1;
if removeborder,
  lastcol0 = find(~all(isallgray,1),1,'last');
  lastrow0 = find(~all(isallgray,2),1,'last');
else
  lastcol0 = nc;
  lastrow0 = nr;
end
if lastrow ~= lastrow0 || lastcol ~= lastcol0,
  fprintf('input width = %d, actual width = %d, input height = %d, actual height = %d\n',...
    sz(2),lastcol0-firstcol+1,sz(1),lastrow0-firstrow+1);
end

img = img(firstrow:lastrow,firstcol:lastcol,:);


function names_numbered = DisplayMaskNames(Msk_IDs,MASKs)
if Msk_IDs ~= 0,
    names = MASKs.MaskDatabaseNames(Msk_IDs);
    names_numbered = cell(size(names));
    disp('Regions:');
    for i = 1:length(names),
        names_numbered{i} = [num2str(Msk_IDs(i)), ': ', names{i}];
        disp(names_numbered{i});
    end
end
end


function [mCatalog] = import_start(sFilterDir)

    % Default return value
    mCatalog = nan;

    % Check if filter directory ends with the appropriate directory separator
    sLastChar = sFilterDir(length(sFilterDir));
    if ~(sLastChar == filesep)
        sFilterDir = [sFilterDir filesep];
    end

    % Get directory in filter directory
    vrDir = dir(sFilterDir);
    if isempty(vrDir)
        errordlg('Directory does not exist');
        return;
    elseif length(vrDir) == 2
        errordlg('Directory is empty. No Filters found.');
        return;
    end

    % Initialize filter list
    cFilter = {};
    % Counter for detected filters
    nFilter = 1;

    for nCnt = 1:length(vrDir)
        % Check for directories
        if ~((strcmp(vrDir(nCnt).name, '.')) || (strcmp(vrDir(nCnt).name, '..')))
            % Get name of file
            sName = vrDir(nCnt).name;
            nPos = strfind(sName, '.m');
            % Is it a .m-file
            if ~isempty(nPos)
                sName = sName(1:(nPos - 1));
                try
                    % Is it an import filter
                    sDescription = feval(sName, 0);
                catch
                    sDescription = [];
                end
                % Is it really an import filter
                if ischar(sDescription)
                    % Insert it into filter list
                    cFilter{nFilter, 1} = sDescription;
                    cFilter{nFilter, 2} = sName;
                    nFilter = nFilter + 1;
                end
            end
        end
    end

    % Charmatrix with names of filters
    mFilterNames = char(cFilter{:,1});
    mFilterFiles = char(cFilter{:,2});

    % Invoke the user interface
    hDialog = import_dialog(mFilterNames, mFilterFiles, sFilterDir);

    % Analyze Output
    if ~ishandle(hDialog)
        answer = 0;
    else
        handles = guidata(hDialog);
        answer = handles.answer;
        % OK pressed
        if answer == 1
            % Get the values from figure
            nFilter = get(handles.lstFilter, 'Value');
            % Remove figure from memory
            delete(hDialog);
            % Get the catalog file
            [newfile, newpath] = uigetfile('*.*', 'Choose catalog datafile');
            % Cancel pressed?
            if ~(isequal(newfile, 0) || isequal(newpath, 0))
                newfile = [newpath newfile];
                % Everything ok?
                if length(newfile) > 1
                    mCatalog = feval(cFilter{nFilter,2}, 1, newfile);
                end
            end
        else
            % Remove figure from memory
            delete(hDialog);
        end
    end


% MFE Toolbox Toolbox
% Version 4.0 28-Oct-2009


function saveNEVTetrodes(NEVFullFilename)

% saveNEVTetrodes
%
% Opens saves a new NEV file and splits it into smaller NEV files
% containing only the tetrodes according to the associated CCF file. The
% CCF file should have the same name as the data file.
%
% NEVFullFilename:  The full path to the NEV to be opened.
%                   DEFAULT: If the filename is not provided, the user will
%                   be prompted to select a file.
%
% Use saveNEVTetrodes(NEVFullFilename)
%
%   Example: saveNEVTetrodes('c:\datafolder\datafile.nev');
%
%   The function will open datafile.nev and datafile.ccf and based on the
%   tetrode information saved in datafile.ccf, it will split datafile.nev
%   into smaller chunks that will only contain channels associated to that
%   particular tetrode.
%
%   Kian Torab
%   ktorab@blackrockmicro.com
%   Blackrock Microsystems
%   Version 1.0.0.0
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Version History
%
% 1.0.0.0:
%   - Initial release.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Opening the file
if ~exist('NEVFullFilename', 'var')
    [dataFilename dataFolder] = getFile('*.nev');
    NEVFullFilename = [dataFolder dataFilename];
elseif exist(NEVFullFilename, 'file') ~= 2
        disp('The NEV file name does not exist.');
        return;
else
    [filepath filename fileext] = fileparts(NEVFullFilename);
    dataFolder = [filepath '/'];
    dataFilename = [filename fileext];
end

%% Openning the associated CCF file
ccfFullFilename = [dataFolder dataFilename(1:end-3) 'ccf'];
if exist(ccfFullFilename, 'file') ~= 2 % for 2.x file type
    ccfFullFilename = [dataFolder dataFilename(1:end-8) '.ccf'];
    if exist(ccfFullFilename, 'file') ~= 2 % for TOC file type
        disp('Cannot find the associated CCF file.');
        disp('This function requires the CCF file used during the recording.');
        disp('The CCF must have the same name as the original recorded file.');
        return;
    end
end
ccf = openCCF(ccfFullFilename);

% Calculating the number of NTrode groups in the file
if isfield(ccf, 'NTrodeInfo')
    if isfield(ccf.NTrodeInfo, 'NTrodeMembers')
        numberOfNTrodeGroups = size(ccf.NTrodeInfo.NTrodeMembers,2);
    else
        disp('This data file does not contain any tetrodes.');
        return;
    end
else
    disp('There is an error in the CCF file.');
    return;
end

% Splitting the data file according to the information saved in the
% associated CCF file.
for idx = 1:numberOfNTrodeGroups
    fprintf('Saving tetrode %d containing channels %s.\n', idx, num2str(ccf.NTrodeInfo.NTrodeMembers{idx}));
    saveNEVSubSpikes(ccf.NTrodeInfo.NTrodeMembers{idx}, NEVFullFilename, 'tet');
end


function x = cellrowassign(x, y, indx)

for k = 1:numel(x)
  x{k}(indx,:) = y{k};
end


function amino_name = ch_to_amino_name ( c )

%*****************************************************************************80
%
%% CH_TO_AMINO_NAME converts a character to an amino acid name.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 May 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Carl Branden, John Tooze,
%    Introduction to Protein Structure,
%    Garland Publishing, 1991.
%
%  Parameters:
%
%    Input, character C, the one letter code for an amino acid.
%    Lower and upper case letters are treated the same.
%
%    Output, string AMINO_NAME, the full name of the
%    corresponding amino acid.  The longest name is 27 characters.
%    If the input code is not recognized, then AMINO_NAME will be set to '???'.
%
  n = 23;

  amino_table = [
    'Alanine                    ', ...
    'Aspartic acid or Asparagine', ...
    'Cysteine                   ', ...
    'Aspartic acid              ', ...
    'Glutamic acid              ', ...
    'Phenylalanine              ', ...
    'Glycine                    ', ...
    'Histidine                  ', ...
    'Isoleucine                 ', ...
    'Lysine                     ', ...
    'Leucine                    ', ...
    'Methionine                 ', ...
    'Asparagine                 ', ...
    'Proline                    ', ...
    'Glutamine                  ', ...
    'Arginine                   ', ...
    'Serine                     ', ...
    'Threonine                  ', ...
    'Valine                     ', ...
    'Tryptophan                 ', ...
    'Undetermined amino acid    ', ...
    'Tyrosine                   ', ...
    'Glutamic acid or Glutamine ' ];

  ch_table = [...
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', ...
    'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', ...
    'X', 'Y', 'Z' ];

  for i = 1 : n
    if ( ch_eqi ( c, ch_table(i) ) )
      amino_name = amino_table(i);
      return
    end
  end

  amino_name = '???';

  return
end


function child = children(tree,uid)
% XMLTREE/CHILDREN Return children's UIDs of node uid
% FORMAT child = children(tree,uid)
%
% tree   - a tree
% uid    - uid of the element
% child  - array of the UIDs of children of node uid
%__________________________________________________________________________
%
% Return UID's of children of node uid
%__________________________________________________________________________
% Copyright (C) 2002-2011  http://www.artefact.tk/

% Guillaume Flandin
% $Id: children.m 4460 2011-09-05 14:52:16Z guillaume $

%error(nargchk(2,2,nargin));

child = [];
uid = uid(:);
l = length(tree);
for i=1:length(uid)
    if uid(i) > 0 && uid(i) <= l
        if strcmp(tree.tree{uid(i)}.type,'element')
            child = [child tree.tree{uid(i)}.contents];
        end
    else
        error('[XMLTree] Invalid UID.');
    end
end
if isempty(child), child = []; end


function mask = PTKGetLungROIFromLeftAndRightLungs(left_and_right_lung_mask, context, reporting)
    % PTKGetLungROIFromLeftAndRightLungs. Extracts a region of interest for the left or right lung given the original image and the left and right lung mask.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2012.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    mask = left_and_right_lung_mask.BlankCopy;

    if context == PTKContext.RightLung
        colormap_index = PTKColormapLabels.RightLung;
    elseif context == PTKContext.LeftLung
        colormap_index = PTKColormapLabels.LeftLung;
    else
        reporting.Error('PTKGetLungROIFromLeftAndRightLungs:UnknownContext', ['The context ' char(context) ' is unknown.']);
    end
    mask.ChangeRawImage(left_and_right_lung_mask.RawImage == colormap_index);
    mask.CropToFitWithBorder(5);
end


classdef prtDataSetBig %< prtDataSetBase

    properties
        dataHandler
        action

        nFeatures
        nObservations
        nTargetDimensions
    end

    properties (Hidden)
        summaryCache
    end

    properties (Hidden)
        maxPool = 4;
    end

    methods (Hidden)
        function self = summaryClear(self)
            % self = summaryClear(self)
            self.summaryCache = [];
        end

        function self = summaryRebuild(self)
            % self = summaryRebuild(self)
            self = summaryClear(self);
            self = summaryBuild(self,true);
        end

        function self = summaryBuild(self,force)
            % self = summaryBuild(self,force)
            %
            if nargin < 2
                force = false;
            end
            if force || isempty(self.summaryCache)
                mrSummary = prtMapReduceSummarizeDataSet;
                self.summaryCache = mrSummary.run(self);
            end
        end
    end

    methods

        function summary = summarize(self)
            summary = self.summaryCache;
            if isempty(summary)
                error('prtDataSetBig:summaryNotBuild','The data set big object does not have a valid summary; use ds = ds.summaryBuild to build and cache one');
            end
        end

        function self = prtDataSetBig(varargin)
            self = prtUtilAssignStringValuePairs(self,varargin{:});
        end

        function [reduced, maps] = mapReduce(self, mapReduceObj)
            [reduced, maps] = mapReduceObj.run(self);
        end
    end

    % these methods act as a front-end for the internal field dataHandler,
    % passing through commands that should go to the dataHandler seamlessly
    methods
        function ds = getNextBlock(self)
            ds = self.dataHandler.getNextBlock;
            ds = self.internalRunAction(ds);
        end
        function ds = getBlock(self,index)
            ds = self.dataHandler.getBlock(index);
            ds = self.internalRunAction(ds);
        end
        function n = getNumBlocks(self)
            n = self.dataHandler.getNumBlocks;
        end
        function type = getDataSetType(self)
            type = self.dataHandler.getDataSetType;
        end
        function ds = getRandomBlock(self)
            ind = ceil((self.getNumBlocks)*rand);
            ds = getBlock(self,ind);
        end
    end

    methods (Hidden)
        function ds = internalRunAction(self,ds)
            if isempty(self.action)
                return
            else
                ds = run(self.action,ds);
            end
        end
    end
    methods % Abstract from prtDataSetBase (We actually don't want to use these)

        function n = get.nFeatures(self)
            n = getNumFeatures(self);
        end
        function n = getNumFeatures(self)
            error('prt:prtDataSetBig:doNotUse','This method cannot be used with objects of type prtDataSetBig.');
        end

        function n = get.nObservations(self)
            n = getNumObservations(self);
        end
        function n = getNumObservations(self)
            error('prt:prtDataSetBig:doNotUse','This method cannot be used with objects of type prtDataSetBig.');
        end

        function n = get.nTargetDimensions(self)
            n = getNumTargetDimensions(self);
        end
        function nTargets = getNumTargetDimensions(self)
            error('prt:prtDataSetBig:doNotUse','This method cannot be used with objects of type prtDataSetBig.');
        end

        function targets = getTargets(self,indices)
            error('prt:prtDataSetBig:doNotUse','This method cannot be used with objects of type prtDataSetBig.');
        end
        function data = getData(self,indices)
            error('prt:prtDataSetBig:doNotUse','This method cannot be used with objects of type prtDataSetBig.');
        end
        function self = retainObservationData(self,indices)
            error('prt:prtDataSetBig:doNotUse','This method cannot be used with objects of type prtDataSetBig.');
        end
        function self = catObservationData(self,varargin)
            error('prt:prtDataSetBig:doNotUse','This method cannot be used with objects of type prtDataSetBig.');
        end

    end
end


% child script of canlab_glm_publish
% runs scn_spm_design_check in publishable manner
% runs in directory containing subject level SPM analyses

z = '_________________________________________________';
diaryname = fullfile('model_review_work_log.txt');

if exist(fullfile(pwd,'SPM.mat'),'file')
    sublevs{1} = pwd;
else
    % figure out which directories are lower level analyses
    % criterion: they contain an SPM.mat file
    spmfiles = filenames(fullfile('*','SPM.mat'),'absolute');
    sublevs = cellfun(@fileparts,spmfiles,'UniformOutput',false);
end

for i = 1:numel(sublevs)
    diary(diaryname), fprintf('%s\n%s\n%s\n', z, sublevs{i}, z), diary off

    try
        scn_spm_design_check(sublevs{i}, 'events_only');
        snapnow
    catch exc
        diary(diaryname)
        disp(getReport(exc,'extended'))
%         fprintf('Design review FAILED for: %s.\n', sublevs{i})
        diary off
    end
end

close all


function CreateAffinePanel(handles)

    %Affine Panel
    handles.affinePanel = uipanel('Parent',handles.toolPanel,'Units','normalize','FontSize',10,'Title','Registration Parameters',...
                                    'Tag','affinePanel','Clipping','off',...
                                    'Position',[0 0 1 1],...
                                    'Visible','on');
    dy = 160;
    h312 = uicontrol(...
    'Parent',handles.affinePanel,...
    'Units','pixel',...
    'FontSize',10,...
    'HorizontalAlignment','right',...
    'Position',[9 124+dy 117 19],...
    'String','Translation Scale:',...
    'Style','text',...
    'Tag','text62');

    handles.affine_tscale = uicontrol(...
    'Parent',handles.affinePanel,...
    'Units','pixel',...
    'FontSize',10,...
    'HorizontalAlignment','left',...
    'Position',[129 122+dy 78 23],...
    'String','0.001',...
    'Style','edit',...
    'Tag','affine_tscale');

    handles.affine_minstep = uicontrol(...
    'Parent',handles.affinePanel,...
    'Units','pixel',...
    'FontSize',10,...
    'HorizontalAlignment','left',...
    'Position',[129 86+dy 78 24],...
    'String','0.01',...
    'Style','edit',...
    'Tag','affine_minstep');

    handles.affine_maxstep = uicontrol(...
    'Parent',handles.affinePanel,...
    'Units','pixel',...
    'FontSize',10,...
    'HorizontalAlignment','left',...
    'Position',[129 52+dy 78 23],...
    'String','1.0',...
    'Style','edit',...
    'Tag','affine_maxstep');

    h316 = uicontrol(...
    'Parent',handles.affinePanel,...
    'Units','pixel',...
    'FontSize',10,...
    'HorizontalAlignment','right',...
    'Position',[8 92+dy 118 17],...
    'String','Minimum Step:',...
    'Style','text',...
    'Tag','text65');

    h317 = uicontrol(...
    'Parent',handles.affinePanel,...
    'Units','pixel',...
    'FontSize',10,...
    'HorizontalAlignment','right',...
    'Position',[8 58+dy 118 17],...
    'String','Maximum Step:',...
    'Style','text',...
    'Tag','text66');

    h318 = uicontrol(...
    'Parent',handles.affinePanel,...
    'Units','pixel',...
    'FontSize',10,...
    'HorizontalAlignment','right',...
    'Position',[8 24+dy 118 17],...
    'String','Iteration Number :',...
    'Style','text',...
    'Tag','text67');

    handles.affine_iternum = uicontrol(...
    'Parent',handles.affinePanel,...
    'Units','pixel',...
    'FontSize',10,...
    'HorizontalAlignment','left',...
    'Position',[129 19+dy 78 23],...
    'String','200',...
    'Style','edit',...
    'Tag','affine_iternum');

    guidata(handles.mainframe, handles);

end


function dtiInitReorientBvecs(dwParams,dwDir,doResamp,doBvecs,bvecs,bvals)
%
%  doRawResample = dtiInitResample(dwParams,dwDir)
%
% Based on user selected params and the outputs of dtiInitAlign and
% dtiInitEddyCC we reorient and save bvecs and bvals files
%
% WEB resources:
%   http://white.stanford.edu/newlm/index.php/DTI_Preprocessing
%   mrvBrowseSVN('dtiInitReorientBvecs');
%
% (C) Stanford VISTA, 8/2011 [lmp]
%

%%
%
% If bvecs file was computed earlier doBvecs will = true. If clobber = true
% or the aligned BVs files do not exist we reorient and save.
if doBvecs || (doResamp && dwParams.clobber == -1) ...
           || dwParams.clobber == 1 ...
           || ~exist(dwDir.alignedBvecsFile,'file') ...
           || ~exist(dwDir.alignedBvalsFile,'file')
    % Reorient and save the b-vectors and bvals
    dtiRawReorientBvecs(bvecs, dwDir.ecFile, dwDir.acpcFile, dwDir.alignedBvecsFile);
    dlmwrite(dwDir.alignedBvalsFile,bvals,' ');
else
    % If clobber = 'ask' prompt the user to overwrite
    if dwParams.clobber == 0
        resp = questdlg([dwDir.alignedBvecsFile ' exists- would you like to overwrite it?'],...
            'Clobber Bvecs/bvals', 'Overwrite','Use Existing File','Abort','Use Existing File');
        if(strcmpi(resp,'Abort')), error('User aborted.'); end
        if(strcmpi(resp,'Overwrite'))
            % If the user selects to overwrite we reorient and save the
            % b-vectors and bvals
            dtiRawReorientBvecs(dwDir.bvecsFile, dwDir.ecFile, dwDir.acpcFile, dwDir.alignedBvecsFile);
            dlmwrite(dwDir.alignedBvalsFile,bvals,' ');
        end
    end
end


function display(this);

    disp(inputname(1));
    if length(this) == 1
        struct(this.EEG)
    else
        TMP = struct(this);

        TMP2 = TMP(1).EEG;
        fieldorder = fieldnames(TMP2);
        for index = 2:length(TMP)
            TMP2(index) = orderfields(TMP(index).EEG, fieldorder);
        end;
        TMP2
    end;


% make sure that running JAABADetect one classifier at a time gives the
% same results as running them in batch

function maxerr = FlyBowlJAABADetect_SanityCheck(expdir,classifierparamsfiles,varargin)

[classifierparams,isrelativepath] = ...
  myparse(varargin,'classifierparams',[],'isrelativepath',true);

if isempty(classifierparams),
  classifierparams = ReadClassifierParamsFile(classifierparamsfiles,'isrelativepath',isrelativepath);
end
nbehaviors = numel(classifierparams);

allScores = cell(1,nbehaviors);
maxerr = zeros(1,nbehaviors);
for i = 1:nbehaviors,

  behavior = classifierparams(i).behaviors.names{1};

  scorefile = fullfile(expdir,classifierparams(i).file.scorefilename);
  if ~exist(scorefile,'file'),
    warning('Score file %s does not exist',scorefile);
    continue;
  end

  allScores(i) = JAABADetect(expdir,'classifierfiles',{classifierparams(i).classifierfile},...
    'configfiles',{classifierparams(i).configfile},'debug',true,'forcecompute',true);

  scoresload = load(scorefile);
  nflies = numel(allScores{i});
  nflies2 = numel(scoresload.allScores.scores);
  if nflies ~= nflies2,
    warning('Number of flies does not match for %s',behavior);
    maxerr(i) = inf;
  end
  nflies = min(nflies,nflies2);
  for fly = 1:nflies,
    if numel(scoresload.allScores.scores{fly}) ~= numel(allScores{i}{fly}),
      warning('Number of frames does not match for %s fly %d\n',behavior,fly);
      maxerr(i) = inf;
    end
    realidx = ~isnan(scoresload.allScores.scores{fly});
    if ~all(~realidx == isnan(allScores{i}{fly})),
      fprintf('%s fly %d: nans do not match\n',behavior,fly);
      maxerr(i) = inf;
      continue;
    end
    maxdiff = max(abs(scoresload.allScores.scores{fly}(realidx) - allScores{i}{fly}(realidx)));
    if maxdiff > 0,
      fprintf('%s fly %d: scores do not match, maxdiff = %f\n',behavior,fly,maxdiff);
      maxerr(i) = max(maxerr(i),maxdiff);
    end
  end

end


function s=openRaw3ViewWindow
%
% Opens a volume 3-view (sag,axi,cor) window and initializes the corresponding data structure.
%
% VOLUME is a cell array of volume structures.
% s is the index of the new one.
%
% This function should ONLY be called by either:
% openVolumeWindow or openGrayWindow.
%
% Modifications:
%
% djh and baw, 7/98
% djh, 2/99 modified to enable the window to be opened under
% either volume or gray mode
%
% djh, 4/99
% - Eliminate overlayClip sliders
% - Added mapWin sliders to show overlay only for pixels with parameter
%   map values that are in the appropriate range.
% bw, 12/29/00
% - scan slider instead of buttons
% djh 2/13/2001
% - open multiple volume windows simultaneously
% ras 10/28/02
% - adds 'Rory' menu for Rory's analysis; local version
% ras 03/06/03
% revamp: now makes a '3-view' showing sagittal, coronal, and axial views
% all at once, instead of paging through the slices

% Make sure the global variables exist
mrGlobals

disp('Initializing Volume view')

% s is the index of the new volume structure.
s = getNewViewIndex(VOLUME); %#ok<NODEF>

% Set name, viewType, & subdir
VOLUME{s} = [];
VOLUME{s} = viewSet(VOLUME{s}, 'name', ['VOLUME{',num2str(s),'}']);
VOLUME{s} = viewSet(VOLUME{s}, 'viewType',  'Volume');
VOLUME{s} = viewSet(VOLUME{s}, 'subdir', 'Volume');

% Refresh function, gets called by refreshScreen
VOLUME{s} = viewSet(VOLUME{s}, 'refreshFn', 'volume3View');

%%%%%%%%%%%%%%%%%%
% Load Anatomies %
%%%%%%%%%%%%%%%%%%
VOLUME{s} = loadAnat(VOLUME{s});
%TODO: Change the functionality of loadAnat to bring it in line with the
%inplane load anat functionality

%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialize data slots %
%%%%%%%%%%%%%%%%%%%%%%%%%

% Initialize slots for co, amp, and ph
VOLUME{s}.co = [];
VOLUME{s}.amp = [];
VOLUME{s}.ph = [];
VOLUME{s}.map = [];
VOLUME{s}.mapName = '';
VOLUME{s}.mapUnits = '';

% Initialize slots for tSeries
VOLUME{s}.tSeries = [];
VOLUME{s}.tSeriesScan = NaN;
VOLUME{s}.tSeriesSlice = NaN;

% Initialize ROIs
VOLUME{s}.ROIs = [];
VOLUME{s}.selectedROI = 0;

% Initialize curDataType / curScan
VOLUME{s}.curDataType = 1;
VOLUME{s}.curScan = 1;

% Initialize location in volume space
dims = viewGet(VOLUME{s},'Size');
VOLUME{s}.loc = round(dims./2);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Make displayModes and color maps %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Initialize displayModes
VOLUME{s} = resetDisplayModes(VOLUME{s});
VOLUME{s}.ui.displayMode = 'anat';

%%%%%%%%%%%%%%%%%%%
% Open the window %
%%%%%%%%%%%%%%%%%%%
% Figure number for volume view window
figName = sprintf('Volume %i', s);
if isfield(mrSESSION,'sessionCode') && isfield(mrSESSION,'description'),
  figName = sprintf('%s: %s  [%s]', figName, mrSESSION.sessionCode, ...
                    mrSESSION.description);
end

VOLUME{s}.ui.figNum = figure('Name', figName, ...
                             'MenuBar', 'none', ...
                             'Units', 'Normalized',...
                             'Color', [.9 .9 .9], ...
                             'Position', [0.25 0.25 0.5 0.5],...
                             'NumberTitle', 'off',  ...
                             'Tag', ['3VolumeWindow: ',VOLUME{s}.name]);

% Handle for volume view window
VOLUME{s}.ui.windowHandle = gcf;

% set up 3 axes, for each view of the volume:
VOLUME{s}.ui.sagAxesHandle = axes('position',[.15 .5 .4 .4]);
VOLUME{s}.ui.corAxesHandle = axes('position',[.5 .5 .4 .4]);
VOLUME{s}.ui.axiAxesHandle = axes('position',[.5 .15 .4 .4]);

% The 'main' axis will arbitarily refer to the axial window
VOLUME{s}.ui.mainAxisHandle = VOLUME{s}.ui.axiAxesHandle;

% ras 05/06: for faster updating, keep track of image/obj handles:
VOLUME{s}.ui.underlayHandle = []; % for ML7+, will make overlays
VOLUME{s}.ui.overlayHandle = [];  % a separate img, and use alpha maps
VOLUME{s}.ui.roiHandles = {};

% Set minColormap property so there's potentially room for 128
% colors
%set(VOLUME{s}.ui.windowHandle, 'minColormap', 128);

% Set closeRequestFcn so we can clean up when the window is closed
set(gcf, 'CloseRequestFcn', 'closeVolumeWindow');

% Set selectedVOLUME when click in this window
set(gcf, 'WindowButtonDownFcn', ['selectedVOLUME =',num2str(s),';']);

%%%%%%%%%%%%%
% Add Menus %
%%%%%%%%%%%%%
disp('Attaching menus')

VOLUME{s} = filesMenu(VOLUME{s});
VOLUME{s} = editMenu(VOLUME{s});
VOLUME{s} = windowMenu(VOLUME{s});
VOLUME{s} = analysisMenu(VOLUME{s});
VOLUME{s} = viewMenu(VOLUME{s});
VOLUME{s} = roiMenu(VOLUME{s});
VOLUME{s} = plotMenu(VOLUME{s});
VOLUME{s} = colorMenu(VOLUME{s});
VOLUME{s} = xformVolumeMenu(VOLUME{s});
VOLUME{s} = grayMenu(VOLUME{s});
VOLUME{s} = eventMenu(VOLUME{s});
VOLUME{s} = helpMenu(VOLUME{s}, 'Volume');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add Annotation String; move to nicer location %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
VOLUME{s} = makeAnnotationString(VOLUME{s});

%%%%%%%%%%%%%%%%%
% Add Color Bar %
%%%%%%%%%%%%%%%%%
% % Make color bar and initialize it to 'off'
VOLUME{s}.ui.colorbarHandle = makeColorBar(VOLUME{s});
setColorBar(VOLUME{s},'off');
VOLUME{s}.ui.cbarRange = [];

%%%%%%%%%%%%%%%%%%%
% Add buttons     %
%%%%%%%%%%%%%%%%%%%
disp('Attaching buttons')

% Buttons and editable text fields for choosing slice number and
% slice orientation
VOLUME{s} = make3ViewSliceUI(VOLUME{s});
setCurSliceOri(VOLUME{s},1); % default to axials

% Buttons for choosing gray mode vs volume mode
VOLUME{s} = makeGrayVolButtons(VOLUME{s});

% add some zoom buttons
VOLUME{s} = makeZoomButtons(VOLUME{s});

% now add a checkbox to toggle the crosshairs
xHairColor = [1 .5 .5];
if ispref('VISTA', 'xHairColor')
    xHairColor = getpref('VISTA', 'xHairColor', xHairColor);
end
callback = [VOLUME{s}.name ' = toggle3ViewCrossHairs(' VOLUME{s}.name ', gcbo);'];
htmp = uicontrol('Style', 'checkbox', 'String', 'Crosshairs', ...
                 'Value', 0, 'Callback', callback, ...
                 'BackgroundColor', get(gcf,'Color'), ...
                 'ForegroundColor', xHairColor ,...
                 'Units', 'Normalized', 'Position', [0 0.1 0.1 0.05]);
VOLUME{s}.ui.xHairToggleHandle = htmp;
VOLUME{s}.ui.crosshairs = 0; % crosshairs initialized off

%%%%%%%%%%%%%%%%%%%
% Add popup menus %
%%%%%%%%%%%%%%%%%%%
disp('Attaching popup menus')

VOLUME{s} = makeROIPopup(VOLUME{s});
VOLUME{s} = makeDataTypePopup(VOLUME{s});

%%%%%%%%%%%%%%%
% Add sliders %
%%%%%%%%%%%%%%%
disp('Attaching sliders')

% Scan number slider
w = 0.12; h = 0.03; l = 0; b = 0.95;
VOLUME{s} = makeSlider(VOLUME{s},'scan',[],[l b w h]);
VOLUME{s} = initScanSlider(VOLUME{s},1);
VOLUME{s} = selectDataType(VOLUME{s},VOLUME{s}.curDataType);

% correlation threshold:
VOLUME{s} = makeSlider(VOLUME{s},'cothresh',[0,1],[.85,.85,.15,.03]);
setCothresh(VOLUME{s},0);

% phase window:
VOLUME{s} = makeSlider(VOLUME{s},'phWinMin',[0,2*pi],[.85,.75,.15,.03]);
VOLUME{s} = makeSlider(VOLUME{s},'phWinMax',[0,2*pi],[.85,.65,.15,.03]);
setPhWindow(VOLUME{s},[0 2*pi]);

% parameter map window:
VOLUME{s} = makeSlider(VOLUME{s},'mapWinMin',[0,1],[.85,.55,.15,.03]);
VOLUME{s} = makeSlider(VOLUME{s},'mapWinMax',[0,1],[.85,.45,.15,.03]);
setMapWindow(VOLUME{s},[0 1]);

% Brightness / Contrast: (Replaces older Anat Clip).
VOLUME{s} = makeBrightnessSlider(VOLUME{s},[.85 .2 .15 .03]);
VOLUME{s} = makeSlider(VOLUME{s},'contrast',[0 1],[.85 .1 .15 .03]);
VOLUME{s} = viewSet(VOLUME{s},'brightness',0.5);
VOLUME{s} = viewSet(VOLUME{s},'contrast',0.05);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialize display parameters %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialize image field
VOLUME{s}.ui.image = [];

% New ROI display fields (ras 01/07)
VOLUME{s}.ui.showROIs = -2;        % list of ROIs to show (0 = hide, -1 = selected)
VOLUME{s}.ui.roiDrawMethod = 'perimeter'; % can be 'boxes', 'perimeter', 'patches'
VOLUME{s}.ui.filledPerimeter = 0; % filled perimeter toggle

disp('Done initializing Volume view')

return;


%Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
%Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
%   notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
%   notice, this list of conditions and the following disclaimer in the
%   documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

function index = flann_load_index(filename, dataset)
%FLANN_LOAD_INDEX  Loads an index from disk
%
% Marius Muja, March 2009

    index = nearest_neighbors('load_index', filename, dataset);
end


classdef ThrottleTermCondOptimVar < AbstractOptimizationVariable
    %ThrottleTermCondOptimVar Summary of this class goes here
    %   Detailed explanation goes here

    properties
        varObj(1,1) ThrottleTermCondition = ThrottleTermCondition(0);

        lb(1,1) double = 0;
        ub(1,1) double = 0;

        useTf(1,1) = false;
    end

    methods
        function obj = ThrottleTermCondOptimVar(varObj)
            obj.varObj = varObj;
            obj.varObj.optVar = obj;

            obj.id = rand();
        end

        function x = getXsForVariable(obj)
            x = [];

            if(obj.useTf)
                x = obj.varObj.targetThrottle;
            end
        end

        function [lb, ub] = getBndsForVariable(obj)
            lb = obj.lb(obj.useTf);
            ub = obj.ub(obj.useTf);
        end

        function [lb, ub] = getAllBndsForVariable(obj)
            lb = obj.lb;
            ub = obj.ub;
        end

        function setBndsForVariable(obj, lb, ub)
            obj.lb = lb;
            obj.ub = ub;
        end

        function useTf = getUseTfForVariable(obj)
            useTf = obj.useTf;
        end

        function setUseTfForVariable(obj, useTf)
            obj.useTf = useTf;
        end

        function updateObjWithVarValue(obj, x)
            obj.varObj.targetThrottle = x;
        end

        function nameStrs = getStrNamesOfVars(obj, evtNum, varLocType)
            nameStrs = {sprintf('Event %i Throttle Termination Condition', evtNum)};
        end
    end
end


%kkxv 'XV, image visualization and color edit, by J. Bradley '
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kxv.pane file
%
% Parameters:
% InputFile: i 'Input ', optional: 'First Input data object'
% Toggle: kdfin 'KDF input compatibility', default: 0: 'accepts KDF input file'
% OutputFile: o 'Output', optional: 'Resulting output data object'
% Toggle: kdfout 'KDF output compatibility', default: 0: 'converts to KDF after calling xv'
%
% Example: o = kkxv(i, {'i','';'kdfin',0;'o','';'kdfout',0})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kxv - XV, image visualization and color edit, by J. Bradley
%
%  DESCRIPTION
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc.  All rights reserved.
%

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

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


function exp_endfun(varargin)
% End the definition of an expression-aware function.
% exp_endfun(Arguments...)
%
% See exp_beginfun. Invokes plugin functions that shall run after the body of the expression-aware
% function (here called poststeps) and handles memoization.
%
% In:
%   Arguments... : optional name-value pairs; some options allowed in exp_beginfun can also be
%                  overridden here: 'set_online', 'append_online', 'add_impure'
%
% Notes:
%   The exp_endfun must be called in every code path that exits the function being defined (except
%   for error conditions), i.e. a premature return must be preceded by and exp_endfun;
%
% See also:
%   exp_beginfun, exp_eval
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-04-15
dp;

% retrieve the context structure
% If you get an "Undefined function or variable" error here then you forgot to call exp_beginfun
% at the beginning of the same function in which exp_endfun was called
context = evalin('caller','exp_internal_context');
if ~context.enabled
    return; end

% update the new function input & output arguments
for i=1:length(context.outargs)
    try context.ws_output_post.(context.outargs{i}) = evalin('caller',context.outargs{i}); catch, end
end

% if the arg system is used by the function, we have an easier-to-handle version of the posteval expression
if evalin('caller','exist(''arg_nvps'',''var'')')
    context.expression_posteval.parts = evalin('caller','arg_nvps'); end

% assign additional exp_endfun options to the context's options...
if ~iscellstr(varargin(1:2:end))
    error('The given arguments must be name-value pairs.'); end
for k=1:2:length(varargin)
    context.opts.(varargin{k}) = varargin{k+1}; end

if context.opts.add_impure
    % if impure, incorporate the original unevaluated expression into the function result (if it's a struct)
    if isfield(context.ws_output_post,context.outargs{1}) && isstruct(context.ws_output_post.(context.outargs{1}))
        context.ws_output_post.(context.outargs{1}).tracking.expression = context.expression_preeval; end
end

% run the poststep(s) on the workspaces (add online expression, etc.)
for s = 1:length(context.opts.poststeps)
    context = context.opts.poststeps{s}(context); end

% handle fingerprinting of the result
if isempty(context.opts.fingerprint_create)
    context.opts.fingerprint_create = hlp_resolve('fingerprint_create',true,context.exec_ctx); end
if strcmp(context.opts.fingerprint_create,'passthrough')
    % no changes are being made to the fingerprint of the output
elseif isfield(context.ws_output_post,context.outargs{1}) && is_impure_expression(context.ws_output_post.(context.outargs{1}))
    % we have an impure expression as output
    if ~isequal(false,context.opts.fingerprint_create) && ~isequal(false,exp_eval(utl_replacerepeated(context.opts.fingerprint_create,{exp_rule(@expression,context.expression_preeval)}),inf)) ...
        % fingerprint creation turned on: fingerprint the data, so we can later check the consistency of impure expression
        context.ws_output_post.(context.outargs{1}).tracking.fingerprint = hlp_fingerprint(rmfield(context.ws_output_post.(context.outargs{1}),'tracking'));
    else
        % fingerprint creation turned off: make sure that the fingerprint gets removed...
        if isfield(context.ws_output_post.(context.outargs{1}).tracking,'fingerprint')
            context.ws_output_post.(context.outargs{1}).tracking = rmfield(context.ws_output_post.(context.outargs{1}).tracking,'fingerprint'); end
    end
end

% remember the computation time of the object
if isfield(context.ws_output_post,context.outargs{1}) && is_impure_expression(context.ws_output_post.(context.outargs{1}))
    context.ws_output_post.(context.outargs{1}).tracking.computation_time = toc(context.eval_time); end

% assign the changed values in the workspace
for fn=fieldnames(context.ws_output_post)'
    assignin('caller',fn{1},context.ws_output_post.(fn{1})); end

% memoize the results (for the original expression)
if ~isempty(context.memoize_id) && isfield(context.ws_output_post,context.outargs{1})
    obj = {context.ws_output_post.(context.outargs{1})};
    for k=2:length(context.outargs)
        % and also append the other output arguments as far as they are set
        try obj = [obj {context.ws_output_post.(context.outargs{k})}]; catch break; end
    end

    % commit object to cache
    utl_memoize_commit(obj,context.memoize_id,context.input_size);
end


function dfsetbinwidthrules(dataset, v0, v1, v2, v3, v4, v5, v6)
% DFSETBINWIDTHRULES Helper function for the dfittool set default bin width panel

%   Copyright 2003-2004 The MathWorks, Inc.
%   $Revision: 1.1.6.3 $  $Date: 2004/01/24 09:35:47 $

binDlgInfo.rule = v0;
binDlgInfo.nbinsExpr = v1;
binDlgInfo.nbins = str2num(v1);
binDlgInfo.widthExpr = v2;
binDlgInfo.width = str2num(v2);
binDlgInfo.placementRule = v3;
binDlgInfo.anchorExpr = v4;
binDlgInfo.anchor = str2num(v4);
binDlgInfo.applyToAll = v5;
binDlgInfo.setDefault = v6;

if (v5 == true) % apply to all
    dsdb = getdsdb;
    ds = down(dsdb);
    while(~isempty(ds))
        ds.binDlgInfo = binDlgInfo;
        ds = right(ds);
    end
    dfupdateallplots(true, false, true);
elseif ~isempty(dataset)
    ds = handle(dataset);
    ds.binDlgInfo = binDlgInfo;
    clearplot(ds);
    updateplot(ds);
end

% Update the main fig axis limits to fit the new histograms
dfupdatexlim;
dfupdateylim;

if (v6 == true) % set default
    dfgetset('binDlgInfo', binDlgInfo);
end


addpath('../core');
addpath('../helpers');

run ../vlfeat/toolbox/vl_setup ;
run ../matconvnet/matlab/vl_setupnn ;

if(~exist('data', 'dir'))
  mkdir('data');
end

if(~exist('data/results', 'dir'))
  mkdir('data/results');
end

if(~exist('networks/imagenet-caffe-ref.mat', 'file'))
  cmd='wget http://www.robots.ox.ac.uk/~aravindh/imagenet-caffe-ref.mat -O networks/imagenet-caffe-ref.mat';
  system(cmd);
  clear cmd;
end

addpath('networks')


function net = remove_layers_from_block(net, type)
  [names, ~] = find_layers_from_block(net, type);
  for i = 1:numel(names)
    layer = net.layers(net.getLayerIndex(names{i}));
    net.removeLayer(names{i});
    net.renameVar(layer.outputs{1}, layer.inputs{1}, 'quiet', true);
  end
end


function [success] = compile_mex(name, files, includes, directory, varargin)
% compile_mex Compile given source files to a MEX function
%
% Compiles or recompiles given source files to a MEX function taking
% into account source files timestamps. Also works in Octave by switching
% to mkoctfile command.
%
% Input:
% - name (string): Name of MEX function.
% - files (cell array): Array of source files.
% - includes (cell array): Optional array of include directories.
% - directory (string): Optional path of target directory.
%
% Output:
% - success (boolean): True if successful.
%

    function datenum = file_timestamp(filename)
        if ~exist(filename, 'file')
            datenum = 0;
            return;
        end;
        file_description = dir(filename);
        datenum = file_description.datenum;
    end

    mexname = fullfile(directory, sprintf('%s.%s', name, mexext));

    if exist(mexname, 'file') == 2 || exist(mexname, 'file') == 3

        function_timestamp = file_timestamp(mexname);

        older = cellfun(@(x) file_timestamp(x) < function_timestamp, files, 'UniformOutput', true);

        if all(older)
            success = true;
            return;
        end;
    end

    mexdebug = get_global_variable('mex_debug', false);

    arguments = {};

    if is_octave()
       arguments{end+1} = '-DOCTAVE';
    else
        arguments{end+1} = '-lut';
    end

    if mexdebug
       arguments{end+1} = '-g';
    end;

    if nargin < 3
        includes = cell(0);
    end

    if nargin < 4
        directory = '';
    end;

    includes = cellfun(@(x) sprintf('-I%s', x), includes, 'UniformOutput', false);

    old_dir = pwd;

    try

        if ~isempty(directory)
            cd(directory)
        end;

        if is_octave()

            [out, status] = mkoctfile('-mex', '-o', name, varargin{:}, includes{:}, files{:}, arguments{:});

            % Clean up mess
            for i = 1:numel(files)
                [pathstr, name, ext] = fileparts(files{i});
                tmpfile = fullfile(directory, [name, '.o']);
                if exist(tmpfile, 'file')
                  delete(tmpfile);
                end
            end

            if status
                error('Compile problem, see compiler output.');
            end;

        else

            mex('-output', name, varargin{:}, includes{:}, files{:}, arguments{:});

        end

        cd(old_dir);

        success = true;

    catch e
        cd(old_dir);
        print_text('ERROR: Unable to compile MEX function: "%s".', e.message);
        success = false;

    end

end


% This function select utterance names from ID cell array that also appears
% in key cell array. It also select the corresponding features in data
% arrya.
% The function assumes key is already sorted.
% [ID_selected, data_selected] = selectData(key, ID, data, FollowKeyIdx)
%
function [ID_selected, data_selected] = selectData(key, ID, data, FollowKeyIdx)
if nargin<4
    FollowKeyIdx = 0;
end

if FollowKeyIdx==0
    ID_selected = {};
    data_selected = {};
end
for i=1:length(ID)
    found = searchInCellBinary(key, ID{i}, 1, length(key));
    if found > 0
        if FollowKeyIdx
            ID_selected{found} = ID{i};
            data_selected{found} = data{i};
        else
            ID_selected{end+1} = ID{i};
            data_selected{end+1} = data{i};
        end
    end
end


function varargout = maxDeltaVInputGUI(varargin)
% MAXDELTAVINPUTGUI MATLAB code for maxDeltaVInputGUI.fig
%      MAXDELTAVINPUTGUI, by itself, creates a new MAXDELTAVINPUTGUI or raises the existing
%      singleton*.
%
%      H = MAXDELTAVINPUTGUI returns the handle to a new MAXDELTAVINPUTGUI or the handle to
%      the existing singleton*.
%
%      MAXDELTAVINPUTGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in MAXDELTAVINPUTGUI.M with the given input arguments.
%
%      MAXDELTAVINPUTGUI('Property','Value',...) creates a new MAXDELTAVINPUTGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before maxDeltaVInputGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to maxDeltaVInputGUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help maxDeltaVInputGUI

% Last Modified by GUIDE v2.5 26-Jun-2013 19:03:07

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @maxDeltaVInputGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @maxDeltaVInputGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before maxDeltaVInputGUI is made visible.
function maxDeltaVInputGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to maxDeltaVInputGUI (see VARARGIN)

% Choose default command line output for maxDeltaVInputGUI
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

%Possible fix for people with display issues.
checkForCharUnitsInGUI(hObject);

options = varargin{1};
deltaVStrName = deltaVTypeEnum(options.quant2opt);
dvTypeStr =  {'Delta-V To Optimize:', deltaVStrName};
set(handles.dvtypelabel, 'String', dvTypeStr);

% UIWAIT makes maxDeltaVInputGUI wait for user response (see UIRESUME)
uiwait(handles.maxDeltaVInputGUI);

% --- Outputs from this function are returned to the command line.
function [maxDV, varargout] = maxDeltaVInputGUI_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
try
varargout{1} = handles.output;
maxDV = str2double(get(handles.maxDVText,'String'));
close(hObject);
catch
    varargout{1} = -1;
    maxDV = 0.0;
end

function maxDVText_Callback(hObject, eventdata, handles)
% hObject    handle to maxDVText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of maxDVText as text
%        str2double(get(hObject,'String')) returns contents of maxDVText as a double
newInput = attemptStrEval(get(hObject,'String'));
set(hObject, 'String', newInput);

% --- Executes during object creation, after setting all properties.
function maxDVText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to maxDVText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in okayButton.
function okayButton_Callback(hObject, eventdata, handles)
% hObject    handle to okayButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
errMsg = {};

maxDV = str2double(get(handles.maxDVText,'String'));
enteredStr = get(handles.maxDVText,'String');
numberName = 'Maximum delta-v';
lb = 0.01;
ub = 100;
isInt = false;
errMsg = validateNumber(maxDV, numberName, lb, ub, isInt, errMsg, enteredStr);

if(isempty(errMsg))
    uiresume(handles.maxDeltaVInputGUI);
else
    msgbox(errMsg,'Errors were found in maximum delta-v inputs','error');
end


function dataset = voc2007_trainval(dataset, usage, use_flip)
% Pascal voc 2007 trainval set
% set opts.imdb_train opts.roidb_train
% or set opts.imdb_test opts.roidb_train

% change to point to your devkit install
devkit                      = voc2007_devkit();

switch usage
    case {'train'}
        dataset.imdb_train    = {  imdb_from_voc(devkit, 'trainval', '2007', use_flip) };
        dataset.roidb_train   = cellfun(@(x) x.roidb_func(x), dataset.imdb_train, 'UniformOutput', false);
    case {'test'}
        dataset.imdb_test     = imdb_from_voc(devkit, 'trainval', '2007', use_flip) ;
        dataset.roidb_test    = dataset.imdb_test.roidb_func(dataset.imdb_test);
    otherwise
        error('usage = ''train'' or ''test''');
end

end


classdef LevelSetSmoothRectangleInclusion < SettingsLevelSetCreator

    properties (Access = public)
        widthH
        widthV
        pnorm
    end

    methods (Access = public)

        function obj = LevelSetSmoothRectangleInclusion(varargin)
            obj.loadParams('paramsLevelSetCreator_SmoothRectangle.json')
            if nargin == 1
                obj.loadParams(varargin{1})
            end
        end

    end

end


names_list = { ...
%    {'red-9' 'blue-7'}, ...
%    {'blue-1' 'red-5'}, ...
%    {'blue-5' 'red-3'}, ...
%    {'red-7' 'yellow-1'}, ...
%    {'red-5' 'blue-7'}, ...
%    {'yellow-2' 'purple-1'}, ...
%    {'green-2' 'red-5'}, ...  % PBM
%    {'green-2' 'purple-1'}, ...
% {'street-3', 'street-5'}, ...
% {'nature-3' 'art'}, ...
% {'street-4' 'street-6'}, ...
% {'street-2' 'street-7'}, ...
% {'street-8' 'street-1'}, ...
% {'nature-7' 'street-4'}, ...
% {'nature-7' 'street-2'}, ...
% {'street-11' 'street-10'}, ...
% {'colors1' 'colors2'}, ...
% {'colors3' 'colors4'}, ...
% {'colors5' 'colors6'}, ...
% {'colors7' 'colors8'}, ...
% {'colors9' 'colors8'}, ...
% {'nature-7' 'street-1'}, ...
% {'street-2' 'street-4'}, ...
% {'colors1' 'street-1'}, ...
% {'colors2' 'street-2'}, ...
% {'colors3' 'street-3'}, ...
% {'colors4' 'nature-7'}, ...
% {'colors5' 'street-4'}, ...
% {'colors6' 'street-5'}, ...
% {'colors7' 'street-7'}, ...
% {'colors8' 'street-10'}, ...
% {'colors9' 'street-11'}, ...
% {'colors10' 'vegetable-9'}, ...
% {'nature-2' 'portrait-2'}, ...
% {'nature-3' 'vegetable-1'}, ...
% {'nature-4' 'vegetable-6'}, ...
% {'nature-5' 'vegetable-11'}, ...
% {'nature-6' 'vegetable-12'}, ...
 {'green-5' 'red-5'}, ...
 {'green-6' 'red-5'}, ...
 {'green-7' 'red-5'}, ...
 {'landscape-1' 'red-5'}, ...
    };

for it=1:length(names_list)

    names = names_list{it};
    disp(['------ ' names{1} '/' names{2} ' ------']);
    generateColorFigure;
end


function [ cimages ] = getSurfaceLabel(imdir,imagename,workspcdir, vpdata)

moveFolder = './roomModel/SpatialLayout_shrink/';

outimgdir = [workspcdir 'Images/'];
if ~exist(outimgdir,'dir')
    mkdir(outimgdir);
end
workspcdir = [workspcdir 'data/'];
if ~exist(workspcdir,'dir')
    mkdir(workspcdir);
end

% tempdir='./sptiallayouttempworkspace/';
%Compute vps
boxlayout=[];
surface_labels=[];

img=imread([imdir imagename]);
[h w kk]=size(img);
if ~exist('vpdata','var')
    [vp p All_lines]=getVP(imdir,imagename,0,workspcdir);
    VP=vp;
    if numel(VP)<6
        aa = zeros(h,w);
        indd = zeros(h,w);
        return;
    end

    vp=[VP(1) VP(2);VP(3) VP(4);VP(5) VP(6)];
    [vp P]=ordervp(vp,h,w,p);
    [vv linemem]=max(P,[],2);
    vpdata.vp=vp;
    vpdata.lines=All_lines;
    vpdata.linemem=linemem;
    vpdata.dim=[h w];
%     visvp(vpdata,img)
end

%Get segmentation and GC surface confidence maps
% sigma=num2str(0.8);
% k1=num2str(100);
% min1=num2str(100);
% inputim=[workspcdir imagename(1:end-4) '.ppm'];
% outputim=[workspcdir imagename(1:end-4) '.pnm'];
% [s w]=system(['./segment' ' ' sigma ' '  k1  ' ' min1 ' ' inputim ' ' outputim ]);

segext='pnm';
nsegments=[5 15 25 35 40 60 80 100];
% fn=['../Imsegs/' imagename(1:end-4) '.' segext];
fn=[moveFolder '/Imsegs/' imagename(1:end-4) '.' segext];
imseg = processSuperpixelImage(fn);

tic
imdata = mcmcComputeImageData(im2double(img), imseg);% made changes here
toc

load(fullfile([moveFolder '/LabelClassifier/'], 'Classifiers_gc.mat'));

spfeatures = mcmcGetAllSuperpixelData(imdir, imseg);
[efeatures, adjlist] = mcmcGetAllEdgeData(spfeatures, imseg(1));

nsegments=[5 15 25 35 40 60 80 100];

pE{1} = test_boosted_dt_mc(eclassifier, efeatures{1});
pE{1} = 1 ./ (1+exp(ecal(1)*pE{1}+ecal(2)));
smaps{1} = msCreateMultipleSegmentations(pE{1}, adjlist{1}, ...
    imseg(1).nseg, nsegments);

for k = 1:numel(nsegments)
    if max(smaps{1}(:, k))>0
        segfeatures{1, k} = mcmcGetSegmentFeatures(imseg, ...
            spfeatures{1}, imdata, smaps{1}(:, k), (1:max(smaps{1}(:, k))));
    end
end

%Get surface label confidences initial from GC
normalize = 1;
pg=zeros(imseg.nseg,7);%7 labels
%get P(L/I)
pg = msTest(imseg, segfeatures, smaps, ...
    labelclassifier, segclassifier,normalize);

filename=fullfile(workspcdir, [imagename(1:end-4) '_lc_gc.mat' ]);
save(filename,'pg');

%visualize

%Compute intergral images for features
tic
[integData]=getIntegralimages([imagename],vpdata,imseg,500,workspcdir,imdir);
toc

%Get candidate layouts and their features
[polyg, Features] = getcandboxlayout( vpdata.vp,vpdata.dim(1),vpdata.dim(2),integData);

%Get initial estimate
Features1=Features;

% load ../LearntClassifiers/pf_i.mat
load([moveFolder '/LearntClassifiers/pf_i.mat']);

lay_score=[];
numL=size(Features,1);
% change features
if(numel(weights)==14)
    tmpf1=sum(Features(:,1:5).*Features(:,11:15),2);
    tmpf2=sum(Features(:,1:5).*Features(:,16:20),2);
    tmpf3=sum(Features(:,6:10).*Features(:,11:15),2);
    tmpf4=sum(Features(:,6:10).*Features(:,16:20),2);
    Features=[Features(:,1:10) tmpf1 tmpf2 tmpf3 tmpf4];

end
%evaluate
score=repmat(weights,[numL,1]).*Features;
score=sum(score,2);
[vv ii]=sort(score,'descend');

boxlayout.polyg=polyg;
boxlayout.init=[vv ii];

% load ../LearntClassifiers/pf_il.mat
load([moveFolder '/LearntClassifiers/pf_il.mat']);
Features=Features1;
if(numel(weights)==59)
    tmpf1=sum(Features(:,1:5).*Features(:,11:15),2);
    tmpf2=sum(Features(:,1:5).*Features(:,16:20),2);
    tmpf3=sum(Features(:,6:10).*Features(:,11:15),2);
    tmpf4=sum(Features(:,6:10).*Features(:,16:20),2);
    Features=[Features(:,1:10) tmpf1 tmpf2 tmpf3 tmpf4 Features(:,31:75) ];%Features(:,114:122)];

end
score=repmat(weights,[numL,1]).*Features;
score=sum(score,2);
[vv ii]=sort(score,'descend');

boxlayout.reestimated=[vv ii];

lay_scores=[vv ii];
save([workspcdir imagename(1:end-4) '_layres.mat'],'polyg','lay_scores');%,'avg_pg');

figure(101);
drawnow;
for lay=1:25
    layoutid=ii(lay);
    Polyg=[];
    for fie=1:5
        Polyg{fie}=[];
        if size(polyg{layoutid,fie})>0
            Polyg{fie}=polyg{layoutid,fie};
        end
    end

    tempimg=displayout(Polyg,w,h,img);
    subplot(5,5,lay);imshow(uint8(tempimg),[]);title(num2str(vv(lay)));
end
saveas(101,[outimgdir imagename(1:end-4) '_boxlayouts.png']);

Polyg=[];
for fie=1:5
    Polyg{fie}=[];
    if size(polyg{ii(1),fie})>0
        Polyg{fie}=polyg{ii(1),fie};
    end
end
ShowGTPolyg(img,Polyg,103);
saveas(103,[outimgdir imagename(1:end-4) '_boxlayout.png']);

%Re-Compute Surface labels (GC+box layout features)
% load(['../LabelClassifier/' 'Classifiers_stage2.mat']);
load([moveFolder '/LabelClassifier/' 'Classifiers_stage2.mat']);
tic
xspfields=[];%save per image
numSup=imseg.nseg;
for lay=1:numL %each layout
    xspf=[];
    for  supno=1:numSup
        tempbndy=imdata.tracedbndy{supno}{1};
        if size(tempbndy,1) > 30

            YY1=tempbndy(1:10:end,1);XX1=tempbndy(1:10:end,2);
        else

            YY1=tempbndy(:,1);XX1=tempbndy(:,2);
        end

        for fi=1:5  %each field
            xarea=0;
            if size(polyg{lay,fi},1)>0

                XX2=polyg{lay,fi}(:,1);
                YY2=polyg{lay,fi}(:,2);

                [in on]=inpolygon(XX1,YY1,[XX2;XX2(1)],[YY2;YY2(1)]);

                if numel(find(in==1))==length(in)
                    X0=XX1;Y0=YY1;
                    xarea=polyarea([X0;X0(1)],[Y0;Y0(1)]);
                elseif  numel(find(in==1))==0

                    X0=[];Y0=[];
                    xarea=0;
                else
                    xarea=polyintarea(XX1,YY1,XX2,YY2,0);

                end

            end
            xspf(supno,fi)=xarea;
        end

    end
    xspfields{lay}=xspf;
end
toc

nsp=imseg.nseg; %num of suppixels
smap = [1:nsp];
smaps{1} = smap(:);

clear segfeatures
for k = 1: 1%numel(nsegments)
    features = mcmcGetSegmentFeatures(imseg, ...
        spfeatures{1}, imdata, smaps{1}(:, k), (1:max(smaps{1}(:, k))));

    for lay=1:numL
        tempfeatures=features;
        [fieldfeatures]=segfieldsfeat_sup(imseg,imseg.nseg,smaps{1}(:,k),xspfields{lay});
        tempfeatures(:,95:100)=fieldfeatures(1:size(features,1),:);
        tempfeatures(:,101:106)=pg{1}(:,1:6);
        segfeatures{lay,k}  = tempfeatures;
    end
end

if numel(vv)>100
    A = [vv(1) 1;vv(100) 1];
else
    A = [vv(1) 1;vv(end) 1];
end
b = [0;log(49)];
params = inv(A)*b;

%     conf = 1./(1+exp(params(1)*vv(1:5)+params(2)));
conf = 1./(1+exp(params(1)*vv(1)+params(2)));
conf=conf./sum(conf);

avg_pg=zeros(imseg.nseg,7);%7 labels

tic
for j=1:1 %take best 5 scored layouts
    lay=ii(j);

    %get P(L/F,I)
    pg = msTest(imseg, segfeatures(lay, :), smaps, ...
        labelclassifier);%, segclassifier,normalize);
    avg_pg=avg_pg+pg{1}.*conf(j);

end
toc

filename=fullfile(workspcdir,[imagename(1:end-4) '_lc_st2.mat' ]);
save(filename,'avg_pg');

surface_labels.restimated={avg_pg};
surface_labels.init=pg;

rl=[255  255 0  0 0 255 0];
gl=[255 0 255  255 0 0 0];
bl=[0  0 255 0 255 255 0];
rl1=[255 202 132 255 0 255 0 191 0 0];
gl1=[236 255 112 255 191 0 255 21 0 0];
bl1=[139 112 255  255 255 0 0 133 255 0];
cimages = msPg2confidenceImages(imseg,{avg_pg});
[aa indd]=max(cimages{1}(:,:,1:6),[],3);

figure(102);
clear mask_color;
mask_r = rl(indd);
mask_g = gl(indd);
mask_b = bl(indd);
mask_color(:,:,1) = mask_r;
mask_color(:,:,2) = mask_g;
mask_color(:,:,3) = mask_b;

hsvmask=rgb2hsv(mask_color);
hsvmask(:,:,3)=aa*255;
%     hsvmask(:,:,2)=aa;
mask_color=hsv2rgb(hsvmask);

tempimg = double(img)*0.5 + mask_color*0.5;
%         tempimg =  mask_color;
imshow(uint8(tempimg));
saveas(102,[outimgdir imagename(1:end-4) '_surfacelabels.png']);

end