text:
% ***************************************************************************
% Problem definition
% ***************************************************************************
% Author: Chaobin
% Email:  chaubyZou@163.com
% Date: October 2020
% ***************************************************************************
% Language: Matlab
% Also available in: Python
% Required library: None
% ***************************************************************************

clear;

q = [0, 1.6, 2.5, 2, 4, 1.5, 0]';
t = [0, 1, 3, 4.5, 6, 8, 10]';

figure()
plot(t, q, 'ro')
xlabel('time')
ylabel('position')
xlim([-1, 11])
ylim([-1, 5])

author: chauby

repo: PolynomialInterpolation


text:
function sF = volume(sF1,center,radius)

sF = sF1;

sF.values = sF1.values;

sF = volume(sF.values, center, radius);

end

author: mtex-toolbox

repo: mtex

save_path: github-repos/MATLAB/mtex-toolbox-mtex


text:
function edge = clipLine3d(line, box)
%CLIPLINE3D Clip a line with a box and return an edge.
%
%   EDGE = clipLine3d(LINE, BOX);
%   Clips the line LINE with the bounds given in BOX, and returns the
%   corresponding edge.
%
%   If the line lies totally outside of the box, returns a 1-by-6 row array
%   containing only NaN's.
%
%   If LINE is a N-by-6 array, with one line by row, returns the clipped
%   edge coresponding to each line in a N-by-6 array.
%
%   See also
%   lines3d, edges3d, createLine3d, clipRay3d
%

% ------
% Author: David Legland
% E-mail: david.legland@inra.fr
% Created: 2008-10-30, from drawLine3d
% Copyright 2008-2022 INRA - TPV URPOI - BIA IMASTE

% get box limits
xmin = box(1); xmax = box(2);
ymin = box(3); ymax = box(4);
zmin = box(5); zmax = box(6);

% extreme corners of the box
p000 = [xmin ymin zmin];
p111 = [xmax ymax zmax];

% main vectors
ex   = [1 0 0];
ey   = [0 1 0];
ez   = [0 0 1];

% box faces parallel to Oxy
planeZ0 = [p000 ex ey];
planeZ1 = [p111 ex ey];

% box faces parallel to Oxz
planeY0 = [p000 ex ez];
planeY1 = [p111 ex ez];

% box faces parallel to Oyz
planeX0 = [p000 ey ez];
planeX1 = [p111 ey ez];

% number of lines
nLines = size(line, 1);

% allocate memory for result
edge = zeros(nLines, 6);

% iterate over lines to clip
for i = 1:nLines

    % compute intersection point with each plane
    ipZ0 = intersectLinePlane(line(i,:), planeZ0);
    ipZ1 = intersectLinePlane(line(i,:), planeZ1);
    ipY0 = intersectLinePlane(line(i,:), planeY0);
    ipY1 = intersectLinePlane(line(i,:), planeY1);
    ipX1 = intersectLinePlane(line(i,:), planeX1);
    ipX0 = intersectLinePlane(line(i,:), planeX0);

    % concatenate resulting points
    points  = [ipX0;ipX1;ipY0;ipY1;ipZ0;ipZ1];

    % compute position of each point on the line
    pos     = linePosition3d(points, line(i,:));

    % keep only defined points
    ind     = find(~isnan(pos));
    pos     = pos(ind);
    points  = points(ind,:);

    % sort points with respect to their position
    [pos, ind] = sort(pos); %#ok<ASGLU>
    points  = points(ind, :);

    % keep median points wrt to position. These points define the limit of
    % the clipped edge.
    nv      = length(ind)/2;

    % create resulting edge.
    edge(i,:)   = [points(nv, :) points(nv+1, :)];
end

% check that middle point of the edge is contained in the box
midX = mean(edge(:, [1 4]), 2);
xOk  = xmin <= midX & midX <= xmax;
midY = mean(edge(:, [2 5]), 2);
yOk  = ymin <= midY & midY <= ymax;
midZ = mean(edge(:, [3 6]), 2);
zOk  = zmin <= midZ & midZ <= zmax;

% if one of the bounding condition is not met, set edge to NaN
edge (~(xOk & yOk & zOk), :) = NaN;

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function pass = test_bvp4c(pref)

if ( nargin == 0 )
    pref = chebfunpref();
end

%% Test using TWOODE():
d = [0, 4];
y0 = chebfun([1, 0], d, pref);
solinit = bvpinit([0, 1, 2, 3, 4], [1, 0]);
% Test bvp4c using default tolerance (RelTol = 1e-3)
y = bvp4c(@twoode, @twobc, y0);         % Chebfun solution
sol = bvp4c(@twoode, @twobc, solinit);  % Matlab's solution
pass(1) = max(max(abs(sol.y' - feval(y,sol.x')))) < 2e-2;

%% Test using MAT4BC(): (A problem with a parameter)

tol = 1e-4;

p_true = 17.096591689705100;
sol1_true = [-0.703689352093852, 1.033088348257337];

% Problem parameter, shared with nested functions.
q = 5;
lambda = 15;

% Derivative function. q is provided by the outer function.
mat4ode = @(x, y, lambda) [ y(2) ; -(lambda - 2*q*cos(2*x))*y(1) ];
% Boundary conditions. lambda is a required argument.
mat4bc = @(ya, yb, lambda) [ ya(2) ; yb(2) ; ya(1)-1 ];
% Auxiliary function -- initial guess for the solution
mat4init = @(x) [ cos(4*x) , -4*sin(4*x) ];

opts = odeset('AbsTol', 1e-5, 'RelTol', 1e-5);
solinit = bvpinit(linspace(0, pi, 10), mat4init, lambda);
solinit = chebfun(mat4init, [0, pi]);

[sol, p] = bvp4c(mat4ode, mat4bc, solinit, lambda, opts);
sol1 = feval(sol, 1);
pass(2) = norm(sol1 - sol1_true, inf) < tol;
pass(3) = abs(p - p_true) < tol;

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
% test for run length coding

% some signal with long cluster of 0/1
n = 1024*2;
options.alpha = 0.1;
x = load_signal('regular',n,options);
x = (x-mean(x))>0;

options.rle_coding_mode = 'shannon';
[tmp,nb_shannon] = perform_rle_coding(x, +1, options);
disp(sprintf('Shannon = %.2f', nb_shannon));

options.rle_coding_mode = 'arithmetic';
[tmp,nb_arith] = perform_rle_coding(x, +1, options);
disp(sprintf('Arithmetic = %.2f', nb_arith));

options.rle_coding_mode = 'arithfixed';
[tmp,nb_arithfixed] = perform_rle_coding(x, +1, options);
disp(sprintf('Arithmetic(laplacian) = %.2f', nb_arithfixed));

[tmp,nb_direct] = perform_arithmetic_coding(x, +1);
disp(sprintf('Direct(entropy) = %.2f', nb_direct));

options.rle_coding_mode = 'nocoding';
[tmp,nb_nocode] = perform_rle_coding(x, +1, options);
disp(sprintf('No code = %.2f', nb_nocode));

% test for bijectivity
options.rle_coding_mode = 'nocoding';
stream = perform_rle_coding(x, +1, options);
xx = perform_rle_coding(stream, -1, options);
disp( sprintf('Error (should be 0): %.2f', norme(x-xx)) );

options.rle_coding_mode = 'arithfixed';
stream = perform_rle_coding(x, +1, options);
xx = perform_rle_coding(stream, -1, options);
disp( sprintf('Error (should be 0): %.2f', norme(x-xx)) );

author: gpeyre

repo: matlab-toolboxes


text:
function out = convert_caffe2img( out )
    assert(length(size(out)) <= 4, 'Only support at most 4-D data for convert.');
    out = single(permute(out(:,:,end:-1:1,:), [2 1 3 4]));
end

author: liuyuisanai

repo: RSA-for-object-detection


text:
function y = nanstd(varargin)
%NANSTD Standard deviation, ignoring NaNs.
%   Y = NANSTD(X) returns the sample standard deviation of the values in X,
%   treating NaNs as missing values.  For a vector input, Y is the standard
%   deviation of the non-NaN elements of X.  For a matrix input, Y is a row
%   vector containing the standard deviation of the non-NaN elements in
%   each column of X. For N-D arrays, NANSTD operates along the first
%   non-singleton dimension of X.
%
%   NANSTD normalizes Y by (N-1), where N is the sample size.  This is the
%   square root of an unbiased estimator of the variance of the population
%   from which X is drawn, as long as X consists of independent, identically
%   distributed samples and data are missing at random.
%
%   Y = NANSTD(X,1) normalizes by N and produces the square root of the
%   second moment of the sample about its mean.  NANSTD(X,0) is the same as
%   NANSTD(X).
%
%   Y = NANSTD(X,FLAG,DIM) takes the standard deviation along dimension
%   DIM of X.
%
%   See also STD, NANVAR, NANMEAN, NANMEDIAN, NANMIN, NANMAX, NANSUM.

%   Copyright 1993-2006 The MathWorks, Inc.
%   $Revision: 1.1.8.1 $  $Date: 2010/03/16 00:15:53 $

% Call nanvar(x,flag,dim) with as many inputs as needed
y = sqrt(nanvar(varargin{:}));

author: marianux

repo: ecg-kit

save_path: github-repos/MATLAB/marianux-ecg-kit


text:
function pptClose(op,ppt,pptFile);
% For Windows machines only: Close an ActiveX Server for
% a particular power point file, saving along the way.
%
% Usage:
%   pptClose(op,ppt,pptFile);
%
% ras, 10/2005.
[p f ext] = fileparts(pptFile);
if ~isempty(p),
	callingDir = pwd;
	cd(p);
end

if ~exist(pptFile,'file')
  % Save file as new:
  invoke(op,'SaveAs',pptFile,1);
else
  % Save existing file:
  invoke(op,'Save');
end

% Close the presentation window:
invoke(op,'Close');

% % Quit PowerPoint
% invoke(ppt,'Quit');

% % Close PowerPoint and terminate ActiveX:
% delete(ppt);

if exist('callingDir', 'var')
	cd(callingDir);
end

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function Show_RVT_Peak(R,fg),
   for (icol = 1:1:length(R)),
      figure(fg); clf
      set (fg, 'KeyPressFcn', @afni_fig_interface);
      subplot(211);
      plot (R(icol).t, real(R(icol).X),'g'); hold on
      if (~isempty(R(icol).RVT)),
         subplot (211);
            plot (R(icol).tmidprd,...
                  zscale(R(icol).RVT, max(R(icol).ptrace),...
                  min(R(icol).ptrace)), 'k');
      end
      plot( R(icol).tptrace, R(icol).ptrace,'ro',...
            R(icol).tptrace, R(icol).ptrace,'r');
      plot( R(icol).tntrace, R(icol).ntrace,'bo',...
            R(icol).tntrace, R(icol).ntrace,'b');
      plot (R(icol).tmidprd, R(icol).ptracemidprd,'kx');
      for (i=1:1:length(R(icol).prd)),
       text( R(icol).tmidprd(i), R(icol).ptracemidprd(i),...
             sprintf('%.2f', R(icol).prd(i)));
      end
      if (isfield(R(icol), 'tR')),
         if (isfield(R(icol), 'ptraceR')),
            plot( R(icol).tR, R(icol).ptraceR,'m');
            plot( R(icol).tR, R(icol).ntraceR,'y');
         end
         if (  isfield(R(icol), 'RVTRS')),
               plot( R(icol).tR,...
                     zscale(  R(icol).RVTRS, max(R(icol).ptrace),...
                              min(R(icol).ptrace) ),...
                     'k.');
         end
      end
      xlabel('time (sec)');
      title (R(icol).vname, 'Interpreter', 'None');

      subplot (413);
      vn = real(R(icol).X)./(abs(R(icol).X)+eps);
      plot (R(icol).t, vn, 'g'); hold on

      plot (R(icol).t, R(icol).phz./2./pi, 'm');
      if (isfield(R(icol), 'phzR')),
         plot (R(icol).tR, R(icol).phzR./2./pi, 'm-.');
      end
      xlabel('time (sec)');
      title ('Scaled by magnitude of analytical signal', 'Interpreter', 'None');
      legend({'Scaled signal','phase'});

      subplot (414);
      plot (R(icol).tst, R(icol).phz_slc(:,1), 'ro', ...
            R(icol).tst, R(icol).phz_slc(:,2), 'bo', ...
            R(icol).tst, R(icol).phz_slc(:,2), 'b-'); hold on;
      plot (R(icol).t, R(icol).phz, 'k');
      grid on
      xlabel('time (sec)');
      title ('Phase sampled at slice acquisition time');
      legend({'slice 0', 'slice 1', 'slice 1', 'original phase'});
      plotsign2(fg);
      drawnow;
   end
return;

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
%
% 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/>.

test = which('commons-cli-1.0.jar');
path =  fileparts(test);

allFiles = dir(path);
dpath = [];

for i = 1:length(allFiles)
    if ~ allFiles(i).isdir
        if i == 1
            dpath = {[path '\' allFiles(i).name]};
        else
            file = {[path '\' allFiles(i).name]};
            dpath = vertcat(dpath, file);
        end
    end
end
javaclasspath(dpath)

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
%% SATISFY_FSU uses the fsuClusterMatlab command to run the SATISFY computation.
%
%  Discussion:
%
%    The arguments to fsuClusterMatlab mean:
%
%    [] allows us to specify an output directory;
%    [] allows us to specify switches to the MOAB queue handler, such as more time.
%    'p" indicates this is a "parfor" job;
%    'w' indicates that the MATLAB session should wait for completion;
%    4 is the number of processors requested;
%    @sat_fun indicates the function we want to execute;
%    {} would contain input arguments if there were any.
%
%    The function "satisfy_fun" must correspond to a MATLAB M-file "satisfy_fun.m"
%    and that file must be in MATLAB's path.
%
%    The easiest way to ensure that the file is in MATLAB's path is to
%    create a subdirectory called "matlab" immediately below your home directory,
%    and place the function file there (as well as any other files needed by the job).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 May 2010
%
%  Author:
%
%    John Burkardt
%
  results = fsuClusterMatlab ( [], [], 'p', 'w', 4, @satisfy_fun, {} );

author: johannesgerer

repo: jburkardt-m


text:
function net = knn(nin, nout, k, tr_in, tr_targets)
%KNN	Creates a K-nearest-neighbour classifier.
%
%	Description
%	NET = KNN(NIN, NOUT, K, TR_IN, TR_TARGETS) creates a KNN model NET
%	with input dimension NIN, output dimension NOUT and K neighbours.
%	The training data is also stored in the data structure and the
%	targets are assumed to be using a 1-of-N coding.
%
%	The fields in NET are
%	  type = 'knn'
%	  nin = number of inputs
%	  nout = number of outputs
%	  tr_in = training input data
%	  tr_targets = training target data
%
%	See also
%	KMEANS, KNNFWD
%

%	Copyright (c) Ian T Nabney (1996-2001)

net.type = 'knn';
net.nin = nin;
net.nout = nout;
net.k = k;
errstring = consist(net, 'knn', tr_in, tr_targets);
if ~isempty(errstring)
  error(errstring);
end
net.tr_in = tr_in;
net.tr_targets = tr_targets;

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function [ x, y ] = dswap ( n, x, incx, y, incy )

%*****************************************************************************80
%
%% DSWAP interchanges two vectors.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 June 2005
%
%  Author:
%
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Jack Dongarra, Cleve Moler, Jim Bunch and Pete Stewart,
%    LINPACK User's Guide,
%    SIAM, 1979.
%
%    Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,
%    Basic Linear Algebra Subprograms for Fortran Usage,
%    Algorithm 539,
%    ACM Transactions on Mathematical Software,
%    Volume 5, Number 3, September 1979, pages 308-323.
%
%  Parameters:
%
%    Input, integer N, the number of entries in the vectors.
%
%    Input, real X(*), one of the vectors to swap.
%
%    Input, integer INCX, the increment between successive entries of X.
%
%    Input, real Y(*), one of the vectors to swap.
%
%    Input, integer INCY, the increment between successive elements of Y.
%
%    Output, real X(*), the swapped vector.
%
%    Output, real Y(*), the swapped vector.
%
  if ( n <= 0 )

  elseif ( incx == 1 & incy == 1 )

    m = mod ( n, 3 );

    for i = 1 : m
      temp = x(i);
      x(i) = y(i);
      y(i) = temp;
    end

    for i = m+1 : 3 : n

      temp = x(i);
      x(i) = y(i);
      y(i) = temp;

      temp = x(i+1);
      x(i+1) = y(i+1);
      y(i+1) = temp;

      temp = x(i+2);
      x(i+2) = y(i+2);
      y(i+2) = temp;

    end

  else

    if ( 0 <= incx )
      ix = 1;
    else
      ix = ( - n + 1 ) * incx + 1;
    end

    if ( 0 <= incy )
      iy = 1;
    else
      iy = ( - n + 1 ) * incy + 1;
    end

    for i = 1 : n
      temp = x(ix);
      x(ix) = y(iy);
      y(iy) = temp;
      ix = ix + incx;
      iy = iy + incy;
    end

  end

  return
end


text:
function F = lowrank(F,x)
% LOWRANK is used to declare that a semidefinite constraint uses data with low rank.
% Used in combination with the solver SDPLR

identifiers = [];
F = flatten(F);
for i = 1:length(F.LMIid)
    switch F.clauses{i}.type
        case 1
            identifiers = [identifiers F.LMIid(i)];
        otherwise
    end
end

if isempty(identifiers)
    F = ([]);
    return
end

if nargin>1
    variables = getvariables(x);
else
    variables = [];
end

lrData.id = identifiers;
lrData.variables = variables;

%F.clauses = {{F.clauses{1}}};
F.clauses{1}.data = lrData;
F.clauses{1}.type  = 14;
F.LMIid = -1;
F.clauses{1}.strict = 0;
F.clauses{1}.cut = 0;

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
function [ vW ] = LmsFilter( vW, mY, vD, numSamples, stepSize, normalizeMode )
% ----------------------------------------------------------------------------------------------- %
% [ vW ] = LmsFilter( vY, vD, stepSize, vW, paramN, paramM, paramL, normalizeMode )
% Applies the Least Mean Squares Adaptive Filter for optimal 'vW' weights
% given the reference signal vD.
% Input:
%   - vW                -   Filter Taps.
%                           The adaptive filter taps (To be updated).
%                           Structure: Vector (paramL x 1).
%                           Type: 'Single' / 'Double'.
%                           Range: (-inf, inf).
%   - vY                -   Input Signal.
%                           The signal to be filtered to by the adaptive
%                           filter to match the reference signal.
%                           Structure: Vector (numSamples x 1.
%                           Type: 'Single' / 'Double'.
%                           Range: (-inf, inf).
%   - vD                -   Reference Signal.
%                           The reference signal
%                           Structure: Vector (numSamples x 1).
%                           Type: 'Single' / 'Double'.
%                           Range: (-inf, inf).
%   - paramL            -   Number of Taps.
%                           Number of taps of the adaptive filter.
%                           Structure: Scalar.
%                           Type: 'Single' / 'Double'.
%                           Range: {1, 2, 3, ...}.
%   - numSamples        -   Number of Samples.
%                           Number of samples of the input vector 'vY' and
%                           'vD'.
%                           Structure: Scalar.
%                           Type: 'Single' / 'Double'.
%                           Range: {1, 2, 3, ..., min(length(vY), length(vD)}.
%   - stepSize          -   Step Size
%                           The step size (paramMu) of the LMS filter.
%                           Basically the SGD step size.
%                           Structure: Scalar.
%                           Type: 'Single' / 'Double'.
%                           Range: (0, inf).
%   - normalizeMode     -   Normalize Mode.
%                           Normalizes the step size by the norm of the
%                           samples.
%                           Structure: Scalar.
%                           Type: 'Single' / 'Double'.
%                           Range: {0, 1} / {OFF, ON}.
% Output:
%   - vW                -   Filter Taps.
%                           The updated adaptive filter taps.
%                           Structure: Vector (paramL x 1).
%                           Type: 'Single' / 'Double'.
%                           Range: (-inf, inf).
% References:
%   1.  A
% Remarks:
%   1.  The values of the step size must be in the range (0, 2 / lambdaMax)
%       where lambdaMax is the maximum eigen value of the samples
%       covariance.
%   2.  In case of normalization it is usually will converge for stepSize
%       within the range [0, 2).
% TODO:
%   1.  C
% Release Notes:
%   -   1.0.000     07/08/2020  Royi Avital
%       *   First release version.
% ----------------------------------------------------------------------------------------------- %

FALSE   = 0;
TRUE    = 1;

OFF     = 0;
ON      = 1;

DELTA_PARAM = 1e-5;

% mW = zeros(length(vW), numSamples);
% mW(:, 1) = vW;

for ii = 2:numSamples
    vY      = reshape(mY(ii, :), [], 1);
    dSample = vD(ii);

    zSample = vW.' * vY;

    eSample = dSample - zSample;

    if(normalizeMode == ON)
        vW(:) = vW + (stepSize * eSample * vY);
    else
        vW(:) = vW + ((stepSize / ((vY.' * vY) + DELTA_PARAM)) * eSample * vY);
    end

%     mW(:, ii) = vW;

end

end

author: RoyiAvital

repo: StackExchangeCodes


text:
function tests = test_spm_dcm_bmr
% Unit Tests for test_spm_dcm_bmr
%__________________________________________________________________________
% Copyright (C) 2016 Wellcome Trust Centre for Neuroimaging

% $Id: test_spm_dcm_bmr.m 7369 2018-07-09 09:58:03Z peter $

tests = functiontests(localfunctions);

% -------------------------------------------------------------------------
function test_bmr(testCase)

data_path = get_data_path();

% Load PEB of full DCM
PEB = load(fullfile(data_path,'PEB_test.mat'));
PEB = PEB.PEB;
PEB = PEB(1);

% Load DCMs
GCM = load(fullfile(data_path,'models','GCM_simulated.mat'));
GCM = GCM.GCM;

% Limit to 3 subjects for performance
GCM = GCM(1:3,:);

% Prune connections on the B-matrix only
[RCM,BMC,BMA] = spm_dcm_bmr(GCM,{'B'});

% Check outputs have expected sizes
[ns,nm] = size(GCM);
assert(all(size(RCM) == size(GCM)));
assert(all(size(BMC) == [1 ns]));
assert(all(size(BMA) == [1 ns]));

% Again with only two outputs
[RCM,BMC] = spm_dcm_bmr(GCM,{'B'});

% Check outputs have expected sizes
[ns,nm] = size(GCM);
assert(all(size(RCM) == size(GCM)));
assert(all(size(BMC) == [1 ns]));

% -------------------------------------------------------------------------
function test_bmr_single_subject(testCase)

data_path = get_data_path();

% Load PEB of full DCM
PEB = load(fullfile(data_path,'PEB_test.mat'));
PEB = PEB.PEB;
PEB = PEB(1);

% Load DCMs
GCM = load(fullfile(data_path,'models','GCM_simulated.mat'));
GCM = GCM.GCM;

% Limit to 1 subject
GCM = GCM(1,:);

% Prune connections on the B-matrix only
[RCM,BMC,BMA] = spm_dcm_bmr(GCM,{'B'});

% Check outputs have expected sizes
[ns,nm] = size(GCM);
assert(all(size(RCM) == size(GCM)));
assert(all(size(BMC) == [1 ns]));
assert(all(size(BMA) == [1 ns]));

% Again with only two outputs
[RCM,BMC] = spm_dcm_bmr(GCM,{'B'});

% Check outputs have expected sizes
[ns,nm] = size(GCM);
assert(all(size(RCM) == size(GCM)));
assert(all(size(BMC) == [1 ns]));

% -------------------------------------------------------------------------
function data_path = get_data_path()

data_path = fullfile( spm('Dir'), 'tests', ...
    'data', 'fMRI', 'simulated_2region');

author: spm


text:
%  ARROWH   Draws a solid 2D arrow head in current plot.
%
%	 ARROWH(X,Y,COLOR,SIZE,LOCATION) draws a  solid arrow  head into
%	 the current plot to indicate a direction.  X and Y must contain
%	 a pair of x and y coordinates ([x1 x2],[y1 y2]) of two points:
%
%	 The first  point is only used to tell  (in conjunction with the
%	 second one)  the direction  and orientation of  the arrow -- it
%	 will point from the first towards the second.
%
%	 The head of the arrow  will be located in the second point.  An
%	 example of use is	plot([0 2],[0 4]); ARROWH([0 1],[0 2],'b')
%
%	 You may also give  two vectors of same length > 2.  The routine
%	 will then choose two consecutive points from "about" the middle
%	 of each vectors.  Useful if you  don't want to worry  each time
%	 about  where to  put the arrows on  a trajectory.  If x1 and x2
%	 are the vectors x1(t) and x2(t), simply put   ARROWH(x1,x2,'r')
%	 to have the right  direction indicated in your x2 = f(x1) phase
%	 plane.
%
%            (x2,y2)
%            --o
%            \ |
%	            \|
%
%
%		  o
%	  (x1,y1)
%
%	 Please note  that the following  optional arguments  need -- if
%	 you want  to use them -- to  be given in that exact order.  You
%	 may pass on empty vectors "[]" to skip arguments you don't want
%	 to set (if you want to access "later" arguments...).
%
%	 The COLOR argument is quite the same as for plots,  i.e. either
%  a string like  'r' or an RGB value vector like  [1 0 0]. If you
%  only want the outlines of the head  (in other words a non-solid
%  arrow head), prefix the color string by 'e' or the color vector
%  by 0, e.g. to get only a red outline use 'er' or [0 1 0 0].
%
%	 The SIZE argument allows you to tune the size of the arrows. If
%	 SIZE is a scalar, it scales the arrow proportionally.  SIZE can
%	 also be  a two element vector,  where the first element  is the
%	 overall  scale (in percent),  the second one controls the width
%	 of the arrow head (again, in percent).
%
%	 The LOCAITON argument can be used to tweak the position  of the
%  arrow head.  If a time series of x and y coordinates are given,
%  you can use this argument  to place the arrow head for instance
%  at 20% along the line.  It can be a vector, if you want to have
%  more than one arrow head drawn.
%
%	 Both SIZE and LOCATION arguments must also be given in percent,
%	 where 100 means standard size, 50 means half size, respectively
%	 100 means end of the vector, 0 beginning of it. Note that those
%	 "locations" correspond to the cardinal position "inside" the
%	 vector, in other words the "index-wise" position.
%
%	 This little tool is mainely intended  to be used for indicating
%	 "directions" on trajectories -- just give two consecutive times
%	 and the corresponding values of a flux and the proper direction
%	 of the trajectory will be shown on the plot.  You may also pass
%	 on two solution vectors, as described above.
%
%	 Note, that the arrow  heads only look good in the original axis
%	 settings (as in when the routine was actually started).  If you
%	 zoom in afterwards, the triangle will get distorted.
%
%  HANDLES = ARROWH(...)  will give you a vector with  the handles
%  to the patches created by this function  (if you want to modify
%  them later on, for instance).
%
%	 Examples of use:
% 	 x1 = [0:.2:2]; x2 = [0:.2:2]; plot(x1,x2); hold on;
% 	 arrowh(x1,x2,'r',[],20);            % passing entire vectors
% 	 arrowh([0 1],[0 1],'eb',[300,75]);  % passing 2 points
% 	 arrowh([0 1],[0 1],'eb',[300,75],25); % head closer to (x1,y1)

%	 Author:     Florian Knorn
%	 Email:      florian@knorn.org
%	 Version:    1.14
%	 Filedate:   Jun 18th, 2008
%
%	 History:    1.14 - LOCATION now also works with lines
%              1.13 - Allow for non-solid arrow heads
%              1.12 - Return handle(s) of created patches
%              1.11 - Possibility to change width
%	             1.10 - Buxfix
%	             1.09 - Possibility to chose *several* locations
%	             1.08 - Possibility to chose location
%	             1.07 - Choice of color
%	             1.06 - Bug fixes
%	             1.00 - Release
%
%	 ToDos:      - Keep proportions when zooming or resizing; has to
%	               be done with callback functions, I guess.
%
%	 Bugs:       None discovered yet, those discovered were fixed
%
%	 Thanks:     Thanks  also  to Oskar Vivero  for using  my humble
%	             little program in his great MIMO-Toolbox.
%
%	 If you have  suggestions for  this program,  if it doesn't work
%	 for your "situation" or if you change something in it -- please
%	 send me an email!  This is my very  first "public" program  and
%	 I'd  like to  improve it where  I can -- your  help is  kindely
%	 appreciated! Thank you!

function handle = arrowh(x,y,clr,ArSize,Where)

%-- errors
if nargin < 2
	error('Please give enough coordinates !');
end
if (length(x) < 2) || (length(y) < 2),
	error('X and Y vectors must each have "length" >= 2 !');
end
if (x(1) == x(2)) && (y(1) == y(2)),
	error('Points superimposed - cannot determine direction !');
end
if nargin <= 2
	clr = 'b';
end
if nargin <= 3
	ArSize = [100,100];
end

handle = [];

%-- check if variables left empty, deal width ArSize and Color
if isempty(clr)
	clr = 'b'; nonsolid = false;
elseif ischar(clr)
	if strncmp('e',clr,1) % for non-solid arrow heads
		nonsolid = true; clr = clr(2);
	else
		nonsolid = false;
	end
elseif isvector(clr)
	if length(clr) == 4 && clr(1) == 0  % for non-solid arrow heads
		nonsolid = true;
		clr = clr(2:end);
	else
		nonsolid = false;
	end
else
	error('COLOR argument of wrong type (must be either char or vector)');
end

if nargin <= 4
	if (length(x) == length(y)) && (length(x) == 2)
		Where = 100;
	else
		Where = 50;
	end
end

if isempty(ArSize)
	ArSize = [100,100];
end
if length(ArSize) == 2
	ArWidth = 0.75*ArSize(2)/100; % .75 to make arrows it a bit slimmer
else
	ArWidth = 0.75;
end
ArSize = ArSize(1);

%-- determine and remember the hold status, toggle if necessary
if ishold,
	WasHold = 1;
else
	WasHold = 0;
	hold on;
end

%-- start for-loop in case several arrows are wanted
for Loop = 1:length(Where),

	%-- if vectors "longer" then 2 are given we're dealing with time series
	if (length(x) == length(y)) && (length(x) > 2),
		j = floor(length(x)*Where(Loop)/100); %-- determine that location
		if j >= length(x), j = length(x) - 1; end
		if j == 0, j = 1; end
		x1 = x(j); x2 = x(j+1); y1 = y(j); y2 = y(j+1);

	else %-- just two points given - take those
		x1 = x(1); x2 = (1-Where/100)*x(1)+Where/100*x(2);
		y1 = y(1); y2 = (1-Where/100)*y(1)+Where/100*y(2);
	end

	%-- get axe ranges and their norm
	OriginalAxis = axis;
	Xextend = abs(OriginalAxis(2)-OriginalAxis(1));
	Yextend = abs(OriginalAxis(4)-OriginalAxis(3));

	%-- determine angle for the rotation of the triangle
	if x2 == x1, %-- line vertical, no need to calculate slope
		if y2 > y1,
			p = pi/2;
		else
			p= -pi/2;
		end
	else %-- line not vertical, go ahead and calculate slope
		%-- using normed differences (looks better like that)
		m = ( (y2 - y1)/Yextend ) / ( (x2 - x1)/Xextend );
		if x2 > x1, %-- now calculate the resulting angle
			p = atan(m);
		else
			p = atan(m) + pi;
		end
	end

	%-- the arrow is made of a transformed "template triangle".
	%-- it will be created, rotated, moved, resized and shifted.

	%-- the template triangle (it points "east", centered in (0,0)):
	xt = [1	-sin(pi/6)	-sin(pi/6)];
	yt = ArWidth*[0	 cos(pi/6)	-cos(pi/6)];

	%-- rotate it by the angle determined above:
	xd = []; yd = [];
	for i=1:3
		xd(i) = cos(p)*xt(i) - sin(p)*yt(i);
		yd(i) = sin(p)*xt(i) + cos(p)*yt(i);
	end

	%-- move the triangle so that its "head" lays in (0,0):
	xd = xd - cos(p);
	yd = yd - sin(p);

	%-- stretch/deform the triangle to look good on the current axes:
	xd = xd*Xextend*ArSize/10000;
	yd = yd*Yextend*ArSize/10000;

	%-- move the triangle to the location where it's needed
	xd = xd + x2;
	yd = yd + y2;

	%-- draw the actual triangle
	handle(Loop) = patch(xd,yd,clr,'EdgeColor',clr);
	if nonsolid, set(handle(Loop),'facecolor','none'); end
end % Loops

%-- restore original axe ranges and hold status
axis(OriginalAxis);
if ~WasHold,
	hold off
end

%-- work done. good bye.

author: Sable

repo: mcbench-benchmarks


text:
function benchmark_drift_simulation(rez, GTfilepath, simRecfilepath, sortType, bAutoMerge, varargin)

bOutFile = 0;

%these definitions for testing outside a script. comment out for normal calling!
%can leave out last 2 lines if output file not desired
% load('D:\test_new_sim\74U_20um_drift_standard\r28_KS2determ_r26rep\rez2.mat');
% GTfilepath = 'D:\test_new_sim\74U_20um_drift_standard\eMouseGroundTruth.mat';
% simRecfilepath = 'D:\test_new_sim\74U_20um_drift_standard\eMouseSimRecord.mat';
% bOutFile = 1;
% out_fid = fopen('D:\test_new_sim\74U_20um_drift_standard\r28_benchmark_output.txt','w');

sortType = 2;
bAutoMerge = 0;

load(GTfilepath);

if bAutoMerge
    testClu = 1 + rez.st3(:,5) ;
else
    testClu = rez.st3(:,2) ;
end

%fprintf( 'length of vargin: %d\n', numel(varargin));
if( numel(varargin) == 1)
    %path for output file
    bOutFile = 1;
    fprintf( 'output filename: %s\n', varargin{1} );
    out_fid = fopen( varargin{1}, 'w' );
end

testRes = rez.st3(:,1);

[testRes, tOrder] = sort(testRes);
testClu = testClu(tOrder);

%get cluster position footprint for each
[cluPos, unitSize] = getFootPrintRez(rez);

[allScores, allFPrates, allMissRates, allMerges, unDetected, overDetected, gtCluIDs] = ...
    compareClustering2_drift(gtClu, gtRes, testClu, testRes, []);

%

clid = unique(gtClu);
clear gtimes
for k = 1:length(clid)
    gtimes{k} = double(gtRes(gtClu==clid(k)));
end

%% figure and output results
autoMiss = (cellfun(@(x) x(1), allMissRates));
autoFP = (cellfun(@(x) x(1), allFPrates));
bestMiss = (cellfun(@(x) x(end), allMissRates));
bestFP = (cellfun(@(x) x(end), allFPrates));

autoScore = ones(1,numel(bestMiss));
autoScore = autoScore - autoMiss -autoFP;
bestScore = ones(1,numel(bestMiss));
bestScore = bestScore - bestMiss - bestFP;

figure

plot(sort(cellfun(@(x) x(1), allFPrates)), '-*b', 'Linewidth', 2)
hold all
plot(sort(cellfun(@(x) x(1), allMissRates)), '-*r', 'Linewidth', 2)
plot(sort(cellfun(@(x) x(end), allFPrates)), 'b', 'Linewidth', 2)
plot(sort(cellfun(@(x) x(end), allMissRates)), 'r', 'Linewidth', 2)
plot(sort(unDetected), 'g', 'Linewidth', 2);
%plot(sort(overDetected), '-g', 'Linewidth', 2);
ylim([0 1])
box off

thGood = 0.8;

fprintf('%d / %d good cells, score > %.2f (pre-merge) \n', sum(autoScore > thGood), numel(allScores), thGood)
fprintf('%d / %d good cells, score > %.2f (post-merge) \n', sum(bestScore > thGood), numel(allScores), thGood)

nMerges = cellfun(@(x) numel(x)-1, allMerges);
fprintf('Mean merges per good cell %2.2f \n', mean(nMerges(bestScore > thGood)))

% disp(cellfun(@(x) x(end), allScores))

xlabel('ground truth cluster')
ylabel('fractional error')

legend('false positives (initial)', 'miss rates (initial)', 'false positives (best)', 'miss rates (best)', 'undetected')
legend boxoff
set(gca, 'Fontsize', 15)
set(gcf, 'Color', 'w')

if bAutoMerge
    titleStr = sprintf('Kilosort%d with Automerge', sortType);
else
    titleStr = sprintf('Kilosort%d Results', sortType);
end
title(titleStr)

hold off;

%Calculate results vs. known unit properties

%sort these in order of the GT label
[~, sortLabelInd] = sort(gtCluIDs);

bestMiss = bestMiss(sortLabelInd);
bestFP = bestFP(sortLabelInd);

%read in amplitude data for the clusters
%contains yDriftRec nGTSpike x 4 array with
%   spike time in seconds
%   yDrift position
%   GT cluster label
%   nominal amplitude at the monitor site (before mulitplying by factor to
%   create amplitude std)
%
load(simRecfilepath);

%get average amplitude for each cluLabel
NN = numel(unique(yDriftRec(:,3)));
meanAmp = zeros(1,NN);
meanPos = zeros(1,NN);
nSpike = zeros(1,NN);
%for the special case of simulated data, the labels start at 1 and are
%sequential
for i = 1:NN
    ind = find(yDriftRec(:,3) == i);
    nSpike(i) = numel(ind);
    meanAmp(i) = mean(yDriftRec(ind,4));
    meanPos(i) = mean(yDriftRec(ind,2));
end

if( bOutFile )
    fprintf(out_fid, 'GTlabel\tnSpike\tmeanAmp\tmeanPos\tundetected\tbestMiss\tbestFP\tbestScore\tautoMiss\tautoFP\tautoScore\tnMerges\tphy labels\n');
else
    fprintf('GTlabel\tnSpike\tmeanAmp\tmeanPos\tundetected\tbestMiss\tbestFP\tbestScore\tautoMiss\tautoFP\tautoScore\tnMerges\tphy labels\n');
end

nMerges = zeros(1,NN);
for i = 1:NN
    nMerges(i) = length(allMerges{i})-1;
    if( bOutFile)
        fprintf(out_fid, '%d\t%d\t%.3f\t%.3f\t%.3f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%d\t', ...
        i, nSpike(i), meanAmp(i), ...
        meanPos(i), unDetected(i), bestMiss(i), bestFP(i),bestScore(i), autoMiss(i),...
        autoFP(i), autoScore(i), nMerges(i));
        for j = 1:length(allMerges{i})-1
            fprintf( out_fid, '%d,', allMerges{i}(j)-1 );
        end
        fprintf(out_fid,'%d\n',allMerges{i}(length(allMerges{i}))-1);
    else
        fprintf('%d\t%d\t%.3f\t%.3f\t%.3f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%d\t', ...
        i, nSpike(i), meanAmp(i), ...
        meanPos(i), unDetected(i), bestMiss(i), bestFP(i),bestScore(i), autoMiss(i),...
        autoFP(i), autoScore(i), nMerges(i));
        for j = 1:length(allMerges{i})-1
            fprintf( '%d,', allMerges{i}(j)-1 );
        end
        fprintf('%d\n',allMerges{i}(length(allMerges{i}))-1);
    end
end

fclose(out_fid);

end

author: MouseLand

repo: Kilosort

save_path: github-repos/MATLAB/MouseLand-Kilosort


text:
function ha = r8mat_house_hxa ( n, a, v )

%*****************************************************************************80
%
%% R8MAT_HOUSE_HXA computes H*A where H is a compact Householder matrix.
%
%  Discussion:
%
%    The Householder matrix H(V) is defined by
%
%      H(V) = I - 2 * v * v' / ( v' * v )
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 April 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of A.
%
%    Input, real A(N,N), the matrix to be premultiplied.
%
%    Input, real V(N), a vector defining a Householder matrix.
%
%    Output, real HA(N,N), the product H*A.
%
  ha = a - 2.0 * v * v' * a / ( v' * v );

  return
end


text:
function [ Acc ] = cssp_off2on(CNT,general_initparam,tau)

opt = opt_cellToStruct(general_initparam);
% Pre-processing
train_raw = prep_selectChannels(CNT{1}, {'Index', opt.channel_index});
train_cnt =prep_filter(train_raw  , {'frequency', opt.band});
train_smt = prep_segmentation(train_cnt, {'interval', opt.time_interval});

test_raw= prep_selectChannels(CNT{2}, {'Index', opt.channel_index});
test_cnt =prep_filter(test_raw , {'frequency', opt.band});
test_smt = prep_segmentation(test_cnt, {'interval', opt.time_interval});

% Feature extracion and Classification
for len_tau=1:length(tau)
    CV.train={
        '[SMT, CSP_W, CSP_D]=func_csp(SMT,{"nPatterns", [2]})'
        'FT=func_featureExtraction(SMT, {"feature","logvar"})'
        '[CF_PARAM]=func_train(FT,{"classifier","LDA"})'
        };
    CV.test={
        'SMT=func_projection(SMT, CSP_W)'
        'FT=func_featureExtraction(SMT, {"feature","logvar"})'
        '[cf_out]=func_predict(FT, CF_PARAM)'
        };
    CV.option={
        'KFold','10'
        };
    SMT=func_TDE(train_smt,train_cnt,tau(len_tau),opt.time_interval);
    [loss]=eval_crossValidation(SMT, CV); % input : eeg, or eeg_epo
    tau_result(1,len_tau)=1-loss;
end
[acc_cv,max_tau]=max(tau_result);
ttau=tau(max_tau);

SMT_tr=func_TDE(train_smt,train_cnt,ttau,opt.time_interval);
[SMT_tr, CSP_W, CSP_D]=func_csp(SMT_tr,{'nPatterns', opt.CSPFilter});
FT_tr=func_featureExtraction(SMT_tr, {'feature','logvar'});
[CF_PARAM]=func_train(FT_tr,{'classifier','LDA'});

SMT_te=func_TDE(test_smt,test_cnt,ttau,opt.time_interval);
SMT_te=func_projection(SMT_te, CSP_W);
FT_te=func_featureExtraction(SMT_te, {'feature','logvar'});
[cf_out]=func_predict(FT_te, CF_PARAM);

[loss out]=eval_calLoss(FT_te.y_dec, cf_out);
Acc=1-loss';
end

author: PatternRecognition

repo: OpenBMI


text:
 function mac = xray_atten_interp(kev, mac, kev_in, varargin)
%function mac = xray_atten_interp(kev, mac, kev_in, [options])
%|
%| Interpolate mass attenuation coefficients (mac) onto desired energies.
%|
%| in
%|	kev	[M,1]
%|	mac	[M,1]
%|	kev_in	[N,1]		desired energies [in keV]
%|
%| option
%|	'interp' {}		default {'pchip', 'extrap'}
%| out
%|	mac	[N,1]		mass attenuation coefficients [cm^2/g],
%|
%| Copyright 2004-05-1, Jeff Fessler, University of Michigan

% default is to show example
if nargin < 1, ir_usage, end
if nargin == 1 && streq(kev, 'test'), xray_atten_interp_test, return, end

% = {'linear', 'extrap'};
% = {'spline', 'extrap'};
arg.interp = {'pchip', 'extrap'};
arg = vararg_pair(arg, varargin);

% trick: allow for the k-edge jumps!
mac = log(mac); % interpolate on a log scale
mac = interp1_jump(kev, mac, kev_in, arg.interp{:});
mac = exp(mac);

% xray_atten_interp_test()
% example usage, cf Fig. 3.4 of Macovski 1983
function xray_atten_interp_test
mtype = 'water'; ax = 10.^[1 3 -2 1.];
mtype = 'lead'; ax = 10.^[1 3 -1 2.5];
[mac kev] = xray_read_atten(mtype);
kev1 = logspace(1,3,1+2^9);
mac1 = xray_atten_interp(kev, mac, kev1);
if im
	clf, loglog(kev, mac, '.', kev1, mac1, '-')
	xlabel 'KeV', ylabel 'mass attenuation coefficient [cm^2/g]'
	axis(ax)
	texts(0.7, 0.7, mtype)
	if streq(mtype, 'lead')
		text(14, 40, 'L edge', 'horizontalalignment', 'center')
		text(88, 1., 'K edge', 'horizontalalignment', 'center')
	end
end
% ir_savefig(['fig_atten_' mtype])

author: JeffFessler

repo: mirt

save_path: github-repos/MATLAB/JeffFessler-mirt


text:
function [success] = viewLineFilledError(inputMean,inputStd,varargin)
	% Makes solid error bars around line.
	% Biafra Ahanonu
	% started: 2014.01.03 [19:13:01]
	% inputs
		% inputMean - Vector [1 timePoints] of y mean for each value of
		% inputStd - Vector [1 timePoints] indicating the std or SEM at each time point in inputMean
	% outputs
		% success - Binary 1 = ran without errors, 0 = encountered errors

	[success] = ciapkg.view.viewLineFilledError(inputMean,inputStd,'passArgs', varargin);
end

author: bahanonu

repo: ciatah

save_path: github-repos/MATLAB/bahanonu-ciatah


text:
% ijcvLocationFigureScript

outdir = '/IUS/vmr20/dhoiem/data/ijcv06/results';

vimages = zeros(200, 200, 3);
himages = zeros(200, 200, 5);

for f = 1:numel(imsegs)

    tmpseg = imresize(imsegs(f).segimage, [200 200]);

    for v = 1:3
        lab = (imsegs(f).vert_labels==v);
        vimages(:, :, v) = vimages(:, :, v) + lab(tmpseg);
    end

    for h = 1:5
        lab = (imsegs(f).horz_labels==h);
        himages(:, :, h) = himages(:, :, h) + lab(tmpseg);
    end

    if mod(f, 50)==0
        disp(f)
    end
end
vimages = vimages ./ repmat(sum(vimages, 3), [1 1 3]);
himages = himages ./ repmat(sum(himages, 3), [1 1 5]);

[tmp, bestv] = max(vimages, [], 3);
[tmp, besth] = max(himages, [], 3);

locimseg.nseg = 7;
locimseg.segimage = (bestv==1) + (bestv==2).*(1+besth) + 7*(bestv==3);
for k = 1:7
    locimseg.npixels(k) = sum(locimseg.segimage(:)==k);
end
lim = APPgetLabeledImage(ones(200,200, 3), locimseg, ...
    {'000', '090', '090', '090', '090', '090', 'sky'}, ones(7, 1), ...
    {'---', '045', '090', '135', 'por', 'sol', '---'}, ones(7, 1));

imwrite(vimages(:, :, [2 1 3]), [outdir '/mainclassloc.jpg'], 'Quality', 100);
for v = 1:3
    imwrite(vimages(:, :, v), [outdir '/vloc' num2str(v) '.jpg'], 'Quality', 100);
end

for h = 1:5
    imwrite(himages(:, :, h), [outdir '/hloc' num2str(h) '.jpg'], 'Quality', 100);
end

imwrite(lim, [outdir '/labeledloc.jpg'], 'Quality', 100);

lim2 = (lim>0).*vimages(:, :, [2 1 3]);
imwrite(lim2, [outdir '/labeledloc2.jpg'], 'Quality', 100);

author: Cloud-CV

repo: object-proposals


text:
clear all; close all;
I=imread('pout.tif');
J=imadjust(I, [0.1 0.5], [0, 1], 0.4);
K=imadjust(I, [0.1, 0.5], [0, 1], 4);
figure;
subplot(121);
imshow(uint8(J));
subplot(122);
imshow(uint8(K));

author: HuangCongQing


text:
function[pixelAccuracy, meanAccuracy, meanIU] = confMatToAccuracies(confusion)
% [pixelAccuracy, meanAccuracy, meanIU] = confMatToAccuracies(confusion)
%
% Compute accuracies from a confusion matrix.
%
% Copyright by Holger Caesar, 2016

% compute various statistics of the confusion matrix
total = sum(confusion(:));
pos = sum(confusion, 2);
res = sum(confusion, 1)';
tp = diag(confusion);
IUs = tp ./ (pos + res - tp);
missing = pos == 0;

% Modified metrics to ignore classes for which we didn't see
% any pixels yet in this epoch
pixelAccuracy = sum(tp) / total;
meanAccuracy = nanmean(tp ./ pos);
meanIU = mean(IUs(~missing));

author: nightrome

repo: matconvnet-calvin


text:
function s = ymdf_to_s_republican ( y, m, d, f )

%*****************************************************************************80
%
%% YMDF_TO_S_REPUBLICAN writes a Republican YMDF date into a string.
%
%  Format:
%
%    ER YYYY/MM/DD.FF
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 March 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, M, D, real F, the YMDF date.
%
%    Output, string S, a representation of the date.
%
  s = sprintf ( 'ER %d/%02d/%05.2f', y, m, d + f );

  return
end


text:
% Rmem_test.m

% check match between Reg1 and Rmem
if 1 | ~isvar('Rm'), printm 'Rm'
	if 0
		ig = image_geom('nx', 512, 'ny', 496, 'nz', 16, 'fov', 500, ...
			'down', 4);
	else % 2d
		ig = image_geom('nx', 100, 'ny', 80, 'dx', 4.2);
	end
	ig.mask = ig.circ(200) > 0;
	kappa = 2 + 1 * cos(2*pi*ig.x/ig.fov) * sin(2*pi*ig.y/ig.fov)';
	kappa = single(kappa) .* ig.mask;
%	kappa = repmat(kappa, [1 1 ig.nz]) .* ig.mask;
%	kappa = ig.mask;

	f.l2b = 3;
%	f.l2b = 0;
	f.pot = 'hyper3'; f.delta = 30; f.pot_arg = {f.pot, f.delta};
%	f.pot = 'quad'; f.delta = inf; f.pot_arg = {f.pot};
	f.offsets = '3d:26';
	f.offsets = [ig.nx+1];
	f.offsets = '';
	Rg = Reg1(kappa, 'pot_arg', f.pot_arg, 'beta', 2^f.l2b, ...
		'offsets', f.offsets, 'type_penal', 'mat');
%		'offsets', f.offsets, 'type_penal', 'mex');
%		'edge_type', 'tight', ...
	Rm = Rmem(kappa, 'pot_arg', f.pot_arg, 'beta', 2^f.l2b, ...
		'distance_power', Rg.distance_power, ...
		'offsets', f.offsets);
%		'edge_type', 'tight', ...

	x = ig.unitv;

	if 1 % check C1
		jf_equal(Rm.C1 * x, Rg.C1 * x)
		jf_equal(Rm.C1 * x(ig.mask), Rg.C1 * x(ig.mask))
	end

	if 1 % check penalty value
		jf_equal(Rg.penal(Rg, x), Rg.penal(Rg, x(ig.mask)))
		jf_equal(Rm.penal(Rm, x), Rm.penal(Rm, x(ig.mask)))
		equivs(Rg.penal(Rg, x), Rm.penal(Rm, x))
	end

	if 1 % check cgrad
		g1 = Rm.cgrad(Rm, x);
		g2 = ig.embed(Rm.cgrad(Rm, x(ig.mask)));
		jf_equal(g1, g2)
		g2 = Rg.cgrad(Rg, x);
im pl 2 2, im(1, g1), im(2, g2), im(3, g1-g2), im(4, ig.mask)
		equivs(g1, g2)
		g3 = ig.embed(Rg.cgrad(Rg, x(ig.mask)));
		jf_equal(g2, g3)
		clear g1 g2 g3
	end

	if 0 % check denom
	return
	end

	%d = Rm.diag(R);
prompt
end

% Robject designed to match Rmem'
if 1 | ~isvar('Ro'), printm 'Ro'
	tmp = repmat(kappa.^2, [1 1 1 length(Rm.offsets)]);
	Ro = Robject(ig.mask, 'edge_type', 'leak', 'beta', 2^f.l2b, ...
		'offsets', Rm.offsets, ...
		'potential', f.pot, 'delta', f.delta, ...
		'type_denom', 'matlab', ...
		'distance_power', Rg.distance_power, 'user_wt', tmp);
	clear tmp
end

if 1
	cpu etic
	g1 = Rm.cgrad(Rm, x);
	cpu etoc 'Rm cgrad time'
	cpu etic
	g2 = Ro.cgrad(Ro, x(ig.mask));
	g2 = embed(g2, ig.mask);
	cpu etoc 'Ro cgrad time'
	equivs(g1, g2)
end

if 0 % these tests superceded by Reg1_test.m
	tmp = sprintf('cgrad%d,offset', Rm.order);
	beta = 2^f.l2b ...
		./ penalty_distance(Rm.offsets(:), Rm.dim) .^ Rm.distance_power;
	g31 = penalty_mex(tmp, single(x), single(kappa), ...
		int32(Rm.offsets), single(beta), ...
		Rm.pot_arg{1}{1}, single(Rm.pot_arg{1}{2}), int32(1));
	g34 = penalty_mex(tmp, single(x), single(kappa), ...
		int32(Rm.offsets), single(beta), ...
		Rm.pot_arg{1}{1}, single(Rm.pot_arg{1}{2}), int32(4));
	jf_equal(g31, g34)
	max_percent_diff(g1, g31)
	max_percent_diff(g2, g31)
end

if 1
	% compare them
	%x = ig.unitv;
	pr Rm.penal(Rm, x)
	pr Ro.penal(Ro, x(ig.mask))
	max_percent_diff 'Rm.penal(Rm,x)' 'Ro.penal(Ro,x(ig.mask))'
end

return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

x = mask;
rng(0)
x = rand(size(mask));
x = x(mask);
max_percent_diff(R0.penal(R0, x), R1.penal(R1, x))
max_percent_diff(R0.diag(R0), R1.diag(R1))
max_percent_diff(R0.cgrad(R0, x), R1.cgrad(R1, x))
max_percent_diff(R0.denom(R0, x), R1.denom(R1, x))
if 0
	d0 = R0.denom(R0, x);
	d1 = R1.denom(R1, x);
	d0 = embed(d0, mask);
	d1 = embed(d1, mask);
	im clf
	im(221, d0)
	im(222, d1)
	im(223, d1-d0)
end


text:
classdef AdaW < ALGORITHM
% <multi/many> <real/integer/label/binary/permutation>
% Evolutionary algorithm with adaptive weights

%------------------------------- Reference --------------------------------
% M. Li and X. Yao, What weights work for you? Adapting weights for any
% Pareto front shape in decomposition-based evolutionary multiobjective
% optimisation, Evolutionary Computation, 2020, 28(2): 227-253.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        function main(Algorithm,Problem)
            %% Generate the weight vectors
            [W,Problem.N] = UniformPoint(Problem.N,Problem.M);  % Generate the weight vectors
            T = ceil(Problem.N/10);                             % The size of neighbours of each weight

            %% Detect the neighbours of each weight
            B = pdist2(W,W);
            [~,B] = sort(B,2);
            B = B(:,1:T);

            %% Generate random population
            Population = Problem.Initialization();
            Z = min(Population.objs,[],1);

            %% Generate an archive set
            Archive = Population(NDSort(Population.objs,1)==1);
            Archive_temp = Population;

            %% Optimization
            while Algorithm.NotTerminated(Population)
                  % For each weight
                  for i = 1 : Problem.N
                      % Choose parents
                      if rand < 0.9
                          P = B(i,randperm(size(B,2)));
                      else
                          P = randperm(Problem.N);
                      end
                      % Generate an offspring
                      Offspring = OperatorGAhalf(Problem,Population(P(1:2)));
                      % Put the offspring into the archive
                      Archive_temp(i) = Offspring;
                      % Update the ideal point
                      Z = min(Z ,Offspring.obj);
                      % Pick a neighbour to update
                      g_old = max(abs(Population(P).objs-repmat(Z,length(P),1))./W(P,:),[],2);
                      g_new = max(repmat(abs(Offspring.obj-Z),length(P),1)./W(P,:),[],2);
                      Population(P(find(g_old >= g_new,1))) = Offspring;
                  end
                  Archive = [Archive,Archive_temp];
                  % Maintenance operation in the archive set
                  Archive = Archive(NDSort(Archive.objs,1)==1);
                  Archive = ArchiveUpdate(Archive, 2 * Problem.N);
                  % Update weights
                  if ~mod(ceil(Problem.FE/Problem.N),ceil(0.05*ceil(Problem.maxFE/Problem.N))) && Problem.FE <= Problem.maxFE*0.9
                     [Population,W,B] = WeightUpdate(Population,W,Archive,Z,T,Problem);
                  end
            end
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function result = ball_unit_07_3d ( func )

%*****************************************************************************80
%
%% BALL_UNIT_07_3D approximates an integral inside the unit ball in 3D.
%
%  Integration region:
%
%    Points (X,Y,Z) such that:
%
%      X**2 + Y**2 + Z**2 <= 1.
%
%  Discussion:
%
%    A 64 point 7-th degree formula is used.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 May 2004
%
%  Author:
%
%    MATLAB version by John Burkardt
%
%  Reference:
%
%    Arthur H Stroud,
%    Approximate Calculation of Multiple Integrals,
%    Prentice Hall, 1971.
%
%  Parameters:
%
%    Input, external FUNC, the name of the user supplied
%    function which evaluates F(X,Y,Z), of the form
%      function value = func ( x, y, z )
%
%    Output, real RESULT, the approximate integral of the function.
%
  norder = 4;
%
%  This is the 5 point Gauss-Legendre rule,
%  but with the midpoint deleted, and with different weights.
%
  xtab1(1:4) = [...
    -0.906179845938663992797626878299E+00, ...
    -0.538469310105683091036314420700E+00, ...
     0.538469310105683091036314420700E+00, ...
     0.906179845938663992797626878299E+00 ];

  weight1(1:4) = [ ...
    0.19455533421780251826E+00, ...
    0.13877799911553081506E+00, ...
    0.13877799911553081506E+00, ...
    0.19455533421780251826E+00 ];
%
%  Set XTAB2 and WEIGHT2.
%
  for j = 1 : norder
    angle = pi * ( 2 * j - 1 ) / ( 2 * norder );
    xtab2(j) = cos ( angle );
  end

  weight2(1:norder) = 1.0E+00;
%
%  Set XTAB3 and WEIGHT3 for the interval [-1,1].
%
  [ xtab3, weight3 ] = legendre_set ( norder );

  w = 3.0E+00 / 16.0E+00;

  quad = 0.0E+00;

  for i = 1 : norder
    for j = 1 : norder
      for k = 1 : norder

        x = xtab1(i) * sqrt ( 1.0E+00 - xtab2(j)^2 ) ...
                     * sqrt ( 1.0E+00 - xtab3(k)^2 );
        y = xtab1(i) * xtab2(j) * sqrt ( 1.0E+00 - xtab3(k)^2 );
        z = xtab1(i) * xtab3(k);

        quad = quad + w * weight1(i) * weight2(j) * weight3(k) ...
          * feval ( func, x, y, z );

      end
    end
  end

  volume = ball_unit_volume_3d ( );
  result = quad * volume;

  return
end


text:
%   AUTHORSHIP
%   Primary Developer: Stephen Meehan <swmeehan@stanford.edu>
%   Math Lead & Secondary Developer:  Connor Meehan <connor.gw.meehan@gmail.com>
%   Bioinformatics Lead:  Wayne Moore <wmoore@stanford.edu>
%   Provided by the Herzenberg Lab at Stanford University
%   License: BSD 3 clause
%

classdef Plots < handle
    properties(Constant)
        DOING_ALL='doingAll';
        DEBUGGING=false;
    end

    properties(SetAccess=private)
        is3D;
        legendHs;
        mdns;
        stds;
        legendH;
        otherPlots={};
    end

    properties
        Hs;
        otherHs;
        cnts;
        names;
        N;
        distFactor;
        mx;
        mxI;
        mn;
        mnI;
        ax;
        javaLegend;
        otherPlotMap;
    end

    methods
        function this=Plots()
            this.Hs=[];
        end

        function setHs(this, Hs)
            this.Hs=Hs;
            this.N=length(this.Hs);
            this.cnts=zeros(1, this.N);
            if isempty(this.names)
                this.names=cell(1, this.N);
                for i=1:this.N
                    this.cnts(i)=length(get(this.Hs(i), 'XData'));
                    this.names{i}=get(this.Hs(i), 'DisplayName');
                end
            else
                for i=1:this.N
                    this.cnts(i)=length(get(this.Hs(i), 'XData'));
                end
            end
            this.setMinMax;
            this.ax=get(Hs(1), 'Parent');
        end

        function setMinMax(this)
            [this.mx, this.mxI]=max(this.cnts);
            [this.mn, this.mnI]=min(this.cnts);
        end

        function setOtherHs(this, Hs)
            this.otherHs=Hs;
        end

        function setLegendHs(this, Hs)
            this.legendHs=Hs;
        end

        function initStats(this)
            if isempty(this.mdns)
                if isempty(this.Hs)
                    return;
                end
                [this.mdns, this.stds, this.is3D]=Plots.Stats(this.Hs);
                if this.is3D
                    this.distFactor=6;
                else
                    this.distFactor=3;
                end
            end
        end

        function setNames(this, names)
            this.names=names;
        end

        function names=getNames(this)
            names=this.names;
        end

        function toggleVisibility(this, idx)
            if ~isempty(this.otherHs)
                R=size(this.otherHs,1);
                for r=1:R
                    plotH=this.otherHs(r, idx);
                    if strcmp('off', get(plotH, 'visible'))
                        set(plotH(r), 'visible', 'on');
                    else
                        set(plotH(r), 'visible', 'off');
                    end
                end
            end
        end

        function clear(this)
            try
                N_=length(this.Hs);
                for i=1:N_
                    delete(this.Hs(i));
                end
                N_=length(this.otherHs);
                for i=1:N_
                    delete(this.otherHs(i));
                end
            catch ex
                %ex.getReport
            end
        end

        function addOtherPlots(this, other)
            this.otherPlots{end+1}=other;
        end

        function flashOtherPlots(this, idx, on)
           if ~isempty(this.otherPlots)
               name=edu.stanford.facs.swing.Basics.RemoveXml(String.RemoveTex(this.names{idx}));
               lIdx=String.LastIndexOf(name, ' training ');
               if lIdx>0
                   name=name.substring(0,lIdx-1);
               end
               nOthers=length(this.otherPlots);
               for i=1:nOthers
                   other=this.otherPlots{i};
                   nNames=length(other.names);
                   for j=1:nNames
                       if strcmp(name, edu.stanford.facs.swing.Basics.RemoveXml(String.RemoveTex(other.names{j})))
                           perc=other.cnts(j)/sum(other.cnts);
                           otherH=other.Hs(j);
                           if nargin<3
                               if isequal(get(otherH, 'visible'), 'on')
                                   set(otherH, 'visible', 'off');
                                   times=3;
                               else
                                   set(otherH, 'visible', 'on');
                                   times=4;
                               end
                           else
                               if ~on
                                   set(otherH, 'visible', 'off');
                                   times=3;
                               else
                                   set(otherH, 'visible', 'on');
                                   times=4;
                               end
                           end
                           Plots.Flash(otherH, perc, times);
                           break;
                       end
                   end
               end
           end
           if nargin>2
               this.setOtherPlotMapVisible(idx, on)
           end
        end

        function yes=isInOtherPlotMap(this, idx)
            if ~isempty(this.otherPlotMap)
                H=this.Hs(idx);
                yes=this.otherPlotMap.isKey(H);
            else
                yes=false;
            end
        end

        function setOtherPlotMapVisible(this, idx, on)
            if ~isempty(this.otherPlotMap)
                H=this.Hs(idx);
                if on
                    vis='on';
                else
                    vis='off';
                end
                if this.otherPlotMap.isKey(H)
                    v=this.otherPlotMap(H);
                    if iscell(v)
                        v=v{1};
                    end
                    if any(v<=0)
                        v(v<0)=v;
                    end
                    set(v, 'visible', vis);
                end
            end
        end

        function setOtherPlotVisible(this, idx, on)
           if ~isempty(this.otherPlots)
               name=edu.stanford.facs.swing.Basics.RemoveXml(String.RemoveTex(this.names{idx}));
               lIdx=String.LastIndexOf(name, ' training ');
               if lIdx>0
                   name=name.substring(0,lIdx-1);
               end
               nOthers=length(this.otherPlots);
               for i=1:nOthers
                   other=this.otherPlots{i};
                   nNames=length(other.names);
                   for j=1:nNames
                       if strcmp(name, edu.stanford.facs.swing.Basics.RemoveXml(String.RemoveTex(other.names{j})))
                           perc=other.cnts(j)/sum(other.cnts);
                           otherH=other.Hs(j);
                           if ~on
                               set(otherH, 'visible', 'off');
                           else
                               set(otherH, 'visible', 'on');
                           end
                       end
                   end
               end
           end
           this.setOtherPlotMapVisible(idx, on)
        end
    end

    methods(Static)

        function [mdns, stds, is3D]=Stats(plotHs)
            N=length(plotHs);
            mdns=zeros(N,3);
            stds=zeros(N,3);
            is3D=true;
            for ii=1:N
                plotH=plotHs(ii);
                if ~ishandle(plotH)
                    return;
                end
                x_=get(plotH, 'XData');
                y_=get(plotH, 'YData') ;
                z_=get(plotH, 'ZData');
                if isempty(z_)
                    [RR,CC]=size(get(plotHs(ii), 'XData'));
                    z_=ones(RR, CC);
                    is3D=false;
                end
                d=[x_; y_; z_]';
                mdns(ii,:)=median(d);
                stds(ii,:)=std(d);
            end
        end

        function Flash(plotH, perc, times)
            vi=get(plotH, 'Visible');
            ms=get(plotH, 'MarkerSize');
            if perc<.02
                set(plotH, 'MarkerSize', ms+7)
            elseif perc<.05
                set(plotH, 'MarkerSize', ms+5)
            elseif perc<.1
                set(plotH, 'MarkerSize', ms+3);
            elseif perc<.2
                set(plotH, 'MarkerSize', ms+2);
            end
            for i=1:times
                %MatBasics.RunLater(@(h,e)go, .1);
                go
            end
            %MatBasics.RunLater(@(h,e)done, .51);
            done
            function go
                set(plotH, 'visible', 'off');
                pause(0.1);
                set(plotH, 'visible', 'on');
                pause(0.05);
            end
            function done
                set(plotH, 'visible', vi);
                set(plotH, 'MarkerSize', ms);
            end
        end

        function [HL, fcnMotion, btns, sortI, plots]=Legend(plotHs, names, ...
                idxsWithName, xMargin, yMargin, doMotion, freq, priorFcn,...
                doubleClicker, doJavaLegend, oldJavaBtns, southComponent,...
                selectedCallback)

            if nargin<13
                selectedCallback=[];
                if nargin<12
                    southComponent=[];
                    if nargin<11
                        oldJavaBtns=[];
                        if nargin<10
                            if nargin<9
                                doubleClicker=[];
                                if nargin<8
                                    priorFcn=[];
                                    if nargin<7
                                        freq=[];
                                        if nargin<6
                                            doMotion=true;
                                            if nargin<5
                                                yMargin=[];
                                                if nargin<4
                                                    xMargin=[];
                                                    if nargin<3
                                                        idxsWithName=[];
                                                        if nargin<2
                                                            names={};
                                                        end
                                                    end
                                                end
                                            end
                                        end
                                    end
                                end
                            end
                            doJavaLegend=false;
                        end
                    end
                end
            end
            app=BasicMap.Global;
            if doJavaLegend
                sup1=app.supStart;
                sup2=app.supEnd;
            end
            btns=[];
            if isa(plotHs, 'Plots')
                that=plotHs;
                plots=plotHs;
                N=plots.N;
            else
                that=[];
                plots=Plots;
                plots.setNames(names);
                if iscell(plotHs)
                    N=length(plotHs);
                    plotHs2=zeros(1,N);
                    for i=1:N
                        plotHs2(i)=plotHs{i};
                    end
                    plotHs=plotHs2;
                else
                    [R,N]=size(plotHs);
                    if R>1
                        otherPlotHs=plotHs(2:end,:);
                        plotHs=plotHs(1,:);
                        plots.setOtherHs(otherPlotHs);
                    end
                end
                plots.setHs(plotHs);
                names=plots.names;
            end
            if isempty(doJavaLegend)
                HL=[];
                fcnMotion=[];
                sortI=[];
                return;
            end
            if N<1
                return;
            end
            if isempty(idxsWithName)
                idxsWithName=1:N;
            end
            assert(N>=length(idxsWithName), ...
                '# of plotHs must be >= # of idxsWithName');
            ax=get(plots.Hs(1), 'Parent');
            fig=get(ax, 'Parent');
            curOver=0;
            overH=[];
            try
                set(fig,'WindowButtonMotionFcn', @legMotion);
            catch ex
            end
            fcnMotion=@legMotion;
            X=xlim(ax);
            Y=ylim(ax);
            assert( length(names) == length(idxsWithName), ...
                'Must be as many namedPlotIdxs as names');

            mx=plots.mx;
            cnts=plots.cnts;
            if isempty(freq)
                Cnt=sum(cnts);
            else
                if length(freq)==length(cnts)
                    if any(isnan(freq))
                        freq(isnan(freq))=-1;
                    end
                    Cnt=sum(freq(freq>=0));
                    cnts=freq;
                    mx=max(cnts);
                else
                    Cnt=freq;
                end
            end
            nNames=length(names);
            cnts2=zeros(1, nNames);
            cntPref=app.getNumeric('cntPref', 2);
            if ~doJavaLegend
                legendHs=zeros(1, nNames);
                for i=1:nNames
                    idx=idxsWithName(i);
                    cnt=cnts(idx);
                    cnts2(i)=cnt;
                    if cnt>=0
                        strCnt=['    ^{\color{blue}' ...
                            String.encodePercent(cnt, Cnt, 1) '  '...
                            '\color[rgb]{.2 .5 .2} ' ...
                            String.encodeCount(cnt, cntPref) '} '];
                        mkSz=6 + (cnt/mx*15);
                        clr=get(plots.Hs(idx), 'MarkerEdgeColor');

                        legendHs(i)=plot(ax, X(1)-X(2), Y(1)-Y(2), 's', ...
                            'MarkerSize', mkSz, 'Color',  clr, ...
                            'MarkerFaceColor', clr, 'LineStyle', 'none');
                    else
                        if isa(plotHs, 'Plots')
                            clr=get(plots.Hs(idx), 'MarkerEdgeColor');
                            legendHs(i)=plot(ax, X(1)-X(2), Y(1)-Y(2), 's', ...
                                'MarkerSize', 6, 'Color',  clr, ...
                                'MarkerFaceColor', clr, 'LineStyle', 'none');
                        else
                            legendHs(i)=plotHs(i);
                        end
                        names{i}=names{i};
                    end

                end
                xlim(ax,X);
                ylim(ax,Y);
                [~,sortI]=sort(cnts2, 'descend');
                HL=legend(ax, legendHs(sortI), names(sortI), ...
                    'Location', 'northeast','AutoUpdate', 'off');
                if ~isempty(xMargin) && ~isempty(yMargin)
                    p=get(HL, 'position');
                    p2=Gui.GetNormalized(ax);
                    xNudge=1-(p2(1)+p2(3));
                    xNudge=xNudge-xMargin;
                    yNudge=1-(p2(2)+p2(4));
                    yNudge=yNudge-yMargin;
                    set(HL, 'position', [p(1)+xNudge, p(2)+yNudge p(3) p(4)]);
                end
                plots.setLegendHs(legendHs);
                HL.ItemHitFcn=@(h,event)Plots.LegendClick(plots, event,...
                    idxsWithName, cnts2);
            else
                for i=1:nNames
                    idx=idxsWithName(i);
                    cnt=cnts(idx);
                    cnts2(i)=cnt;
                    clr=get(plots.Hs(idx), 'MarkerEdgeColor');
                    if cnt>=0
                        strSymbol=['•'];
                        f=11+(cnt/mx*15);
                        f= ceil((f-4)/4)+3;
                        if f>=10
                            f=10;
                        end
                        f=String.encodeInteger(f);
                        str=['' strSymbol ''];
                        strCnt=[sup1 ' ' ...
                            String.encodePercent(cnt,Cnt,1) ''...
                            '  ' ...
                            String.encodeCount(cnt, cntPref) '' ...
                            sup2 ];
                    else
                        ls=get(plots.Hs(idx), 'LineStyle');
                        if strcmpi(ls, 'none')
                            str=['• '];
                        else
                            str=['− '];
                        end
                        strCnt='';
                    end
                    names{i}=['' str names{i} '  '...
                        strCnt Html.EncodeSort('name', strtrim(char(...
                        edu.stanford.facs.swing.Basics.RemoveXml(...
                        lower(names{i}))))) ...
                        Html.EncodeSort('frequency', cnt) ...
                        ''];
                end
                [~, sortI]=sort(cnts2, 'descend');
                [outerPnl, ~, btns,sortGui]=...
                    Radio.Panel3(names(sortI), 1:nNames, 13, ...
                    @(h,e, i)Plots.JavaLegendClick(plots, i, sortI,...
                    idxsWithName, plots.Hs, cnts2, h, selectedCallback), ...
                    true,Html.Wrap(['Deselecting '...
                    'hides items in plot & selecting '...
                    'unhides']));
                sortGui.setProperties(app, 'javaLegend.');
                if ~isempty(oldJavaBtns)
                    it=oldJavaBtns.iterator;
                    while it.hasNext
                        btn=it.next;
                        if ~btn.isSelected
                            k=StringArray.IndexOf(names,char(btn.getText));
                            m=find(sortI==k, 1);
                            if ~isempty(m)
                                b=btns.get(m-1);
                                b.setSelected(false);
                                set(plots.Hs(k), 'visible', 'off');
                                disp('was OFF');
                            end
                        end
                    end
                    sortGui.setAllChbText;
                elseif isequal(idxsWithName, 1:nNames)
                    for i=1:nNames
                        if isequal('off', get(plots.Hs(i), 'visible'))
                            b=btns.get(i-1);
                            b.setSelected(false);
                        end
                    end
                end
                if ~isempty(southComponent)
                    bp=Gui.BorderPanel(0,0);
                    bp.add(outerPnl, 'Center');
                    bp.add(southComponent, 'South');
                    outerPnl=bp;
                end
                if ~isempty(oldJavaBtns) && oldJavaBtns.size>0
                    HL=Gui.WindowAncestor(oldJavaBtns.get(0));
                    HL.setContentPane(outerPnl);
                    HL.pack;
                else
                    pu=showMsg(outerPnl, 'Legend', 'north east+', false, ...
                        false, 0, false);
                    HL=pu.dlg;
                end
                sortGui.dlg=HL;
                btns.get(0).getParent.scrollRectToVisible(java.awt.Rectangle(0,0,1,1))
                if ismac
                    if 1<size(get(0, 'MonitorPositions'), 1)
                        if isequal('on', get(fig, 'visible'))
                            MatBasics.RunLater(@(h,e)relocate(getjframe(fig)), .52)
                        else
                            disp('huh');
                        end
                    end
                end
            end
            if ~isempty(that)
                that.legendH=HL;
            end
            function relocate(ref)
                Gui.LocateJava(HL, ref, 'north east+');
                HL.setVisible(true);
            end
            function legMotion(hObj, event)
                if ~isvalid(ax)
                    return;
                end
                cp=get(ax, 'CurrentPoint');
                if isempty(cp)
                    return;
                end
                C=size(cp,2);
                x=cp(2,1);
                y=cp(2,2);
                z=cp(2,3);
                try
                    e=Gui.GetPixels(HL);
                catch ex
                    e=[];
                end
                %[normX normY normFigX normFigY e]
                if ~isempty(e)
                    cp2=get(get(HL, 'Parent'), 'currentpoint');
                    if cp2(2)<=e(2)+e(4) && cp2(2)>=e(2)
                        if cp2(1)>=e(1) && cp2(1)<= e(1)+e(3)
                            if ~isempty(doubleClicker)
                                doubleClicker.stopListening;
                            end
                            return;
                        end
                    end
                end
                if ~isempty(doubleClicker)
                    doubleClicker.startListening;
                end
                if ~doMotion
                    if ~isempty(priorFcn)
                        feval(priorFcn, hObj, event);
                    end
                    return;
                end
                plots.initStats;
                if plots.is3D
                    [D,II]=pdist2(plots.mdns, [x y z], 'euclidean', 'Smallest', 1);
                    limit=pdist2(plots.mdns(II,:), ...
                        plots.mdns(II,:)+(plots.stds(II,:)*plots.distFactor));
                else
                    [D,II]=pdist2(plots.mdns(:,1:2), [x y], 'euclidean', 'Smallest', 1);
                    limit=pdist2(plots.mdns(II,1:2), plots.mdns(II,1:2)+...
                        (plots.stds(II,1:2)*plots.distFactor));
                end
                if Plots.DEBUGGING
                    %is3D
                    [x y z ; II D limit]
                    plots.names{II}
                    %cp
                    %[plots.mdns(II,:);plots.stds(II,:)]
                    if II==plots.mxI
                        disp('hey');
                    end
                end
                if D<=limit
                    over=II;
                else
                    over=0;
                end
                if ~ishandle(overH)
                    return;
                end
                if curOver ~= over
                    curOver=over;
                    if over>0
                        %disp(['Over ' names{II}]);
                        nameIdx=find(idxsWithName==II,1);
                        if nameIdx>0
                            nm=names{nameIdx};
                            if doJavaLegend
                                nm=strrep(nm, '', '_{{');
                                nm=strrep(nm, '', '}');
                                nm=char(...
                                    edu.stanford.facs.swing.Basics.RemoveXml(nm));
                                nm=strrep(nm, '_{{', '^{');
                                nm=strrep(nm, '•','');
                            end
                            if isempty(overH)
                                if plots.is3D
                                    overH=text(ax, x, y, z, nm, ...
                                        'fontSize', 9, ...
                                        'color', [0 0 .5],...
                                        'EdgeColor', 'red', ...
                                        'FontName', 'Arial', ...
                                        'backgroundColor', [255/256 252/256 170/256]);
                                else
                                    overH=text(ax, x, y, nm, ...
                                        'fontSize', 9, 'color', [0 0 .5], 'EdgeColor',...
                                        'red', 'FontName', 'Arial', ...
                                        'backgroundColor', [255/256 252/256 170/256]);
                                end
                            else
                                if plots.is3D
                                    set(overH, 'visible', 'on', 'Position', ...
                                        [x y z], 'String', nm);
                                    %uistack(overH, 'top');
                                else
                                    set(overH, 'visible', 'on', 'Position', ...
                                        [x y 0], 'String', nm);
                                end
                            end
                        else
                            disp('background');
                        end
                    else
                        %disp('Over NOTHING');
                        if ~isempty(overH)
                            set(overH, 'visible', 'off');
                        end
                    end
                end
                if ~isempty(priorFcn)
                    feval(priorFcn, hObj, event);
                end
            end
        end

        function LegendClick(this, event, idxsWithName, nums)
            H=get(event.Peer, 'UserData');
            idx_=find(this.legendHs==event.Peer, 1);
            idx=idxsWithName(idx_);
            if ~isempty(H)
                set(event.Peer, 'UserData', []);
                delete(H);
                this.toggleVisibility(idx);
                return;
            end
            this.initStats;
            plotH=this.Hs(idx);
            perc= nums(idx_)/max(nums);
            Plots.Flash(plotH, perc, 4);
            X=this.mdns(idx, 1);
            Y=this.mdns(idx, 2);
            ax=get(this.Hs(idx), 'Parent');
            str=get(event.Peer, 'DisplayName');
            fsz=11;
            if this.is3D
                Z=this.mdns(idx, 3);
                Plots.ShowLegendTip(ax, event.Peer, X, Y, str, fsz, 0, Z);
                [X Y Z]
            else
                Plots.ShowLegendTip(ax, event.Peer, X, Y, str, fsz, 0);
            end
            this.toggleVisibility(idx);
            this.flashOtherPlots(idx);
        end

        function ok=JavaLegendClick(this, idx_, sortI, idxsWithName, plotHs, ...
                nums, h, selectedCallback)
            idx=idxsWithName(sortI(idx_));
            plotH=plotHs(idx);
            if ~ishandle(plotH)
                msg('Supervisors not showing', 5, 'east+');
                ok=false;
                return;
            end
            ok=true;
            hasOtherMap=this.isInOtherPlotMap(idx);
            doingAll=nargin==8 && isequal(Plots.DOING_ALL, ...
                    char(h.getActionCommand));
            if ~h.isSelected
                set(plotH, 'visible', 'off');
                times=3;
            else
                if doingAll && hasOtherMap
                    %nope
                    if this.otherPlotMap.size<length(this.Hs)
                        h.setSelected(false)
                        return;
                    end
                end
                set(plotH, 'visible', 'on');
                times=4;
            end
            if doingAll
                if ~isempty(selectedCallback)
                    feval(selectedCallback, h, idx, true);
                end
                this.setOtherPlotVisible(idx, h.isSelected);
                return;
            end
            perc=nums(idx)/max(nums);
            Plots.Flash(plotH, perc, times);
            if ~isempty(selectedCallback)
                feval(selectedCallback, h, idx, false);
            end
            this.flashOtherPlots(idx, h.isSelected);
        end

        function ShowLegendTip(ax, hLegend, posX, posY, str, fsz, secs, posZ)
            if nargin<8
                [normX, normY]=Gui.DataToAxNorm(ax, posX, posY);
                tipH=text(normX+.03, normY+.03, str, ...
                    'fontSize', fsz, 'color', [0 0 .5], 'EdgeColor',...
                    'red', 'FontName', 'Arial', 'parent', ax, ...
                    'FontAngle', 'italic', 'units', 'normalized',...
                    'backgroundColor', [255/256 252/256 170/256]);
            else
                tipH=text(ax, posX, posY, posZ, str, ...
                    'fontSize', fsz, 'color', [0 0 .5], 'EdgeColor',...
                    'red', 'FontName', 'Arial', 'FontAngle', 'italic',...
                    'backgroundColor', [255/256 252/256 170/256]);

            end
            set(tipH, 'ButtonDownFcn', @(h,e)freeze(h, hLegend));
            if secs>0
                MatBasics.RunLater(@(h,e)closeTip, secs);
            else
                freeze(tipH, hLegend);
            end

            function freeze(hText, hLegend)
                if isempty(get(tipH, 'UserData'))
                    set(hText, 'UserData', true);
                    set(hText, 'FontSize', fsz-2);
                    set(hText, 'FontAngle', 'normal');
                    set(hLegend, 'UserData', hText);
                else
                    set(hLegend, 'UserData', []);
                    delete(hText);
                end
            end

            function closeTip
                if isempty(get(tipH, 'UserData'))
                    delete(tipH);
                end
            end
        end

    end
end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
%**************************************************************
%* mex interface to Andy Liaw et al.'s C code (used in R package randomForest)
%* Added by Abhishek Jaiantilal ( abhishek.jaiantilal@colorado.edu )
%* License: GPLv2
%* Version: 0.02
%
% Calls Classification Random Forest
% A wrapper matlab file that calls the mex file
% This does prediction given the data and the model file
% Options depicted in predict function in http://cran.r-project.org/web/packages/randomForest/randomForest.pdf
%**************************************************************
%function [Y_hat votes] = classRF_predict(X,model, extra_options)
% requires 2 arguments
% X: data matrix
% model: generated via classRF_train function
% extra_options.predict_all = predict_all if set will send all the prediction.
%
%
% Returns
% Y_hat - prediction for the data
% votes - unnormalized weights for the model
% prediction_per_tree - per tree prediction. the returned object .
%           If predict.all=TRUE, then the individual component of the returned object is a character
%           matrix where each column contains the predicted class by a tree in the forest.
%
%
% Not yet implemented
% proximity

function [Y_new, votes, prediction_per_tree] = classRF_predict(X,model, extra_options)

    if nargin<2
		error('need atleast 2 parameters,X matrix and model');
    end

    if exist('extra_options','var')
        if isfield(extra_options,'predict_all')
            predict_all = extra_options.predict_all;
        end
    end

    if ~exist('predict_all','var'); predict_all=0;end

	[Y_hat,prediction_per_tree,votes] = mexClassRF_predict(X',model.nrnodes,model.ntree,model.xbestsplit,model.classwt,model.cutoff,model.treemap,model.nodestatus,model.nodeclass,model.bestvar,model.ndbigtree,model.nclass, predict_all);
	%keyboard
    votes = votes';

    clear mexClassRF_predict

    Y_new = double(Y_hat);
    new_labels = model.new_labels;
    orig_labels = model.orig_labels;

    for i=1:length(orig_labels)
        Y_new(find(Y_hat==new_labels(i)))=Inf;
        Y_new(isinf(Y_new))=orig_labels(i);
    end

    1;

repo: sr-metric


text:
function r = invgamrand1(a, b, varargin)
%INVGAMRAND1 Random matrices from inverse gamma distribution (mex)
%
%   R = INVGAMRAND1(A,B) returns a matrix of random numbers chosen
%   from the inverse gamma distribution with parameters A and B.
%   The size of R is the common size of A and B if both are matrices.
%   Both parameters have to be a scalar.
%
%   Note: Parameterization as in (Neal, 1996).
%      A is mean of the distribution
%      B is degrees of freedom
%
%	See also INVGAMRAND, GAMRAND1
%
% Copyright (c) 1999 Aki Vehtari

% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.

error('No mex-file for this archtitecture. See Matlab help and convert.m in ./linuxCsource or ./winCsource for help.')

author: gpstuff-dev

repo: gpstuff

save_path: github-repos/MATLAB/gpstuff-dev-gpstuff


text:
function out = double(fa)
% Convert to double precision
% FORMAT double(fa)
% fa - a file_array
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

%
% $Id: double.m 1143 2008-02-07 19:33:33Z spm $

out = double(numeric(fa));

author: fieldtrip

repo: fieldtrip


text:
% ------------------------------------------------------------------------
%  Copyright (C)
%  Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain
%  University of California Berkeley (UCB) - USA
%
%  Jordi Pont-Tuset <jordi.pont@upc.edu>
%  Pablo Arbelaez <arbelaez@berkeley.edu>
%  June 2014
% ------------------------------------------------------------------------
% This file is part of the MCG package presented in:
%    Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J,
%    "Multiscale Combinatorial Grouping,"
%    Computer Vision and Pattern Recognition (CVPR) 2014.
% Please consider citing the paper if you use this code.
% ------------------------------------------------------------------------
function eval_and_save_labels(labels_folder,database,gt_set)

if nargin<2
    database = 'pascal2012';
end
if nargin<3
    gt_set = 'val2012';
end

% Get the name of the folder to refer to the method
if strcmp(labels_folder(end),filesep)
    labels_folder(end) = [];
end
tmp = strfind(labels_folder,filesep);
if isempty(tmp)
    method_name = labels_folder;
    masks_dir = fullfile(root_dir, 'datasets', database, method_name);
else
    method_name = labels_folder(tmp(end)+1:end);
    masks_dir = labels_folder;
end

% Results folder
res_dir   = fullfile(root_dir, 'results', database, method_name);
if ~exist(res_dir,'dir')
    mkdir(res_dir)
end

% Load which images to consider
im_ids = database_ids(database,gt_set);

% Sweep all images
num_images = numel(im_ids);
parfor ii=1:num_images
    curr_id = im_ids{ii};
    res_file = fullfile(res_dir,[curr_id '.mat']);

    % Are these candidates already evaluated?
    if ~exist(res_file, 'file')

        % Input file with candidates as labels
        labels_file = fullfile(masks_dir,[curr_id '.mat']);

        % Check if labels are computed
        if ~exist(labels_file, 'file')
            error(['Results ''' labels_file '''not found. Have you computed them?'])
        end

        % Load candidates
        cands = load(labels_file);

        % Load GT
        gt = get_ground_truth(database,curr_id);

        % Get all objects ids
        obj_ids = unique(gt.object);
        obj_ids(obj_ids==0) = [];
        obj_ids(obj_ids==255) = [];
        n_objs = numel(obj_ids);
        valid_pixels = (gt.object~=255);

        % Store true_areas
        true_areas = zeros(n_objs,1);
        for kk=1:n_objs
            true_areas(kk) = sum(gt.object(:)==kk);
        end

        % Store the class of each object
        obj_classes = zeros(n_objs,1);
        for kk=1:n_objs
            idx = find(gt.object==obj_ids(kk),1,'first');
            obj_classes(kk) = gt.class(idx);
        end

        % Overlap superpixels with GT objects
        n_leaves = length(unique(cands.superpixels));
        superpixels = cands.superpixels;
        superpixels(~valid_pixels) = 0;
        leave_fp   = zeros(n_objs,n_leaves);  % False positives
        leave_int  = zeros(n_objs,n_leaves);  % Intersection with GT
        for kk=1:n_objs
            tmp = hist(double(superpixels(:)).*(gt.object(:)==kk),(0:n_leaves));
            leave_int(kk,:) = tmp(2:end);
            tmp = hist(double(superpixels(:)).*(gt.object(:)~=kk),(0:n_leaves));
            leave_fp(kk,:) = tmp(2:end);
        end

        % Create matrix padded with zeros to be compatible with mex_eval_labels
        n_cands    = size(cands.labels,1);
        n_max_labels = length(unique(cands.superpixels));
        label_matrix = zeros(n_cands,n_max_labels);
        for jj=1:n_cands
            label_matrix(jj,1:length(cands.labels{jj})) = cands.labels{jj};
        end

        % Compute fp, fn etc. from these values on the superpixels
        inters     = zeros(n_objs,n_cands);
        false_pos  = zeros(n_objs,n_cands);
        false_neg  = zeros(n_objs,n_cands);
        jaccards   = zeros(n_objs,n_cands);
        if n_cands>0
            for kk=1:n_objs
                [inters(kk,:),false_pos(kk,:)] = mex_eval_labels(leave_int(kk,:),leave_fp(kk,:),label_matrix);
                false_neg(kk,:) = true_areas(kk)-inters(kk,:);
                jaccards(kk,:) = inters(kk,:)./(false_pos(kk,:)+true_areas(kk));
            end
        end
        assert(sum(isnan(jaccards(:)))==0)

        % Store results
        parsave(res_file,jaccards,inters,false_pos,false_neg,true_areas,obj_classes)
    end
end
end

function parsave(res_file,jaccards,inters,false_pos,false_neg,true_areas,obj_classes) %#ok<INUSD>
    save(res_file, 'jaccards','inters', 'false_pos', 'false_neg','true_areas','obj_classes');
end

author: s-gupta

repo: rcnn-depth

save_path: github-repos/MATLAB/s-gupta-rcnn-depth