function [] = plot_route(ax, route, parsed_osm)
% plot (over map) the route found by route planner
%
% usage
%   PLOT_ROUTE(ax, route, parsed_osm)
%
% input
%   ax = axes object handle.
%   route = matrix of nodes traversed along route, as returned by the
%           route_planner function.
%   parsed_osm = parsed OpenStreetMap XML data, as returned by the
%                parse_openstreetmap function.
%
% 2012.04.24 (c) Ioannis Filippidis, jfilippidis@gmail.com
%
% See also ROUTE_PLANNER, PARSE_OPENSTREETMAP.

% empty path ?
if isempty(route)
    warning('path is empty. This means that the planner found no path.')
    return
end

nodexy = parsed_osm.node.xy;
start_xy = nodexy(:, route(1, 1) );
path_xy = nodexy(:, route);
path_end = nodexy(:, route(1, end) );

held = takehold(ax);

plotmd(ax, start_xy, 'Color', 'm', 'Marker', 'o', 'MarkerSize', 15)
plotmd(ax, path_xy, 'Color', 'r', 'LineStyle', '--', 'LineWidth', 5)
plotmd(ax, path_end, 'Color', 'c', 'Marker', 's', 'MarkerSize', 15)

restorehold(ax, held)


function H = lbfgsadd(H,k,dscale)
%lbfgsadd  adds k variables to the L-BFGS matrix H.
%
%   H = lbfgsadd(H,k,dscale) expands H to accomodate k new variables.
%   The new diagonal part of H (H0) gets set to dscale.
%
%   See also lbfgsdel, lbfgshprod, lbfgsupdate, lbfgsinit.

% $Id: lbfgsadd.m 385 2008-09-02 22:22:41Z mpf $

jMax = H.jMax;

H.S  = [ H.S ;    zeros(k,jMax)   ];
H.Y  = [ H.Y ;    zeros(k,jMax)   ];
H.H0 = [ H.H0; repmat(dscale,k,1) ];


% isnumeric() - returns 1
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008

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

function r = isnumeric(a)

    r = 1;


function parFormatDescription
% Description of .par file format for specifying event-related or block-
% design stimuli.
%
% The format is as follows: a tab-delimited ASCII text file with the
% following columns:
%
% (1) [\tab] (2) [\tab] (3) [\tab] (4) [\tab] (5) [\tab] (6) [\tab] (7)
%
% where: (1) is the onset time in seconds;
%        (2) is an integer specifying an event type, with 0 specifying
%            a 'baseline' or 'null' condition;
%        (3) is a text label specifying the name of a condition. (Only
%            the first occurrence of a condition is parsed to get the
%            name);
%        (4) specifies a color to associate w/ each condition, for use
%            in visualizing data that is sorted by condition. The color
%            is specified in matlab format, either a single letter
%            (e.g. 'w' for 'white', 'r' for 'red', 'm' for 'magenta')
%            or the format '[R G B]' where R, G, and B are the relative
%            intensities of the red, green and blue channels, each ranging
%            from 0-1 (see 'help plot');
%        (5) specifies a path to an image to associate w/ each condition,
%            for use in visualizing data that is sorted by condition;
%        (6) and (7) specify behavioral data, such as response times
%            or correct/incorrect responses.
%
%   All columns except for (1) and (2) are optional. If you don't have
%   information for a column, but would like to include it for a later
%   column, you can add the text '' or [] for that column (or add two
%   tabs).
%
%
%
% Importantly, .par files here have an implicit assumption that
% there's always _something_ going on during an experiment: events don't
% have a separately-specified duration, but are assumed to continue
% until the next event starts. Therefore, you may want to specify
% explicitly the end of a scan as a separate event (which can be
% assigned to a null condition or a negative number, if you like).

% if someone called this as a function, just give them the info:
p = fileparts(mfilename);
web(fullfile(p,'parFormatDescription.txt'));

return


function CPD = discrete_CPD(clamped, dom_sizes)
% DISCRETE_CPD Virtual constructor for generic discrete CPD
% CPD = discrete_CPD(clamped, dom_sizes)

CPD.dom_sizes = dom_sizes;
CPD = class(CPD, 'discrete_CPD', generic_CPD(clamped));


function [ y,dzdy ] = pad_data(  I,P,dzdy)
%PAD_DATA Summary of this function goes here
%   Detailed explanation goes here

    if(length(P)==1)
        P=ones(1,4)*P;
    end

    if isempty(dzdy)
        %%forward
        original_size=size(I);
        new_size=original_size;
        new_size(1)=new_size(1)+P(1)+P(2);
        new_size(2)=new_size(2)+P(3)+P(4);
        y=zeros(new_size,'like',I);
        y(1+P(1):P(1)+original_size(1),1+P(3):P(3)+original_size(2),:,:)=I;

    else
        %backward
        new_size=size(dzdy);
        original_size=new_size;
        original_size(1)=original_size(1)-P(1)-P(2);
        original_size(2)=original_size(2)-P(3)-P(4);
        y=I(1+P(1):P(1)+original_size(1),1+P(3):P(3)+original_size(2),:,:);
        dzdy=dzdy(1+P(1):P(1)+original_size(1),1+P(3):P(3)+original_size(2),:,:);

    end

end


function varargout = size( x, dim )

%   Disciplined convex/geometric programming information for SIZE:
%       SIZE imposes no convexity restrictions on its first argument.
%       The second argument, if supplied, must be a positive integer.

s = x.size_;
if nargin > 1,
    if nargout > 1,
        error( 'Too many output arguments.' );
    elseif ~isnumeric( dim ) || length( dim ) ~= 1 || dim <= 0 || dim ~= floor( dim ),
        error( 'Dimension argument must be a positive integer scalar.' );
    elseif dim > length( s ),
        varargout{1} = 1;
    else
        varargout{1} = s(dim);
    end
elseif nargout > 1,
    ns = length( s );
    no = nargout;
    if no > ns,
        s( end+1:no ) = 1;
    elseif no < ns,
        s( no ) = prod( s( no : end ) );
    end
    for k = 1 : no,
        varargout{k} = s(k); %#ok
    end
else
    varargout{1} = s;
end

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


function GCO_SetLabeling(Handle,Labeling)
% GCO_SetLabeling     Sets the current labeling
%     GCO_SetLabeling(Handle,Labeling) sets the entire labeling.

GCO_LoadLib();
if (isnumeric(Labeling))
    NumSites = gco_matlab('gco_getnumsites',Handle);
    NumLabels = gco_matlab('gco_getnumlabels',Handle);
    if (length(Labeling) ~= NumSites)
        error('Labeling must be of length NumSites');
    end
    if (~isa(Labeling,'int32'))
        if (any(floor(Labeling) ~= Labeling))
            error('Labeling was not integer valued');
        end
        Labeling = int32(Labeling);
    end
    if (min(Labeling) < 1 || max(Labeling) > NumLabels)
        error('Label must be in range 1..NumLabels');
    end
    gco_matlab('gco_setlabeling',Handle,Labeling);
end


function [step, lowerBound, upperBound] = defaultBoundaries(nPoints)
%Generates default lower bound, upper bound, and step for qth derivatives.

    step = 1;
    lowerBound = 1;
    upperBound = nPoints;

end


%% Mean-Shift Video Tracking
% by Sylvain Bernhardt
% July 2008
%% Description
% Insert in the image I a rectangle
% which size is H,W and thickness is
% expressed in pixels.
%
% I = Draw_target(x,y,W,H,I,thick)

function I = Draw_target(x,y,W,H,I,thick)
R=1; G=2; B=3;
I(y:y+thick-1,x:x+W,R) = 255;
I(y:y+thick-1,x:x+W,G) = 0;
I(y:y+thick-1,x:x+W,B) = 0;

I(y+H-thick+1:y+H,x:x+W,R) = 255;
I(y+H-thick+1:y+H,x:x+W,G) = 0;
I(y+H-thick+1:y+H,x:x+W,B) = 0;

I(y:y+H,x:x+thick-1,R) = 255;
I(y:y+H,x:x+thick-1,G) = 0;
I(y:y+H,x:x+thick-1,B) = 0;

I(y:y+H,x+W-thick+1:x+W,R) = 255;
I(y:y+H,x+W-thick+1:x+W,G) = 0;
I(y:y+H,x+W-thick+1:x+W,B) = 0;


function varargout = minus(varargin)
%-   Subtraction of two DISKFUN objects.
%
%   F - G subtracts G from F, where F and G are DISKFUN objects or scalars.
%
% See also DISKFUN/PLUS, DISKFUN/UMINUS.

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

[varargout{1:nargout}] = minus@separableApprox(varargin{:});

end


function varargout = lzipdecode(varargin)
%
% output = lzipdecode(input)
%    or
% output = lzipdecode(input,info)
%
% Decompressing an Lzip-compressed byte-stream to recover the original data
% This function depends on the ZMat toolbox (http://github.com/fangq/zmat)
%
% authors:Qianqian Fang (q.fang <at> neu.edu)
%
% input:
%      input: a string, int8/uint8 vector or numerical array to store Lzip-compressed data
%      info (optional): a struct produced by the zmat/lzipencode function during
%            compression; if not given, the inputs/outputs will be treated as a
%            1-D vector
%
% output:
%      output: the decompressed byte stream stored in a uint8 vector; if info is
%            given, output will restore the original data's type and dimensions
%
% examples:
%      [bytes, info]=lzipencode(eye(10));
%      orig=lzipdecode(bytes,info);
%
% license:
%     BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%

if(nargin==0)
    error('you must provide at least 1 input');
end
if(exist('zmat','file')==2 || exist('zmat','file')==3)
    if(nargin>1)
        [varargout{1:nargout}]=zmat(varargin{1},varargin{2:end});
    else
        [varargout{1:nargout}]=zmat(varargin{1},0,'lzip',varargin{2:end});
    end
else
    error('you must install ZMat toolbox to use this feature: http://github.com/fangq/zmat')
end


function YESNO = factored(X)

YESNO = ~isempty(X.midfactors);


function [elec] = read_polhemus_pos(filename)

% READ_POLHEMUS_POS reads electrode positions measured with the Polhemus tracker in
% one of the EEG labs at the DCCN. The software used with the Polhemus is from CTF.
%
% Use as:
%   [elec] = read_polhemus_pos(filename)
%
% This returns an electrode structure with
%   elec.label     cell-array with electrode labels (strings)
%   elec.pnt       position of each electrode

% Copyright (C) 2004-2019, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

fid = fopen_or_error(filename, 'rt');
line = fgetl(fid);
Nchan = str2double(line);

for i=1:Nchan
  line = fgetl(fid);
  [t, r] = strtok(line);
  elec.label{i} = char(t);
  elec.pnt(i,:) = sscanf(r, '%f')';
end
elec.label = elec.label(:);

try
  % read the fiducials
  line = fgetl(fid);
  [t, r] = strtok(line);
  fiducial.label{1} = char(t);
  fiducial.pnt(1,:) = sscanf(r, '%f')';
  line = fgetl(fid);
  [t, r] = strtok(line);
  fiducial.label{2} = char(t);
  fiducial.pnt(2,:) = sscanf(r, '%f')';
  line = fgetl(fid);
  [t, r] = strtok(line);
  fiducial.label{3} = char(t);
  fiducial.pnt(3,:) = sscanf(r, '%f')';
  % add the fiducials to the electrode array
  elec.label = cat(1, elec.label(:), fiducial.label(:));
  elec.pnt   = cat(1, elec.pnt, fiducial.pnt);
catch
  % do nothing
end

fclose(fid);


function [vectorField] = backward(vectorField)
% BACKWARD Flips the direction of a given vector field
%
% [vectorField] = backward(vectorField)
%
% INPUT ARGUMENTS
% vectorField 	- Vector field to flip
%
% OPTIONAL INPUT ARGUMENTS
% N/A
%
% OUTPUT ARGUMENTS
% vectorField 	- Flipped vector field

% Copyright (c) 2012 Daniel Forsberg
% danne.forsberg@outlook.com

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

dims = ndims(vectorField{1});

for k = 1 : dims
    vectorField{k} = - vectorField{k};
end


function name = p28_name ( )

%*****************************************************************************80
%
%% P28_NAME returns the name of problem 28.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string NAME, the name of the problem.
%
  name = 'Genz #2 / Patterson #6, Product Peak';

  return
end


function region = p06_region ( )

%*****************************************************************************80
%
%% P06_REGION returns the name of the integration region for problem 06.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string REGION, the name of the integration region.
%
  region = 'box';

  return
end


function [roi_table, region_obj] = ttest_table_by_condition(region_obj, DATA_OBJ, varargin)
% Extract region-by-region data from DATA_OBJ fmri_data object(s) in
% regions specified by region_obj, and return a table of means and stats,
% along with extracted data.
%
% First line: One-line summary description of function
%
% :Usage:
% ::
%
%     [roi_table, region_obj] = ttest_table_by_condition(region_obj, DATA_OBJ, [optional inputs])
%
% For objects: Type methods(object_name) for a list of special commands
%              Type help object_name.method_name for help on specific
%              methods.
%
% ..
%     Author and copyright information:
%
%     Copyright (C) 2017 Tor Wager
%
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/>.
% ..
%
% :Inputs:
%
%   **region_obj:**
%        A region object from CANlab core tools
%
%   **DATA_OBJ:**
%        an fmri_data object or cell vector of fmri_data objects with data
%        to extract.  Does not need to be in the same space as region
%        object -- extract_data.m method converts using mm coordinates.
%        Reslicing can induce variation in results due to interpolation.
%
% :Optional Inputs:
%   **'conditionnames', 'condition_names':**
%        Followed by cell vector of names for each condition
%        No spaces or special characters.
%
%
% :Outputs:
%
%   **roi_table:**
%        A table object containing ROI coordinates, names, and indices for
%        each region, along with means, and t-stats
%
%   **region_obj:**
%        The region object you entered in, with appended data,
%        images x conditions, stored in .dat field for each region.
%
% :Examples:
% ::
%
%    % give examples of code here
%    param1 = abc();
%    param2 = xyz();
%    [out1,out2] = func_call(param1, param2)
%
% :References:
%   CITATION(s) HERE
%
% :See also:
%   - list other functions related to this one, and alternatives*
%

% ..
%    Programmers' notes:
%    List dates and changes here, and author of changes
% ..

% -------------------------------------------------------------------------
% DEFAULTS AND INPUTS
% -------------------------------------------------------------------------

% Get volume from a region
volfunction = @(x) x.numVox .* prod(abs(diag(x.M(1:3, 1:3))));

if ~iscell(DATA_OBJ)
    DATA_OBJ = {DATA_OBJ};
end

nconditions = length(DATA_OBJ);
conditionnames = cell(1, nconditions);

for i = 1:length(DATA_OBJ)
    conditionnames{i} = sprintf('Cond_%d', i);
end

% optional inputs with default values
for i = 1:length(varargin)
    if ischar(varargin{i})
        switch varargin{i}

            case {'conditionnames', 'condition_names', 'conditions'}
                conditionnames = varargin{i+1}; varargin{i+1} = [];

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

if length(conditionnames) ~= nconditions
    error('Condition names and DATA_OBJ must be cells of same length');
end

nrois = length(region_obj);

% Initial table
% ------------------------------------------------------------------------
Index = (1:nrois)';
Name_of_Region = char(region_obj.shorttitle);
xyz_mm = cat(1, region_obj.mm_center);

for i = 1:nrois
    volume_mm3(i, 1) = volfunction(region_obj(i));
end

roi_table = table(Index, Name_of_Region, xyz_mm, volume_mm3);

% Initial table
% ------------------------------------------------------------------------

conditionnames = strrep(conditionnames, ' - ', '_vs_');
conditionnames = strrep(conditionnames, '-', '_vs_');
conditionnames = strrep(conditionnames, ' ', '_');

% extract ROI average data from each region
% Make regions x conditions matrix
% ------------------------------------------------------------------------

stars_by_condition = cell(nrois, nconditions);
[means_by_condition, t_by_condition, p_by_condition] = deal(zeros(nrois, nconditions));

for i = 1:nconditions

    rois_tmp = extract_data(region_obj, DATA_OBJ{i});

    % cat within regions to return data in region_obj object
    clear mydat
    for j = 1:nrois

        mydat = rois_tmp(j).dat(:, 1);

        % pad with longer of two
        [Anew Bnew] = padwithnan(region_obj(j).dat, mydat, 1);

        % region_obj(j).dat(:, i)
        region_obj(j).dat = [Anew Bnew];

    end

    % cat into image x roi matrix
    % for statistical tests
    dat = cat(2, rois_tmp.dat);

    % t-tests on each region across images (often subjects)
    [h, p, ci, stat] = ttest(dat);

    means_by_condition(:, i) = nanmean(dat)';

    t_by_condition(:, i) = stat.tstat';

    p_by_condition(:, i) = p';

    % Stars for each region
    for j = 1:length(p)

        if p(j) < .0015, mystr = '***';
        elseif p(j) < .015, mystr = '**';
        elseif p(j) < .055, mystr = '*';
        elseif p(j) < .105, mystr = '+';
        else mystr = ''; xadj = 0;
        end

        stars_by_condition{j, i} = mystr;

    end % loop through regions

    roi_table.(['t_' conditionnames{i}]) =  t_by_condition(:, i);

    signame = sprintf('sig%d', i);
    roi_table.(signame) = stars_by_condition(:, i);

end % loop through conditions

roi_table.means_by_condition = means_by_condition;
roi_table.p_by_condition = p_by_condition;

end % function


function z = classifierHead(x,poolerWeights,classifierWeights)
% classifierHead   The standard classification head for a BERT model.
%
%   Z = classifierHead(X,poolerWeights,classifierWeights) applies
%   bert.layer.pooler and bert.layer.classifier to X with poolerWeights and
%   classifierWeights respectively. Both poolerWeights and
%   classifierWeights must be structs with fields 'kernel' and 'bias'.

% Copyright 2021 The MathWorks, Inc.
z = bert.layer.pooler(x,poolerWeights);
z = bert.layer.classifier(z,classifierWeights);
end


function display(this)
%DISPLAY   Displays parameters of ALT_BA optical flow algorithm
%
%   This is a member function of the class 'alt_ba_optical_flow'.
%
% Authors: Deqing Sun, Department of Computer Science, Brown University
% Contact: dqsun@cs.brown.edu
% $Date: 2009 $
% $Revision: $
%
% Copyright 2009-2010, Brown University, Providence, RI. USA
%
%                          All Rights Reserved
%
% All commercial use of this software, whether direct or indirect, is
% strictly prohibited including, without limitation, incorporation into in
% a commercial product, use in a commercial service, or production of other
% artifacts for commercial purposes.
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for research purposes is hereby granted without fee,
% provided that the above copyright notice appears in all copies and that
% both that copyright notice and this permission notice appear in
% supporting documentation, and that the name of the author and Brown
% University not be used in advertising or publicity pertaining to
% distribution of the software without specific, written prior permission.
%
% For commercial uses contact the Technology Venture Office of Brown University
%
% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO
% THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
% FITNESS FOR ANY PARTICULAR PURPOSE.  IN NO EVENT SHALL THE AUTHOR OR
% BROWN UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
% DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
% PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
% ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
% THIS SOFTWARE.

  disp(sprintf('Image sequence (size):          %s', ...
               mat2str(size(this.images))));
  disp(sprintf('Spatial term weighting:         %s', ...
               mat2str(this.lambda)));
  disp(sprintf('Linear solver:                  %s', ...
               this.solver));
  disp(sprintf('# of pyramid levels:            %d', ...
               this.pyramid_levels));
  disp(sprintf('Spacing of pyramid levels:      %d', ...
               this.pyramid_spacing));
  disp(sprintf('Max. # of iterations:           %d', ...
               this.max_iters));
  disp(sprintf('Limit flow updates              %d', ...
               this.limit_update));


function f = real(f)
%REAL   Real part of a CHEBTECH.
%   REAL(F) is the real part of F.
%
% See also ISREAL, IMAG, CONJ.

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

% Compute the real part of the coefficients:
f.coeffs = real(f.coeffs);

if ( ~any(f.coeffs(:)) )
    % Input was imaginary, so output a zero CHEBTECH:
    f = f.make(zeros(1, size(f.coeffs, 2)));
    f.ishappy = 1;
end

end


classdef IspPressureCurveElement < AbstractCurveElement
    %IspPressureCurveElement Summary of this class goes here
    %   Detailed explanation goes here

    properties(Constant)
        minIndepValue = 0;
        maxIndepValue = NaN;

        minDepValue = 1E-6;
        maxDepValue = NaN;

        mandatoryIndepValues = [LaunchVehicleEngine.vacPress, LaunchVehicleEngine.seaLvlPress];
    end

    methods
        function obj = IspPressureCurveElement(atmoPress, engineIsp)
            obj.indepVar = atmoPress;
            obj.depVar = engineIsp;
        end

        function indepVarName = getIndepVarName(obj)
            indepVarName = 'Atmospheric Pressure';
        end

        function indepVarUnit = getIndepVarUnit(obj)
            indepVarUnit = 'kPa';
        end

        function depVarName = getDepVarName(obj)
            depVarName = 'Isp';
        end

        function depVarUnit = getDepVarUnit(obj)
            depVarUnit = 'sec';
        end
    end
end


%% Helper scriprt for running the DC Motor Simulation
close all % figures
disp('Running Simulation ...')
tic
plotMotorSim([Voltage, Inertia],0,'Starting Simulation...');

% perform simulation
for i = 1:noRuns
    V = Voltage(i);     % input voltage         (V)
    Jd = Inertia(i);    % load inertia          (g-cm^2)
    sim('MaxonDCMotor.mdl',[0 20]);
    time{i} = tout;
    velocity{i} = vel;
    plotMotorSim([Voltage, Inertia],i,['Run ',num2str(i), ' of ',num2str(noRuns)])
end
clear NbBlocks blk m powerguiblock vel tout t s simData
plotMotorSim([Voltage, Inertia],i,'Finished Simulation')
toc


function [trx,alltimestamps] = MergeMWTData(varargin)

MINDT = .0001;

trxall = varargin(1:3:end-2);
fnsall = varargin(2:3:end-1);
fnscopyall = varargin(3:3:end);
nsets = numel(trxall);
if nsets < 1,
  error('Usage: MergeMWTData(trx1,fns1,trx2,fns2,...)');
end

ids1 = unique([trxall{1}.id]);
ntargets = numel(ids1);
for seti = 2:nsets,
  ids2 = [trxall{seti}.id];
  if ~isempty(setxor(ids1,ids2)),
    error('ids do not match for sets 1 and %d',seti);
  end
end
idsall = cell(1,nsets);
for seti = 1:nsets,
  idsall{seti} = [trxall{seti}.id];
end

idx = cell(1,nsets);
for seti = 1:nsets,
  [~,idx{seti}] = ismember(ids1,idsall{seti});
end

alltimestamps = [];
for seti = 1:nsets,
  alltimestamps = union(alltimestamps,[trxall{seti}.timestamps]);
end
dts = diff(alltimestamps);
if any(dts < MINDT),
  error('Rounding error check failed: there are timestamps < %f apart',MINDT);
end

% frames per target
framesall = cell(ntargets,nsets);
firstframes = nan(ntargets,nsets);
endframes = nan(ntargets,nsets);
for seti = 1:nsets,
  for i = 1:ntargets,
    j = idx{seti}(i);
    [~,framesall{i,seti}] = ismember(trxall{seti}(j).timestamps,alltimestamps);
    firstframes(i,seti) = min(framesall{i,seti});
    endframes(i,seti) = max(framesall{i,seti});
  end
end

trx = [];
for i = 1:ntargets,
  trk = struct;
  trk.id = ids1(i);
  % union all frames for which there is data
  trk.firstframe = min(firstframes(i,:));
  trk.endframe = max(endframes(i,:));
  trk.nframes = trk.endframe - trk.firstframe + 1;
  trk.off = 1 - trk.firstframe;
  trk.timestamps = alltimestamps(trk.firstframe:trk.endframe);
  trk.dt = diff(trk.timestamps);
  for seti = 1:nsets,
    j = idx{seti}(i);
    frames = framesall{i,seti};
    for k = 1:numel(fnsall{seti}),
      fn = fnsall{seti}{k};
      sz = size(trxall{seti}(j).(fn));
      if numel(frames) ~= sz(2),
        error('Number of frames does not match size of %s for input %d',fn,seti);
      end
      if sz(2) ~= trk.nframes,
        fprintf('Adding %d empty frames to id %d, input %d, field %s\n',...
          trk.nframes-sz(2),ids1(i),fn);
      end
      sz(2) = trk.nframes;
      if iscell(trxall{seti}(j).(fn)),
        tmp = cell(sz);
      else
        tmp = nan(sz);
      end
      tmp(:,frames-trk.firstframe+1,:) = trxall{seti}(j).(fn);
      if isfield(trk,fn),
        if iscell(trk.(fn)) || iscell(tmp) || ...
            ndim(trk.(fn)) ~= numel(sz) || ...
            ~all(size(trk.(fn))==sz),
          warning('Field %s in multiple inputs and cannot be merged, skipping input %d',fn,seti);
        else
          idxdouble = ~isnan(trk.(fn)) & ~isnan(tmp);
          if any(trk.(fn)(idxdouble) ~= tmp(idxdouble)),
            warning('Field %s is in multiple inputs and does not match, skipping mismatches from input %d',fn,seti);
          end
          idxadd = isnan(trk.(fn)) & ~isnan(tmp);
          trk.(fn)(idxadd) = tmp(idxadd);
        end
      else
        trk.(fn) = tmp;
      end
    end
    for k = 1:numel(fnscopyall{seti}),
      fn = fnscopyall{seti}{k};
      trk.(fn) = trxall{seti}.(fn);
    end
  end
  trx = structappend(trx,trk);
end

% check for fields that got lost
fnsmerge = fieldnames(trx);
for seti = 1:nsets,
  fns = fieldnames(trxall{seti});
  missingfns = setdiff(fns,fnsmerge);
  if ~isempty(missingfns),
    fprintf('The following fields from input %d were not merged:',seti);
    fprintf(' %s',missingfns{:});
    fprintf('\n');
  end
end


function printAPResults( classes, results )
if ~isnumeric(results)
    aps = [results(:).ap]';
else
    aps = results;
end

for i = 1:numel(classes)
    class_string = classes{i}(1:min(5,length(classes{i})));
    fprintf('& %5s ', class_string)
end
fprintf('& %5s \\\\ \n', 'mean')
for i = 1:numel(classes)
    fprintf('& %2.3f ', aps(i))
end
fprintf('& %2.3f \\\\ \n', mean(aps))

end


%% Dislocation Density Tensor
%
%% PLEASE HELP AND ADD CONTENT HERE
%


% Extract WINDOWSIZE consecutive frames at position SLIDINGWINDOWIDX from a
% given image sequence.
function slidingWindow = assembleSlidingWindows(I, startFrame, windowSize, slidingWindowIdx)

    % Get the index of the reference frame for the current sliding window.
    refFrameIdx = startFrame + slidingWindowIdx - 1;

    % Extract sliding window from the given input sequence.
    slidingWindow.frames = I(:,:,(refFrameIdx - floor(windowSize / 2)):(refFrameIdx + floor(windowSize / 2)));
    % Capture reference frame for the current window.
    slidingWindow.referenceFrame = I(:,:,refFrameIdx);


function xform = mrAlignMI(sessionDir, vAnatFile, inplaneFile, initXFM, nuCorrect, forceSave)
% function xform = mrAlignMI(sessionDir, vAnatFile, inplaneFile, initXFM, nuCorrect, forceSave)
%
% * sessionDir is where the relevent mrSESSION lives. Defaults to pwd.
%
% * vAnatFile: default is a file browser if it's not found in the usual places.
%
% * inplaneFile: we currently need the first and last slice from the original
% inplane data to compute the coarse alignment. In the future, this info
% should be stored in the Inplane/anat.mat file.
%
% * initXFM : define [x y z] translations (first 3 params of the
% terminal output) from the automatically  computed coarse
% alignment. This is usuful when the algorithm  converges to an
% obviously wrong location (local minima) by allowing a different
% starting position.
%
% forceSave: flag to force saving computed xofrm to the mrSESSION file.
% Default is to show the computed alignment and then ask the user if they
% want to save.
%
% Tries to compute an inplane-to-vAnatomy alignment fully automatically.
% The core algorithm is quite simple (once you get past the file management
% stuff). It generates a coarse alignment by:
%  1. assuming that the vAnatomy is in the standard vAnatomy orientation
%     (sagittal, left-is-left, yxz, etc), and
%  2. using the original inplane header info to bring the inplane into a
%     standard orientation.
% It then uses a rigid body mutual information registration algorithm (from
% spm2) to refine the alignmnet.
%
% It seems to work perfectly when you have non-surface coil, whole-brain or
% most-brain data. YMMV with other data varieties.
%
% HISTORY:
% 2005.05.27 RFD (bob@sirl.stanford.edu) wrote it.
% 2005.06.27 RFD: slight changes to allow gzipped I-files.
% 2005.10.60 SOD: modified so it can refine existing mrSESSION.alignment's,
% put in a correction for an intensity gradient which seems
% to improve the alignment for surface-coil data, and put in
% another check that i foud useful. They come unfortenately with
% two more dialogs.
% 2006.04.03 SOD: added initXFM option

if(isempty(which('spm_coreg')))
    error('Requires spm2 tools! Try adding .../matlab/toolbox/mri/spm2 to your path.');
end
if(~exist('sessionDir','var') || isempty(sessionDir))
    sessionDir = pwd;
end
if(~exist('forceSave','var') || isempty(forceSave))
    forceSave = false;
end
if (~exist('nuCorrect','var') || isempty(nuCorrect))
    nuCorrect = [];
end
loadSession(sessionDir);
global HOMEDIR;
HOMEDIR = sessionDir;
global mrSESSION;
if(~exist('vAnatFile','var') || isempty(vAnatFile))
    % Try to find it
    vAnatFile = getVAnatomyPath;
end
if(~exist('inplaneFile','var') || isempty(inplaneFile))
    % Try to find it
    inplaneDir = fullfile(sessionDir,'Raw','Anatomy','Inplane');
    d = dir(fullfile(inplaneDir, 'I*001*'));
    if ~isempty(d), % ie any Ifiles are found
        inplaneFile = fullfile(inplaneDir, d(1).name);
        if(~exist(inplaneFile,'file'))
            [f,p] = uigetfile({'*.dcm','Dicom';'*.001','I-file';'*.gz','gzipped';'*.*','all'}, ...
                'Select a slice from raw Inplane files...', inplaneFile);
            if(isequal(f,0) || isequal(p,0))
                disp('User canceled.'); return;
            else
                inplaneFile = fullfile(p,f);
            end
        end;
    end
end
inplaneAnatFile = fullfile(sessionDir,'Inplane','anat.mat');
if(~exist(inplaneAnatFile,'file'))
    [f,p] = uigetfile({'*.mat','mat';'*.*','all'}, ...
        'Select the Inplane anat.mat file...', inplaneAnatFile);
    if(isequal(f,0) || isequal(p,0))
        disp('User canceled.'); return;
    else
        inplaneAnatFile = fullfile(p,f);
    end
end
disp(inplaneAnatFile);
disp(vAnatFile);

% check if alignment exists and give option to use this as a
% starting point allowing refinements of an existing alignment
% only do this if no initXFM is defined
useStartingEstimate = 0;
if notDefined('initXFM'),
    if isfield(mrSESSION,'alignment'),
        bn = questdlg(['mrSESSION.alignment exists. Do you want to to use ' ...
            'it as a starting estimate?'],...
            'starting estimate','Yes','No','No');
        if strmatch(bn,'Yes'),
            useStartingEstimate = 1;
        end;
    end;
end;

[v.img,v.mm] = readVolAnat(vAnatFile);
sz = size(v.img);
% Build a very rough xform to axial, ac-pc space
hsz = sz./2;
% ***FIXME: I'm not sure the v.mm is correct here. I've only tested it on
% isotropic data so far, so I can't tell.
vAnatAcpcXform = [0 0 v.mm(3) -hsz(3); 0 -v.mm(2) 0 hsz(1); -v.mm(1) 0 0 hsz(2); 0 0 0 1];
VF.uint8 = uint8(v.img);
VF.mat = vAnatAcpcXform;

ip = load(inplaneAnatFile);
% Correct for intensity gradient.
% yet another anoying dialog, sorry...
% For surface-coil data the results look better with correction - at
% least for the subject I tested.
if isempty(nuCorrect),
    bn = questdlg('Do you want to correct for an intensity gradient?',...
        'intensity gradient','Yes','No','No');
    if strmatch(bn,'Yes'),
        nuCorrect = true;
    else
        nuCorrect = false;
    end
end
if nuCorrect,
    [GradInt GradNoise]  = regEstFilIntGrad(ip.anat);
    ip.anat              = regCorrIntGradWiener(ip.anat,GradInt,GradNoise);
end;

% **** FIXE ME: we should compute and store the cannonical xform when we
% create the anat.mat file. Also, we can do a bit better for the initial
% alignment by taking the crop into account in the translations.
%sz = size(ip.anat);
% We assume that the brain is centered in the crop region.
%cropOffset = ip.inplanes.crop(1,:)-(ip.inplanes.fullSize-diff(ip.inplanes.crop))/2;
%cropOffset = ip.inplanes.crop(1,[2,1]); % OK
% apparently ip.inplanes.crop will not exist for older versions
if ~isfield(ip,'inplanes'),
    sz               = size(ip.anat);
    ip.inplanes.crop = [1 1;sz(1) sz(2)];
end
% not used?!
%cropOffset = [ip.inplanes.crop(1,[2,1])./2 0];%4 (best?)
%cropOffset = [eye(3) cropOffset'; 0 0 0 1];

% If Ifiles exist use them for an initial xform otherwise center on 0.
if ~ieNotDefined('inplaneFile'),
    xformToScanner = inv(computeXformFromIfile(inplaneFile,ip.inplanes.crop));
    xformToScanner(1:3,4) = xformToScanner(1:3,4)+[10 -20 -20]';
    % GE convention is right-to-left, but we want l-to-r (Talairach convention)
    %lrFlip = [-1 0 0 ip.inplanes.fullSize(1); 0 1 0 0; 0 0 1 0; 0 0 0 1];
    %lrFlip = [-1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1];
    VG.mat = xformToScanner;
else
    % default xform (center on 0,0,0)
    disp(sprintf('[%s]:No Ifiles found centering volume on 0.',mfilename));
    voxSize = mrSESSION.inplanes.voxelSize;
    VG.mat = [diag(voxSize),-(size(ip.anat)'.*voxSize'./2); 0 0 0 1];
    % GE convention is right-to-left, but we want l-to-r (Talairach
    % convention)
    % Careful! If you rerun you don't want to keep flipping your image
    % all the time
    VG.mat(1,:) =  -VG.mat(1,:);
    %VG.mat(2,:) =  -VG.mat(2,:);
    %VG.mat(3,:) =  -VG.mat(3,:);
    VG.mat
end;
%ip.anat = mrAnatHistogramClip(ip.anat, 0.4, 0.99);
ip.anat = mrAnatHistogramClip(ip.anat, 0.2, 0.99);
VG.uint8 = uint8(ip.anat*255+0.5);

if useStartingEstimate,
    revAlignment = spm_imatrix(VF.mat*mrSESSION.alignment/VG.mat);
    flags.params = revAlignment(1:6);
    disp('flags.params :');disp(flags.params);
    flags.sep    = [8 4 2 1];
    rotTrans     = spm_coreg(VG,VF,flags);
    oldAlignment = mrSESSION.alignment;
    disp('Old alignment :');disp(oldAlignment);
else
    % allow manually reset of the starting position
    if ~exist('initXFM','var')
        initXFM =[];
    end
    % max 6 params if less fill with zeros
    if numel(initXFM) < 6,
        flags.params = [initXFM(:)' zeros(1,6-numel(initXFM))];
    else
        flags.params = initXFM;
    end;
    % for dire need
    flags.sep    = [16 8 4 2];
    rotTrans     = spm_coreg(VG,VF,flags);
end;
%xform = spm_matrix(rotTrans)*VG.mat\VF.mat;
% volCoords = xform*[inplaneCoords]
alignment = VF.mat\spm_matrix(rotTrans)*VG.mat;
disp('Alignment matrix :');disp(alignment);

% output
xform = alignment;

sz = size(v.img);
bb = [1,1,1; sz];
ipVol = mrAnatResliceSpm(ip.anat, inv(alignment), bb, [1 1 1], [1 1 1 0 0 0], 0);
ipVol(isnan(ipVol)) = 0;
if(forceSave)
    % Save an image so user can check the alignment
    volIm = makeMontage(v.img); volIm = volIm./255;
    ipIm = makeMontage(ipVol);
    ipIm(ipIm<0)=0;ipIm(ipIm>1)=1;
    ipIm = cat(3,ipIm,volIm,volIm);
    imwrite(ipIm, fullfile(sessionDir,'align.png'));
    % just save it to existing mrSESSION
    mrSESSION.alignment = alignment;
    saveSession;
    % Delete old files that were built using previous alignment.
    cleanAllFlats; cleanGray; cleanVolume;
else
    disp('checking alignment...');
    % another check that i (SOD) found usefull
    % coronal (rotated...)
    % overlayVolumes(shiftdim(ipVol,2),shiftdim(v.img,2));
    % sagittal
    overlayVolumes(ipVol,v.img);
    % horizontal
    overlayVolumes(shiftdim(ipVol,1),shiftdim(v.img,1));

    volIm = makeMontage(v.img,40:9:sz(3)-40); volIm = volIm./255;
    if ~useStartingEstimate,
        ipVolInitial = mrAnatResliceSpm(ip.anat, inv(VF.mat\eye(4)*VG.mat), ...
            bb, [1 1 1], [1 1 1 0 0 0], 0);
        titlestring  = 'Initial coarse alignment';
    else
        ipVolInitial = mrAnatResliceSpm(ip.anat, inv(oldAlignment), ...
            bb, [1 1 1], [1 1 1 0 0 0], 0);
        titlestring  = 'Initial alignment from mrSESSION.alignment';
    end;
    ipVolInitial(isnan(ipVolInitial)) = 0;
    %figure;imagesc(makeMontage(ipVolInitial));axis equal;
    ipIm = makeMontage(ipVolInitial,40:9:sz(3)-40);
    ipIm(ipIm<0)=0;ipIm(ipIm>1)=1;
    figure;
    subplot(2,1,1);
    image(cat(3,ipIm,volIm,volIm)); axis equal tight off;
    title(titlestring);
    subplot(2,1,2);
    ipIm = makeMontage(ipVol,40:9:sz(3)-40);
    ipIm(ipIm<0)=0;ipIm(ipIm>1)=1;
    image(cat(3,ipIm,volIm,volIm)); axis equal tight off;
    title('Final alignment');

    [f,p] = uigetfile('*.mat','Save alignment to mrSESSION file?',fullfile(sessionDir,'mrSESSION.mat'));
    if(isequal(f,0)||isequal(p,0))
        error('Cancelled- alignment NOT SAVED.');
    else
        mrSESSION.alignment = alignment;
        saveSession;
        % Delete old files that were built using previous alignment.
        cleanAllFlats; cleanGray; cleanVolume;
    end
end
return;


%DOUBLE Dataset to double conversion
%
%	D = double(A)
%
% Converts a dataset A to a double D, which is just the set of datavectors.


function [cl, imgdat] = extract_from_rois(imgs_to_extract_from, mask_image, varargin)
% Generic function for extracting image data from a mask or atlas image,
% and returning the data and averages within regions specified by the user.
%
% :Usage:
% ::
%
%    [cl, imgdat] = extract_from_rois(imgs_to_extract_from, mask_image, varargin)
%
%  Regions to average over can be either regions of contiguous voxels
%  bounded by voxels with values of 0 or NaN, which are considered non-data
%  values, or regions defined by unique integer codes in the mask image
%  (i.e., for atlas images with unique codes for each defined region.)
%
%  Mask/Atlas image does NOT have to be in the same space as the images to
%  extract from.  It will be remapped/resliced.
%
%  extracted data is returned in single data format.
%
% :Inputs:
%
%   **char array** of strings containing 4D image file names (data extracted from these)
%
%   **mask_image** to extract from
%
% :Optional Inputs:
%
%   **average_over:**
%        Default = 'unique_mask_values' to average over unique integer codes in the mask image
%        (i.e., for atlas images with unique codes for each defined region)
%
%        OPT = 'contiguous_regions' to average over contiguous voxels
%        bounded by voxels of 0 or NaN (non-data values)
%
%
% :Examples:
% ::
%
%    imgs_to_extract_from = filenames('w*.nii','char');
%    mask_image = which('anat_lbpa_thal.img');
%    [cl, imgdat] = extract_from_rois(imgs_to_extract_from, mask_image);
%
% : Programmer Notes:
% ::
%   Marianne corrected a mistaken variable name from dat to regiondat in
%   line 175. Error would go unnoticed if region dat was not empty (which
%   is normally the case). June 2016
%

    if isempty(mask_image)
        mask_image = which('anat_lbpa_thal.img');
    end

    average_over = 'unique_mask_values'; %'contiguous_regions'  or 'unique_mask_values';

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

                % reserved keywords
                case 'contiguous_regions', average_over = 'contiguous_regions';
                case 'unique_mask_values', average_over = 'unique_mask_values';
            end
        end
    end

    space_defining_image = deblank(imgs_to_extract_from(1, :));

    % Note: we need to write out the image here only because we need its
    % anatomical boundaries (in-mask areas), contig voxels, etc. for later

    tmpname = num2str(round(10*rand(1, 5))); tmpname(tmpname == ' ') = []; tmpname = ['tmp_mask_' tmpname '.img'];

    maskData = scn_map_image(mask_image, space_defining_image, 'write', tmpname);
    maskData = maskData(:);

    volInfo = iimg_read_img(tmpname, 2);
    maskData = maskData(volInfo.wh_inmask);

    % This needs to be made Windows-compatible. kludgy now.
    eval(['!rm ' tmpname])
    eval(['!rm ' tmpname(1:end-4) '.hdr'])

    % Now we have the mask data and volInfo structure, and we can extract

    %%
    clear imgdat
    switch spm('Ver')

        case {'SPM12', 'SPM8', 'SPM5'}

            imgdat = iimg_get_data(volInfo, imgs_to_extract_from, 'single', 'verbose', 'noexpand');

        case {'SPM2', 'SPM99'}
            % legacy, for old SPM

            imgdat = iimg_get_data(volInfo, imgs_to_extract_from, 'single', 'verbose');

        otherwise
            error('Unknown version of SPM! Update code, check path, etc.');
    end

    %% Now get averages by cluster, if requested

    switch average_over

        % Define integer codes for sets of voxels to average over.

        case 'unique_mask_values'
            maskData = round(maskData);
            u = unique(maskData)'; u(u == 0) = [];
            nregions = length(u);
            fprintf('Averaging over unique mask values, assuming integer-valued mask: %3.0f regions\n', nregions);

        case 'contiguous_regions'
            u = unique(volInfo.cluster); u(u == 0) = [];
            maskData = volInfo.cluster;

        case 'none'

        otherwise
            error('Illegal value for average_over.  See help for this function.');
    end

    %% Now get the average activity in each region and define a "cluster"

    nregions = length(u);

    cl = struct('title', 'title', 'threshold', NaN, 'Z', NaN, 'voxSize', abs(diag(volInfo.mat(1:3, 1:3)))', ...
        'XYZ', [0 0 0]', 'XYZmm', [0 0 0]', 'from_label', NaN, 'M', volInfo.mat, 'dim', volInfo.dim);

    cl(1:nregions) = cl;

    for i = 1:nregions
        imgvec = maskData == u(i);

        regiondat = imgdat(:, imgvec);

        if ~isempty(regiondat)
            regionmean = double(nanmean(regiondat')');

        else
            regionmean = NaN .* zeros(size(regiondat, 1), 1);
            disp('WARNING: Empty region dat, check your masks');
        end

        cl(i).average_data = regionmean;
        cl(i).XYZ = volInfo.xyzlist(imgvec,:)';
        cl(i).XYZmm = voxel2mm(cl(i).XYZ,volInfo.mat);

        cl(i).Z = ones(1,size(cl(i).XYZ,2));

    end
end


function f = ldivide(f, c, varargin)
%.\   Left array divide for a TRIGTECH.
%   C .\ F is equivalent to F ./ C.
%
% See also MLDIVIDE, RDIVIDE, TIMES.

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

f = rdivide(c, f, varargin{:});

end


function frame2gif(volume,videoname,delaytime,resizeRate,height)
if exist('delaytime','var')~=1
    delaytime=0.5;
end
if exist('resizeRate','var')~=1
    resizeRate=1;
end
if exist('height','var')~=1
    height=0;
end

nframes=size(volume,4);

for i=1:nframes
    im=volume(:,:,:,i);
    if height~=0
        [h,w,nchannels]=size(im);
        resizeRate=height/h;
    end
    if resizeRate<1
        im=imresize(imfilter(im,fspecial('gaussian',5,0.7),'same','replicate'),resizeRate,'bicubic');
    else if resizeRate>1
            im=imresize(im,resizeRate,'bicubic');
        end
    end
    [X,map]=rgb2ind(im,256);
    if i==1
        imwrite(X,map,videoname,'DelayTime',delaytime,'LoopCount',Inf);
    else
        imwrite(X,map,videoname,'WriteMode','append','DelayTime',delaytime);
    end
end


function [C,W,G,V2W] = qslim(V,F,t,varargin)
  % QSLIM Very simple wrapper for qslim
  %
  % [C,W,G,V2W] = qslim(V,F,t,'ParameterName',ParameterValue)
  %
  % Inputs:
  %   V  #V by 3 input mesh vertex positions
  %   F  #F by 3 input mesh triangle indices (1-indexed)
  %   t  target number of faces {0 for all collapse}
  %   Optional:
  %     'QSlimFlags' followed by qslim flags
  % Outputs:
  %   C  #collapse list of edge collapse structs with fields
  %     .a index into V of vertex collapsed to
  %     .b index into V of vertex collapsed from
  %     .da  1 by 3 displacement of vertex a
  %     .rm list of indices in F of faces removed by this collapse
  %     .mod list of indices in F of faces modified by this collapse
  %   W  #W by 3 collapsed mesh vertex positions
  %   G  #G by 3 collapsed mesh triangle indices (1-indexed)
  %   V2W  #V list of indices into W
  %
  % See also: readLOG, perform_edge_collapse, path_to_qslim
  %

  qslim_flags = '';
  if nargin <3
    t = 0;
  end

  v = 1;
  while v<=numel(varargin)
    switch varargin{v}
    case 'QSlimFlags'
      assert((v+1)<=numel(varargin));
      v = v+1;
      qslim_flags = varargin{v};
    otherwise
      error(['Unsupported parametername: ' varargin{v}]);
    end
    v = v+1;
  end

  prefix = tempprefix();
  input = [prefix '.smf'];
  output = [prefix '.log'];

  % Write input to file
  writeSMF(input,V,F);

    % prepare command string
    command = sprintf('%s -t %d -M log -q %s %s >%s', ...
      path_to_qslim,t,qslim_flags,input,output);
  try
    [status,result] = system(command);
    if status ~= 0
      error(result);
    end

    [VV,FF,C] = readLOG(output);
    % should match input
    assert(size(VV,1)==size(V,1));
    assert(size(FF,1)==size(F,1));
    assert(isequal(F,FF));

    delete(input);
    delete(output);
  catch ME
    fprintf('%s\n',command);
    rethrow(ME);
  end

  % This is expensive so only perform if required by output
  if nargout>1
    [W,G,V2W] = perform_edge_collapse(V,F,C,t);
  end

end


%% OPENMAS HIT-BOX ENUMERATION CLASSES (OMAS_hitBoxType.m) %%%%%%%%%%%%%%%%
% This file contains the enumeration definition of the simulation
% recognised object types.

% Author: James A. Douthwaite 25/01/19

classdef OMAS_hitBoxType < uint8
   % Assign uint8 type to enumeration values
   enumeration
      none(0);           % Generic
      spherical(1);      % Spherical bounding box assumption
      AABB(2);           % Axis aligned bounding box
      OBB(3);            % Object orientated bounding box
      capsule(4);        % Capsule enclosed volume
      mesh(5);           % Mesh enclosed volume
   end
end


function [seq, ground_truth] = load_video_info(video_path, video_name)

ground_truth = dlmread([video_path '/groundtruth_rect.txt']);
% ground_truth = dlmread([video_path, '/', video_name, '_gt', '.txt']);

seq.format = 'otb';
seq.len = size(ground_truth, 1);
seq.init_rect = ground_truth(1,:);

img_path = [video_path '/img/'];

if exist([img_path num2str(1, '%04i.png')], 'file'),
    img_files = num2str((1:seq.len)', [img_path '%04i.png']);
elseif exist([img_path num2str(1, '%04i.jpg')], 'file'),
    img_files = num2str((1:seq.len)', [img_path '%04i.jpg']);
elseif exist([img_path num2str(1, '%04i.bmp')], 'file'),
    img_files = num2str((1:seq.len)', [img_path '%04i.bmp']);
else
    error('No image files to load.')
end

seq.s_frames = cellstr(img_files);

end


function prepareDummyTracksKatie(moviename)

expdir = fileparts(moviename);
[~,nframes,fid,~] = get_readframe_fcn(moviename);
if fid>0,
  fclose(fid);
end
T = struct;
T.timestamps = ones(1,nframes)*now;
T.trx.x = ones(1,nframes)*5;
T.trx.y = ones(1,nframes)*5;
T.trx.a = ones(1,nframes)*1;
T.trx.b = ones(1,nframes)*1;
T.trx.theta = zeros(1,nframes);
T.trx.id = 1;
T.trx.firstframe = 1;
T.trx.endframe = nframes;
T.trx.x_mm = T.trx.x;
T.trx.y_mm = T.trx.y;
T.trx.a_mm = T.trx.a;
T.trx.b_mm = T.trx.b;
T.trx.theta_mm = T.trx.theta;
T.trx.dt = 1/1300;
T.trx.fps = 1300;
T.trx.pxpermm = 1;
T.trx.sex = 'M';
T.trx.off = 0;
T.trx.nframes = nframes;

save(fullfile(expdir,'trx.mat'),'-struct','T');


im = iread('lena.pgm');
whos im
about im
figure(1); idisp(im)
im(100,120)
im(100:104,120:124)
figure(2); plot(im(200,:))
eye = iroi(im);

im = iread('lena.pgm', 'double');
about im
idisp(im)

[im,tags]=iread('/Users/corkep/proj/Oxford/2012/images/lumix/P1000545.JPG');
idisp(im)
tags
tags.DigitalCamera


function [ xpnew ] = syncFlippedLandmarks( xp )

lookup = [6 5 4 3 2 1 12 11 10 9 8 7 17 16 15 14 13 20 19 18 21];
if size(xp,1)==2
    xpnew(1,:) = xp(1,lookup);
    xpnew(2,:) = xp(2,lookup);
else
    xpnew = xp(lookup);
end

end


function F = restrict(F, newDomain)
%RESTRICT   Restrict a CHEBFUN object to a subinterval.
%   G = RESTRICT(F, [S1, S2]) returns a CHEBFUN G defined on the interval [S1,
%   S2] which agrees with F on that interval. Any interior breakpoints in
%   F.DOMAIN within [S1, S2] are kept in G.DOMAIN.
%
%   G = RESTRICT(F, S), where S is a row vector, will introduce additional
%   interior breakpoints at S(2:end-2).
%
%   In both cases, if S(1) > S(end), S(1) < F.domain(1), or S(end) >
%   F.domain(end), then an error is returned. If S is empty or a scalar, then an
%   empty CHEBFUN G is returned.
%
%   Note that G will not be 'simplified'. If this is required, call G =
%   SIMPLIFY(RESTRICT(F)), or G = F{S}.
%
% See also OVERLAP, SUBSREF, DEFINE, SIMPLIFY.

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

% Tweak the domain of a quasimatrix input:
[F, newDomain] = tweakDomain(F, newDomain);

% Loop over the columns:
for k = 1:numel(F)
    F(k) = columnRestrict(F(k), newDomain);
end

end

function f = columnRestrict(f, newDomain)

% Ignore duplicate entries in newDomain:
newDomain([false, ~diff(newDomain)]) = [];

% Empty case:
if ( isempty(f) )
    return
elseif ( isempty(newDomain) || numel(newDomain) == 1 )
    f = chebfun();
    return
end

% Cast a periodic chebfun to a regualr chebfun:
if ( isPeriodicTech(f) )
    f = chebfun(f);
end

% Grab domain from f:
oldDomain = f.domain;

% Trivial case:
if ( (numel(newDomain) == 2) && domainCheck(f, newDomain([1, end])) )
    % The domains are the same!
    return
end

% Check the domain is valid:
if ( (newDomain(1) < oldDomain(1)) || (newDomain(end) > oldDomain(end)) || ...
        any(diff(newDomain) < 0) )
    % newDom is not a valid subinterval of oldDom!
    error('CHEBFUN:CHEBFUN:restrict:subdom', 'Not a valid subdomain.');
end

% Obtain FUN cell and pointValues from f:
funs = f.funs;
pointValues = f.pointValues;

% Discard intervals to the left:
discardIntsLeft = oldDomain(2:end) < newDomain(1);
oldDomain([discardIntsLeft, false]) = [];
funs(discardIntsLeft) = [];
pointValues([discardIntsLeft, false],:,:) = [];

% Discard intervals to the right:
discardIntsRright = oldDomain(1:end-1) > newDomain(end);
oldDomain([false, discardIntsRright]) = [];
funs(discardIntsRright) = [];
pointValues([false, discardIntsRright],:,:) = [];

% Take the union of the new and old domains:
if ( ~isempty( oldDomain(2:end-1) ) ) % Required due to Matlab union() behavior.
    % NB: the old endpoints will either be in newDomain or are not required.
    newDomain = union(oldDomain(2:end-1), newDomain);
end
numFuns = numel(funs);

% Initialise storage for new FUN objects and pointValues:
newFuns = cell(1, numel(newDomain)-1);

% Loop through each fun and restrict as required:
l = 0;
for k = 1:numFuns
    % Find the breaks which correspond to the kth fun:
    subsIdx = (newDomain >= oldDomain(k)) & (newDomain <= oldDomain(k+1));
    if ( sum(subsIdx) == 2 )
        % This interval is already a FUN: (i.e., no new breaks to introduce)
        newFuns{l+1} = restrict(funs{k}, newDomain(subsIdx));
        l = l + 1;
    else
        numSubs = sum(subsIdx)-1;
        if ( numSubs > 0 )
            % Restrict the FUN at the corresponding break points:
            newFuns(l+(1:numSubs)) = restrict(funs{k}, newDomain(subsIdx));
            l = l + numSubs;
        end
    end
end

% Update the pointValues:
newPointValues = chebfun.getValuesAtBreakpoints(newFuns);
% Restore existing pointValues:
[mask, locB] = ismember(oldDomain, newDomain);
locB(~logical(locB)) = [];
newPointValues(locB,:) = pointValues(mask,:);

% Attach data to CHEBFUN to return as output:
f.domain = newDomain;
f.funs = newFuns;
f.pointValues = newPointValues;

end


function varargout = plot_line(varargin)
% PLOT_LINE M-file for plot_line.fig
%      PLOT_LINE, by itself, creates a new PLOT_LINE or raises the existing
%      singleton*.
%
%      H = PLOT_LINE returns the handle to a new PLOT_LINE or the handle to
%      the existing singleton*.
%
%      PLOT_LINE('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in PLOT_LINE.M with the given input arguments.
%
%      PLOT_LINE('Property','Value',...) creates a new PLOT_LINE or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before plot_line_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to plot_line_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 plot_line

% Last Modified by GUIDE v2.5 27-Mar-2004 18:44:35

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @plot_line_OpeningFcn, ...
                   'gui_OutputFcn',  @plot_line_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 plot_line is made visible.
function plot_line_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 plot_line (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = plot_line_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
varargout{1} = handles.output;

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

% Get the file to open
[filename, pathname] = uigetfile('*.dat','Load Data');
if filename ~= 0

   % Open the input file
   filename = [pathname filename];
   [fid,msg] = fopen(filename,'rt');

   % Check to see of the open failed.
   if fid < 0

      % There was an error--tell user.
      str = ['File ' filename ' could not be opened.'];
      title = 'File Open Failed';
      errordlg(str,title,'modal');

   else

      % File opened successfully. Read the (x,y) pairs from
      % the input file.  Get first (x,y) pair before the
      % loop starts.
      [in,count] = fscanf(fid,'%g',2);
      ii = 0;

      while ~feof(fid)
         ii = ii + 1;
         x(ii) = in(1);
         y(ii) = in(2);

         % Get next (x,y) pair
         [in,count] = fscanf(fid,'%g',2);
      end

      % Data read in.  Close file.
      fclose(fid);

      % Now plot the data.
      hline = plot(x,y,'LineWidth',3);
      xlabel('x');
      ylabel('y');
      grid on;

      % Associate the context menu with line
      set(hline,'Uicontextmenu',handles.ContextMenu1);

      % Save the line's handle as application data
      handles.hline = hline;
      guidata(gcbf, handles);

   end
end

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

close(gcbf);

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

set(handles.hline,'LineStyle','-');

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

set(handles.hline,'LineStyle','--');

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

set(handles.hline,'LineStyle',':');

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

set(handles.hline,'LineStyle','-.');

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

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