text:
function [xopt,fval,exitflag,output] = spcompsearch(z, xbox, options)
% SPCOMPSEARCH  Modified compass (coordinate) search algorithm
%    performing a local search of the sparse grid inpterpolant.
%    X = SPCOMPSEARCH(Z)  Finds a local optimizer X for the given
%    sparse grid interpolant Z using a modified compass search
%    algorithm starting from the best available sparse grid point.
%    The entire range of the sparse grid interplant is searched.
%
%    X = SPCOMPSEARCH(Z, XBOX) Uses the search box XBOX, X = [a1,
%    b1; a2, b2; ...]. The size of search box XBOX must be smaller
%    than or equal to the range of the interpolant.
%
%    X = SPCOMPSEARCH(Z, XBOX, OPTIONS)  Additionally, an OPTIONS
%    structure can be provided, see SPOPTIMSET for further details.
%
%    [X,FVAL] = SPCOMPSEARCH(...)  returns the value of the
%    sparse grid interpolant at X.
%
%    [X,FVAL,EXITFLAG] = SPCOMPSEARCH(...)  returns an EXITFLAG
%    that describes the exit condition of SPCOMPSEARCH. Possible
%    values of EXITFLAG and the corresponding exit conditions are
%
%     1  SPCOMPSEARCH converged to a solution X.
%     0  Maximum number of iterations reached.
%
%    [X,FVAL,EXITFLAG,OUTPUT] = SPCOMPSEARCH(...) returns a
%    structure OUTPUT with the number of function evaluations in
%    OUTPUT.nFevals and the computing time in .time.
%
%    Example: (minimizing the three-hump camel-back function)
%       f = inline('12*x.^2-6.3*x.^4+x.^6+6*y*(y-x)');
%       range = [-3 3; -3 3];
%       options = spset('keepFunctionValues','on');
%       z = spvals(f, 2, range, options);
%       [xopt, fval] = spcompsearch(z)
%
%    See also SPOPTIMSET.

% Author : Andreas Klimke
% Version: 2.1
% Date   : September 1, 2007

% Change log:
% V2.1 : September 1, 2007
%        Changed calling syntax to match other optimization
%        methods. Added maximum number of iterations.
% V2.0 : January 23, 2006
%        Added TolFun break criterium.
% V1.9 : June 9, 2005
%        Removed multiple start processing from V1.5; moved to
%        separate routine SPMULTISTART. Removed start point
%        computation; moved to separate routine.
% V1.8 : April 15, 2005
%        Corrected bug concerning testCorners option; Modified
%        slightly to cope with new dimension-adaptive format.
% V1.7 : January 14, 2005
%        Corrected bug that lead to wrong rescaling of parts of the
%        grid data if previous results were used.
% V1.6 : January 11, 2005
%        Added capability for handling polynomial sparse grid
%        interpolants. Added tolerance on X as options.
% V1.5 : November 13, 2004
%        Added feature for performing multiple searches at a time.
% V1.4 : September 6, 2004
%        Added capability for handling dimension-adaptive data.
% V1.3 : September 6, 2004
%      : Added check if the spvals structure contains a valid
%        range; otherwise, set it to [0,1]^d.
% V1.2 : March 9, 2004
%        Added random start point option
% V1.1 : February 18, 2004
%        Moved search for optimum of sparse grid points to separate
%        routine (spfindopt.m).
% V1.0 : January 7, 2004
%        Initial version

% ------------------------------------------------------------
% Sparse Grid Interpolation Toolbox
% Copyright (c) 2006 W. Andreas Klimke, Universitaet Stuttgart
% Copyright (c) 2007-2008 W. A. Klimke. All Rights Reserved.
% See LICENSE.txt for license.
% email: klimkeas@ians.uni-stuttgart.de
% web  : http://www.ians.uni-stuttgart.de/spinterp
% ------------------------------------------------------------

t0 = clock;

if nargin < 2, xbox = []; end
if nargin < 3, options = []; end

d = z.d;

% In case that no range has been provided to spvals -> set it to
% [0,1]^d.
if isempty(z.range)
	z.range = [zeros(d,1) ones(d,1)];
end
if isempty(xbox)
	xbox = z.range;
end

if isfield(z, 'dimAdapt')
	n = z.maxLevel';
else
	n = z.maxLevel*ones(d,1,'uint8');
end

% savepoints = [];

% Determine optimization start point(s)
[xopt, fval] = spgetstartpoint(z, xbox, options);

minimize = spoptimget(options, 'Minimize', 'on');
maximize = spoptimget(options, 'Maximize', 'off');
if strcmpi(minimize, 'on'), isminimize = 1; else isminimize = 0; end
if strcmpi(maximize, 'on'), ismaximize = 1; else ismaximize = 0; end

ymin = []; ymax = [];
if isminimize
	ymin = fval(1);
	if ismaximize
		ymax = fval(2);
	end
else
	ymax = fval(1);
end

switch(lower(z.gridType))
 case {'maximum', 'noboundary', 'clenshaw-curtis'}
	linear = 1;
 case {'chebyshev', 'gauss-patterson'}
	linear = 0;
 otherwise
		error('MATLAB:spinterp:badopt',['Unknown grid type ''' gridtype '''.']);
end

maxiter = spoptimget(options, 'MaxIter', 100);

tolx = spoptimget(options, 'TolX', []);
if isempty(tolx)
	if linear
		tolx = inf;
	else
		tolx = max(z.estRelError * 1e-2, 10*eps);
	end
end

tolfun = spoptimget(options, 'TolFun', 1e-6);
dispopt = spoptimget(options, 'Display', 'off');

nfevals = 0;

x = zeros(2*d,d);

exitflag = zeros(size(xopt,2));

for k = 1:size(xopt,2)

	% Compute the step length parameters
	dx = 1./2.^(floor(double(n)/double(d))).*(z.range(:,2)-z.range(:,1));
	dxunit = 1./2.^(floor(double(n)/double(d)));
	dxmin = 1./2.^double(n);
	dxminvec = 1./2.^double(n).*(z.range(:,2)-z.range(:,1));

	% correct the start values to lie on a full grid point
	if linear
		updated = 0;
		for l = 1:d
			xtemp = floor((xopt(l,k) - z.range(l,1)) / ...
										dxminvec(l))*dxminvec(l) + z.range(l,1);
			while xtemp < xbox(l,1)
				xtemp = xtemp + dxminvec(l);
			end
			if xtemp > xbox(l,2)
				% this can only be true if the search box is smaller than the
				% step width dx. In this case, take the center of the search
				% box as the starting point.
				xtemp = (xbox(l,1) + xbox(l,2))/2;
			end
			if xtemp ~= xopt(l,k)
				xopt(l,k) = xtemp;
				updated = 1;
			end
		end
		if updated
			xoptcell = num2cell(xopt(:,k));
			nfevals = nfevals + 1;
      if k == 1 && isminimize
        ymin = spinterp(z, xoptcell{:});
      else
        ymax = spinterp(z, xoptcell{:});
      end
    end
	end

  [isdispiter, iterstr] = initoptidisp(dispopt);
  if isdispiter
	  if k == 1 && isminimize
		  disp(sprintf(iterstr, 0, nfevals, 0, ymin, 'start point'));
	  else
		  disp(sprintf(iterstr, 0, nfevals, 0, ymax, 'start point'));
		end
	end
	if k == 2
		isminimize = 0;
	end

	exitflag(k) = 0;
	for kit = 1:maxiter

		% save the points for later processing, if requested by the
    % user
		%if nargout == 3
		%	if isminimize
		%		savepoints = [savepoints; [xopt(:,k)' ymin]];
		%	else
		%		savepoints = [savepoints; [xopt(:,k)' ymax]];
		%	end
		%end

		nfevals = nfevals + uint32(d)*2;

		% Generate search points
		id = uint32(1);
		for l = 1:d
			for l2 = 1:d
				if l == l2
					x(id,l) = xopt(l,k) - dx(l);
					x(id+1,l) = xopt(l,k) + dx(l);
					if x(id,l) < xbox(l,1)
            x(id,l) = xbox(l,1);
          end
          if x(id+1,l) > xbox(l,2)
            x(id+1,l) = xbox(l,2);
          end
				else
					x(id,l2) = xopt(l2,k);
					x(id+1,l2) = xopt(l2,k);
				end
			end
			id = id + 2;
		end

		% Perform sparse grid interpolation
		xcell = num2cell(x,1);
		ytemp = spinterp(z, xcell{:});

		if isminimize
			[ymintemp, id] = min(ytemp);
			if ymintemp < ymin
				xopt(:,k) = x(id,:)';
      	if isdispiter, disp(sprintf(iterstr, kit, nfevals, ...
	                          0, ymintemp, 'coordinate step')); end
        % Terminate if function value change is below tolerance
        if abs(ymin-ymintemp) < tolfun
				  ymin = ymintemp;
					exitflag(k) = 1;
          break;
        end
        ymin = ymintemp;
			else
      	if isdispiter, disp(sprintf(iterstr, kit, nfevals, ...
	                          0, ymin, 'contract step')); end
				if all(dxunit <= dxmin) && all(dxunit <= tolx)
					exitflag(k) = 1;
					break;
				end
				for l = 1:d
					if dxunit(l) > dxmin(l) || dxunit(l) > tolx
						dxunit(l) = dxunit(l) / 2;
						dx(l) = dx(l) / 2;
					end
				end
			end
		else
			[ymaxtemp, id] = max(ytemp);
			if ymaxtemp > ymax
				xopt(:,k) = x(id,:)';
      	if isdispiter, disp(sprintf(iterstr, kit, nfevals, ...
	                          0, ymaxtemp, 'coordinate step')); end
        % Terminate if function value change is below tolerance
        if abs(ymax-ymaxtemp) < tolfun
				  ymax = ymaxtemp;
					exitflag(k) = 1;
          break;
        end
				ymax = ymaxtemp;
			else
      	if isdispiter, disp(sprintf(iterstr, kit, nfevals, ...
	                          0, ymax, 'contract step')); end
				if all(dxunit <= dxmin) && all(dxunit <= tolx)
					exitflag(k) = 1;
					break;
				end
				for l = 1:d
					if dxunit(l) > dxmin(l) || dxunit(l) > tolx
						dxunit = dxunit / 2;
						dx = dx / 2;
					end
				end
			end
		end
	end
end

fval = [ymin ymax];

if nargout == 4
	output.nFEvals = nfevals;
	output.time = etime(clock, t0);
	% output.points = savepoints;
end


text:
clear, clc;

% This is an example for running the function altra
%
%  Problem:
%
%  min  1/2 || x - v||^2 + z * sum_j w_j ||x_{G_j}||
%
%  G_j's are nodes with tree structure
%
%  The tree structured group information is contained in
%  opts.ind, which is a 3 x nodes matrix, where nodes denotes the number of
%  nodes of the tree.
%
%  opts.ind(1,:) contains the starting index
%  opts.ind(2,:) contains the ending index
%  opts.ind(3,:) contains the corresponding weight (w_j)
%
%  Note:
%  1) If each element of x is a leaf node of the tree and the weight for
%  this leaf node are the same, we provide an alternative "efficient" input
%  for this kind of node, by creating a "super node" with
%  opts.ind(1,1)=-1; opts.ind(2,1)=-1; and opts.ind(3,1)=the common weight.
%
%  2) If the features are well ordered in that, the features of the left
%  tree is always less than those of the right tree, opts.ind(1,:) and
%  opts.ind(2,:) contain the "real" starting and ending indices. That is to
%  say, x( opts.ind(1,j):opts.ind(2,j) ) denotes x_{G_j}. In this case,
%  the entries in opts.ind(1:2,:) are within 1 and n.
%
%
%  If the features are not well ordered, please use the input opts.G for
%  specifying the index so that
%   x( opts.G ( opts.ind(1,j):opts.ind(2,j) ) ) denotes x_{G_j}.
%  In this case, the entries of opts.G are within 1 and n, and the entries of
%  opts.ind(1:2,:) are within 1 and length(opts.G).
%
%% Related papers
%
% [1] Jun Liu and Jieping Ye, Moreau-Yosida Regularization for
%     Grouped Tree Structure Learning, NIPS 2010
%
%%

cd ..
cd ..

root=cd;
addpath(genpath([root '/SLEP']));
                     % add the functions in the folder SLEP to the path

% change to the original folder
cd Examples/tree;

n=10000;
v=randn(n,1);
ind=[ [-1, -1, 0.5]'; [1, 3000, 0.2]'; [3001, 6000, 0.2]'; [6001, 10000, 0.2]';...
    [1, 10000, 2]'];

nodes=size(ind,2);

tic;
x=altra(v, n, ind, nodes);
toc;

author: zzstefan

repo: BrainNetClass


text:
function p = predict(theta, X)
%PREDICT Predict whether the label is 0 or 1 using learned logistic
%regression parameters theta
%   p = PREDICT(theta, X) computes the predictions for X using a
%   threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)

m = size(X, 1); % Number of training examples

% You need to return the following variables correctly
p = zeros(m, 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned logistic regression parameters.
%               You should set p to a vector of 0's and 1's
%

p = sigmoid(X * theta)>=0.5 ;

% =========================================================================

end

author: Borye


text:
function model = multimodelExpandParam(model, params)

% MULTIMODELEXPANDPARAM Create model structure from MULTIMODEL model's parameters.
% FORMAT
% DESC returns a multi-task learning wrapper model structure filled with the
% parameters in the given vector. This is used as a helper function to
% enable parameters to be optimised in, for example, the NETLAB
% optimisation functions.
% ARG model : the model structure in which the parameters are to be
% placed.
% ARG param : vector of parameters which are to be placed in the
% model structure.
% RETURN model : model structure with the given parameters in the
% relevant locations.
%
% SEEALSO : multimodelCreate, multimodelExtractParam, modelExpandParam
%
% COPYRIGHT : Neil D. Lawrence, 2007, 2008
%
% MODIFICATIONS: Mauricio Alvarez, 2008, 2009

% MLTOOLS

if numel(model.outputDim) == 1
    endVal = model.numParams - model.numModels*model.numSep;
    baseParams = params(1:endVal);
    passParams(model.sharedIndices) = baseParams;
    if ~isempty(model.separateIndices)
        for i = 1:length(model.comp)
            startVal = endVal + 1;
            endVal = endVal + model.numSep;
            passParams(model.separateIndices) = params(startVal:endVal);
            model.comp{i} = modelExpandParam(model.comp{i}, passParams);
        end
    else
        for i = 1:length(model.comp)
            model.comp{i} = modelExpandParam(model.comp{i}, passParams);
        end
    end
else
    startVal = 1;
    endVal = 0;
    for i = 1:length(model.comp)
        endVal = endVal + model.comp{i}.nParams;
        model.comp{i} = modelExpandParam(model.comp{i}, params(startVal:endVal));
        startVal = endVal + 1;
    end
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function [NNpredBest, errors] = NNseq(Ytr, YtsOriginal, YtsMissing, windowSizes, startingPoint, replacePresent)

% NNSEQ Sequential NN
% COPYRIGHT: Andreas C. Damianou, 2012
% VARGPLVM

if nargin < 6 || isempty(replacePresent),   replacePresent = true;  end
if nargin < 5 || isempty(startingPoint),    startingPoint = 1;      end
if nargin < 4 || isempty(windowSizes),      windowSizes = 1:5;      end

errors=[];
indexMissing = find(isnan(YtsMissing(1,:)));
indexPresent = setdiff(1:size(YtsMissing,2), indexMissing);

fprintf('  Initialising')
indNN = [];
miniNN = [];
for i=1:size(YtsMissing,1)
    fprintf('.')
    % initialize the latent points using the nearest neighbour from the training data
    dst = dist2(YtsMissing(i,indexPresent), Ytr(:,indexPresent));
    [mind, mini(i)] = min(dst);
    [miniNN(i,:) indNN(i,:)] = sort(dst); %%% mini(i) == indNN(i,1);
end
fprintf('\n')

errInd = 1;
NNpredBest = [];
for ws=windowSizes % Default: 1:5 (ws 11 gives the best results)
    windowSize = ws;
    fprintf('# Testing for windowSize = %d...\n',ws)

    NNpred = Ytr(mini,:);
    NNpredDyn = [];
    mindNN = [];
    miniNN = [];
    dstNN = [];
    NNpredDyn(1,:) = NNpred(startingPoint,:);
    fprintf('  Predicting')
    % Predict for multiple candidates (as many as the window size) and
    % select the one which is more coherent with the up-to-now sequence.
    for i=2:size(YtsMissing,1)
        fprintf('.')
        candidate = [];
        for j=1:windowSize
            candidate(j,:) = Ytr(indNN(i,j),:);
            % If this is true, then the present dimensions will be replaced
            % by the given ones (as opposed to just returning the whole
            % training NN).
            if replacePresent
                candidate(j,indexPresent) = YtsMissing(i, indexPresent); %% OPTIONAL!!
            end
        end

        if i == 2 %%% OPTIONAL 2 !!!
            % Find the most coherent to the whole first training point (which we
            % know is smooth)
            dstNN = dist2(Ytr(indNN(i,1),:),candidate); %%% OPTIONAL 2 !!!
        else %%% OPTIONAL 2 !!!
            dstNN = dist2(NNpredDyn(i-1,:), candidate);
        end %%% OPTIONAL 2 !!!

        [mindNN, miniNN(i)] = min(dstNN);
        NNpredDyn(i,:) = candidate(miniNN(i),:);
    end
   fprintf('\n')
   errors(errInd)= ...
       sum(sum(abs(NNpredDyn(:,indexMissing) - YtsOriginal(:,indexMissing)) ))/prod(size(YtsOriginal(:,indexMissing)));

   if errors(errInd) == min(errors)
       NNpredBest = NNpredDyn;
   end
   errInd = errInd+1;
  % meanPose = repmat(mean(Ytr),size(YtsOriginal,1),1);

end

repo: vargplvm


text:
% MakeJAABAResultsMovie(expdir,classifierparamsfile,'nframesperseg',500,'nintervals',10,'aviname','JAABAResultsMovie_FCF_cantons_1500002_None_Rig1Plate15BowlA_20120519T160453.avi')

function MakeJAABAResultsMovie(expdir,classifierparamsfile,varargin)

%% parse parameters

frac_bottom = .1;
border_bottom = .05;
border_middle = .02;
trx_linewidth = 1;
target_linewidth = 2;
bar_width = .8;
trx_rad = 25;
pxborder = [];
aborder = 1;
trxcolor = [0,0,0];
figpos = [50,50,1500,1000];
barbackcolor = [.5,.5,.5];
textcolor = [0,0,0];
fontsize = 30;
aback = .25;
printnone = true;
mintrajlength = 100;
nintervals = 1;
compression = 'None';
behaviorname_dict = cell(0,2);
allowedcompressions = {'Indeo3', 'Indeo5', 'Cinepak', 'MSVC', 'RLE', 'None','Uncompressed AVI','Motion JPEG AVI'};
useVideoWriter = exist('VideoWriter','file');
aviname = '';
fps = 10;
usemencoder = true;
animaltype='fly';
headmarksize=10;
bottomtextfontsize=8;

[framestarts,nframesperseg,fracstarts,fracperseg,targets,hfig,...
  pxwidthradius,pxheightradius,awidthradius,aheightradius,frac_bottom,...
  trx_linewidth,target_linewidth,...
  behavior_colors,behavior_cm,...
  border_bottom,border_middle,bar_width,...
  trx_rad,score_norm_prctile,...
  pxborder,aborder,...
  trxcolor,...
  figpos,...
  barbackcolor,...
  behaviorweight,...
  textcolor,fontsize,...
  pxback,aback,...
  printnone,...
  mintrajlength,...
  nintervals,...
  useVideoWriter,...
  avifileTempDataFile,aviname,fps,...
  usemencoder,titlepagetext,...
  titlepausetime,...
  behaviorname_dict,...
  behaviororder,...
  textprefix,...
  textsuffix,...
  fixedaxis,...
  animaltype,...
  headmarksize,...
  bottomtextfontsize,...
  isstjaaba] = ...
  myparse(varargin,'framestarts',[],'nframesperseg',[],...
  'fracstarts',[],'fracperseg',1/60,...
  'targets',[],...
  'hfig',1,...
  'pxwidthradius',[],...
  'pxheightradius',[],...
  'awidthradius',3,...
  'aheightradius',3,...
  'frac_bottom',frac_bottom,...
  'trx_linewidth',trx_linewidth,...
  'target_linewidth',target_linewidth,...
  'behavior_colors',zeros(0,3),...
  'behavior_cm',@(x) jet(x)*.7,...
  'border_bottom',border_bottom,...
  'border_middle',border_middle,...
  'bar_width',bar_width,...
  'trx_rad',trx_rad,...
  'score_norm_prctile',80,...
  'pxborder',pxborder,...
  'aborder',aborder,...
  'trxcolor',trxcolor,...
  'figpos',figpos,...
  'barbackcolor',barbackcolor,...
  'behaviorweight',[],...
  'textcolor',textcolor,...
  'fontsize',fontsize,...
  'pxback',[],...
  'aback',aback,...
  'printnone',printnone,...
  'mintrajlength',mintrajlength,...
  'nintervals',nintervals,...
  'useVideoWriter',useVideoWriter,...
  'avifileTempDataFile','',...
  'aviname',aviname,...
  'fps',fps,...
  'usemencoder',usemencoder,...
  'titlepagetext',{},...
  'titlepausetime',2,...
  'behaviorname_dict',behaviorname_dict,...
  'behaviororder',{},...
  'textprefix','',...
  'textsuffix','',...
  'fixedaxis',[],...
  'animaltype',animaltype,...
  'headmarksize',headmarksize,...
  'bottomtextfontsize',bottomtextfontsize,...
  'isstjaaba',false);

classifierparams = ReadClassifierParamsFile(classifierparamsfile);
nbehaviors = numel(classifierparams);
behaviors = cell(1,nbehaviors);
scorefns = cell(1,nbehaviors);
labelfns = cell(1,nbehaviors);
for i = 1:nbehaviors,
  behaviors{i} = classifierparams(i).behaviors.names{1};
  j = find(strcmp(behaviors{i},behaviorname_dict(:,1)),1);
  if ~isempty(j),
    behaviors{i} = behaviorname_dict{j,2};
  else
    behaviors{i} = regexprep(behaviors{i},'(_|^)([a-z])','${upper($2)}');
  end
  scorefn = classifierparams(i).file.scorefilename;
  scorefns{i} = regexprep(scorefn,'\.mat$','');
  labelfns{i} = regexprep(scorefns{i},'score','label','preservecase','once');
end

if ~isempty(behaviororder),
  [ism,orderidx] = ismember(behaviors,behaviororder);
  orderidx(~ism) = inf;
  [~,orderidx] = sort(orderidx);
  behaviors = behaviors(orderidx);
  scorefns = scorefns(orderidx);
  labelfns = labelfns(orderidx);
  classifierparams = classifierparams(orderidx);
end

if ~ischar(compression),
  compression = '';
end
if ~ispc && ~useVideoWriter,
  compression = 'None';
end
if ~isempty(compression) && ~any(strcmpi(compression,allowedcompressions)),
  fprintf('Unknown compressor %s\n',compression);
  compression = '';
end

if isempty(aviname),
  [~,experiment_name] = fileparts(expdir);
  aviname = fullfile(expdir,sprintf('JAABAResultsMovie_%s.avi',experiment_name));
end

%% create trx structure

trx = Trx('trxfilestr',classifierparams(1).file.trxfilename,...
  'moviefilestr',classifierparams(1).file.moviefilename,...
  'perframedir',classifierparams(1).file.perframedir);
if isfield(classifierparams,'perframe') && isfield(classifierparams(1).perframe,'params'),
  trx.SetPerFrameParams(classifierparams(1).perframe.params);
end
if isfield(classifierparams,'perframe') && isfield(classifierparams(1).perframe,'landmark_params'),
  trx.SetLandmarkParams(classifierparams(1).perframe.landmark_params);
end

trx.AddExpDir(expdir,'openmovie',false);

%% for video reading

moviename = fullfile(expdir,trx.moviefilestr);
if exist(moviename)
  [readframe,~,fid,headerinfo] = get_readframe_fcn(moviename);
  im = readframe(1);
  [headerinfo.nr,headerinfo.nc,~] = size(im);
else

  maxx = 0; maxy = 0;
  for ndx = 1:trx.nflies
    maxx = max(max(trx(ndx).x+trx(ndx).a*2),maxx);
    maxy = max(max(trx(ndx).y+trx(ndx).a*2),maxy);
  end
  nr = ceil(maxy);
  nc = ceil(maxx);
  headerinfo.nr = nr;
  headerinfo.nc = nc;
  ncolors = 1;
  nframes = max([trx.endframe]);
  readframe = @(x)(uint8(256*ones(nr,nc)));
  fid = 0;

end

%% choose frames, target to show

% how many intervals
nintervals = max([nintervals,numel(targets),numel(nframesperseg),...
  numel(framestarts),numel(fracperseg),numel(fracstarts)]);

% choose frame starts evenly spaced throughout the movie
if isempty(framestarts) && isempty(fracstarts),
  framestarts = round(linspace(max(trx.firstframe),min(trx.endframe),nintervals));
end

if ~isempty(nframesperseg) && numel(nframesperseg) < nintervals,
  nframesperseg = [nframesperseg,nframesperseg(end)+zeros(1,nintervals-numel(nframesperseg))];
end

% make sizes match
if isempty(targets),
  for segi = 1:nintervals,
    if numel(nframesperseg) >= segi,
      mintrajlength_curr = max([mintrajlength,nframesperseg(segi)]);
      idx = trx.nframes>mintrajlength_curr;
      if numel(framestarts) >= segi,
        idx = idx & trx.firstframe<=framestarts(segi) & ...
          trx.endframe >= framestarts(segi);
      end
      idx = setdiff(find(idx),targets(1:segi-1));
      targets(segi) = randsample(idx,1);
    end
  end
elseif numel(targets) < nintervals,
  targets = [targets,targets(end)+zeros(1,nintervals-numel(targets))];
end
if numel(fracperseg) < nintervals,
  fracperseg = [fracperseg,fracperseg(end)+zeros(1,nintervals-numel(fracperseg))];
end
if numel(fracstarts) < nintervals && ~isempty(fracstarts),
  fracstarts = [fracstarts,fracstarts(end)+zeros(1,nintervals-numel(fracstarts))];
end

frameends = nan(1,nintervals);
for targeti = 1:nintervals,
  target = targets(targeti);
  firstframe = trx.firstframes(target);
  endframe = trx.endframes(target);
  nframes_curr = endframe - firstframe + 1;

  if numel(nframesperseg) < targeti || isnan(nframesperseg(targeti)),
    nframesperseg(targeti) = round(nframes_curr*fracperseg(targeti));
  end
  if numel(framestarts) < targeti || isnan(framestarts(targeti)),
    framestarts(targeti) = firstframe + round(fracstarts(targeti)*nframes_curr);
  end
  frameends(targeti) = max(firstframe,min(endframe,framestarts(targeti)+nframesperseg(targeti)-1));
end
%nframesperseg = frameends-framestarts+1;

%% get the score normalizations

score_norms = nan(nbehaviors,1);
for i = 1:nbehaviors,
  tmp = trx(targets).(scorefns{i});
  if iscell(tmp),
    tmp = [tmp{:}];
  end
  score_norms(i) = prctile(abs(tmp),score_norm_prctile);
end

%% choose weights for each behavior

if isempty(behaviorweight),
  behaviorweight = nan(nbehaviors,1);
  for behaviori = 1:nbehaviors,
    tmp = trx(targets).(labelfns{behaviori});
    if iscell(tmp),
      tmp = [tmp{:}];
    end
    behaviorweight(behaviori) = nnz(tmp>0);
  end
  behaviorweight = behaviorweight / sum(behaviorweight);
end
if numel(behaviorweight) == 1,
  behaviorweight = ones(nbehaviors,1);
end
behaviorweight = behaviorweight(:);

%% choose colors for each behavior

nadd = nbehaviors - size(behavior_colors,1);
if nadd > 0,
  tmp = behavior_cm(256);
  behavior_colors = cat(1,behavior_colors,tmp(round(linspace(1,256,nadd)),:));
end

%% initialize plot

if ishandle(hfig),
  set(0,'CurrentFigure',hfig);
  clf(hfig);
else
  hfig = figure(hfig);
end
set(hfig,'Units','pixels','Position',figpos);

mainpos = [0,frac_bottom+border_bottom+border_middle,1,1-frac_bottom-border_bottom-border_middle];
haxmain = axes('Position',mainpos);
haxbottom = axes('Position',[0,border_bottom,1,frac_bottom]);

t = framestarts(1);
im = readframe(t);
ncolors = size(im,3);
if ncolors == 1,
  him = imagesc(im2double(im),'Parent',haxmain,[0,1]);
  colormap(haxmain,'gray');
else
  him = image(im2double(im),'Parent',haxmain);
end
hold(haxmain,'on');
%axis(haxmain,'image');
htrx = plot(haxmain,nan,nan,'.-','LineWidth',trx_linewidth,'color',trxcolor);
htarget = plot(haxmain,nan,nan,'-','LineWidth',target_linewidth,'color','k');
if strcmp(animaltype,'larva')
    htarget_extra=plot(haxmain,nan,nan,'.','MarkerSize',headmarksize,'color','k');
end
if strcmp(animaltype,'larva_highres')
    htarget_extra(1)=plot(haxmain,nan,nan,'.-','MarkerSize',headmarksize,'color','k');
    htarget_extra(2)=plot(haxmain,nan,nan,'.','MarkerSize',headmarksize,'color','b');
end
set(haxmain,'XTick',[],'YTick',[]);
i = t+trx(target).off;

a = trx(targets).a;
if iscell(a),
  a = [a{:}];
end
meana = nanmedian(a)*4;
if isempty(pxwidthradius),
  pxwidthradius = awidthradius*meana;
end
if isempty(pxheightradius),
  pxheightradius = aheightradius*meana;
end
if isempty(pxborder),
  pxborder = aborder*meana;
end
if isempty(pxback),
  pxback = meana*aback;
end

set(haxmain,'Units','pixels');
mainpos = get(haxmain,'Position');
set(haxmain,'Units','normalized');
pxheightradius1 = min((pxwidthradius)*mainpos(4) / mainpos(3),(headerinfo.nr-1)/2);
pxwidthradius1 = min((pxheightradius)*mainpos(3) / mainpos(4),(headerinfo.nc-1)/2);
pxheightradius = max(pxheightradius1,pxheightradius);
pxwidthradius = max(pxwidthradius1,pxwidthradius);

% if we want a static axis
if ~isempty(fixedaxis),
   ax = fixedaxis;
else
   ax = ResetAxis(headerinfo.nc/2,headerinfo.nr/2,1,headerinfo.nr,headerinfo.nc,pxwidthradius,pxheightradius,pxborder);
end

hinfo = text(ax(1),ax(4),'','Parent',haxmain,'Color',textcolor,...
  'FontUnits','pixels','FontSize',fontsize,...
  'HorizontalAlignment','left',...
  'VerticalAlignment','bottom');

axis(haxmain,'image');
axis(haxmain,ax);

hbar = nan(1,nbehaviors);
hbarback = nan(1,nbehaviors);
for i = 1:nbehaviors,
  hbarback(i) = patch(i+bar_width/2*[-1,1,1,-1,-1],zeros(1,5)+.1,barbackcolor,'EdgeColor','none','Parent',haxbottom);
  if i == 1,
    hold(haxbottom,'on');
  end
  hbar(i) = patch(i+bar_width/2*[-1,1,1,-1,-1],zeros(1,5)+.1,behavior_colors(i,:),'EdgeColor','none','Parent',haxbottom);
end
htext = text(nan,nan,'','Parent',haxmain,'Color',textcolor,...
  'FontUnits','pixels','FontSize',fontsize);
plot(haxbottom,[0,nbehaviors+1],[0,0],'--','color',[.5,.5,.5]);
set(haxbottom,'XTick',1:nbehaviors,'XTickLabel',behaviors,'YTick',[],...
  'XLim',[.5,nbehaviors+.5],'YLim',[-1,1],'XColor','w','Color','k','TickLength',[0,0],'FontSize',bottomtextfontsize);

set(hfig,'Color','k');

if isstjaaba,
  set([htrx,htarget],'Visible','off');
  textpos = [size(im,2)/2,size(im,1)];
end

%% update plots

isfirstframe = true;

if ~isempty(titlepagetext),
  titlepagetext2 = sprintf(', %s',titlepagetext{:});
end

for segi = 1:numel(framestarts),

  % data for this target
  target = targets(segi);

  nframes_curr = trx(target).nframes;
  x = trx(target).x;
  y = trx(target).y;
  a = trx(target).a;
  b = trx(target).b;
  if strcmp(animaltype,'larva')
      pos.xspine=trx(target).xspine;
      pos.yspine=trx(target).yspine;
  end
   if strcmp(animaltype,'larva_highres')
      pos.xspine=trx(target).xspine;
      pos.yspine=trx(target).yspine;
      pos.xcontour=trx.xcontour{target};
      pos.ycontour=trx.ycontour{target};
  end
  try
     sex = trx(target).sex;
  catch
     sex = repmat({'?'},1,numel(x));
  end
  theta = trx(target).theta;
  % try to make sector somewhat continuous
  fil = [0.000263865082737   0.106450771973592   0.786570725887342   0.106450771973592   0.000263865082737];
  fil = fil / sum(fil(:));
  smooththeta = imfilter(theta,fil,'same','replicate');
  sector = floor(modrange((smooththeta-pi/8),0,2*pi)/pi*4)+1;
  % close holes
  if numel(sector) > 2,
    for i = 1:numel(sector),
      if ((i==1) || (i==numel(sector)) || (sector(i-1)==sector(i+1))) && ...
          (i==1 || sector(i)~=sector(i-1)) && ...
          (i==numel(sector) || sector(i)~=sector(i+1)) && ...
          (i==1 || abs(modrange(theta(i)-theta(i-1),-pi,pi))<pi/12) && ...
          (i==numel(sector) || abs(modrange(theta(i)-theta(i+1),-pi,pi))<pi/12),
        if i == 1,
          sector(i) = sector(i+1);
        else
          sector(i) = sector(i-1);
        end
      end
    end
  end

  scores = nan(nbehaviors,nframes_curr);
  labels = nan(nbehaviors,nframes_curr);
  for behaviori = 1:nbehaviors,
    scores(behaviori,:) = min(1,max(-1,trx(target).(scorefns{behaviori})/score_norms(behaviori)));
    labels(behaviori,:) = double(trx(target).(labelfns{behaviori}))*2-1;
  end

  for t = framestarts(segi):frameends(segi),
      im = readframe(t);
      set(him,'CData',im2double(im));
      i = t+trx(target).off;

      i0 = max(1,min(nframes_curr,i-trx_rad(1)));
      i1 = max(1,min(nframes_curr,i+trx_rad(1)));

      set(htrx,'XData',x(i0:i1),...
          'YData',y(i0:i1));
      switch animaltype
          case 'fly'
              updatefly(htarget,x(i),y(i),...
                  theta(i),a(i),b(i));
          case 'larva'
              pos2=struct('xspine',pos.xspine(:,i),'yspine',pos.yspine(:,i));
              updatelarvaspecies(htarget,htarget_extra,pos2)
          case 'larva_highres'
              pos2=struct('xspine',pos.xspine(:,i),'yspine',pos.yspine(:,i),'xcontour',pos.xcontour{i},'ycontour',pos.ycontour{i});
              updatelarvacontour(htarget,htarget_extra,pos2);
          otherwise
              error('Unknown animal type %s',animaltype);
      end

    for behaviori = 1:nbehaviors,
      set(hbar(behaviori),'YData',[0,0,1,1,0]*scores(behaviori,i));
      set(hbarback(behaviori),'YData',[0,0,1,1,0]*labels(behaviori,i));
    end
    w = max(0,scores(:,i)).*behaviorweight;
    z = sum(w);
    if z == 0,
      colortmp = [0,0,0];
    else
      colortmp = sum(bsxfun(@times,w,behavior_colors),1)/z*max(scores(:,i));
    end
    set(htarget,'Color',colortmp);

    if isstjaaba,
      tailpos = textpos;
      halign = 'center';
      valign = 'bottom';
    else

      tailpos = [x(i)-(pxback+2*a(i))*cos(theta(i)),y(i)-(pxback+2*a(i))*sin(theta(i))];
      sectori = sector(i);
      % floor(modrange((smooththeta(i)-pi/8),0,2*pi)/pi*4)+1;

      if ismember(sectori,[1,7,8]),
        halign = 'right';
      elseif ismember(sectori,[2,6]),
        halign = 'center';
      elseif ismember(sectori,[3,4,5]),
        halign = 'left';
      else
        error('Sanity check: sectori > 8 or < 1');
      end
      if ismember(sectori,[1,2,3]),
        valign = 'bottom';
      elseif ismember(sectori,[4,8]),
        valign = 'middle';
      elseif ismember(sectori,[5,6,7]),
        valign = 'top';
      else
        error('Sanity check: sectori > 8 or < 1');
      end
    end

    labelis = find(scores(:,i) > 0);
    s = cell(1,numel(labelis));
    for iii = 1:numel(labelis),
      s{iii} = sprintf('\\color[rgb]{%f %f %f}%s',behavior_colors(labelis(iii),:),behaviors{labelis(iii)});
    end
    if printnone && isempty(s),
      s = {'None'};
    end

    set(htext,'String',s,...
      'Position',tailpos,...
      'HorizontalAlignment',halign,...
      'VerticalAlignment',valign);

    if isstjaaba,
      ss = sprintf('Frame %d',t);
    else
      ss = sprintf('Target %d (%s), Frame %d',target,sex{i},t);
    end
    if ~isempty(textprefix),
      ss = sprintf('%s, %s',textprefix,ss);
    end
    if ~isempty(textsuffix),
      ss = sprintf('%s, %s',ss,textsuffix);
    end
    if ~isempty(titlepagetext),
      ss = [ss,titlepagetext2];
    end

    set(hinfo,'String',ss)

    if isempty(fixedaxis),
       outofbounds = x(i)-pxborder < ax(1) || ...
          x(i)+pxborder > ax(2) || ...
          y(i)-pxborder < ax(3) || ...
          y(i)+pxborder > ax(4);
    else
       outofbounds = false;
    end
    if isempty(fixedaxis) && (t == framestarts(segi) || outofbounds),
      ax = ResetAxis(x,y,i,headerinfo.nr,headerinfo.nc,pxwidthradius,pxheightradius,pxborder);
      axis(haxmain,ax);
      set(hinfo,'Position',ax([1,4]));
    end
    drawnow;

    if isfirstframe,

      if useVideoWriter,
        if strcmpi(compression,'None') || strcmpi(compression,'Uncompressed AVI'),
          profile = 'Uncompressed AVI';
        else
          profile = 'Motion JPEG AVI';
        end
        aviobj = VideoWriter(aviname,profile); %#ok<TNMLP>
        set(aviobj,'FrameRate',fps);
        if ~strcmpi(profile,'Uncompressed AVI'),
          set(aviobj,'Quality',100);
        end
        open(aviobj);
      else
        if isempty(avifileTempDataFile),
          aviobj = avifile(aviname,'fps',fps,'quality',100,'compression',compression);  %#ok<REMFF1>
        else
          aviobj = myavifile(aviname,'fps',fps,'quality',100,'compression',compression,...
            'TempDataFile',avifileTempDataFile);
          fprintf('Temporary data file for avi writing: %s\n',aviobj.TempDataFile);
        end
      end

      if ~isempty(titlepagetext),
        set(htext,'Visible','off');
        htitle = text(mean(ax(1:2)),mean(ax(3:4)),...
          titlepagetext,'HorizontalAlignment','center',...
          'VerticalAlignment','middle',...
          'Color',[.5,0,0],'Parent',haxmain,...
          'FontSize',40,'FontWeight','bold');
        fr = getframe(hfig);
        for pausei = 1:fps*titlepausetime,
          if useVideoWriter,
            writeVideo(aviobj,fr);
          else
            aviobj = addframe(aviobj,fr);
          end
        end
        set(htext,'Visible','on');
        delete(htitle);
      end

      isfirstframe = false;
    end

    % pause for a few frames at the start of a new segment
    if t == framestarts(segi) && numel(framestarts) > 1,
      set(hinfo,'Color',[.5,0,0],'FontWeight','bold');
      fr = getframe(hfig);
      for pausei = 1:fps,
        if useVideoWriter,
          writeVideo(aviobj,fr);
        else
          aviobj = addframe(aviobj,fr);
        end
      end
      set(hinfo,'Color',textcolor,'FontWeight','normal');
    end

    fr = getframe(hfig);
    height = size(fr.cdata,1);
    width = size(fr.cdata,2);
    if useVideoWriter,
      writeVideo(aviobj,fr);
    else
      aviobj = addframe(aviobj,fr);
    end

    set(hfig,'Position',figpos);

  end
end

%% clean up

if useVideoWriter,
  close(aviobj);
else
  aviobj = close(aviobj); %#ok<NASGU>
end

if fid>0,
  fclose(fid);
end
%% compress using mencoder

if isunix && usemencoder,
  [path,base,ext] = fileparts(aviname);
  tmpfile = fullfile(path,[base,'_tmp',ext]);
  newheight = 4*ceil(height/4);
  newwidth = 4*ceil(width/4);
  % subtitles are upside down, so encode with subtitles and flip, then flip
  % again
  cmd = sprintf('mencoder %s -o %s -ovc xvid -xvidencopts fixed_quant=4 -vf scale=%d:%d',...
    aviname,tmpfile,newwidth,newheight);
  status = system(cmd);
  if status ~= 0,
    error('Failed to compress avi to %s',tmpfile);
  end
  unix(sprintf('mv %s %s',tmpfile,aviname));
end

function ax = ResetAxis(x,y,i,nr,nc,pxwidthradius,pxheightradius,pxborder)

n = numel(x);

minx = x(i);
maxx = x(i);
miny = y(i);
maxy = y(i);
w = pxwidthradius-2*pxborder;
h = pxheightradius-2*pxborder;
for j = i+1:n,
  minx = min(minx,x(j));
  maxx = max(maxx,x(j));
  dx = ceil(maxx-minx)+1;
  if dx > w,
    break;
  end
  miny = min(miny,y(j));
  maxy = max(maxy,y(j));
  dy = ceil(maxy-miny)+1;
  if dy > h,
    break;
  end
end
mux = (minx+maxx)/2;
muy = (miny+maxy)/2;
ax = [mux+pxwidthradius*[-1,1],muy+pxheightradius*[-1,1]];

if ax(2)>nc && ax(1)<1,
  ax(1:2) = (nc+1)/2+pxwidthradius*[-1,1];
elseif ax(2)>nc,
  ax(2) = nc;
  ax(1) = nc-(2*pxwidthradius+1)+1;
elseif ax(1)<1,
  ax(1) = 1;
  ax(2) = 2*pxwidthradius+1;
end
if ax(2)>nc || ax(1)<1,
  ax(1:2) = (nc+1)/2+pxwidthradius*[-1,1];
end
if ax(4)>nr && ax(3)<1,
  ax(3:4) = (nr+1)/2+pxwidthradius*[-1,1];
elseif ax(4)>nr,
  ax(4) = nr;
  ax(3) = nr-(2*pxheightradius+1)+1;
elseif ax(3)<1,
  ax(3) = 1;
  ax(4) = 2*pxheightradius+1;
end
if ax(4)>nr || ax(3)<1,
  ax(3:4) = (nr+1)/2+pxheightradius*[-1,1];
end

author: kristinbranson

repo: JAABA


text:
function [pvec, pstruct] = tapas_beta_obs_transp(r, ptrans)
% --------------------------------------------------------------------------------------------------
% Copyright (C) 2013 Christoph Mathys, TNU, UZH & ETHZ
%
% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public
% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version). For further details, see the file
% COPYING or <http://www.gnu.org/licenses/>.

pvec    = NaN(1,length(ptrans));
pstruct = struct;

pvec(1)      = exp(ptrans(1));         % nupr
pstruct.nupr = pvec(1);

return;

author: translationalneuromodeling

repo: tapas


text:
% tested on win32 platform + VC7
% it may also work well on other platfoms/compilers
mex -O SegInMat.cpp bresenham.cpp
mex -O LineTwoPnts.cpp bresenham.cpp

author: Cloud-CV

repo: object-proposals


text:
%% sigmoid_pchip
% Below is a demonstration of the features of the |sigmoid_pchip| function

%%
clear; close all; clc;

%% Syntax
% |[s]=sigmoid_pchip(optStruct)|

%% Description
% UNDOCUMENTED

%% Examples

%%
% Plot settings
plotColors=gjet(250);
fontSize=15;

%% Creating sigmoid curves with prescribed start and end slopes

%%

n=10;
plotColor=gjet(n);
nPlot=2000;
t=linspace(0,1,nPlot)';

optStruct.nLin=10;
optStruct.rMode=1;
optStruct.n=nPlot;

%%
% Varying slope with matched slopes

cFigure;
hold on;
title('Slope variation','fontSize',fontSize);

c1_q=linspace(0,1,n); %Slope variations
for q=1:1:n

    optStruct.c1=c1_q(q);
    optStruct.c2=optStruct.c1;
    optStruct.r1=0.4;
    optStruct.r2=optStruct.r1;

    [Vi]=sigmoid_pchip(optStruct);

    hp=plotV(Vi,'r-','LineWidth',3); set(hp,'Color',plotColor(q,:));
end

plotV([t(:) t(:)],'k--','LineWidth',5);
colormap(gjet(250)); colorbar; caxis([min(c1_q) max(c1_q)]);
axis tight; axis equal; hold on; box on; grid on; view(2);
set(gca,'FontSize',15);
drawnow;

%%
% Varying slope with different start/end slopes

cFigure;
hold on;
title('Slope variation','fontSize',fontSize);

c1_q=linspace(0,1,n); %Slope variations
for q=1:1:n

    optStruct.c1=c1_q(q);
    optStruct.c2=optStruct.c1/2;
    optStruct.r1=0.25;
    optStruct.r2=optStruct.r1;

    [Vi]=sigmoid_pchip(optStruct);

    hp=plotV(Vi,'r-','LineWidth',3); set(hp,'Color',plotColor(q,:));
end

plotV([t(:) t(:)],'k--','LineWidth',5);
colormap(gjet(250)); colorbar; caxis([min(c1_q) max(c1_q)]);
axis tight; axis equal; hold on; box on; grid on; view(2);
set(gca,'FontSize',15);
drawnow;

%%
% Varying extent of slope at ends

cFigure;
hold on;
title('Extent variation','fontSize',fontSize);

r1_q=linspace(0.1,0.4,n); %Extent variations
for q=1:1:n

    optStruct.c1=0.25;
    optStruct.c2=optStruct.c1;
    optStruct.r1=r1_q(q);
    optStruct.r2=optStruct.r1;

    [Vi]=sigmoid_pchip(optStruct);

    hp=plotV(Vi,'r-','LineWidth',3); set(hp,'Color',plotColor(q,:));
end

plotV([t(:) t(:)],'k--','LineWidth',5);
plotV([t(:) optStruct.c1*t(:)],'k--','LineWidth',5);
plotV([t(:) optStruct.c1*t(:)+(1-optStruct.c1)],'k--','LineWidth',5);
colormap(gjet(250)); colorbar; caxis([min(r1_q) max(r1_q)]);
axis tight; axis equal; hold on; box on; grid on; view(2);
set(gca,'FontSize',15);
drawnow;

%%
% Varying number of points on the initial linear slope

optStruct.c1=0.2;
optStruct.c2=optStruct.c1;
optStruct.r1=0.35;
optStruct.r2=optStruct.r1;
optStruct.rMode=1;
optStruct.n=nPlot;

cFigure;
hold on;
title('Extent variation','fontSize',fontSize);

nLin_q=2:1:10; %Extent variations
n=numel(nLin_q);
for q=1:1:n

    optStruct.nLin=nLin_q(q);

    [Vi]=sigmoid_pchip(optStruct);

    hp=plotV(Vi,'r-','LineWidth',3); set(hp,'Color',plotColor(q,:));
end

plotV([t(:) t(:)],'k--','LineWidth',5);
plotV([t(:) optStruct.c1*t(:)],'k--','LineWidth',5);
plotV([t(:) optStruct.c1*t(:)+(1-optStruct.c1)],'k--','LineWidth',5);
colormap(gjet(250)); colorbar; caxis([min(nLin_q) max(nLin_q)]);
axis tight; axis equal; hold on; box on; grid on; view(2);
set(gca,'FontSize',15);
drawnow;

%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>

%%
% _*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:
clear;
gcp;

% same demo as demo_script.m but using the class @CNMF
%% load file

addpath(genpath('utilities'));
addpath(genpath('deconvolution'));
CNM = CNMF;                                     % contruct CNMF object
filename = 'demoMovie.tif';                     % filename to be processed
K = 40;                                         % number of components to be found

options = CNMFSetParms(...
    'p',2,...                                   % order of AR dynamics
    'gSig',5,...                                % half size of neuron
    'merge_thr',0.80,...                        % merging threshold
    'nb',2,...                                  % number of background components
    'min_SNR',3,...                             % minimum SNR threshold
    'space_thresh',0.5,...                      % space correlation threshold
    'cnn_thr',0.2...                            % threshold for CNN classifier
    );

%%
% Below is the standard processing pipeline. This processing can be
% executed in one shot using the CNM.fit function:
% CNM.fit(filename,options,K)

%% load the dataset and create the object
CNM.readFile(filename);                         % insert path to file here
CNM.optionsSet(options);                        % setup the options structure

%% Process the dataset

CNM.preprocess;             % preprocessing (compute some quantities)
CNM.initComponents(K);      % initialization
CNM.plotCenters()           % plot center of ROIs detected during initialization
CNM.updateSpatial();        % update spatial components
CNM.updateTemporal(0);      % update temporal components (do not deconvolve at this point)

%% component classification

CNM.evaluateComponents();   % evaluate spatial components based on their correlation with the data
CNM.CNNClassifier('')       % evaluate spatial components with the CNN classifier
CNM.eventExceptionality();  % evaluate traces
CNM.keepComponents();       % keep the components that are above certain thresholds

%% merge found components
CNM.merge();
CNM.displayMerging();

%% repeat processing

CNM.updateSpatial();
CNM.updateTemporal();
CNM.extractDFF();           % extract DF/F values.

%% do some plotting
figure;
CNM.plotContours();
CNM.plotComponentsGUI();     % display all components

author: flatironinstitute

repo: CaImAn-MATLAB


text:
function numElems = node_create_subject(nodeSubject, nodeRoot, sSubject, iSubject, iSearch)
% NODE_CREATE_SUBJECT: Create subject node from subject structure.
%
% USAGE:  node_create_subject(nodeSubject, nodeRoot, sSubject, iSubject)
%
% INPUT:
%     - nodeSubject : BstNode object with Type 'subject' => Root of the subject subtree
%     - nodeRoot    : BstNode object, root of the whole database tree
%     - sSubject    : Brainstorm subject structure
%     - iSubject    : indice of the subject node in Brainstorm subjects list
%     - iSearch     : ID of the active DB search, or empty/0 if none
% OUTPUT:
%     - numElems    : Number of node children elements (including self) that
%                     pass the active search filter. If 0, node should be hidden

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2008-2016
%          Martin Cousineau, 2019-2020

% If iSubject=0 => default subject
import org.brainstorm.tree.*;

% Parse inputs
if nargin < 4 || isempty(iSearch) || iSearch == 0
    iSearch = 0;
    % No search applied: ensure the node is added to the database
    numElems = 1;
else
    numElems = 0;
end
showParentNodes = node_show_parents(iSearch);

% Update node fields
nodeSubject.setFileName(sSubject.FileName);
nodeSubject.setItemIndex(0);
nodeSubject.setStudyIndex(iSubject);
if (iSubject ~= 0)
    nodeSubject.setComment(sSubject.Name);
else
    nodeSubject.setComment('(Default anatomy)');
end

% Anatomy files to use : Individual or Protocol defaults
% ==== Default anatomy ====
if sSubject.UseDefaultAnat && (iSubject ~= 0)
    nodeLink = BstNode('defaultanat', '(Default anatomy)', '', 0, 0);
    nodeSubject.add(nodeLink);

% ==== Individual anatomy ====
else
    % Create list of anat files (put the default at the top)
    iAnatList = 1:length(sSubject.Anatomy);
    iAtlas = find(~cellfun(@(c)(isempty(strfind(char(c), '_volatlas')) && isempty(strfind(char(c), '_tissues'))), {sSubject.Anatomy.FileName}));
    if (length(sSubject.Anatomy) > 1)
        iAnatList = [sSubject.iAnatomy, setdiff(iAnatList,[iAtlas,sSubject.iAnatomy]), setdiff(iAtlas,sSubject.iAnatomy)];
    end
    % Create and add anatomy nodes
    for iAnatomy = iAnatList
        if ismember(iAnatomy, iAtlas)
            nodeType = 'volatlas';
        else
            nodeType = 'anatomy';
        end
        [nodeCreated, nodeAnatomy] = CreateNode(nodeType, ...
            char(sSubject.Anatomy(iAnatomy).Comment), ...
            char(sSubject.Anatomy(iAnatomy).FileName), ...
            iAnatomy, iSubject, iSearch);

        if nodeCreated
            % If current item is default one
            if ismember(iAnatomy, sSubject.iAnatomy)
                nodeAnatomy.setMarked(1);
            end
            if showParentNodes
                nodeSubject.add(nodeAnatomy);
            else
                nodeRoot.add(nodeAnatomy);
            end
            numElems = numElems + 1;
        end
    end

    % Sort surfaces by category
    SortedSurfaces = db_surface_sort(sSubject.Surface);
    iSorted = [SortedSurfaces.IndexScalp, SortedSurfaces.IndexOuterSkull, SortedSurfaces.IndexInnerSkull, ...
               SortedSurfaces.IndexCortex, SortedSurfaces.IndexOther, SortedSurfaces.IndexFibers, SortedSurfaces.IndexFEM];
    % Process all the surfaces
    for i = 1:length(iSorted)
        iSurface = iSorted(i);
        SurfaceType = sSubject.Surface(iSurface).SurfaceType;
        % Create a node adapted to represent this surface
        [nodeCreated, nodeSurface] = CreateNode(lower(SurfaceType), ...
            char(sSubject.Surface(iSurface).Comment), ...
            char(sSubject.Surface(iSurface).FileName), ...
            iSurface, iSubject, iSearch);
        if nodeCreated
            % If current item is default one
            if ismember(iSurface, sSubject.(['i' SurfaceType]))
                nodeSurface.setMarked(1);
            end
            if showParentNodes
                nodeSubject.add(nodeSurface);
            else
                nodeRoot.add(nodeSurface);
            end
            numElems = numElems + 1;
        end
    end
end
end

% Create a Java object for a database node if it passes the active search
%
% Inputs:
%  - nodeType to iStudy: See BstJava's constructor
%  - iSearch: ID of the active search filter (or 0 if none)
%
% Outputs:
%  - isCreated: Whether the node was actually created (1 or 0)
%  - node: Newly created Java object for the node
function [isCreated, node] = CreateNode(nodeType, nodeComment, ...
        nodeFileName, iItem, iStudy, iSearch)
    import org.brainstorm.tree.BstNode;
    % Only create Java object is required
    [isCreated, filteredComment] = node_apply_search(iSearch, nodeType, nodeComment, nodeFileName);
    if isCreated
        node = BstNode(nodeType, filteredComment, nodeFileName, iItem, iStudy);
    else
        node = [];
    end
end

author: brainstorm-tools


text:
function a = le( x, y )

evalin( 'caller', 'cvx_verify' );
b = cvx_pushcnstr( x, y, '<=' );
if nargout, a = b; 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 pbmwrite(arg1,arg2,arg3,arg4)
%PBMWRITE Write a PBM (portable bitmap) file to disk.
%
%   PBMWRITE(X,MAP,'FILENAME') writes a PBM file containing the indexed
%   image X and color map MAP to the file 'FILENAME'.
%
%   PBMWRITE(X,MAP,'FILENAME','ENCODING') where 'ENCODING' is either
%   'ascii' (or 'plain') or 'binary' (or 'raw') lets the user specify
%   whether the PBM file should be ascii or binary encoded. Default is
%   'ascii'.
%
%   PBMWRITE(I,'FILENAME') writes a PBM file containing the black and
%   white image in the matrix I to the file 'FILENAME'.
%
%   PBMWRITE(I,'FILENAME','ENCODING') allows the user to specify the
%   encoding as described above.
%
%   The 'ascii' format is the most portable and is the only that allows
%   a MAXVALUE larger than 255, so it is also the most general. The
%   'binary' format files are, however, much smaller and many times
%   faster to read and write than the 'ascii' format.
%
%   If file name has no suffix, '.pbm' is used.
%
%   See also: PBMREAD, PGMREAD, PGMWRITE, PPMREAD, PPMWRITE.

%   Author:      Peter J. Acklam
%   Time-stamp:  1998-04-15 21:26:36
%   E-mail:      jacklam@math.uio.no (Internet)
%   URL:         http://www.math.uio.no/~jacklam

nargs = nargin;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check number of input arguments.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

error( nargchk( 2, 4, nargs ) );

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Identify input arguments.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if ( nargs == 2 )               % 2 input arguments

   %
   % PBMWRITE(I,'FILENAME')
   %
   I = arg1;
   filename = arg2;
   encoding = 'ascii';
   isindexed = 0;

elseif ( nargs == 4 )           % 4 input arguments

   %
   % PBMWRITE(X,MAP,'FILENAME','ENCODING')
   %
   X = arg1;
   map = arg2;
   filename = arg3;
   encoding = arg4;
   isindexed = 1;

else                            % 3 input arguments

   if ( ischar(arg2) & ischar(arg3) )

      %
      % PBMWRITE(I,'FILENAME','ENCODING')
      %
      I = arg1;
      filename = arg2;
      encoding = arg3;
      isindexed = 0;

   else

      %
      % PBMWRITE(X,MAP,'FILENAME')
      %
      X = arg1;
      map = arg2;
      filename = arg3;
      encoding = 'ascii';
      isindexed = 1;

   end

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% These are no longer needed, so delete them to save memory.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear arg1 arg2 arg3 arg4

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check filename.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if ~ischar(filename) | isempty(filename)
   error( 'File name must be a non-empty string' );
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add suffix to file name if necessary.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

k  = [ find( filename == filesep ) ];
if isempty(k)
   k = 0;
else
   k = max(k);
end
if all( filename(k+1:end) ~= '.' )
   filename = [ filename '.pbm' ];
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check and simplify the encoding specification.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if ~ischar( encoding )
   error( 'Encoding specification must be a string.' );
end

if any( encoding(1) == 'aApP' )         % Ascii (or plain) format.
   isascii = 1;
elseif any( encoding(1) == 'bBrR' )     % Binary (or raw) format.
   isascii = 0;
else
   error( 'Illegal encoding specification.' );
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Open output file for writing.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

fid = fopen( filename, 'w', 'ieee-be' );    % Big-endian byte ordering.
if ( fid == -1 )
   error( [ 'Can''t open file ''' filename ''' for writing.' ] );
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Get dimension of image.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if isindexed
   [ rows, cols ] = size( X );
else
   [ rows, cols ] = size( I );
end
pixels = rows*cols;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Write file header.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Magic number.
if isascii
   magic = 'P1';
else
   magic = 'P4';
end

% Write header. Use FLOOR( CLOCK ) to avoid a second value of 60.
fprintf( fid, [ ...
   '%s\n', ...
   '# Created by Matlab (%s) %04d-%02d-%02d %02d:%02d:%02d\n', ...
   '%d %d\n', ...
   ], magic, mfilename, floor( clock ), cols, rows );

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Write image. Color images are first converted to grayscale.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

w = [ 0.298936 ; 0.587043 ; 0.114021 ];

if isascii
   bits_on_this_line = 0;
   bits_on_each_line = 35;
   format = [ '%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d ' ...
              '%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d ' ...
              '%d %d %d %d %d\n' ];
else
   cols8 = 8*ceil( cols/8 );
end

for row = 1:rows

   % Convert to ones (black) and zeros (white).
   if isindexed
      bits = 1 - round( map(X(row,1:cols),:)*w );
   else
      bits = 1 - round( I(row,1:cols))';
   end

   if isascii           % Write ascii format.

      % If we are to fill more characters on a line already begun.
      if bits_on_this_line > 0

         % Get the format to be used when filling the rest of this line
         % and the number of bits that can be fit on this line.
         sub_format = format(bits_on_this_line*3+1:length(format));
         bits_to_eol = bits_on_each_line - bits_on_this_line;

         % Get the bits to write on this line and the remaining bits.
         bits_to_write_now = min( length(bits), bits_to_eol );
         sub_bits = bits(1:bits_to_eol);
         bits = bits(bits_to_eol+1:length(bits));

         % Write bits to file and increment number of bits on this line.
         fprintf( fid, sub_format, sub_bits );
         bits_on_this_line = bits_on_this_line + bits_to_write_now;
         bits_on_this_line = rem( bits_on_this_line, bits_on_each_line );

      end

      % If we are to begin writing on a new line.
      if bits_on_this_line == 0

         % Write bits to file and get number of bits on last line.
         fprintf( fid, format, bits );
         bits_on_this_line = rem( length(bits), bits_on_each_line );

      end

   else                 % Write binary format.

      newbits = zeros( 1, cols8 );
      newbits(1:cols) = bits;
      fwrite( fid, newbits, 'ubit1' );

   end

end

fclose( fid );          % Close file.

author: Sable

repo: mcbench-benchmarks


text:
function [ fn ] = getBatchWrapper_rgbflow(opts, numThreads, trainopts)

fn = @(imdb,batch, moreopts) getBatch(imdb,batch,opts,numThreads, trainopts, moreopts) ;
end

% -------------------------------------------------------------------------
function [im,labels] = getBatch(imdb, batch, opts, numThreads, trainopts, moreopts)
% -------------------------------------------------------------------------
nFrames=imdb.images.nFrames(batch);
images = cell(1,numel(nFrames));

labels = imdb.images.label(batch) ;

for k = 1:numel(nFrames)
    images{k}  = strcat([imdb.images.name{batch(k)}(1:end-4) filesep], images{k} ) ;
end

opts.nFrames = nFrames;

if ~isempty(moreopts) || nargin < 6
  for f = fieldnames(moreopts)'
    f = char(f) ;
    trainopts.(f) = moreopts.(f);
  end
end

opts.nFramesPerVid = trainopts.nFramesPerVid;
opts.numAugments = trainopts.numAugments;
opts.frameSample = trainopts.frameSample;
opts.augmentation =  trainopts.augmentation;
if isfield(trainopts, 'temporalStride')
  opts.temporalStride =  trainopts.temporalStride(randi(numel(trainopts.temporalStride))) ; % shuffle;
end
if isfield(trainopts, 'nFrameStack')
  opts.nFrameStack = trainopts.nFrameStack;
else
  opts.nFrameStack = trainopts.nFramesPerVid;
end
if isfield(trainopts, 'keepFramesDim')
  keepFramesDim = trainopts.keepFramesDim;
else
  keepFramesDim = false;
end
if isfield(trainopts, 'cheapResize')
  opts.cheapResize =  trainopts.cheapResize;
end
if isfield(trainopts, 'fetchGPU')
  opts.fetchGPU =  trainopts.fetchGPU;
end

if isfield(trainopts, 'prefetch')
    opts.prefetch = trainopts.prefetch;
end
if isfield(trainopts, 'frameList')
    opts.frameList = trainopts.frameList;
end
if isfield(trainopts, 'subMedian')
    opts.subMedian = trainopts.subMedian;
end

im = cnn_get_im_flow_batch(images, opts, ...
                            'numThreads', numThreads, ...
                            'augmentation', opts.augmentation , ...
                            'flowDir', imdb.flowDir, ...
                            'imageDir', imdb.imageDir) ;

if iscell(im), return; end

if nargout == 1 % to work with dag code
  if ndims(im) > 4 && ~keepFramesDim
    sz = size(im);
    nFrames = sz(5:end);
    im = permute(im, [1 2 3 5 4]);
    im = reshape(im, sz(1), sz(2), sz(3), []);

  end
  im = {'input', im(:,:,end-2:end,:,:), 'label', labels, 'input_flow', im(:,:,1:end-3,:,:)} ;

end

end

author: feichtenhofer

repo: st-resnet


text:
function [pred,model,prob] = mdlTrans_tsvm(Xl,Yl,Xu,param)
%Wrapper of Transducive SVM
%
%	This is a model-level semi-supervised (transductive) learning
% algorithm. It may be used as a baseline to other domain adaptation
% methods.
% Application scope:
%	+ partially labeled data
%	+ label type: classification

% Xl:	labeled X
% Yl:	labels of Xl, should be a vector containing class indices starting from 1
% Xu:	unlabeled X
%
% param: Struct of hyper-parameters, please see the first cell of this
%	program ("default parameters") for details. You can set parameter p to
%	x by setting param.p = x. For parameters that are not set, default
%	values will be used.

% pred : predicted labels for Xu
% prob : the confidence of pred
% model: model. For multi-class problems, one-vs-all strategy will be used
%	and model{i} is the model for class i
%
%	The svm-light toolbox and matlab interface can be obtained from
% http://svmlight.joachims.org/ and https://github.com/sods/svml
% ref: T. Joachims, "Transductive inference for text classification using
% support vector machines," 1999
%
% Copyright 2016 Ke YAN, Tsinghua Univ. http://yanke23.com , xjed09@gmail.com

svmlPath = 'svml-master';
addpath(svmlPath)

%% default parameters
% please find the details and other parameters in function svml
t = 2;
c = 1;
g = .001;
TransPosFrac = nan; % Fraction of unlabeled examples to be classified into
					% the positive class. If nan, we will estimate it using
					% Xu
defParam

%% train the classifier and predict
X = [Xl;Xu];
nTest = size(Xu,1);

nCls = max(Yl);
if nCls > 2
	warning('currently using one-vs-all strategy on TSVM, one-vs-one may be better.');
	prob = nan(nTest,nCls);

	for iCls = 1:nCls
		Y1 = Yl==iCls;
		Y1 = (Y1-.5)*2;% {0,1} to {-1,+1}
		if isnan(TransPosFrac)
			TransPosFrac = nnz(Yl==iCls)/length(Yl);
		end

		net = svml('', 'Kernel', t, 'C', c, 'KernelParam',g,'TransPosFrac',TransPosFrac,...
			'ExecPath',svmlPath,'Verbosity',0);
		Y1 = [Y1;zeros(nTest,1)]; % label 0 for the unlabeled samples
		net = svmltrain(net, X, Y1);
		prob(:,iCls) = svmlfwd(net, Xu);
		model{iCls} = net;
	end
	[~,pred] = max(prob,[],2);

else
	Y1 = (Yl-1.5)*2;
	if isnan(TransPosFrac)
		TransPosFrac = nnz(Y1==1)/length(Y1);
	end

	net = svml('', 'Kernel', t, 'C', c, 'KernelParam',g,'TransPosFrac',TransPosFrac,...
		'ExecPath',svmlPath,'Verbosity',0);
	Y1 = [Y1;zeros(nTest,1)];
	net = svmltrain(net, X, Y1);
	prob = svmlfwd(net, Xu);
	pred = sign(prob)/2+1.5;
	model = net;
end

end

%   Accepted options are:
%   Field      SVM light option  Range, description
%   'Verbosity'      -v       {0 .. 3}, default value 1
%                             Verbosity level
%   'Regression'     -z       {0, 1}, default value 0
%                             Switch between regression [1] and
%                             classification [0]
%   'C'              -c       (0, Inf), default value (avg. x*x)^-1
%                             Trade-off between error and margin
%   'TubeWidth'      -w       (0, Inf), default value 0.1
%                             Epsilon width of tube for regression
%   'CostFactor'     -j       (0, Inf), default value 1
%                             Cost-Factor by which training errors on
%                             positive examples outweight errors on
%                             negative examples
%   'Biased'         -b       {0, 1}, default value 1
%                             Use biased hyperplane x*w+b0 [1] instead of
%                             unbiased x*w0 [0]
%   'RemoveIncons'   -i       {0, 1}, default value 0
%                             Remove inconsistent training examples and
%                             retrain
%   'ComputeLOO'     -x       {0, 1}, default value 0
%                             Compute leave-one-out estimates [1]
%   'XialphaRho'     -o       )0, 2), default value 1.0
%                             Value of rho for XiAlpha-estimator and for
%                             pruning leave-one-out computation
%   'XialphaDepth'   -k       {0..100}, default value 0
%                             Search depth for extended XiAlpha-estimator
%   'TransPosFrac'   -p       (0..1), default value ratio of
%                             positive and negative examples in the
%                             training data. Fraction of unlabeled
%                             examples to be classified into the positive
%                             class
%   'Kernel'         -t       {0..4}, default value 1
%                             Type of kernel function:
%                             0: linear
%                             1: polynomial (s a*b+c)^d
%                             2: radial basis function exp(-gamma ||a-b||^2)
%                             3: sigmoid tanh(s a*b + c)
%                             4: user defined kernel from kernel.h
%   'KernelParam'    -d, -g, -s, -r, -u
%                             Depending on the kernel, this vector
%                             contains [d] for polynomial kernel, [gamma]
%                             for RBF, [s, c] for tanh kernel, string for
%                             user-defined kernel
%   'MaximumQP'      -q       {2..}, default value 10
%                             Maximum size of QP-subproblems
%   'NewVariables'   -n       {2..}, default value is the value chosen
%                             for 'MaximumQP'. Number of new variables
%                             entering the working set in each
%                             iteration. Use smaller values to prevent
%                             zig-zagging
%   'CacheSize'      -m       (5..Inf), default value 40.
%                             Size of cache for kernel evaluations in MB
%   'EpsTermin'      -e       (0..Inf), default value 0.001
%                             Allow that error for termination criterion
%                             [y [w*x+b] - 1] < eps
%   'ShrinkIter'     -h       {5..Inf}, default value 100.
%                             Number of iterations a variable needs to be
%                             optimal before considered for shrinking
%   'ShrinkCheck'    -f       {0, 1}, default value 1
%                             Do final optimality check for variables
%                             removed by shrinking. Although this test is
%                             usually positive, there is no guarantee
%                             that the optimum was found if the test is
%                             omitted.
%   'TransLabelFile' -l       String. File to write predicted labels of
%                             unlabeled examples into after transductive
%                             learning.
%   'AlphaFile'      -a       String. Write all alphas to this file after
%                             learning (in the same order as in the
%                             training set).

author: viggin

repo: domain-adaptation-toolbox


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%	SurfBox-MATLAB (c)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%%	Yue Lu and Minh N. Do
%%
%%	Department of Electrical and Computer Engineering
%%	Coordinated Science Laboratory
%%	University of Illinois at Urbana-Champaign
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%%	ccsym.m
%%
%%	First created: 08-14-05
%%	Last modified: 04-13-06
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function y = ccsym(x, k, type)

%% Exploit the complex conjugate symmetry in the fft of real signals.

%% type: 'c' compact 'e' expand
%% k: along which dimension

%% Dimensions of the problem
N = ndims(x);
szX = size(x);

if type == 'c'
    %% initialize the subscript array
    sub_array = repmat({':'}, [N, 1]);
    sub_array{k} = 1 : szX(k) / 2 + 1;
    y = x(sub_array{:});
else
    %% subscript mapping for complex conjugate symmetric signal
    %% recovery

    szX(k) = (szX(k)-1) * 2;
    sub_conj = cell(N, 1);

    for m = 1 : N
        sub_conj{m} = [1 szX(m):-1:2];
    end

    sub_conj{k} = [szX(k)/2 : -1 : 2];
    %% recover the full signal in the spatial domain complex
    %% conjugate symmetry.
    y = cat(k, x, conj(x(sub_conj{:})));

end

%%	This software is provided "as-is", without any express or implied
%%	warranty. In no event will the authors be held liable for any
%%	damages arising from the use of this software.

author: thomaskuestner


text:
function strs = slstrsplit(srcstr, delimiters)
%SLSTRSPLIT splits a string into cell array of strings by delimiters
%
% $ Syntax $
%   - strs = slstrsplit(srcstr, delimiters)
%
% $ Arguments $
%   - srcstr:       the source string
%   - delimiters:   the array of delimiting chars
%
% $ Description $
%   - strs = slstrsplit(srcstr, delimiters) splits the source string into
%     a cell array of parts, which are delimited by the chars in
%     delimiters.
%
% $ Remarks $
%   - If for adjacent delimiters, the between will not will extracted.
%   - No further processing is applied, you can use functions like
%     slcompresstext to achieve these goals.
%
% $ History $
%   - Created by Dahua Lin, on Aug 13, 2006
%

%% determine delimiter positions

n0 = length(srcstr);
is_delimiter = false(n0, 1);

nd = length(delimiters);
for i = 1 : nd
    ch = delimiters(i);
    is_delimiter(srcstr == ch) = true;
end

dps = find(is_delimiter);
dps = dps(:)';

%% extract parts

if isempty(dps)
    strs = {srcstr};
else
    sps = [1, dps+1];
    eps = [dps-1, n0];
    fv = find(sps <= eps);
    if ~isempty(fv)
        sps = sps(fv);
        eps = eps(fv);
        np = length(fv);
        strs = cell(np, 1);
        for i = 1 : np
            strs{i} = srcstr(sps(i):eps(i));
        end
    else
        strs = {};
    end
end

author: lmthang


text:
%kxprism 'Interactive 2D & 3D Plotting'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros xprism.pane file
%
% Parameters:
% InputFile: i1 'Input File 1', optional: 'Input plot 1'
% InputFile: i2 'Input File 2', optional: 'Input plot 2'
% InputFile: i3 'Input File 3', optional: 'Input plot 3'
% InputFile: i4 'Input File 4', optional: 'Input plot 4'
% Double: update 'Update time', default: 1: 'How often to check input file for modification'
%
% Example: kxprism({i1, i2, i3, i4}, {'i1','';'i2','';'i3','';'i4','';'update',1})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% xprism - Interactive 2D & 3D Plotting
%
%  DESCRIPTION
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

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

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

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB