text:
function planC = copyStrToScan_meshBased(structNum,scanNum,planC)
%function planC = copyStrToScan_meshBased(structNum,scanNum,planC)
%
%This function derives a new structure from structNum which is associated
%to scanNum. The naming convention for this new structure is
%[structName assoc scanNum]. If structNum is already associated to scanNum,
%the unchanged planC is returned back.
%
%APA, 11/13/07
%
% 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/>.

global stateS

if ~exist('planC')
    global planC
end

indexS = planC{end};

%return if structNum is already associated to scanNum
assocScanNum = getAssociatedScan(planC{indexS.structures}(structNum).assocScanUID);
if assocScanNum == scanNum
    warning(['Structure Number ',num2str(structNum),' is already assocoated with scan ',num2str(scanNum)])
    return;
end

%set Matlab path to directory containing the Mesh-library
currDir = cd;
if ispc
    meshDir = fileparts(which('libMeshContour.dll'));
    cd(meshDir);
    loadlibrary('libMeshContour','MeshContour.h');
elseif isunix
    meshDir = fileparts(which('libMeshContour.so'));
    cd(meshDir);
    loadlibrary('libMeshContour.so','MeshContour.h');
end

%Create Mesh-representation if it does not exist
clearMeshFlag = 0;
smoothIter = 10;

if ~isfield(planC{indexS.structures}(structNum),'meshRep') || (isfield(planC{indexS.structures}(structNum),'meshRep') && ~isempty(planC{indexS.structures}(structNum).meshRep) && planC{indexS.structures}(structNum).meshRep == 0)  || (isfield(planC{indexS.structures}(structNum),'meshRep') && isempty(planC{indexS.structures}(structNum).meshRep))

    assocScan = getStructureAssociatedScan(structNum,planC);
    [xVals, yVals, zVals] = getScanXYZVals(planC{indexS.scan}(assocScan));
    structUID   = planC{indexS.structures}(structNum).strUID;
    [rasterSegments, planC, isError]    = getRasterSegments(structNum,planC);
    [mask3M, uniqueSlices] = rasterToMask(rasterSegments, assocScan);
    mask3M = permute(mask3M,[2 1 3]);
    %Handle structures defined on single CT slice
    if size(mask3M,3)==1
        if uniqueSlices==1
            mask3M(:,:,2) = zeros(size(mask3M));
            uniqueSlices = [uniqueSlices uniqueSlices+1];
        elseif uniqueSlices==length(zVals)
            mask3M(:,:,2) = zeros(size(mask3M));
            uniqueSlices = [uniqueSlices uniqueSlices-1];
        else
            mask3M(:,:,2) = zeros(size(mask3M));
            uniqueSlices = [uniqueSlices uniqueSlices+1];
        end
    end
    calllib('libMeshContour','loadVolumeAndGenerateSurface',structUID,xVals,yVals,zVals(uniqueSlices), double(mask3M),0.5, uint16(smoothIter))
    %Store mesh under planC
    planC{indexS.structures}(structNum).meshS = calllib('libMeshContour','getSurface',structUID);
    clearMeshFlag = 1;
end

%Get transformation matrix
if ~isfield(planC{indexS.scan}(scanNum),'transM') | isempty(planC{indexS.scan}(scanNum).transM)
    transMnew = eye(4);
else
    transMnew = planC{indexS.scan}(scanNum).transM;
end
if ~isfield(planC{indexS.scan}(assocScanNum),'transM') | isempty(planC{indexS.scan}(assocScanNum).transM)
    transMold = eye(4);
else
    transMold = planC{indexS.scan}(assocScanNum).transM;
end
transM = inv(transMnew)*transMold;

%Get z-coordinates of scan
[jnk1,jnk2,scanZv] = getScanXYZVals(planC{indexS.scan}(scanNum));
for i = 1:length(scanZv)
    coord = scanZv(i);
    pointOnPlane = [0 0 coord] - transM(1:3,4)';
    planeNormal = (inv(transM(1:3,1:3))*[0 0 1]')';
    pointOnPlane = (inv(transM(1:3,1:3))*pointOnPlane')';
    structUID   = planC{indexS.structures}(structNum).strUID;
    contourS    = calllib('libMeshContour','getContours',structUID,single(pointOnPlane),single(planeNormal),single([0 1 0]),single([1 0 0]));
    if ~isempty(contourS) && length(length(contourS.segments)) > 0
        for segNum = 1:length(contourS.segments)
            pointsM = applyTransM(transM,contourS.segments(segNum).points);
            contour(i).segments(segNum).points(:,1) = pointsM(:,1);
            contour(i).segments(segNum).points(:,2) = pointsM(:,2);
            contour(i).segments(segNum).points(:,3) = coord*pointsM(:,1).^0;
        end
    else
        contour(i).segments(1).points = [];
    end
end

%Clear Surface Mesh
unloadlibrary('libMeshContour')
if clearMeshFlag
    planC{indexS.structures}(structNum).meshRep = 0;
    planC{indexS.structures}(structNum).meshS = [];
end

%Change directory back
cd(currDir)

strname = [planC{indexS.structures}(structNum).structureName,' asoc ',num2str(scanNum)];

newstr = newCERRStructure(scanNum);
newstr.contour = contour;
newstr.structureName = strname;
newstr.associatedScan = scanNum;
newstr.assocScanUID = planC{indexS.scan}(scanNum).scanUID;
newstr.meshRep = 0;
numStructs = length(planC{indexS.structures});

%Append new structure to planC.
planC{indexS.structures} = dissimilarInsert(planC{indexS.structures}, newstr, numStructs+1, []);

%Create Raster Segments
planC = getRasterSegs(planC, numStructs+1);

%Update uniformized data.
[jnk, relStructNum] = getStructureAssociatedScan(numStructs+1,planC);
if relStructNum==1
    planC = setUniformizedData(planC);
else
    planC = updateStructureMatrices(planC, numStructs+1);
end

if isfield(stateS,'handle') && ishandle(stateS.handle.CERRSliceViewer)
    stateS.structsChanged = 1;
    CERRRefresh
end

return;


text:
function test_old_preproc_resample

% MEM 1gb
% WALLTIME 00:10:00
% DEPENDENCY

%this script tests the anti-aliasing filter in the resample function as used by ft_preproc_resample

fs    = 1000;
nsec  = 100;
nsmp  = fs*nsec;
tim   = ([1:nsmp]-1)./fs;
foi   = [0:(fs-1)];

datin       = randn(1,nsmp);
datin2      = reshape(datin, [fs nsec]);
datin2pow   = abs(fft(datin2, [], 1)).^2;

dathigh     = ft_preproc_highpassfilter(datin, fs, 300, 10, 'but', 'twopass');
dathigh     = dathigh + 0.1.*sin(2.*pi.* 400 .* tim);
dathigh2    = reshape(dathigh, [fs nsec]);
dathigh2pow = abs(fft(dathigh2, [], 1)).^2;

datlow     = ft_preproc_lowpassfilter(datin, fs, 300, 10, 'but', 'twopass');
datlow     = datlow + 0.1.*sin(2.*pi.* 400 .* tim);
datlow2    = reshape(datlow, [fs nsec]);
datlow2pow = abs(fft(datlow2, [], 1)).^2;

figure;hold on;
plot(foi, mean(datin2pow,2));
plot(foi, mean(dathigh2pow,2),'r');
plot(foi, mean(datlow2pow,2), 'm');

dathigh     = ft_preproc_highpassfilter(datin, fs, 400, 10, 'fir', 'twopass');
dathigh     = dathigh + 0.1.*sin(2.*pi.* 350 .* tim) + 0.1.*randn(1,nsmp);
dathigh2    = reshape(dathigh, [fs nsec]);
dathigh2pow = abs(fft(dathigh2, [], 1)).^2;

datlow     = ft_preproc_lowpassfilter(datin, fs, 400, 10, 'fir', 'twopass');
datlow     = datlow + 0.1.*sin(2.*pi.* 350 .* tim);
datlow2    = reshape(datlow, [fs nsec]);
datlow2pow = abs(fft(datlow2, [], 1)).^2;

figure;hold on;
plot(foi, mean(datin2pow,2));
plot(foi, mean(dathigh2pow,2),'r');
plot(foi, mean(datlow2pow,2), 'm');

newfs    = 500;
newfoi   = [0:(newfs-1)];
dathighr = ft_preproc_resample(dathigh, fs, newfs, 'resample');
dathighx = reshape(dathighr, [newfs nsec]);
dathighxpow = abs(fft(dathighx, [], 1)).^2;

dathighlow = ft_preproc_resample(ft_preproc_lowpassfilter(dathigh, fs, 150, 2, 'but', 'twopass'), fs, newfs, 'resample');
dathighlow = reshape(dathighlow, [newfs nsec]);
dathighlowpow = abs(fft(dathighlow, [], 1)).^2;

figure;hold on;
plot(foi(1:250),    (mean(dathigh2pow(1:250,2:end-1),2)));
plot(newfoi(1:250), (mean(dathighxpow(1:250,2:end-1),2)),'r');
plot(newfoi(1:250), (mean(dathighlowpow(1:250,2:end-1),2)),'m');

figure;hold on;
plot(foi(1:250), mean(dathighxpow(1:250,2:end-1),2)./mean(dathigh2pow(1:250,2:end-1),2));

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [x,upper,possible,p,successful] = sdpPump(p,x,tolerance)

upper = inf;
intvars = [p.integer_variables(:);p.binary_variables(:)];
convars = p.noninteger_variables;
possible = 0;
successful = 0;

if length(convars)==1 && length(p.K.s)==1 && p.K.s(1)>0 && sum(p.K.q)==0
    possible = 1;
    if isempty(p.sdpPumpData)
        p.sdpPumpData.H = p.F_struc(1+p.K.f+p.K.l:end,:);
        p.sdpPumpData.H0 = reshape(p.sdpPumpData.H(:,1),p.K.s(1),p.K.s(1));
        p.sdpPumpData.Hx = reshape(p.sdpPumpData.H(:,1+convars),p.K.s(1),p.K.s(1));
        p.sdpPumpData.Hz = p.sdpPumpData.H(:,1 + intvars);if nnz(p.sdpPumpData.Hz)/numel(p.sdpPumpData.Hz)>0.5;p.sdpPumpData.Hz = full(p.sdpPumpData.Hz);end
    end
    Hy = p.sdpPumpData.H0 + reshape(p.sdpPumpData.Hz*x(intvars),p.K.s(1),p.K.s(1));
    s = eig(full(p.sdpPumpData.Hx),full(Hy));
    s(isinf(s))=[];
    s(isnan(s))=[];
    if any(s)
        x(convars) = min(-1./s(s~=0));
        if ~isnan(x(convars))
            x(convars) = max(x(convars),p.lb(convars));
            x(convars) = min(x(convars),p.ub(convars));
            if checkfeasiblefast(p,x,tolerance)
                upper = computecost(p.f,p.c,p.Q,x,p);
                successful = 1;
            else
                upper = inf;
                successful = 0;
            end
        end
    end
end

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
function q = simpqual ( p, t, type )

%*****************************************************************************80
%
%% SIMPQUAL computes the simplex quality.
%
%  Discussion:
%
%    If TYPE = 1, the quality measure used computes the ratio of
%    the radii of the inscribed and circumscribed circles or spheres.
%
%    Only dimensions 1, 2 and 3 can be handled.  In 1D, the quality is always 1.
%
%  Licensing:
%
%    (C) 2004 Per-Olof Persson.
%    See COPYRIGHT.TXT for details.
%
%  Reference:
%
%    Per-Olof Persson and Gilbert Strang,
%    A Simple Mesh Generator in MATLAB,
%    SIAM Review,
%    Volume 46, Number 2, June 2004, pages 329-345.
%
%  Parameters:
%
%    Input, real P(NP,ND), the coordinates of a set of nodes.
%
%    Input, integer T(NT,1:ND+1), a list of the nodes which make up each
%    simplex in the mesh.
%
%    Input, integer TYPE, specifies the quality measure:
%    1: Compute the radius ratio (default)
%    2: Use an approximate formula.
%
%    Output, real Q(NT), the simplex quality measure.
%
  if ( nargin < 3 )
    type = 1;
  end

  switch type
%
%  RADIUS RATIO
%
    case 1

      switch size ( p, 2 )

        case 1

          q = ones ( 1, size(t,2) );

        case 2

          a=sqrt(sum((p(t(:,2),:)-p(t(:,1),:)).^2,2));
          b=sqrt(sum((p(t(:,3),:)-p(t(:,1),:)).^2,2));
          c=sqrt(sum((p(t(:,3),:)-p(t(:,2),:)).^2,2));
          r=1/2*sqrt((b+c-a).*(c+a-b).*(a+b-c)./(a+b+c));
          R=a.*b.*c./sqrt((a+b+c).*(b+c-a).*(c+a-b).*(a+b-c));
          q = 2 * r ./ R;

        case 3

          d12=p(t(:,2),:)-p(t(:,1),:);
          d13=p(t(:,3),:)-p(t(:,1),:);
          d14=p(t(:,4),:)-p(t(:,1),:);
          d23=p(t(:,3),:)-p(t(:,2),:);
          d24=p(t(:,4),:)-p(t(:,2),:);
          d34=p(t(:,4),:)-p(t(:,3),:);
          v=abs(dot(cross(d12,d13,2),d14,2))/6;
          s1=sqrt(sum(cross(d12,d13,2).^2,2))/2;
          s2=sqrt(sum(cross(d12,d14,2).^2,2))/2;
          s3=sqrt(sum(cross(d13,d14,2).^2,2))/2;
          s4=sqrt(sum(cross(d23,d24,2).^2,2))/2;
          p1=sqrt(sum(d12.^2,2)).*sqrt(sum(d34.^2,2));
          p2=sqrt(sum(d23.^2,2)).*sqrt(sum(d14.^2,2));
          p3=sqrt(sum(d13.^2,2)).*sqrt(sum(d24.^2,2));
          q=216*v.^2./(s1+s2+s3+s4)./sqrt((p1+p2+p3).*(p1+p2-p3).* ...
                                    (p1+p3-p2).*(p2+p3-p1));

        otherwise

          error ( 'SIMPQUAL - Dimension not implemented.' );
    end
%
%  APPROXIMATE FORMULA
%
    case 2

     switch size(p,2)

       case 1

         q = ones ( 1, size(t,2) );

       case 2

         d12 = sum((p(t(:,2),:)-p(t(:,1),:)).^2,2);
         d13 = sum((p(t(:,3),:)-p(t(:,1),:)).^2,2);
         d23 = sum((p(t(:,3),:)-p(t(:,2),:)).^2,2);
         q = 4*sqrt(3)*abs(simpvol(p,t))./(d12+d13+d23);

       case 3

         d12 = sum((p(t(:,2),:)-p(t(:,1),:)).^2,2);
         d13 = sum((p(t(:,3),:)-p(t(:,1),:)).^2,2);
         d14 = sum((p(t(:,4),:)-p(t(:,1),:)).^2,2);
         d23 = sum((p(t(:,3),:)-p(t(:,2),:)).^2,2);
         d24 = sum((p(t(:,4),:)-p(t(:,2),:)).^2,2);
         d34 = sum((p(t(:,4),:)-p(t(:,3),:)).^2,2);
         q = 216*abs(simpvol(p,t))/sqrt(3)./(d12+d13+d14+d23+d24+d34).^(3/2);

       otherwise

         error ( 'SIMPQUAL - Dimension not implemented.' );
    end

  otherwise

    error ( 'SIMPQUAL - Incorrect type.' );

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
%      Copyright (C) 2009-2013 Biomedizinische NMR Forschungs GmbH
%                     http://www.biomednmr.mpg.de
%            Author: Tilman Johannes Sumpf <tsumpf@gwdg.de>
%
%       Distributed under the Boost Software License, Version 1.2.
%          (See accompanying file LICENSE_1_0.txt or copy at
%                 http://www.boost.org/LICENSE_1_0.txt)

classdef asDataClass < handle

    properties (GetAccess = public, SetAccess = private)
        dat         = [];   % the data dataArrayay
    end

    properties (Access = private)
        selection       = [];     % asSelectionClass object containing the valueChanger array

        updFig      = [];   % update figure callback from the main gui

        % allows methods to alter the image array, making it different
        % from the original that might still be in Workspace
        enableDestrFun  = true;

    end

    methods

        function enableDestructiveFunctions(obj, toggle)
            if nargin < 2
                toggle = true;
            else
                if ~isscalar (toggle)
                    warning('asDataClass:invalidArgument','invalid argument\n');
                end
            end
            obj.enableDestrFun = toggle;
        end

        function obj = asDataClass(dataArray, figureUpdateCallback)

            % validate input data
            obj.dat = asDataClass.validateImageArray(dataArray);

            % store figure update callback to local property
            obj.updFig = figureUpdateCallback;

        end

        function linkToSelectionClassObject(obj, selectionClassObject)
            obj.selection = selectionClassObject;
        end

        function fft2SelectedFrames(obj)
            if obj.enableDestrFun
                str = obj.selection.getValue;

                % create a command string from the gathered informations
                command = strcat('obj.dat(',str,') = asDataClass.mrFft(obj.dat(',str,'));');

                % execute command
                eval(command);

                obj.updFig();
            end
        end

        function ifft2SelectedFrames(obj)
            if obj.enableDestrFun
                str = obj.selection.getValue;

                % create a command string from the gathered informations
                command = strcat('obj.dat(',str,') = asDataClass.mrIfft(obj.dat(',str,'));');

                % execute command
                eval(command);

                obj.updFig();
            end
        end

        function fft2All(obj)
            if obj.enableDestrFun
                if numel(obj.dat) > 1e7
                    %                 mbh = waitbar(0,'deriving FFT of all
                    %                 images...','MenuBar','none');
                    mbh = msgbox('deriving FFT of all images...');
                    obj.dat = asDataClass.mrFft(obj.dat);
                    close(mbh);
                else
                    obj.dat = asDataClass.mrFft(obj.dat);
                end
                obj.updFig();
            end
        end

        function ifft2All(obj)
            if obj.enableDestrFun
                if numel(obj.dat) > 1e7
                    mbh = msgbox('deriving iFFT of all images...');
                    obj.dat = asDataClass.mrIfft(obj.dat);
                    close(mbh);
                else
                    obj.dat = asDataClass.mrIfft(obj.dat);
                end
                obj.updFig();
            end
        end

        function fftshift2All(obj)
            if obj.enableDestrFun
                if numel(obj.dat) > 1e7
                    %                 mbh = waitbar(0,'deriving FFT of all
                    %                 images...','MenuBar','none');
                    mbh = msgbox('deriving FFTshift2 of all images...');
                    obj.dat = asDataClass.fftshift2(obj.dat);
                    close(mbh);
                else
                    obj.dat = asDataClass.fftshift2(obj.dat);
                end
                obj.updFig();
            end
        end

        function rot90(obj, k)
            if obj.enableDestrFun
                if nargin < 2
                    k = 1;
                else
                    if k ~= 1 && k ~=-1
                        warning('arrShow:rot90','k can be either -1 or 1');
                        k = 1;
                    end
                end

                si = size(obj.dat);
                noDims = length(si);

                % get original selection
                origSel = obj.selection.getValueAsCell;

                % get colon dims
                colDims = obj.selection.getColonDims;

                if any(colDims == 0)
                    warning('arrShow:rot90','both colon dimensions need to be selected for rot90');
                else
                    colDims = sort(colDims);
                    pOrder = 1 : noDims;  % original panel ordering

                    newOrder = pOrder;
                    newSel = origSel;

                    newOrder(colDims(1)) = pOrder(colDims(2));
                    newOrder(colDims(2)) = pOrder(colDims(1));
                    newSel{colDims(1)} = origSel{colDims(2)};
                    newSel{colDims(2)} = origSel{colDims(1)};

                    obj.dat = permute(obj.dat,newOrder);
                    if k == 1
                        obj.dat = flipdim(obj.dat,colDims(1));
                    else
                        obj.dat = flipdim(obj.dat,colDims(2));
                    end

                    % valueChanger array
                    newDims = size(obj.dat);
                    obj.selection.reInit(newDims, newSel);

                    obj.updFig();
                end
            end
        end

        function flipDim(obj,dim)
            if obj.enableDestrFun
                obj.dat = flipdim(obj.dat,dim);
                obj.updFig();
            end
        end

        function sumSqr(obj,dim)
            if obj.enableDestrFun
                if nargin ==1
                    dim = length(size(obj.dat)); % use the last dimensions
                end
                si = size(obj.dat);
                l = length(si);
                if dim > l
                    fprintf('dimension %d > number of available dimensions (%d)\n',dim, l);
                else
                    obj.dat = sqrt(sum(obj.dat .* conj(obj.dat),dim));

                    % get original selection
                    si(dim) = 1;
                    sel = obj.selection.getValueAsCell;
                    sel{dim} = '1';

                    % update selection class
                    obj.selection.reInit(si, sel);

                    obj.updFig();
                end
            end
        end

        function max(obj,dim)
            obj.maxMin(dim,@max);
        end

        function min(obj,dim)
            obj.maxMin(dim,@min);
        end

        function squeeze(obj)
            if obj.enableDestrFun
                % get original selection
                sel = obj.selection.getValueAsCell;
                si = size(obj.dat);

                if length(sel) > 2
                    % find dims which will be kept alive
                    sd = si ~= 1;

                    obj.dat = squeeze(obj.dat);
                    sel = sel(sd);

                    % avoid dealing with less than 2 dimensions
                    if length(sel) == 1
                        sel = [sel,{'1'}];
                    end

                    obj.selection.reInit( size(obj.dat), sel);

                    obj.updFig();
                else
                    fprintf('squeezing away one of the last 2 dimensions is not implemented yet :-(\n');
                end
            end
        end

        function setDestructiveSelectionString(obj)
            A = obj.dat;

            noDims = length(size(A));
            colonStr = repmat(': , ',[1,noDims]);
            initStr = ['A = A( ',colonStr,';'];
            initStr(end-2) = ')';

            str = mydlg('Enter selection','Set selection string',initStr);
            if isempty(str)
                return;
            end

            try
                eval(str);
            catch err
                disp(err);
                return;
            end

            obj.overwriteImageArray(A);
        end

        function permute(obj,order)
            if obj.enableDestrFun

                % if no reordering vector is given: open permute dialog
                if nargin < 2 || isempty(order)
                    noDims = length(size(obj.dat));
                    prevValue = num2str(1:noDims,'%d,');
                    prevValue(end) = []; % remove last ','
                    newValue = mydlg('Enter selection string','Selection input dlg',prevValue);
                    if ~isempty(newValue)
                        order = str2num(newValue); % need to use str2num instead of str2double as this is not a scalar
                        if (length(order) ~= noDims ||...
                                min(order) ~= 1 ||...
                                max(order) ~= noDims)
                            warning('PermuteDlg:valueCheck','invalid value');
                            return;
                        end
                    else
                        return;
                    end
                end

                % get original selection
                sel = obj.selection.getValueAsCell;

                % permute array and selection
                obj.dat = permute(obj.dat,order);
                sel = sel(order);

                si = size(obj.dat);
                obj.selection.reInit( si, sel);
                obj.updFig();
            end
        end

        function overwriteImageArray(obj, arr)
            if obj.enableDestrFun

                % get original selection
                origSel = obj.selection.getValueAsCell;
                origSi = size(obj.dat);

                % accept new array
                obj.dat = asDataClass.validateImageArray(arr);
                newSi = size(obj.dat);

                % check if dimensions are equal
                if length(newSi) == length(origSi)
                    dimEqual = true;
                    for i = 1 : length(newSi)
                        if(origSi(i) ~= newSi(i))
                            dimEqual = true;
                            break;
                        end
                    end
                else
                    dimEqual = false;
                end

                % create init selection cell array
                if dimEqual
                    sel = origSel;
                else
                    sel = cell(length(newSi),1);
                    sel{1} = ':';
                    sel{2} = ':';
                    for i = 3 : length(newSi)
                        sel{i} = '1';
                    end
                end

                % reinit selection class
                obj.selection.reInit(newSi, sel);

                obj.updFig();
            end

        end
    end

    methods (Static)

        function dataArray = validateImageArray(dataArray)
            if iscell(dataArray)
                dataArray = asDataClass.cell2imageMat(dataArray);
            end

            if ~isnumeric(dataArray)
                warning('asDataClass:validateImageArray','Input dataArrayay seems not to be numeric. Trying to convert it into double...');
                dataArray = double(dataArray);
            end

            si      = size(dataArray);
            if length(si) < 2
                error('asDataClass:validateImageArray','input dataArrayay has to be at least 2 dimensional');
            end

            if issparse(dataArray);
                dataArray = full(dataArray);
            end

            if any(~isnumeric(dataArray(:)))
                warning('asDataClass:validateImageArray','There are invalid entries in the image dataArrayay. Replacing these entries with zeros...');
                dataArray(~isnumeric(dataArray(:))) = 0;
            end
        end

        function arr = cell2imageMat(cellArr)

            fprintf('isolating images from input cell vector...');

            % check if first cell content has at least 2 dimensions
            refSi = size(cellArr{1});
            if length(refSi) >= 2
                refN = prod(refSi);
            else
                error('asDataClass:cell2imageMat','arrays in input cell must be at least 2 dimensional');
            end

            % if all other cells contain arrays with same number of
            % elements, sort them into an image array
            arr = zeros([refN,numel(cellArr)]);
            for i = 1 : numel(cellArr)
                if numel(cellArr{i}) == refN
                    arr(:,i) = cellArr{i}(:);
                else
                    error('asDataClass:cell2imageMat','arrays in input cell have different size');
                end
            end
            si  = [refSi, squeeze(size(cellArr))];
            arr = reshape(arr,si);
            fprintf('  done.\n');
        end

        function out = fftshift2(in)
            out = fftshift(fftshift(in,1),2);
        end

        %------------------------------------------------------------------
        %Change mrFft & mrIfft for MRiLab compatibility <Fang Liu>
        %28-April-2013  change fft2 to fftn
        %16-May-2013    apply different fft & ifft based on input dimension for multi Rx coil recon

%         function out = mrFft(in)
%             si = size(in);
%             a = 1 / (sqrt(si(1)) * sqrt(si(2)));
%             out = asDataClass.fftshift2(fft2(asDataClass.fftshift2(in))) * a;
%
%         end
%
%         function out = mrIfft(in)
%             si = size(in);
%             a = sqrt(si(1)) * sqrt(si(2));
%             out = asDataClass.fftshift2(ifft2(asDataClass.fftshift2(in))) * a;
%         end

        function out = mrFft(in)
            switch ndims(in)
                case 5 % multi echo
                    d = size(in);
                    out = zeros(d);
                    for j = 1: d(5)
                        for i = 1: d(4)
                            out(:,:,:,i,j) = fftshift(fftn(fftshift(in(:,:,:,i,j))));
                        end
                    end
                case 4 % multi Rx coil
                    d = size(in);
                    out = zeros(d);
                    for i = 1: d(4)
                        out(:,:,:,i) = fftshift(fftn(fftshift(in(:,:,:,i))));
                    end
                otherwise % normal
                    out = fftshift(fftn(fftshift(in)));
            end
        end

        function out = mrIfft(in)
           switch ndims(in)
                case 5 % multi echo
                    d = size(in);
                    out = zeros(d);
                    for j = 1: d(5)
                        for i = 1: d(4)
                            out(:,:,:,i,j) = fftshift(ifftn(fftshift(in(:,:,:,i,j))));
                        end
                    end
                case 4 % multi Rx coil
                    d = size(in);
                    out = zeros(d);
                    for i = 1: d(4)
                        out(:,:,:,i) = fftshift(ifftn(fftshift(in(:,:,:,i))));
                    end
                otherwise % normal
                    out = fftshift(ifftn(fftshift(in)));
            end
        end
        %-----------------End----------------------------------------------

    end

    methods (Access = private)
        function maxMin(obj,dim,funPtr)
            if obj.enableDestrFun
                if nargin ==1
                    dim = length(size(obj.dat)); % use the last dimensions
                end
                si = size(obj.dat);
                l = length(si);
                if dim > l
                    fprintf('dimension %d > number of available dimensions (%d)\n',dim, l);
                else
                    obj.dat = funPtr(obj.dat,[],dim);

                    % get original selection
                    si(dim) = 1;
                    sel = obj.selection.getValueAsCell;
                    sel{dim} = '1';

                    % update selection class
                    obj.selection.reInit(si, sel);

                    obj.updFig();
                end
            end
        end
    end
end

author: leoliuf

repo: MRiLab

save_path: github-repos/MATLAB/leoliuf-MRiLab


text:
function test_suite = test_medianLine
%TESTMEDIANLINE  One-line description here, please.
%   output = testMedianLine(input)
%
%   Example
%   testMedianLine
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2009-04-22,    using Matlab 7.7.0.471 (R2008b)
% Copyright 2009 INRA - Cepia Software Platform.
% Licensed under the terms of the LGPL, see the file "license.txt"

test_suite = functiontests(localfunctions);

function testTwoPoints(testCase) %#ok<*DEFNU>
% test with 2 points

p1 = [0 0];
p2 = [10 0];
exp = [5 0 0 10];
line = medianLine(p1, p2);
testCase.assertEqual(exp, line, 'AbsTol', .01);

function testEdge(testCase)
% test with an edge as input

p1 = [0 0];
p2 = [10 0];
exp = [5 0 0 10];
line = medianLine([p1 p2]);
testCase.assertEqual(exp, line, 'AbsTol', .01);

function testTwoPointArrays(testCase) %#ok<*DEFNU>
% test with 2 points

p1 = [0 0; 10 10];
p2 = [10 0;10 20];

exp = [5 0 0 10; 10 15 -10 0];

line = medianLine(p1, p2);
testCase.assertEqual(exp, line, 'AbsTol', .01);

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
%kcpRGBNTSCtoLuvstar 'converts an image from RGB NTSC to L*u*v* '
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros cpRGBNTSCtoLuvstar.pane file
%
% Parameters:
% InputFile: i 'Input ', required: 'First Input data object'
% OutputFile: o 'Output', required: 'Resulting output data object'
%
% Example: o = kcpRGBNTSCtoLuvstar(i, {'i','';'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% cpRGBNTSCtoLuvstar - converts an image from RGB NTSC to L*u*v*
%
%  DESCRIPTION
% call ckfromRGBNTSC with the parameter -luvstar to convert an image RGB NTSC to L*u*v*
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
%
%  RESTRICTIONS
%
%  REFERENCES
% All references for the COLOR toolbox are on the file $COLOR/Readme.html
%
%  COPYRIGHT
% Copyright (C) 1997 Rafael Santos. Khoros (C) Khoral Research, Inc.
%

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

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

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function H = compute_infos(I)
level = 256;
dat = double(I);
p = zeros(1, level);
for i = 1 : size(dat, 1)
    for j = 1 : size(dat, 2)
        temp = dat(i,j);
        p(1, temp+1) = p(1, temp+1) + 1;
    end
end
p = p/(size(dat, 1)*size(dat, 2));
H = 0;
for i = 1 : level
    if p(i) ~= 0
        H = H + p(i)*log2(p(i));
    end
end
H = -H;

author: decouples


text:
function p3 = diff(p1)
%PREAL/DIFF Overloaded DIFF function for class preal.

global useUnitsFlag

if ~(useUnitsFlag) % If physunits is disabled...
    p3=diff(double(p1)); % ... treat as double.
    return
end

if isscalar(p1)
    p3=preal([]);
    return
end
if isvector(p1)
    p3=preal(ones(size(p1)));
    p3(end)=[];
    for k=1:numel(p3)
        p3(k)=p1(k+1)-p1(k);
    end
else
    error('preal/diff is only defined for vectors')
end

author: Sable

repo: mcbench-benchmarks


text:
% VARGPLVM_INIT Initialise the global options structure for a demo that runs the
% variational GP-LVM.
% COPYRIGHT: Andreas C. Damianou, 2012
% VARGPLVM

% Initialise options. If the field name of 'defaults' already exists as a
% variable, the globalOpt will take this value, otherwise the default one.

defaults.experimentNo = 404;
defaults.itNo =2000;
defaults.indPoints = 49;
defaults.latentDim = 40;
% Set to 1 to use dynamics or to 0 to use the standard var-GPLVM
defaults.dynUsed = 1;
defaults.fixedBetaIters = 0;
% Set to 1 to tie the inducing points with the latent vars. X
defaults.fixInd = 0;
defaults.dynamicKern = {'rbf', 'white', 'bias'};
defaults.mappingKern = 'rbfardjit'; % {'rbfard2', 'bias', 'white'};
defaults.reconstrIters = 1000;
% Leave empty {} for no dynamics.
% Other options are:
% 'time': temporal dynamics, based on input t
% 'labels': provided labels
% 'data': autoencoder
defaults.dynamicsConstrainType = {};
% 0.1 gives around 0.5 init.covars. 1.3 biases towards 0.
defaults.vardistCovarsMult=1.3;
defaults.dataSetSplit = 'everyTwo';
defaults.blockSize = 8;
% 720x1280
defaults.dataSetName = [];  % For vargplvmLoadData
defaults.dataSetField = []; % For vargplvmLoadData
defaults.testReoptimise = 1;
defaults.invWidthMultDyn = 100;
defaults.invWidthMult = 5;

% The values of this field are either strings, so that [@initX 'Embed']
% is called, or it can be a matrix of an a priori computed latent space.
% Other options for embedding:
% 'pca','isomap2','vargplvm','fgplvm','outputs'. The last requires that
% Q==D and initialises X=Y where the data is scaled so that it's 0 mean
% 1 variance
defaults.initX ='ppca';
defaults.regularizeMeans = 0;
defaults.initVardistIters = 0;
defaults.enableParallelism = false;
defaults.DgtN = 1;
defaults.doPredictions = false;
defaults.initSNR = 100;
defaults.scale2var1 = 0;
defaults.initVardistIters = 50;
defaults.diaryFile = [];
defaults.doGradChek = false;
% By default do not learn the variance of the dynamic kernel (this is
% basically applied to the matern class of kernels, hoping that the
% lengthscale will compensate for fixing this value)
defaults.learnDynKernelVariance = false;

% This allows to rewrite the standard form of the bound F + KL as
% 2*((1-fw)*F + fw*KL), where fw is the KLweight. This means that when fw
% is 0.5 there's no difference, otherwise the KL term can be more or less
% emphasized
defaults.KLweight = 0.5;

defaults.optimiser = 'scg2';

fnames = fieldnames(defaults);
 for i=1:length(fnames)
    if ~exist(fnames{i})
        globalOpt.(fnames{i}) = defaults.(fnames{i});
    else
        globalOpt.(fnames{i}) = eval(fnames{i});
    end
 end

 clear('defaults', 'fnames','i');

author: SheffieldML

repo: vargplvm


text:
function f = sum( f, dim )
%SUM   Definite Integration of a DISKFUN.
%   G = sum(F,DIM) where DIM is 1 or 2 integrates only over theta
%   (angular direction) or r (radial direction) respectively,
%   and returns as its output a chebfun in the remaining variable.
%
%   G = sum(F) is the same as sum(F,1)
%
% See also SUM2.

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

% Empty check:
if ( isempty( f ) )
    f = [];
    return;
end

% Default to radial direction:
if ( nargin == 1 )
    dim = 1;
end

% Get the low rank representation for f.
[cols, D, rows] = cdr(f);
dom = f.domain;
%restrict cols to match domain

if ( dim == 1 )
    % Integrate over r. Need to include the measure on the disk.
    r = chebfun('x');
    cols = r.*cols;
    cols = restrict(cols, [0 1]);
    f = rows * ( sum(cols) * D ).';
    if ( isa(f, 'chebfun') )
        f = simplify( f, [], 'globaltol' );
    else
        % f = double
        f = chebfun(f, dom(1:2)).';
    end
elseif ( dim == 2 )
    f = cols * ( D * sum( rows ).' );
    if  ( isa(f, 'chebfun') )
        f = simplify( f.', [], 'globaltol' );
    else
        f = chebfun( f, dom(3:4) );
    end
else
    error('CHEBFUN:DISKFUN:sum:unknown', ...
          'Undefined function ''sum'' for that dimension');
end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
% Test file for @deltafun/real.m

function pass = test_real(pref)

if (nargin < 1)
    pref = chebfunpref();
end
%%
d = deltafun();
pass(1) = isempty(real(d));

f = bndfun(@sin);
d = deltafun(f, struct('deltaMag', 1i, 'deltaLoc', 0));
pass(2) = ~isa(real(d), 'deltafun');
h = real(1i*d);
pass(3) = isa(h, 'deltafun');
pass(4) = h.deltaMag == -1;
%%

f = fun.constructor(@(x) exp(x), struct('domain', [-1, 1]));
A = rand(4,4);
B = rand(4,4);
d = deltafun(f, struct('deltaMag', A + 1i*B, 'deltaLoc', [-.5, -.25, 0, 1]));
h = real(d);
pass(5) = all(all(h.deltaMag == A));
end


text:
% eeg_global() - declare global EEGLAB variables. These variables are
%                used only as global by the main function eeglab(),
%                the function pop_rejmenu() and the history eegh() function.
%
% Global variables:
%  EEG        - structure containing the current dataset
%  ALLEEG     - array of structures containing all the loaded datasets
%  CURRENTSET - index of the current dataset in the ALLEEG array
%  LASTCOM    - most recent command run by EEGLAB
%  ALLCOM     - cell array containing the EEGLAB session command history
%               See the history (h) function for more details.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab()

% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% 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

% global variables
% ----------------
global EEG;		% current dataset
global ALLEEG;		% all datasets
global CURRENTSET;	% current set index

%global W_MAIN;		% main window
%global H_MAIN;		% main window
%global EEGMENU;		% main menu
global ALLCOM;		% all commands (history)
global LASTCOM;		% last command
global STUDY;
global CURRENTSTUDY;

author: PatternRecognition

repo: OpenBMI


text:
function [vM, vM_]=cluster200x(fTaumin, fTaumax, fXk, fXmeff, fP1, fRfact, fMerr, fZerr,mCat)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Example: [vMain, vClus]=cluster200x(2880,14400,0.5,3.0,0.99,10,0,0,a)
% Author: van Stiphout, Thomas
% Email: vanstiphout@sed.ethz.ch
% Created: 14. Feb. 2007
% Changed: -
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Variables:
% mCat              Catalog to be declustered
% iYr1                Starting year (read from mCat)
% iYr2                Ending year (read from mCat)
% fXmeff            Magnitude cutoff
% fRfact             rfact
% fTau0              Tau0 (is equal fTaumin)
% fTaumin          Taumin
% fTaumax         Taumax
% fP1                  P1
% fXk                  xk
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% prevent year 2000 problem / transition
fYrStart_=floor(min(mCat(:,3)));
mCatTime_=mCat(:,3);
mCat(:,3)=mCat(:,3)-fYrStart_;
% prepare variables
fTaumin=fTaumin*24*60;
fTau0=fTaumin;
fTaumax=fTaumax*24*60;
sYr1=num2str(floor(min(mCat(:,3))));
sYr2=num2str(ceil(max(mCat(:,3))));
% sYr1=sYr1(3:4);
% sYr2=sYr2(3:4);

% does catalog contain 12 columns?
if (size(mCat,2)<12)
    mTmp=nan(size(mCat,1),(12-size(mCat,2)));
    mCat=[mCat mTmp];
end
!rm tmp cluster.* input.cmn tmp v.dat CA.hypo71
% export to readalbe format for tmp
export2hypo71(mCat,'tmp');
% remove NaN from exported catalog
unix(['sed ''s/NaN/   /'' tmp > CA.hypo71']);
% write input file (input.cmn)
infile=fopen('input.cmn','w');
fprintf(infile,'CA.hypo71\n4\n%2s\n%2s\n%3.1f\n%06.3f\n%08.3f\n%010.2f\n%010.2f\n%05.2f\n%05.2f',...
    sYr1,sYr2,fXmeff,fRfact,fTau0,fTaumin,fTaumax,fP1,fXk);
fclose(infile);
% run declustering algorithm of f reasenberg cluster200x
unix('~/zmap/src/thomas/decluster/reasen/cluster200x > tmp');
% extract vector with 1 and 0's of events in declustered catalog
unix(['awk -f ~/zmap/src/thomas/decluster/reasen/clu2list.awk cluster.ano > v.dat ' ]);
% import vector
vM_=load('v.dat');
vSelN0=(vM_==0);
vSelNc=zeros(size(vSelN0));

for i=1:max(vM_)
    vPos1=find(vM_==i);
    if ~isempty(vPos1)
        vPos2=find(mCat(vPos1,6)==max(mCat(vPos1,6)));
        if (vPos2==1)
            vPos3=vPos1(vPos2);
        else
            vPos3=vPos1(1);
        end
        vSelNc(vPos3)=1;
    end
    clear vPos1 vPos2 vPos3
end

vM=(logical(vSelN0) | logical(vSelNc));
% % clean up
% !rm cluster.*

author: CelsoReyes


text:
%
% Usage:   gstruct =mexGroupStructOfString(s)
%
% Name: mexGroupStructOfString
%
% Description: decode a multi-line string describing "simply" the structure of groups
%    of variables needed by mexProximalGraph, mexProximalTree, mexFistaGraph,
%    mexFistaTree and mexStructTrainDL and builds the corresponding group structure.
%    Each line describes a group of variables as a node of a tree.
%    It has up to 4 fields separated by spaces:
%        node-id node-weight [variables-list] -> children-list
%    Let's define Ng = number of groups, and Nv = number of variables.
%    node-id must be in the range (0 - Ng-1), and there must be Ng nodes
%    weight is a float
%    variables-list : a space separated list of integers, maybe empty,
%         but '[' and '] must be present. Numbers in the range (0 - Nv-1)
%    children-list : a space separated list of node-id's
%        If the list is empty, '->' may be omitted.
%    The data must obey some rules :
%        - A group contains the variables of the corresponding node and of the whole subtree.
%        - Variables attached to a node are those that are not int the subtree.
%        - If the data destination is a Graph, there may be several independant trees,
%          and a varibale may appear in several trees.
%    If the destination is a Tree, there must be only one tree, the root node
%    must have id == 0 and each variable must appear only once.
%
% Inputs: s:  the multi-lines string
%
% Output: groups: cell array, one element for each node
%                an element is itsel a 4 elements cell array:
%	          nodeid (int >= 0), weight (double), array of vars of the node,
%                array of children (nodeid's)
%
% Author: Jean-Paul CHIEZE, 2012

author: tiepvupsu

repo: DICTOL

save_path: github-repos/MATLAB/tiepvupsu-DICTOL


text:
function gX = ratquadKernGradX(kern, X, X2)

% RATQUADKERNGRADX Gradient of RATQUAD kernel with respect to input locations.
% FORMAT
% DESC computes the gradident of the rational quadratic
% kernel with respect to the input positions where both the row
% positions and column positions are provided separately.
% ARG kern : kernel structure for which gradients are being
% computed.
% ARG x1 : row locations against which gradients are being computed.
% ARG x2 : column locations against which gradients are being computed.
% RETURN g : the returned gradients. The gradients are returned in
% a matrix which is numData2 x numInputs x numData1. Where numData1 is
% the number of data points in X1, numData2 is the number of data
% points in X2 and numInputs is the number of input
% dimensions in X.
%
% SEEALSO ratquadKernParamInit, kernGradX, ratquadKernDiagGradX
%
% COPYRIGHT : Neil D. Lawrence, 2006

% KERN

gX = zeros(size(X2, 1), size(X2, 2), size(X, 1));
for i = 1:size(X, 1);
  gX(:, :, i) = ratquadKernGradXpoint(kern, X(i, :), X2);
end

function gX = ratquadKernGradXpoint(kern, x, X2)

% RATQUADKERNGRADXPOINT Gradient with respect to one point of x.

gX = zeros(size(X2));
n2 = dist2(X2, x);
wi2 = (.5/(kern.lengthScale*kern.lengthScale*kern.alpha));
ratquadPart = kern.variance*(1+n2*wi2).^-(kern.alpha+1)/(kern.lengthScale*kern.lengthScale);
for i = 1:size(x, 2)
  gX(:, i) =(X2(:, i) - x(i)).*ratquadPart;
end

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function [SurfCov,Dis,CylVol,dis] = surface_coverage(P,Axis,Point,nl,ns,Dmin,Dmax)

% ---------------------------------------------------------------------
% SURFACE_COVERAGE.M   Computes point surface coverage measure
%
% Version       1.1.0
% Last update   7 Oct 2021
%
% Copyright (C) 2017-2021 Pasi Raumonen
% ---------------------------------------------------------------------
% Inputs:
% Axis      Axis direction (1 x 3)
% Point     Starting point of the cylinder (1 x 3)
% nl        Number of layers in the axis direction used for to partition
%               the cylinder surface into layer/sectors
% ns        Number of sectors used to partition the cylinder surface into
%               layer/sectors
% Dmin      (Optional) Minimum point distance from the axis to be included
%               into SurfCov calculations
% Dmax      (Optional) Maximum point distance from the axis to be included
%               into SurfCov calculations
%
% Output:
% SurfCov   Number between 0 and 1 descring how big portion of the cylinder
%               surface is covered with points
% Dis       (Optional) Mean distances of the distances of the layer/sectors
% CylVol    (Optional) Volume of the cylinder estimated by the mean
%               distances of the layer/sectors as cylindrical sections
% dis       (Optional) Same as "Dis" but empty cells are interpolated
% ---------------------------------------------------------------------
% Computes surface coverage (number between 0 and 1) of points on cylinder
% surface defined by "Axis" and "Point".

% Changes from version 1.0.0 to 1.1.0, 7 Oct 2021:
% 1) Added two possible inputs, minimum and maximum distance,
%    Dmin and Dmax, which can be used to filter out points for the surface
%    coverage calculations
% 2) Computes the SurfCov estimate with four baseline directions used in
%    the sector determination and selects the largest value
% 3) Smalle changes to speed up computations

%% Compute the distances and heights of the points
[d,V,h] = distances_to_line(P,Axis,Point);
h = h-min(h);
Len = max(h);

%% (Optional) Filter out points based on the distance to the axis
if nargin >= 6
  Keep = d > Dmin;
  if nargin == 7
    Keep = Keep & d < Dmax;
  end
  V = V(Keep,:);
  h = h(Keep);
end

%% Compute SurfCov
% from 4 different baseline directions to determine the angles and select
% the maximum value
V0 = V;
[U,W] = orthonormal_vectors(Axis); % First planar axes
R = rotation_matrix(Axis,2*pi/ns/4); % Rotation matrix to rotate the axes
SurfCov = zeros(1,4);
for i = 1:4
  %% Rotate the axes
  if i > 1
    U = R*U;
    W = R*W;
  end

  %% Compute the angles (sectors) of the points
  V = V0*[U W];
  ang = atan2(V(:,2),V(:,1))+pi;

  %% Compute lexicographic order (sector,layer) of every point
  Layer = ceil(h/Len*nl);
  Layer(Layer <= 0) = 1;
  Layer(Layer > nl) = nl;
  Sector = ceil(ang/2/pi*ns);
  Sector(Sector <= 0) = 1;
  LexOrd = [Layer Sector-1]*[1 nl]';

  %% Compute SurfCov
  Cov = zeros(nl,ns);
  Cov(LexOrd) = 1;
  SurfCov(i) = nnz(Cov)/nl/ns;
end
SurfCov = max(SurfCov);

%% Compute volume estimate
if nargout > 1
  % Sort according to increasing lexicographic order
  [LexOrd,SortOrd] = sort(LexOrd);
  d = d(SortOrd);

  % Compute mean distance of the sector-layer intersections
  Dis = zeros(nl,ns); % mean distances
  np = length(LexOrd);     % number of points
  p = 1;
  while p <= np
    t = 1;
    while (p+t <= np) && (LexOrd(p) == LexOrd(p+t))
      t = t+1;
    end
    Dis(LexOrd(p)) = average(d(p:p+t-1));
    p = p+t;
  end

  if nargout > 2
    % Interpolate missing distances
    D = Dis;
    dis = Dis;
    Dinv = D((nl:-1:1)',:);
    D = [Dinv Dinv Dinv; D D D; Dinv Dinv Dinv];
    Zero = Dis == 0;
    RadMean = average(Dis(Dis > 0));
    for i = 1:nl
      for j = 1:ns
        if Zero(i,j)
          if nnz(D(i+nl-1:i+nl+1,j+ns-1:j+ns+1)) > 1
            d = D(i+nl-1:i+nl+1,j+ns-1:j+ns+1);
            dis(i,j) = average(d(d > 0));
          elseif nnz(D(i+nl-2:i+nl+2,j+ns-2:j+ns+2)) > 1
            d = D(i+nl-2:i+nl+2,j+ns-2:j+ns+2);
            dis(i,j) = average(d(d > 0));
          elseif nnz(D(i+nl-3:i+nl+3,j+ns-3:j+ns+3)) > 1
            d = D(i+nl-3:i+nl+3,j+ns-3:j+ns+3);
            dis(i,j) = average(d(d > 0));
          else
            dis(i,j) = RadMean;
          end
        end
      end
    end
    % Compute the volume estimate
    r = dis(:);
    CylVol = 1000*pi*sum(r.^2)/ns*Len/nl;
  end
end

author: InverseTampere

repo: TreeQSM


text:
function cvx_optpnt = exponential( sx )

%EXPONENTIAL   Exponential cone.
%   EXPONENTIAL, called with no arguments, creates three scalar variables X,
%   Y, and Z and constraints them to lie in an exponetial cone. That is,
%   given the declaration
%       variables x y z
%       {x,y,z} == exp_cone
%   constraints the variables to satisfy
%       y*exp(x/y) <= z
%       y > 0
%   The inequality form does not obey the disciplined convex programming
%   ruleset, but a function EXP_P has been created to represent this
%   computation; so the set declaration above is equivalent to
%       EXP_P(X,Y) <= Z
%   EXP_CONE(SX), where SX is a size vector, creates three array variables
%   X, Y, and Z, each of size SX, which are constrained elementwise to
%   satisfy EXP_P(X,Y) <= Z. If SX is empty, then SX=[1,1] is assumed.

cvx_expert_check( 'exponential' );
error( nargchk( 0, 1, nargin ) );

%
% Check size vector
%

if nargin == 0 || isempty( sx ),
    sx = [1,1]; %#ok
else
    [ temp, sx ] = cvx_check_dimlist( sx, true ); %#ok
    if ~temp,
        error( 'First argument must be a dimension vector.' );
    end
end

%
% Build the cone
%

cvx_begin_set
    variables x( sx ) y( sx ) z( sx )
    [ tx, dummy ] = find( cvx_basis( x ) ); %#ok
    [ ty, dummy ] = find( cvx_basis( y ) ); %#ok
    [ tz, dummy ] = find( cvx_basis( z ) ); %#ok
    newnonl( cvx_problem, 'exponential', [ tx(:)' ; ty(:)' ; tz(:)' ] );
cvx_end_set

cvx_optpnt = cvxtuple( struct( 'x', x, 'y', y, 'z', z ) );

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.

repo: REST


text:
clear all, close all, clc
A = imread('../../CH01_SVD/DATA/dog.jpg');
B = rgb2gray(A);

%% Wavelet Compression
[C,S] = wavedec2(B,4,'db1');
Csort = sort(abs(C(:))); % Sort by magnitude

for keep =  [.1 .05 .01 .005]
    thresh = Csort(floor((1-keep)*length(Csort)));
    ind = abs(C)>thresh;
    Cfilt = C.*ind;      % Threshold small indices

    % Plot Reconstruction
    Arecon=uint8(waverec2(Cfilt,S,'db1'));
    figure, imagesc(uint8(Arecon))
end

author: dynamicslab


text:
% Copyright (C) 2017-2018 Titus Cieslewski, RPG, University of Zurich,
%   Switzerland
%   You can contact the author at <titus at ifi dot uzh dot ch>
% Copyright (C) 2017-2018 Siddharth Choudhary, College of Computing,
%   Georgia Institute of Technology, Atlanta, GA, USA
% Copyright (C) 2017-2018 Davide Scaramuzza, RPG, University of Zurich,
%   Switzerland
%
% This file is part of dslam_open.
%
% dslam_open 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.
%
% dslam_open 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 dslam_open. If not, see <http://www.gnu.org/licenses/>.

function result = areMatchesConsistent(all_robot_data, query_robot, ...
    match_a, match_b, position_tolerance)
% Basically make sure that
% T_M1_Q1 * T_Q1_Q2 is similar to T_M1_M2 * T_M2_Q2, i.e.
% that they are within tolerance.
T_M1_Q1 = match_a.match.Sim_M_Q;
T_M2_Q2 = match_b.match.Sim_M_Q;
% T_Q1_Q2
T_O_Q1 = all_robot_data{query_robot}.Sim_O_C{match_a.frame_i};
T_O_Q2 = all_robot_data{query_robot}.Sim_O_C{match_b.frame_i};
T_Q1_Q2 = tInv(T_O_Q1) * T_O_Q2;
% T_M1_M2
match_robot = match_a.match.robot_i;
assert(match_robot == match_b.match.robot_i);
T_O_M1 = all_robot_data{match_robot}.Sim_O_C{match_a.match.frame_i};
T_O_M2 = all_robot_data{match_robot}.Sim_O_C{match_b.match.frame_i};
T_M1_M2 = tInv(T_O_M1) * T_O_M2;

T_M1_Q2_1 = T_M1_Q1 * T_Q1_Q2;
T_M1_Q2_2 = T_M1_M2 * T_M2_Q2;

error = tInv(T_M1_Q2_1) * T_M1_Q2_2;

result = norm(error(1:3, 4)) < position_tolerance;

end

author: uzh-rpg


text:
function appdata = sliceomaticsetdata(d,xmesh,ymesh,zmesh)
% SLICEOMATICSETDATA(rawdata) - Create the data used for
% sliceomatic in the appdata D.

% Check variables
error(nargchk(1,4,nargin))

% Simplify the isonormals
  disp('Smoothing for IsoNormals...');
  d.smooth=smooth3(d.data);  % ,'box',5);
  d.reducenumbers=[floor(size(d.data,2)/20)...
          floor(size(d.data,1)/20)...
          floor(size(d.data,3)/20) ];
  d.reducenumbers(d.reducenumbers==0)=1;

  if nargin == 4
      % Reorder vectors: make them horizontal (prepare to flipdim)
      if size(xmesh,1)>size(xmesh,2)
          xmesh=xmesh';
      end
      if size(ymesh,1)>size(ymesh,2)
          ymesh=ymesh';
      end
      if size(zmesh,1)>size(zmesh,2)
          zmesh=zmesh';
      end
      % Set axis orientation
      xdir='normal';
      ydir='normal';
      zdir='normal';
      if issorted(xmesh)~=1
          xmesh=flipdim(xmesh,2);
          xdir='reverse';
          d.xlim = [xmesh(1) xmesh(end)];
          xmesh=flipdim(xmesh,2);
      else
          d.xlim = [xmesh(1) xmesh(end)];
      end
      if issorted(ymesh)~=1
          ymesh=flipdim(ymesh,2);
          ydir='reverse';
          d.ylim = [ymesh(1) ymesh(end)];
          ymesh=flipdim(ymesh,2);
      else
          d.ylim = [ymesh(1) ymesh(end)];
      end
      % This should not be the case for medical images
      if issorted(zmesh)~=1
          zmesh=flipdim(zmesh,2);
          zdir='reverse';
          d.zlim = [zmesh(1) zmesh(end)];
          zmesh=flipdim(zmesh,2);
      else
          d.zlim = [zmesh(1) zmesh(end)];
      end

      % Vol vis suite takes numbers in X/Y form.
      ly = 1:d.reducenumbers(1):size(d.data,2);
      lx = 1:d.reducenumbers(2):size(d.data,1);
      lz = 1:d.reducenumbers(3):size(d.data,3);

      for i = 1:length(ly)
          ly(i) = xmesh(ly(i));
      end
      for i = 1:length(lx)
          lx(i) = ymesh(lx(i));
      end
      for i = 1:length(lz)
          lz(i) = zmesh(lz(i));
      end

      d.reducelims={ ly lx lz };
      disp('Generating reduction volume...');
      d.reduce= reducevolume(d.data,d.reducenumbers);
      d.reducesmooth=smooth3(d.reduce,'box',5);
      % Set axis
      %d.xlim = [xmesh(1) xmesh(end)];
      %d.ylim = [ymesh(1) ymesh(end)];
      %d.zlim = [zmesh(1) zmesh(end)];
      d.xmesh = xmesh;
      d.ymesh = ymesh;
      d.zmesh = zmesh;
        d.xdir = xdir;
        d.ydir = ydir;
        d.zdir = zdir;

  else
        % Vol vis suite takes numbers in X/Y form.
        ly = 1:d.reducenumbers(1):size(d.data,2);
        lx = 1:d.reducenumbers(2):size(d.data,1);
        lz = 1:d.reducenumbers(3):size(d.data,3);

        d.reducelims={ ly lx lz };
        disp('Generating reduction volume...');
        d.reduce= reducevolume(d.data,d.reducenumbers);
        d.reducesmooth=smooth3(d.reduce,'box',5);

        d.xlim = [1 size(d.data,2)];
        d.ylim = [1 size(d.data,1)];
        d.zlim = [1 size(d.data,3)];
        d.xmesh = nan;
        d.ymesh = nan;
        d.zmesh = nan;
        d.xdir = 'normal';
        d.ydir = 'normal';
        d.zdir = 'normal';
    end

  appdata = d;

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function [ bad_idx ] = prepLBPconf( config, options, type, annotation_struct, images_fname, gt_fname )
%PREPLBPCONF Prepares configuration for LBP features function call.
%   Detailed explanation goes here
%
% INPUT:
%   config       ...     structure config (see experiment02.m)
%   options      ...     structure options (bw, bw_margin, components, M, order, ...)
%   type         ...     string with one of ['TRN', 'TST', 'VAL'] value
%   datapath     ...     path to dataset (TRN, VAL, TST)
%   images_fname ...     full path filename where matrix with images will be stored
%   gt_fname     ...     full path filename where GT will be stored
%
% 09-08-10 Michal Uricar
% 12-07-11 Michal Uricar, corners dataset modification

    bad_idx = [];

    if (~strcmp(type, 'TRN') && ~strcmp(type, 'VAL') && ~strcmp(type, 'TST'))
        error('??? Invalid type of dataset. Must be one of [''TRN'', ''VAL'', ''TST'']');
    end;

    fprintf(['Prepare ' type ' images...\n']);

%     load(datapath);
    switch (config.nImages)
        case 'all'
            nImages = annotation_struct.N;
        case 'half'
            nImages = round(annotation_struct.N/2);
        otherwise
            nImages = str2num(config.nImages);
    end;

    gt = cell(nImages, 1);

    fprintf([type ': Creating array of images...\n']);
    imSize = [options.bw(2), options.bw(1)];
    Images = uint8(zeros(options.bw(1)*options.bw(2), nImages));
    for i = 1 : nImages
        [I, Annotation] = getImageFrame(options, i, annotation_struct);

        if (isempty(Annotation))
            bad_idx = [bad_idx i];
            continue;
        end;

        Points = prepareS0gt(Annotation.P, options);    % transform nose to the center of face
        Points = Points(:, options.comselect);          % extract relevant points only (name list in options.compnames)
        Points(:, options.M) = Annotation.P(:, 10);     % copy back original nose position

        fprintf([type ': %.2f%% Processing image %s.\n'], i*100/nImages, Annotation.image.filename);

        Images(:, i) = I(:);
        gt{i} = Points;
        %gt{i} = TestPoints;
    end;

    %% Save array of Images
    fprintf([ type ': Saving array of images to file %s...\n'], images_fname);
    save(images_fname, 'Images', 'imSize');
    fprintf([ type ': Saving ground truth points to file %s...\n'], gt_fname);
    save(gt_fname, 'gt');
end

author: uricamic

repo: flandmark

save_path: github-repos/MATLAB/uricamic-flandmark


text:
% AstarMOO A*-MOO navigation class
%
% A concrete subclass of the Navigation class that implements the A*
% navigation algorithm for multiobjective optimization (MOO) - i.e.
% optimizes over several objectives/criteria.
%
% Methods:
%     plan              Compute the cost map given a goal and map
%     path              Compute a path to the goal
%     visualize         Display the obstacle map (deprecated)
%     plot              Display the obstacle map
%     costmap_modify    Modify the costmap
%     costmap_get       Return the current costmap
%     costmap_set       Set the current costmap
%     distancemap_get   Set the current distance map
%     heuristic_get     Get the current heuristic map
%     display           Print the parameters in human readable form
%     char              Convert to string
%
% Properties:
% TBD
%
% Example::
%
%         load map1           % load map
%         goal = [50;30];
%         start = [20;10];
%         as = AstarMOO(map);    % create Navigation object
%         as.plan(goal,2);       % setup costmap for specified goal
%         as.path(start);        % plan solution path star-goal, animate
%         P = as.path(start);    % plan solution path star-goal, return path
%
% Example 2:
%         goal = [100;100];
%         start = [1;1];
%         as = AstarMOO(0);   % create Navigation object with random occupancy grid
%         as.addCost(1,L);    % add 1st add'l cost layer L
%         as.plan(goal,3);    % setup costmap for specified goal
%         as.path(start);     % plan solution path start-goal, animate
%         P = as.path(start);    % plan solution path start-goal, return path
%
% Notes::
% - Obstacles are represented by Inf in the costmap.
%
% References::
% - A Pareto Optimal D* Search Algorithm for Multiobjective Path Planning, A. Lavin.
% - A Pareto Front-Based Multiobjective Path Planning Algorithm, A. Lavin.
% - Robotics, Vision & Control, Sec 5.2.2, Peter Corke, Springer, 2011.
%
% Author::
% Alexander Lavin
%
% See also Navigation, Astar, AstarPO.

% Copyright (C) 1993-2015, by Peter I. Corke, Alexander Lavin
%
% 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
%
% The RTB implementation of this algorithm is done by Alexander Lavin.
% http://alexanderlavin.com

% Implementation notes:
%
% All the state is kept in the structure called a
% X is an index into the array of states.
% state pointers are kept as matlab array index rather than row,col format

classdef AstarMOO < Navigation

    properties (SetAccess=private, GetAccess=private)

        % essential world info
        costmap   % world cost map: obstacle = Inf
        G         % index of goal point
        N         % number of objectives

        % info kept per cell (state):
        b            % backpointer (0 means not set)
        t            % tag: NEW OPEN CLOSED

        cost_g       % path distance summation
        cost_h       % path heuristic (state to goal) cost
        cost_01      % add'l cost layer 01 (unused)
        cost_02      % add'l cost layer 02 (unused)
        cost_03      % add'l cost layer 03 (unused)
                     % add more cost layers if needed...

        priority
        tie

        % list of open states: 2xN matrix
        %   each open point is a column, row 1 = index of cell, row 2 = k
        openlist
        niter

        changed

        openlist_maxlen     % keep track of maximum length
        quiet

        % tag state values
        NEW = 0;
        OPEN = 1;
        CLOSED = 2;
    end

    methods % start of public methods
        % AstarMOO class constructor:
        function as = AstarMOO(world, varargin)
            %AstarMOO.AstarMOO A*-MOO constructor
            %
            % AS = AstarMOO(MAP, OPTIONS) is a A* navigation object, and MAP is an
            % occupancy grid, a representation of a planar world as a
            % matrix whose elements are 0 (free space) or 1 (occupied).
            % The occupancy grid is coverted to a costmap with a unit cost
            % for traversing a cell.
            %
            % Options::
            % 'goal',G      Specify the goal point (2x1)
            % 'metric',M    Specify the distance metric as 'euclidean' (default)
            %               or 'cityblock'.
            % 'inflate',K   Inflate all obstacles by K cells.
            % 'quiet'       Don't display the progress spinner
            %
            % Other options are supported by the Navigation superclass.
            %
            % Notes::
            % - If MAP == 0 a random map is created.
            %
            % See also Navigation.Navigation.

            % invoke the superclass constructor
            as = as@Navigation(world, varargin{:}); % includes the occgrid

            % options
            opt.quiet = false;
            opt = tb_optparse(opt, varargin);
            as.quiet = opt.quiet;

            as.occgrid2costmap(as.occgrid);

            % initialize the A* state variables
            as.reset();
            if ~isempty(as.goal)
                as.goal_change();
            end
            as.changed = false;
        end

        function reset(as)
            %AstarMOO.reset Reset the planner
            %
            % AS.reset() resets the A* planner.  The next instantiation
            % of AS.plan() will perform a global replan.

            % build the matrices required to hold the state of each cell for A*
            as.b = zeros(size(as.occgrid), 'uint32');     % backpointers
            as.t = zeros(size(as.occgrid), 'uint8');      % tags, all NEW=0
            as.cost_g = Inf*ones(size(as.costmap));       % path cost estimate
            as.openlist = zeros(2,0);                     % the open list, one column per point

            as.openlist_maxlen = -Inf;
        end

        %AstarMOO.goal_change Changes to costlayers due to new goal
        %position
        function goal_change(as)

            if isempty(as.b)
                return;
            end
            goal = as.goal;

            % keep goal in index rather than row,col format
            as.G = sub2ind(size(as.occgrid), goal(2), goal(1));
            as.INSERT(as.G, as.projectCost(as.G), 'goalset');
            as.cost_g(as.G) = 0;

            % new goal changes cost layers:
            as.calcHeuristic(as.occgrid, as.goal);
        end

        function s = char(as)
            %AstarMOO.char Convert navigation object to string
            %
            % AS.char() is a string representing the state of the Astar
            % object in human-readable form.
            %
            % See also AstarMOO.display, Navigation.char.

            % most of the work is done by the superclass
            s = char@Navigation(as);
        end

        function plot(as, varargin)
            %AstarMOO.plot Visualize navigation environment
            %
            % AS.plot() displays the occupancy grid and the goal distance
            % in a new figure.  The goal distance is shown by intensity which
            % increases with distance from the goal.  Obstacles are overlaid
            % and shown in red.
            %
            % AS.plot(P) as above but also overlays a path given by the set
            % of points P (Mx2).
            %
            % See also Navigation.plot.

            plot@Navigation(as, 'distance', as.cost_h, varargin{:});
        end

       % invoked by Navigation.step
        function n = next(as, current)
            % Backpropagate from goal to start
            % Return [col;row] of previous step
            if as.changed
                error('Cost map has changed, replan');
            end
            X = sub2ind(size(as.occgrid), current(2), current(1));
            X = as.b(X); % set X as the backpointer of X
            if X == 0
                n = []; % goal (no further backpointer)
            else
                [r,c] = ind2sub(size(as.costmap), X);
                n = [c;r];
            end
        end

        function plan(as, goal, N)
            %AstarMOO.plan Prep the grid for planning.
            %
            % AS.plan() updates AS with a costmap of distance to the
            % goal from every non-obstacle point in the map.  The goal is
            % as specified to the constructor.
            %
            % Inputs:
            %   goal: goal state coordinates
            %   N: number of optimization objectives; standard A* is 2
            %   (i.e. distance and heuristic)

            as.N = N; % number of optimization objectives
            as.openlist = zeros(as.N+1,0);

            % Setup cost layers. If a
            % cost layer is goal-dependent, it's setup function needs to
            % also be called in AS.goal_change(). If more cost layers are
            % needed, add similar to AS.cost_01.

            % initializations first:
            as.cost_g = zeros(size(as.occgrid));
            as.cost_h = zeros(size(as.occgrid)); % filled after setting goal below
            % if add'l costs haven't been added with addCost()
            if isempty(as.cost_01)
                as.cost_01 = zeros(size(as.occgrid));
            end
            if isempty(as.cost_02)
                as.cost_02 = zeros(size(as.occgrid));
            end
            if isempty(as.cost_03)
                as.cost_03 = zeros(size(as.occgrid));
            end

            if nargin > 1
                as.goal = goal; % invokes superclass method set.goal()
            end
            if isempty(as.goal)
                error('must specify a goal point');
            end

            % Setup cost layers AS.cost_g and AS.cost_h.
            % assign values to the distance cost layer, set as AS.costmap
            as.occgrid2costmap(as.occgrid);
            % assign values to the heuristic cost layer, set as AS.cost_h
            as.calcHeuristic(as.occgrid, as.goal);
            % Additional cost layers are added by the user with the
            % AS.addCost() method

            % Cost priority/tiebreaker: cost_g (distance to node)
            as.priority = as.cost_g;
            as.tie = 1; % first cost: cost_g
        end

        function P = path(as, start)
        %AstarMOO.path Find a path between two points
        %
        % AS.path(START) finds and displays a path from START to GOAL
        % which is overlaid on the occupancy grid.
        %
        % P = AS.path(START) returns the path (2xM) from START to GOAL.
            if nargin < 1
                error('must specify start state');
            end

            % invoke the superclass path function, which iterates on our
            % next method
            start = [start; 1]; % Specifies backpropogation for NAV.path()
            if nargout == 0
                path@Navigation(as, start);
            else
                P = path@Navigation(as, start);
            end
        end

        % Handler invoked by Navigation.path() to start the navigation process
        % Calculate the solution path
        % Line comments LN reference A* pseudocode in Lavin's "A Pareto
        % Front-Based Multiobjective Path Planning Algorithm" where n is
        % the line number.
        function navigate_init(as, start)
            as.openlist = zeros(as.N+1,0); % make sure openlist is empty
            % begin with the start node
            start = sub2ind(size(as.costmap), start(2), start(1));
            as.openlist(1,1) = start;
            as.t(start) = as.OPEN;
            as.niter = 0; flag = 0; % init while loop
            % Plan the A* path
            while ~isempty(as.openlist) % L4
                % Normalize costs on the open list, choose expansion state:
                queue = normc(as.openlist(2:size(as.openlist,1),:)');
                [~,ind]=min(sum(queue,2));
                X = as.openlist(1,ind); % L5; minimum state on the open list
                as.DELETE(X); % L6; remove state from the openlist

                as.niter = as.niter + 1;

                if ~as.quiet && mod(as.niter, 20) == 0 % i.e. spinner every 20 iterations
                    as.spinner();
                end

                % Populate the openlist:
                for Y=as.neighbors(X) % L7,8; check node's 8 neighbors
                    if(Y==as.G) % L9; check for goal
                        as.b(Y) = X;
                        as.updateCosts(Y,X,as.N)
                        flag = 1; % flag for goal
                        break;
                    end
                    if as.t(Y)==as.NEW && as.costmap(Y)~=Inf % hasn't been checked and isn't an obstacle
                        as.b(Y) = X;
                        as.updateCosts(Y,X,as.N); % as.N = 2 -> base case w/ only distance cost parameters (g and h)
                        % project node's costs into objective space:
                        objspace = as.projectCost(Y,X);
                        as.INSERT(Y, objspace, '');
                    end
                end
                if as.verbose
                    disp(' ')
                end
                if flag==1 % goal found
                    break;
                end
            end
            if ~as.quiet
                fprintf('\r');
            end
            as.changed = false;
        end

        function layer = cost_get(as)
        %AstarMOO.cost_get Get the specified cost layer
            layer = as.cost_02;
        end

        function c = heuristic_get(as)
        %AstarMOO.heuristic_get Get the current heuristic map
        %
        % C = AS.heuristic_get() is the current heuristic map.  This map is the same size
        % as the occupancy grid and the value of each element is the shortest distance
        % from the corresponding point in the map to the current goal.  It is computed
        % by Astar.plan.
        %
        % See also Astar.plan.
            c = as.cost_h;
        end

        function c = costmap_get(as)
        %AstarMOO.costmap_get Get the current costmap
        %
        % C = AS.costmap_get() is the current costmap.  The cost map is the same size
        % as the occupancy grid and the value of each element represents the cost
        % of traversing the cell.  It is autogenerated by the class constructor from
        % the occupancy grid such that:
        % - free cell (occupancy 0) has a cost of 1
        % - occupied cell (occupancy >0) has a cost of Inf
        %
        % See also Astar.costmap_set, Astar.costmap_modify.

            c = as.costmap;
        end

        function costmap_set(as, costmap)
        %AstarMOO.costmap_set Set the current costmap
        %
        % AS.costmap_set(C) sets the current costmap.  The cost map is the same size
        % as the occupancy grid and the value of each element represents the cost
        % of traversing the cell.  A high value indicates that the cell is more costly
        % (difficult) to traverese.  A value of Inf indicates an obstacle.
        %
        % Notes::
        % - After the cost map is changed the path should be replanned by
        %   calling AS.plan().
        %
        % See also Astar.costmap_get, Astar.costmap_modify.
            if ~all(size(costmap) == size(as.occgrid))
                error('costmap must be same size as occupancy grid');
            end
            as.costmap = costmap;
            as.changed = true;
            end

        function costmap_modify(as, point, newcost)
        %AstarMOO.costmap_modify Modify cost map
        %
        % AS.costmap_modify(P, NEW) modifies the cost map at P=[X,Y] to
        % have the value NEW.  If P (2xM) and NEW (1xM) then the cost of
        % the points defined by the columns of P are set to the corresponding
        % elements of NEW.
        %
        % Notes::
        % - After one or more point costs have been updated the path
        %   should be replanned by calling AS.plan().
        %
        % See also AstarMOO.costmap_set, AstarMOO.costmap_get.

            if numel(point) == 2
                % for case of single point ensure it is a column vector
                point = point(:);
            end
            if numcols(point) ~= numcols(newcost)
                error('number of columns in point must match columns in newcost');
            end
            for i=1:numcols(point)
                X = sub2ind(size(as.costmap), point(2,i), point(1,i));
                as.costmap(X) = newcost(i);
            end
            if as.t(X) == as.CLOSED
                as.INSERT(X, as.h(X), 'modifycost');
            end
            as.changed = true;
        end

        function addCost(as, layer, values)
        %AstarMOO.addCost Add an additional cost layer
        %
        % AS.addCost(LAYER, VALUES) adds the matrix specified by values as a
        % cost layer.  The layer number is given by LAYER, and VALUES has the same
        % size as the original occupancy grid.

            if size(values)~=size(as.occgrid)
                display('Layer size does not match the environment')
                return
            end
            if max(max(values))~=1 || min(min(values))~=0
                display('Layer values are not normalized [0:1]')
                return
            end

            if layer==1
                as.cost_01 = values;
            elseif layer==2
                as.cost_02 = values;
            elseif layer==3
                as.cost_03 = values;
            else
                display('Layer index out of range')
            end
            % If more cost layers needed, add additional elseif statements
            % as above.
        end

    end % end of public methods

    methods (Access=protected) % start of private methods

        function occgrid2costmap(as, og, cost)
            if nargin < 3
                cost = 1; % cost to traverse each cell
            end
            as.costmap = og;
            as.costmap(as.costmap==1) = Inf; % occupied cells -> infinite path cost
            as.costmap(as.costmap==0) = cost; % unoccupied cells -> path cost
        end

        function calcHeuristic(as, grid, goal)
            as.cost_h=zeros(size(grid));
            for ii=1:size(grid,1)
                for jj=1:size(grid,2)
                    as.cost_h(ii,jj)=sqrt((ii-goal(1))^2+(jj-goal(2))^2);
                end
            end
        end

             % NOTE: Only for costs that accumulate (i.e. sum) over the
            % path, and for dynamic costs.
            % E.g. the heuristic parameter AS.cost_h only needs updating
            % when the goal state changes; it's values are stored for each
            % cell.
            %
            % Location moving from state b to a.

        function k_new = updateCosts(as, a, b, obj)

            if nargout > 0
                k_new = as.cost_g(b) + as.dc(b,a);
                return
            end
            if obj == 0                        % just return what the new priority cost would be (k_new)
                return
            end
            if obj > 1                         % base case
                as.cost_g(a) = as.cost_g(b) + as.dc(b,a);
                % (no heuristic update needed)
            end
            if obj > 2                         % w/ cost_01: elevation
                % (no elevation update needed)
            end
            if obj > 3                         % w/ cost_02: solar
                sV = [cos(as.niter/100);sin(as.niter/100)]; % rotates 1rad per 100 steps
                as.cost_02(a) = dot(sV,as.vc(b,a));
            end
            if obj > 4                         % w/ cost_03: risk
                % (no risk update needed)
            end
        end

        % Returns the projection of state a into objective space. If
        % specified, location is moving from b to a.
        function pt = projectCost(as, a, b)
            switch nargin
                case 2
                    pt = [as.cost_g(a);
                          as.cost_h(a);
                          as.cost_01(a);
                          as.cost_02(a);
                          as.cost_03(a);
                          ];
                case 3
                    pt = [as.cost_g(b) + as.dc(a,b);
                          as.cost_h(a);
                          as.cost_01(a);
                          as.cost_02(a);
                          as.cost_03(a);
                          ];
                otherwise
                    return
            end
        end

        % X is new node with costs in array pt

        function INSERT(as, X, pt, where)

            if nargin>2
                as.message('insert (%s) %d = %f\n', where, X, pt);
            end

            i = find(as.openlist(1,:) == X);
            if length(i) > 1
                error('A*:INSERT: state in open list %d times', X);
            end

            if as.t(X) == as.NEW
                % add a new column to the open list
                as.openlist = [as.openlist [X; pt]];
            elseif as.t(X) == as.OPEN
                % L13: If a node with same position as successor is in the
                % OPEN list & has a lower f than successor, then skip this
                % successor.
                if pt(as.tie) < as.priority(X) % break tie with the sum of path costs
                    % add a new column to the open list
                    as.openlist = [as.openlist [X; pt]];
                end
            elseif as.t(X) == as.CLOSED
                % L14: If a node with same position as successor is in the
                % CLOSED list & has a lower f than successor, then skip this
                % successor.
                if pt(as.tie) < as.priority(X) % break tie with the sum of path costs
                    % add a new column to the open list
                    as.openlist = [as.openlist [X; pt]];
                end
            end

            % keep track of the max length of the openlist:
            if numcols(as.openlist) > as.openlist_maxlen
                as.openlist_maxlen = numcols(as.openlist);
            end

            as.t(X) = as.OPEN; % tag X as open
        end

        function DELETE(as, X)
            as.message('delete %d\n', X);
            i = find(as.openlist(1,:) == X);
            if length(i) ~= 1
                error('D*:DELETE: state %d doesnt exist', X);
            end
            as.openlist(:,i) = []; % remove the column
            as.t(X) = as.CLOSED;
        end

        % return the distance cost of moving from state X to state Y
        function cost = dc(as, X, Y)
            [r,c] = ind2sub(size(as.costmap), [X; Y]);
            dist = sqrt(sum(diff([r c]).^2));
            dcost = (as.costmap(X) + as.costmap(Y))/2;

            cost = dist * dcost;
        end

        % return the robot unit vector; direction of moving from state X to state Y
        function vector = vc(as, X, Y)
            [Xi,Xj] = ind2sub(size(as.occgrid),X);
            [Yi,Yj] = ind2sub(size(as.occgrid),Y);
            vector = [Yi-Xi;Yj-Xj];
            vector = vector/norm(vector);
%             slope = vector(2) / vector(1);
%             theta = dot([0,1],[vector])/(norm([0,1])*norm(vector));
        end

        % return index of neighbor states (max 8) as a row vector
        function Y = neighbors(as, X)
            dims = size(as.costmap);
            [r,c] = ind2sub(dims, X);

            % list of 8-way neighbors:
            Y = [r-1 r-1 r-1 r r  r+1 r+1 r+1; c-1 c c+1 c-1 c+1 c-1 c c+1];
            % only use neighbors w/in grid bounds...
            k = (min(Y)>0) & (Y(1,:)<=dims(1)) & (Y(2,:)<=dims(2));
            Y = Y(:,k);
            Y = sub2ind(dims, Y(1,:)', Y(2,:)')';
        end

    end % end of private methods
end

author: petercorke

repo: robotics-toolbox-matlab


text:
function [cohsig,sptsig,c] = crbs7(y,rlx_int,eukenf,c_int,c_tr,xi)
% Written by John Smith
% October 21st, 2010
% University of Colorado at Boulder, CIRES
% John.A.Smith@Colorado.EDU
% MATLAB version 7.10.0.59 (R2010a) 64-bit
% Adapted from "Coherent Rayleigh-Brillouin Scattering"
% by Xingguo Pan

% Computes the coherent and spontaneous
% RBS spectrum given the parameters
% in crbs_molecular using the s7 model
% by X. Pan, 2002

% Called by: crbs_molecular.m

n_xi=numel(xi);

n=7;
a=zeros(n,n);
b=zeros(n,2);

cohsig=zeros(1,n_xi);
sptsig=zeros(1,n_xi);

cpxunit=sqrt(-1);

y7=1.5*y;
gamma_int=c_int/(c_tr+c_int);
j020=-y;
j030=1.5*j020;
j100=-gamma_int*y/rlx_int;
j001=j100*c_tr/c_int;
j100001=j100*sqrt(c_tr/c_int);
j110=j100*5/6+j020*2/3;
j011110=j100*sqrt(5/(8*c_int));
j_nu=0.4*(1.5+c_int)+(3+c_int)/(2*rlx_int)+9*eukenf/(16*rlx_int^2);
j_de=-1+(4/15)*eukenf*(1.5+c_int)+(c_int/3)*eukenf/rlx_int;
j_co=-y*(2*gamma_int/3);
j011=j_co*j_nu/j_de;

for i=1:n_xi
    z=xi(i)+y7*cpxunit;
	w0=w0_func(z);
	w1=-sqrt(pi)+z*w0;
	w2=z*w1;
	w3=-0.5*sqrt(pi)+z*w2;
	w4=z*w3;
	w5=-3*sqrt(pi)/4+z*w4;
	w6=z*w5;

    i0000=w0/(sqrt(pi));
	i0100=w1*sqrt(2/pi);
	i0001=i0100;
	i0010=(2*w2-w0)/(sqrt(6*pi));
	i1000=i0010;
	i0011=(2*w3-3*w1)/(sqrt(5*pi));
	i1100=i0011;
	i0101=2*w2/sqrt(pi);
	i0110=(-w1+2*w3)/sqrt(3*pi);
	i1001=i0110;
	i0111=(-3*w2+2*w4)*sqrt(2/(5*pi));
	i1101=i0111;
	i1111=(13*w2-12*w4+4*w6)/(5*sqrt(pi));
	i0002=(-w0+2*w2)/sqrt(3*pi);
	i0200=i0002;
	i0211=(-w1+8*w3-4*w5)/sqrt(15*pi);
	i1102=i0211;
	i0202=2*(w0-2*w2+2*w4)/(3*sqrt(pi));
	i0210=(w0+4*w2-4*w4)/(3*sqrt(2*pi));
	i1002=i0210;
	i0102=(-w1+2*w3)*sqrt(2/(3*pi));
	i0201=i0102;
	i1010=(5*w0-4*w2+4*w4)/(6*sqrt(pi));
	i1110=(7*w1-8*w3+4*w5)/sqrt(30*pi);
	i1011=i1110;

    a(:,1)=-j030*[i0000 i0001 i0011 i0002 i0010 0 0]+[cpxunit 0 0 0 0 0 0];
    a(:,2)=-j030*[i0100 i0101 i0111 i0102 i0110 0 0]+[0 cpxunit 0 0 0 0 0];
    a(:,3)=(j030-j110)*[i1100 i1101 i1111 i1102 i1110 0 0]+j011110*[0 0 0 0 0 -i0100 -i0101]+[0 0 -cpxunit 0 0 0 0];
    a(:,4)=(j020-j030)*[i0200 i0201 i0211 i0202 i0210 0 0]+[0 0 0 3/2*cpxunit 0 0 0];
    a(:,5)=(j030-j100)*[i1000 i1001 i1011 i1002 i1010 0 0]+j100001*[0 0 0 0 0 -i0000 -i0001]+[0 0 0 0 -cpxunit 0 0];
    a(:,6)=j100001*[i1000 i1001 i1011 i1002 i1010 0 0]+(j001-j030)*[0 0 0 0 0 i0000 i0001]+[0 0 0 0 0 cpxunit 0];
    a(:,7)=j011110*[i1100 i1101 i1111 i1102 i1110 0 0]+(j011-j030)*[0 0 0 0 0 i0100 i0101]+[0 0 0 0 0 0 cpxunit];

    b(:,1)=-[i0100 i0101 i0111 i0102 i0110 0 0];
    b(:,2)=-[i0000 i0001 i0011 i0002 i0010 0 0];

    c=linsolve(a,b);

    cohsig(i)=c(1,1)*conj(c(1,1));
    sptsig(i)=2*real(c(1,2));
end
end


text:
function msh = fs_meshFromSurface(fsSurface)
% Create a vistasoft-comptible mesh from a freesurfer surface
%  msh = fs_meshFromSurface(surfaceFile)
%
% Input:
%   fsSurface: path to freesurfer surface file
% Output:
%   msh: vistasoft compatible mesh
%
% Example:
%   fsPath = getenv('SUBJECTS_DIR');
%   fsSurface = fullfile(fsPath, 'wlsubj004', 'surf', 'lh.white');
%   msh = fs_meshFromSurface(fsSurface);
%   meshVisualize(msh)

[initVertices, initFaces] = freesurfer_read_surf(fsSurface);

% We need row vectors for coordinates in vistasoft
vertices = initVertices';
faces    = initFaces';

% There is a 0.5 voxel difference in freesurfer coordinates, as their
%   origin is in the center of a voxel, not a corner
vertices = bsxfun(@plus, vertices, [-.5 .5 -.5]');

% We need to reorient dimensions and shift by 128. The shift is because
% Freesufer's origin is in the center of the image, and for vistasoft it's
% in the corner
vertices = vertices([2 3 1],:)+128;

% Two of the three dimensions are opposite polarity
vertices([1 2],:) = 256 - (vertices([1 2],:));

% Create a standard mesh and add vertices and triangles
msh = meshCreate;
msh.initVertices = vertices;
msh.triangles = faces-1;   % vista triangles are zero indexed
msh.vertices = msh.initVertices;
msh.colors = ones(4, size(msh.vertices,2))*128;

% Construct surface normals
TR = triangulation(msh.triangles'+1, msh.vertices');
VN = vertexNormal(TR);
msh.normals = VN';

% Smooth and color
msh = meshSmooth(msh);
msh = meshColor(msh);

return

%% debug

% build a mesh using vistasoft tools
classfile = '/Volumes/server/Projects/Retinotopy/IndividualTemplates/data/Winawer/wl_subj004/3DAnatomy/t1_class.nii.gz';
vs.msh = meshBuildFromClass(classfile, [1 1 1], 'left'); % 'right' also works
vs.msh = meshSmooth(vs.msh);
vs.msh = meshColor(vs.msh);

fsPath = getenv('SUBJECTS_DIR');
fsSurface = fullfile(fsPath, 'wl_subj004', 'surf', 'lh.white');
fs.msh = fs_meshFromSurface(fsSurface);

% Visualize the meshes
meshVisualize(fs.msh);
meshVisualize(vs.msh);

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function dispDoneGibbonCode

disp(['--- Done --- ',datestr(now)]);

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

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
function experiments = stack_vot2017()

set_global_variable('bundle', 'http://data.votchallenge.net/vot2017/main/description.json');

baseline.name = 'baseline';
baseline.converter = [];
baseline.type = 'supervised';
baseline.tags = {'camera_motion', 'illum_change', 'occlusion', 'size_change', 'motion_change', 'empty'};

baseline.parameters.repetitions = 15;
baseline.parameters.burnin = 10;
baseline.parameters.skip_initialize = 5;
baseline.parameters.failure_overlap = 0;

baseline.analysis = {'ar', 'expected_overlap', 'speed'};

unsupervised.name = 'unsupervised';
unsupervised.converter = [];
unsupervised.type = 'unsupervised';
unsupervised.tags = {'camera_motion', 'illum_change', 'occlusion', 'size_change', 'motion_change', 'empty'};

unsupervised.parameters.repetitions = 1;
unsupervised.parameters.burnin = 0;

unsupervised.analysis = {'overlap', 'speed'};

realtime.name = 'realtime';
realtime.converter = [];
realtime.type = 'realtime';
realtime.tags = {'camera_motion', 'illum_change', 'occlusion', 'size_change', 'motion_change', 'empty'};

realtime.parameters.repetitions = 1;
realtime.parameters.default_fps = 20;
realtime.parameters.grace = 3;
realtime.parameters.burnin = 10;
realtime.parameters.override_fps = true;
realtime.parameters.skip_initialize = 5;
realtime.parameters.realtime_type = 'real';

realtime.analysis = {'expected_overlap'};

experiments = {baseline, unsupervised, realtime};

end

author: votchallenge

repo: toolkit-legacy