text:
function [fc,core]=qtt_tucker_m(tt, sz, tol)
%Compute the QTT-Tucker representation of TT
%   [FC,CORE]=QTT_TUCKER_M(TT, SZ, TOL) Computes the QTT-Tucker
%   representation of TT-tensor. This is a technical function: use
%   corresponding constructors of the QTT-Tucker class
%
%
% TT-Toolbox 2.2, 2009-2012
%
%This is TT Toolbox, written by Ivan Oseledets et al.
%Institute of Numerical Mathematics, Moscow, Russia
%webpage: http://spring.inm.ras.ru/osel
%
%For all questions, bugs and suggestions please mail
%ivan.oseledets@gmail.com
%---------------------------

d = tt.d;
n = tt.n;
rcr = tt.r;

fc = cell(d,1);

% Initial orthogonalization - 1->d
for i=1:d-1
    cr = tt{i};
    cr = reshape(cr, rcr(i)*n(i), rcr(i+1));
    [cr, rv]=qr(cr, 0);
    cr2 = tt{i+1};
    cr2 = rv*reshape(cr2, rcr(i+1), n(i+1)*rcr(i+2));
    rcr(i+1) = size(cr,2);
    tt{i} = reshape(cr, rcr(i), n(i), rcr(i+1));
    tt{i+1} = reshape(cr2, rcr(i+1), n(i+1), rcr(i+2));
end;

% Split tucker factors from d->1
core = tt;
nextcr = core{d};
rtuck = zeros(d,1);
for i=d:-1:1
    cr = nextcr;
    cr = permute(cr, [2, 1, 3]);
    cr = reshape(cr, n(i), rcr(i)*rcr(i+1));
    [u,s,v]=svd(cr, 'econ');
    s = diag(s);
    nrm = norm(s);
    r = my_chop2(s, tol*nrm); % !!!!!!
    rtuck(i) = r;
    if (i>1)
        fc{i} = u(:,1:r);
        cr = diag(s(1:r))*v(:,1:r)';
        cr = reshape(cr, r, rcr(i), rcr(i+1));
        cr = permute(cr, [1, 3, 2]);
        cr = reshape(cr, r*rcr(i+1), rcr(i));
        [cr,rv] = qr(cr, 0);
        cr2 = core{i-1};
        cr2 = reshape(cr2, rcr(i-1)*n(i-1), rcr(i));
        cr2 = cr2*(rv.');
        rcr(i) = size(cr, 2);
        nextcr = reshape(cr2, rcr(i-1), n(i-1), rcr(i));
        cr = reshape(cr, r, rcr(i+1), rcr(i));
        core{i} = permute(cr, [3, 1, 2]);
    else
        cr = v(:,1:r)';
        cr = reshape(cr, r, rcr(i), rcr(i+1));
        core{i} = permute(cr, [2, 1, 3]);
        fc{i} = u(:,1:r)*diag(s(1:r));
    end;
end;

% Quantics approximation
for i=1:d
    %d0 = log2(n(i));
    fc{i} = tt_tensor(fc{i});
    szc=sz{i}; d0=numel(szc); m0=szc(end); szc=szc(:);
    %fc{i} = tt_reshape(fc{i}, [2*ones(1,d0-1), 2*rtuck(i)], tol);
    fc{i}=tt_reshape(fc{i},[szc(1:end-1); m0*rtuck(i)],tol);
    nocore = fc{i}{d0}; % rqtt, 2*rtuck, 1
    rqtt = size(nocore, 1);
    if (i<d)
        % Play with QRs: fc{i}->cr{i}->cr{i+1}->fc{i+1}
        nocore = reshape(nocore, rqtt*m0, rtuck(i));
        [ocore, nocore]=qr(nocore, 0);
        cr1 = core{i};
        cr1 = permute(cr1, [2, 1, 3]);
        cr1 = reshape(cr1, rtuck(i), rcr(i)*rcr(i+1));
        cr1 = nocore*cr1;
        rtuck(i) = size(cr1, 1);
        fc{i}{d0} = reshape(ocore, rqtt, m0, rtuck(i));

        cr1 = reshape(cr1, rtuck(i)*rcr(i), rcr(i+1));
        [cr1, rv]=qr(cr1, 0);
        cr2 = core{i+1};
        cr2 = reshape(cr2, rcr(i+1), rtuck(i+1)*rcr(i+2));
        cr2 = rv*cr2;
        rcr(i+1) = size(cr1, 2);
        cr1 = reshape(cr1, rtuck(i), rcr(i), rcr(i+1));
        core{i} = permute(cr1, [2,1,3]);
        cr2 = reshape(cr2, rcr(i+1), rtuck(i+1), rcr(i+2));
        cr2 = permute(cr2, [1, 3, 2]);
        cr2 = reshape(cr2, rcr(i+1)*rcr(i+2), rtuck(i+1));
        [cr2, rv]=qr(cr2, 0);
        fc{i+1} = fc{i+1}*(rv.');
        rtuck(i+1) = size(cr2, 2);
        cr2 = reshape(cr2, rcr(i+1), rcr(i+2), rtuck(i+1));
        core{i+1} = permute(cr2, [1, 3, 2]);
    else
        fc{i}{d0} = reshape(nocore, rqtt, m0, rtuck(i));
    end;
end;

end

author: oseledets

repo: TT-Toolbox


text:
function plotAlongDim(asObj,pos,plotDim)

% settings --------------
STAT_Y = 1;   % static y scale
STAT_Y_MODE = 2; % 1 scale image statistic object
                 % 2 scale from global min an max
                 % 3 manual
MANUAL_YLIM = [0,1]; % used only if STAT_Y_MODE = 3

PLOT_STD      = false;  % plot errorbars in ROI mode
DISPLAY_STATS = true;  % BETA: Print some statistics

% complex plot representations
CPLOT_MODE = 3; % 1 = magnitude and phase,
                % 2 = real and imag
                % 3 = real and imag in one window
        % ONLY MODE 3 SUPPORTED YET!!!

START_AT_ZERO = true;   % always start plots at zero point rather than first available TE

DO_NOT_USE_ROIS = false;    % ignore rois in image and always plot single pixel positions

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

% check if we should plot ROI means rather than single pixel values
if DO_NOT_USE_ROIS || isempty(asObj.roi) || ~isvalid(asObj.roi)
    use_roi_mean = false;
else
    use_roi_mean = true;
end

% get all images in asObject
s = asObj.getAllImages;

% check validity of plotDim
sel = asObj.selection.getValueAsCell;
colDims = sort(asObj.selection.getColonDims);
if isempty(plotDim)
    fprintf('no plot dimension given\n');
    asObj.cursor.togglePlotAlongDim(false);
    return;
end
if plotDim > length(sel)
    fprintf('Selected plot dimension (%d) > number of dims (%d)\n', plotDim, length(sel));
    asObj.cursor.togglePlotAlongDim(false);
    return;
end
if plotDim == colDims(1) || plotDim == colDims(2)
    fprintf('Selected plot dimension (%d) is not allowed to be a colon dim\n', plotDim);
    asObj.cursor.togglePlotAlongDim(false);
    return;
end

% create a selection string for the current cursor position and the
% plotDimension
if use_roi_mean
    sel{colDims(1)} = ':';   % if we have a roi, get the complete images
    sel{colDims(2)} = ':';
else
    sel{colDims(1)} = num2str(pos(1));
    sel{colDims(2)} = num2str(pos(2));
end
sel{plotDim} = ':';
selStr = '';
for i = 1 : length(sel)
    selStr = [selStr,sel{i},','];
end
selStr(end) = []; % remove last comma from string
eval(['s=s(',selStr,');']); % get selection

% get selected complex part
cplxFun = asObj.complexSelect.getFunPointer;
isComplexPhasePlot = false;
if strcmp(asObj.complexSelect.getSelection,'Pha') && use_roi_mean
    isComplexPhasePlot = true; % to avoid phase wrapping problems when
                               % deriving a mean phase value of a roi, we
                               % need to keep the data complex at this
                               % point
else
    s = cplxFun(s);            % for all selections except phase, we apply
                               % the selection before possible roi summations
end

% if we want to use the ROI, derive mean within ROI area
if use_roi_mean
    remainingDims = 1:length(size(s));
    remainingDims([colDims,plotDim]) = [];
	s = permute(s,[colDims,plotDim,remainingDims]); % make colon dims the first dimensions
    s = squeeze(s);
    si = size(s);
    StDev = zeros(1, si(1,3));
    roiMask = asObj.roi.createMask;   % apply mask to all images
    s = bsxfun(@times,s,roiMask);

    % get the standart deviation
    for i = 1:1:si(1,3)
        StDev(i) = std(nonzeros(s(:,:,i)));
    end

    % derive means
    s = squeeze(sum(sum(s,1),2))/asObj.roi.getN;

    if isComplexPhasePlot
        s = cplxFun(s); % if we are dealing with a phase plot, we have to
                        % derive the phase from the mean complex value now
    end
else
    roiMask = [];
    s = squeeze(s);
end

% if this is the first call...
if isempty(asObj.UserData) ||...
        ~isfield(asObj.UserData,'plotFigHandle') ||...
        ~ishandle(asObj.UserData.plotFigHandle)||...
        ~strcmp(get(asObj.UserData.plotFigHandle,'UserData'),'plotFig')

    % create plot window below asObject
    figPos = asObj.getFigureOuterPosition;
    figPos(2) = figPos(2) - figPos(4) - 26;
    asObj.UserData.plotFigHandle = figure('OuterPosition',figPos,...
        'MenuBar','figure',...
        'ToolBar','none',...
        'UserData','plotFig',...
        'name',asObj.getFigureTitle,...
        'IntegerHandle','off',...
        'CloseRequestFcn',@(src, evnt)closeReqCb(src,asObj));
    asObj.UserData.plotAxisHandle = axes('parent',asObj.UserData.plotFigHandle);

    % lead asObj to calculate and store the global min and max
    updateGlobalRange(asObj,plotDim);

    % store current complex selection (so that we can recognize possible
    % changes later)
    asObj.UserData.cplxSelection = asObj.complexSelect.getSelection;

    % set focus to new plot figure
    figure(asObj.getFigureHandle);
end

% check, if the complex selection has changed
if ~strcmp(asObj.complexSelect.getSelection, asObj.UserData.cplxSelection)
    % if so, recalculate global minima and maxima
    updateGlobalRange(asObj,plotDim);
    asObj.UserData.cplxSelection = asObj.complexSelect.getSelection;
end

% create x ticks
if isfield(asObj.UserData,'TE')
    x = asObj.UserData.TE;
else
    N = length(s);
    x = 1 : N;
end

% set plot start x
if START_AT_ZERO
    xStart =0;
else
    xStart = x(1);
end

% get the axis handle for the plot
ah = asObj.UserData.plotAxisHandle;

% plot
if isfield(asObj.UserData,'map')
    datatipStyle = 'x';
else
    datatipStyle = 'x-';
end
if isreal(s)
    if use_roi_mean && PLOT_STD
        errorbar(x, s, StDev, datatipStyle,'parent',ah);
    else
        plot(ah,x,s,datatipStyle);
    end
    ylabel(ah,asObj.complexSelect.getSelection);
else
    % complex plot (real and imaginary part)
    cPlot(x,s,'mode',CPLOT_MODE,'parent',ah,datatipStyle);
%     cPlot(s,'x-','parent',ah);
    ylabel(ah,'real / imag    (blue / green)');
end
xlim(ah,[xStart,x(end)]);

% set ylim from global mini and maximum
if STAT_Y
    switch(STAT_Y_MODE)
        case 1
            YLIM = [asObj.statistics.getMin, asObj.statistics.getMax];
            if ~isreal(YLIM)
                YLIM(1) = min(real(YLIM(1)),imag(YLIM(1)));
                YLIM(2) = max(real(YLIM(2)),imag(YLIM(2)));
            end
        case 2
            YLIM = asObj.UserData.range;
        case 3
            YLIM = MANUAL_YLIM;
    end
    ylim(ah,YLIM);
end

% annotations
if use_roi_mean
    title(ah,sprintf('ROI mean values over dim %d',plotDim));
else
    title(ah,sprintf('Pixel %d / %d over dim %d',pos(1),pos(2),plotDim));
end

% BETA: Print some statistics
if isreal(s) && DISPLAY_STATS  % only supported for real values yet
    mi = min(s);
    ma = max(s);
    me = mean(s);
    ra = ma - mi;
    str = sprintf('\nMin  : %2.2f\nMax  : %2.2f\nRange: %2.2f\nMean : %2.2f',mi,ma,ra,me);
%     fprintf([str,'\n']);
%     text(0,YLIM(1)',str,'Parent',ah,'VerticalAlignment','bottom');
    text(0,0,str,'Parent',ah,'VerticalAlignment','bottom');
end

end

function updateGlobalRange(asObj,plotDim)
    fprintf('getting global minimum and maximum...');
    th = tic;
    all = asObj.getAllImages;

    % (BETA) isolate nonColonDim & nonPlotDim dimension...
    % The current implementation does not call this function at selection
    % changes. This can causes problems, when selection is changed.
    if(true)
        sel = asObj.selection.getValueAsCell;
        sel{plotDim} = ':';
        selStr = '';
        for i = 1 : length(sel)
            selStr = [selStr,sel{i},','];
        end
        selStr(end) = []; % remove last comma from string
        eval(['all=all(',selStr,');']); % get selection
    end

    % get selected complex part
    cplxFun = asObj.complexSelect.getFunPointer;
    all = cplxFun(all);

    if isreal(all)
        mi = min(all(:));
        ma = max(all(:));
    else
        mir = min(real(all(:)));
        mar = max(real(all(:)));

        mii = min(imag(all(:)));
        mai = max(imag(all(:)));

        mi = min(mir,mii);
        ma = max(mar,mai);
    end
    asObj.UserData.range = [mi,ma];
    fprintf('   done in %f\n',toc(th));
end

function closeReqCb(src, asObj)
    if isvalid(asObj)
        asObj.cursor.togglePlotAlongDim(false)
    end
    delete(src);
end

author: leoliuf

repo: MRiLab

save_path: github-repos/MATLAB/leoliuf-MRiLab


text:
function l = lumHK(img)
%
%       l = lum(img)
%
%       This function calculates the Helmholtz-Kohlrausch luminance
%
%
%       input:
%           img: an RGB image
%
%       output:
%           l: normalized Helmholtz-Kohlrausch luminance
%
%     Copyright (C) 2015  Francesco Banterle
%
%     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/>.
%

check3Color(img);

imgXYZ = ConvertRGBtoXYZ(img, 0);
imgLCh = ConvertXYZtoCIELCh(imgXYZ, 0);

L = imgLCh(:,:,1);
C = imgLCh(:,:,2);
h = imgLCh(:,:,3);

h2 = ((h - 90) / 2) * pi / 360;

l = L + (2.5 - 0.025 * L) .* (0.116 * abs(sin(h2)) + 0.085) .* C;
l = l / max(l(:));

end

author: banterle


text:
function item = subsasgn_job(item, subs, val)

% function varargout = subsasgn_job(item, subs)
% Treat a subscript reference as a reference in a job structure instead
% of a cfg_item structure. If subs is empty, then the subtree
% beginning at item will be initialised with val. Otherwise, subs(1)
% should have a subscript type of '()' or '{}', depending on the
% structure of the harvested job (cell or struct array). subs(2) should
% have a subscript type of '.' and the subscript reference should be a
% tagname from item.val.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: subsasgn_job.m 5678 2013-10-11 14:58:04Z volkmar $

rev = '$Rev: 5678 $'; %#ok

if isempty(subs)
    item = initialise(item, '<DEFAULTS>', false);
    item = initialise(item, val, false);
elseif numel(subs) == 1
    if any(strcmp(subs(1).type, {'()', '{}'}))
        if max(subs(1).subs{1}) > numel(item.cfg_item.val)
            defsubs = setdiff((numel(item.cfg_item.val)+1):max(subs(1).subs{1}), subs(1).subs{1});
        else
            defsubs = [];
        end
        if strcmp(subs(1).type, '()')
            if numel(val) == 1
                val = repmat(val, 1, numel(subs(1).subs{1}));
            elseif numel(val) ~= numel(subs(1).subs{1})
                cfg_message('matlabbatch:subsref_job', 'Item ''%s'': invalid subscript reference.', gettag(item));
            end
            if numel(item.values) == 1 && ~item.forcestruct
                % struct array reference or () subscript into cell array
                citem = initialise(item.values{1}, '<DEFAULTS>', false);
                item  = subsasgn(item, substruct('.', treepart(item, false), '()', {defsubs}), {citem});
                for k = 1:numel(subs(1).subs{1})
                    citem = initialise(item.values{1}, '<DEFAULTS>', false);
                    if isstruct(val)
                        val1 = val(k);
                    else
                        val1 = val{k};
                    end
                    citem = initialise(citem, val1, false);
                    item  = subsasgn(item, substruct('.', treepart(item, false), '{}', {subs(1).subs{1}(k)}), citem);
                end
            else
                % () subscript into cell array, no default items allowed
                if isempty(defsubs)
                    item1 = initialise(item, '<DEFAULTS>', false);
                    item1 = initialise(item1, val, false);
                    for k = 1:numel(subs(1).subs{1})
                        item = subsasgn(item, substruct('.', treepart(item, false), '{}', {subs(1).subs{1}(k)}), item1.cfg_item.val{k});
                    end
                else
                    cfg_message('matlabbatch:subsref_job', 'Item ''%s'': invalid subscript reference.', gettag(item));
                end
            end
        elseif strcmp(subs(1).type, '{}')
            if numel(item.values) == 1 && ~item.forcestruct
                if isa(item.values{1}, 'cfg_branch')
                    % struct array - no {} reference allowed
                    cfg_message('matlabbatch:subsref_job', 'Item ''%s'': invalid subscript reference.', gettag(item));
                else
                    citem = initialise(item.values{1}, '<DEFAULTS>', false);
                    item  = subsasgn(item, substruct('.', treepart(item, false), '()', {defsubs}), {citem});
                    for k = 1:numel(subs(1).subs{1})
                        citem = initialise(item.values{1}, '<DEFAULTS>', false);
                        citem = initialise(citem, val, false);
                        item  = subsasgn(item, substruct('.', treepart(item, false), '{}', {subs(1).subs{1}(k)}), citem);
                    end
                end
            elseif isstruct(val)
                val1 = cell(size(val));
                for k = 1:numel(val)
                    val1{k} = val(k);
                end
                item1 = initialise(item, '<DEFAULTS>', false);
                item1 = initialise(item1, val1, false);
                for k = 1:numel(subs(1).subs{1})
                    item = subsasgn(item, substruct('.', treepart(item, false), '{}', {subs(1).subs{1}(k)}), item1.cfg_item.val{k});
                end
            else
                cfg_message('matlabbatch:subsref_job', 'Item ''%s'': invalid subscript reference.', gettag(item));
            end
        end
    elseif strcmp(subs(1).type, '.') && (numel(item.values) == 1) && ~item.forcestruct && isa(item.values{1}, 'cfg_branch')
        if numel(item.cfg_item.val) == 0
            item.cfg_item.val{1} = initialise(item.values{1}, '<DEFAULTS>', false);
            item.cfg_item.val{1} = subsasgn_job(item.cfg_item.val{1}, subs, val);
        elseif numel(item.cfg_item.val) == 1
            item.cfg_item.val{1} = subsasgn_job(item.cfg_item.val{1}, subs, val);
        else
            cfg_message('matlabbatch:subsref_job', 'Item ''%s'': invalid subscript reference.', gettag(item));
        end
    else
        cfg_message('matlabbatch:subsref_job', 'Item ''%s'': invalid subscript reference.', gettag(item));
    end
else
    [sts, vind] = checksubs_job(item, subs, false);
    if (numel(item.values) == 1) && ~item.forcestruct && isa(item.values{1}, 'cfg_branch')
        nsubs = subs(2:end);
    else
        nsubs = subs(3:end);
    end
    if sts
        citem = subsasgn_job(subsref(item, substruct('.', treepart(item, false),'{}',{vind})), nsubs, val);
        item  = subsasgn(item, substruct('.', treepart(item, false), '{}', subs(1).subs), citem);
    else
        [sts, vind] = checksubs_job(item, subs, true);
        if sts
            if numel(item.values) == 1
                if max(subs(1).subs{1}) > numel(item.cfg_item.val)
                    defsubs = setdiff((numel(item.cfg_item.val)+1):max(subs(1).subs{1}), subs(1).subs{1});
                else
                    defsubs = [];
                end
                if numel(val) == 1
                    val = repmat(val, 1, numel(subs(1).subs{1}));
                elseif numel(val) ~= numel(subs(1).subs{1})
                    cfg_message('matlabbatch:subsref_job', 'Item ''%s'': invalid subscript reference.', gettag(item));
                end
                citem = initialise(item.values{1}, '<DEFAULTS>', false);
                item  = subsasgn(item, substruct('.', treepart(item, false), '()', {defsubs}), {citem});
                citem = subsasgn_job(subsref(item, substruct('.', treepart(item, true),'{}',{vind})), nsubs, val);
                item  = subsasgn(item, substruct('.', treepart(item, false), '{}', subs(1).subs), citem);
            else
                if max(subs(1).subs{1}) > numel(item.cfg_item.val) + 1
                    cfg_message('matlabbatch:subsref_job', 'Item ''%s'': invalid subscript reference.', gettag(item));
                else
                    citem = subsasgn_job(subsref(item, substruct('.', treepart(item, true),'{}',{vind})), nsubs, val);
                    item  = subsasgn(item, substruct('.', treepart(item, false), '{}', subs(1).subs), citem);
                end
            end
        else
            cfg_message('matlabbatch:subsref_job', 'Item ''%s'': invalid subscript reference.', gettag(item));
        end
    end
end

author: spm


text:
function h = p13_fh ( p, varargin )

%*****************************************************************************80
%
%% P13_FH returns a mesh size function for problem 13.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 February 2006
%
%  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 point coordinates.
%
%    Input, VARARGIN, room for extra arguments.
%
%    Output, real H(NP,1), the mesh size function.
%
  np = size ( p, 1 );
  h = ones ( np, 1 );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [model,centers] = FCMmodel(Problem,Population,L1,L2)
% Fuzzy clustering-based method for modeling c_size* M models, where c_size
% is the number of clusters and M the number of objectives.

%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

% This function is written by Cheng He

    PopDec      = Population.decs;
    csize       = 1 + ceil((length(Population)-L1)/L2);
    [centers,~] = fcm(PopDec,csize,[2 NaN 0.05 false]);
    dis         = pdist2(PopDec,centers);
    [~,index]   = sort(-dis);
    group       = index(1:L1,:);

    %% Build GP model of each objective for each cluster
    model   = cell(csize,Problem.M);
    THETA   = 5.*ones(csize,Problem.M,Problem.D);
    for i   = 1 : csize
        temp = Population(group(:,i));
        PopDec = temp.decs;
        PopObj = temp.objs;
        for j = 1 : Problem.M
            dmodel = dacefit(PopDec,PopObj(:,j),...
                     'regpoly0','corrgauss',...
                     squeeze(THETA(i,j,:)),...
                     1e-5.*ones(1,Problem.D),...
                     100.*ones(1,Problem.D));
            model{i,j}   = dmodel;
            THETA(i,j,:) = dmodel.theta;
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function conditionPlots(hFig)
%"conditionPlots"
%   Adjusts all plots in the figure to some standard.
%
% 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/>.

if exist('hFig')
    hFigs = hFig;
else
    rootKids = get(0, 'children');
    hFigs = rootKids(strcmpi(get(rootKids, 'type'), 'figure'));
end

for j=1:length(hFigs)

    hFig = hFigs(j);
%     pos = get(hFig, 'position');
%     pos = [pos(1) pos(2) 280 336];
%     set(hFig, 'position', pos);
%     axis fill;

    kids = get(hFig, 'children');

    axes = kids(strcmpi(get(kids, 'type'), 'axes'));

	for i=1:length(axes)
        h = axes(i);

        set(h, 'FontSize', 14, 'FontWeight', 'Bold');
%         set(get(h, 'children'), 'color', [0 0 0]);
        set(get(h, 'title'), 'FontSize', 14, 'FontWeight', 'Bold');
        set(get(h, 'xlabel'), 'FontSize', 14, 'FontWeight', 'Bold');
        set(get(h, 'ylabel'), 'FontSize', 14, 'FontWeight', 'Bold');
        hDraw = get(h, 'Children');       % Drawings
        hLines = hDraw(strcmpi(get(hDraw, 'type'), 'line'));
        set(hLines, 'LineWidth', 2, 'MarkerSize', 9);
%         set(hLines, 'LineWidth', 2);

        legend = findobj(h, 'Tag', 'legend');
        legKids = get(legend, 'children');
        text = legKids(strcmpi(get(legKids, 'type'), 'text'));
        set(text, 'fontsize', 12, 'fontweight', 'Bold');
	end

end

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
%--- help for load_mode ---
%
%  INTERNAL FUNCTION
%
%

author: jmaih


text:
function [fA1Value, fA2Value] = calc_MaxLikelihoodA1A2(mCatalog, mControl, fBValue, bReBin)
% function [fAValue] = calc_MaxLikelihoodA(mCatalog, mControl, fBValue, bReBin)
% -----------------------------------------------------------------------------
% Computes the maximum likelihood a-values for a set of given catalogs
%   and a fixed b-value
%
% Input parameters:
%   mCatalog        Catalog containing different periods with varying
%                   magnitude of completeness
%   mControl        Controlmatrix containing informations about the single catalogs
%                   mControl(n,:) contains information about caCatalogs{n}
%                   Column 1: Starting time of catalog
%                   Column 2: Magnitude of completeness
%                   Column 3: Starting magnitude bin
%                   Column 4: Magnitude bin stepsize (must be 0.1)
%   fBValue         Fixed b-value
%   bReBin          Rebin the catalogs to the given binning in mControl
%                   (must be 0)
%
% Output parameters:
%   fAValue         Maximum likelihooda-value
%
% Danijel Schorlemmer
% July 5, 2002

% Get the number of different periods in the catalog
[nRow_, nColumn_] = size(mControl);
% Init vector with ending times for each period
vMaxTime_ = zeros(nRow_, 1);
% Loop over the control matrix
for nCnt_ = 1:nRow_
  % Determine starting time of period
  fMinTime_ = mControl(nCnt_, 1);
  % Determine ending time of period
  if nCnt_ < nRow_
    vMaxTime_(nCnt_) = mControl(nCnt_+1, 1);
  else
    vMaxTime_(nCnt_) = max(mCatalog(:,3));
  end
  % Create subcatalog for period
  vSel_ = (mCatalog(:,3) >= fMinTime_) & (mCatalog(:,3) < vMaxTime_(nCnt_));
  mTmpCatalog_ = mCatalog(vSel_,:);
  % Rebin the catalog (should not be used)
  if bReBin
    fMaxMag_ = max(mTmpCatalog_(:,6));
    for nBin_ = mControl(nCnt_,3):mControl(nCnt_,4):(fMaxMag_ + mControl(nCnt_,4))
      vSel_ = (mTmpCatalog_(:,6) >= (nBin_ - (mControl(nCnt_,4)/2))) & (mTmpCatalog_(:,6) < (nBin_ + (mControl(nCnt_,4)/2)));
      mTmpCatalog_(vSel_,6) = nBin_;
    end
  end
  % Cut the subcatalog at magnitude of completeness
  vSel_ = mTmpCatalog_(:,6) >= mControl(nCnt_,2);
  mTmpCatalog_ = mTmpCatalog_(vSel_,:);
  % Store the subcatalog
  caCatalogs_{nCnt_} = mTmpCatalog_;
end
% Add the ending times to the control matrix
mControl = [mControl vMaxTime_];
% Set the callback starting values
vStartValue = [1; 1];
% Find the maximum likelihood solution
[fAValues, vDummy, bExitFlag_] = fminsearch('callback_LogLikelihoodA1A2Value', vStartValue, [], caCatalogs_, mControl, fBValue);
fA1Value = fAValues(1);
fA2Value = fAValues(2);

author: CelsoReyes


text:
%[2012]-"Flower pollination algorithm for global optimization"

% (9/12/2020)

function FPA = jFlowerPollinationAlgorithm(feat,label,opts)
% Parameters
lb    = 0;
ub    = 1;
thres = 0.5;
beta  = 1.5;    % levy component
P     = 0.8;    % switch probability

if isfield(opts,'N'), N = opts.N; end
if isfield(opts,'P'), P = opts.P; end
if isfield(opts,'T'), max_Iter = opts.T; end
if isfield(opts,'beta'), beta = opts.beta; end
if isfield(opts,'thres'), thres = opts.thres; end

% Objective function
fun = @jFitnessFunction;
% Number of dimensions
dim = size(feat,2);
% Initial
X   = zeros(N,dim);
for i = 1:N
  for d = 1:dim
    X(i,d) = lb + (ub - lb) * rand();
  end
end
% Compute fitness
fit  = zeros(1,N);
fitG = inf;
for i = 1:N
  fit(i) =fun(feat,label,(X(i,:) > thres),opts);
  % Best flower
  if fit(i) < fitG
    fitG = fit(i);
    Xgb  = X(i,:);
  end
end
% Pre
Xnew = zeros(N,dim);

curve = zeros(1,max_Iter);
curve(1) = fitG;
t = 2;
% Iterations
while t <= max_Iter
	for i = 1:N
    % Global pollination
    if rand() < P
      % Levy distribution (2)
      L = jLevyDistribution(beta,dim);
      for d = 1:dim
        % Global pollination (1)
        Xnew(i,d) = X(i,d) + L(d) * (X(i,d) - Xgb(d));
      end
    % Local pollination
    else
      % Different flower j, k in same species
      R   = randperm(N);
      J   = R(1);
      K   = R(2);
      % Epsilon [0 to 1]
      eps = rand();
      for d = 1:dim
        % Local pollination (3)
        Xnew(i,d) = X(i,d) + eps * (X(J,d) - X(K,d));
      end
    end
    % Check boundary
    XB = Xnew(i,:); XB(XB > ub) = ub; XB(XB < lb) = lb;
    Xnew(i,:) = XB;
  end
  % Fitness
  for i = 1:N
    % Compute fitness
    Fnew = fun(feat,label,(Xnew(i,:) > thres),opts);
    % Update if there is better solution
    if Fnew <= fit(i)
      X(i,:) = Xnew(i,:);
      fit(i) = Fnew;
    end
    % Best flower
    if fit(i) < fitG
      Xgb  = X(i,:);
      fitG = fit(i);
    end
  end
  curve(t) = fitG;
  fprintf('\nIteration %d Best (FPA)= %f',t,curve(t))
  t = t + 1;
end
% Select features
Pos   = 1:dim;
Sf    = Pos((Xgb > thres) == 1);
sFeat = feat(:,Sf);
% Store results
FPA.sf = Sf;
FPA.ff = sFeat;
FPA.nf = length(Sf);
FPA.c  = curve;
FPA.f  = feat;
FPA.l  = label;
end

%// Levy Flight //
function LF = jLevyDistribution(beta,dim)
% Sigma
nume  = gamma(1 + beta) * sin(pi * beta / 2);
deno  = gamma((1 + beta) / 2) * beta * 2 ^ ((beta - 1) / 2);
sigma = (nume / deno) ^ (1 / beta);
% Parameter u & v
u = randn(1,dim) * sigma;
v = randn(1,dim);
% Step
step = u ./ abs(v) .^ (1 / beta);
LF   = 0.01 * step;
end

author: JingweiToo

repo: Wrapper-Feature-Selection-Toolbox


text:
%% This code allows complete manual reselection of every corner in the
%% images.
%% This tool is specifically useful in the case of highly distorted images.
%%
%% Use it when in standard mode.
%% In memory efficient mode, use manual_corner_extraction_no_read.m

if ~exist('n_ima'),
   fprintf(1,'No image data available\n');
   return;
end;

check_active_images;

if n_ima == 0,

    fprintf(1,'No image data available\n');

else

if ~exist(['I_' num2str(ind_active(1))]),
   n_ima_save = n_ima;
   active_images_save = active_images;
   ima_read_calib;
   n_ima = n_ima_save;
   active_images = active_images_save;
   check_active_images;
   if no_image_file,
      disp('Cannot extract corners without images');
      return;
   end;
end;

fprintf(1,'\nManual re-extraction of the grid corners on the images\n');

q_converge = input('Do you want to try to automatically find the closest corner? - only works with ckecker board corners  ([]=yes, other = no) ','s');

if isempty(q_converge),
    q_converge = 1;
    fprintf(1,'Automatic refinement of the corner location after manual mouse click\n');
    disp('Window size for corner finder (wintx and winty):');
    wintx = input('wintx ([] = 5) = ');
    if isempty(wintx), wintx = 5; end;
    wintx = round(wintx);
    winty = input('winty ([] = 5) = ');
    if isempty(winty), winty = 5; end;
    winty = round(winty);

    fprintf(1,'Window size = %dx%d\n',2*wintx+1,2*winty+1);
else
    q_converge = 0;
    fprintf(1,'No attempt to refine the corner location after manual mouse click\n');
end;

ima_numbers = input('Number(s) of image(s) to process ([] = all images) = ');

if isempty(ima_numbers),
   ima_proc = 1:n_ima;
else
   ima_proc = ima_numbers;
end;

fprintf(1,'Processing image ');

for kk = ima_proc;

    if active_images(kk),

        fprintf(1,'%d...',kk);

        eval(['I = I_' num2str(kk) ';']);

        eval(['x = x_' num2str(kk) ';']);

        Np = size(x,2);

        figure(2);
        image(I);
        colormap(map);
        hold on;
        hx = plot(x(1,:)+1,x(2,:)+1,'r+');
        hcp = plot(x(1,1)+1,x(2,1)+1,'co');
        hold off;

        for np = 1:Np,

            set(hcp,'Xdata',x(1,np)+1,'Ydata',x(2,np)+1);

            title(['Click on corner #' num2str(np) ' out of ' num2str(Np) ' (right button: keep point unchanged)']);

            [xi,yi,b] = ginput4(1);

            if b==1,
                xxi = [xi;yi];
                if q_converge,
                    [xxi] = cornerfinder(xxi,I,winty,wintx);
                end;
                x(1,np) = xxi(1) - 1;
                x(2,np) = xxi(2) - 1;
                set(hx,'Xdata',x(1,:)+1,'Ydata',x(2,:)+1);
            end;

        end;

        eval(['wintx_' num2str(kk) ' = wintx;']);
        eval(['winty_' num2str(kk) ' = winty;']);

        eval(['x_' num2str(kk) '= x;']);

    else

        if ~exist(['omc_' num2str(kk)]),

            eval(['dX_' num2str(kk) ' = NaN;']);
            eval(['dY_' num2str(kk) ' = NaN;']);

            eval(['wintx_' num2str(kk) ' = NaN;']);
            eval(['winty_' num2str(kk) ' = NaN;']);

            eval(['x_' num2str(kk) ' = NaN*ones(2,1);']);
            eval(['X_' num2str(kk) ' = NaN*ones(3,1);']);

            eval(['n_sq_x_' num2str(kk) ' = NaN;']);
            eval(['n_sq_y_' num2str(kk) ' = NaN;']);

        end;

    end;

end;

fprintf(1,'\ndone\n');

end;

repo: ekfmonoslam


text:
% This is the testing demo of FFDNet for denoising noisy color images corrupted by
% AWGN with clipping setting. The noisy input is 8-bit quantized.
%
% To run the code, you should install Matconvnet first. Alternatively, you can use the
% function `vl_ffdnet_matlab` to perform denoising without Matconvnet.
%
% "FFDNet: Toward a Fast and Flexible Solution for CNN based Image
% Denoising" 2018/03/23
% If you have any question, please feel free to contact with me.
% Kai Zhang (e-mail: cskaizhang@gmail.com)

% clear; clc;

format compact;
global sigmas; % input noise level or input noise level map
addpath(fullfile('utilities'));

folderModel = 'models';
folderTest  = 'testsets';
folderResult= 'results';
imageSets   = {'CBSD68','Kodak24','McMaster'}; % testing datasets
setTestCur  = imageSets{1};      % current testing dataset

showResult  = 1;
useGPU      = 1;
pauseTime   = 0;

imageNoiseSigma = 25;  % image noise level, 25.5 is the default setting of imnoise( ,'gaussian')
inputNoiseSigma = 25;  % input noise level

folderResultCur       =  fullfile(folderResult, [setTestCur,'_Clip_',num2str(imageNoiseSigma(1)),'_',num2str(inputNoiseSigma(1))]);
if ~isdir(folderResultCur)
    mkdir(folderResultCur)
end

load(fullfile('models','FFDNet_Clip_color.mat'));
net = vl_simplenn_tidy(net);

% for i = 1:size(net.layers,2)
%     net.layers{i}.precious = 1;
% end

if useGPU
    net = vl_simplenn_move(net, 'gpu') ;
end

% read images
ext         =  {'*.jpg','*.png','*.bmp','*.tif'};
filePaths   =  [];
for i = 1 : length(ext)
    filePaths = cat(1,filePaths, dir(fullfile(folderTest,setTestCur,ext{i})));
end

% PSNR and SSIM
PSNRs = zeros(1,length(filePaths));
SSIMs = zeros(1,length(filePaths));

for i = 1:length(filePaths)

    % read images
    label   = imread(fullfile(folderTest,setTestCur,filePaths(i).name));
    [w,h,c] = size(label);

    if c == 3
        [~,nameCur,extCur] = fileparts(filePaths(i).name);
        label = im2single(label);

        % add noise
        randn('seed',0);
        %input = imnoise(label,'gaussian'); % corresponds to imageNoiseSigma = 25.5;
        input = imnoise(label,'gaussian',0,(imageNoiseSigma/255)^2);

        if mod(w,2)==1
            input = cat(1,input, input(end,:,:)) ;
        end
        if mod(h,2)==1
            input = cat(2,input, input(:,end,:)) ;
        end

        % tic;
        if useGPU
            input = gpuArray(input);
        end

        % set noise level map
        sigmas = inputNoiseSigma/255; % see "vl_simplenn.m".

        % perform denoising
        res    = vl_simplenn(net,input,[],[],'conserveMemory',true,'mode','test'); % matconvnet default
        % res    = vl_ffdnet_concise(net, input);    % concise version of vl_simplenn for testing FFDNet
        % res    = vl_ffdnet_matlab(net, input); % use this if you did  not install matconvnet; very slow

        % output = input -res(end).x; % for 'model_color.mat'
        output = res(end).x;

        if mod(w,2)==1
            output = output(1:end-1,:,:);
            input  = input(1:end-1,:,:);
        end
        if mod(h,2)==1
            output = output(:,1:end-1,:);
            input  = input(:,1:end-1,:);
        end

        if useGPU
            output = gather(output);
            input  = gather(input);
        end
        %toc;

        % calculate PSNR, SSIM and save results
        [PSNRCur, SSIMCur] = Cal_PSNRSSIM(im2uint8(label),im2uint8(output),0,0);
        if showResult
            imshow(cat(2,im2uint8(input),im2uint8(label),im2uint8(output)));
            title([filePaths(i).name,'    ',num2str(PSNRCur,'%2.2f'),'dB','    ',num2str(SSIMCur,'%2.4f')])
            %imwrite(im2uint8(output), fullfile(folderResultCur, [nameCur, '_' num2str(imageNoiseSigma(1),'%02d'),'_' num2str(inputNoiseSigma(1),'%02d'),'_PSNR_',num2str(PSNRCur*100,'%4.0f'), extCur] ));
            drawnow;
            pause()
        end
        disp([filePaths(i).name,'    ',num2str(PSNRCur,'%2.2f'),'dB','    ',num2str(SSIMCur,'%2.4f')])
        PSNRs(i) = PSNRCur;
        SSIMs(i) = SSIMCur;

    end
end

disp([mean(PSNRs),mean(SSIMs)]);

author: cszn

repo: FFDNet

save_path: github-repos/MATLAB/cszn-FFDNet


text:
function handles = render_call_boxes(current_axes,handles,roi, fill_heigth)
%% This function draws rectangles in the focus view and page view

axis_xlim = get(current_axes,'Xlim');
axis_ylim = get(current_axes,'Ylim');

% Find calls within the current window
calls_in_page = find( (handles.data.calls.Box(:,1) >= axis_xlim(1) & handles.data.calls.Box(:,1) < axis_xlim(2)  ) ...
    | ( handles.data.calls.Box(:,1) + handles.data.calls.Box(:,3)  >= axis_xlim(1) & handles.data.calls.Box(:,1) + handles.data.calls.Box(:,3)  <= axis_xlim(2) )...
    | ( handles.data.calls.Box(:,1)<=  axis_xlim(1) & handles.data.calls.Box(:,1) + handles.data.calls.Box(:,3) >=  axis_xlim(2) )...
    );

boxes = handles.data.calls.Box(calls_in_page,:);

% Draw labels if there are any labels other than 'USV'
% if ~isempty(calls_in_page) any(handles.data.calls.Type ~= 'USV')
    LabelVisible = 'on'; % use 'hover' to only display labels on mouse over2
% else
%     LabelVisible = 'off';
% end

% Loop through all calls
for box_number = 1:length(calls_in_page)
    current_tag = num2str(calls_in_page(box_number));

    if fill_heigth
        boxes(box_number,2) = axis_ylim(1);
        boxes(box_number,4) = axis_ylim(2);
    end

    line_width = 0.5;
    box_color = 'r';
    line_style = '-';

    % Make the line thick if current call
    if handles.data.calls.Accept(calls_in_page(box_number))
        box_color = [0 1 0];
    end
    if calls_in_page(box_number) == handles.data.currentcall
        line_width = 2;
    end

    if roi

        % Only display a label if it isn't just "USV"
        if handles.data.calls.Type(calls_in_page(box_number)) == {'USV'}
            label = '';
        else
            label = char(handles.data.calls.Type(calls_in_page(box_number)));
        end

        % Add a new rectangle if there isn't a handle for one yet, or
        % update an existing one
        if box_number > length(handles.FocusWindowRectangles) % draw a new rectangle if we need more
            c = uicontextmenu;
            handles.FocusWindowRectangles{box_number} = drawrectangle(...
                'Position', boxes(box_number, :),...
                'Parent', current_axes,...
                'Color', box_color,...
                'FaceAlpha', 0,...
                'LineWidth', line_width,...
                'Tag', current_tag,...
                'uicontextmenu', c,...
                'label', label,...
                'LabelAlpha', .5,...
                'LabelVisible', LabelVisible);
            addlistener(handles.FocusWindowRectangles{box_number},'ROIClicked',@callBoxDeleteCallback);
            addlistener(handles.FocusWindowRectangles{box_number},'ROIMoved', @roiMovedCallback);
        else
            set(handles.FocusWindowRectangles{box_number},...
                'Position', boxes(box_number, :),...
                'Color', box_color,...
                'LineWidth', line_width,...
                'Tag', current_tag,...
                'Visible', true,...
                'label', label,...
                'LabelVisible', LabelVisible);
        end

    else
        % Add a new rectangle if there isn't a handle for one yet, or
        % update an existing one
        if box_number > length(handles.PageWindowRectangles)
            handles.PageWindowRectangles{box_number} = rectangle(current_axes,...
                'Position',  boxes(box_number, :),...
                'LineWidth', line_width,...
                'LineStyle', line_style,...
                'EdgeColor', box_color,...
                'PickableParts', 'none');
        else
            set(handles.PageWindowRectangles{box_number},...
                'Position',  boxes(box_number, :),...
                'EdgeColor', box_color,...
                'LineWidth', line_width,...
                'Visible', true)
        end

    end
end

% Make any extra boxes invisible
if roi
    for i = length(calls_in_page)+1:length(handles.FocusWindowRectangles)
        handles.FocusWindowRectangles{i}.Visible = false;
    end
else
    for i = length(calls_in_page)+1:length(handles.PageWindowRectangles)
        handles.PageWindowRectangles{i}.Visible = false;
    end
end

end

author: DrCoffey

repo: DeepSqueak

save_path: github-repos/MATLAB/DrCoffey-DeepSqueak


text:
function pde = Stokesdata0

%
nu = 1;
pde = struct('f',@f,'g',@g,'exactp', @exactp, ...
             'exactu', @exactu,'g_D', @g_D, 'nu', nu);

    function z = f(p)
        x = p(:,1); y = p(:,2);
        z(:,1) = -4*pi^2*(2*cos(2*pi*x)-1).*sin(2*pi*y)+x.^2;
        z(:,2) = 4*pi^2*(2*cos(2*pi*y)-1).*sin(2*pi*x);
    end

    function z = g(p)
        z = zeros(size(p,1),1);
    end

    function z = exactu(p)
        x = p(:,1); y = p(:,2);
        z(:,1) = (1-cos(2*pi*x)).*sin(2*pi*y);
        z(:,2) = -(1-cos(2*pi*y)).*sin(2*pi*x);
    end

    function z = exactp(p)
        x = p(:,1); % y = p(:,2);
        z = 1/3*x.^3;
    end

    function z = g_D(p) % Dirichlet boundary condition
        z = exactu(p);
    end
end

repo: ifem


text:
function displayFinalModels_LGG(pathExperiments,nameOutcomes,fSetNames,pathFig)
% -------------------------------------------------------------------------
% function displayFinalModels_LGG(pathExperiments,nameOutcomes,fSetNames,pathFig)
% -------------------------------------------------------------------------
% DESCRIPTION:
% This function displays the final models for all analyzed outcomes in the
% MRIliver study, in terms of: multivariable model response, model variables, and
% prediction performance estimation. See ref.[1] for more details.
% -------------------------------------------------------------------------
% REFERENCE:
% [1] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and
%     MRI texture features for the prediction of lung metastases in soft-tissue
%     sarcomas of the extremities. Physics in Medicine and Biology, 60(14),
%     5471-5496. doi:10.1088/0031-9155/60/14/5471
% -------------------------------------------------------------------------
% INPUTS:
% 1. pathExperiments: Full path to the directory containing all experiments.
%                     --> Ex: '/myProject/WORKSPACE/LOGISTIC_REGRESSION'
% 2. fSetNames: Cell of strings specifying the name of the type of feature
%               set analyzed.
%               --> Ex: {'T1W_T2W','T1W_T2F','T1CE_T2W','T1CE_T2F'}
% 3. nameOutcomes: Cell of strings specifying the outcome names to analyze.
%                  --> Ex: {'nonIDH1','IDHcodel','progression','lowGrade'}
% 4. pathFig: (optional).  Full path to where figure is saved without
%             displaying it. Put '' for displaying the figure and not
%             saving it to 'pathFig' (default).
%             --> Ex: ''
% -------------------------------------------------------------------------
% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>
% -------------------------------------------------------------------------
% HISTORY:
% - Creation: January 2017
%--------------------------------------------------------------------------
% STATEMENT:
% This file is part of masterScript_LiverMRI.m, a program to detect
% desmoplastic lesions via texture analysis of MRI images.
% --> Copyright (C) 2015-2017  Martin Vallieres
%
%    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/>.
% -------------------------------------------------------------------------

if nargin < 4
    pathFig = '';
end

startpath = pwd;
nOutcomes = length(nameOutcomes);

cd(pathExperiments), load('training')

for o = 1:nOutcomes
    cd([pathExperiments,'/FINAL_MODELS/',nameOutcomes{o},'/',fSetNames{o}])
    load('finalModel'), load('coeff'), load('modelCI'), load('response') % Variables 'finalModel', 'coeff',  'modelCI', and 'response' now present in MATLAB workspace
    finalModel.outcomeData = training.(nameOutcomes{o}).outcome;
    order = size(finalModel.Data,2);
    plotSigmoidalResponse_LGG(response,finalModel.outcomeData,modelCI,nameOutcomes{o},pathFig);
    fprintf(['\n\n --> THE FINAL MULTIVARIABLE MODEL FOR "%s" OUTCOME, "%s" FSET IS:\n\n'...
             '               g(x) =               \n'],nameOutcomes{o},fSetNames{o})
    for i = 1:order
        fprintf([num2str(coeff(i)),' X ',finalModel.Name{i},'\n'])
        fprintf('                    +               \n')
    end
    fprintf(['                   ',num2str(coeff(end)),'\n'])
    fprintf('\nWITH CORRESPONDING PREDICTION PERFORMANCE ESTIMATION:\n')
    try
        fprintf(['AUC = ',num2str(roundsd(finalModel.AUC,ceil(log10(finalModel.AUC632/roundsd(finalModel.SE_AUC,1))))),' ± ',num2str(roundsd(finalModel.SE_AUC,1)),'\n'])
        fprintf(['Sensitivity = ',num2str(roundsd(finalModel.Sensitivity,ceil(log10(finalModel.Sensitivity/roundsd(finalModel.SE_Sensitivity,1))))),' ± ',num2str(roundsd(finalModel.SE_Sensitivity,1)),'\n'])
        fprintf(['Specificity = ',num2str(roundsd(finalModel.Specificity,ceil(log10(finalModel.Specificity/roundsd(finalModel.SE_Specificity,1))))),' ± ',num2str(roundsd(finalModel.SE_Specificity,1)),'\n'])
    end
    % Calculation of prediction confidence probability
    indPos = find(finalModel.outcomeData); indNeg = find(~finalModel.outcomeData);
    prob = 1./(1 + exp(-response));
    probConfidence = (sum(prob(indPos)) + sum(1 - prob(indNeg)))/numel(prob); finalModel.probConfidence = probConfidence; save('finalModel','finalModel')
    fprintf('\n*** WITH CORRESPONDING PROBABILITY OF PREDICTION CONFIDENCE: %.2f ***\n',probConfidence);
    fprintf('\n\n')
end

cd(startpath)
end

author: mvallieres

repo: radiomics


text:
function dq = dqconj(dv,WHICHCONJ)

% DQCONJ   Dual quaternion conjugate
%
%      DQ = DQCONJ(DV) returns the dual quaternion conjugate of the dual
%      quaternion DV. DV (resp. DQ) is a 8-vector representing a dual
%      quaternion or an array 8*N (column i represents dual quaternion i)
%      where N is the number of dual quaternions. The default type of
%      conjugate is 'point' (see below). DQ has the same size as DV.
%
%       DQ = DQCONJ(DV,WHICHCONJ) returns the type of dual quaternion conjugate
%       corresponding to WHICHCONJ (DV = Q0+eps*Q1):
%         - 'point': mixed conjugate: dV* = Q0*-eps*Q1* (used for point
%         transformations).
%         - 'line': quaternion conjugate: dV* = Q0*+eps*Q1* (used for line
%         transformations).
%         - 'other': dual number conjugate: dV* = Q0-eps*Q1
%
% See also QCONJ, DQMULT

if nargin < 2
    WHICHCONJ = 'point'; % default is 'mixed' conjugate' (point transformation)
end

sdv = size(dv);
if sdv == [1 8]
    dv = dv.';
    sdv = size(dv);
end

% wrong size
if sdv(1) ~= 8
    error('DualQuaternion:DQconj:wrongsize',...
        '%d rows in array dv. It should be 8.',sdv(1));
end

n = sdv(2);
dq = sym(zeros(8,n));
switch WHICHCONJ
    case 'point' % % case of point transformation
        dq(1:4,:) = qconj(dv(1:4,:));
        dq(5:8,:) = -qconj(dv(5:8,:));
    case 'line' % case of line transformation
        dq(1:4,:) = qconj(dv(1:4,:));
        dq(5:8,:) = qconj(dv(5:8,:));
    case 'other' % dual number conjugate
        dq(1:4,:) = dv(1:4,:);
        dq(5:8,:) = -dv(5:8,:);
    otherwise
        error('DualQuaternion:DQconj:wrongsize',...
            'WHICHCONJ must be ''point'', ''line'' or ''other'' ');
end

author: Sable

repo: mcbench-benchmarks


text:
function got_displayed = warn_once(varargin)
% Emit a specific warning only once (per MATLAB session).
% GotDiplayed = warn_once(MessageId,Message,Arguments...)
%
% This function behaves like the built-in warning, except that a message with the given content is
% only emitted once per MATLAB session. The warnings can be reset with the command: clear warn_once
%
% In:
%   MessageId: optional message ID (see built-in warning)
%
%   Message : the message content, as in sprintf
%             special case: if this is 'clear', the memory of displayed warnings will be discarded
%
%   Arguments... : list of arguments that may be substituted into Message (like in sprintf)
%
% Out:
%   GotDisplayed : whether the message got displayed
%
% Examples:
%   % display a warning, but just once
%   warn_once('Error opening file %s',filename);
%
% See also:
%   warning
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2011-02-13

% Copyright (C) Christian Kothe, SCCN, 2011, christian@sccn.ucsd.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

persistent displayed_warnings;

if strcmp(varargin{1},'clear')
    % clear the stored messages
    displayed_warnings = [];
    return;
end

% determine the message content
if length(varargin) > 1 && any(varargin{1}==':') && ~any(varargin{1}==' ') && ischar(varargin{2})
    message_content = [varargin{1} sprintf(varargin{2:end})];
else
    message_content = sprintf(varargin{1:end});
end

% generate a hash of it
str = java.lang.String(message_content);
message_id = sprintf('x%.0f',str.hashCode()+2^31);

% and check if it had been displayed before
if ~isfield(displayed_warnings,message_id)
    % emit the warning
    warning(varargin{:});
    got_displayed = true;
    % remember to not display the warning again
    displayed_warnings.(message_id) = true;
else
    got_displayed = false;
end

repo: REST


text:
function [M] = spm_mci_priors (M)
% Quantities for computing log prior in subspace
% FORMAT [M] = spm_mci_priors (M)
%
% M.V               projection matrix
% M.ipC             Inverse prior cov in reduced space
% M.log_prior_t2    second term of log prior
% M.Np              dimension of reduced space
%__________________________________________________________________________
% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging

% Will Penny
% $Id: spm_mci_priors.m 6548 2015-09-11 12:39:47Z will $

if isstruct(M.pC)
    pC=full(diag(spm_vec(M.pC)));
else
    pC = M.pC;
end
V  = spm_svd(pC,exp(-32));
Np = size(V,2);
pC = V'*pC*V;
ipC = inv(pC);
log_prior_t2 = spm_logdet(ipC)/2-0.5*Np*log(2*pi);

M.ipC=ipC;
M.V=V;
M.log_prior_t2=log_prior_t2;
M.Np=Np;


text:
function [ b_labels ] = ml_2binary(labels)
%ML_2BINARY Transforms class labels to binary {-1,+1} class consisting of
%positive and negative class labels. This is needed for instance for binary
% class adaboost
%
%   input -----------------------------------------------------------------
%
%       o labels    : (N x 1), set of N labels with K classes
%
%   ouput -----------------------------------------------------------------
%
%       o b_lables  : (N x 1), set of N binary lables {-1,+1}
%
%

% find unique labels

N        = size(labels(:),1);
classes  = unique(labels);
b_lables = zeros(N,1);

if length(classes) == 2

    b_labels(labels == classes(1)) = -1;
    b_labels(labels == classes(2)) =  1;

else
    error('not yet implemented');

end

end

author: epfl-lasa


text:
%%% This script is used to read the binary file produced by the DCA1000
%%% and Mmwave Studio
%%% Command to run in Matlab GUI -readDCA1000('<ADC capture bin file>')
function [retVal] = readDCA1000(folder_locaion, numADCSamples)
%% global variables
% change based on sensor config
% numADCSamples = 128; % number of ADC samples per chirp should be variable
numADCBits = 16; % number of ADC bits per sample
numRX = 4; % number of receivers
numLanes = 2; % do not change. number of lanes is always 2
max_numChirps = 459000;
isReal = 0; % set to 1 if real only data, 0 if complex data0
adcData = [];
%% read file
% search all files under this folder
files = dir(folder_locaion); % find all the files under the folder
n_files = length(files);
processed_files = [3:n_files];

for index = 1:length(processed_files)
    inum = processed_files(index);
    file_name = files(inum).name;
    file_location = strcat(folder_locaion,'/',file_name);
    % read .bin file
    fid = fopen(file_location,'r');
    adcData_tmp = fread(fid, 'int16');
    adcData = [adcData; adcData_tmp];
end

% if 12 or 14 bits ADC per sample compensate for sign extension
if numADCBits ~= 16
    l_max = 2^(numADCBits-1)-1;
    adcData(adcData > l_max) = adcData(adcData > l_max) - 2^numADCBits;
end
fclose(fid);
fileSize = size(adcData, 1);
% real data reshape, filesize = numADCSamples*numChirps
if isReal
    numChirps = fileSize/numADCSamples/numRX;
    LVDS = zeros(1, fileSize);
    %create column for each chirp
    LVDS = reshape(adcData, numADCSamples*numRX, numChirps);
    %each row is data from one chirp
    LVDS = LVDS.';
else
    % for complex data
    % filesize = 2 * numADCSamples*numChirps
    numChirps = fileSize/2/numADCSamples/numRX;
    LVDS = zeros(1, fileSize/2);
    %combine real and imaginary part into complex data
    %read in file: 2I is followed by 2Q
    counter = 1;
    for i=1:4:fileSize-1
        LVDS(1,counter) = adcData(i) + sqrt(-1)*adcData(i+2);
        LVDS(1,counter+1) = adcData(i+1)+sqrt(-1)*adcData(i+3);
        counter = counter + 2;
    end
    % create column for each chirp
    LVDS = reshape(LVDS, numADCSamples*numRX, numChirps);
    %each row is data from one chirp
%     LVDS = LVDS.'; % make comment to avoid the 'out of memory'
end

% organize data per RX
clear adcData
clear adcData_tmp
if numChirps <= max_numChirps % 900 frames
    adcData = zeros(numRX,numChirps*numADCSamples);
    for row = 1:numRX
        for i = 1: numChirps
            adcData(row, (i-1)*numADCSamples+1:i*numADCSamples) = LVDS((row-1)*numADCSamples+1:row*numADCSamples,i);
        end
    end
    retVal = adcData;
else
    adcData1 = zeros(numRX,max_numChirps*numADCSamples);
    for row = 1:numRX
        for i = 1:max_numChirps
            adcData1(row, (i-1)*numADCSamples+1:i*numADCSamples) = LVDS((row-1)*numADCSamples+1:row*numADCSamples,i);
        end
    end

    left_numChirps = numChirps - max_numChirps;
    adcData2 = zeros(numRX,left_numChirps*numADCSamples);
    for row = 1:numRX
        for i = 1:left_numChirps
            adcData2(row, (i-1)*numADCSamples+1:i*numADCSamples) = LVDS((row-1)*numADCSamples+1:row*numADCSamples,i+max_numChirps);
        end
    end

    clear LVDS
    retVal = [adcData1, adcData2];

% return receiver data
% data format is [Rx; chirps]
end

author: Xiangyu-Gao


text:
function neqn = p39_neqn ( )

%*****************************************************************************80
%
%% P39_NEQN returns the number of equations for problem P39.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer NEQN, the number of equations.
%
  neqn = 1;

  return
end


text:
function x = p19_root ( i )

%*****************************************************************************80
%
%% P19_ROOT returns a root for problem 19.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 January 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer I, the index of the requested root.
%
%    Output, real X, the value of the root.
%
  if ( i == 1 )
    x = 0.33186603357456253747;
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'P19_ROOT - Fatal error!\n' );
    fprintf ( 1, '  Illegal root index = %d\n', i );
    error ( 'P19_ROOT - Fatal error!' );
  end

  return
end


text:
function [files, metadata] = experiment_unsupervised(tracker, sequence, directory, parameters, scan)

    files = {};
    metadata.completed = true;
	cache = get_global_variable('experiment_cache', true);
	silent = get_global_variable('experiment_silent', false);

    defaults = struct('repetitions', 15);
    context = struct_merge(parameters, defaults);
    metadata.deterministic = false;

    time_file = fullfile(directory, sprintf('%s_time.txt', sequence.name));

    times = zeros(sequence.length, context.repetitions);

    if ~scan && cache && exist(time_file, 'file')
        times = csvread(time_file);
    end;

	r = context.repetitions;

	if isfield(tracker, 'metadata') && isfield(tracker.metadata, 'deterministic') && tracker.metadata.deterministic
		r = 1;
	end

	check_deterministic = ~(scan && nargout < 2); % Ensure faster execution when we only want a list of files by ommiting determinisim check.

    for i = 1:r

        result_file = fullfile(directory, sprintf('%s_%03d.txt', sequence.name, i));

        if cache && exist(result_file, 'file')
            files{end+1} = result_file; %#ok<AGROW>
            values = dir(fullfile(directory, sprintf('%s_%03d_*.value', sequence.name, i)));
            files(end+1:end+length(values)) = cellfun(@(x) fullfile(directory, x.name), num2cell(values), 'UniformOutput', false);
            continue;
        end;

        if check_deterministic && i == 4 && is_deterministic(sequence, 3, directory)
            if ~silent
                print_debug('Detected a deterministic tracker, skipping remaining trials.');
            end;
            metadata.deterministic = true;
            break;
        end;

        if scan
            metadata.completed = false;
            continue;
        end;

        print_indent(1);

        print_text('Repetition %d', i);

        context.repetition = i;

		data.sequence = sequence;
		data.index = 1;
		data.context = context;
		data.result = repmat({0}, sequence.length, 1);
		data.timing = nan(sequence.length, 1);
        data.properties = properties_create(sequence);
        data.channels = {};

		data = tracker_run(tracker, @callback, data);

	    times(:, i) = data.timing;
	    write_trajectory(result_file, data.result);
		csvwrite(time_file, times);

        properties_save(directory, sprintf('%s_%03d', sequence.name, i), data.properties);

        files{end+1} = result_file; %#ok<AGROW>
        values = dir(fullfile(directory, sprintf('%s_%03d_*.value', sequence.name, i)));
        files(end+1:end+length(values)) = cellfun(@(x) fullfile(directory, x.name), num2cell(values), 'UniformOutput', false);

        print_indent(-1);
    end;

    if exist(time_file, 'file')
        files{end+1} = time_file;
    else
        metadata.completed = false;
    end;

end

function [image, region, properties, data] = callback(state, data)

	region = [];
	image = [];
    properties = struct();

    if isempty(data.channels)
        if ~all(ismember(state.channels, fieldnames(data.sequence.channels)));
            error('Sequence does not contain all channels required by the tracker.');
        end;
        data.channels = state.channels;
    end;

	% Handle initial frame (initialize for the first time)
	if isempty(state.region)
		region = data.sequence.initialize(data.sequence, data.index, data.context);
		image = sequence_get_image(data.sequence, data.index, data.channels);
		return;
	end;

	% Store initialization
	if data.index == 1
		data.result{data.index} = 1;
	else
		data.result{data.index} = state.region;
	end;
	data.timing(data.index) = state.time;

    data.properties = properties_set(data.properties, data.index, state.properties);

	data.index = data.index + 1;

	% End of sequence
	if data.index > data.sequence.length
		return;
	end

    image = sequence_get_image(data.sequence, data.index, data.channels);

end

author: votchallenge

repo: toolkit-legacy


text:
classdef PTKGetContextForLobe < PTKPlugin
    % PTKGetContextForLobe. Plugin for finding the region of interest for a lobe.
    %
    %     This is a plugin for the Pulmonary Toolkit. Plugins can be run using
    %     the gui, or through the interfaces provided by the Pulmonary Toolkit.
    %     See PTKPlugin.m for more information on how to run plugins.
    %
    %     Plugins should not be run directly from your code.
    %
    %     PTKGetContextForLobe runs the plugin PTKLeftAndRightLungs to segment
    %     the left and right lungs, then calls the library function
    %     PTKGetLobeROI to extract the region of interest for the required lobe.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2012.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    properties
        ButtonText = 'Lobe<BR>ROI'
        ToolTip = 'Fetches the ROI for a lobe context'
        Category = 'Context'

        AllowResultsToBeCached = true
        AlwaysRunPlugin = false
        Context = PTKContextSet.Lobe
        PluginType = 'ReplaceImage'
        HidePluginInDisplay = true
        FlattenPreviewImage = false
        PTKVersion = '2'
        ButtonWidth = 6
        ButtonHeight = 2
        GeneratePreview = true

        MemoryCachePolicy = 'Permanent'
        DiskCachePolicy = 'Permanent'
    end

    methods (Static)
        function results = RunPlugin(dataset, context, reporting)
            lobe_mask = dataset.GetResult('PTKLobes', PTKContext.LungROI);
            results = PTKGetLobeROI(lobe_mask, context, reporting);
        end
    end
end

author: tomdoel

repo: pulmonarytoolkit


text:
function varargout = legendflex(varargin)
%LEGENDFLEX Creates a more flexible legend
%
% legendflex(M, param1, val1, ...)
% legendflex(h, M, param1, val1, ...)
% [legend_h,object_h,plot_h,text_str] = legendflex(...)
%
% This offers a more flexible version of the legend command.  It offers a
% different method of positioning the legend, as well as options to:
%
%   - organize legend text and symbols in a grid with a specified number of
%     rows and/or columns
%   - rescale the horizontal space used by each legend symbol
%   - create multiple legends for the same axis
%   - add a title to the legend within the legend box
%
% Unlike in the default legend command, where the legend is positioned
% relative to the labeled objects' parent axis according to one of 16
% location strings, this function positions the legend based on two anchor
% points (one on either the figure or a child object of a figure, and one
% on the legend itself) and a buffer (or offset) between these two anchor
% points. The anchor points refer to the corners and centers of each
% side of the box surrounding the reference object and the legend itself;
% they can be refered to either as numbers (1-8, clockwise from northwest
% corner) or strings ('nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w').  The
% position of the legend is determined by these two points and the distance
% between them, defined in the 'buffer' variable, which by default is
% measured in pixels.  So the combination of
%
%  (..., 'ref', gca, 'anchor', [3 3], 'buffer', [-10 -10])
%
% means that you want the northeast corner of the current axis to be
% aligned with the northeast corner of the legend, but with the legend
% shifted 10 pixels to the left and down.
%
% This method of positioning can be particularly useful when labeling a
% figure that includes many subplots that share a common color scheme,
% where the "best" location for a legend is not necessarily within the
% bounds of an axis.  Unlike the legend command, the axes in the figure are
% never resized (and it is up to the user to check that the legend fits on
% the figure in the specified location).  In addition to being easier than
% manually positioning a legend, this function updates the legend location
% when the figure is resized, preserving the desired alignment.  The
% following anchor/buffer combinations, when used with the default
% reference and a buffer unit of pixels, approximately replicate the
% typical legend locations:
%
% Specifier              Anchor    Buffer
%
% north                  [2 2]     [  0 -10]
% south                  [6 6]     [  0  10]
% east                   [4 4]     [-10   0]
% west                   [8 8]     [ 10   0]
% northeast              [3 3]     [-10 -10]
% northwest              [1 1]     [ 10 -10]
% southeast              [5 5]     [-10  10]
% southwest              [7 7]     [ 10  10]
% northoutside*          [2 6]     [  0  10]
% southoutside*          [6 2]     [  0 -10]
% eastoutside*           [3 8]     [ 10   0]
% westoutside*           [8 3]     [-10   0]
% northeastoutside*      [3 1]     [ 10   0]
% northwestoutside*      [1 3]     [-10   0]
% southeastoutside*      [5 7]     [ 10   0]
% southwestoutside*      [7 5]     [-10   0]  *placed outside axis rather
%                                              than resizing plot box
%
% This function should support all types of plot objects.
%
% Updates to labeled line and patch properties should be reflected in the
% legend.  In pre-R2014b versions of Matlab (those that use the old
% non-object graphics handles), properties of more complex legend labels,
% such as contours, quivers, bars, etc.) will also be synced to the legend;
% however, at this time, the code doesn't update properties for anything
% other than lines and patches in R2014b+ (haven't found a good way to
% listen for changes to the properties of the other graphics object types).
%
% A note on resizing: This function assigns a resize function to the parent
% figure to maintain the position of the legend (in terms of anchor
% location and buffer) as the figure size changes.  If you manually resize
% the legend, this function will respect changes to height, width, and
% units (though I don't recommend changing the units to 'normalized', as
% this can cause the text and symbols to overflow the legend box on
% resize).  It will not respect manual repositioning when resizing, since
% it assumes you want to maintain the anchor/buffer prescription used to
% create it.  Overall, I've tried to make this resize as unobtrusive as
% possible; if your figure already has a resize function at the time you
% apply it, that behavior is inherited, with the legend-resize called
% afterward.  If you plan to further modify the figure's resize function
% post-legendflex and want to maintain repositioning of the legends,
% retrieve the resize function via hfun = get(hfig, 'ResizeFcn'), pass it
% to the new resize function, and invoke it via feval(oldfun, h, ed), where
% h and ed are the default variables passed by a callback function.
%
% Input variables:
%
%   M:          cell array of strings, labels for legend
%
%   h:          handle of axis or handle(s) of object(s) to be labeled.  If
%               this is an axis handle, all children of the axis will be
%               included in the legend.  If not included, current axis is
%               used.
%
% Optional input variables (passed as parameter/value pairs): [default]
%
%   ncol:       number of columns, or 0 to indicate as many as necessary
%               given the # of labeled objects [1 if nrow is 0, 0
%               otherwise]
%
%   nrow:       number of rows, or 0 to indicate as many as necessary
%               given the # of labeled objects [0]
%
%   ref:        handle of object used to position the legend. This can be
%               either a figure or a child object of a figure (and does not
%               need to relate in any way to the objects being labeled).
%               If not included, the reference will be to the axis that a
%               normal legend would be associated with (usually the parent
%               axis of the labeled objects, unless objects from multiple
%               axes are passed, in which case it's the parent object of
%               the first labeled object).
%
%   anchor:     1 x 2 array specifying which points of the reference object
%               and new legend, respectively, to anchor to each other.
%               Anchor points can be described using either numbers (in a 1
%               x 2 double array) or directional strings (in a 1 x 2 cell
%               array) as follows:
%               1:  'nw'    upper left corner
%               2:  'n'     center of top edge
%               3:  'ne'    upper right corner
%               4:  'e'     center of right edge
%               5:  'se'    bottom right corner
%               6:  's'     center of bottom edge
%               7:  'sw'    bottom left corner
%               8:  'w'     center of left edge
%
%               [[3 3], i.e. {'ne' 'ne'}]
%
%   buffer:     1 x 2 array of horizontal and vertical distance,
%               respectively, from the reference anchor point to the legend
%               anchor point. Distance is measured in units specified by
%               bufferunit. [[-10 -10]]
%
%   bufferunit: unit for buffer distance.  Note that this property only
%               affects the units used to position the legend, not the
%               units for the legend itself (which is always a fixed size,
%               based on the space needed to encapsulate the specified
%               symbols and text).  The 'normalized' units are normalized
%               to size of the figure. ['pixels']
%
%   box:        'on' or 'off', specifies whether to enclose legend objects
%               in a box ['on']
%
%   xscale:     scalar value indicating scale factor to apply to the width
%               required by each symbol, relative to the size used by
%               legend. For example, 0.5 will shorten the lines/patches by
%               half. [1]
%
%   title:      A title string to be added inside the legend box, centered,
%               above all legend entries.  This can be either a string or a
%               cell array of strings; the latter will produce a multi-line
%               title. If empty, no title is added.  ['']
%
%   padding:    1 x 3 array, pixel spacing added to beginning of each
%               column (before symbol), between symbol and text, and after
%               text, respectively.  Usually, the default provides the
%               spacing typical of a regular legend, but occassionally the
%               extent properties wrap a little too close to text, making
%               things look crowded; in these cases you can try unsquishing
%               (or squishing, via use of negative values) things via this
%               parameter. [2 1 1]
%
%   nolisten:   logical scalar.  If true, don't add the event listeners.
%               The event listeners update the legend objects when you
%               change a property of the labeled objects (such as line
%               style, color, etc.).  However, the updating requires the
%               legend to be redrawn, which can really slow things down,
%               especially if you're labelling lots of objects that get
%               changed together (if you change the line width of 100
%               labeled lines, the legend gets redrawn 100 times).  In more
%               recent releases, this also occurs when printing to file, so
%               I recommend setting this to true if you plan to print a
%               legend with a large number of labeled objects.  The legend
%               will still be redrawn on figure resize regardless of the
%               value of this parameter. [false]
%
%   In addition to these legendflex-specific parameters, this function will
%   accept any parameter accepted by the original legend function (e.g.
%   font properties) except 'location', 'boxon', 'boxoff', or 'hide'.
%
% Output variables:
%
%   legend_h:   handle of the legend axis.  It is not linked to an axis or
%               graphics objects in the same way as a Matlab legend.
%               However, on figure resize, all properties of the legend
%               objects are checked for changes, so adjusting the figure
%               size can re-link the legend to the labeled objects after
%               you have made changes to those objects.
%
%   object_h:   handles of the line, patch, and text graphics objects
%               created in the legend
%
%   plot_h:     handles of the lines and other objects labeled in this
%               legend
%
%   text_str:   cell array of the text strings used in the legend
%
%
% Example:
%
% % Replicating an example from legend.m:
%
% figure;
% b = bar(rand(10,5),'stacked'); colormap(summer); hold on
% x = plot(1:10,5*rand(10,1),'marker','square','markersize',12,...
%          'markeredgecolor','y','markerfacecolor',[.6 0 .6],...
%          'linestyle','-','color','r','linewidth',2); hold off
% lbl = {'Carrots','Peas','Peppers','Green Beans','Cucumbers','Eggplant'};
%
% % Rather than covering up data or resizing the axis, let's squeeze the
% % legend into the margin at the top of the figure;
%
% legendflex([b,x], lbl, 'ref', gcf, ...
%                        'anchor', {'n','n'}, ...
%                        'buffer',[0 0], ...
%                        'nrow',2, ...
%                        'fontsize',8);

% Copyright 2011-2014 Kelly Kearney

% Detemine whether HG2 is in use

hg2flag = ~verLessThan('matlab', '8.4.0');
r2016aflag = ~verLessThan('matlab', '9.0.0');
r2013bflag = ~verLessThan('matlab', '8.2.0');

%-------------------
% Parse input
%-------------------
%
% allinput = varargin; % Save for callback later
%
% islegin = false(size(varargin));

% First inputs must be either:
% (M, ...)
% (h, M, ...)

narginchk(1,Inf);

% Split input into the variables that will be passed to legend (handles and
% labels) and everything else

handlepassed = all(ishandle(varargin{1})); % for HG1/HG2

iscellstr = @(x) cellfun(@(y) ischar(y), x); % For now...
% iscellstr = @(x) cellfun(...
%     @(y) ischar(y) || (iscell(y) && all(cellfun(@ischar,y))), x); % for multi-line?

if handlepassed
    legin = varargin(1:2);
    if ~iscell(legin{2}) || ~all(iscellstr(legin{2}))
        error('Legend labels must be a cell array of strings');
    end
    pv = varargin(3:end);
else
    legin = varargin(1);
    if ~iscell(legin{1}) || ~all(iscellstr(legin{1}))
        if isnumeric(legin{1})
            error('Unable to parse input 1; check that handle(s) exist');
        else
            error('Legend labels must be a cell array of strings');
        end
    end
    pv = varargin(2:end);
end

% Parse my optional properties

if hg2flag
    defref = gobjects(0);
else
    defref = NaN;
end

if r2013bflag
    addParamMethod = 'addParameter';
else
    addParamMethod = 'addParamValue';
end

p = inputParser;
p.(addParamMethod)('xscale',     1,         @(x) validateattributes(x, {'numeric'}, {'nonnegative','scalar'}));
p.(addParamMethod)('ncol',       0,         @(x) validateattributes(x, {'numeric'}, {'scalar', 'integer'}));
p.(addParamMethod)('nrow',       0,         @(x) validateattributes(x, {'numeric'}, {'scalar', 'integer'}));
p.(addParamMethod)('ref',        defref,    @(x) validateattributes(x, {'numeric','handle'}, {'scalar'}));
p.(addParamMethod)('anchor',     [3 3],     @(x) validateattributes(x, {'numeric','cell'}, {'size', [1 2]}));
p.(addParamMethod)('buffer',     [-10 -10], @(x) validateattributes(x, {'numeric'}, {'size', [1 2]}));
p.(addParamMethod)('bufferunit', 'pixels',  @(x) validateattributes(x, {'char'}, {}));
p.(addParamMethod)('box',        'on',      @(x) validateattributes(x, {'char'}, {}));
p.(addParamMethod)('title',      '',        @(x) validateattributes(x, {'char','cell'}, {}));
p.(addParamMethod)('padding',    [2 1 1],   @(x) validateattributes(x, {'numeric'}, {'size', [1 3]})); % 'nonnegative'
p.(addParamMethod)('nolisten',   false,     @(x) validateattributes(x, {'logical'}, {'scalar'}));
p.KeepUnmatched = true;

p.parse(pv{:});
Opt = p.Results;

% Any parameters that don't match mine are assumed to be a legend property.
%  If not, legend will handle the error when I call it.

Extra = p.Unmatched;
extra = [fieldnames(Extra) struct2cell(Extra)];
extra = extra';

% Validate that units and box inputs are correct

validatestring(Opt.bufferunit, {'pixels','normalized','inches','centimeters','points','characters'}, 'legendflex', 'bufferunit');
validatestring(Opt.box, {'on', 'off'}, 'legendflex', 'box');

% Translate anchor strings to numbers, if necessary

if iscell(Opt.anchor)
    [blah, Opt.anchor] = ismember(Opt.anchor, {'nw','n','ne','e','se','s','sw','w'});
    if ~all(blah)
        error('Anchor must be 1 x 2 cell array of strings: n, e, s, w, ne, nw, se, sw');
    end
else
    validateattributes(Opt.anchor, {'numeric'}, {'integer', '<=', 8}, 'legendflex', 'anchor');
end

% Create a temporary legend to get all the objects

S = warning('off', 'MATLAB:legend:PlotEmpty');
if r2016aflag
    % The new legend objects are pretty opaque... even diving into the
    % undocumented properties, I haven't been able to find the handles of
    % the legend sub-components (lines, text, etc).  So I need to stick to
    % the legacy version, which creates an axis object rather than legend
    % object. Legacy version has bug in text properties parsing, though, so
    % need to work around that too: use the new-style legend object to get
    % proper text properties, then use those to alter the buggy old-style
    % legend.
    tmp = legend(legin{:}, extra{:}, 'location', 'northeast');
    textProps = {'FontAngle','FontName','FontSize','FontUnits','FontWeight','Interpreter'};
    tprop = get(tmp, textProps);
    delete(tmp);
    wtmp = warning('off', 'MATLAB:handle_graphics:exceptions:SceneNode'); % silence Latex interpreter thing
    [h.leg, h.obj, h.labeledobj, h.textstr] = legend(legin{:}, extra{:}, 'location', 'northeast');
    warning(wtmp);
    nobj = length(h.labeledobj);
    for it = 1:length(textProps)
        set(h.obj(1:nobj), textProps{it}, tprop{it});
    end
else
    [h.leg, h.obj, h.labeledobj, h.textstr] = legend(legin{:}, extra{:}, 'location', 'northeast');
    nobj = length(h.labeledobj);
end
warning(S);

if nobj == 0
    warning('Plot empty; no legend created');
    return
end

% There's a bug in R2014b-R2015a that causes rendering issues if a contour
% object is included in a legend and legend is called with more than one
% output. For some reason, the rendering issues disappear only if the
% contour object(s) is listed last in the legend.  So for now, my
% workaround for this is to change the order of the legend labels as
% necessary.  Issue appears to be fixed in 2015b.

iscont = strcmp(get(h.labeledobj, 'type'), 'contour');
cbugflag = ~verLessThan('matlab', '8.4.0') && verLessThan('matlab', '8.6.0') && any(iscont);

if cbugflag

    if length(legin) == 1
        legin = {h.labeledobj legin{1}};
    end

    delete(h.leg);

    [srt, isrt] = sort(iscont);
    legin{1} = legin{1}(isrt);
    legin{2} = legin{2}(isrt);

    [h.leg, h.obj, h.labeledobj, h.textstr] = legend(legin{:}, extra{:}, 'location', 'northeast');

end

% # rows and columns

if (Opt.ncol == 0) && (Opt.nrow == 0)
    Opt.ncol = 1;
    Opt.nrow = nobj;
elseif (Opt.ncol == 0)
    Opt.ncol = ceil(nobj./Opt.nrow);
elseif (Opt.nrow == 0)
    Opt.nrow = ceil(nobj./Opt.ncol);
end
if Opt.ncol*Opt.nrow < nobj
    error('Number of legend entries greater than specified grid allows; change ncol and/or nrow');
end

% Reference object

if hg2flag

    if isempty(Opt.ref)

        if all(ishandle(legin{1}))
            tmp = ancestor(legin{1}, 'axes');
            if iscell(tmp)
                Opt.ref = tmp{1};
            else
                Opt.ref = tmp(1);
            end
        else
            Opt.ref = gca;
        end

    end
else
    if isnan(Opt.ref)
        tmp = get(h.leg, 'UserData');
        Opt.ref = tmp.PlotHandle;
    end
end
if ~ishandle(Opt.ref)
    error('Input ref must be a graphics handle');
end

% Box

Opt.box = strcmpi('on', Opt.box);

% Convert units to getpos abbreviations

unittable = {...
    'px'  'Pixels'
    'nz'  'Normalized'
    'in'  'Inches'
    'cm'  'Centimeters'
    'pt'  'Points'
    'ch'  'Characters'};
Opt.bufunit = unittable{strcmpi(unittable(:,2),Opt.bufferunit),1};

% Check for title

addtitle = ~isempty(Opt.title);

%-------------------
% New placement of
% everything in
% legend
%-------------------

% Determine parent figure

figh = ancestor(Opt.ref, 'figure');
currax = get(figh, 'currentaxes');

% Calculate row height

legpospx = getpos(h.leg, 'px');

% rowHeight = legpospx(4)/nobj;
vmarginNm =  0.275/nobj;
vmarginPx = legpospx(4) * vmarginNm;

rowHeightNm = (1 - vmarginNm)/nobj;
rowHeight = rowHeightNm .* legpospx(4);

% Determine width needed for each text string

if nobj == 1
    textExtent = get(h.obj(1:nobj), 'Extent');
else
    textExtent = cell2mat(get(h.obj(1:nobj), 'Extent'));
end
textWidthPx  = textExtent(:,3) .* legpospx(3);
textHeightPx = textExtent(:,4) .* legpospx(4);
textWidthNm = textExtent(:,3);

% Calculate horizontal space needed for symbols

symbolWidthPx = textExtent(1,1) .* legpospx(3) * Opt.xscale;
symbolWidthNm = textExtent(1,1);

% Calculate column width needed for 2px-symbol-1px-text-1px

colWidth = zeros(Opt.ncol*Opt.nrow,1);
colWidth(1:nobj) = textWidthPx + symbolWidthPx + sum(Opt.padding);
colWidth = reshape(colWidth, Opt.nrow, Opt.ncol);
colWidth = max(colWidth,[],1);

% If title is added, figure out how much space it will need

if addtitle
    textProps = {'FontAngle','FontName','FontSize','FontUnits','FontWeight','Interpreter'};
    textVals = get(h.obj(1), textProps);
    ttlprops = [textProps; textVals];

    fpos = getpos(figh, 'px');
    figtmp = figure('units','pixels','position',[0 0 fpos(3:4)],'visible','off');
    axes('parent',figtmp,'position',[0 0 1 1],'xlim',[0 fpos(3)],'ylim',[0 fpos(4)]);
    tmp = text(0,0,Opt.title, ttlprops{:}, 'horiz', 'left', 'vert', 'bottom');
    ttlex = get(tmp, 'extent');
    ttlwidth = ceil(ttlex(3)) + 4; % Add a little padding
    ttlheight = ceil(ttlex(4));

    if ttlwidth > sum(colWidth)
        colWidth(end) = colWidth(end) + (ttlwidth-sum(colWidth));
    end
    close(figtmp);
end

% Locate bottom left corner of each legend symbol, text box, and title

xsymbnew = [0 cumsum(colWidth(1:end-1))]+Opt.padding(1);
ysymbnew = (rowHeight*Opt.nrow + vmarginPx)-(1:Opt.nrow)*rowHeight;
[xsymbnew, ysymbnew] = meshgrid(xsymbnew, ysymbnew);
xsymbnew = xsymbnew(1:nobj);
ysymbnew = ysymbnew(1:nobj);

xtext = xsymbnew + Opt.padding(2) + symbolWidthPx;
ytext = ysymbnew;% + 1;

xsymbold = zeros(nobj,1);
ysymbold = 1 - (1/nobj)*(1:nobj);

wnewleg = sum(colWidth);
hnewleg = rowHeight*Opt.nrow + vmarginPx;

if addtitle
    xttl = wnewleg/2;
    yttl = hnewleg;
    hnewleg = hnewleg + ttlheight;
end

% Get legend position in bufferunit and translate to pixels

legpos = positionleg(Opt.ref, wnewleg, hnewleg, Opt.anchor, Opt.buffer, Opt.bufunit);
tmpax = axes('units', Opt.bufferunit, 'position', legpos,'visible','off');
legpos = getpos(tmpax, 'px');
delete(tmpax);

%-------------------
% Create legend
%-------------------

% Create the legend axis

hnew.leg = axes('units', 'pixels', ...
               'position', legpos, ...
               'xlim', [0 legpos(3)], ...
               'ylim', [0 legpos(4)], ...
               'xtick', [], ...
               'ytick', [], ...
               'box', 'on', ...
               'parent', figh);

% Copy the text strings to the new legend

textProps = {'FontAngle','FontName','FontSize','FontUnits','FontWeight','Interpreter','HorizontalAlignment','VerticalAlignment'};
textVals = get(h.obj(1:nobj), textProps);

if hg2flag
    hnew.obj = gobjects(size(h.obj));
else
    hnew.obj = zeros(size(h.obj));
end
for it = 1:nobj
    props = [textProps; textVals(it,:)];
    hnew.obj(it) = text(xtext(it), ytext(it), h.textstr{it}, props{:}, ...
                        'horizontalalignment', 'left', ...
                        'verticalalignment', 'bottom');
end

% Copy the symbols to the new legend

nsymbol = length(h.obj) - nobj;

for ii = 1:nsymbol

    if strcmp(get(h.obj(nobj+ii), 'type'), 'hggroup')

        tag = get(h.obj(nobj+ii),'Tag');
        if ~isempty(tag)
            [blah, idx] = ismember(tag,h.textstr);
        end

        chld = findall(h.obj(nobj+ii), 'type', 'line', '-or', 'type', 'patch');
        for ic = 1:length(chld)
            xy = get(chld(ic), {'xdata', 'ydata'});

            xnorm = xy{1}./symbolWidthNm;
            ynorm = (xy{2}- (1-idx*rowHeightNm))./rowHeightNm;

            xnew = xnorm * symbolWidthPx + xsymbnew(idx);
            ynew = ynorm * rowHeight     + ysymbnew(idx);

            set(chld(ic), 'xdata', xnew, 'ydata', ynew);
        end

        hnew.obj(nobj+ii) = copyobj(h.obj(nobj+ii), hnew.leg);

    else

        hnew.obj(nobj+ii) = copyobj(h.obj(nobj+ii), hnew.leg);

        tag = get(h.obj(nobj+ii),'Tag');
        if ~isempty(tag) % assumes empty tags indicate repetition of previous tag (true pre-2014b)
            [blah, idx] = ismember(tag,h.textstr);
        end

        xy = get(h.obj(nobj+ii), {'xdata', 'ydata'});

        xnorm = xy{1}./symbolWidthNm;
        ynorm = (xy{2}- (1-idx*rowHeightNm))./rowHeightNm;

        xnew = xnorm * symbolWidthPx + xsymbnew(idx);
        ynew = ynorm * rowHeight     + ysymbnew(idx);

        set(hnew.obj(nobj+ii), 'xdata', xnew, 'ydata', ynew);

    end

end

% Add title

if addtitle
    text(xttl, yttl, Opt.title, ttlprops{:}, 'horiz', 'center', 'vert', 'bottom');
end

% Add box or hide axis

if Opt.box
    set(hnew.leg, 'box', 'on');
else
    if hg2flag
        set(hnew.leg, 'box', 'off', 'color', 'none', 'xcolor', 'none', 'ycolor', 'none');
    else
        set(hnew.leg, 'visible', 'off');
    end
end

% Delete the temporary legend

delete(h.leg);

% Return focus to previously-current axis

set(figh, 'currentaxes', currax);
drawnow; % Not sure why this is necessary for the currentaxes to take effect, but it is

% Fix for vertical-alignment issue: This solution still isn't perfect, but
% it seems to help for most Interpreter-none and Interpreter-latex cases.
% The TeX interpreter still places sub- and superscripts too high/low... no
% robust fix found for that yet.
%
% TODO: need to add proper calcs for when title included
%
% Thanks to S�ren Enemark for this suggestion.

if ~addtitle
    try % TODO: Crashing on some edge cases
        textobj = hnew.obj(1:nobj);
        yheight = get(hnew.leg, 'ylim');
        yheight = yheight(2);

        ylo = get(textobj(Opt.nrow), 'extent');
        ylo = ylo(2);
        yhi = get(textobj(1), 'extent');
        yhi = sum(yhi([2 4]));
        dy = yheight/2 - 0.5*(ylo + yhi);
        for ii = 1:length(textobj)
            pos = get(textobj(ii), 'position');
            set(textobj(ii), 'position', pos + [0 dy 0]);
        end
    end
end

%-------------------
% Callbacks and
% listeners
%-------------------

% Save some relevant variables in the new legend axis's application data

Lf.ref        = Opt.ref;
Lf.w          = wnewleg;
Lf.h          = hnewleg;
Lf.anchor     = Opt.anchor;
Lf.buffer     = Opt.buffer;
Lf.bufunit    = Opt.bufunit;
Lf.bufferunit = Opt.bufferunit;
Lf.plotobj    = h.labeledobj;
Lf.legobj     = hnew.obj;

setappdata(hnew.leg, 'legflex', Lf);

% Resize listeners

addlistener(hnew.leg, 'Position', 'PostSet', @(src,evt) updatelegappdata(src,evt,hnew.leg));
if hg2flag && strcmp(Lf.ref.Type, 'figure')
    addlistener(Lf.ref, 'SizeChanged', @(src,evt) updatelegpos(src,evt,hnew.leg));
else
    addlistener(Lf.ref, 'Position', 'PostSet', @(src,evt) updatelegpos(src,evt,hnew.leg));
end
rsz = get(figh, 'ResizeFcn');
if isempty(rsz) % No previous resize function
    set(figh, 'ResizeFcn', @updatelegfigresize);
else
    if ~iscell(rsz)
        rsz = {rsz};
    end
    hasprev = cellfun(@(x) isequal(x, @updatelegfigresize), rsz);
    if ~hasprev
        rsz = {rsz{:} @updatelegfigresize};
        set(figh, 'ResizeFcn', {@wrapper, rsz});
    end
end

if ~Opt.nolisten

    % Run the resync function if anything changes with the labeled objects

    objwatch = findall(h.labeledobj, 'type', 'line', '-or', 'type', 'patch');

    for ii = 1:length(objwatch)
        switch lower(get(objwatch(ii), 'type'))
            case 'line'
                triggerprops = {'Color','LineStyle','LineWidth','Marker','MarkerSize','MarkerEdgeColor','MarkerFaceColor'};
                addlistener(objwatch(ii), triggerprops, 'PostSet', @(h,ed) resyncprops(h,ed,hnew.leg));
            case 'patch'
                triggerprops = {'CData','CDataMapping','EdgeAlpha','EdgeColor','FaceAlpha','FaceColor','LineStyle','LineWidth','Marker','MarkerEdgeColor','MarkerFaceColor','MarkerSize'};
                addlistener(objwatch(ii), triggerprops, 'PostSet', @(h,ed) resyncprops(h,ed,hnew.leg));
        end
    end

end

%-------------------
% Output
%-------------------

out = {hnew.leg, hnew.obj, h.labeledobj, h.textstr};
varargout = out(1:nargout);

%***** Subfunctions *****

%------------------------
% Position new legend
%------------------------

function legpos = positionleg(href, w, h, anchor, buffer, bufunit)
% ap: position vector for reference object
% lp: position vector for legend

if strcmp(get(href, 'type'), 'figure')
    tmp = axes('parent', href,'position', [0 0 1 1],'visible','off');
    pos = getpos(tmp, bufunit);
    delete(tmp);
else
    pos = getpos(href, bufunit);
end

htmp = axes('units', 'pixels', 'position', [0 0 w h], 'visible','off');
lpos = getpos(htmp, bufunit);
delete(htmp);
w = lpos(3);
h = lpos(4);

% Find anchor locations on reference object

refxy = [...
    pos(1)          pos(2)+pos(4)
    pos(1)+pos(3)/2 pos(2)+pos(4)
    pos(1)+pos(3)   pos(2)+pos(4)
    pos(1)+pos(3)   pos(2)+pos(4)/2
    pos(1)+pos(3)   pos(2)
    pos(1)+pos(3)/2 pos(2)
    pos(1)          pos(2)
    pos(1)          pos(2)+pos(4)/2];

% How bottom left relates to each anchor point

shift = [...
    0       -h
    -w/2    -h
    -w      -h
    -w      -h/2
    -w      0
    -w/2    0
    0       0
    0       -h/2];

% Legend location

corner = refxy(anchor(1),:) + buffer + shift(anchor(2),:);
legpos = [corner w h];

%------------------------
% Listener functions
%------------------------

% If user manually resizes the legend, update the app data

function updatelegappdata(src, evt, legax)
if ishandle(legax)
    Lf = getappdata(legax, 'legflex');
    pos = getpos(legax, 'px');
    Lf.w = pos(3);
    Lf.h = pos(4);
    setappdata(legax, 'legflex', Lf);
end
% If reference object moves or resizes, reposition the legend appropriately

function updatelegpos(src, evt, legax)
if ishandle(legax)
    Lf = getappdata(legax, 'legflex');
    legpos = positionleg(Lf.ref, Lf.w, Lf.h, Lf.anchor, Lf.buffer, Lf.bufunit);
    set(legax, 'Units', Lf.bufferunit, 'Position', legpos);
end

% Since figure resize can change axis size without actually triggering a
% listener, force this

function updatelegfigresize(src, evt)

allax = findall(src, 'type', 'axes');
for ii = 1:length(allax)
    isleg = ~isempty(getappdata(allax(ii), 'legflex'));
    if ~isleg
        pos = get(allax(ii), 'Position');
        set(allax(ii), 'Position', pos); % No change, just trigger PostSet
    end
end

% If plotted object changes, resync with legend

function resyncprops(src, evt, legax)

if ishandle(legax) % In case it's been deleted

    Lf = getappdata(legax, 'legflex');

    str = cellstr(num2str((1:length(Lf.plotobj))'));
    [htmp.leg, htmp.obj, htmp.labeledobj, htmp.textstr] = legend(Lf.plotobj, str);

    objtype = get(Lf.legobj, 'type');
    isline = strcmp(objtype, 'line');
    ispatch = strcmp(objtype, 'patch');
    ishg = strcmp(objtype, 'hggroup');
    hgidx = find(ishg);

    lobj = [Lf.legobj(isline) htmp.obj(isline)];
    pobj = [Lf.legobj(ispatch) htmp.obj(ispatch)];

    if ~isempty(hgidx)
        for ih = hgidx
            chldln1 = findall(Lf.legobj(ih), 'type', 'line');
            chldln2 = findall(htmp.obj(ih), 'type', 'line');

            lobj = [lobj; [chldln1 chldln2]];

            chldpa1 = findall(Lf.legobj(ih), 'type', 'patch');
            chldpa2 = findall(htmp.obj(ih), 'type', 'patch');

            pobj = [pobj; [chldpa1 chldpa2]];

        end
    end

    lprops = {'color','linestyle','linewidth','marker','markersize','markeredgecolor','markerfacecolor'};
    for il = 1:size(lobj,1)
        lvals = get(lobj(il,2), lprops);
        pv = [lprops; lvals];
        set(lobj(il,1), pv{:});
    end

    pprops = {'cdata','cdatamapping','edgealpha','edgecolor','facealpha','facecolor','linestyle','linewidth','marker','markeredgecolor','markerfacecolor','markersize'};
    for ip = 1:size(pobj,1)
        pvals = get(pobj(ip,2), pprops);
        pv = [pprops; pvals];
        set(pobj(ip,1), pv{:});
    end

    cmap = colormap(htmp.leg);
    colormap(legax, cmap);

    delete(htmp.leg);
end

% Wrapper to add multiple callback functions to resize

function wrapper(ObjH, EventData, fcnList)
for ii = 1:length(fcnList)
    feval(fcnList{ii}, ObjH, EventData);
end

author: baptistar

repo: BOCS

save_path: github-repos/MATLAB/baptistar-BOCS


text:
function display(this)
%DISPLAY   Displays parameters of HS optical flow algorithm
%
%   This is a member function of the class 'hs_optical_flow'.

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

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

author: kristinbranson

repo: JAABA