function marker = extractScatterhistogramMarker(patch_data, t)

% EXTRACTS THE MARKER STYLE USED FOR MATLAB OBJECTS
% OF TYPE "PATCH". THESE OBJECTS ARE USED IN AREASERIES
% BARSERIES, CONTOURGROUP, SCATTERGROUP.

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

%-AXIS STRUCTURE-%
axis_data = get(ancestor(patch_data.Parent,'axes'));

%-FIGURE STRUCTURE-%
figure_data = get(ancestor(patch_data.Parent,'figure'));

%-INITIALIZE OUTPUT-%
marker = struct();

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

%-MARKER SIZE (STYLE)-%
marker.size = patch_data.MarkerSize(t)*0.20;

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

%-MARKER SYMBOL (STYLE)-%
if ~strcmp(patch_data.MarkerStyle(t),'none')

    switch patch_data.MarkerStyle(t)
        case '.'
            marksymbol = 'circle';
        case 'o'
            marksymbol = 'circle';
        case 'x'
            marksymbol = 'x-thin-open';
        case '+'
            marksymbol = 'cross-thin-open';
        case '*'
            marksymbol = 'asterisk-open';
        case {'s','square'}
            marksymbol = 'square';
        case {'d','diamond'}
            marksymbol = 'diamond';
        case 'v'
            marksymbol = 'triangle-down';
        case '^'
            marksymbol = 'triangle-up';
        case '<'
            marksymbol = 'triangle-left';
        case '>'
            marksymbol = 'triangle-right';
        case {'p','pentagram'}
            marksymbol = 'star';
        case {'h','hexagram'}
            marksymbol = 'hexagram';
    end

    marker.symbol = marksymbol;
end

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

%-MARKER LINE WIDTH (STYLE)-%
marker.line.width = patch_data.LineWidth(t);

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

%--MARKER COLOR--%

%-figure colormap-%
colormap = figure_data.Colormap;

% marker face color
MarkerColor = patch_data.Color(t, :);

filledMarkerSet = {'o','square','s','diamond','d',...
    'v','^', '<','>','hexagram','pentagram'};

filledMarker = ismember(patch_data.MarkerStyle(t), filledMarkerSet);

if filledMarker && strcmp(patch_data.MarkerFilled, 'on')

    if isnumeric(MarkerColor)
        markercolor = sprintf('rgb(%f,%f,%f)', 255*MarkerColor);
    else

        switch MarkerColor

            case 'none'

                markercolor = 'rgba(0,0,0,0)';

            case 'auto'

                if ~strcmp(axis_data.Color,'none')
                    col = 255*axis_data.Color;
                else
                    col = 255*figure_data.Color;
                end

                markercolor  = ['rgb(' num2str(col(1)) ',' num2str(col(2)) ',' num2str(col(3)) ')'];

            case 'flat'

                for n = 1:length(patch_data.CData)

                    capCD = max(min(patch_data.CData(n),axis_data.CLim(2)),axis_data.CLim(1));
                    scalefactor = (capCD - axis_data.CLim(1))/diff(axis_data.CLim);
                    col =  255*(colormap(1 + floor(scalefactor*(length(colormap)-1)),:));

                    markercolor{n} = ['rgb(' num2str(col(1)) ',' num2str(col(2)) ',' num2str(col(3)) ')'];

                end
        end
    end

    marker.color = markercolor;

end

if filledMarker
    marker.line.color = markercolor;
end

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

end


function test_int_test ( )

%*****************************************************************************80
%
%% TEST_INT_TEST tests the TEST_INT library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 November 2009
%
%  Author:
%
%    John Burkardt
%
  timestamp ( )
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST_INT_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the TEST_INT library.\n' );

  test_int_test01 ( )
  test_int_test02 ( )
  test_int_test03 ( )
  test_int_test04 ( )
  test_int_test05 ( )
  test_int_test06 ( )
  test_int_test07 ( )
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST_INT_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( )

  return
end


function this = MrAffineTransformation_constructor(this, testVariants)
% Unit test for MrAffineTransformation Constructor
%
%   Y = MrUnitTest()
%   run(Y, 'MrAffineTransformation_constructor')
%
% This is a method of class MrUnitTest.
%
% IN
%
% OUT
%
% EXAMPLE
%   MrAffineTransformation_constructor
%
%   See also MrUnitTest

% Author:   Saskia Bollmann
% Created:  2017-10-19
% Copyright (C) 2017 Institute for Biomedical Engineering
%                    University of Zurich and ETH Zurich
%
% This file is part of the TAPAS UniQC Toolbox, which is released
% under the terms of the GNU General Public License (GPL), version 3.
% You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version).
% For further details, see the file COPYING or
%  <http://www.gnu.org/licenses/>.

% Unit test for MrAffineTransformation Constructor

switch testVariants
    case 'propVal' % test prop/val syntax

        % actual solution
        actSolution = this.make_affineTransformation_reference(0);

        % expected solution
        % get classes path
        classesPath = tapas_uniqc_get_path('classes');
        % make full filename
        solutionFileName = fullfile(classesPath, '@MrUnitTest' , 'affineTrafo.mat');
        expSolution = load(solutionFileName);
        expSolution = expSolution.affineTrafo;

        % verify equality of expected and actual solution
        % import matlab.unittests to apply tolerances for objects
        import matlab.unittest.TestCase
        import matlab.unittest.constraints.IsEqualTo
        import matlab.unittest.constraints.AbsoluteTolerance
        import matlab.unittest.constraints.PublicPropertyComparator

        this.verifyThat(actSolution, IsEqualTo(expSolution,...
            'Within', AbsoluteTolerance(10e-7),...
            'Using', PublicPropertyComparator.supportingAllValues));

    case 'matrix' % test affine transformation as input
        % expected solution
        expSolution = this.make_affineTransformation_reference(0);
        expSolution = expSolution.affineMatrix;
        % actual solution
        % make actual solution from affine matrix of expected solution
        actSolution = MrAffineTransformation(expSolution);
        actSolution = actSolution.affineMatrix;

        % verify equality of expected and actual solution
        this.verifyEqual(actSolution, expSolution, 'absTol', 10e-7);
end
end


function [flowx,flowy] = specific_wind(x,y,nel)
%vertical_wind   Reference problem 3.1 convective wind
%   [flowx,flowy] = specific_wind(x,y,nel);
%   input
%          x          x coordinate vector
%          y          y coordinate vector
%          nel        number of elements
%   specifies constant vertical wind.
%   IFISS function: DJS; 5 March 2005.
% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage
      flowx =  zeros(nel,1);  flowy =  ones(nel,1);
      return


function nodes2 = grNeighborNodes(edges, node)
%GRNEIGHBORNODES Find adjacent nodes of a given node
%
%   Deprecated, use 'grAdjacentNodes' instead.
%
%   NEIGHS = grNeighborNodes(EDGES, NODE)
%   EDGES: the complete edges list
%   NODE: index of the node
%   NEIGHS: the nodes adjacent to the given node.
%
%   NODE can also be a vector of node indices, in this case the result is
%   the set of neighbors of any input node.
%
%   see also
%   grAdjacentNodes

%   HISTORY
%   10/02/2004 documentation
%   13/07/2004 faster algorithm
%   03/10/2007 can specify several input nodes

warning('MatGeom:deprecated', ...
    'function grNeighborNodes is obsolete, use grAdjacentNodes instead');

[i, j] = find(ismember(edges, node)); %#ok<NASGU>
nodes2 = edges(i,1:2);
nodes2 = unique(nodes2(:));
nodes2 = sort(nodes2(~ismember(nodes2, node)));


function OutputFile = dipoles_merge(DipoleFiles)
% DIPOLES_MERGE: Merge multiple dipoles files

% @=============================================================================
% 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: Elizabeth Bock, Francois Tadel, Jeremy Moreau, 2015

% Load in all dipole files
for i = 1:length(DipoleFiles)
    % Check file path file
    if ~file_exist(DipoleFiles{i})
        DipoleFiles{i} = file_fullpath(DipoleFiles{i});
    end
    if ~file_exist(DipoleFiles{i})
        error(['File not found: ' DipoleFiles{i}]);
    end
    % Load file
    DipoleMat = load(DipoleFiles{i});
    % Do not accept subsets of dipoles
    if (DipoleMat.Subset > 1)
        error('TODO: Update this function for merging files with subsets.')
    end
    % First file: template
    if (i == 1)
        MergeMat = DipoleMat;
        MergeMat.DipoleNames = {};
        MergeMat.Dipole = [];

        % Calculate sampling rate of first dipole file
        if (length(DipoleMat.Time) == 1)
            DipOneSamplingRate = 0;  % Set sampling rate to 0 if only one dipole
        elseif (length(DipoleMat.Time) > 1)
            DipOneSamplingRate = DipoleMat.Time(2) - DipoleMat.Time(1);
        end

    % Following files: check that they are compatible
    else
        if ((DipOneSamplingRate ~= 0) && (length(DipoleMat.Time) > 1))
            if (abs(DipOneSamplingRate - (DipoleMat.Time(2) - DipoleMat.Time(1))) > 0.00001)
                error('Only files with equal sampling rate can be merged.');
            end
        elseif (DipoleMat.Subset ~= MergeMat.Subset)
            error('Only files with equal number of channel subsets can be merged.');
        end
    end

    % Names just have the group number (i.e. Group #1, Group #2)
    lastGroupNumber = length(MergeMat.DipoleNames);
    nGroups = length(DipoleMat.DipoleNames);
    % Loop through the groups
    for g = 1:nGroups
        % Add the name
        MergeMat.DipoleNames{end+1} = ['Group #' num2str(lastGroupNumber + g)];
        % Update the index numbers
        ind = find([DipoleMat.Dipole.Index] == g);
        if ~isempty(ind)
            [DipoleMat.Dipole(ind).Index] = deal(lastGroupNumber + g);
        end
    end
    % Merge the Dipole structures
    MergeMat.Dipole = [MergeMat.Dipole, DipoleMat.Dipole];
    MergeMat.DataFile = '';
    % Merge history
    MergeMat = bst_history('add', MergeMat, 'merge', ['Merged file: ' file_short(DipoleFiles{i})]);
end

% Set new Time sampling for merged dipoles
MergeMat.Time = unique([MergeMat.Dipole.Time]);

% ===== SAVE NEW FILE =====
% Update the comment to reflect the number of merged files
MergeMat.Comment = ['Merge: ' num2str(length(DipoleFiles)) ' files'];
% Create output filename
OutputFile = file_unique(bst_fullfile(fileparts(DipoleFiles{1}), 'dipoles_merged.mat'));
% Save new file in Brainstorm format
bst_save(OutputFile, MergeMat, 'v7');

% ===== UPDATE DATABASE =====
% Get study of the first file
[sStudy,iStudy] = bst_get('DipolesFile', file_short(DipoleFiles{1}));
% Create structure
BstDipolesMat = db_template('Dipoles');
BstDipolesMat.FileName = file_short(OutputFile);
BstDipolesMat.Comment  = MergeMat.Comment;
BstDipolesMat.DataFile = MergeMat.DataFile;
% Add to study
sStudy = bst_get('Study', iStudy);
iDipole = length(sStudy.Dipoles) + 1;
sStudy.Dipoles(iDipole) = BstDipolesMat;
% Save study
bst_set('Study', iStudy, sStudy);
% Update tree
panel_protocols('UpdateNode', 'Study', iStudy);
% Select node
panel_protocols('SelectNode', [], BstDipolesMat.FileName);
% Save database
db_save();


figure(1)
plot(t, Y{3}')


function r = ge(p,q)
% this function compares the greater than or equality condition of x, y, and z values of the structures that I use in
% the FVtool.
%
% SYNOPSIS:
%
%
% PARAMETERS:
%
%
% RETURNS:
%
%
% EXAMPLE:
%
% SEE ALSO:
%

% Copyright (c) 2012-2016 Ali Akbar Eftekhari
% See the license file

if (isa(p, 'FaceVariable')&&isa(q, 'FaceVariable'))
    r=p;
    r.xvalue = p.xvalue>=q.xvalue;
    r.yvalue = p.yvalue>=q.yvalue;
    r.zvalue = p.zvalue>=q.zvalue;
elseif isa(p, 'FaceVariable')
    r=p;
    r.xvalue = p.xvalue>=q;
    r.yvalue = p.yvalue>=q;
    r.zvalue = p.zvalue>=q;
else
    r=q;
    r.xvalue = p>=q.xvalue;
    r.yvalue = p>=q.yvalue;
    r.zvalue = p>=q.zvalue;
end


function ok = dfcanplotdata(ds,dffig)
%DFCANPLOTDATA Determine if we can plot data in the current plot

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

% No problem unless we have non-positive data
ok = true;
xlimits = xlim(ds);
xmin = xlimits(1);
if xmin>0
   return
end

% Get handle to control containing the distribution list
if nargin<2
   dffig = dfgetset('dffig');
end
hsel = getappdata(dffig,'selectioncontrols');

% No problem unless we have a probability plot
h = hsel(3);   % handle of display type control
choice = get(hsel(3),'Value');
ftypes = getappdata(hsel(3),'codenames');
ftype = ftypes{choice};
if ~isequal(ftype, 'probplot')
   return
end

% No problem unless distribution has support that excludes some data
ax = get(dffig,'CurrentAxes');
distspec = getappdata(ax,'DistSpec');
lobnd = distspec.support(1);
strict = ~distspec.closedbound(1);
if strict && lobnd>=xmin
   ok = false;
elseif ~strict && lobnd>xmin
   ok = false;
end


function ori = subSet(S3G,varargin)
% indexing of rotation
%
% Syntax
%   ori = subSet(SO3G,ind) %
%

ori = subSet@orientation(orientation(S3G),varargin{:});


function status = besa_save2Avr(file_path, file_name, data_matrix, ...
    time_samples, channel_labels, data_scale_factor, time_scale_factor)
% BESA_SAVE2AVR writes a data matrix into ASCII-vectorized file format
%
% Parameters:
%     [file_path]
%         Full path to the folder where the file should be saved.
%
%     [file_name]
%         The name of the file where the output should be written.
%
%     [data_matrix]
%         A 2D data matrix to be saved. It should have the size
%         [NumberOfChannels x NumberOfTimeSamples].
%
%     [time_samples]
%         An array with the time samples corresponding to the data. The
%         size of the array should be [1 x NumberOfTimeSamples].
%
%     [channel_labels]
%         An array containing the channel labels for the current data.
%
%     [data_scale_factor]
%         A constant used for converting the data values from Tesla into fT
%         (10e15) or from Volt into uV (10e6). If the data is already in fT
%         or uV the just set it to 1.
%
%     [time_scale_factor]
%         A constant used for converting the time samples from seconds into
%         milliseconds (1000). If the time samples are already in
%         milliseconds just set the constant to 1.
%
% Return:
%     [status]
%         The status of the writing process. Still unused.
%

% Copyright (C) 2013, BESA GmbH
%
% File name: besa_save2Avr.m
%
% This file is part of MATLAB2BESA.
%
%    MATLAB2BESA 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.
%
%    MATLAB2BESA 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 MATLAB2BESA. If not, see <http://www.gnu.org/licenses/>.
%
% Author: Todor Jordanov
% Created: 2012-04-17

n_tbins = size(time_samples, 2);

% Check if the matrix is [NumberOfChannels x NumberOfTimeSamples]
% or [NumberOfTimeSamples x NumberOfChannels] instead and if required
% transpose the matrix
tmp_size = size(data_matrix, 1);
% Case [NumberOfTimeSamples x NumberOfChannels]
if(n_tbins == tmp_size)

    % Transpose
    data_matrix = data_matrix';

end

n_channels = size(data_matrix, 1);

% Scale the time.
start_time = time_scale_factor * time_samples(1);
time_step = time_scale_factor * (time_samples(2) - time_samples(1));

% Scale the data.
data_matrix = data_matrix .* data_scale_factor;

% Change to the directory where the data should be saved.
cd(file_path)

% Open file for writing.
fid = fopen(file_name, 'w');

% Write the first line of the header.
fprintf(fid, ...
    'Npts= %d   TSB= %f DI= %f SB= 1.000 SC= 200.0 Nchan= %d\n', ...
    n_tbins, start_time, time_step, n_channels);

if(iscell(channel_labels))

    tmp = channel_labels{1};
    for iCh = 2:n_channels

        tmp = [tmp ' ' channel_labels{iCh}];

    end

    channel_labels = tmp;

end
% Write the second line of the header.
fprintf(fid, '%s\n', channel_labels);

% Write the data matrix to the file.
for i=1:n_channels

    for j=1:n_tbins

        fprintf(fid, '%f ', data_matrix(i, j));

    end

    fprintf(fid, '\n');

end

fclose(fid);

status = 1;


%% Stress Tensors
%
%% PLEASE HELP AND ADD CONTENT HERE
%


function colors = getColorChoices
%getColorChoices Returns a structure containing several high-contrast colors.
%   COLORS = getColorChoices returns a structure containing several colors
%   defined as RGB triplets.

%   Copyright 2005 The MathWorks, Inc.
%   $Revision $  $Date: 2005/05/27 14:07:15 $

% First color in the list will be the default.
temp = {'Medium Blue',   [ 72  72 248]/255
        'Light Blue',    [ 72 136 248]/255
        'Light Red',     [248  79  79]/255
        'Green',         [ 72 248  72]/255
        'Yellow',        [248 246  74]/255
        'Magenta',       [248  72 248]/255
        'Cyan',          [ 72 248 248]/255
        'Light Gray',    [232 232 232]/255
        'Black',         [  0   0   0]/255};

colors = struct('Label', temp(:,1), 'Color', temp(:,2));


function varargout = grMergeMultipleEdges(nodes, edges)
%GRMERGEMULTIPLEEDGES Remove all edges sharing the same extremities
%
%   [NODES2, EDGES2] = grMergeMultipleEdges(NODES, EDGES)
%   Remove configuration with two edges sharing the same 2 nodes.
%

%   -----
%   author : David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 13/08/2003.
%

%   HISTORY
%   10/02/2004 doc
%   2011-05-18 rename to grMergeMultipleEdges

rmedge = [];
for e = 1:length(edges)
    edge = edges(e, :);
    for e2 = e+1:length(edges)
        if (edge(1) == edges(e2, 1) && edge(2) == edges(e2, 2)) || ...
           (edge(1) == edges(e2, 2) && edge(2) == edges(e2, 1))
                rmedge(length(rmedge)+1) = e2; %#ok<AGROW>
        end
    end
end

[nodes, edges] = grRemoveEdges(nodes, edges, rmedge);

% process output depending on how many arguments are needed
if nargout == 1
    out{1} = nodes;
    out{2} = edges;
    varargout{1} = out;
end

if nargout == 2
    varargout = {nodes, edges};
end


function mfig = montagefigurefiles(x,y)
% by Nick Sinclair (nws5@pitt.edu)  Jul 08, 2010

% figurearray is row-vector of handles to figures that you'd like
% included in the montage

% x is horizontal number of subplots
% y is vertical number of subplots

% props array specifies properties that you'd like copied over to the new
% subplots. I did this because copying all of the properties gave me errors
% because I didn't know how to exclude the read-only properties. So for now
% you have to specify each one. Check 'Axes Properties' in help for more
% properties to copy over.

% The space between subplots can be adjusted with 'spacerx' and 'spacery'

% The axis labels and Ticks are only displayed on the first column and
% last row. If it's not appropriate, it's easy to change. For example, it's
% particularly ugly if you have an odd number of plots or varying xlim/ylim
% Just set LabelOnlyPerimeter = 0;

% returns handle to new figure mfig

% IMPORTANT ADJUSTABLE PARAMETERS
props ={'XLim','YLim','CLim','Xscale','Yscale', ...
    'YTickLabelMode','XTickLabelMode','View','YDir', ...
    'XDir','DataAspectRatio','DataAspectRatioMode'};
legprops = {'String','FontAngle','FontName','FontSize','FontUnits','FontWeight'};
    %properties to copy from legends

left = 0.03;  % margins (add it in if you like, in the same way as left)
top = .98;    %
bottom = 0.05;%
spacerx = 1/10; % size of space between subplots compared to subplot width
spacery = 1/5;  %
newfigposition = [.1 .1 .75 .75]; %set size and position of newfig
LabelOnlyPerimeter = 1;
% END IMPORTANT ADJUSTABLE PARAMETERS

[FileName,PathName] = uigetfile('*.*','Select Figure Files to Montage', 'MultiSelect','on');

for jj = 1:length(FileName),
    figurearray(jj) = openfig(strcat(PathName,char(FileName(jj))),'new','invisible');
end

mfig = figure('units', 'normalized', 'outerposition', newfigposition);

j = 1;

count = 0;

for ii = 1:length(figurearray),
   fig(ii).axhandles = findobj(get(figurearray(ii),'Children'),'Type','Axes','-not','Tag','Colorbar','-not','Tag','legend');
   count = count+length(fig(ii).axhandles); %count up axes excluding colorbars, incl subplots
end

% disp(['found: ',num2str(count),' plots']);

wxfactor = 1/spacerx;                   % convenience
wyfactor = 1/spacery;
dx = (1-left)/(((wxfactor+1)*x)+1);     %calc so that it all adds up to 1
dy = (top-bottom)/(((wyfactor+1)*y)+1); %
sizex = wxfactor*dx;                    %
sizey = wyfactor*dy;                    %

for i = 1:length(figurearray),
    for subaxis = 1:length(fig(i).axhandles)
        row = floor((j-1)/x) + 1;
        col = mod((j-1),x)+1;
        set(0,'CurrentFigure',mfig);
        pos(1) = left + col*(dx) + (col-1)*sizex; %set subplot position
        pos(3) = sizex;                           %
        pos(2) = top - row*dy - (row)*sizey;      %
        pos(4) = sizey;                           %
        s(j) = subplot('Position',pos); %handle to axis j in subplot (target)
%         set(0,'CurrentFigure',i);
        origaxis = fig(i).axhandles(subaxis);

        %This label complication is because the xlabel property of the axis is
        %only a handle to a child string of the axis. hence
        %get(axishandle,'xlabel') gives you the handle to the label which you
        %can then set properties for.

        copyobj(get(origaxis,'Children'),s(j)) %send all children to subplot j
        set(get(s(j),'Title'),'String',get(get(origaxis,'Title'),'String'));
        set(get(s(j),'Title'),'FontSize',(0.7*get(get(origaxis,'Title'),'FontSize')));
        set(s(j),props,get(origaxis,props));    %set the specified properties of axis j
        if LabelOnlyPerimeter,
            if (col==1),            % if first column set labels/ticks
                set(get(s(j),'ylabel'),'String',get(get(origaxis,'ylabel'),'String'));
                set(get(s(j),'ylabel'),'FontSize',(0.7*get(get(origaxis,'ylabel'),'FontSize')));
            else
                set(s(j),'YTickLabelMode','manual');
                set(s(j),'YTick',[]);
            end

            if (row == ceil(length(figurearray)/x)), %if last row, labels/ticks
                set(get(s(j),'xlabel'),'String',get(get(origaxis,'xlabel'),'String'));
                set(get(s(j),'xlabel'),'FontSize',(0.7*get(get(origaxis,'xlabel'),'FontSize')));
            else
                set(s(j),'XTickLabelMode','manual');
                set(s(j),'XTick',[]);
            end
        else
                set(get(s(j),'ylabel'),'String',get(get(origaxis,'ylabel'),'String'));
                set(get(s(j),'ylabel'),'FontSize',(0.7*get(get(origaxis,'ylabel'),'FontSize')));
                set(get(s(j),'xlabel'),'String',get(get(origaxis,'xlabel'),'String'));
                set(get(s(j),'xlabel'),'FontSize',(0.7*get(get(origaxis,'xlabel'),'FontSize')));
        end

        if ~isempty(legend(origaxis)),
            legend(s(j),'toggle');
            set(legend(s(j)),legprops,get(legend(origaxis),legprops));
        end

        j = j+1;
    end
end

for jj = 1:length(FileName),
    close(figurearray(jj),'new','invisible');
end


function [indices] = sequence_query_tag(sequence, tag, subset)
% sequence_query_tag Find tag occurences in sequence
%
% The function returns indices of all frames that contain the specified tag.
%
% Input:
% - sequence (structure): A valid sequence structure.
% - tag (string): Name of the tag.
% - subset (vector): A set of frame numbers or a binary mask to be used
% when looking for a tag. Frame indices will be returned relative to that
% subset of frames.
%
% Output:
% - indices (integer): A vector of indices of frames that contain the given tag.

if nargin < 3
   subset = true(sequence.length, 1);
end

if strcmp(tag, 'all')
    if nargin < 3
        indices = 1:sequence.length;
    else
        indices = 1:numel(subset);
    end;
    return;
end;

if strcmp(tag, 'empty')
    indices = find(all(~sequence.tags.data, 2));
    return;
end;

tag_index = find(strcmp(sequence.tags.names, tag), 1);

if isempty(tag_index)
    indices = [];
else
    indices = find(sequence.tags.data(subset, tag_index));
end;


function fh = tapas_physio_plot_cropped_phys_to_acqwindow(ons_secs, sqpar, verbose)
% plot parts of the time series to be processed into regressors
%
% USAGE
%   fh = tapas_physio_plot_cropped_phys_to_acqwindow(ons_secs, sqpar, y)
%
% INPUT
%   ons_secs    - output of tapas_physio_crop_scanphysevents_to_acq_window
%   sqpar       - output of tapas_physio_crop_scanphysevents_to_acq_window
%
% OUTPUT
%   fh          figure handle of output figure

% Author: Lars Kasper
%
% Copyright (C) 2013, Institute for Biomedical Engineering, ETH/Uni Zurich.
%
% This file is part of the PhysIO toolbox, which is released under the terms of the GNU General Public
% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version). For further details, see the file
% COPYING or <http://www.gnu.org/licenses/>.

if nargin == 3
    % If verbose is passed as argument (from updated tapas_physio_review):
    fh = tapas_physio_get_default_fig_params(verbose);
else
    % Backwards compatibility:
    fh = tapas_physio_get_default_fig_params();
end

set(fh,'Name','Preproc: Cutout actual scans - all events and gradients');

Ndummies    = sqpar.Ndummies;
Nslices     = sqpar.Nslices;
sampling    = 1;

%% 1. Plot uncropped data
t        = ons_secs.raw.t;
cpulse      = ons_secs.raw.cpulse;
r           = ons_secs.raw.r;
c           = ons_secs.raw.c;
spulse      = ons_secs.raw.spulse;
svolpulse   = ons_secs.raw.svolpulse;

hasCardiacData = ~isempty(c);
hasRespData = ~isempty(r);

maxValc = max(abs(c));
maxValr = max(abs(r));
if hasCardiacData && hasRespData
    maxVal = maxValc; % max(maxValc, maxValr);
    colors = [1 0 0; 0 1 0];
elseif hasCardiacData
    maxVal = maxValc;
    colors = [1 0 0];

else
    maxVal = maxValr;
    colors = [0 1 0];
end

ampsv = maxVal*1;
amps = maxVal*0.8; % maxVal / 3;
ampc = maxVal*1.2; % maxVal / 2;

%% Plot raw time series data and recorded events as stems
y = [c, r];
x = y(1:sampling:end, :);
stem(spulse(1:Ndummies*Nslices),amps*ones(Ndummies*Nslices,1),'k--');
hold on;
stem(svolpulse(Ndummies+1:end),ampsv*ones(length(svolpulse)-Ndummies,1),'c', 'LineWidth',2);
stem(spulse((Ndummies*Nslices+1):end), amps*ones(length(spulse)-Ndummies*Nslices,1), 'c--') ;

if hasCardiacData
    stem(cpulse, ampc*ones(length(cpulse),1), 'r--') ;
end

for iLine = 1:size(x,2)
   plot(t(1:sampling:end), x(:,iLine), '--', 'Color', colors(iLine,:));
end

%% 2. Plot cropped data

t           = ons_secs.t;
cpulse      = ons_secs.cpulse;
r           = ons_secs.fr;
c           = ons_secs.c;
spulse      = ons_secs.spulse;
svolpulse   = ons_secs.svolpulse;

hs = zeros(1,0);

%plot physiological time courses and scan events
if hasRespData
    hs(end+1) = plot(t,r,'ko');
else
    hs(end+1) = plot(t,c,'ko');
end

y = [c, r];
x = y (1:sampling:end, :);
hs(end+1) = stem(spulse(1:Ndummies*Nslices),amps*ones(Ndummies*Nslices,1),'--k');
hold on;
hs(end+1) = stem(svolpulse(Ndummies+1:end),ampsv*ones(length(svolpulse)-Ndummies,1),'c', 'LineWidth',2);
hs(end+1) = stem(spulse((Ndummies*Nslices+1):end), amps*ones(length(spulse)-Ndummies*Nslices,1), '--c') ;

if hasCardiacData
    hs(end+1) = stem(cpulse, ampc*ones(length(cpulse),1), 'r') ;
end

for iLine = 1:size(x,2)
    hs(end+1) = plot(t(1:sampling:end), x(:,iLine), '-', 'Color', colors(iLine,:));
end

xlabel('t (s)'); ylabel('Amplitude (a. u.)');
title('Cutout region for physiological regressors');

if hasCardiacData && hasRespData

    legend( hs, {
        'used respiratory signal', ...
        ['dummy scan event marker (N = ' int2str(Ndummies*Nslices) ')'], ...
        ['volume event marker (N = ' int2str(length(svolpulse)-Ndummies) '), without dummies'], ...
        ['scan event marker (N = ' int2str(length(spulse)-Ndummies*Nslices) ')'], ...
        ['cardiac pulse (heartbeat) marker (N = ' int2str(length(cpulse)) ')'], ...
        'cardiac signal (dashed = raw)', 'respiratory signal (dashed = raw)'});
elseif hasCardiacData
    legend( hs, {
        'used cardiac signal', ...
        ['dummy scan event marker (N = ' int2str(Ndummies*Nslices) ')'], ...
        ['volume event marker (N = ' int2str(length(svolpulse)-Ndummies) '), without dummies'], ...
        ['scan event marker (N = ' int2str(length(spulse)-Ndummies*Nslices) ')'], ...
        ['cardiac pulse (heartbeat) marker (N = ' int2str(length(cpulse)) ')'], ...
        'cardiac signal (dashed = raw)'});
else % only respData
    legend( hs, {
        'used respiratory signal', ...
        ['dummy scan event marker (N = ' int2str(Ndummies*Nslices) ')'], ...
        ['volume event marker (N = ' int2str(length(svolpulse)-Ndummies) '), without dummies'], ...
        ['scan event marker (N = ' int2str(length(spulse)-Ndummies*Nslices) ')'], ...
        'respiratory signal (dashed = raw)'});
end

ylim(1.4*maxVal*[-1 1]);


function LoadFullFish(hfig,i_fish,isFullData,hdf5_dir,mat_dir)
M_fish_set = getappdata(hfig,'M_fish_set');
fishset = M_fish_set(i_fish);
setappdata(hfig,'fishset',fishset);

%% load data from file
disp(['loading fish ' num2str(i_fish) '...']);
loadStart = tic;
isLoadTS = 1;
if ~exist('hdf5_dir','var') || ~exist('mat_dir','var'),
    data_masterdir = getappdata(hfig,'data_masterdir');
    data_dir = fullfile(data_masterdir,['subject_' num2str(i_fish)]);
    if exist('isFullData','var'),
        if isFullData % true
             hdf5_dir = fullfile(data_dir,'TimeSeries.h5');
        else % % %isFullData == -1,
            hdf5_dir = fullfile(data_dir,'TimeSeries.h5');
            absIX = h5read(hdf5_dir,'/absIX');
            setappdata(hfig,'absIX',absIX);
            isLoadTS = 0; % don't load Time series
%         else % false
%             hdf5_dir = fullfile(data_dir,'TimeSeries_half.h5');
        end
    else % default without isfulldata input is full-data
        hdf5_dir = fullfile(data_dir,'TimeSeries.h5');
    end
    mat_dir = fullfile(data_dir,'data_full.mat');
end

% load 'data'
load(mat_dir,'data'); % struct with many fields
names = fieldnames(data); % cell of strings
for i = 1:length(names),
    setappdata(hfig,names{i},eval(['data.',names{i}]));
end

if isLoadTS,
    % load time series (hdf5 file)
    CellResp = h5read(hdf5_dir,'/CellResp');
    CellRespZ = h5read(hdf5_dir,'/CellRespZ');
    CellRespAvr = h5read(hdf5_dir,'/CellRespAvr');
    CellRespAvrZ = h5read(hdf5_dir,'/CellRespAvrZ');
    absIX = h5read(hdf5_dir,'/absIX');

    setappdata(hfig,'CellResp',CellResp);
    setappdata(hfig,'CellRespZ',CellRespZ);
    setappdata(hfig,'CellRespAvr',CellRespAvr);
    setappdata(hfig,'CellRespAvrZ',CellRespAvrZ);
    setappdata(hfig,'absIX',absIX);
end

loadTime = toc(loadStart);
disp([num2str(loadTime) ' sec']);

end


function tabMI = motionCompMeanMI(meanMap,ROI)
%
%    gb 04/25/05
%
% Computes a matrix of MI from a cell array of mean maps
% tabMI(i,j) = motionCompMI(meanMap{i},ROI,meanMap{j});
%

if ieNotDefined('ROI')
    ROI = '';
end

n = length(meanMap);
tabMI = zeros(n);

for i = 1:n
    for j = 1:n
        if isempty(meanMap{i}) | isempty(meanMap{j})
            continue;
        end

        tabMI(i,j) = motionCompMI(meanMap{i},ROI,meanMap{j});
    end
end


function display(v,varargin)
% standard output

if check_option(varargin,'onlyShowVectors')
  d = [v.x(:),v.y(:),v.z(:)];
  d(abs(d) < 1e-10) = 0;

  cprintf(d,'-L','  ','-Lc',{'x' 'y' 'z'});
  return
end

displayClass(v,inputname(1),varargin{:});%...
  %'moreInfo',char(v.refSystem,'compact'),varargin{:});

if length(v) ~= 1, disp([' size: ' size2str(v)]);end

if v.antipodal, disp(' antipodal: true'); end

% display resolution
if isOption(v,'resolution')
  disp([' resolution: ',xnum2str(getOption(v,'resolution')/degree),mtexdegchar]);
  v.opt = rmfield(v.opt,'resolution');
end

% display all other options
disp(char(dynOption(v)));

% display coordinates
if check_option(varargin,'skipCoordinates') || isempty(v) || getMTEXpref('generatingHelpMode')

elseif check_option(varargin,'all') || (length(v) < 20)

  display(v,'onlyShowVectors')

else

  disp(' ')
  s = setappdata(0,'data2beDisplayed',v);
  disp(['  show vectors'])
  disp(' ')

end


function [meanDoseV, stdDoseV, DVHm, volsV, shiftXv, shiftYv, shiftZv] = simulate_organ_motion(planC,structNumV,doseNum, igrtFlag)
%function [DVH_out, DVHm, volsV] = simulate_organ_motion(planC,structNumV,doseNum)
%
%APA, 09/21/2012
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR 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.
%
% CERR 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 CERR.  If not, see <http://www.gnu.org/licenses/>.

indexS = planC{end};

%Number of Fractions and Trials
numFractions = 1; % 48
numTrials    = 1; % 200
numStructs   = length(structNumV);

shiftXv = zeros(1,numTrials);
shiftYv = shiftXv;
shiftZv = shiftXv;

structurenamesC = {planC{indexS.structures}.structureName};
rectumIndex = getMatchingIndex('rectum_o',lower(structurenamesC),'exact');
rectalCS = calculate_structure_cross_sectional_area(rectumIndex,planC);
bladderVol = getMatchingIndex('bladder_o',lower(structurenamesC),'exact');

% % Systematic Shifts in cm (Inter-treatment)
% XdispSys_Std = 0; % L-R
% YdispSys_Std = 0; % A-P
% ZdispSys_Std = 0; % S-I

% % Random Shifts in cm (inter-fraction)
% XdispRnd_Std = 1; % L-P
% YdispRnd_Std = 1; % A-P
% ZdispRnd_Std = 1; % S-I

%Distances are in cm
XpdfMean = 0; % L-P
YpdfMean = 0; % A-P
ZpdfMean = 0; % S-I

%Get scan associated with doseNum
scanNum = getAssociatedScan(planC{indexS.dose}(doseNum).assocScanUID, planC);

if isempty(scanNum) %Assume dose is associated with this scan
    scanNum = getStructureAssociatedScan(structNumV(1),planC);
end

%Get reference transformation matrix for doseNum
if ~isempty(scanNum) && isempty(planC{indexS.dose}(doseNum).transM)
    referenceTransM = planC{indexS.scan}(scanNum).transM;
else
    referenceTransM = planC{indexS.dose}(doseNum).transM;
end

%Store the reference doseArray
referenceDoseArray = planC{indexS.dose}(doseNum).doseArray;

%Try and get a binWidth from stateS.  If it doesnt exist, get it from
%the CERROptions file (allows this function to be called outside CERR)
global stateS;
if ~isempty(stateS) && isfield(stateS, 'optS') && isfield(stateS.optS, 'DVHBinWidth') && ~isempty(stateS.optS.DVHBinWidth)
    binWidth = stateS.optS.DVHBinWidth;
else
    optS = CERROptions;
    binWidth = optS.DVHBinWidth;
end

%Compute DVH at given dose
structCount = 0;
for structNum = structNumV
    structCount = structCount + 1;
    [dosesCurrentV{structCount}, volsV{structCount}] = getDVH(structNum, doseNum, planC);
end

%Divide doseArray into fractions
planC{indexS.dose}(doseNum).doseArray = planC{indexS.dose}(doseNum).doseArray / numFractions;

%Get systematic errors
% deltaX_systematic = randn(1, numTrials) * XdispSys_Std + XpdfMean;
% deltaY_systematic = randn(1, numTrials) * YdispSys_Std + YpdfMean;
% deltaZ_systematic = randn(1, numTrials) * ZdispSys_Std + ZpdfMean;

hWait = waitbar(0,'Computing plan robustness...');

if isempty(referenceTransM)
    referenceTransM_matrix = eye(4);
else
    referenceTransM_matrix = referenceTransM;
end

%Obtain DVH calculation points in blocks
optS    = planC{indexS.CERROptions};

ROIImageSize = [planC{indexS.scan}(scanNum).scanInfo(1).sizeOfDimension1  planC{indexS.scan}(scanNum).scanInfo(1).sizeOfDimension2];

deltaY = planC{indexS.scan}(scanNum).scanInfo(1).grid1Units;

%Get raster segments for structure.
structCount = 0;
for structNum = structNumV

    structCount = structCount + 1;

    [segmentsM, planC, isError] = getRasterSegments(structNum, planC);

    if isempty(segmentsM)
        isError = 1;
    end
    numSegs = size(segmentsM,1);

    %Relative sampling of ROI voxels in this place, compared to CT spacing.
    %Set when rasterSegments are generated (usually on import).
    sampleRate = optS.ROISampleRate;

    %Sample the rows
    indFullV =  1 : numSegs;
    if sampleRate ~= 1
        rV = 1 : length(indFullV);
        rV([rem(rV+sampleRate-1,sampleRate)~=0]) = [];
        indFullV = rV;
    end

    %Block process to avoid swamping on large structures
    if isfield(optS, 'DVHBlockSize') & ~isempty(optS.DVHBlockSize)
        DVHBlockSize = optS.DVHBlockSize;
    else
        DVHBlockSize = 5000;
    end

    blocks{structCount} = ceil(length(indFullV)/DVHBlockSize);

    start = 1;

    for b = 1 : blocks{structCount}

        %Build the interpolation points matrix

        dummy = zeros(1,DVHBlockSize * ROIImageSize(1));
        x1V = dummy;
        y1V = dummy;
        z1V = dummy;
        volsSectionV{structCount} =  dummy;

        if start+DVHBlockSize > length(indFullV)
            stop = length(indFullV);
        else
            stop = start + DVHBlockSize - 1;
        end

        indV = indFullV(start:stop);

        mark = 1;
        for i = indV

            tmpV = segmentsM(i,1:10);
            delta = tmpV(5) * sampleRate;
            xV = tmpV(3): delta : tmpV(4);
            len = length(xV);
            rangeV = ones(1,len);
            yV = tmpV(2) * rangeV;
            zV = tmpV(1) * rangeV;
            sliceThickness = tmpV(10);
            %v = delta^2 * sliceThickness;
            v = delta * (deltaY*sampleRate) * sliceThickness;
            x1V(mark : mark + len - 1) = xV;
            y1V(mark : mark + len - 1) = yV;
            z1V(mark : mark + len - 1) = zV;
            volsSectionV{structCount}(mark : mark + len - 1) = v;
            mark = mark + len;

        end

        %cut unused matrix elements
        x1V = x1V(1:mark-1);
        y1V = y1V(1:mark-1);
        z1V = z1V(1:mark-1);
        volsSectionV{structCount} = volsSectionV{structCount}(1:mark-1);

        %Get transformation matrices for both dose and structure.
        transMDose    = getTransM('dose', doseNum, planC);
        transMStruct  = getTransM('struct', structNum, planC);

        %Forward transform the structure's coordinates.
        if ~isempty(transMStruct)
            [x1V, y1V, z1V] = applyTransM(transMStruct, x1V, y1V, z1V);
        end

        dvhCalcPtsC{structCount}{b} = [x1V', y1V', z1V'];

        %Interpolate.
        %   [dosesSectionV] = getDoseAt(doseNum, x1V, y1V, z1V, planC);

        %   dosesV = [dosesV, dosesSectionV];
        %   volsV  = [volsV, volsSectionV{structCount}];

        start = stop + 1;

    end

end

%Loop over to generate DVH
for iTrial = 1:numTrials

    [deltaX_systematic, deltaY_systematic, deltaZ_systematic, XdispRnd_Std, YdispRnd_Std, ZdispRnd_Std] = getShiftParameters(rectalCS,bladderVol,igrtFlag);
    deltaX_systematic = min(max(deltaX_systematic,-1.0),1.0);
    deltaY_systematic = min(max(deltaY_systematic,-1.5),1.5);
    deltaZ_systematic = min(max(deltaZ_systematic,-1.0),1.0);
    deltaX = deltaX_systematic + randn(1, numFractions) * XdispRnd_Std + XpdfMean;
    deltaY = deltaY_systematic + randn(1, numFractions) * YdispRnd_Std + YpdfMean;
    deltaZ = deltaZ_systematic + randn(1, numFractions) * ZdispRnd_Std + ZpdfMean;

    % To get planned DVH - comment it otherwise
    deltaX = 0;
    deltaY = 0;
    deltaZ = 0;

    shiftXv(1,iTrial) = mean(deltaX);
    shiftYv(1,iTrial) = mean(deltaY);
    shiftZv(1,iTrial) = mean(deltaZ);

    structCount = 0;
    for structNum = structNumV

        structCount = structCount + 1;

        tmpDoseV = zeros(1,length(dosesCurrentV{structCount}));

        for iFraction = 1:numFractions

            waitbar(((iTrial-1)*numStructs + structCount)/(numTrials*numStructs),hWait)

            transM = referenceTransM_matrix;
            transM(1:3,4) = transM(1:3,4) + [deltaX(iFraction); deltaY(iFraction); deltaZ(iFraction)];

            %Apply the new transM to dose
            planC{indexS.dose}(doseNum).transM = transM;

            % Convert Dose to Gy
            if max(planC{indexS.dose}(doseNum).doseArray(:)) > 150
                planC{indexS.dose}(doseNum).doseArray = planC{indexS.dose}(doseNum).doseArray/100;
            end

            %Get doses and volumes of points in structure.
            %[dosesV, volsV] = getDVH(structNum, doseNum, planC);

            volsV{structCount}  = [];
            dosesV{structCount} = [];

            for b = 1 : blocks{structCount}
                x1V = dvhCalcPtsC{structCount}{b}(:,1);
                y1V = dvhCalcPtsC{structCount}{b}(:,2);
                z1V = dvhCalcPtsC{structCount}{b}(:,3);

                %Back transform the coordinates into the doses' coordinate system.
                [x1V, y1V, z1V] = applyTransM(inv(transM), x1V, y1V, z1V);

                %Interpolate.
                [dosesSectionV] = getDoseAt(doseNum, x1V, y1V, z1V, planC);

                dosesV{structCount} = [dosesV{structCount}, dosesSectionV];
                volsV{structCount}  = [volsV{structCount}, volsSectionV{structCount}];
            end

            tmpDoseV = tmpDoseV + dosesV{structCount};

        end

        DVHm{structCount}(:,iTrial) = single(tmpDoseV(:));

    end

end

close(hWait)

%Reassign reference transM and doseArray to doseNum
planC{indexS.dose}(doseNum).transM = referenceTransM;
planC{indexS.dose}(doseNum).doseArray = referenceDoseArray;

%Compute Mean and Std Dev in blocks
structCount = 0;
for structNum = structNumV

    structCount = structCount + 1;

    numVoxels = length(volsV{structCount});
    DVHBlockSize = 5000;
    blocks = ceil(numVoxels/DVHBlockSize);
    start = 1;

    for b = 1 : blocks

        if start+DVHBlockSize > numVoxels
            stop = numVoxels;
        else
            stop = start + DVHBlockSize - 1;
        end

        DVH_block = DVHm{structCount}(start:stop,:);

        meanDoseV{structCount}(start:stop) = mean(DVH_block,2);
        stdDoseV{structCount}(start:stop)  = std(DVH_block,0,2);

        start = stop + 1;

    end
end

% %Histogram for the expectation of dose over all trials
% [doseBinsV, volsHistV] = doseHist(meanDoseV, volsV, binWidth);
% DVH_out = [doseBinsV(:)'; volsHistV(:)'];


function drawboard(board)

for i = 1:numel(board)
    patch(board(i).xy(:,1), board(i).xy(:,2), [0.5 0.5 0.5]);
end

axis image off


function [f,df] = knitro_callback_f(x,model)

global latest_x_f
global latest_df
global latest_f

x = x(:);
if isequal(x,latest_x_f)
    df = latest_df;
    f = latest_f;
else
    [f,df] = fmincon_fun_liftlayer(x,model);
    latest_x_f = x;
    latest_f = f;
    latest_df = df;
end


% DEMO4 - Playing with NetCDF-JAVA functions
echo('on')
% Starting DEMO4 ----------------------------------------------------------
%% ---- Example of data access using the NetCDF-Java API
ds = ncdataset('http://geoport.whoi.edu/thredds/dodsC/examples/OS_MBARI-M1_20091020_R_TS.nc');
nc = ds.netcdf;

%% ---- Query NetCDF using Java API
nc.getConventionUsed()
nc.getDetailInfo()
nc.hasUnlimitedDimension()
nc.getUseNaNs()

%% ---- Set properties using Java API
% The following line turns off the auto conversion of missing_values to NaN
% NOTE: This switches ALL netcdf files not just the one you are working on.
% nc.setUseNaNs(0)

%% ---- Dump NcML to file using Java API
out = java.io.BufferedWriter(java.io.FileWriter('trash_me.xml'));
nc.writeNcML(out, '')
out.close()
echo('off') % Ending DEMO4 ------------------------------------------------


function lmcKernDisplay(kern, spacing)

% LMCKERNDISPLAY Display parameters of the LMC kernel.
% FORMAT
% DESC displays the parameters of the LMC kernel to the console.
% ARG kern : the kernel to display.
%
% FORMAT does the same as above, but indents the display according
% to the amount specified.
% ARG kern : the kernel to display.
% ARG spacing : how many spaces to indent the display of the kernel by.
%
% SEEALSO : modelDisplay, kernDisplay
%
% COPYRIGHT : Mauricio A. Alvarez , 2010

% KERN

fhandle = str2func([kern.basicKernelType 'KernDisplay']);
fhandle(kern, spacing);
if nargin > 1
  spacing = repmat(32, 1, spacing);
else
  spacing = [];
end
spacing = char(spacing);
if kern.nout>5
    fprintf(spacing)
    fprintf('For more than 5 outputs, the corregionalization matrix is not printed.\n');
else
    for i = 1:kern.nout
        for j = 1:kern.nout
            fprintf(spacing)
            fprintf('Corregionalization matrix entry (%d,%d) : %f\n', ...
                i,j, kern.B(i,j));
        end
    end
end


function mv = mv_analysisMenu(mv, hfig);
%
% mv = mv_analysisMenu(mv, hfig);
%
% Add menus with analysis options for
% the MultiVoxel UI.
%
%
% ras,  04/05
if ieNotDefined('hfig')
    hfig = gcf;
end

if ieNotDefined('mv')
    mv = get(hfig, 'UserData');
end

mv.ui.analMenu = uimenu('ForegroundColor',  'k',  'Label',  'Analysis',  'Separator',  'on');

% split-half option (odd v even trials)
uimenu(mv.ui.analMenu, 'Label', 'Split-Half analysis', ...
       'Separator', 'off', ...
       'Callback', 'mv_splitHalf;');

% split-half option (odd v even trials), remove means
uimenu(mv.ui.analMenu, 'Label', 'Split-Half analysis (remove means)', ...
       'Separator', 'off', ...
       'Callback', 'mv_splitHalf([], 1);');

% % add bootstrapping option (odd v even trials)
% uimenu(mv.ui.analMenu, 'Label', 'Reliability Analysis (odd vs even)', ...
%        'Separator', 'off', ...
%        'Callback', 'results = mv_reliability;');

% % add bootstrapping option (choose subsets)
% uimenu(mv.ui.analMenu, 'Label', 'Reliability Analysis (select subsets)', ...
%        'Separator', 'off', ...
%        'Callback', 'results = mv_reliability([], ''user'');');

% % sort by voxR option
% uimenu(mv.ui.analMenu, 'Label', 'Sort Voxels by Voxel Reliability', ...
%    'Separator', 'on', 'Callback', 'mv_sortByVoxR;');
%
% % sort by omniR option
% uimenu(mv.ui.analMenu, 'Label', 'Sort Voxels by Omnibus Correlation', ...
%    'Separator', 'off', 'Callback', 'mv_sortByOmniR;');
%
% % sort by MI option
% uimenu(mv.ui.analMenu, 'Label', 'Sort Voxels by Mutual Information', ...
%    'Separator', 'off', 'Callback', 'mv_sortByMutualInf;')

% sort by voxel amplitude
uimenu(mv.ui.analMenu, 'Label', 'Sort Voxel Order (sortrows)', ...
   'Separator', 'on', 'Callback', 'mv_sortVoxels([],  ''sortrows'',  ''dialog'');');

% sort by dprime
uimenu(mv.ui.analMenu, 'Label', 'Sort Voxel Order (d'')', ...
   'Separator', 'off', 'Callback', 'mv_sortVoxels([],  ''dprime'');');

% sort by GLM variance explained
uimenu(mv.ui.analMenu, 'Label', 'Sort Voxel Order (GLM variance explained)', ...
   'Separator', 'off', 'Callback', 'mv_sortVoxels([],  ''varexplained'');');

% clustering analysis option
uimenu(mv.ui.analMenu, 'Label', 'Cluster Voxels', ...
   'Separator', 'off', 'Callback', 'mv_basicCluster;');

% blur time courses option
uimenu(mv.ui.analMenu, 'Label', 'Temporal Blur Each Voxel''s Time Course', ...
   'Separator', 'on', ...
   'Callback', 'mv_blurTimeCourse;');

% sub-select voxels option
uimenu(mv.ui.analMenu,  'Label',  'Select Voxel Subset Based on Criteria...',  ...
    'Separator',  'on',  'Callback',  'mv_selectSubset([],  [],  ''dialog''); multiVoxelUI; ');

% remove outliers option
uimenu(mv.ui.analMenu, 'Label', 'Remove Outlier Voxels', ...
   'Separator', 'off', ...
   'Callback', 'mv_removeOutliers;');

% pick a subset option
uimenu(mv.ui.analMenu, 'Label', 'Click on voxels for a new UI', ...
   'Separator', 'off', 'Callback', 'mv_pickVoxels;');

% make a time course UI option
uimenu(mv.ui.analMenu, 'Label', 'Time Course UI for these voxels', ...
   'Separator', 'on', 'Callback', 'mv_makeTCUI;');

% % dump data to workspace option
% uimenu(mv.ui.analMenu, 'Label', 'Dump Data to Workspace', ...
%    'Separator', 'on', 'Callback', 'tc_dumpDataToWorkspace;');
%

set(hfig, 'UserData', mv);

return


function pts = trianglePoints(dt, idx)
    trIndices = dt.ConnectivityList(idx, :);
    pts = zeros(length(trIndices), 2);
    for i = 1:length(trIndices)
        pts(i, :) = dt.Points(trIndices(i), :);
    end
end


classdef ReferenceCellOfPathComputer < handle

    properties (Access = private)
        isInCell
    end

    properties (Access = private)
        pathVertexes
        mesh
    end

    methods (Access = public)

        function obj = ReferenceCellOfPathComputer(cParams)
            obj.init(cParams)

        end

        function cellsR = compute(obj)
            cellsR = obj.computeFirstReferenceCell();
            vertex = obj.pathVertexes;
            for ivertex = 2:length(vertex)
                vI   = vertex(ivertex);
                vOld = vertex(ivertex-1);
                cells    = obj.computeCellsOfVertex(vI);
                cellsOld = obj.computeCellsOfVertex(vOld);
                commonCells = intersect(cells,cellsOld);
                cellsR(ivertex) = commonCells(1);
            end

        end

    end

    methods (Access = private)

        function init(obj,cParams)
            obj.pathVertexes = cParams.pathVertexes;
            obj.mesh         = cParams.mesh;
        end

        function cell = computeFirstReferenceCell(obj)
            firstVertex  = obj.pathVertexes(1);
            cells =  obj.computeCellsOfVertex(firstVertex);
            cell  = cells(1);
        end

        function cells = computeCellsOfVertex(obj,vertex)
            vertexInCell  = obj.mesh.connec;
            itIs = (vertexInCell == vertex);
            cells = any(itIs,2);
            cells = find(cells);
        end

    end

end


%Sensor Sensor superclass
%
% A superclass to represent robot navigation sensors.
%
% Methods::
%   plot        plot a line from robot to map feature
%   display     print the parameters in human readable form
%   char        convert to string
%
% Properties::
% robot   The Vehicle object on which the sensor is mounted
% map     The Map object representing the landmarks around the robot
%
% Reference::
%
%   Robotics, Vision & Control,
%   Peter Corke,
%   Springer 2011
%
% See also RangeBearing, EKF, Vehicle, Map.

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

classdef Sensor < handle
    % TODO, pose option, wrt vehicle

    properties
        robot
        map

        verbose

        ls
        animate     % animate sensor measurements
        interval    % measurement return subsample factor
        fail
        delay

    end

    methods

        function s = Sensor(robot, map, varargin)
        %Sensor.Sensor Sensor object constructor
        %
        % S = Sensor(VEHICLE, MAP, OPTIONS) is a sensor mounted on a vehicle described by the Vehicle class object
        % VEHICLE and observing landmarks in a map described by the Map class object MAP.
        %
        % Options::
        % 'animate'    animate the action of the laser scanner
        % 'ls',LS      laser scan lines drawn with style ls (default 'r-')
        % 'skip', I    return a valid reading on every I'th call
        % 'fail',T     sensor simulates failure between timesteps T=[TMIN,TMAX]
        %

            opt.skip = 1;
            opt.animate = false;
            opt.fail =  [];
            opt.ls = 'r-';
            opt.delay = 0.1;

            [opt,args] = tb_optparse(opt, varargin);

            s.interval = opt.skip;
            s.animate = opt.animate;

            s.robot = robot;
            s.map = map;
            s.verbose = false;
            s.fail = opt.fail;
            s.ls = opt.ls;
        end

        function plot(s, jf)
        %Sensor.plot Plot sensor reading
        %
        % S.plot(J) draws a line from the robot to the J'th map feature.
        %
        % Notes::
        % - The line is drawn using the linestyle given by the property ls
        % - There is a delay given by the property delay

            if isempty(s.ls)
                return;
            end

            h = findobj(gca, 'tag', 'sensor');
            if isempty(h)
                % no sensor line, create one
                h = plot(0, 0, s.ls, 'tag', 'sensor');
            end

            % there is a sensor line animate it

            xi = s.map.map(:,jf);
            set(h, 'XData', [s.robot.x(1), xi(1)], 'YData', [s.robot.x(2), xi(2)]);
            pause(s.delay);

            drawnow
        end

        function display(s)
            %Sensor.display Display status of sensor object
            %
            % S.display() displays the state of the sensor object in
            % human-readable form.
            %
            % Notes::
            % - This method is invoked implicitly at the command line when the result
            %   of an expression is a Sensor object and the command has no trailing
            %   semicolon.
            %
            % See also Sensor.char.
            loose = strcmp( get(0, 'FormatSpacing'), 'loose');
            if loose
                disp(' ');
            end
            disp([inputname(1), ' = '])
            disp( char(s) );
        end % display()

        function str = char(s)
            %Sensor.char Convert sensor parameters to a string
            %
            % s = S.char() is a string showing sensor parameters in
            % a compact human readable format.
            str = [class(s) ' sensor class:'];
            str = char(str, char(s.map));
        end

    end % method
end % classdef