text:
Network vgg16 {
Layer CONV1 {
Type: CONV
Dimensions { K 64,C 3,R 3,S 3,Y 224,X 224 }
Dataflow {
TemporalMap (1,1) K;
TemporalMap (1,1) C;
TemporalMap (3,1) Y;
SpatialMap (3,1) X;
TemporalMap (3,3) R;
TemporalMap (3,3) S;
}
}

Layer CONV2 {
Type: CONV
Dimensions { K 64,C 64,R 3,S 3,Y 224,X 224 }
Dataflow {
TemporalMap (1,1) K;
TemporalMap (1,1) C;
TemporalMap (3,1) Y;
SpatialMap (3,1) X;
TemporalMap (3,3) R;
TemporalMap (3,3) S;
}
}

Layer CONV3 {
Type: CONV
Dimensions { K 128,C 64,R 3,S 3,Y 112,X 112 }
Dataflow {
TemporalMap (1,1) K;
TemporalMap (1,1) C;
TemporalMap (3,1) Y;
SpatialMap (3,1) X;
TemporalMap (3,3) R;
TemporalMap (3,3) S;
}
}

Layer CONV4 {
Type: CONV
Dimensions { K 128,C 128,R 3,S 3,Y 112,X 112 }
Dataflow {
TemporalMap (1,1) K;
TemporalMap (1,1) C;
TemporalMap (3,1) Y;
SpatialMap (3,1) X;
TemporalMap (3,3) R;
TemporalMap (3,3) S;
}
}

Layer CONV5 {
Type: CONV
Dimensions { K 256,C 128,R 3,S 3,Y 56,X 56 }
Dataflow {
TemporalMap (1,1) K;
TemporalMap (1,1) C;
TemporalMap (3,1) Y;
SpatialMap (3,1) X;
TemporalMap (3,3) R;
TemporalMap (3,3) S;
}
}

Layer CONV6 {
Type: CONV
Dimensions { K 256,C 256,R 3,S 3,Y 56,X 56 }
Dataflow {
TemporalMap (1,1) K;
TemporalMap (1,1) C;
TemporalMap (3,1) Y;
SpatialMap (3,1) X;
TemporalMap (3,3) R;
TemporalMap (3,3) S;
}
}

Layer CONV7 {
Type: CONV
Dimensions { K 256,C 256,R 3,S 3,Y 56,X 56 }
Dataflow {
TemporalMap (1,1) K;
TemporalMap (1,1) C;
TemporalMap (3,1) Y;
SpatialMap (3,1) X;
TemporalMap (3,3) R;
TemporalMap (3,3) S;
}
}

Layer CONV8 {
Type: CONV
Dimensions { K 512,C 256,R 3,S 3,Y 28,X 28 }
Dataflow {
TemporalMap (1,1) K;
TemporalMap (1,1) C;
TemporalMap (3,1) Y;
SpatialMap (3,1) X;
TemporalMap (3,3) R;
TemporalMap (3,3) S;
}
}

Layer CONV9 {
Type: CONV
Dimensions { K 512,C 512,R 3,S 3,Y 28,X 28 }
Dataflow {
TemporalMap (1,1) K;
TemporalMap (1,1) C;
TemporalMap (3,1) Y;
SpatialMap (3,1) X;
TemporalMap (3,3) R;
TemporalMap (3,3) S;
}
}

Layer CONV10 {
Type: CONV
Dimensions { K 512,C 512,R 3,S 3,Y 28,X 28 }
Dataflow {
TemporalMap (1,1) K;
TemporalMap (1,1) C;
TemporalMap (3,1) Y;
SpatialMap (3,1) X;
TemporalMap (3,3) R;
TemporalMap (3,3) S;
}
}

Layer CONV11 {
Type: CONV
Dimensions { K 512,C 512,R 3,S 3,Y 14,X 14 }
Dataflow {
TemporalMap (1,1) K;
TemporalMap (1,1) C;
TemporalMap (3,1) Y;
SpatialMap (3,1) X;
TemporalMap (3,3) R;
TemporalMap (3,3) S;
}
}

Layer CONV12 {
Type: CONV
Dimensions { K 512,C 512,R 3,S 3,Y 14,X 14 }
Dataflow {
TemporalMap (1,1) K;
TemporalMap (1,1) C;
TemporalMap (3,1) Y;
SpatialMap (3,1) X;
TemporalMap (3,3) R;
TemporalMap (3,3) S;
}
}

Layer CONV13 {
Type: CONV
Dimensions { K 512,C 512,R 3,S 3,Y 14,X 14 }
Dataflow {
TemporalMap (1,1) K;
TemporalMap (1,1) C;
TemporalMap (3,1) Y;
SpatialMap (3,1) X;
TemporalMap (3,3) R;
TemporalMap (3,3) S;
}
}

}

author: maestro-project

repo: maestro


text:
function a = latin_cover ( n, p )

%*****************************************************************************80
%
%% LATIN_COVER returns a 2D Latin Square Covering.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 August 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of points.
%
%    Input, integer P(N), a permutation which describes the
%    first Latin square.
%
%    Output, integer A(N,N), the Latin cover.  A(I,J) = K
%    means that (I,J) is one element of the K-th Latin square.
%
  perm_check ( n, p );

  for i = 1 : n
    for k = 1 : n
      ik = i4_wrap ( i + k - 1, 1, n );
      a(i,p(ik)) = k;
    end
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
classdef MaF14 < PROBLEM
% <multi/many> <real> <large/none>
% LSMOP3

%------------------------------- Reference --------------------------------
% R. Cheng, M. Li, Y. Tian, X. Zhang, S. Yang, Y. Jin, and X. Yao, A
% benchmark test suite for evolutionary many-objective optimization,
% Complex & Intelligent Systems, 2017, 3(1): 67-81.
%------------------------------- 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".
%--------------------------------------------------------------------------

    properties(Access = private)
        sublen;	% Number of variables in each subcomponent
        len;    % Cumulative sum of lengths of variable groups
    end
    methods
        %% Default settings of the problem
        function Setting(obj)
            % Parameter setting
            if isempty(obj.M); obj.M = 3; end
            if isempty(obj.D); obj.D = 20*obj.M; end
            obj.lower    = zeros(1,obj.D);
            obj.upper    = [ones(1,obj.M-1),10.*ones(1,obj.D-obj.M+1)];
            obj.encoding = ones(1,obj.D);
            % Calculate the number of variables in each subcomponent
            nk = 2;
            c  = 3.8*0.1*(1-0.1);
            for i = 1 : obj.M-1
                c = [c,3.8.*c(end).*(1-c(end))];
            end
            obj.sublen = floor(c./sum(c).*(obj.D-obj.M+1)/nk);
            obj.len    = [0,cumsum(obj.sublen*nk)];
        end
        %% Calculate objective values
        function PopObj = CalObj(obj,PopDec)
            [N,D] = size(PopDec);
            M     = obj.M;
            nk    = 2;
            PopDec(:,M:D) = (1+repmat((M:D)./D,N,1)).*PopDec(:,M:D) - repmat(PopDec(:,1)*10,1,D-M+1);
            G = zeros(N,M);
            for i = 1 : 2 : M
                for j = 1 : nk
                    G(:,i) = G(:,i) + Rastrigin(PopDec(:,obj.len(i)+M-1+(j-1)*obj.sublen(i)+1:obj.len(i)+M-1+j*obj.sublen(i)));
                end
            end
            for i = 2 : 2 : M
                for j = 1 : nk
                    G(:,i) = G(:,i) + Rosenbrock(PopDec(:,obj.len(i)+M-1+(j-1)*obj.sublen(i)+1:obj.len(i)+M-1+j*obj.sublen(i)));
                end
            end
            G      = G./repmat(obj.sublen,N,1)./nk;
            PopObj = (1+G).*fliplr(cumprod([ones(N,1),PopDec(:,1:M-1)],2)).*[ones(N,1),1-PopDec(:,M-1:-1:1)];
        end
        %% Generate points on the Pareto front
        function R = GetOptimum(obj,N)
            R = UniformPoint(N,obj.M);
        end
        %% Generate the image of Pareto front
        function R = GetPF(obj)
            if obj.M == 2
                R = obj.GetOptimum(100);
            elseif obj.M == 3
                a = linspace(0,1,10)';
                R = {a*a',a*(1-a'),(1-a)*ones(size(a'))};
            else
                R = [];
            end
        end
    end
end

function f = Rastrigin(x)
    f = sum(x.^2-10.*cos(2.*pi.*x)+10,2);
end

function f = Rosenbrock(x)
    f = sum(100.*(x(:,1:size(x,2)-1).^2-x(:,2:size(x,2))).^2+(x(:,1:size(x,2)-1)-1).^2,2);
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function segclassifier = mcmcTrainSegmentationClassifier(data, labels, segimind, trainind)

ntrees = 10;
nnodes = 8;

disp(num2str(mean(labels==1)))

keep = zeros(numel(labels), 1);

for k = 1:numel(trainind)
    keep(find(segimind==trainind(k))) = 1;
end
ind = find(keep);

segclassifier = train_boosted_dt_2c(data(ind, :), [], labels(ind), ntrees, nnodes);

author: zouchuhang

repo: LayoutNet


text:
function [y, yvar, gene, times, scale, rawExp, rawVar] = drosGetData(drosexp, genes, getmedians),

% DROSGETDATA Get Drosophila data as processed by mmgMOS.
% FORMAT
% DESC Extract given genes from drosexp structure.
% ARG drosexp : drosexp structure as returned by drosLoadData
% ARG genes : indices or gene labels to extract
% ARG getmedians : return median values and zero variances
% RETURN y : the normalised expression levels.
% RETURN yvar : the variance of the normalised expression levels.
% RETURN gene : the gene names and Affymetrix array tags.
% RETURN times : the times of the expression measurements.
% RETURN scale : the scaling factor applied to normalise.
% RETURN rawExp : the raw gene expresion level.
% RETURN rawVar : the raw variance of the gene expression.
%
% SEEALSO : drosLoadData
%
% COPYRIGHT : Neil D. Lawrence, 2006
% COPYRIGHT : Antti Honkela, 2007

% SHEFFIELDML

if nargin < 3,
  getmedians = 0;
end

if iscell(genes),
  genes = drosFindGeneinds(drosexp, genes, 0, 1);
end

N = length(genes);

gene = drosexp.genes(genes);
if size(gene, 1) < size(gene, 2),
  gene = gene';
end
gene = [gene, gene];

rawExp = zeros(36, N);
rawVar = zeros(36, N);
yFull = zeros(36, N);
yFullVar = zeros(36, N);

rawExp = drosexp.mean(genes, :)';
rawVar = (drosexp.se(genes, :)').^2;
if getmedians,
  yFull = exp(drosexp.pctiles(genes, :, 3))';
  yFullVar = zeros(size(yFull));
else
  if isfield(drosexp, 'fitmean'),
    yFull = drosexp.fitmean(genes, :)';
    yFullVar = drosexp.fitvar(genes, :)';
  else
    for k=1:N,
      prof = squeeze(drosexp.pctiles(genes(k), :, :));
      for l=1:36,
	t = distfit(exp(prof(l, :)), 'normal');
	yFull(l, k) = t(1);
	yFullVar(l, k) = t(2) .^ 2;
      end
    end
  end
end

% Rescale so that average standard deviation of curves is 1.
scale = sqrt(var(yFull));
scaleMat = ones(size(yFull, 1), 1)*scale;
yFull = yFull./scaleMat;
yFullVar = yFullVar./(scaleMat.*scaleMat);

y{1} = yFull(1:12, :);
y{2} = yFull(13:24, :);
y{3} = yFull(25:36, :);
yvar{1} = yFullVar(1:12, :);
yvar{2} = yFullVar(13:24, :);
yvar{3} = yFullVar(25:36, :);
times = (1:12)';
%save('./data/barencoData.mat', 'y', 'yvar', 'gene', 'times', 'scale', 'rawVar', 'rawExp');

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
% Read a dataset captured at multiple binning factors and compression
% levels from a given directory. If simulate=true, low-resolution images
% are simulated from 1x1 binning (ground truth) data via bicubic
% downscaling.
function imageDataset = readDatasetWithMultipleBinningFactors(datasetDir, factors, compress_affix, type, createGroundTruth, simulate)

    if nargin < 4
        type = 'png';
    end
    if nargin < 5
        createGroundTruth = false;
    end

    % Read data for the different binning factors.
    for binningFactorIdx = 1:length(factors)

        if factors(binningFactorIdx) == 1 % No adaptation required for compression
            if createGroundTruth
                % Create the ground truth images by averaging over sequences of
                % consecutive frames.
                imageDataset.groundTruth = createGroundTruthImages([datasetDir, '/Bin', num2str( factors(binningFactorIdx) )], type);
            else
                % Read the ground truth from the given directory.
                frames = readImageSequence([datasetDir, '/Bin1'], ['*.', type]);
                if ~isa(frames, 'double')
                    % Convert to double.
                    frames = double(frames) / 255;
                end
                imageDataset.groundTruth = frames;
            end
        else % Adaptations required for compression
            if simulate
                gt = imageDataset.groundTruth;
                frames = zeros(size(gt,1) / factors(binningFactorIdx), size(gt,2) / factors(binningFactorIdx));
                for k = 1:size(gt,3)
                    frames(:,:,k) = imresize(gt(:,:,k), 1 / factors(binningFactorIdx));
                end
                imageDataset.(['Bin', num2str( factors(binningFactorIdx) )]) = frames;
            else
                % Read image sequence associated with the current binning factor.
                frames = readImageSequence([datasetDir, '/Bin', num2str( factors(binningFactorIdx) ),compress_affix], ['*.', type]);
                if ~isa(frames, 'double')
                    % Convert to double.
                    frames = double(frames) / 255;
                end
                imageDataset.(['Bin', num2str( factors(binningFactorIdx) )]) = frames;
            end
        end

    end

author: thomas-koehler

repo: SupER


text:
function latin_random_test ( )

%*****************************************************************************80
%
%% LATIN_RANDOM_TEST tests the LATIN_RANDOM library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 November 2014
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'LATIN_RANDOM_TEST:\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the LATIN_RANDOM library.\n' );

  seed = 123456789;

  for test = 1 : 3

    seed = latin_random_test01 ( seed );

  end
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'LATIN_RANDOM_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


text:
function [figsize,figborders]=getfigdim(figh)
% [figsize,figborders]=getfigdim(figh)  GET FIGure DIMensions.
%   Function creates a figure and then measures the appropriate values to
%   obtain border widths and heights of the menu and tool bars and other
%   parameters. This can then be used to size and place figures more exactly.
%   "figh" is the handle of the figure whose dimensions are measured.
%       If "figh" is not specified or empty then a figure will be created.
%   "figsize" is a four element row vector which specifies the figure.
%       The vector is as follows:  [left bottom width height]
%       These are the same values returned by "OuterPosition" property.
%   "figborders" is a 6 element row vector which is defined as:
%       [figureborder titlebarheight menubarheight ...
%                           toolbarheight minfigwidth minfigheight]
%       The figureborder is defined for all four sides of the figure.
%       The minfigwidth, minfigheight are the minimum size of figures that
%       Matlab produces without menu and tool bars.
%
%   Example:
%       [fsize,fborder]=getfigdim;
%       fsize = [227   241   570   504]
%       fborder = [5    26    21    27   125    37]

%   Copyright 2006 Mirtech, Inc.
%   created 08/20/2006  by Mirko Hrovat on Matlab Ver. 7.2
%   Mirtech, Inc.       email: mhrovat@email.com

%Create a figure if it doesn't exist
if nargin==0 || isempty(figh),
    figh=figure;
    clrflg=1;
else
    figure(figh);
    clrflg=0;
end
menbarstate=get(figh,'MenuBar');
toolbarstate=get(figh,'ToolBar');
unitsstate=get(figh,'Units');
set(figh,'Units','pixels');
drawnow
figsize=get(figh,'OuterPosition');
figpos=get(figh,'Position');
if nargout==2,
    set(figh,'MenuBar','none');
    set(figh,'ToolBar','none');
    drawnow
    p1=get(figh,'OuterPosition');
    p =get(figh,'Position');

    set(figh,'MenuBar','figure');
    set(figh,'ToolBar','none');
    drawnow
    p2=get(figh,'OuterPosition');

    set(figh,'MenuBar','none');
    set(figh,'ToolBar','figure');
    drawnow
    p3=get(figh,'OuterPosition');

    set(figh,'MenuBar','none');
    set(figh,'ToolBar','none');
    set(figh,'OuterPosition',[figsize(1),figsize(2),10,10]);
    drawnow
    p4=get(figh,'OuterPosition');

    figborders=zeros(1,6);
    figborders(4)= p3(4)-p1(4);             % calculate height of Toolbar
    figborders(3)= p2(4)-p1(4);             % calculate height of Menubar
    figborders(1)= (p1(3)-p(3))/2;          % calculate width of figure border
    figborders(2)= p1(4)-p(4)-2*figborders(1); % calculate height of title bar
    figborders(5:6)=p4(3:4);                % get minimium figure sizes
end %if nargout==2
% close the figure if created, otherwise return to original state
if clrflg,
    close(figh);
else
    set(figh,'MenuBar',menbarstate);
    set(figh,'ToolBar',toolbarstate);
    set(figh,'Units',unitsstate);
    set(figh,'Position',figpos);
    drawnow
end
% ---------- END ----------

author: Sable

repo: mcbench-benchmarks


text:
function dirbackup(s1, s2, runmode)
% function dirbackup(a, b, mode)
%
% Creates a backup of folder 'a' in folder 'b' or updates the current
% backup in folder 'b'. The function deletes files and folders from
% directory 'b' if they are not present in directory 'a'. It also compares
% each file with the same name by date and if a difference is found, the
% files in folder 'b' are updated, provided the file in folder 'a' is found
% to be newer. However, if the file in folder 'b' is found to be newer than
% the file in folder 'a', the user is asked for confirmation of update.
% Currently, the code is optimised for DOS-based system calls. Matlab calls
% to delete files and directories are significantly slower than DOS calls.
%
% The 'mode' argument can be used to determine the following:
%   -1:     No backup performed. Trial run only with command line
%           information.
%   0:      Minimal user input mode. Only questions when the backup would
%           involve updating a file that is newer in the backup directory.
%           This is the default option.
%   1:      Safe mode. Questions most actions (significant user input
%           required to do a backup), except for copying (without
%           overwriting) files/directories to the backup directory.
%
% Example:
%
% dirbackup('C:\Mywork', 'D:\Backup\Mywork', 0)

if (nargin < 3)
   runmode = 0;
end;

tmp = what(s1);
s1 = tmp.path;
tmp = what(s2);
s2 = tmp.path;

if ~exist(s2, 'dir')
   fprintf('\nBackup folder does not yet exist. ');
   R = input('Do you want to create the folder and copy the source? (y/n) ', 's');
   if strcmpi(R, 'y')
      [status, out] = system(sprintf('xcopy "%s" "%s" /E /I /R /K /H /Y', s1, s2));
      if status
         fprintf('Backup failed.');
      end;
   else
      fprintf('\nBackup process cancelled by user.');
   end;
end;

% Remove the '.' and '..' from the file structure arrays
file1 = dir(s1);
nfiles1 = length(file1);
for i = nfiles1:-1:1
   if (isequal(file1(i).name , '.') || isequal(file1(i).name , '..'))
      file1(i) = [];
   end;
end;
file2 = dir(s2);
nfiles2 = length(file2);
for i = nfiles2:-1:1
   if (isequal(file2(i).name , '.') || isequal(file2(i).name , '..'))
      file2(i) = [];
   end;
end;

% Sort file names in current directory (ignoring case) ...
nfiles1 = length(file1);
[x, i] = sort(lower({file1(:).name}));
file1 = file1(i);
nfiles2 = length(file2);
[x, i] = sort(lower({file2(:).name}));
file2 = file2(i);

% Loop through the files, comparing the 'Date modified' values ...
n1 = 1; n2 = 1;
while (n1 <= nfiles1 && n2 <= nfiles2)
   if strcmpi(file1(n1).name, file2(n2).name)
      % Current files have same name (ignoring case) ...
      if (file1(n1).isdir + file2(n2).isdir == 2)
         % Both files are directories. Call this function (recursive) ...
         dirbackup([s1, '\', file1(n1).name], [s2, '\', file2(n2).name], runmode);
      elseif (file2(n2).isdir + file1(n1).isdir == 1)
         % One file is a directory, while the other is not ...
         error('Target directories contain a file ''%s'' and directory ''%s''', file1(n1).name, file2(n2).name);
      elseif (file1(n1).isdir + file2(n2).isdir == 0)
         % Both are non-directory files ...
         if ~strcmp(file1(n1).date, file2(n2).date)
            % The dates are different and one of the files should be updated ...
            loc_update(s1, file1(n1), s2, file2(n2), runmode);
         end;
      end;
      % Continue to next files in s1 and s2 ...
      n1 = n1 + 1;
      n2 = n2 + 1;
   else
      % Current files in s1 and s2 are different. Sort the files by
      % name, ignoring case ...
      [xx, pos] = sort(lower({file1(n1).name, file2(n2).name}));
      if (pos(1) == 1)
         % The file in s1 is higher up the alphabetic rank. Copy
         % file from s1 to s2 ...
         loc_copy(s1, file1(n1), s2, file1(n1), runmode);
         % Continue to next file in s1 ...
         n1 = n1 + 1;
      else
         % The file in s2 is higher up the alphabetic rank ...
         % Directory s1 is the source, delete file or directory in s2 ....
         if file2(n2).isdir
            loc_deletedir([s2, '\', file2(n2).name], runmode);
         else
            loc_deletefile([s2, '\', file2(n2).name], runmode);
         end;
         % Continue to next file in s2 ...
         n2 = n2 + 1;
      end;
   end;
end;

% One of the directories is exhausted ...
if (n1 > nfiles1)
   % Remaining files in s2 not present in s1. Delete files from s2 ...
   for n2 = n2:nfiles2
      if (file2(n2).isdir)
         loc_deletedir([s2, '\', file2(n2).name], runmode);
      else
         loc_deletefile([s2, '\', file2(n2).name], runmode);
      end;
   end;
   n2 = n2 + 1;
elseif (n2 > nfiles2)
   % Remaining files in s1 not present in s2. Copy the files to s2 ...
   for n1 = n1:nfiles1
      loc_copy(s1, file1(n1), s2, file1(n1), runmode);
   end;
   n1 = n1 + 1;
end;

function loc_update(srcdir, srcfile, tgtdir, tgtfile, runmode)
% Default choice is to continue the backup ...
R = 'y';
source = [srcdir, '\', srcfile.name];
target = [tgtdir, '\.'];
if (datenum(srcfile.date) > datenum(tgtfile.date))
   % Directory s1 has newer file, update file in s2 ...
   if (runmode == 1)
      fprintf('\nThe file ''%s'' (source) is newer than the file ''%s'' (target). ', source, target);
      R = input('\nDo you wish to overwrite the target file? (y/n/q) ', 's');
   end;
else
   fprintf('\nThe file ''%s'' (source) is older than the file ''%s'' (target). ', source, target);
   R = input('\nAre you sure you wish to overwrite the target file? (y/n/q)  ', 's');
end;
ok = getanswer(R);
fprintf('\n''%s'' ... ', [tgtdir, '\', tgtfile.name]);
if ok
   if (runmode >= 0)
      [status, out] = system(sprintf('xcopy "%s" "%s" /K /H /Y /Q', source, target));
   else
      status = 0;
   end;
   if status
      fprintf('An unforeseen error occurred during the backup process.\nThe file ''%s'' could not be copied to ''%s''.\nSystem message: %s', source, target, out);
   else
      fprintf('[UPDATED]');
   end;
else
   fprintf('[SKIPPED]');
end;

% Local copy function ...
function loc_copy(srcdir, srcfile, tgtdir, tgtfile, runmode)
source = [srcdir, '\', srcfile.name];
target = tgtdir;
% Directories are a bit tricky to copy properly without errors occurring
% and/or DOS waiting for user input (without a message in the matlab
% console). The following code has been tested and worked under various
% conditions tested.
if srcfile.isdir
   source = [source, '\*'];
   % Check to see if directory already exists. This shouldn't be necessary,
   % but it is!
   if ~exist([target, '\', srcfile.name], 'dir')
      mkdir(target, srcfile.name);
   end
   target = [target, '\', srcfile.name, '\.'];
else
   target = [target, '\.'];
end;
fprintf('\n%s ... ', source);
if (runmode >= 0)
   [status, out] = system(sprintf('xcopy "%s" "%s" /E /K /H /Y /Q', source, target));
else
   status = 0;
end;
if status
   fprintf('An unforeseen error occurred during the backup process.\nThe file/directory ''%s'' could not be copied to ''%s''.\nSystem message: %s', source, target, out);
else
   fprintf('[COPIED]');
end;

%Local file delete function ...
function loc_deletefile(target, runmode)
% Default choice is to continue the backup ...
R = 'y';
if (runmode == 1)
   fprintf('\nThe file ''%s'' is no longer in the source directory. ', target);
   R = input('Delete? (y/n/q) ', 's');
end;
% Go through potential user options and retrieve answer ...
ok = getanswer(R);
fprintf('\n''%s'' ... ', target);
if ok
   if (runmode >= 0)
      [status, out] = system(sprintf('del /AH /AR /AS /AA "%s"', target));
   else
      status = 0;
   end;
   if status
      fprintf('An unforeseen error occurred during the backup process.\nThe file ''%s'' could not be deleted.\nSystem message: %s', target, out);
   else
      fprintf('[DELETED]');
   end;
else
   fprintf('[SKIPPED]');
end;

% Local directory delete function ...
function loc_deletedir(target, runmode)
% Default choice is to continue the backup ...
R = 'y';
if (runmode == 1)
   fprintf('\nThe directory ''%s'' is no longer in the source directory. ', target);
   R = input('Delete? (y/n/q) ', 's');
end;
% Go through potential user options and retrieve answer ...
ok = getanswer(R);
fprintf('\n''%s'' ... ', target);
if ok
   if (runmode >= 0)
      [status, out] = system(sprintf('rmdir "%s" /S /Q', target));
   else
      status = 0;
   end;
   if status
      fprintf('An unforeseen error occurred during the backup process.\nThe directory ''%s'' could not be deleted.\nSystem message: %s', target, out);
   else
      fprintf('[DELETED]');
   end;
else
   fprintf('[SKIPPED]');
end;

function ok = getanswer(R)
ok = 0;
if strcmpi(R, 'y')
   ok = 1;
elseif strcmpi(R, 'n')
   ok = 0;
elseif strcmpi(R, 'q')
   error('Backup process stopped by user.');
else
   error('Incorrect choice. Backup process stopped.');
end;


text:
%SHOWIMG  Pajdla: Shows scaled images in the gray palette
%
%
%	function f = showimg(m,f)
%
%	m = image matrix
%	f = figure handle
%
%       See also:  IMAGE, IMAGESC, COLORMEN.

%	Author: 	Tomas Pajdla, Tomas.Pajdla@esat.kuleuven.ac.be
%					    pajdla@vision.felk.cvut.cz
%			03/06/95 ESAT-MI2, KU Leuven
%	Documentation:
%	Language: 	Matlab 4.2, (c) MathWorks
%
function f = showimg(m,f);

if (nargin==2)
 figure(f);
else
 f=figure;
%  colormen;
 colormap('gray');
end

imagesc(m);
axis('image');

return

author: strawlab

repo: MultiCamSelfCal


text:
function [ftlb] = J2ftlb(J)
% Convert energy or work from joules to foot-pounds.
% Chad A. Greene 2012
ftlb = J*0.73756217557;


text:
function [ cost, grad, numTotal, pred_cell ] = drdae_discrim_joint_kl_obj( ...
    theta, eI, data_cell, targets_cell, mixture_spectrum, fprop_only, pred_out)
% Copyright (c) 2014-present University of Illinois at Urbana-Champaign
% All rights reserved.
%
% Developed by:     Po-Sen Huang, Paris Smaragdis
%                   Department of Electrical and Computer Engineering
%                   Department of Computer Science
%
% discrim. training + joint masking
%
%PRNN_OBJ MinFunc style objective for Deep Recurrent Denoising Autoencoder
%   theta is the full parameter vector
%   eI contains experiment / network architecture
%   data_cell is a cell array of matrices. Each a distinct length is a cell
%             entry. Each matrix has a time series example in each column
%   targets_cell is parallel to data, but contains the labels for each time
%   fprop_only is a flag that only computes the cost, no gradient
%   numTotal is total number of frames evaluated
%   pred_out is a binary flag for whether pred_cell is populated
%            pred_cell only filled properly when utterances one per cell

%% Debug: Turns this into an identity-function for debugging rest of system
if isfield(eI, 'objReturnsIdentity') && eI.objReturnsIdentity
    cost = 0; grad = 0; numTotal = 0;
    for l = 1:numel(data_cell)
        numUtterances = size(data_cell{l}, 2);
        original_vector = reshape(data_cell{l}, eI.winSize*eI.featDim, []);
        midPnt = ceil(eI.winSize/2);
        original_vector = original_vector((midPnt-1)*14+1 : midPnt*14, :);
        pred_cell{l} = reshape(original_vector, [], numUtterances);
    end
    return;
end

%if isempty(return_activation),
  return_activation = 0;
%end

%% Load data from globals if not passed in (happens when run on RPC slave)
global g_data_cell;
global g_targets_cell;
isSlave = false;
if isempty(data_cell)
    data_cell = g_data_cell;
    targets_cell = g_targets_cell;
    isSlave = true;
end;
pred_cell = cell(1,numel(data_cell));
act_cell = cell(1,numel(data_cell));
%% default short circuits to false
if ~isfield(eI, 'shortCircuit')
    eI.shortCircuit = 0;
end;

%% default dropout to false
if ~isfield(eI, 'dropout')
  eI.dropout = 0;
end;

%% setup weights and accumulators
[stack, W_t] = rnn_params2stack(theta, eI);
cost = 0; numTotal = 0;
outputDim = eI.layerSizes(end);

%% setup structures to aggregate gradients
stackGrad = cell(1,numel(eI.layerSizes));

if isfield(eI, 'fullRNN') && eI.fullRNN==1
   W_t_grad = cell(1,numel(eI.layerSizes)-1);
    for l = 1:numel(eI.layerSizes)-1
        W_t_grad{l}.W = zeros(size(W_t{l}.W));
    end
else
   W_t_grad = zeros(size(W_t));
end

for l = 1:numel(eI.layerSizes)
    stackGrad{l}.W = zeros(size(stack{l}.W));
    stackGrad{l}.b = zeros(size(stack{l}.b));
end
if eI.shortCircuit
    stackGrad{end}.W_ss = zeros(size(stack{end}.W_ss));
end;
%% check options
if ~exist('fprop_only','var')
    fprop_only = false;
end;
if ~exist('pred_out','var')
    pred_out = false;
end;

% DROPOUT: vector of length of hidden layers with 0 or 1
% (to drop or keep activation unit) with prob=0.5
hActToDrop = cell(numel(eI.layerSizes),1);
for i=1:numel(eI.layerSizes)-1
 if eI.dropout
   hActToDrop{i} = 1/eI.dropout * binornd(1,eI.dropout, eI.layerSizes(i),1);
   %hActToDrop{i} = round(rand(eI.layerSizes(i),1));
 else
   hActToDrop{i} = ones(eI.layerSizes(i),1);
 end
end

%% loop over each distinct length
for c = 1:numel(data_cell)
    if isempty(data_cell{c}), continue; end

    data = data_cell{c};
    targets = {};
    if ~isempty(targets_cell), targets = targets_cell{c}; end;
    uttPred = [];
    T =size(data,1) / eI.inputDim;
    % store hidden unit activations at each time instant
    hAct = cell(numel(eI.layerSizes)-1, T);
    for t = 1:T
        %% forward prop all hidden layers
        for l = 1:numel(eI.layerSizes)-1
            if l == 1
                hAct{1,t} = stack{1}.W * data((t-1)*eI.inputDim+1:t*eI.inputDim, :);
            else
                hAct{l,t} = stack{l}.W * hAct{l-1,t};
            end;
            hAct{l,t} = bsxfun(@plus, hAct{l,t}, stack{l}.b);
            % temporal recurrence. limited to single layer for now
            if t > 1
                if isfield(eI, 'fullRNN') && eI.fullRNN==1
                    hAct{l,t} = hAct{l,t} + W_t{l}.W * hAct{l,t-1};
                elseif l == eI.temporalLayer
                    hAct{l,t} = hAct{l,t} + W_t * hAct{l,t-1};
                end
            end;

            % nonlinearity
            if strcmpi(eI.activationFn,'tanh')
                hAct{l,t} = tanh(hAct{l,t});
            elseif strcmpi(eI.activationFn,'logistic')
                hAct{l,t} = 1./(1+exp(-hAct{l,t}));
            elseif strcmpi(eI.activationFn,'RELU')
                hAct{l,t} = max(0,hAct{l,t});
            else
                error('unrecognized activation function: %s',eI.activationFn);
            end;
            %dropout (hActToDrop will be all ones if no dropout specified)
            hAct{1,t} = bsxfun(@times, hAct{1,t}, hActToDrop{l});
        end;
        % forward prop top layer not done here to avoid caching it
    end;
    %% compute cost and backprop through time
    if  eI.temporalLayer
        if isfield(eI, 'fullRNN') && eI.fullRNN==1
            delta_t = cell(1, numel(eI.layerSizes)-1);
            for l = 1:numel(eI.layerSizes)-1
                delta_t{l} = zeros(eI.layerSizes(l),size(data,2));
            end
        else
            delta_t = zeros(eI.layerSizes(eI.temporalLayer),size(data,2));
        end
    end;

    y1_dim= 1:outputDim/2;
    y2_dim= outputDim/2+1:outputDim;
    mixtures=mixture_spectrum{c};

    for t = T:-1:1
        l = numel(eI.layerSizes);
        %% forward prop output layer for this timestep
        curPred = bsxfun(@plus, stack{l}.W * hAct{l-1,t}, stack{l}.b);

        if eI.outputnonlinear==1,
           if strcmpi(eI.activationFn,'tanh')
                curPred = tanh(curPred);
           elseif strcmpi(eI.activationFn,'logistic')
                curPred = 1./(1+exp(-curPred));
           elseif strcmpi(eI.activationFn,'RELU')
                curPred = max(0,curPred);
           else
                error('unrecognized activation function: %s',eI.activationFn);
           end
        end

        mixture=mixtures((t-1)*numel(y1_dim)+1:t*numel(y1_dim),:);
        a1 = curPred(y1_dim,:); a2 = curPred(y2_dim,:);

        const=eI.const;%1e-8 ;
        const2=eI.const2;% 1e-3;

        if strcmp(eI.opt,'softlinear'),
            y1= (a1)./((a1)+(a2)+1e-10).* mixture;
            y2= (a2)./((a1)+(a2)+1e-10).* mixture;
        elseif strcmp(eI.opt,'softabs'),
            y1= abs(a1)./(abs(a1)+abs(a2)+1e-10).* mixture;
            y2= abs(a2)./(abs(a1)+abs(a2)+1e-10).* mixture;
        elseif strcmp(eI.opt,'softabs_const') || strcmp(eI.opt,'softabs_kl_const'),
            y1= abs(a1)./(abs(a1)+abs(a2)+const).* mixture;
            y2= abs(a2)./(abs(a1)+abs(a2)+const).* mixture;
        elseif strcmp(eI.opt, 'softquad')
            y1= (a1.^2)./((a1.^2)+(a2.^2)+1e-10).* mixture;
            y2= (a2.^2)./((a1.^2)+(a2.^2)+1e-10).* mixture;
        else
        end
        weighted_curPred=[y1; y2];

        % add short circuit to regression prediction if model has it
        if eI.shortCircuit
            weighted_curPred = weighted_curPred + stack{end}.W_ss ...
                * data((t-1)*eI.inputDim+1:t*eI.inputDim, :);
        end;
        if pred_out, uttPred = [weighted_curPred, uttPred]; end;
        % skip loss computation if no targets given
        if isempty(targets), continue; end;

        curTargets = targets((t-1)*outputDim+1:t*outputDim, :);
        curTargets_neg = [curTargets(outputDim/2+1:outputDim,:); curTargets(1:outputDim/2,:)];

        y_t = (1- eI.r) * weighted_curPred + eI.r * curTargets_neg - curTargets;

        ya_ta= y_t(y1_dim,:);
        yb_tb= y_t(y2_dim,:);

        if strcmp(eI.opt,'softlinear'),
            delta_y1 =  (ya_ta-yb_tb).* y2./(a1+a2+1e-10);
            delta_y2 = (-ya_ta+yb_tb) .* y1./ (a1+a2+1e-10);
        elseif strcmp(eI.opt,'softabs'),
            delta_y1 =  (ya_ta-yb_tb).* y2./(abs(a1)+abs(a2)+1e-10);
            delta_y2 = (-ya_ta+yb_tb) .* y1./ (abs(a1)+abs(a2)+1e-10);

            delta_y1(a1<0) = -delta_y1(a1<0);
            delta_y2(a2<0) = -delta_y2(a2<0);
        elseif strcmp(eI.opt,'softabs_const'),
             const_div=const./((abs(a1)+abs(a2)+const).^2).* mixture;
             delta_y1 =  (ya_ta-yb_tb).* y2./(abs(a1)+abs(a2)+const);
             delta_y1 = delta_y1+ ya_ta.* const_div;
             delta_y2 = (-ya_ta+yb_tb) .* y1./ (abs(a1)+abs(a2)+const);
             delta_y2= delta_y2+ yb_tb.* const_div;

             delta_y1(a1<0) =  -delta_y1(a1<0);
             delta_y2(a2<0) =  -delta_y2(a2<0);
        elseif strcmp(eI.opt,'softabs_kl_const'),
             y_target_a = curTargets(y1_dim, :);
             y_target_b = curTargets(y2_dim, :);
             y_target_neg_a = y_target_b;
             y_target_neg_b = y_target_a;

             y_pred_a = weighted_curPred(y1_dim, :);
             y_pred_b = weighted_curPred(y2_dim, :);

             const_div=const./((abs(a1)+abs(a2)+const).^2).* mixture;

             delta_y1 =  (-y_target_a./(y_pred_a+const2) + y_target_b./(y_pred_b+const2)).* y2./(abs(a1)+abs(a2)+const);
             delta_y1 = delta_y1+  (-y_target_a./(y_pred_a+const2)+1).* const_div;

             delta_y2 =  (y_target_a./(y_pred_a+const2) - y_target_b./(y_pred_b+const2)).* y1./(abs(a1)+abs(a2)+const);
             delta_y2= delta_y2+ (-y_target_b./(y_pred_b+const2)+1) .* const_div;

             % discrim part
             delta_y1 =  delta_y1- eI.r* (-y_target_neg_a./(y_pred_a+const2) + y_target_neg_b./(y_pred_b+const2)).* y2./(abs(a1)+abs(a2)+const);
             delta_y1 = delta_y1-   eI.r* (-y_target_neg_a./(y_pred_a+const2)+1).* const_div;

             delta_y2 = delta_y2- eI.r*(y_target_neg_a./(y_pred_a+const2) - y_target_neg_b./(y_pred_b+const2)).* y1./(abs(a1)+abs(a2)+const);
             delta_y2= delta_y2-  eI.r*(-y_target_neg_b./(y_pred_b+const2)+1) .* const_div;

             delta_y1(a1<0) =  -delta_y1(a1<0);
             delta_y2(a2<0) =  -delta_y2(a2<0);
        elseif strcmp(eI.opt, 'softquad')
            delta_y1 =  (ya_ta-yb_tb).* (2*a1.*y2)./ (a1.^2+a2.^2+1e-10); %  y1= (a1.^2)./((a1.^2)+(a2.^2)+1e-8);%.* mixture;
            delta_y2 =  (-ya_ta+yb_tb).* (2*a2.*y1)./ (a1.^2+a2.^2+1e-10);%         y2= (a2.^2)./((a1.^2)+(a2.^2)+1e-8);%.* mixture;
        else
        end

        delta = [ delta_y1; delta_y2 ];
        if strcmp(eI.opt,'softlinear') || strcmp(eI.opt,'softabs') || strcmp(eI.opt, 'softquad') || strcmp(eI.opt,'softabs_const'),
             cost = cost + 0.5 * ( sum( sum((weighted_curPred - curTargets).^2)) ...
                -  eI.r* sum( sum((weighted_curPred - curTargets_neg).^2)));
        elseif strcmp(eI.opt,'softabs_kl_const'),
             cost = cost +...
             sum(sum( curTargets.*log( curTargets./(weighted_curPred + const2) + const2 )-curTargets+ weighted_curPred +const2))...
            -eI.r* sum(sum( curTargets_neg.*log( curTargets_neg./(weighted_curPred + const2) + const2 )-curTargets_neg+ weighted_curPred +const2));
        else

        end

        if eI.outputnonlinear==1,
             if strcmpi(eI.activationFn,'tanh')
                delta = delta .* (1 -curPred.^2);
            elseif strcmpi(eI.activationFn,'logistic')
                delta = delta .* curPred .* (1 - curPred);
            elseif strcmpi(eI.activationFn,'RELU')
                delta = delta .* double(curPred>0);
            else
                error('unrecognized activation function: %s',eI.activationFn);
            end;
        end

        if fprop_only, continue; end;
        %% regression layer gradient and delta
        stackGrad{l}.W = stackGrad{l}.W + delta * hAct{l-1,t}';
        stackGrad{l}.b = stackGrad{l}.b + sum(delta,2);
        % short circuit layer

        if eI.shortCircuit
            stackGrad{end}.W_ss = stackGrad{end}.W_ss + delta ...
                * data((t-1)*eI.inputDim+1:t*eI.inputDim, :)';
        end;
        delta = stack{l}.W' * delta;
        %% backprop through hidden layers
        for l = numel(eI.layerSizes)-1:-1:1
            % aggregate temporal delta term if this is the recurrent layer
            if isfield(eI, 'fullRNN') && eI.fullRNN==1
                delta = delta + delta_t{l};
            elseif l == eI.temporalLayer
              delta = delta + delta_t;
            else
            end
            % push delta through activation function for this layer
            % tanh unit choice assumed
            if strcmpi(eI.activationFn,'tanh')
                delta = delta .* (1 - hAct{l,t}.^2);
            elseif strcmpi(eI.activationFn,'logistic')
                delta = delta .* hAct{l,t} .* (1 - hAct{l,t});
            elseif strcmpi(eI.activationFn,'RELU')
                delta = delta .* double(hAct{l,t}>0);
            else
                error('unrecognized activation function: %s',eI.activationFn);
            end;
            % gradient of bottom-up connection for this layer
            if l > 1
                stackGrad{l}.W = stackGrad{l}.W + delta * hAct{l-1,t}';
            else
                stackGrad{l}.W = stackGrad{l}.W + delta * data((t-1)*eI.inputDim+1:t*eI.inputDim, :)';
            end;
            % gradient for bias
            stackGrad{l}.b = stackGrad{l}.b + sum(delta,2);

            % compute derivative and delta for temporal connections
            if t > 1
                if isfield(eI, 'fullRNN') && eI.fullRNN==1
                     W_t_grad{l}.W = W_t_grad{l}.W + delta * hAct{l,t-1}';
                     % push delta through temporal weights
                     delta_t{l} = W_t{l}.W' * delta;
                elseif l == eI.temporalLayer
                     W_t_grad = W_t_grad + delta * hAct{l,t-1}';
                     % push delta through temporal weights
                     delta_t = W_t' * delta;
                end
            end
            % push delta through bottom-up weights
            if l > 1
                delta = stack{l}.W' * delta;
            end;
        end
        % reduces avg memory usage but doesn't reduce peak
        %hAct(:,t) = [];
    end
    pred_cell{c} = uttPred;
    % Return the activations for this utterance.
    if return_activation,
      act_cell{c} = cell2mat(hAct);
    end
    % keep track of how many examples seen in total
    numTotal = numTotal + T * size(targets,2);
end

%% stack gradients into single vector and compute weight cost
wCost = numTotal * eI.lambda * sum(theta.^2);
grad = rnn_stack2params(stackGrad, eI, W_t_grad, true);
grad = grad + 2 * numTotal * eI.lambda * theta;

%% clipping
if isfield(eI,'clip') && eI.clip~=0, % if eI.clip==0, no clip
  if eI.clip > 0 % method one -clip the whole
      norm_grad = norm(grad);
      fprintf('norm_grad:%f\n', norm_grad);
      % avoid numerial problem
      if norm_grad <0 || norm_grad > 1e15 || isnan(norm_grad) || isinf(norm_grad),
          grad = zeros(size(grad));
          fprintf('set gradient to zeros\n');
      end
      if norm_grad > eI.clip
         grad = eI.clip * grad/ norm_grad;
      end
  else % method two - clip each entry
      clip_value = -1*eI.clip;
      grad(grad > clip_value)=clip_value;
      grad(grad < -clip_value)=-clip_value;
  end
end

%%
avCost = cost/numTotal;
avWCost = wCost/numTotal;
cost = cost + wCost;

% print output
if ~isSlave && ~isempty(targets_cell)
    fprintf('loss:  %f  wCost:  %f \t',avCost, avWCost);

    if isfield(eI, 'fullRNN') && eI.fullRNN==1
        fprintf('wNorm: %f  rNorm: %f  oNorm: %f\n',sum(stack{1}.W(:).^2),...
            sum(W_t{1}.W(:).^2), sum(stack{end}.W(:).^2));
    else
        fprintf('wNorm: %f  rNorm: %f  oNorm: %f\n',sum(stack{1}.W(:).^2),...
            sum(W_t(:).^2), sum(stack{end}.W(:).^2));
    end
end;

author: posenhuang

repo: deeplearningsourceseparation


text:
classdef PTKGetContextForSegment < PTKPlugin
    % PTKGetContextForSegment. Plugin for finding the region of interest for a segment.
    %
    %     This is a plugin for the Pulmonary Toolkit. Plugins can be run using
    %     the gui, or through the interfaces provided by the Pulmonary Toolkit.
    %     See PTKPlugin.m for more information on how to run plugins.
    %
    %     Plugins should not be run directly from your code.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

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

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

        MemoryCachePolicy = 'Permanent'
        DiskCachePolicy = 'Permanent'
    end

    methods (Static)
        function results = RunPlugin(dataset, context, reporting)
            segment_mask = dataset.GetResult('PTKPulmonarySegments', PTKContext.LungROI);
            results = PTKGetSegmentROI(segment_mask, context, reporting);
        end
    end
end

author: tomdoel

repo: pulmonarytoolkit


text:
function result = UTCtimestamp()

time_unix = java.lang.System.currentTimeMillis;

% http://stackoverflow.com/questions/12661862/converting-epoch-to-date-in-matlab

time_reference = datenum('1970', 'yyyy');
time_matlab = time_reference + time_unix / 8.64e7;
result = datestr(time_matlab, 'yyyy-mm-ddTHH:MM:SSZ');

author: jianxiongxiao

repo: ProfXkit


text:
function y = cvx_isaffine( x, full ) %#ok
if nargin == 2 && full,
	y = true( size( x ) );
else
    y = true;
end

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

author: yu-jiang

repo: radpbook

save_path: github-repos/MATLAB/yu-jiang-radpbook


text:
function x = rhs( y )
x = y.rhs_;

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


text:
function dtiSpatialNormalize(dt6FileName, templateName, outDirName, useBrainMask, useB0)
%
% dtiSpatialNormalize([dt6FileName=uiget], [templateName='MNI'],
%                     [outDirName=inName_templateName],
%                     [useBrainMaskFlag=false], [useB0Flag=false])
%
% Compute spatial normalization for a single subject and save a
% spatially-normalized copy of the data. Now works with the new
% NIFTI-based dt6 format (should work on old data too).
%
% To normalize a mrDiffusion dataset, try running dtiSpatialNormalize. If
% you don't enter a specific dt6 filename, it will prompt you for a
% dt6 file. It will save a normalized copy of the data in a
% directory with the same name as the one containing the dt6 file,
% but with '_templateName' appended on the end. It will also save a
% png image in there that is a montage showing the normalized PDD
% map overlaid on the MNI t1. This is useful for checking the results.
%
% 2007.10.30 RFD: revamped this script, cleaning up much code in the
% process.
% 2007.11.19 RFD: turned this into a proper function and moved it
% to the xform dir.

if(~exist('dt6FileName','var'))
  dt6FileName = '';
end
if(~exist('useB0','var')||isempty(useB0))
  useB0 = false;
end
if(~exist('useBrainMask','var')||isempty(useBrainMask))
  useBrainMask = false;
end
if(~exist('templateName','var')||isempty(templateName))
  templateName = 'MNI';
end

switch templateName
 case {'MNI','SIRL54'}
  templateDir = fullfile(fileparts(which('mrDiffusion.m')),'templates');
  if(useB0)
	template = fullfile(templateDir, [templateName '_EPI']);
  else
	template = fullfile(templateDir, [templateName '_T1']);
  end
  if(useBrainMask)
	template = [template '_brain'];
  end
  template = [template '.nii.gz'];
 otherwise
  template = templateName;
  [junk,templateName] = fileparts(template);
end

[dt,t1] = dtiLoadDt6(dt6FileName,false);

if(~exist('outDirName','var')||isempty(outDirName))
  outDirName = [fileparts(dt.dataFile) '_' templateName];
end
spm_defaults; global defaults; defaults.analyze.flip = 0;
params = defaults.normalise.estimate;

if(useB0)
    desc = [templateName ' normalized using b0'];
    im = mrAnatHistogramClip(double(dt.b0),0.4,0.98);
    xf = dt.xformToAcpc;
	if(useBrainMask)
	  im(~dt.brainMask) = 0;
	  desc = [desc ' (masked)'];
	end
else
    desc = [templateName ' normalized using T1'];
    im = mrAnatHistogramClip(double(t1.img),0.4,0.98);
    xf = t1.xformToAcpc;
	if(useBrainMask)
	  im(~t1.brainMask) = 0;
	  desc = [desc ' (masked)'];
	end
end

disp(['Normalizing ' dt6FileName ' to ' template '...']);
sn = mrAnatComputeSpmSpatialNorm(im, xf, template, params);

[dt_sn,t1_sn] = dtiSpmDeformer(dt,sn,t1);

t1 = niftiGetStruct(single(t1_sn.img), t1_sn.xformToAcpc, [], desc, 't1');
b0 = niftiGetStruct(single(dt_sn.b0), dt_sn.xformToAcpc, [], desc, 'b=0');
bm = niftiGetStruct(uint8(dt_sn.brainMask), dt_sn.xformToAcpc, [], desc, 'dtBrainMask');
sz = size(dt_sn.dt6);
niftiDt6 = reshape(dt_sn.dt6(:,:,:,[1 4 2 5 6 3]),[sz(1:3),1,sz(4)]);
tensors = niftiGetStruct(niftiDt6, dt_sn.xformToAcpc, [], desc, 'DTI');

% Load the MNI to check the normalization results:
mni = niftiRead(fullfile(templateDir, 'MNI_T1.nii.gz'));
[pddT1,acpcToImXform,mm] = dtiRawCheckTensors(tensors, mni, bm);
sl = 6:2:size(mni.data,3)-2;
imgRgb = makeMontage3(flipdim(permute(pddT1,[2 1 3 4]),1), sl, mni.pixdim(1), 0, [], [], -1);
%figure; image(imgRgb);

% To save the results:
[fullParentDir, dataDir] = fileparts(outDirName);
files.b0 = fullfile(dataDir,'bin','b0.nii.gz');
files.brainMask = fullfile(dataDir,'bin','brainMask.nii.gz');
files.tensors = fullfile(dataDir,'bin','tensors.nii.gz');
files.t1 = fullfile(dataDir,'t1.nii.gz');
mkdir(outDirName);
mkdir(fullfile(outDirName,'bin'));
b0.fname = fullfile(fullParentDir,files.b0);
tensors.fname = fullfile(fullParentDir,files.tensors);
bm.fname = fullfile(fullParentDir,files.brainMask);
t1.fname = fullfile(fullParentDir,files.t1);
writeFileNifti(b0);
writeFileNifti(tensors);
writeFileNifti(bm);
writeFileNifti(t1);
adcUnits = dt_sn.adcUnits;
params.buildDate = datestr(now,'yyyy-mm-dd HH:MM');
l = license('inuse');
params.buildId = sprintf('%s on Matlab R%s (%s)',l(1).user,version('-release'),computer);
params.sourceData = dt_sn.dataFile;
save(fullfile(outDirName,'dt6'),'adcUnits','params','files');
imwrite(imgRgb,fullfile(outDirName,'pddT1.png'));

return;

bd = '/biac3/wandell4/data/reading_longitude/dti_y4/';
inDir = 'dti06_smooth2';

d = dir(fullfile(bd,'*0*'));
n = 0;
for(ii=1:length(d))
  tmp = fullfile(bd,d(ii).name,inDir,'dt6.mat');
  if(exist(tmp,'file'))
	n = n+1;
    sc{n} = d(ii).name;
	fn{n} = tmp;
  end
end

for(ii=1:length(fn))
  disp(['Processing ' sc{ii} '...']);
  dtiRawFixDt6File(fn{ii});
  dtiSpatialNormalize(fn{ii}, 'SIRL54', [], true);
end

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function colorsurface( ptch, cameras )
%COLORSURFACE: color in a surface based on image data
%
%   COLORSURFACE(PTCH,CAMERAS) colors-in each vertex of the patch PTCH
%   using the nearest image pixel in one of the cameras in CAMERAS.

%   Copyright 2005-2009 The MathWorks, Inc.
%   $Revision: 1.0 $    $Date: 2006/06/30 00:00:00 $

error( nargchk( 2, 2, nargin ) );

if ~ishandle( ptch ) || ~strcmpi( get( ptch, 'Type' ), 'patch' )
    error( 'COLORSURFACE:BadPatch', 'First argument must the handle to a patch object created using the PATCH command' );
end

vertices = get( ptch, 'Vertices' );
normals = get( ptch, 'VertexNormals' );
num_vertices = size( vertices, 1 );

% Get the view vector for each camera
num_cameras = numel( cameras );
cam_normals = zeros( 3, num_cameras );
for ii=1:num_cameras
    cam_normals(:,ii) = spacecarving.getcameradirection( cameras(ii) );
end

% For each vertex, use the normal to find the best camera and then lookup
% the value.
vertexcdata = zeros( num_vertices, 3 );
for ii=1:num_vertices
    % Use the dot product to find the best camera
    angles = normals(ii,:)*cam_normals./norm(normals(ii,:));
    [~,cam_idx] = min( angles );
    % Now project the vertex into the chosen camera
    [imx,imy] = spacecarving.project( cameras(cam_idx), ...
        vertices(ii,1), vertices(ii,2), vertices(ii,3) );
    vertexcdata(ii,:) = double( cameras(cam_idx).Image( round(imy), round(imx), : ) )/255;
end

% Set it into the patch
set( ptch, 'FaceVertexCData', vertexcdata, 'FaceColor', 'interp' );


text:
function c = camSimpleGraphics(csize)

%CAMSIMPLEGRAPHICS Create a simple camera graphics 3D object.
%   CAMGRAPHICS creates a solid representing a camera. The objective is
%   heading towards the camera optical axis and is located at camera
%   position. Initial configuration is: position at origin and optical
%   axis aligned with world's Z axis.
%
%   This function creates an object much simpler (with much less vertices)
%   than CAMGRAPHICS, with the aim of accelerating rendering.
%
%   The result is a structure with fields:
%       .vert0  the vertices in camera frame.
%       .vert   the vertices in world frame.
%       .faces  the definition of faces.
%
%   Fields .vert and .faces are used to draw the object via the PATCH
%   command. Further object repositionning is accomplished with DRAWOBJECT.
%
%   CAMSIMPLEGRAPHICS(SIZE) allows for choosing the camera size. Default is 0.1.
%
%   See also CAMGRAPHICS, PATCH, SET, DRAWOBJECT.

%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.

if nargin == 0
    csize = 0.1;
end

h = .8; % body height
w = 1;  % body width
t = .3; % body thickness

% body vertices
rect      = [1 1;-1 1;-1 -1;1 -1]*diag([w h])/2;
body      = [rect,zeros(4,1);rect,-t*ones(4,1)];

% vertices in camera frame
vert0     = body;

% graphics structure - vertices and faces
c.vert0   = csize*vert0;
c.vert    = c.vert0;
c.faces   = [ ...
    01 02 03 04
    05 06 07 08
    01 02 06 05
    02 03 07 06
    03 04 08 07
    04 01 05 08];

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB 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.
%
%   SLAMTB 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 SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE

author: joansola

repo: slamtb

save_path: github-repos/MATLAB/joansola-slamtb


text:
clear; close all; clc;

%%

toolboxPath=fileparts(fileparts(fileparts(mfilename('fullpath'))));
docPath=fullfile(fileparts(fileparts(fileparts(mfilename('fullpath')))),'docs');
libPath=fullfile(fileparts(fileparts(fileparts(mfilename('fullpath')))),'lib');
docToolsPath=fullfile(fileparts(fileparts(fileparts(mfilename('fullpath')))),'docs','docTools');

pathNames={docToolsPath,libPath,docPath};

%% Prepare boilerplate

licenseBoilerPlate=fullfile(toolboxPath,'licenseBoilerPlate.txt');
[T]=txtfile2cell(licenseBoilerPlate);

footerTargetText='% _*GIBBON footer text*_ ';

%%

licenseLink='https://github.com/gibbonCode/GIBBON/blob/master/LICENSE';

%Add comment symbols
for q=1:1:numel(T)
    T{q}=['% ',T{q}];
end

%Add target header
T=[{'%% '};{footerTargetText};{'% '};{['% License: <',licenseLink,'>']};T(1:end)];

%%

fileExtension='.m';

%%

numPaths=numel(pathNames);
for q_path=1:1:numPaths
    pathName=pathNames{q_path};
    files = dir(fullfile(pathName,'*.m'));
    files={files(1:end).name};
    files=sort(files(:));
    numFiles=numel(files);
    for q_file=1:1:numFiles
        fileName=fullfile(pathName,files{q_file});
        [T_now]=txtfile2cell(fileName);
        T_now(end+1:end+numel(T))=T;
        cell2txtfile(fileName,T_now,0);
    end
end

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

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
function [ zsl_accuracy, Y_hit5 ] = zsl_el( S_est, S_te_gt, param)
% ZSL_EL calculates zero-shot classification accuracy
%
% INPUT:
%    S_est: estimated semantic labels
%    S_te_gt: ground truth semantic labels
%    param: other parameters
%
% Output:
%    zsl_accuracy: zero-shot classification accuracy (per-sample)

dist     =  1 - (pdist2(S_est, NormalizeFea(S_te_gt')', 'cosine'));
Y_hit5   = zeros(size(dist,1),param.HITK);
for i    = 1:size(dist,1)
    [~, I] = sort(dist(i,:),'descend');
    Y_hit5(i,:) = param.testclasses_id(I(1:param.HITK));
end

n = 0;
for i  = 1:size(dist,1)
    if ismember(param.test_labels(i),Y_hit5(i,:))
        n = n + 1;
    end
end
zsl_accuracy = n/size(dist,1);

end

author: Elyorcv

repo: SAE

save_path: github-repos/MATLAB/Elyorcv-SAE


text:
clc
clear all
easy = 1; %% easy=1 用于测试：EN, SF,SD,PSNR,MSE, MI, VIF, AG, CC, SCD, Qabf等指标； easy=0 用于测试：Nabf, SSIM, MS_SSIM, FMI_pixel, FMI_dct, FMI_w等指标
dataset = 'TNO'
row_name1 = 'row1';
row_data1 = 'row2';
Method_name = 'SeAFusion';
row = 'A';
row_name = strrep(row_name1, 'row', row);
row_data = strrep(row_data1, 'row', row);
fileFolder=fullfile('../Image/Source-Image/TNO/ir'); % 源图像A所在文件夹 此处是'Evaluation\Image\Source-Image\TNO\ir'
dirOutput=dir(fullfile(fileFolder,'*.*'));
fileNames = {dirOutput.name};
[m, num] = size(fileNames);
ir_dir = fullfile('../Image/Source-Image/TNO/ir'); % 源图像A所在文件夹 此处是'Evaluation\Image\Source-Image\TNO\ir'
vi_dir = fullfile('../Image/Source-Image/TNO/vi'); % 源图像B所在文件夹 此处是'Evaluation\Image\Source-Image\TNO\vi'
Fused_dir = fullfile('../Image/Algorithm/SeAFusion_TNO'); % 融合结果所在文件夹 此处是 'Evaluation\Image\Algorithm\SeAFusion_TNO'
EN_set = [];    SF_set = [];SD_set = [];PSNR_set = [];
MSE_set = [];MI_set = [];VIF_set = []; AG_set = [];
CC_set = [];SCD_set = []; Qabf_set = [];
SSIM_set = []; MS_SSIM_set = [];
Nabf_set = [];FMI_pixel_set = [];
FMI_dct_set = []; FMI_w_set = [];
 for j = 1:num
    if (isequal(fileNames{j}, '.') || isequal(fileNames{j}, '..'))
        continue;
    else
        fileName_source_ir = fullfile(ir_dir, fileNames{j});
        fileName_source_vi = fullfile(vi_dir, fileNames{j});
        fileName_Fusion = fullfile(Fused_dir, fileNames{j});
        ir_image = imread(fileName_source_ir);
        vi_image = imread(fileName_source_vi);
        fused_image   = imread(fileName_Fusion);
        if size(ir_image, 3)>2
            ir_image = rgb2gray(ir_image);
        end

        if size(vi_image, 3)>2
            vi_image = rgb2gray(vi_image);
        end

        if size(fused_image, 3)>2
            fused_image = rgb2gray(fused_image);
        end

        [m, n] = size(fused_image);
    %     fused_image = fused_image(7:m-6, 7:n-6);
        ir_size = size(ir_image);
        vi_size = size(vi_image);
        fusion_size = size(fused_image);
        if length(ir_size) < 3 && length(vi_size) < 3
            [EN, SF,SD,PSNR,MSE, MI, VIF, AG, CC, SCD, Qabf, Nabf, SSIM, MS_SSIM, FMI_pixel, FMI_dct, FMI_w] = analysis_Reference(fused_image,ir_image,vi_image, easy);
            EN_set = [EN_set, EN];SF_set = [SF_set,SF];SD_set = [SD_set, SD];PSNR_set = [PSNR_set, PSNR];
            MSE_set = [MSE_set, MSE];MI_set = [MI_set, MI]; VIF_set = [VIF_set, VIF];
            AG_set = [AG_set, AG]; CC_set = [CC_set, CC];SCD_set = [SCD_set, SCD];
            Qabf_set = [Qabf_set, Qabf]; Nabf_set = [Nabf_set, Nabf];
            SSIM_set = [SSIM_set, SSIM]; MS_SSIM_set = [MS_SSIM_set, MS_SSIM];
            FMI_pixel_set = [FMI_pixel_set, FMI_pixel]; FMI_dct_set = [FMI_dct_set,FMI_dct];
            FMI_w_set = [FMI_w_set, FMI_w];
        else
            disp('unsucessful!')
            disp( fileName_Fusion)
        end

        fprintf('Fusion Method:%s, Image Name: %s\n', Method_name, fileNames{j})
    end
end
save_dir = '../Metric'; %存放Excel结果的文件夹
if exist(save_dir,'dir')==0
    mkdir(save_dir);
end
file_name = fullfile(save_dir, strcat('Metric_', Method_name, '.xlsx')); %存放Excel文件的文件名
%% 将测试结果写入 Excel， 此处采用writetable， 第一行可能会有问题，算法名在第二行，评估结果从第三行开始
if easy ==1
    SD_table = table(SD_set');
    PSNR_table = table(PSNR_set');
    MSE_table = table(MSE_set');
    MI_table = table(MI_set');
    VIF_table = table(VIF_set');
    AG_table = table(AG_set');
    CC_table = table(CC_set');
    SCD_table = table(SCD_set');
    EN_table = table(EN_set');
    Qabf_table = table(Qabf_set');
    SF_table = table(SF_set');
    method_name = cellstr(Method_name);
    method_table = table(method_name);

    writetable(SD_table,file_name,'Sheet','SD','Range',row_data);
    writetable(PSNR_table,file_name,'Sheet','PSNR','Range',row_data);
    writetable(MSE_table,file_name,'Sheet','MSE','Range',row_data);
    writetable(MI_table,file_name,'Sheet','MI','Range',row_data);
    writetable(VIF_table,file_name,'Sheet','VIF','Range',row_data);
    writetable(AG_table,file_name,'Sheet','AG','Range',row_data);
    writetable(CC_table,file_name,'Sheet','CC','Range',row_data);
    writetable(SCD_table,file_name,'Sheet','SCD','Range',row_data);
    writetable(EN_table,file_name,'Sheet','EN','Range',row_data);
    writetable(Qabf_table,file_name,'Sheet','Qabf','Range',row_data);
    writetable(SF_table,file_name,'Sheet','SF','Range',row_data);

    writetable(method_table,file_name,'Sheet','SD','Range',row_name);
    writetable(method_table,file_name,'Sheet','PSNR','Range',row_name);
    writetable(method_table,file_name,'Sheet','MSE','Range',row_name);
    writetable(method_table,file_name,'Sheet','MI','Range',row_name);
    writetable(method_table,file_name,'Sheet','VIF','Range',row_name);
    writetable(method_table,file_name,'Sheet','AG','Range',row_name);
    writetable(method_table,file_name,'Sheet','CC','Range',row_name);
    writetable(method_table,file_name,'Sheet','SCD','Range',row_name);
    writetable(method_table,file_name,'Sheet','EN','Range',row_name);
    writetable(method_table,file_name,'Sheet','Qabf','Range',row_name);
    writetable(method_table,file_name,'Sheet','SF','Range',row_name);
else
    Nabf_table = table(Nabf_set');
    SSIM_table = table(SSIM_set');
    MS_SSIM_table = table(MS_SSIM_set');
    FMI_pixel_table = table(FMI_pixel_set');
    FMI_dct_table = table(FMI_dct_set');
    FMI_w_table = table(FMI_w_set');
    method_name = cellstr(Method_name);
    method_table = table(method_name);

    writetable(Nabf_table,file_name,'Sheet','Nabf','Range',row_data);
    writetable(SSIM_table,file_name,'Sheet','SSIM','Range',row_data);
    writetable(MS_SSIM_table,file_name,'Sheet','MS_SSIM','Range',row_data);
    writetable(FMI_pixel_table,file_name,'Sheet','FMI_pixel','Range',row_data);
    writetable(FMI_dct_table,file_name,'Sheet','FMI_dct','Range',row_data);
    writetable(FMI_w_table,file_name,'Sheet','FMI_w','Range',row_data);

    writetable(method_table,file_name,'Sheet','Nabf','Range',row_name);
    writetable(method_table,file_name,'Sheet','SSIM','Range',row_name);
    writetable(method_table,file_name,'Sheet','MS_SSIM','Range',row_name);
    writetable(method_table,file_name,'Sheet','FMI_pixel','Range',row_name);
    writetable(method_table,file_name,'Sheet','FMI_dct','Range',row_name);
    writetable(method_table,file_name,'Sheet','FMI_w','Range',row_name);

end

author: Linfeng-Tang

repo: Image-Fusion


text:
%  locate_variables locate variables in an array
%
%  ::
%
%
%  Args:
%
%  Returns:
%     :
%
%  Note:
%
%  Example:
%
%     See also:
%

author: jmaih


text:
clearvars -except yolonet yoloml yolojb
close all

% Download yolo network if it does not exist in the current folder (which it won't the
% first time you run the code). This takes a while. Code snippet courtesy of mathworks.

if exist('yolonet.mat','file') == 0
    url = 'https://www.mathworks.com/supportfiles/gpucoder/cnn_models/Yolo/yolonet.mat';
    websave('yolonet.mat',url);
end

%load yolo network from current folder (this can take a while) if it does not exist in
%workspace (which it won't the first time you run code)
if exist('yolonet') ~= 1
    load yolonet.mat
end

% the first time we run the script, we need to modify yolonet and save it
% with a new name (yoloml)
if exist('yoloml.mat','file') == 0
    display('modifying network')

    % extract a layer graph from the network. We need to modify this graph.
    lgraph = layerGraph(yolonet.Layers);

    % the yolo network from MATLAB is built like a classifier.
    % We need to convert it to a regression network. This means modifying the
    % last two layers
    lgraph = removeLayers(lgraph,'ClassificationLayer');
    lgraph = removeLayers(lgraph,'softmax');

    % According to the original YOLO paper, the last transfer function
    % is not a leaky, but a normal ReLu (I think).
    % In MATLAB, this is equivalent to a leaky ReLu with Scale = 0.
    alayer = leakyReluLayer('Name','linear_25','Scale',0);
    rlayer = regressionLayer('Name','routput');
    lgraph = addLayers(lgraph,rlayer);
    lgraph = replaceLayer(lgraph,'leakyrelu_25',alayer);
    lgraph = connectLayers(lgraph,'FullyConnectedLayer1','routput');
    yoloml = assembleNetwork(lgraph);

    %save the network with a new name
    display('saving modified network')
    save yoloml yoloml

% if we have created and saved yoloml but not loaded it to workspace, load
% it now.
elseif exist('yoloml') ~= 1
    display('loading modified network')
    load('yoloml.mat')
end

author: darkscyla

repo: MATLAB-Carla-Interface


text:
function [best_overlap,best_boxes] = closest_candidates(gt_boxes, candidates)
% do a matching between gt_boxes and candidates

  num_gt_boxes = size(gt_boxes, 1);
  num_candidates = size(candidates, 1);

  iou_matrix = zeros(num_gt_boxes, num_candidates);
  for i = 1:num_gt_boxes
    iou = overlap(gt_boxes(i,:), candidates);
    iou_matrix(i,:) = iou';
  end

  best_overlap = zeros(num_gt_boxes, 1);
  best_boxes = -ones(num_gt_boxes, 4);

  [best_overlap,best_boxes] = greedy_matching(iou_matrix, gt_boxes, candidates);
end

function [best_overlap,best_boxes] = greedy_matching(iou_matrix, gt_boxes, candidates)
  [n, m] = size(iou_matrix);
  assert(n == size(gt_boxes, 1));
  assert(m == size(candidates, 1));
  if n > m
    gt_matching = greedy_matching_rowwise(iou_matrix');
    candidate_matching = (1:m)';
  else
    gt_matching = (1:n)';
    candidate_matching = greedy_matching_rowwise(iou_matrix);
  end

  best_overlap = zeros(n, 1);
  best_boxes = zeros(n, 4);
  for pair_idx = 1:numel(gt_matching)
    gt_idx = gt_matching(pair_idx);
    candidate_idx = candidate_matching(pair_idx);

    best_overlap(gt_idx) = iou_matrix(gt_idx, candidate_idx);
    best_boxes(gt_idx,:) = candidates(candidate_idx, :);
  end
end

function [matching, objective] = greedy_matching_rowwise(iou_matrix)
  assert(size(iou_matrix, 1) <= size(iou_matrix, 2));
  n = size(iou_matrix, 1);
  matching = zeros(n, 1);
  objective = 0;
  for i = 1:n
    % find max element int matrix
    [max_per_row, max_col_per_row] = max(iou_matrix, [], 2);
    [max_iou,row] = max(max_per_row);
    if max_iou == -inf
      break
    end

    objective = objective + max_iou;
    col = max_col_per_row(row);
    matching(row) = col;
    iou_matrix(row,:) = -inf;
    iou_matrix(:,col) = -inf;
  end
end

author: hosang

repo: detection-proposals


text:
function spquad_test02 ( )

%*****************************************************************************80
%
%% SPQUAD_TEST02 reports the size of various sparse grids.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 January 2012
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SPQUAD_TEST02:\n' );
  fprintf ( 1, '  Print out the order (number of points) used\n' );
  fprintf ( 1, '  for sparse grids of various levels and spatial dimensions.\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Dimension / Level size table for Sparse Grid Rule\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, ' Dim:  ' )
  for d = 1 : 10
    fprintf ( 1, '  %6d', d );
  end
  fprintf ( 1, '\n' );
  fprintf ( 1, 'Level:\n' );
  for k = 0 : 5
    fprintf ( 1, '  %2d:  ', k );
    for d = 1 : 10
      [ x, w ] = spquad ( d, k );
      n = length ( w );
      fprintf ( 1, '  %6d', n );
    end
    fprintf ( 1, '\n' );
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function bs = ISC(bs)
% Calculate brain-wide inter-subject correlations in patterns across parcel means
%
% :Usage:
% ::
%
%     bs = ISC(bs)
%
% For objects: Type methods(object_name) for a list of special commands
%              Type help object_name.method_name for help on specific
%              methods.
%
% ..
%     Author and copyright information:
%
%     Copyright (C)2020 Tor Wager
%
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/>.
% ..
%
% :Inputs:
%
%   **bs:**
%        A brainpathway_multisubject object
%
%
% :Optional Inputs:
%   **'nofactor':**
%        Omit factor analysis
%
%
% :Outputs:
%
%   **bs:**
%        A brainpathway_multisubject object
%        Output is added to relevant object properties:
%
%         bs.connectivity.regions.isc = intersubject correlation matrix;
%         bs.connectivity.regions.isc_subj_unusualness = 1/mean isc with others for each subject. 1/isc = [0 Inf] (bounded at zero);
%         bs.connectivity.regions.isc_outliers = subjects with isc_subj_unusualness > 2 SD above the mean
%         bs.connectivity.regions.isc_numfactors = estimated number of factors from elbow of PCA eigenvalues
%         bs.connectivity.regions.isc_Lambda = Subject factor loadings, can be correlated with other variables
%         bs.connectivity.regions.isc_Lambda_descrip = 'Lambdas are n_subjects x numfactors factor loadings, describing dimensions of subject similarity here';
%
%
% :Examples:
% ::
%
%    % None yet - example from HCP data
%
% :References:
%
% :See also:
%   - methods(brainpathway_multisubject)
%

% ..
%    Programmers' notes:
%    12/2020 Created by Tor Wager
% ..

fprintf('Flattening conn matrices. ')
mat = bs.flatten_conn_matrices('replacenans');

% Find NaNs and replace with subject mean (so regions will have min=zero influence on isc)
% Done now in flatten_conn_matrices
% fprintf('Imputing missing values. ')
%
% whnan = isnan(mat);
% subjmean = nanmean(mat');
%
% for i = 1:size(mat, 1)
% 	mat(i, whnan(i, :)) = subjmean(i);
% end

fprintf('Calculating ISC. ')
isc = corrcoef(double(mat'));

create_figure('region isc');
imagesc(isc); colorbar
drawnow

%whnan = all(isnan(isc), 1);
% anynans = sum(any(whnan, 2));

% Subject unusualness (potential outliers)
% --------------------------
meanisc = mean(isc) - (1./size(isc, 1)); % subtract the 1 on the diagonal
isc_subj_unusualness = 1 ./ meanisc;

isc_outliers = isc_subj_unusualness > (mean(isc_subj_unusualness) + 2 * std(isc_subj_unusualness));

figure; plot( 1 ./ meanisc, 'bo', 'MarkerFaceColor', [.3 .3 1]);

% Factor analysis
% --------------------------
fprintf('Factor analysis ')

% Choose # dimensions: where acceleration is greatest, i.e., derivative of
% eigenvalues changes fastest and the curve flattens at the "elbow"
[eigvec, eigval] = pcacov(isc);
gg = gradient(gradient(eigval));
[~, isc_numfactors] = max(gg);

fprintf('(%d) factors. ', isc_numfactors)

Lambda = factoran(isc, isc_numfactors, 'Xtype', 'cov');

if isc_numfactors > 1

    create_figure('region isc');
    scatterhist(Lambda(:, 1), Lambda(:, 2));
    xlabel('Factor 1')
    ylabel('Factor 2')

end

fprintf('\n');
disp('Added results to bs.connectivity.regions.isc');

bs.connectivity.regions.isc = isc;
bs.connectivity.regions.isc_subj_unusualness = isc_subj_unusualness;
bs.connectivity.regions.isc_outliers = isc_outliers;
bs.connectivity.regions.isc_numfactors = isc_numfactors;
bs.connectivity.regions.isc_Lambda = Lambda;
bs.connectivity.regions.isc_Lambda_descrip = 'Lambdas are n_subjects x numfactors factor loadings, describing dimensions of subject similarity here';

% bs.connectivity.regions.isc = intersubject correlation matrix;
% bs.connectivity.regions.isc_subj_unusualness = 1/mean isc with others for each subject. 1/isc = [0 Inf] (bounded at zero);
% bs.connectivity.regions.isc_outliers = subjects with isc_subj_unusualness > 2 SD above the mean
% bs.connectivity.regions.isc_numfactors = estimated number of factors from elbow of PCA eigenvalues
% bs.connectivity.regions.isc_Lambda = Subject factor loadings, can be correlated with other variables
% bs.connectivity.regions.isc_Lambda_descrip = 'Lambdas are n_subjects x numfactors factor loadings, describing dimensions of subject similarity here';

end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function [pc,Pf,Pb] = rc2pcv(rc,R0)

%function [pc,Pf,Pb] = rc2pcv(rc,R0)
% Transforms forward reflection coefficients rcb into
% normalized correlation matrices pc.

%S. de Waele, March 2003.

s = kingsize(rc);
order = s(3)-1;
dim = s(1); I = eye(dim);
%if nargin == 1, R0 = I; end

pc = zeros(s);  pc(:,:,1)  = I;

Pf   = zeros(s); Pf(:,:,1)   = R0;
Pb   = zeros(s); Pb(:,:,1)  = R0;

for p = 1:order,
   TsqrtPf = Tsqrt(Pf(:,:,p)); %square root M defined by: M=Tsqrt(M)*Tsqrt(M)'
   TsqrtPb= Tsqrt(Pb(:,:,p));
   %partial correlation
   pc(:,:,p+1) = -inv(TsqrtPf)*rc(:,:,p+1)*TsqrtPb;
   %residual matrices
   Pf(:,:,p+1)  = (I-TsqrtPf *pc(:,:,p+1) *pc(:,:,p+1)'*inv(TsqrtPf ))*Pf(:,:,p);
   Pb(:,:,p+1) = (I-TsqrtPb*pc(:,:,p+1)'*pc(:,:,p+1) *inv(TsqrtPb))*Pb(:,:,p);
end %for p = 2:order,


text:
%% Run the statistics for a version of the VEP
saveFile = 'dataStatistics.mat';

%% Setup the directories and titles
setupDir(1) = struct('inDir', [], 'outDir', [], 'title', [], 'fieldPath', []);
setupDir(1).inDir = 'N:\ARLAnalysis\VEP\VEPRobust_1Hz_Post_Median_Unfiltered';
setupDir(1).outDir = 'N:\ARLAnalysis\VEP\VEPRobust_1Hz_Post_Median_Unfiltered_Report';
setupDir(1).title = 'VEP robust 1Hz';
setupDir(1).fieldPath = {'etc', 'noiseDetection', 'reference', 'noisyStatistics'};
%% Get the directory list
for k = 1:length(setupDir)
    inList = dir(setupDir(k).inDir);
    inNames = {inList(:).name};
    inTypes = [inList(:).isdir];
    inNames = inNames(~inTypes);

    %% Take only the .set files
    validNames = true(size(inNames));
    for j = 1:length(inNames)
        ext = inNames{j}((end-3):end);
        if ~strcmpi(ext, '.set')
            validNames(j) = false;
        else
            inNames{j} = [setupDir(k).inDir filesep inNames{j}];
        end
    end
    %% Consolidate the results in a single structure for comparative analysis
    collectionStats = createCollectionStatistics(setupDir(k).title, ...
                                          inNames, setupDir(k).fieldPath);
    %% Save the statistics in the specified file
    save([setupDir(k).outDir filesep saveFile], 'collectionStats', '-v7.3');

    %% Display the reference statistics
    showNoisyStatistics(collectionStats);
end

author: VisLab

repo: EEG-Clean-Tools


text:
function [collect] = ft_channelcombination(channelcmb, datachannel, includeauto, dirflag)

% FT_CHANNELCOMBINATION creates a cell-array with combinations of EEG/MEG channels
% for subsequent cross-spectral-density, coherence and/or connectivity ananalysis
%
% You should specify channel combinations as a two-column cell-array,
%   cfg.channelcmb = {  'EMG' 'MLF31'
%                       'EMG' 'MLF32'
%                       'EMG' 'MLF33' };
% to compare EMG with these three sensors, or
%   cfg.channelcmb = { 'MEG' 'MEG' };
% to make all MEG combinations, or
%   cfg.channelcmb = { 'EMG' 'MEG' };
% to make all combinations between the EMG and all MEG channels.
%
% For each column, you can specify a mixture of real channel labels
% and of special strings that will be replaced by the corresponding
% channel labels. Channels that are not present in the raw datafile
% are automatically removed from the channel list.
%
% When directional connectivity measures will subsequently be computed, the
% interpretation of each channel-combination is that the direction of the
% interaction is from the first column to the second column.
%
% Note that the default behavior is to exclude symmetric pairs and
% auto-combinations.
%
% See also FT_CHANNELSELECTION

% Undocumented options:
%   includeauto = 0 (or 1), include auto-combinations
%   dirflag     = 0 (or 1, or 2) specifies the treatment of the order in
%                   the columns of the output. If dirflag = 0, the order is
%                   preserved, if dirflag = 1, the order is reversed,
%                   second input column is put first. If dirflag = 2, both
%                   directions are added to the list of combinations.

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

if nargin<3 || isempty(includeauto), includeauto = 0; end
if nargin<4 || isempty(dirflag),     dirflag     = 0; end

% ensure that datachannel is a column vector
datachannel = datachannel(:);

if ischar(channelcmb) && strcmp(channelcmb, 'all')
  % make all possible combinations of all channels
  channelcmb = {'all' 'all'};
end

% it should have a selection of two channels or channelgroups in each row
if size(channelcmb,1)==2 && size(channelcmb,2)~=2
  ft_warning('transposing channelcombination matrix');
  channelcmb = channelcmb';
end

if ~(numel(channelcmb)==2 && iscell(channelcmb{1}) && iscell(channelcmb{2})) &&...
    isempty(setdiff(channelcmb(:), datachannel))
  % there is not much to do, since there are no channelgroups with special names
  % each element of the input therefore already contains a proper channel name

  switch dirflag
    case 0
      % nothing to do
    case 1
      % switch the order
      channelcmb = channelcmb(:,[2 1]);
    case 2
      channelcmb = [channelcmb; channelcmb(:,[2 1])];
    otherwise
      ft_error('unknown value for input argument ''dirflag''');
  end
  collect = channelcmb;

  if includeauto
    autochannel = unique(channelcmb(:));
    for ch=1:numel(autochannel)
      collect = cat(1, collect, [autochannel(ch) autochannel(ch)]);
    end
  end

else
  % a combination is made for each row of the input selection after
  % translating the channel group (such as 'all') to the proper channel names
  % and within each set, double occurences and autocombinations are removed

  selmat = false(numel(datachannel));
  for sel=1:size(channelcmb,1)
    % translate both columns and subsequently make all combinations
    if iscell(channelcmb(sel,1)) && iscell(channelcmb(sel,2))
    % - channelcmb is a 1x2 cell-array containing cells
      channelcmb1 = ft_channelselection(channelcmb{sel,1}, datachannel);
      channelcmb2 = ft_channelselection(channelcmb{sel,2}, datachannel);
    else
    % - channelgroups with special names
      channelcmb1 = ft_channelselection(channelcmb(sel,1), datachannel);
      channelcmb2 = ft_channelselection(channelcmb(sel,2), datachannel);
    end
    % translate both columns and subsequently make all combinations
    list1 = match_str(datachannel, channelcmb1);
    list2 = match_str(datachannel, channelcmb2);

    selmat(list1,list2) = true;
    if dirflag==2
      % also fill the other 'direction'
      selmat(list2,list1) = true;
    end

    if ~includeauto
      % exclude the auto-combinations
      selmat = selmat & ~eye(size(selmat));
    else
      % ensure that the appropriate diagonal entries are filled
      autovec = false(numel(datachannel),1);
      autovec([list1(:);list2(:)]) = true;
      selmat = selmat | diag(autovec);
    end

  end

  if dirflag<2
    % remove double occurrences
    selmat   = selmat & ~tril(selmat, -1)';
  end
  [i1, i2] = find(selmat);

  switch dirflag
    case 0
      % original behavior,
      % row-to-column, i.e. outflow according to FT's convention
      indx = [i1 i2];
    case 1
      % column-to-row, i.e. inflow according to FT's convention
      indx = [i2 i1];
    case 2
      % both
      indx = [i1 i2];

    otherwise
      ft_error('unknown value for input argument ''dirflag''');
  end

  if isempty(indx)
    collect = cell(0,2);
  else
    collect = [datachannel(indx(:,1)) datachannel(indx(:,2))];
  end
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function plot_noisy_missing( dataname )

load( ['..\..\',dataname] );

end

author: andrewssobral

repo: lrslibrary


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

function s = python_copy_vars_from(out, tryexcept)
%private function

  if (nargin == 1)
    tryexcept = true;
  end

  if (~tryexcept)
    %% no error checking
    s = { sprintf('octoutput_drv(%s)', out) };
  else
    %% with try-except block
    s = { 'try:' ...
          sprintf('    octoutput_drv(%s)', out) ...
          'except:' ...
          '    echo_exception_stdout("while copying variables from Python")' ...
          '    raise'
        };
  end

repo: octsympy


text:
function [ xdp, ddp ] = dif_basis_derivk ( nd, xd, k )

%*****************************************************************************80
%
%% DIF_BASIS_DERIVK: Lagrange basis K-th derivative difference tables.
%
%  Discussion:
%
%    Given ND points XD, a Lagrange basis polynomial L(J)(X) is associated
%    with each point XD(J).
%
%    This function computes a table DDP(*,*) whose J-th column contains
%    the difference table for the K-th derivative of L(J)(X).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 June 2013
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Carl deBoor,
%    A Practical Guide to Splines,
%    Springer, 2001,
%    ISBN: 0387953663,
%    LC: QA1.A647.v27.
%
%  Parameters:
%
%    Input, integer ND, the number of data points.
%
%    Input, real XD(ND), the X values upon which the
%    Lagrange basis polynomials are to be based.
%
%    Input, integer K, the index of the derivative.
%
%    Output, real XDP(ND-K), the X values upon with
%    the derivative difference table is based.  In fact, these are
%    all 0.
%
%    Output, real DDP(ND-K,ND), the divided difference
%    tables for all the Lagrange basis polynomials.  Column J of DDP
%    contains the table for basis polynomial associated with XD(J).
%
  ddp = zeros ( nd - k, nd );
%
%  Process the vectors one column at a time.
%
  for j = 1 : nd
%
%  Set the data.
%
    yd(1:nd,1) = 0.0;
    yd(j,1) = 1.0;
%
%  Compute the divided difference table.
%
    dd = data_to_dif ( nd, xd, yd );
%
%  Compute the divided difference table for the derivative.
%
    [ xdp, ddp(1:nd-k,j) ] = dif_derivk_table ( nd, xd, dd, k );

  end

  return
end


text:
function P = pos(A)

P = A .* double( A > 0 );


text:
function [dat,beta,x] = ft_preproc_detrend(dat, begsample, endsample)

% FT_PREPROC_DETREND removes mean and linear trend from the
% data using using a General Linear Modeling approach.
%
% Use as
%   [dat] = ft_preproc_detrend(dat, begin, end)
% where
%   dat        = data matrix (Nchans X Ntime)
%   begsample  = index of the begin sample for the trend estimate
%   endsample  = index of the end sample for the trend estimate
%
% If no begin and end sample are specified for the trend estimate, it
% will be estimated on the complete data.
%
% See also FT_PREPROC_BASELINECORRECT, FT_PREPROC_POLYREMOVAL

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

% take the whole segment if begsample and endsample are not specified
if nargin<2 || isempty(begsample)
  begsample = 1;
end
if nargin<3|| isempty(endsample)
  endsample = size(dat,2);
end

[dat,beta,x] = ft_preproc_polyremoval(dat, 1, begsample, endsample);


text:
function vs = sphere01_triangle_vertices_to_centroid ( v1, v2, v3 )

%*****************************************************************************80
%
%% SPHERE01_TRIANGLE_VERTICES_TO_CENTROID gets a spherical triangle centroid.
%
%  Discussion:
%
%    A unit sphere centered at 0 in 3D satisfies the equation:
%
%      X*X + Y*Y + Z*Z = 1
%
%    A spherical triangle is specified by three points on the sphere.
%
%    The (true) centroid of a spherical triangle is the point
%
%      VT = (XT,YT,ZT) = Integral ( X, Y, Z ) dArea / Integral 1 dArea
%
%    Note that the true centroid does NOT, in general, lie on the sphere.
%
%    The "flat" centroid VF is the centroid of the planar triangle defined by
%    the vertices of the spherical triangle.
%
%    The "spherical" centroid VS of a spherical triangle is computed by
%    the intersection of the geodesic bisectors of the triangle angles.
%    The spherical centroid lies on the sphere.
%
%    VF, VT and VS lie on a line through the center of the sphere.  We can
%    easily calculate VF by averaging the vertices, and from this determine
%    VS by normalizing.
%
%    Of course, we still will not have actually computed VT, which lies
%    somewhere between VF and VS!
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 September 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real V1(3), V2(3), V3(3), the vertices of the triangle.
%
%    Output, real VS(3), the coordinates of the "spherical
%    centroid" of the spherical triangle.
%
  vs(1:3) = ( v1(1:3) + v2(1:3) + v3(1:3) ) / 3.0;

  norm = sqrt ( sum ( vs(1:3).^2 ) );

  vs(1:3) = vs(1:3) / norm;

  return
end


text:
function [f,p] = spm_DEM_basis(x,v,P)
% evaluates a parameterized set of basis functions
% problem
% FORMAT [f,p] = spm_DEM_basis(x,v,P)
%
% x   - hidden states
% v   - causal inputs
% P   - parameters
%
% f   - f(x)
% p   - p(i)
%
% returns:
%   f = sum(P(i)*B(x,i))
%   P = p/sum(p)
%
% where B(x,i) are basis functions
%
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_DEM_basis.m 3140 2009-05-21 18:38:17Z karl $

% basis set
%--------------------------------------------------------------------------
try, basis; catch, basis = 'radial'; end

% evaluate basis functions
%==========================================================================
switch basis

    case{'radial'}

        % Gaussian basis functions
        %------------------------------------------------------------------
        X = linspace(-2,2,length(P));
        W = 4*log(2)/(X(2) - X(1))^2;
        for i = 1:length(P)
            p(:,i) = exp(-W*(x - X(i)).^2);
        end
        f = (p*P(:))./sum(p,2);

    case{'spline'}

        % Natural spline
        %------------------------------------------------------------------
        X = linspace(-2,2,length(P));
        f = spline(X,P,x);

    case{'poly'}

        % Polynomial basis set
        %------------------------------------------------------------------
        f     = 0;
        for i = 1:length(P.p)
            B = x.^(i - 1);
            f = f + P.p(i)*B;
        end

    case{'dct'}

        % Discrete cosine basis set
        %------------------------------------------------------------------
        f     = 0;
        for i = 1:length(P.p)
            B = cos(i*pi*x/2);
            f = f + P.p(i)*B;
        end
end

f = spm_vec(f);

author: spm


text:
function mesh = genIntfMesh3D(mesh,intf)

%% USAGE: enrich mesh information for interface problem.
% INPUTS:
% mesh --- nt-by-3 matrix contains p and t information
% intf --- interface function in analytical form
%               g(x,y,z) = 0
%
% OUTPUTS:
% pLoc --- mesh node indices.  possible values:
%               pLoc(i) =-1 if g(xi,yi,zi) < 0
%               pLoc(i) = 0 if g(xi,yi,zi) = 0 (on interface)
%               pLoc(i) = 1 if g(xi,yi,zi) > 0
% tLoc --- mesh element indices.  possible values:
%               tLoc(i) = 1 if the element Ti is in region 1 (g(X) < 0)
%               tLoc(i) = 2 if the element Ti is in region 2 (g(X) > 0)
%               tLoc(i) = -ki if Ti is the ki-th interface element
% intType --- interface element type.  possible values:
%             0 for noninterface element,
%             1 for Type 1: one vertex on one side, three vertices on the other
%             2 for Type 2: two vertice on each side of interface)
% eLoc --- mesh edge indices.  possible values:
%               eLoc(i) = 1 if the element Ti is in region 1 (g(X) < 0)
%               eLoc(i) = 2 if the element Ti is in region 2 (g(X) > 0)
%               eLoc(i) = -ki if Ti is the ki-th interface element
% eIntP --- neI-by-3 vector, stores the coordinate of interface
%                    intersection points on each edge.
%
% Last updated by Xu Zhang on 07/09/20

%% 1. generate pLoc
%% basic assumption:
p = mesh.p; t = mesh.t; e = mesh.e; f = mesh.f;
nt = length(t); ne = length(e); nf = length(f);
pLoc = sign(feval(intf,p(:,1),p(:,2),p(:,3))); pLoc(pLoc == 0) = 1;

%% 2. generate tLoc and intType
id1 = sign(feval(intf,p(t(:,1),1),p(t(:,1),2),p(t(:,1),3)));
id2 = sign(feval(intf,p(t(:,2),1),p(t(:,2),2),p(t(:,2),3)));
id3 = sign(feval(intf,p(t(:,3),1),p(t(:,3),2),p(t(:,3),3)));
id4 = sign(feval(intf,p(t(:,4),1),p(t(:,4),2),p(t(:,4),3)));
id = id1+id2+id3+id4;
idm = id1.*id2.*id3.*id4;
tLoc = zeros(nt,1); intType = zeros(nt,1);
r1 = find(id == -4); tLoc(r1) = 1; intType(r1) = 0;
r2 = find(id == 4);  tLoc(r2) = 2; intType(r2) = 0;
r6 = (id == -1); tLoc(r6) = 1; intType(r6) = 0; % one pt is - and others are zero
r7 = (id == 1); tLoc(r7) = 2;  intType(r7) = 0; % one pt is + and others are zero
r8 = (id == -2 & idm == 0); tLoc(r8) = 1; intType(r8) = 0; % two pts are - and others are zero
r9 = (id == 2 & idm == 0);  tLoc(r9) = 2; intType(r8) = 0; % two pts are + and others are zero
r10 = (id == -3 & idm == 0); tLoc(r10) = 1; intType(r10) = 0; % three pts are - and the other s zero
r11 = (id == 3 & idm == 0);  tLoc(r11) = 2; intType(r11) = 0; % three pts are + and the other s zero
r3 = (id == -2 & idm ~= 0); intType(r3) = 1;
r4 = (id == 2 & idm ~= 0);  intType(r4) = 1;
r5 = (id == 0); intType(r5) = 2;
nt1 = length(r1) + sum(r6) + sum(r8) + sum(r10);
nt2 = length(r2) + sum(r7) + sum(r9) + sum(r11);
ntI = nt-nt1-nt2;
tLoc(tLoc == 0) = -(1:ntI);

%% 3. generate eLoc
eLoc = zeros(ne,1);
ide1 = sign(feval(intf,p(e(:,1),1),p(e(:,1),2),p(e(:,1),3))); ide1(ide1 == 0) = 1;
ide2 = sign(feval(intf,p(e(:,2),1),p(e(:,2),2),p(e(:,2),3))); ide2(ide2 == 0) = 1;
ide = ide1+ide2;
re1 = find(ide == -2); eLoc(re1) = 1;
re2 = find(ide == 2);  eLoc(re2) = 2;
ne1 = length(re1); ne2 = length(re2); neI = ne-ne1-ne2;
eLoc(eLoc == 0) = -(1:neI);

%% 4. generate eIntP
p1 = p(e(eLoc<0,1),:);
p2 = p(e(eLoc<0,2),:);
eIntP = IntersectPoint3D(p1, p2, intf);

%% 5. generate fLoc
fLoc = zeros(nf,1);
fID = sum(pLoc(mesh.f),2);
rf1 = find(fID == -3); fLoc(rf1) = 1;
rf2 = find(fID == 3);  fLoc(rf2) = 2;
nf1 = length(rf1); nf2 = length(rf2); nfI = nf-nf1-nf2;
fLoc(fLoc == 0) = -(1:nfI);

%% Form Mesh
mesh.pLoc = pLoc;
mesh.eLoc = eLoc;
mesh.tLoc = tLoc;
mesh.fLoc = fLoc;
mesh.eIntP = eIntP;
mesh.intType = intType;

repo: ifem


text:
function score = DM(Population,optimum)
% <max> <multi/many> <real/integer/label/binary/permutation> <large/none> <constrained/none> <expensive/none> <multimodal/none> <sparse/none> <dynamic/none>
% Metric for diversity

%------------------------------- Reference --------------------------------
% K. Deb and S. Jain, Running performance metrics for evolutionary
% multi-objective optimization, KanGAL Report 2002004, 2002.
%------------------------------- 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".
%--------------------------------------------------------------------------

    PopObj = Population.best.objs;
    if size(PopObj,2) ~= size(optimum,2)
        score = nan;
    else
        fmax  = max(optimum,[],1);
        fmin  = min(optimum,[],1);
        H     = calGrid(optimum(:,1:end-1),fmax(1:end-1),fmin(1:end-1),size(PopObj,1));
        h     = H & calGrid(PopObj(:,1:end-1),fmax(1:end-1),fmin(1:end-1),size(PopObj,1));
        score = calM(h,H)./calM(H,H);
    end
end

function h = calGrid(P,fmax,fmin,div)
% Determine whether each grid has at least one point

    [N,M] = size(P);
    d     = (fmax-fmin)./div;
    GLoc  = ceil((P-repmat(fmin,N,1))./repmat(d,N,1));
    GLoc  = max(1,GLoc);
    h     = zeros(M,div);
    for i = 1 : M
        h(i,:) = ismember(1:div,GLoc(:,i));
    end
end

function m = calM(h,H)
% Calculate the value function m()

    M = size(h,1);
    h = [ones(M,1),h,ones(M,1)];
    H = [ones(M,1),H,ones(M,1)];
    m = 0;
    for i = 1 : M
        for j = 2 : size(h,2)-1
            if H(i,j)
                if h(i,j)
                    if h(i,j-1)
                        if h(i,j+1)
                            m = m + 1;
                        else
                            m = m + 0.67;
                        end
                    else
                        if h(i,j+1)
                            m = m + 0.67;
                        else
                            m = m + 0.75;
                        end
                    end
                else
                    if h(i,j-1)
                        if h(i,j+1)
                            m = m + 0.75;
                        else
                            m = m + 0.5;
                        end
                    else
                        if h(i,j+1)
                            m = m + 0.5;
                        else
                            m = m + 0;
                        end
                    end
                end
            end
        end
    end
end

author: BIMK

repo: PlatEMO


text:
function huffman_test1
% HUFFMAN_TEST1
% This is a simple test to have a code profile of the functions

%   $Author: Giuseppe Ridino' $
%   $Revision: 1.0 $  $Date: 02-Jul-2004 16:47:25 $

profile clear
profile on -history

tic

data = uint8(256*sin(1:100000));
[zipped,info] = norm2huff(data);
unzipped = huff2norm(zipped,info);

toc

unzipped = uint8(unzipped);
ok = isequal(data,unzipped)

profile off
profile report

author: Sable

repo: mcbench-benchmarks


text:
function element_num = sphere_grid_q4_element_num ( nelemx, nelemy )

%*****************************************************************************80
%
%% SPHERE_GRID_Q4_ELEMENT_NUM counts the elements in a Q4 sphere grid.
%
%  Example:
%
%    Input:
%
%      NELEMX = 3, NELEMY = 2
%
%    Output:
%
%      ELEMENT_NUM = NELEMX * NELEMY = 6
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 September 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NELEMX, NELEMY, the number of elements along the
%    X and Y directions.
%
%    Output, integer ELEMENT_NUM, the number of elements in the grid.
%
  element_num = nelemx * nelemy;

  return
end


text:
function getdata (option)
global A opt leg label

[fname,pname] = uigetfile({'*.csv';'*.xls';'*.txt'},'Select File');
dbfile= strcat(pname,fname);
if length(dbfile) == 0 return; end

% Check if the file IS there
d= dir(fname);
if isempty(d.name)
	errordlg ('Sorry, don''t find that file','Error');
	return;
end

% Open the file
fdata= fopen(fname,'rt');
A= [];
leg= {};

% Put a comma before first column. This is required to use tblread, get
% propper reading of column names but avoid that the user has to
% include it
fileout= fopen('Qdata.csv','wt');
while 1
	s = fgets(fdata);
	if ~ischar(s), break, end
	fprintf(fileout,'%s%s',',',s);
end
fclose(fdata);
fname= 'Qdata.csv';

% Read it
switch option
	case 1
		[A,leg]= tblread(fname,'comma');
	case 2
		[A,leg]= xlsread(dbfile);
	case 3
		[A,leg]= xlsread(dbfile,-1)
end

%Generate cell string array fot title if there aren't any
if isempty(leg) leg= cellstr( num2str( flipud(rot90([1:size(A,2)])) ) ); end

% Choosing default x-y-z columns
opt.xc= 1;
switch size(A,2)
	case 1
		opt.yc= 1;
		opt.ec= 1;
		opt.zc= 1;
	case 2
		opt.yc= 2;
		opt.ec= 2;
		opt.zc= 2;
	otherwise
		opt.yc= [2:size(A,2)-1];
		opt.ec= [fix(size(A,2)/2):size(A,2)];
		opt.zc= [3:size(A,2)];
end

return


text:
function [net1] = vl_simplenn_mergebnorm(net)

%% merge bnorm parameters into adjacent Conv layer

for i = 1:numel(net.layers)
    if strcmp(net.layers{i}.type, 'conv')
        net.layers{i}.weightDecay(2) = 1;
    end
end

for i = 1:numel(net.layers)
    if strcmp(net.layers{i}.type, 'bnorm')
        ws = net.layers{i}.weights{1};
        bs = net.layers{i}.weights{2};
        mu_sigmas = net.layers{i}.weights{3};
        for j = 1:numel(ws)
            net.layers{i-1}.weights{1}(:,:,:,j) =single(double(net.layers{i-1}.weights{1}(:,:,:,j))*double(ws(j))/(double(mu_sigmas(j,2))));
            net.layers{i-1}.weights{2}(j) =single(double(bs(j)) - double(ws(j))*double(mu_sigmas(j,1))/(double(mu_sigmas(j,2))));
        end
        net.layers{i-1}.learningRate(2) = 1;
    end
end

net1 = net;
net1.layers = {};
net1 = rmfield(net1,'meta');
for i = 1:numel(net.layers)
    if ~strcmp(net.layers{i}.type, 'bnorm')
        net1.layers{end+1} = net.layers{i};
    end
end

net1.layers = net1.layers(1:end-1);

end

author: cszn

repo: DnCNN

save_path: github-repos/MATLAB/cszn-DnCNN