text:
classdef TonemapDurand < handle
    %TONEMAPDURAND  Tonemapping algorithm used to map HDR image to 8-bit range
    %
    % This algorithm decomposes image into two layers: base layer and detail
    % layer using bilateral filter and compresses contrast of the base layer
    % thus preserving all the details.
    %
    % This implementation uses regular bilateral filter from OpenCV.
    %
    % Saturation enhancement is possible as in cv.TonemapDrago.
    %
    % For more information see [DD02].
    %
    % ## References
    % [DD02]:
    % > Fredo Durand and Julie Dorsey. "Fast bilateral filtering for the
    % > display of high-dynamic-range images". In ACM Transactions on Graphics
    % > (TOG), volume 21, pages 257-266. ACM, 2002.
    %
    % See also: cv.Tonemap, cv.TonemapDrago, cv.TonemapReinhard,
    %  cv.TonemapMantiuk, tonemap
    %

    properties (SetAccess = private)
        % Object ID
        id
    end

    properties (Dependent)
        % positive value for gamma correction.
        %
        % Gamma value of 1.0 implies no correction, gamma equal to 2.2 is
        % suitable for most displays. Generally gamma > 1 brightens the image
        % and gamma < 1 darkens it.
        Gamma
        % resulting contrast on logarithmic scale
        %
        % i.e. `log(max/min)`, where `max` and `min` are maximum and minimum
        % luminance values of the resulting image.
        Contrast
        % positive saturation enhancement value.
        %
        % 1.0 preserves saturation, values greater than 1 increase saturation
        % and values less than 1 decrease it.
        Saturation
        % bilateral filter sigma in color space.
        SigmaSpace
        % bilateral filter sigma in coordinate space.
        SigmaColor
    end

    %% TonemapDurand
    methods
        function this = TonemapDurand(varargin)
            %TONEMAPDURAND  Creates TonemapDurand object
            %
            %     obj = cv.TonemapDurand()
            %     obj = cv.TonemapDurand('OptionName',optionValue, ...)
            %
            % ## Options
            % * __Gamma__ default 1.0
            % * __Contrast__ default 4.0
            % * __Saturation__ default 1.0
            % * __SigmaSpace__ default 2.0
            % * __SigmaColor__ default 2.0
            %
            % See also: cv.TonemapDurand.process
            %
            this.id = TonemapDurand_(0, 'new', varargin{:});
        end

        function delete(this)
            %DELETE  Destructor
            %
            %     obj.delete()
            %
            % See also: cv.TonemapDurand
            %
            if isempty(this.id), return; end
            TonemapDurand_(this.id, 'delete');
        end
    end

    %% Tonemap
    methods
        function dst = process(this, src)
            %PROCESS  Tonemaps image
            %
            %     dst = obj.process(src)
            %
            % ## Input
            % * __src__ source RGB image, 32-bit `single` 3-channel array.
            %
            % ## Output
            % * __dst__ destination image of same size as `src`, 32-bit
            %   `single` 3-channel array with values in [0,1] range.
            %
            % See also: cv.TonemapDurand.TonemapDurand
            %
            dst = TonemapDurand_(this.id, 'process', src);
        end
    end

    %% Algorithm
    methods (Hidden)
        function clear(this)
            %CLEAR  Clears the algorithm state
            %
            %     obj.clear()
            %
            % See also: cv.TonemapDurand.empty, cv.TonemapDurand.load
            %
            TonemapDurand_(this.id, 'clear');
        end

        function b = empty(this)
            %EMPTY  Returns true if the algorithm is empty
            %
            %     b = obj.empty()
            %
            % ## Output
            % * __b__ Returns true if the object is empty (e.g in the
            %   very beginning or after unsuccessful read).
            %
            % See also: cv.TonemapDurand.clear, cv.TonemapDurand.load
            %
            b = TonemapDurand_(this.id, 'empty');
        end

        function name = getDefaultName(this)
            %GETDEFAULTNAME  Returns the algorithm string identifier
            %
            %     name = obj.getDefaultName()
            %
            % ## Output
            % * __name__ This string is used as top level XML/YML node tag
            %   when the object is saved to a file or string.
            %
            % See also: cv.TonemapDurand.save, cv.TonemapDurand.load
            %
            name = TonemapDurand_(this.id, 'getDefaultName');
        end

        function save(this, filename)
            %SAVE  Saves the algorithm parameters to a file
            %
            %     obj.save(filename)
            %
            % ## Input
            % * __filename__ Name of the file to save to.
            %
            % This method stores the algorithm parameters in the specified
            % XML or YAML file.
            %
            % See also: cv.TonemapDurand.load
            %
            TonemapDurand_(this.id, 'save', filename);
        end

        function load(this, fname_or_str, varargin)
            %LOAD  Loads algorithm from a file or a string
            %
            %     obj.load(fname)
            %     obj.load(str, 'FromString',true)
            %     obj.load(..., 'OptionName',optionValue, ...)
            %
            % ## Input
            % * __fname__ Name of the file to read.
            % * __str__ String containing the serialized model you want to
            %   load.
            %
            % ## Options
            % * __ObjName__ The optional name of the node to read (if empty,
            %   the first top-level node will be used). default empty
            % * __FromString__ Logical flag to indicate whether the input is a
            %   filename or a string containing the serialized model.
            %   default false
            %
            % This method reads algorithm parameters from the specified XML or
            % YAML file (either from disk or serialized string). The previous
            % algorithm state is discarded.
            %
            % See also: cv.TonemapDurand.save
            %
            TonemapDurand_(this.id, 'load', fname_or_str, varargin{:});
        end
    end

    %% Getters/Setters
    methods
        function value = get.Gamma(this)
            value = TonemapDurand_(this.id, 'get', 'Gamma');
        end
        function set.Gamma(this, value)
            TonemapDurand_(this.id, 'set', 'Gamma', value);
        end

        function value = get.Contrast(this)
            value = TonemapDurand_(this.id, 'get', 'Contrast');
        end
        function set.Contrast(this, value)
            TonemapDurand_(this.id, 'set', 'Contrast', value);
        end

        function value = get.Saturation(this)
            value = TonemapDurand_(this.id, 'get', 'Saturation');
        end
        function set.Saturation(this, value)
            TonemapDurand_(this.id, 'set', 'Saturation', value);
        end

        function value = get.SigmaSpace(this)
            value = TonemapDurand_(this.id, 'get', 'SigmaSpace');
        end
        function set.SigmaSpace(this, value)
            TonemapDurand_(this.id, 'set', 'SigmaSpace', value);
        end

        function value = get.SigmaColor(this)
            value = TonemapDurand_(this.id, 'get', 'SigmaColor');
        end
        function set.SigmaColor(this, value)
            TonemapDurand_(this.id, 'set', 'SigmaColor', value);
        end
    end

end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
function [center, rotMat] = imPrincipalAxes(img, varargin)
% Computes principal axes of a 2D/3D binary image.
%
%   [CENTER, ROTMAT] = imPrincipalAxes(IMG)
%
%   (Note: currently only implemented for binary images)
%
%   Example
%     % Compute principal axes of a discretized 3D ellipsoid
%     % (requires the MatGeom toolbox)
%     elli = [50.12 50.23 50.34  30 20 10   30 20 10];
%     img = discreteEllipsoid(1:100, 1:100, 1:100, elli);
%     [center, rotMat] = imPrincipalAxes(img);
%     center
%     center =
%        51.1209   51.2245   51.3454
%     rotation3dToEulerAngles(rotMat)
%     ans =
%        30.0107   19.9733   10.0252
%
%
%   See also
%     imEquivalentEllipse, imEquivalentEllipsoid, imMoment, principalAxes
%

% ------
% Author: David Legland
% e-mail: david.legland@inrae.fr
% Created: 2019-08-09,    using Matlab 9.6.0.1072779 (R2019a)
% Copyright 2019 INRAE - Cepia Software Platform.

%% Default parameters

spacing = [1 1 1];
origin = [1 1 1];

%% Parse inputs

dim = size(img);

% check image data type
binary = islogical(img);
if ~binary
    error('Requires a binary image as input');
end

%% Computation of Principal axes

if length(dim) == 2
    % extract points of the current particle
    inds = find(img > 0);
    [y, x] = ind2sub(dim, inds);

    % convert to user coordinates
    x = x * spacing(1) + origin(1);
    y = y * spacing(2) + origin(2);

    % compute approximate location of ellipsoid center
    xc = mean(x);
    yc = mean(y);
    center = [xc yc];

    % recenter points (should be better for numerical accuracy)
    x = (x - xc);
    y = (y - yc);
    points = [x y];

    % compute the covariance matrix
    covPts = cov(points, 1) + diag(spacing(1:2) / 12);

elseif length(dim) == 3
    % extract points of the current particle
    inds = find(img > 0);
    [y, x, z] = ind2sub(dim, inds);

    % convert to user coordinates
    x = x * spacing(1) + origin(1);
    y = y * spacing(2) + origin(2);
    z = z * spacing(3) + origin(3);

    % compute approximate location of ellipsoid center
    xc = mean(x);
    yc = mean(y);
    zc = mean(z);
    center = [xc yc zc];

    % recenter points (should be better for numerical accuracy)
    x = (x - xc);
    y = (y - yc);
    z = (z - zc);
    points = [x y z];

    % compute the covariance matrix
    covPts = cov(points, 1) +  diag(spacing(1:3) / 12);

else
    error('MatImage:imPrincipalAxes', ...
        'Dimension of input image must be either 2 or 3');
end

% perform a principal component analysis with 3 variables,
% to extract inertia axes
[U, S] = svd(covPts);

% sort axes from greater to lower
[S, ind] = sort(diag(S), 'descend'); %#ok<ASGLU>

% format U to ensure first axis points to positive x direction
U = U(ind, :);
if U(1,1) < 0
    U = -U;
    % keep matrix determinant positive
    U(:,3) = -U(:,3);
end
rotMat = U;

author: mattools

repo: matImage

save_path: github-repos/MATLAB/mattools-matImage


text:
function hz=spc2hz(i,fs,n)
hz = i/((n-1)/(fs/2));

author: jtkim-kaist

repo: VAD

save_path: github-repos/MATLAB/jtkim-kaist-VAD


text:
%SAVEPGM	Write a PGM format file
%
%	SAVEPGM(filename, im)
%
%	Saves the specified image array in a binary (P5) format PGM image file.
%
% SEE ALSO:	loadpgm
%

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

function savepgm(fname, im)

	fid = fopen(fname, 'w');
	if isempty(fid),
		error('cant open file for write');
	end
	[r,c] = size(im');
	fprintf(fid, 'P5\n');
	fprintf(fid, '%d %d\n', r, c);
	fprintf(fid, '255\n');
	fwrite(fid, im', 'uchar');
	fclose(fid)

author: petercorke

repo: machinevision-toolbox-matlab


text:
function [D, optinf] = ccmod(X, S, dsz, opt)

% ccmod -- Convolutional Constrained Method of Optimal Directions (MOD)
%
%         argmin_{d_m} (1/2) \sum_k ||\sum_m x_k,m * d_m - s_k||_2^2
%                      such that ||d_m||_2 = 1
%
%         The solution of the Convolutional Constrained MOD problem
%         (see wohlberg-2016-efficient) is computed using the ADMM
%         approach (see boyd-2010-distributed).
%
% Usage:
%       [D, optinf] = ccmod(X, S, dsz, opt)
%
% Input:
%       X           Coefficient maps (3D array)
%       S           Input images
%       dsz         Dictionary size
%       opt         Algorithm parameters structure
%
% Output:
%       D           Dictionary filter set (3D array)
%       optinf      Details of optimisation
%
%
% Options structure fields:
%   Verbose           Flag determining whether iteration status is displayed.
%                     Fields are iteration number, functional value,
%                     data fidelity term, l1 regularisation term, and
%                     primal and dual residuals (see Sec. 3.3 of
%                     boyd-2010-distributed). The values of rho and sigma
%                     are also displayed if options request that they are
%                     automatically adjusted.
%   MaxMainIter       Maximum main iterations
%   AbsStopTol        Absolute convergence tolerance (see Sec. 3.3.1 of
%                     boyd-2010-distributed)
%   RelStopTol        Relative convergence tolerance (see Sec. 3.3.1 of
%                     boyd-2010-distributed)
%   G0                Initial value for G
%   H0                Initial value for H
%   sigma             ADMM penalty parameter
%   AutoSigma         Flag determining whether sigma is automatically updated
%                     (see Sec. 3.4.1 of boyd-2010-distributed)
%   AutoSigmaPeriod   Iteration period on which sigma is updated
%   SigmaRsdlRatio    Primal/dual residual ratio in sigma update test
%   SigmaScaling      Multiplier applied to sigma when updated
%   AutoSigmaScaling  Flag determining whether SigmaScaling value is
%                     adaptively determined (see wohlberg-2015-adaptive). If
%                     enabled, SigmaScaling specifies a maximum allowed
%                     multiplier instead of a fixed multiplier.
%   StdResiduals      Flag determining whether standard residual definitions
%                     (see Sec 3.3 of boyd-2010-distributed) are used instead
%                     of normalised residuals (see wohlberg-2015-adaptive)
%   RelaxParam        Relaxation parameter (see Sec. 3.4.3 of
%                     boyd-2010-distributed)
%   LinSolve          Linear solver for main problem: 'SM' or 'CG'
%   MaxCGIter         Maximum CG iterations when using CG solver
%   CGTol             CG tolerance when using CG solver
%   CGTolAuto         Flag determining use of automatic CG tolerance
%   CGTolFactor       Factor by which primal residual is divided to obtain CG
%                     tolerance, when automatic tolerance is active
%   ZeroMean          Force learned dictionary entries to be zero-mean
%   AuxVarObj         Flag determining whether objective function is computed
%                     using the auxiliary (split) variable
%
%
% Author: Brendt Wohlberg <brendt@lanl.gov>  Modified: 2015-12-18
%
% This file is part of the SPORCO library. Details of the copyright
% and user license can be found in the 'License' file distributed with
% the library.

if nargin < 4,
  opt = [];
end
checkopt(opt, defaultopts([]));
opt = defaultopts(opt);

% Set up status display for verbose operation
hstr = 'Itn   Obj       Cnst      r         s      ';
sfms = '%4d %9.2e %9.2e %9.2e %9.2e';
nsep = 44;
if opt.AutoSigma,
  hstr = [hstr '   sigma  '];
  sfms = [sfms ' %9.2e'];
  nsep = nsep + 10;
end
if opt.Verbose && opt.MaxMainIter > 0,
  disp(hstr);
  disp(char('-' * ones(1,nsep)));
end

% Collapsing of trailing singleton dimensions greatly complicates
% handling of both SMV and MMV cases. The simplest approach would be
% if S could always be reshaped to 4d, with dimensions consisting of
% image rows, image cols, a single dimensional placeholder for number
% of filters, and number of measurements, but in the single
% measurement case the third dimension is collapsed so that the array
% is only 3d.
if size(S,3) > 1,
  xsz = size(X);
  % Insert singleton 3rd dimension (for number of filters) so that
  % 4th dimension is number of images in input s volume
  S = reshape(S, [size(S,1) size(S,2) 1 size(S,3)]);
else
  xsz = [size(X) 1];
end

% Set dsz to correct form
if numel(dsz) == 3, dsz = dsz(1:2); end

% Mean removal and normalisation projections
Pzmn = @(x) bsxfun(@minus, x, mean(mean(x,1),2));
Pnrm = @(x) normalise(x);

% Projection of filter to full image size and its transpose
% (zero-pad and crop respectively)
Pzp = @(x) zpad(x, xsz(1:2));
PzpT = @(x) bcrop(x, dsz);

% Projection of dictionary filters onto constraint set
if opt.ZeroMean,
  Pcn = @(x) Pnrm(Pzp(Pzmn(PzpT(x))));
else
  Pcn = @(x) Pnrm(Pzp(PzpT(x)));
end

% Start timer
tstart = tic;

% Compute coefficients in DFT domain
Xf = fft2(X, size(S,1), size(S,2));
% Compute signal in DFT domain
Sf = fft2(S);
% S convolved with all coefficients in DFT domain
XSf = sum(bsxfun(@times, conj(Xf), Sf), 4);

% Set up algorithm parameters and initialise variables
sigma = opt.sigma;
if isempty(sigma), sigma = size(S,3); end;
Nd = prod(xsz(1:3));
cgt = opt.CGTol;
optinf = struct('itstat', [], 'opt', opt);
r = Inf;
s = Inf;
epri = 0;
edua = 0;

% Initialise main working variables
D = []; Df = [];
if isempty(opt.G0),
  G = zeros([xsz(1) xsz(2) xsz(3)], class(S));
else
  G = opt.G0;
end
Gprv = G;
if isempty(opt.H0),
  if isempty(opt.G0),
    H = zeros([xsz(1) xsz(2) xsz(3)], class(S));
  else
    H = G;
  end
else
  H = opt.H0;
end

% Main loop
k = 1;
while k <= opt.MaxMainIter && (r > epri | s > edua),

  % Solve subproblems and update dual variable
  if strcmp(opt.LinSolve, 'SM'),
    Df = solvemdbi_ism(Xf, sigma, XSf + sigma*fft2(G - H));
  else
    [Df, cgst] = solvemdbi_cg(Xf, sigma, XSf + sigma*fft2(G - H), ...
                              cgt, opt.MaxCGIter, Df(:));
  end
  D = ifft2(Df, 'symmetric');

  % See pg. 21 of boyd-2010-distributed
  if opt.RelaxParam == 1,
    Dr = D;
  else
    Dr = opt.RelaxParam*D + (1-opt.RelaxParam)*G;
  end

  G = Pcn(Dr + H);
  H = H + Dr - G;

  % Compute data fidelity term in Fourier domain (note normalisation)
  if opt.AuxVarObj,
    Gf = fft2(G); % This represents unnecessary computational cost
    Job = sum(vec(abs(sum(bsxfun(@times,Gf,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
    Jcn = 0;
  else
    Job = sum(vec(abs(sum(bsxfun(@times,Df,Xf),3)-Sf).^2))/(2*xsz(1)*xsz(2));
    Jcn = norm(vec(Pcn(D) - D));
  end

  nD = norm(D(:)); nG = norm(G(:)); nH = norm(H(:));
  if opt.StdResiduals,
    % See pp. 19-20 of boyd-2010-distributed
    r = norm(vec(D - G));
    s = norm(vec(sigma*(Gprv - G)));
    epri = sqrt(Nd)*opt.AbsStopTol+max(nD,nG)*opt.RelStopTol;
    edua = sqrt(Nd)*opt.AbsStopTol+sigma*nH*opt.RelStopTol;
  else
    % See wohlberg-2015-adaptive
    r = norm(vec(D - G))/max(nD,nG);
    s = norm(vec(Gprv - G))/nH;
    epri = sqrt(Nd)*opt.AbsStopTol/max(nD,nG)+opt.RelStopTol;
    edua = sqrt(Nd)*opt.AbsStopTol/(sigma*nH)+opt.RelStopTol;
  end

  if opt.CGTolAuto && (r/opt.CGTolFactor) < cgt,
    cgt = r/opt.CGTolFactor;
  end

  % Record and display iteration details
  tk = toc(tstart);
  optinf.itstat = [optinf.itstat; [k Job Jcn r s epri edua sigma tk]];
  if opt.Verbose,
    if opt.AutoSigma,
      disp(sprintf(sfms, k, Job, Jcn, r, s, sigma));
    else
      disp(sprintf(sfms, k, Job, Jcn, r, s));
    end
  end

  % See wohlberg-2015-adaptive and pp. 20-21 of boyd-2010-distributed
  if opt.AutoSigma,
    if k ~= 1 && mod(k, opt.AutoSigmaPeriod) == 0,
      if opt.AutoSigmaScaling,
        sigmlt = sqrt(r/s);
        if sigmlt < 1, sigmlt = 1/sigmlt; end
        if sigmlt > opt.SigmaScaling, sigmlt = opt.SigmaScaling; end
      else
        sigmlt = opt.SigmaScaling;
      end
      ssf = 1;
      if r > opt.SigmaRsdlRatio*s, ssf = sigmlt; end
      if s > opt.SigmaRsdlRatio*r, ssf = 1/sigmlt; end
      sigma = ssf*sigma;
      H = H/ssf;
    end
  end

  Gprv = G;
  k = k + 1;

end

% Record run time and working variables
optinf.runtime = toc(tstart);
optinf.D = D;
optinf.G = G;
optinf.H = H;
optinf.sigma = sigma;
optinf.cgt = cgt;
if exist('cgst'), optinf.cgst = cgst; end

D = PzpT(G);

if opt.Verbose && opt.MaxMainIter > 0,
  disp(char('-' * ones(1,nsep)));
end

return

function u = vec(v)

  u = v(:);

return

function u = normalise(v)

  nrm = sqrt(sum(sum(v.^2, 1), 2));
  nrm(nrm == 0) = 1;
  u = bsxfun(@rdivide, v, nrm);

return

function u = zpad(v, sz)

  u = zeros(sz(1), sz(2), size(v,3), size(v,4), class(v));
  u(1:size(v,1), 1:size(v,2),:,:) = v;

return

function u = bcrop(v, sz)

  if numel(sz) <= 2,
    if numel(sz) == 1
      cs = [sz sz];
    else
      cs = sz;
    end
    u = v(1:cs(1), 1:cs(2), :);
  else
    if size(sz,1) < size(sz,2), sz = sz'; end
    cs = max(sz);
    u = zeros(cs(1), cs(2), size(v,3));
    for k = 1:size(v,3),
      u(1:sz(k,1), 1:sz(k,2), k) = v(1:sz(k,1), 1:sz(k,2), k);
    end
  end

return

function opt = defaultopts(opt)

  if ~isfield(opt,'Verbose'),
    opt.Verbose = 0;
  end
  if ~isfield(opt,'MaxMainIter'),
    opt.MaxMainIter = 200;
  end
  if ~isfield(opt,'AbsStopTol'),
    opt.AbsStopTol = 1e-6;
  end
  if ~isfield(opt,'RelStopTol'),
    opt.RelStopTol = 1e-4;
  end
  if ~isfield(opt,'G0'),
    opt.G0 = [];
  end
  if ~isfield(opt,'H0'),
    opt.H0 = [];
  end
  if ~isfield(opt,'sigma'),
    opt.sigma = [];
  end
  if ~isfield(opt,'AutoSigma'),
    opt.AutoSigma = 0;
  end
  if ~isfield(opt,'AutoSigmaPeriod'),
    opt.AutoSigmaPeriod = 10;
  end
  if ~isfield(opt,'SigmaRsdlRatio'),
    opt.SigmaRsdlRatio = 10;
  end
  if ~isfield(opt,'SigmaScaling'),
    opt.SigmaScaling = 2;
  end
  if ~isfield(opt,'AutoSigmaScaling'),
    opt.AutoSigmaScaling = 0;
  end
  if ~isfield(opt,'StdResiduals'),
    opt.StdResiduals = 0;
  end
  if ~isfield(opt,'RelaxParam'),
    opt.RelaxParam = 1;
  end
  if ~isfield(opt,'LinSolve'),
    opt.LinSolve = 'SM';
  end
  if ~isfield(opt,'MaxCGIter'),
    opt.MaxCGIter = 1000;
  end
  if ~isfield(opt,'CGTol'),
    opt.CGTol = 1e-3;
  end
  if ~isfield(opt,'CGTolAuto'),
    opt.CGTolAuto = 0;
  end
  if ~isfield(opt,'CGTolAutoFactor'),
    opt.CGTolFactor = 50;
  end
  if ~isfield(opt,'ZeroMean'),
    opt.ZeroMean = 0;
  end
  if ~isfield(opt,'AuxVarObj'),
    opt.AuxVarObj = 0;
  end

return

author: thfylsty


text:
function insertDCMDose(planC,dcmFileName)
%
%Insert dose from dcm file into the currently open planC.
%
% 11/07/2013
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

global stateS

if ~exist('planC','var')
    global planC
end
indexS = planC{end};

if ~exist('dcmFileName','var')
    [fileName, dirName] = uigetfile('*.dcm','Pick Dose file');
    dcmFileName = fullfile(dirName,fileName);
end

dcmInitFlag = init_ML_DICOM;
[dcmObj, isDcm] = scanfile_mldcm(dcmFileName);
dcmdirS = [];
if isDcm
    dcmdirS = dcmdir_add(dcmFileName, dcmObj, dcmdirS);
    dcmObj.clear;
else
    error('Invalid DICOM data')
end

% Read options file
pathStr = getCERRPath;
optName = [pathStr 'CERROptions.json'];
optS = opts4Exe(optName);

dataS = populate_planC_field('dose', dcmdirS.PATIENT,optS);

if ~isempty(planC{indexS.dose})
    planC{indexS.dose} = dissimilarInsert(planC{indexS.dose},dataS,length(planC{indexS.dose})+1);
else
    planC{indexS.dose} = dataS;
end

%Check dose-grid
doseNum = length(planC{indexS.dose});
for doseNum = 1:length(planC{indexS.dose})
    if planC{indexS.dose}(doseNum).zValues(2) - planC{indexS.dose}(doseNum).zValues(1) < 0
        planC{indexS.dose}(doseNum).zValues = flipud(planC{indexS.dose}(doseNum).zValues);
        planC{indexS.dose}(doseNum).doseArray = flipdim(planC{indexS.dose}(doseNum).doseArray,3);
    end
end

if isfield(stateS, 'CERRFile')
    stateS.doseSetChanged = 1;
    stateS.doseDisplayChanged = 1;
    stateS.doseSet = length(planC{indexS.dose});
    CERRRefresh
end

CERRStatusString('Done inserting dose.')

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


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

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

% Last Modified by GUIDE v2.5 14-Apr-2012 03:41:49

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

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end

% End initialization code - DO NOT EDIT

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

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

% Update handles structure
guidata(hObject, handles);

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

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

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on selection change in c1.
function c1_Callback(hObject, eventdata, handles)
% hObject    handle to c1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c1

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

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

% --- Executes on selection change in g1.
function g1_Callback(hObject, eventdata, handles)
% hObject    handle to g1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g1

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

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

% --- Executes on selection change in g2.
function g2_Callback(hObject, eventdata, handles)
% hObject    handle to g2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g2

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

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

% --- Executes on selection change in c2.
function c2_Callback(hObject, eventdata, handles)
% hObject    handle to c2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c2

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

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

% --- Executes on selection change in g3.
function g3_Callback(hObject, eventdata, handles)
% hObject    handle to g3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g3 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g3

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

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

% --- Executes on selection change in c3.
function c3_Callback(hObject, eventdata, handles)
% hObject    handle to c3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c3 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c3

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

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

% --- Executes on selection change in g4.
function g4_Callback(hObject, eventdata, handles)
% hObject    handle to g4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g4 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g4

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

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

% --- Executes on selection change in c4.
function c4_Callback(hObject, eventdata, handles)
% hObject    handle to c4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c4 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c4

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

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

% --- Executes on selection change in c6.
function c6_Callback(hObject, eventdata, handles)
% hObject    handle to c6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c6 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c6

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

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

% --- Executes on selection change in g6.
function g6_Callback(hObject, eventdata, handles)
% hObject    handle to g6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g6 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g6

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

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

% --- Executes on selection change in g5.
function g5_Callback(hObject, eventdata, handles)
% hObject    handle to g5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g5 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g5

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

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

% --- Executes on selection change in c5.
function c5_Callback(hObject, eventdata, handles)
% hObject    handle to c5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c5 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c5

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

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

% --- Executes on selection change in c7.
function c7_Callback(hObject, eventdata, handles)
% hObject    handle to c7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c7 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c7

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

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in g7.
function g7_Callback(hObject, eventdata, handles)
% hObject    handle to g7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g7 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g7

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

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

% --- Executes on selection change in g8.
function g8_Callback(hObject, eventdata, handles)
% hObject    handle to g8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns g8 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from g8

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

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in c8.
function c8_Callback(hObject, eventdata, handles)
% hObject    handle to c8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns c8 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from c8

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

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

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
C=[0 4 3 2 1];
G=[0 4.00 3.75 3.50 3.00 2.50 2.00 1.50 1.00 0.00];
cc(1)=C(get(handles.c1,'Value'));
gg(1)=G(get(handles.g1,'Value'));
cc(2)=C(get(handles.c2,'Value'));
gg(2)=G(get(handles.g2,'Value'));
cc(3)=C(get(handles.c3,'Value'));
gg(3)=G(get(handles.g3,'Value'));
cc(4)=C(get(handles.c4,'Value'));
gg(4)=G(get(handles.g4,'Value'));
cc(5)=C(get(handles.c5,'Value'));
gg(5)=G(get(handles.g5,'Value'));
cc(6)=C(get(handles.c6,'Value'));
gg(6)=G(get(handles.g6,'Value'));
cc(7)=C(get(handles.c7,'Value'));
gg(7)=G(get(handles.g7,'Value'));
cc(8)=C(get(handles.c8,'Value'));
gg(8)=G(get(handles.g8,'Value'));
GPA=sum(cc.*gg)/sum(cc);
set(handles.GPA,'String',GPA)
global ABCXYZ ;
ABCXYZ=(sum(cc));
XX(GPA);

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

% Hints: get(hObject,'String') returns contents of cgpa0 as text
%        str2double(get(hObject,'String')) returns contents of cgpa0 as a double

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

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

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

% Hints: get(hObject,'String') returns contents of ch0 as text
%        str2double(get(hObject,'String')) returns contents of ch0 as a double

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

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

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
cgpa_previous=(get(handles.cgpa0 ,'String'));
ch_previous=(get(handles.ch0 ,'String'));
gpa_current=(get(handles.GPA ,'String'));
cgpa_previous=str2num(cgpa_previous);
ch_previous=str2num(ch_previous);
gpa_current=str2num(gpa_current);
global ABCXYZ;
ccgpa=(gpa_current.*ABCXYZ+cgpa_previous.*ch_previous)./(ABCXYZ+ch_previous);
set(handles.CCGPA,'String',ccgpa);
XX(ccgpa);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function XX(t)
if   t==4
    msgbox('Parable Performance!','CGPA','replace');return;
end
if   t>=3.5
    msgbox('Excellent Performance!','CGPA','replace');return;
end
if    t>=3
    msgbox('Fair!','CGPA','replace');return;
end
if     t>=2
    msgbox('You Need To work evenmore!','CGPA','replace');return;
end
if       t<2
    msgbox('Bad Perfprmance!','CGPA','replace');return;
end

author: Sable

repo: mcbench-benchmarks


text:
classdef MicrostrainImuDataReader < DataReader
properties(Access=private)
    prevImuBuffer = {};% record the previous imu data
    imudata = zeros(7, 1);  % time(sec), ax, ay, ax, gx, gy, gz in metric units.
    numPrevImuDataToKeep = 40;
    fileID;
    imuFileType = 4;
    nominalSamplingInterval = 0.008;
end

methods(Access=public)
    function reader = MicrostrainImuDataReader(imufile, startTime)
        [reader.fileID, reader.imudata, reader.prevImuBuffer]=...
            readimuheader(imufile, reader.prevImuBuffer, startTime, ...
            reader.numPrevImuDataToKeep, reader.imuFileType);
    end
end

methods(Access=protected)
    function data = nextImpl(this)
        if(length(this.prevImuBuffer)==this.numPrevImuDataToKeep)
            this.prevImuBuffer(1) = [];
        end
        this.prevImuBuffer{end + 1} = this.imudata;
        lasttime = this.imudata(1);
        [this.fileID, this.imudata]=grabnextimudata(...
            this.fileID, this.imudata(1), this.imuFileType);
        currenttime = this.imudata(1);
        if currenttime - lasttime > this.nominalSamplingInterval * 1.5
            fprintf('Warn: Microstrain IMU data missing from %.6f to %.6f!\n', ...
                lasttime, currenttime);
        end
        if currenttime - lasttime < this.nominalSamplingInterval * 0.5
            fprintf('Warn: Microstrain IMU data duplicate from %.6f to %.6f!\n', ...
                lasttime, currenttime);
        end
        data = this.imudata;
    end
    function data = previousImpl(this)
        data = this.prevImuBuffer{end};
    end
    function data = currentImpl(this)
        data = this.imudata;
    end
end
end

repo: ekfmonoslam


text:
function [A_hat, E_hat, Y, mu, iter] = inexact_alm_rpca_with_lmsvds(D, lambda, tol, maxIter)

% Oct 2009
% This matlab code implements the inexact augmented Lagrange multiplier
% method for Robust PCA.
%
% D - m x n matrix of observations/data (required input)
%
% lambda - weight on sparse error term in the cost function
%
% tol - tolerance for stopping criterion.
%     - DEFAULT 1e-7 if omitted or -1.
%
% maxIter - maximum number of iterations
%         - DEFAULT 1000, if omitted or -1.
%
% Initialize A,E,Y,u
% while ~converged
%   minimize (inexactly, update A and E only once)
%     L(A,E,Y,u) = |A|_* + lambda * |E|_1 + <Y,D-A-E> + mu/2 * |D-A-E|_F^2;
%   Y = Y + \mu * (D - A - E);
%   \mu = \rho * \mu;
% end
%
% Minming Chen, October 2009. Questions? v-minmch@microsoft.com ;
% Arvind Ganesh (abalasu2@illinois.edu)
%
% Copyright: Perception and Decision Laboratory, University of Illinois, Urbana-Champaign
%            Microsoft Research Asia, Beijing

[m, n] = size(D);

if nargin < 2
  lambda = 1 / sqrt(m);
end

if nargin < 3
  tol = 1e-7;
elseif tol == -1
  tol = 1e-7;
end

if nargin < 4
  maxIter = 1000;
elseif maxIter == -1
  maxIter = 1000;
end

% initialize
Y = D;
norm_two = norm(Y, 2);
norm_inf = norm( Y(:), inf) / lambda;
dual_norm = max(norm_two, norm_inf);
Y = Y / dual_norm;

A_hat = zeros( m, n);
E_hat = zeros( m, n);
mu = 1.25/norm_two; % this one can be tuned
mu_bar = mu * 1e7;
rho = 1.5;          % this one can be tuned
d_norm = norm(D, 'fro');

iter = 0;
total_svd = 0;
converged = false;
sv = 10;
while ~converged
  iter = iter + 1;

  temp_T = D - A_hat + (1/mu)*Y;
  E_hat = max(temp_T - lambda/mu, 0);
  E_hat = E_hat+min(temp_T + lambda/mu, 0);

  myA = D - E_hat + (1/mu)*Y;
  [myM, ~] = size(myA);
  myR = (myM/100)/2;
  [U,S,V] = LMSVDS(myA, myR, []);

  diagS = diag(S);
  svp = length(find(diagS > 1/mu));
  if svp < sv
    sv = min(svp + 1, n);
  else
    sv = min(svp + round(0.05*n), n);
  end

  A_hat = U(:, 1:svp) * diag(diagS(1:svp) - 1/mu) * V(:, 1:svp)';

  total_svd = total_svd + 1;

  Z = D - A_hat - E_hat;

  Y = Y + mu*Z;
  mu = min(mu*rho, mu_bar);

  %% stop Criterion
  stopCriterion = norm(Z, 'fro') / d_norm;
  if stopCriterion < tol
    converged = true;
  end

  %     if mod( total_svd, 10) == 0
  %         disp(['#svd ' num2str(total_svd) ' r(A) ' num2str(rank(A_hat))...
  %             ' |E|_0 ' num2str(length(find(abs(E_hat)>0)))...
  %             ' stopCriterion ' num2str(stopCriterion)]);
  %     end
  %
  if ~converged && iter >= maxIter
    %disp('Maximum iterations reached') ;
    converged = 1 ;
  end
end

author: andrewssobral

repo: lrslibrary


text:
function plotIVHCallback(command, varargin)
%"plotIVHCallback"
%   Callbacks for IVH plots, all functions are in the expanded view.
%
%JRA 5/20/04
%
% 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/>.
%
%Usage:
%   function plotIVHCallback(command, varargin)

switch upper(command)
    case 'EXPANDEDVIEW'
    %Request to expand the DVH view.
        hFig = get(gcbo, 'parent');
        ud = get(hFig, 'userdata');
        %set(hFig, 'doublebuffer', 'on');

        %Freeze all other figure objects.
        figChild = get(hFig, 'children');
        for i=1:length(figChild)
            try
                set(figChild(i), 'units', 'pixels');
            end
        end

        %Add margin on right side of figure.
        pos = get(hFig, 'position');
        if ~isfield(ud, 'handles')
            pos(3) = pos(3) + 200;
        else
            framePos = get(ud.handles.frame, 'position');
            frameWidth = framePos(3);
            pos(3) = pos(3) + frameWidth;
        end
        set(hFig, 'position', pos);

        %Return units to normalized.
        figChild = get(hFig, 'children');
        for i=1:length(figChild)
            try
                set(figChild(i), 'units', 'normalized');
            end
        end

        %Change menubar item to reflect change back option.
        set(gcbo, 'label', 'Simple Options', 'callback',['plotIVHCallback(''SIMPLEVIEW'')']);

        %Actually perform the initialization.
        if ~isfield(ud, 'handles')
            plotIVHCallback('INITEXPANDED');
            set(hFig, 'toolbar', 'figure');
        else
            try
                set(ud.handles.motionline, 'visible', 'on')
            end

            try
                n = get(ud.handles.strList, 'value');
                if n > 0
                    set(ud.plots(n-1).hLine, 'selected', 'on');
                    hAxis = get(ud.plots(n-1).hLine, 'parent');
                    set(hAxis, 'buttonDownFcn', 'plotIVHCallback(''CLICKINPLOT'')');
                end
            end
        end
        for i=1:length(ud.plots)
            set(ud.plots(i).hLine, 'hittest', 'on', 'buttondownfcn',['plotIVHCallback(''IVHCLICKED'', ' num2str(i) ')']);
        end

    case 'IVHCLICKED'
        clicked = varargin{1};
        hAxis = get(gcbo, 'parent');
        hFig = get(hAxis, 'parent');
        ud = get(hFig, 'userdata');
        set(ud.handles.strList, 'value', clicked+1);
        plotIVHCallback('SELECTIVH');
        return;

    case 'SIMPLEVIEW'
    %Return to the simple view by contracting the margin.
        hFig = get(gcbo, 'parent');
        ud = get(hFig, 'userdata');

        %Freeze all other figure objects.
        figChild = get(hFig, 'children');
        for i=1:length(figChild)
            try
                set(figChild(i), 'units', 'pixels');
            end
        end

        %Remove the margin, using the frame size as guide.
        framePos = get(ud.handles.frame, 'position');
        frameWidth = framePos(3);
        pos = get(hFig, 'position');
        pos(3) = pos(3) - frameWidth;
        set(hFig, 'position', pos);

        try
            set(ud.handles.motionline, 'visible', 'off')
        end

        for i=1:length(ud.plots)
            hAxis = get(ud.plots(i).hLine, 'parent');
            set(ud.plots(i).hLine, 'selected', 'off', 'hittest', 'off');
        end
        set(hAxis, 'buttonDownFcn', '');

        %Return units to normalized.
        figChild = get(hFig, 'children');
        for i=1:length(figChild)
            try
                set(figChild(i), 'units', 'normalized');
            end
        end

        set(gcbo, 'label', 'Expanded Options', 'callback',['plotIVHCallback(''EXPANDEDVIEW'')']);

    case 'INITEXPANDED'
    %If this is the first time the expanded view is requested, draw all the uicontrols.
        barW = 200;
        hFig = get(gcbo, 'parent');

        ud = get(hFig, 'userdata');
        plots = ud.plots;

        hAxis = get(plots(1).hLine, 'parent');

        pos = get(hFig, 'position');
        h = pos(4); w = pos(3);
        units = 'pixels';

        for i=1:length(plots)
            strNames{i} = [plots(i).struct '--' num2str(plots(i).doseNum)];
            set(plots(i).hLine, 'hittest', 'off');
        end
        strNames = {'None' strNames{:}};

        frame.X = w-barW+10;
        frame.Y = 10;
        frame.W = barW-20;
        frame.H = h-20;
        hTmp = uicontrol(hFig, 'style', 'frame', 'units', units, 'position', [frame.X frame.Y frame.W frame.H]);
        frameColor = get(hTmp, 'BackgroundColor');
        delete(hTmp);
        %Dummy frame for units.
        ud.handles.frame = axes('units', units, 'Position', [w-barW 0 barW h], 'visible', 'off');
        axes('units', units, 'Position', [frame.X frame.Y frame.W frame.H], 'color', frameColor, 'ytick',[],'xtick',[], 'box', 'on', 'parent', hFig);

        uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+10 frame.Y+frame.H-25 80 15], 'string', 'Selected DVH:', 'horizontalAlignment', 'left');
        ud.handles.strList = uicontrol(hFig, 'style', 'popupmenu', 'units', units, 'position', [frame.X+90 frame.Y+frame.H-25 80 15], 'string', strNames, 'horizontalAlignment', 'left', 'callback', 'plotIVHCallback(''SELECTIVH'');');

        uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+10 frame.Y+frame.H-50 80 15], 'string', 'Linestyle:', 'horizontalAlignment', 'left');
        hTmp = axes('units', units, 'Position', [frame.X+90 frame.Y+frame.H-50 80 15], 'color', frameColor, 'ytick',[],'xtick',[], 'box', 'off', 'parent', hFig, 'xcolor', frameColor, 'ycolor', frameColor);
        ud.handles.lineStyle = line([0 1], [.5 .5], 'color', 'red', 'linestyle', '-', 'visible', 'off', 'parent', hTmp);

        ud.handles.doseTxt = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+10 frame.Y+frame.H-75 80 15], 'string', 'FromDose:', 'horizontalAlignment', 'left');
        ud.handles.doseVal = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+90 frame.Y+frame.H-75 80 15], 'string', '.', 'horizontalAlignment', 'right');

        ud.handles.statTxt = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+10 frame.Y+frame.H-100 80 15], 'string', 'DVH Stats:', 'horizontalAlignment', 'left');

        ud.handles.meanTxt = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+20 frame.Y+frame.H-125 80 15], 'string', 'Mean Scan:', 'horizontalAlignment', 'left');
        ud.handles.meanVal = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+90 frame.Y+frame.H-125 80 15], 'string', '.', 'horizontalAlignment', 'right');

        ud.handles.totalTxt = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+20 frame.Y+frame.H-150 80 15], 'string', 'Total Vol:', 'horizontalAlignment', 'left');
        ud.handles.totalVal = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+90 frame.Y+frame.H-150 80 15], 'string', '.', 'horizontalAlignment', 'right');

        ud.handles.maxTxt = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+20 frame.Y+frame.H-175 80 15], 'string', 'Max Scan:', 'horizontalAlignment', 'left');
        ud.handles.maxVal = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+90 frame.Y+frame.H-175 80 15], 'string', '.', 'horizontalAlignment', 'right');

        ud.handles.minTxt = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+20 frame.Y+frame.H-200 80 15], 'string', 'Min Scan:', 'horizontalAlignment', 'left');
        ud.handles.minVal = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+90 frame.Y+frame.H-200 80 15], 'string', '.', 'horizontalAlignment', 'right');

        ud.handles.abovePtTxt = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+10 frame.Y+frame.H-250 170 15], 'string', 'Vol above point in DVH:', 'horizontalAlignment', 'center');
        uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+10 frame.Y+frame.H-275 80 15], 'string', 'Scan', 'horizontalAlignment', 'center');
        ud.handles.volTxt = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+90 frame.Y+frame.H-275 80 15], 'string', 'Volume', 'horizontalAlignment', 'center');

        ud.handles.scanDoseVal = uicontrol(hFig, 'style', 'edit', 'units', units, 'position', [frame.X+10 frame.Y+frame.H-300 80 20], 'string', '.', 'horizontalAlignment', 'center', 'callback', 'plotIVHCallback(''DOSEVAL'')');
        ud.handles.scanVolVal = uicontrol(hFig, 'style', 'text', 'units', units, 'position', [frame.X+90 frame.Y+frame.H-300 80 15], 'string', '.', 'horizontalAlignment', 'center');

        %control to display legend in new figure
        ud.handles.legendChk = uicontrol(hFig, 'style', 'checkbox', 'units', units, 'position', [frame.X+10 frame.Y+frame.H-350 150 20], 'string', 'Show Legend', 'horizontalAlignment', 'center', 'callback', 'plotIVHCallback(''LEGENDCALL'')');

        %control to export IVH to excel
        ud.handles.exportIVH = uicontrol(hFig, 'style', 'push', 'units', units, 'position', [frame.X+10 frame.Y+frame.H-380 100 20], 'string', 'Export IVH', 'horizontalAlignment', 'center', 'callback', 'plotIVHCallback(''EXPORTIVH'')');

        yLim = get(hAxis, 'yLim');
        ud.handles.motionline = line([0 0], [yLim(1) yLim(2)], 'color', 'blue', 'parent', hAxis, 'hittest', 'off');

        %Return units to normalized.
        figChild = get(hFig, 'children');
        for i=1:length(figChild)
            try
                set(figChild(i), 'units', 'normalized');
            end
        end
        set(hFig, 'userdata', ud);

    case 'SELECTIVH'
        %An IVH has been selected from the list, populate fields.
        if strcmpi(get(gcbo, 'type'), 'line')
            hAxis = get(gcbo, 'parent');
            hFig = get(hAxis, 'parent');
            ud = get(hFig, 'userdata');
            hPopup = ud.handles.strList;
        elseif strcmpi(get(gcbo, 'type'), 'uicontrol')
            hFig = get(gcbo, 'parent');
            ud = get(hFig, 'userdata');
            hPopup = ud.handles.strList;
        end
        val = get(hPopup, 'value');
        val = val - 1;
        hPlots = [ud.plots.hLine];
        set(hPlots, 'selected', 'off');
        if val > 0
            hAxis = get(hPlots(val), 'parent');
            set(hAxis, 'buttonDownFcn', 'plotIVHCallback(''CLICKINPLOT'')');
            set(hPlots(val), 'selected', 'on');
            lS = get(hPlots(val), 'linestyle');
            col = get(hPlots(val), 'color');
            lW = get(hPlots(val), 'linewidth');
            set(ud.handles.lineStyle, 'linestyle', lS, 'color', col, 'linewidth', lW, 'visible', 'on');

            dose = str2double(get(ud.handles.scanDoseVal, 'string'));
            currentPlot = get(ud.handles.strList, 'value') - 1;
            xLim = get(hAxis, 'xLim');
            if dose < xLim(1)
                dose = xLim(1);
            elseif dose > xLim(2)
                dose = xLim(2);
            end
            surfVol = interp1(ud.plots(currentPlot).xVals, ud.plots(currentPlot).yVals, dose);
            if isnan(surfVol)
                surfVol = 0;
            end
            if ~strcmpi(ud.plots(currentPlot).abs, 'ABS')
                surfVol = surfVol*100;
            end
            set(ud.handles.motionline, 'xdata', [dose dose], 'visible', 'on');
            set(ud.handles.scanDoseVal, 'string', num2str(dose));
            set(ud.handles.scanVolVal, 'string', num2str(surfVol));
            %If we are dealing with a DSH, rename fields and use different
            %metrics calculations from DVH.
            if strcmpi(ud.plots(val).type, 'DSH')
                areaV = ud.plots(val).volsV;
                dosesV = ud.plots(val).doseBins;
                meanD = sum(dosesV.*areaV)/sum(areaV);
                totalArea = sum(areaV);
                maxDose = max(dosesV);
                minDose = min(dosesV);
                set(ud.handles.statTxt, 'string', 'DSH Stats:')
                set(ud.handles.totalTxt, 'string', 'Total Surface:')
                set(ud.handles.meanVal, 'string', num2str(meanD))
                set(ud.handles.totalVal, 'string', num2str(totalArea))
                set(ud.handles.maxVal, 'string', num2str(maxDose));
                set(ud.handles.minVal, 'string', num2str(minDose));
                set(ud.handles.doseVal, 'string', ud.plots(val).doseName);
                if strcmpi(ud.plots(val).abs, 'ABS')
                    set(ud.handles.abovePtTxt, 'string', 'Abs Surface above selected level:')
                    set(ud.handles.volTxt, 'string', 'Abs Surface');
                else
                    set(ud.handles.abovePtTxt, 'string', '% Surface above selected level:')
                    set(ud.handles.volTxt, 'string', '% Surface');
                end

            %If we are dealing with a IVH, rename fields and use different
            %metrics calculations from ISH.
            elseif strcmpi(ud.plots(val).type, 'IVH')
                volHistV = ud.plots(val).volsV;
                doseBinsV = ud.plots(val).doseBins;
                meanD = sum(doseBinsV.*volHistV)/sum(volHistV);
                totalVol = sum(volHistV);
                ind = max(find([volHistV~=0]));
                maxD = doseBinsV(ind);
                ind = min(find([volHistV~=0]));
                minD = doseBinsV(ind);
                set(ud.handles.statTxt, 'string', 'IVH Stats:')
                set(ud.handles.totalTxt, 'string', 'Total Volume:')
                set(ud.handles.meanVal, 'string', num2str(meanD))
                set(ud.handles.totalVal, 'string', num2str(totalVol))
                set(ud.handles.maxVal, 'string', num2str(maxD));
                set(ud.handles.minVal, 'string', num2str(minD));
                set(ud.handles.doseVal, 'string', ud.plots(val).doseName);
                if strcmpi(ud.plots(val).abs, 'ABS')
                    set(ud.handles.abovePtTxt, 'string', 'Abs Volume above selected level:')
                    set(ud.handles.volTxt, 'string', 'Abs Volume');
                else
                    set(ud.handles.abovePtTxt, 'string', '% Volume above selected level:')
                    set(ud.handles.volTxt, 'string', '% Volume');
                end
            else
                error('Not a valid plot type for IVH callback.')
            end
        else
            hAxis = get(hPlots(1), 'parent');
            set(hAxis, 'buttonDownFcn', '')
            set(ud.handles.lineStyle, 'visible', 'off');
            set(ud.handles.motionline, 'visible', 'off');
        end
        set(hFig, 'userdata', ud);

    case 'CLICKINPLOT'
    %A DVH is selected and the plot has been clicked, update guide line/fields.
        hAxis = gcbo;
        hFig = get(hAxis, 'parent');
        ud = get(hFig, 'userdata');
        set(hFig, 'WindowButtonUpFcn', 'plotIVHCallback(''UNCLICKINPLOT'')');
        set(hFig, 'WindowButtonMotionFcn', 'plotIVHCallback(''PLOTMOTION'')');
        currentPlot = get(ud.handles.strList, 'value') - 1;
        cP = get(hAxis, 'currentpoint');
        %Interpolate Surf/Vol, display.
        dose = cP(1,1);
        xLim = get(hAxis, 'xLim');
        if dose < xLim(1)
            dose = xLim(1);
        elseif dose > xLim(2)
            dose = xLim(2);
        end
        surfVol = interp1(ud.plots(currentPlot).xVals, ud.plots(currentPlot).yVals, dose);
        if isnan(surfVol)
            surfVol = 0;
        end
        if ~strcmpi(ud.plots(currentPlot).abs, 'ABS')
            surfVol = surfVol*100;
        end
        set(ud.handles.motionline, 'xdata', [dose dose], 'visible', 'on');
        set(ud.handles.scanDoseVal, 'string', num2str(dose));
        set(ud.handles.scanVolVal, 'string', num2str(surfVol));

    case 'UNCLICKINPLOT'
        hFig = gcbo;
        ud = get(hFig, 'userdata');
        set(hFig, 'WindowButtonMotionFcn', '');
        set(hFig, 'WindowButtonUpFcn', '');
        set(hFig, 'userdata', ud);

    case 'DOSEVAL'
    %A value has been entered into the doseVal field.
        hFig = get(gcbo, 'parent');
        dose = str2double(get(gcbo, 'string'));
        ud = get(hFig, 'userdata');
        currentPlot = get(ud.handles.strList, 'value') - 1;
        hAxis = get(ud.plots(currentPlot).hLine, 'parent');
        xLim = get(hAxis, 'xLim');
        if dose < xLim(1)
            dose = xLim(1);
        elseif dose > xLim(2)
            dose = xLim(2);
        end
        surfVol = interp1(ud.plots(currentPlot).xVals, ud.plots(currentPlot).yVals, dose);
        if isnan(surfVol)
            surfVol = 0;
        end
        if ~strcmpi(ud.plots(currentPlot).abs, 'ABS')
            surfVol = surfVol*100;
        end
        set(ud.handles.motionline, 'xdata', [dose dose], 'visible', 'on');
        set(ud.handles.scanDoseVal, 'string', num2str(dose));
        set(ud.handles.scanVolVal, 'string', num2str(surfVol));

    case 'PLOTMOTION'
    %An IVH is selected, the plot has been clicked and motion is occuring. Update guide line/fields.
        hFig = gcbo;
        ud = get(hFig, 'userdata');
        currentPlot = get(ud.handles.strList, 'value') - 1;
        hAxis = get(ud.plots(currentPlot).hLine, 'parent');
        cP = get(hAxis, 'currentpoint');
        dose = cP(1,1);
        xLim = get(hAxis, 'xLim');
        if dose < xLim(1)
            dose = xLim(1);
        elseif dose > xLim(2)
            dose = xLim(2);
        end
        surfVol = interp1(ud.plots(currentPlot).xVals, ud.plots(currentPlot).yVals, dose);
        if isnan(surfVol)
            surfVol = 0;
        end
        if ~strcmpi(ud.plots(currentPlot).abs, 'ABS')
            surfVol = surfVol*100;
        end
        set(ud.handles.motionline, 'xdata', [dose dose], 'visible', 'on');
        set(ud.handles.scanDoseVal, 'string', num2str(dose));
        set(ud.handles.scanVolVal, 'string', num2str(surfVol));

    case 'LEGENDCALL'
        %executes when "Show Legend" is toggled on or off

        value = get(gcbo,'value');
        hLegend = findobj('tag','IVH_Legend');
        close(hLegend)
        if value == 0
            return;
        end
        hFig = get(gcbo, 'parent');
        ud = get(hFig, 'userdata');
        hLegend = figure('tag','IVH_Legend','name','IVH Legend','numberTitle','off','menubar','Figure','color','w');
        position = get(hLegend,'position');
        figColor = get(hLegend,'color');
        axisLegend = axes('units', 'normalized', 'Position', [0 0 1 1], 'color', figColor, 'ytick',[],'xtick',[], 'box', 'off', 'parent', hLegend,'nextPlot','add','units','normalized','visible','off');
        numLines = length(ud.plots);
        dy = 0.8/numLines;
        position(3) = 400;
        position(4) = (numLines+1)*30;
        set(hLegend,'position',position)

        for i = 1:numLines
            LineStyle = get(ud.plots(i).hLine,'LineStyle');
            LineWidth = get(ud.plots(i).hLine,'LineWidth');
            Color = get(ud.plots(i).hLine,'Color');
            line([0.05 0.15],[0.8-(i-1)*dy 0.8-(i-1)*dy],'LineStyle',LineStyle,'LineWidth',LineWidth,'Color',Color,'parent',axisLegend)
            txt = ['Struct = ',ud.plots(i).struct,', Scan = ',ud.plots(i).doseName];
            text(0.18,0.8-(i-1)*dy,txt)
        end
        axis(axisLegend,[0 1 0 1])

    case 'EXPORTIVH'
        hFig = get(gcbo, 'parent');
        ud = get(hFig, 'userdata');
        currentIVH = get(ud.handles.strList, 'value') - 1;
        if currentIVH == 0
            warndlg('Please select IVH to be exported.','IVH not selected','modal')
            return;
        end

        M = [ud.plots(currentIVH).xVals; ud.plots(currentIVH).yVals];
        %Export only NumPts points
        NumPts = 65000;
        if size(M,2)>NumPts
            indAll = round(linspace(1,size(M,2),NumPts));
            M = M(:,indAll);
        end
        [fname, pname] = uiputfile('*.xls','Save the IVH data as:');
        if isnumeric(fname)
            return;
        end
        try
            xlswrite(fullfile(pname,fname), M');
        catch
            csvwrite(fullfile(pname,fname), M');
        end

end


text:
function [boxes blobIndIm blobBoxes hierarchy priority] = Image2HierarchicalGrouping(im, sigma, k, minSize, colourType, functionHandles)
% function [boxes blobIndIm blobBoxes hierarchy] = Image2HierarchicalGrouping
%                              (im, sigma, k, minSize, colourType, functionHandles)
%
% Creates hierarchical grouping from an image
%
% im:                   Image
% sigma (= 0.8):        Smoothing for initial segmentation (Felzenszwalb 2004)
% k (= 100):            Threshold for initial segmentation
% minSize (= 100):      Minimum size of segments for initial segmentation
% colourType:           ColourType in which to do grouping (see Image2ColourSpace)
% functionHandles:      Similarity functions which are called. Function
%                       creates as many hierarchies as there are functionHandles
%
% boxes:                N x 4 array with boxes of all hierarchical groupings
% blobIndIm:            Index image with the initial segmentation
% blobBoxes:            Boxes belonging to the indices in blobIndIm
% hierarchy:            M x 1 cell array with hierarchies. M =
%                       length(functionHandles)
%
%     Jasper Uijlings - 2013

% Change colour space
[colourIm imageToSegment] = Image2ColourSpace(im, colourType);

% Get initial segmentation, boxes, and neighbouring blobs
[blobIndIm blobBoxes neighbours] = mexFelzenSegmentIndex(imageToSegment, sigma, k, minSize);
numBlobs = size(blobBoxes,1);

% Skip hierarchical grouping if segmentation results in single region only
if numBlobs == 1
    warning('Oversegmentation results in a single region only');
    boxes = blobBoxes;
    hierarchy = [];
    priority = 1; % priority is legacy
    return;
end

%%% Calculate histograms and sizes as prerequisite for grouping procedure

% Get colour histogram
[colourHist blobSizes] = BlobStructColourHist(blobIndIm, colourIm);

% Get texture histogram
textureHist = BlobStructTextureHist(blobIndIm, colourIm);
% textureHist = BlobStructTextureHistLBP(blobIndIm, colourIm);

% Allocate memory for complete hierarchy.
blobStruct.colourHist = zeros(size(colourHist,2), numBlobs * 2 - 1);
blobStruct.textureHist = zeros(size(textureHist,2), numBlobs * 2 - 1);
blobStruct.size = zeros(numBlobs * 2 -1, 1);
blobStruct.boxes = zeros(numBlobs * 2 - 1, 4);

% Insert calculated histograms, sizes, and boxes
blobStruct.colourHist(:,1:numBlobs) = colourHist';
blobStruct.textureHist(:,1:numBlobs) = textureHist';
blobStruct.size(1:numBlobs) = blobSizes ./ 3;
blobStruct.boxes(1:numBlobs,:) = blobBoxes;

blobStruct.imSize = size(im,1) * size(im,2);

%%% If you want to use original blobs in similarity functions, uncomment
%%% these lines.
% blobStruct.blobs = cell(numBlobs * 2 - 1, 1);
% initialBlobs = SegmentIndices2Blobs(blobIndIm, blobBoxes);
% blobStruct.blobs(1:numBlobs) = initialBlobs;

% Loop over all merging strategies. Perform them one by one.
boxes = cell(1, length(functionHandles)+1);
priority = cell(1, length(functionHandles) + 1);
hierarchy = cell(1, length(functionHandles));
for i=1:length(functionHandles)
    [boxes{i} hierarchy{i} blobStructT mergeThreshold] = BlobStruct2HierarchicalGrouping(blobStruct, neighbours, numBlobs, functionHandles{i});
    boxes{i} = boxes{i}(numBlobs+1:end,:);
    priority{i} = (size(boxes{i}, 1):-1:1)';
end

% Also save the initial boxes
i = i+1;
boxes{i} = blobBoxes;
priority{i} = ones(size(boxes{i}, 1), 1) * (size(boxes{1}, 1)+1);

% Concatenate boxes and priorities resulting from the different merging
% strategies
boxes = cat(1, boxes{:});
priority = cat(1, priority{:});
[priority ids] = sort(priority, 'ascend');
boxes = boxes(ids,:);

author: zouchuhang

repo: LayoutNet


text:
function f = conj(f)
%CONJ   Complex conjugate of a SPHEREFUN.
%   CONJ(F) returns the complex conjugate of F.  For a complex F, CONJ(F) =
%   REAL(F) - i*IMAG(F).
%
%   Since only real-valued SPHEREFUNS are presently supported, this
%   function is trivial.
%
% See also SPHEREFUN/REAL, SPHEREFUN/IMAG.

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

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function f = flops_lu(n)
% FLOPS_LU   Flops for LU decomposition.
% FLOPS_LU(n) returns the number of flops to compute lu(rand(n,n)).
% The matrix is assumed to be symmetric positive definite, so that no pivoting is required.

% Number of flops for the algorithm in Cormen et al:
% Number of multiplies+adds is:
%   sum(k=1:n) sum(i=k+1:n) sum(j=k+1:n) 3
% = sum(k=1:n) 3(n-k)^2
% = sum(k=0:(n-1)) 3 k^2
% = n(n-0.5)(n-1)
% Number of divides is: n-1
f = n*(n-0.5)*(n-1) + (n-1)*flops_div;


text:
load ../graphs/dfs_example.mat
[d dt ft pred] = dfs(A,2);
[ignore order] = sort(dt);
labels(order)

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function val=soft_threshodr(groups,nc,w,mu)
%soft_threshodr
%
val=w/(1+mu);
end

author: xiubooth


text:
function X = PQRFFT (x, N, ifn)
% Calculate the DFT of a real N-point sequence or the inverse
% DFT corresponding to a real N-point sequence.
% ifn > 0, forward transform
%          input x(n)  - N real values
%          output X(k) - The first N/2+1 points are the real
%            parts of the transform, the next N/2-1 points
%            are the imaginary parts of the transform. However
%            the imaginary part for the first point and the
%            middle point which are known to be zero are not
%            stored.
% ifn < 0, inverse transform
%          input X(k) - The first N/2+1 points are the real
%            parts of the transform, the next N/2-1 points
%            are the imaginary parts of the transform. However
%            the imaginary part for the first point and the
%            middle point which are known to be zero are not
%            stored.
%          output x(n) - N real values

% P. Kabal $Revision: 1.1 $  $Date: 2003/12/07 13:34:11 $

if (ifn > 0)
    X = fft (x, N);
    XR = real(X(0+1:N/2+1));
    XI = imag(X(1+1:N/2-1+1));
    X = [XR XI];
else
    xR = [x(0+1:N/2+1)];
    xI = [0 x(N/2+1+1:N-1+1) 0];
    x = complex ([xR xR(N/2-1+1:-1:1+1)], [xI -xI(N/2-1+1:-1:1+1)]);
    X = real (ifft (x, N));
end

author: stephencwelch

repo: Perceptual-Coding-In-Python


text:
function s=sprintsi(x,d,w)
%SPRINTSI Print X with SI multiplier S=(X,D,W)
% D is number of decimal places (+ve) or significant digits (-ve) [default=-3]
% |W| is total width including multiplier
% if W<=0 then trailing 0's will be eliminated
%
% Example: sprintsi(2345,-2) gives '2.3 k'

%      Copyright (C) Mike Brookes 1998
%      Version: $Id: sprintsi.m 713 2011-10-16 14:45:43Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   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 can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin<3 w=0; end;
if nargin<2 d=-3; end;
f='afpnum kMGT';
e=max(-18,min(12,floor(log10(abs(x)))));
k=floor(e/3);
dp=max([0 d 3*k-d-e-1]);
if w<=0 & dp
   w=abs(w);
   dp=max(find([1 mod(mod(round(x*10^(dp-3*k)),10^dp),10.^(dp:-1:1))]))-1;
end
if(k)
   s=sprintf(sprintf('%%%d.%df %c',w-2,dp,f(k+7)),x*1e-3^k);
else
   s=sprintf(sprintf('%%%d.%df ',w-1,dp),x*1e-3^k);
end

author: covarep

repo: covarep

save_path: github-repos/MATLAB/covarep-covarep


text:
classdef LabelsPlot
  % timeline images/plots for UI

  methods (Static)

    function labels_plot = labelsPlot(t0,t1,nTL,nBeh,beh2TL,TL2beh,nflies)
      % labels_plot constructor

      n = t1-t0+1;

      labels_plot = struct();
      labels_plot.n = n;
      labels_plot.off = 1-t0;
      labels_plot.nflies = nflies;
      labels_plot.nbeh = nBeh;
      labels_plot.nTL = nTL;
      labels_plot.beh2TL = beh2TL;
      labels_plot.TL2beh = TL2beh;

      labels_plot.im = zeros(nTL,n,3);
      labels_plot.predicted_im = []; % image for predicted timeline
      labels_plot.suggest_xs = nan;
      labels_plot.error_xs = nan;
      labels_plot.suggest_gt = nan;
      %labels_plot.suggested_im = zeros([1,n,3]);
      %labels_plot.error_im = zeros([1,n,3]);
      labels_plot.x = nan(2,n,nBeh,nflies);
      labels_plot.y = nan(2,n,nBeh,nflies);
      labels_plot.predx = nan(2,n,nBeh,nflies);
      labels_plot.predy = nan(2,n,nBeh,nflies);
    end

    function labels_plot = labelsPlotClearXYLabels(labels_plot,ifly,iBeh,t0,t1)
      % Clear .x, .y for given flies/behaviors/time interval.
      % ifly: vector of fly indices. if -1, use 1:.nflies.
      % iBeh: vector of behavior indices. if -1, use 1:.nbeh.
      % t0, t1: scalar time indices

      if isequal(ifly,-1)
        ifly = 1:labels_plot.nflies;
      end
      if isequal(iBeh,-1)
        iBeh = 1:labels_plot.nbeh;
      end
      assert(t0<=t1);
      idx = (t0:t1)+labels_plot.off;

      labels_plot.x(:,idx,iBeh,ifly) = nan;
      labels_plot.y(:,idx,iBeh,ifly) = nan;
    end

    function labels_plot = labelsPlotWriteXYLabelsInterval(labels_plot,iFly,...
        iBeh,t0,t1,x,y)
      % Write a track (x,y) to .x, .y over a certain time interval.
      %
      % iFly: scalar fly index
      % iBeh: scalar behavior index
      % t0, t1: scalar time indices
      % x: vector of length t1-t0+2. NOTE: this is ONE LONGER than
      %   numel(t0:t1)
      % y: vector of length t1-t0+2. ONE LONGER than numel(t0:t1).

      assert(isscalar(iFly));
      assert(isscalar(iBeh));
      assert(t0<=t1);
      idx = (t0:t1)+labels_plot.off;
      n = t1-t0+1;
      assert(numel(x)==n+1);
      assert(numel(y)==n+1);
      x = x(:)';
      y = y(:)';

      labels_plot.x(:,idx,iBeh,iFly) = [x(1:end-1);x(2:end)];
      labels_plot.y(:,idx,iBeh,iFly) = [y(1:end-1);y(2:end)];
    end

    function labels_plot = labelsPlotWriteXYFull(labels_plot,ifly,x,y,...
        labelidx,predictedidx,scores,confThreshs)
      % Update labels_plot.x, .y, .predx, .predy from labels/predictions.
      %
      % ifly: scalar fly index (into eg labels_plot.x(:,:,:,ifly)
      % x, y: vectors, track positions
      % labelidx: .vals field from labelIdx structure. Values are in
      %   1:labels_plot.nbeh
      % predictedidx: optional, can be [] if no prediction. Values are in
      %   {0,1,2,1.5}, see JLabelData.GetPredictedIdx.
      % scores: optional, can be [] if no prediction. See GetPredictedIdx.
      % confThreshs: vector of length labels_plot.nbeh, or [] if no pred

      %MERGESTUPDATED

      assert(isscalar(ifly) && any(ifly==1:labels_plot.nflies));
      assert(isequal(numel(x),numel(y),labels_plot.n));
      assert(isequal([labels_plot.nTL labels_plot.n],size(labelidx)));
      tfPred = ~isempty(predictedidx);
      if tfPred
        assert(isequal([labels_plot.nTL labels_plot.n],size(predictedidx),size(scores)));
        assert(isvector(confThreshs)&&numel(confThreshs)==labels_plot.nbeh);
      end

      for ibeh = 1:labels_plot.nbeh
        iTL = labels_plot.beh2TL(ibeh);
        tfBeh = labelidx(iTL,:)==ibeh;

        idx = find(tfBeh);
        if isempty(idx)
          idx1 = double(labels_plot.n);
        else
          idx1 = min(idx+1,double(labels_plot.n));
        end
        labels_plot.x(1,idx,ibeh,ifly) = x(idx);
        labels_plot.x(2,idx,ibeh,ifly) = x(idx1);
        labels_plot.y(1,idx,ibeh,ifly) = y(idx);
        labels_plot.y(2,idx,ibeh,ifly) = y(idx1);
      end
      if tfPred
        for iTL = 1:labels_plot.nTL
          iBehs = labels_plot.TL2beh{iTL};
          assert(numel(iBehs)==2);
          iBehPos = iBehs(1);
          iBehNeg = iBehs(2);

          idxPos = predictedidx(iTL,:)==1 & ...
                    abs(scores(iTL,:))>confThreshs(iBehPos);
          idxNeg = predictedidx(iTL,:)==2 & ...
                    abs(scores(iTL,:))>confThreshs(iBehNeg);
          idxPos = find(idxPos);
          idxNeg = find(idxNeg);
          idxPos1 = min(idxPos+1,labels_plot.n);
          idxNeg1 = min(idxNeg+1,labels_plot.n);

          labels_plot.predx(1,idxPos,iBehPos,ifly) = x(idxPos);
          labels_plot.predx(2,idxPos,iBehPos,ifly) = x(idxPos1);
          labels_plot.predx(1,idxNeg,iBehNeg,ifly) = x(idxNeg);
          labels_plot.predx(2,idxNeg,iBehNeg,ifly) = x(idxNeg1);
          labels_plot.predy(1,idxPos,iBehPos,ifly) = y(idxPos);
          labels_plot.predy(2,idxPos,iBehPos,ifly) = y(idxPos1);
          labels_plot.predy(1,idxNeg,iBehNeg,ifly) = y(idxNeg);
          labels_plot.predy(2,idxNeg,iBehNeg,ifly) = y(idxNeg1);
        end
      end
    end

    % Note: labels_plot.x and .y are directly modified in
    % JLabel/SetLabelPlot

%     function labels_plot = labelsPlotWriteIm(labels_plot,t0,t1,labelidx,...
%         labelcolors,unkcolor)
%       % Write labels to labels_plot.im in time interval [t0,t1]. Image data
%       % outside that range is unaffected.
%       %
%       % labelidx: .vals, .imp, should be constrained to time interval [t0 t1]
%
%       assert(t0<=t1);
%       n = t1-t0+1;
%       assert(labelidx.nbeh==labels_plot.nbeh);
%       assert(isequal(size(labelidx.vals),size(labelidx.imp),...
%         [labels_plot.nTL n]));
%       assert(isequal(size(labelcolors),[labels_plot.nbeh 3]));
%
%       idx = (t0:t1)+labels_plot.off;
%       imslice = labels_plot.im(:,idx,:);
%       for chan = 1:3
%         imslice(:,:,chan) = unkcolor(chan);
%       end
%
%       % Permute image matrix to make it easier to assign behavior colors
%       imslice = permute(imslice,[3 1 2]); % imslice is now 3xnTLxn
%
%       for behaviori = 1:labels_plot.nbeh
%         tf = (labelidx.vals==behaviori) & labelidx.imp;
%         curColor = labelcolors(behaviori,:);
%         for channel = 1:3,
%           imslice(channel,tf) = curColor(channel);
%         end
%
%         tf = (labelidx.vals==behaviori) & ~labelidx.imp;
%         curColor = ShiftColor.decreaseIntensity(labelcolors(behaviori,:));
%         for channel = 1:3,
%           imslice(channel,tf) = curColor(channel);
%         end
%       end
%
%       labels_plot.im(:,idx,:) = permute(imslice,[2 3 1]);
%
%       % JLabel/SetLabelPlot does direct access to labels_plot.im
%     end

    function labels_plot = labelsPlotWriteImInterval(labels_plot,iTL,t0,t1,color)
      % Write a single color to a time interval
      %
      % iTL: vector of timeline indices. If equal to -1, use 1:nTL.
      % t0, t1: time indices
      % color: 3-element RGB color

      if isequal(iTL,-1)
        iTL = 1:labels_plot.nTL;
      end
      assert(t0<=t1);
      idx = (t0:t1)+labels_plot.off;
      for chan = 1:3
        labels_plot.im(iTL,idx,chan) = color(chan);
      end
    end

    function labels_plot = labelsPlotWriteIm(labels_plot,labelidx,labelcolors,unkcolor)
      % Write all labels from labelidx to labels_plot.

      assert(labels_plot.nbeh==labelidx.nbeh);
      assert(isequal(size(labelcolors),[labels_plot.nbeh 3]));

      for chan = 1:3
        labels_plot.im(:,:,chan) = unkcolor(chan);
      end

      % Permute image matrix to make it easier to assign behavior colors
      % MK-- permuting maybe slow, removing it.
%       im = permute(labels_plot.im,[3 1 2]); % im is now 3xnTLxn

      for behaviori = 1:labels_plot.nbeh
        curTL = labels_plot.beh2TL(behaviori);
        tf = (labelidx.vals(curTL,:) == behaviori) & labelidx.imp(curTL,:);
        curColor = labelcolors(behaviori,:);
        for channel = 1:3,
%           im(channel,tf) = curColor(channel); % if using the permute above.
          labels_plot.im(curTL,tf,channel) = curColor(channel);
        end

        tf = (labelidx.vals(curTL,:) == behaviori) & ~labelidx.imp(curTL,:);
        curColor = ShiftColor.decreaseIntensity(labelcolors(behaviori,:));
        for channel = 1:3,
%           im(channel,tf) = curColor(channel);
          labels_plot.im(curTL,tf,channel) = curColor(channel);
        end
      end

%       labels_plot.im = permute(im,[2 3 1]);

      % JLabel/SetLabelPlot does direct access to labels_plot.im
    end

    function labels_plot = labelsPlotSetPredIm(labels_plot,...
        scores,pred,confThresh,bottomType,bottomDist,...
        scores_bottom,pred_bottom,labelcolors,scorecolor)
      % Set labels_plot.predicted_im, single classifier version
      % - Top: binary prediction
      % - Middle: raw scores
      % - Bottom: configureable
      %
      % scores: 1 x n double, normalized scores
      % pred: 1 x n. 1==beh, 2==no-beh (also allowed, 0 or 1.5. See JLabelData.GetPredictedIdx)
      % confThresh: 1x2 array for beh/noBeh resp
      % bottomType: char enum
      % bottomDist: n-long vector, only used if bottomType=='Distance'
      % scores_bottom: 1 x n double
      % pred_bottom: 1 x n. 1==beh, 2==no-beh (not used if bottomType=='Distance')
      % labelcolors: nbeh x 3 (nbeh==2)
      % scorecolors: 63x3x3

      %MERGESTUPDATED

      assert(isequal(size(scores),size(pred),size(scores_bottom),size(pred_bottom)));
      assert(numel(confThresh)==2);
      %assert(size(labels_plot.predicted_im,1)==6);

      labels_plot.predicted_im = zeros(6,labels_plot.n,3);

      idxBottomScores = ~isnan(scores_bottom);
      bottomScoreNdx = ceil(scores_bottom(idxBottomScores)*31)+32;

      im = labels_plot.predicted_im;
%       im(:) = 0;
      for iBeh = 1:2
        idxScores = pred==iBeh;
        idxPredict = idxScores & abs(scores)>confThresh(iBeh);
        idxBottom = pred_bottom==iBeh;
        scoreNdx = ceil(scores(idxScores)*31)+32; % scoreNdx in [1,63]
        for channel = 1:3
          im(1,idxPredict,channel) = labelcolors(iBeh,channel);
          im(2,idxPredict,channel) = labelcolors(iBeh,channel);
          im(3,idxScores,channel) = scorecolor(scoreNdx,channel,1);
          im(4,idxScores,channel) = scorecolor(scoreNdx,channel,1);

          % Bottom row (configureable)
          if strcmp(bottomType,'Distance')
            im(5:6,:,channel) = repmat(1-bottomDist(:)',[2 1 1]);
            im(5:6,isnan(bottomDist(:)'),channel) = 0;
          else
            im(5,idxBottomScores,channel) = scorecolor(bottomScoreNdx,channel,1);
            im(6,idxBottom,channel) = labelcolors(iBeh,channel);
          end
        end
      end

      labels_plot.predicted_im = im;
    end

    function labels_plot = labelsPlotSetPredImMultiClsAnalog(labels_plot,scores,scorecolors)
      % scores: 1 x n double, normalized scores
      % scorecolors: cell vector with nclassifiers elements. Each element
      %   scorecolors{iCls} is 63x3x3

      nTL = labels_plot.nTL;
      assert(isequal(size(scores),[nTL labels_plot.n]));
      assert(numel(scorecolors)==nTL);

      scores(isnan(scores)) = 0;

      labels_plot.predicted_im = zeros(nTL,labels_plot.n,3);
      im = labels_plot.predicted_im;
      im(:) = 0;
      for iTL = 1:nTL
        scoreNdx = ceil(scores(iTL,:)*31)+32; % scoreNdx in [1,63]
        scoreclr = scorecolors{iTL};
        for channel = 1:3
          im(iTL,:,channel) = scoreclr(scoreNdx,channel,1);
        end
      end

      labels_plot.predicted_im = im;
    end

    function labels_plot = labelsPlotSetPredImMultiClsBinary(labels_plot,...
        predIdx,scores,confThreshs,labelcolors)
      % Set labels_plot.predicted_im, multiclass version
      % At the moment, we just show the predicted (binary) bouts, as the
      % regular tripartite timeline is likely too cluttered for multiple
      % classifiers.
      %
      % predIdx: ntimelines x nSamp array, values in {0,1,2,1.5}, see JLabelData.GetPredictedIdx
      % scores: ntimelines x nSamp
      % confThreshs: ntimelines x 2. confThreshs(i,:) is [lo hi] thresholds
      %   for ith classifier/timeline
      % labelcolors: nbehaviors x 3 color array

      %MERGESTUPDATED

      nTL = labels_plot.nTL;
      nSamp = labels_plot.n;
      assert(isequal([nTL nSamp],size(predIdx),size(scores)));
      assert(isequal(size(confThreshs),[nTL 2]));
      assert(isequal(size(labelcolors),[labels_plot.nbeh 3]));

      labels_plot.predicted_im = zeros(nTL,nSamp,3);
      %assert(isequal(size(labels_plot.predicted_im),[nTL labels_plot.n 3]));

      im = labels_plot.predicted_im;
      im(:) = 0;
      for iTL = 1:nTL
        iLbls = labels_plot.TL2beh{iTL};
        for i12 = [1 2]
          iBeh = iLbls(i12);
          ct = confThreshs(iBeh);
          assert(ct==confThreshs(iTL,i12));

          tfPred = predIdx(iTL,:)==i12 & abs(scores(iTL,:))>ct;

          curColor = labelcolors(iBeh,:);
          for channel = 1:3,
            im(iTL,tfPred,channel) = curColor(channel);
          end
        end
      end

      labels_plot.predicted_im = im;
    end

  end

end

author: kristinbranson

repo: JAABA


text:
function result = bdf_sum ( func, n, x, w )

%*****************************************************************************80
%
%% BDF_SUM carries out an explicit backward difference quadrature rule for [0,1].
%
%  Discussion:
%
%    The integral:
%
%      Integral ( 0 <= X <= 1 ) F(X) dX
%
%    The quadrature rule:
%
%      sum ( 1 <= I <= N ) W(I) * BDF^(I-1) FUNC ( 0 )
%
%    The integral from 0 to 1 is approximated using data at X = 0,
%    -1, -2, ..., -N+1.  This is a form of extrapolation, and
%    the approximation can become poor as N increases.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 June 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, external FUNC, the function which evaluates
%    the integrand.  The function must have the form
%      function value = func ( x ).
%
%    Input, integer N, the order.
%
%    Input, real X(N), the abscissas.
%
%    Input, real W(N), the weights.
%
%    Output, real RESULT, the approximate value of the integral.
%
  diftab = zeros ( n, 1 );

  for i = 1 : n
    diftab(i) = func ( x(i) );
  end

  for i = 2 : n
    for j = i : n
      diftab(n+i-j) = ( diftab(n+i-j-1) - diftab(n+i-j) );
    end
  end

  result = w(1:n)' * diftab(1:n);

  return
end

author: johannesgerer

repo: jburkardt-m