text:
function hfssSetSolveInside(fid, Object, solveInsideFlag)

fprintf(fid, 'oEditor.ChangeProperty _\n');
fprintf(fid, '\tArray("NAME:AllTabs",  _\n');
fprintf(fid, '\t\tArray("NAME:Geometry3DAttributeTab", _\n');
fprintf(fid, '\t\t\tArray("NAME:PropServers",  "%s"), _\n', Object);
fprintf(fid, '\t\t\tArray("NAME:ChangedProps", _\n');
if (solveInsideFlag)
	fprintf(fid, '\t\t\t\tArray("NAME:Solve Inside", "Value:=", true) _\n');
else
	fprintf(fid, '\t\t\t\tArray("NAME:Solve Inside", "Value:=", false) _\n');
end
fprintf(fid, '\t\t\t\t) _\n');
fprintf(fid, '\t\t\t) _\n');
fprintf(fid, '\t\t) \n');

author: yuip

repo: hfss-api

save_path: github-repos/MATLAB/yuip-hfss-api


text:
function CancelEdit(topH)

% CancelEdit(topH)
%
% Sets the cancel flag in the user data.
%
% DBR 4/99

uiData = get(topH, 'UserData');
uiData.cancel = 1;
set(topH, 'UserData', uiData);
uiresume;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function h=m_quiver(long,lat,u,v,varargin)
% M_QUIVER Makes a quiverplot on a map (QUIVER-style)
%    M_QUIVER(LONG,LAT,U,V) plots velocity vectors as arrows with components
%    (U,V) at the points (LONG,LAT) on the currently defined map.  The
%    matrices LONG,LAT,U,V must all be the same size. U and V contain the
%    eastward and northward components of velocity. Arrow scaling is automatic.
%
%    M_QUIVER(X,Y,U,V,S) automatically scales the arrows to fit within the
%    grid and then stretches them by S.  Use S=0 to plot the arrows without
%    the automatic scaling; In this case the scaling is 1 unit/degree
%    latitude. Note that we do not scale arrows with respect to map
%    coordinates! Instead, the arrows will correspond better to actual motions
%    over some time step. The tradeoff is that a single scale arrow cannot
%    be accurate for the entire map (M_VEC scales arrows according to
%    map coordinates).
%
%    M_QUIVER(...,LINESPEC) uses the plot linestyle specified for
%    the velocity vectors.  Any marker in LINESPEC is drawn at the base
%    instead of an arrow on the tip.  Use a marker of '.' to specify
%    no marker at all.  See PLOT for other possibilities. M_QUIVER is a wrapper
%    for QUIVER - for fancier arrows it is possible to replace the call to
%    QUIVER with one to another routine that draws fancy arrows, e.g.
%    ARROW (from TMW user-contrib software archive), or to use M_VEC.
%
%    M_QUIVER(...,'filled') fills any markers specified.
%
%    H = M_QUIVER(...) returns a vector of line handles.
%
%    See also QUIVER, M_VEC

% Rich Pawlowicz (rich@ocgy.ubc.ca) 20/Jan/97
%
% This software is provided "as is" without warranty of any kind. But
% it's mine, so you can't sell it.
%

% 6/Nov/00 - eliminate returned stuff if ';' neglected (thx to D Byrne)

global MAP_PROJECTION MAP_VAR_LIST

% Have to have initialized a map first

if isempty(MAP_PROJECTION)
  disp('No Map Projection initialized - call M_PROJ first!');
  return;
end

[X,Y]=m_ll2xy(long,lat,'clip','point');

[XN,YN]=m_ll2xy(long,lat+.01,'clip','point');
[XE,YE]=m_ll2xy(long+(.01)./cos(lat*pi/180),lat,'clip','point');

mU=u.*(XE-X)*100 + v.*(XN-X)*100;
mV=u.*(YE-Y)*100 + v.*(YN-Y)*100;

h=quiver(X,Y,mU,mV,varargin{:});
set(h,'tag','m_quiver');

if nargout==0
 clear h
end

author: CelsoReyes


text:
path = '../traindata/transform/transform_512/02/';
dirs = dir([path '*.mat']);
dirs = struct2cell(dirs);

for i = 1:size(dirs,2)
    if(str2num(dirs{1,i}(1:end-4))>3000)
        delete([path dirs{1,i}]);
    end
end

author: xjqicuhk

repo: SIMS

save_path: github-repos/MATLAB/xjqicuhk-SIMS


text:
function TableDemo(Action);

persistent Handles T;

% function TableDemo(Action);
%
% Demonstrates the table class.
% The Action argument selects the button callback code
% and should not be supplied from the command line.
%
% Copyright (c) SINUS Messtechnik GmbH 2002
% www.sinusmess.de - Sound & Vibration Instrumentation
%                  - PCB Services
%                  - Electronic Design & Production

if nargin == 0
   % No Action parameter supplied:  create figure, table and other controls

   % Create figure and initialise data
   Handles.TableDemoFig = figure;
   set(Handles.TableDemoFig, 'Position', [50 50 800 420], ...
                             'Name', 'Table Test', ...
                             'ResizeFcn', 'TableDemo(''Resize'')');
   RowMax = 10;
   ColMax = 15;
   load PSE.mat;

   % Create table object with visible frame, create table controls and assign data
   T = table(Handles.TableDemoFig, 'Units', 'pixels', ...
                                   'Position', [10 40 780 370], ...
                                   'Visible', 'on');
   T = controls(T, RowMax, ColMax, 'ForegroundColor', 'red');
   T{:,:} = PSE;  % Assign data to table (can also be indexed specifically)

   % Create pushbuttons on figure
   Handles.SaveData    = uicontrol(Handles.TableDemoFig, ...
                                   'Style', 'pushbutton', ...
                                   'Position', [10 10 90 20], ...
                                   'String', 'Save Data', ...
                                   'Callback', 'TableDemo(''SaveData'')');
   Handles.RemoveTable = uicontrol(Handles.TableDemoFig, ...
                                   'Style', 'pushbutton', ...
                                   'Position', [100 10 90 20], ...
                                   'String', 'Remove Table', ...
                                   'Callback', 'TableDemo(''RemoveTable'')');
   Handles.Scroll      = uicontrol(Handles.TableDemoFig, ...
                                   'Style', 'pushbutton', ...
                                   'Position', [190 10 90 20], ...
                                   'String', 'Scroll to 3,4', ...
                                   'Callback', 'TableDemo(''Scroll'')');
   Handles.ScrollBack  = uicontrol(Handles.TableDemoFig, ...
                                   'Style', 'pushbutton', ...
                                   'Position', [280 10 90 20], ...
                                   'String', 'Scroll to 1,1', ...
                                   'Callback', 'TableDemo(''ScrollBack'')');
   Handles.SetMagic    = uicontrol(Handles.TableDemoFig, ...
                                   'Style', 'pushbutton', ...
                                   'Position', [370 10 90 20], ...
                                   'String', 'Set Magic Square', ...
                                   'Callback', 'TableDemo(''SetMagic'')');

else
   % Action argument supplied (selects callback function for figure or control).
   % Other callbacks are handled automatically in the table class directory.

   switch Action
   case 'Resize'       % ResizeFcn of Handles.TableDemoFig
      FigurePos = get(Handles.TableDemoFig, 'Position');
      TablePos = get(T, 'Position');
      TablePos(3) = FigurePos(3) - 20;
      TablePos(4) = FigurePos(4) - 50;
      T = set(T, 'Position', TablePos);
   case 'SaveData'     % Assign data from table (can also be indexed specifically)
      a = T{:,:};
      save save.mat a;
   case 'RemoveTable'  % Delete table
      T = delete(T);
      set(Handles.SaveData,    'Enable','off');
      set(Handles.RemoveTable, 'Enable','off');
      set(Handles.Scroll,      'Enable','off');
      set(Handles.ScrollBack,  'Enable','off');
      set(Handles.SetMagic,    'Enable','off');
   case 'Scroll'       % Set coordinates of upper left corner displayed within table
      T = scroll(T, 3, 4);
   case 'ScrollBack'   % Set coordinates of upper left corner displayed within table
      T = scroll(T, 1, 1);
   case 'SetMagic'     % Assign data to table (indexed specifically)
      T(1:5,3:7) = num2cell(magic(5));
   otherwise           % This should never happen...
      msgbox(['Unknown Action: ' Action], 'TableDemo', 'error');
   end
end

author: Sable

repo: mcbench-benchmarks


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

%%
clear; close all; clc;

%% Syntax
% |maxFig(varargin);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<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:
function geometry_test063 ( )

%*****************************************************************************80
%
%% TEST063 tests PLANE_NORMAL2EXP_3D.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 December 2010
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST063\n' );
  fprintf ( 1, '  PLANE_NORMAL2EXP_3D puts a plane defined by\n' );
  fprintf ( 1, '    point, normal form into explicit form.\n' );

  pp(1:3,1) = [ -1.0;   0.0; -1.0 ];
  normal(1:3,1) = [ -0.2672612; -0.5345225; -0.8017837 ];

  r8vec_print ( 3, pp, '  The point PP:' );

  r8vec_print ( 3, normal, '  Normal vector:' );

  [ p1, p2, p3 ] = plane_normal2exp_3d ( pp, normal );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  P1, P2, P3:\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  %12f  %12f  %12f\n', p1(1:3,1) );
  fprintf ( 1, '  %12f  %12f  %12f\n', p2(1:3,1) );
  fprintf ( 1, '  %12f  %12f  %12f\n', p3(1:3,1) );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function f = pskernelObjective(lntheta, models, prior)

% PSKERNELOBJECTIVE Likelihood approximation for point set IVM.

% KERN

% KERN

% PSIVM

if nargin < 3
  prior = 1;
end
f = 0;
numTasks = length(models.task);
for taskNo = 1:numTasks
  models.task(taskNo).lntheta = models.lntheta;
  f = f + kernelObjective(lntheta, models.task(taskNo), prior);
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function dist=KLDiv(P,Q)
%  dist = KLDiv(P,Q) Kullback-Leibler divergence of two discrete probability
%  distributions
%  P and Q  are automatically normalised to have the sum of one on rows
% have the length of one at each
% P =  n x nbins
% Q =  1 x nbins or n x nbins(one to one)
% dist = n x 1

if size(P,2)~=size(Q,2)
    error('the number of columns in P and Q should be the same');
end

if sum(~isfinite(P(:))) + sum(~isfinite(Q(:)))
   error('the inputs contain non-finite values!')
end

% normalizing the P and Q
if size(Q,1)==1
    Q = Q ./sum(Q);
    P = P ./repmat(sum(P,2),[1 size(P,2)]);
    temp =  P.*log(P./repmat(Q,[size(P,1) 1]));
    temp(isnan(temp))=0;% resolving the case when P(i)==0
    dist = sum(temp,2);

elseif size(Q,1)==size(P,1)

    Q = Q ./repmat(sum(Q,2),[1 size(Q,2)]);
    P = P ./repmat(sum(P,2),[1 size(P,2)]);
    temp =  P.*log(P./Q);
    temp(isnan(temp))=0; % resolving the case when P(i)==0
    dist = sum(temp,2);
end


text:
function F = plus( F, G )
% + PLUS of two CHEBFUN2V objects.
%   F + G if F and G are CHEBFUN2V objects does componentwise addition.
%
%   F + G if F is a double and G is a CHEBFUN2V does componentwise addition.
%
%   F + G if F is a CHEBFUN2V and G is a double does componentwise addition.
%
%   PLUS(F,G) is called for the syntax F + G.

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

% Empty check:
if ( isempty( F ) || isempty( G ) )
    F = chebfun2v;
    return
end

if ( ~isa( F , 'chebfun2v' ) )
    F = plus(G, F);
    return
end

nF = F.nComponents;

if ( isa(G, 'double') )              % CHEBFUN2V + DOUBLE
    if ( numel(G) == 1 )             % CHEBFUN2V + SCALAR
        for jj = 1 : nF
            F.components{jj} = plus(F.components{jj}, G);
        end
    elseif ( numel(G) == nF )        % CHEBFUN2V + MATRIX
        for jj = 1 : nF
             F.components{jj} = plus(F.components{jj}, G(jj));
        end
    else
        error('CHEBFUN:CHEBFUN2V:plus:doubleSize', 'Dimension mismatch.')
    end
elseif ( isa(G, 'chebfun2') )        % CHEBFUN2V + CHEBFUN
    for jj = 1 : nF
        F.components{jj} = plus(F.components{jj}, G);
    end
elseif ( isa(G, 'chebfun2v') )       % CHEBFUN2V + CHEBFUN2V
    nG = G.nComponents;
    if ( nG ~= nF )
        error('CHEBFUN:CHEBFUN2V:plus:components', ...
            'The chebfun2v objects do not have the same components.')
    end
    if ( G.isTransposed ~= F.isTransposed )
        error('CHEBFUN:CHEBFUN2V:plus:transposed', 'Dimension mismatch.')
    end
    for jj = 1 : nF                  % Add each component together
        F.components{jj} = plus(F.components{jj}, G.components{jj});
    end
else
    error('CHEBFUN:CHEBFUN2V:plus:type', 'Unrecongized input arguments')
end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function fx = f_HGFinGame(x,P,u,in)
% HGF-learner in a dyadic game
% function fx = f_HGFinGame(x,P,u,in)
% HGF stands for "Hierarchical Gaussian Filter" (cf. Mathys et al. 2014).
% In a dyadic game, HGF tracks P(o=1), i.e. the probaiblity that the
% opponent choses the option o=1 [see f_VBvolatile0.m].
% IN:
%   - x: the previous posterior sufficient statistics:
%   x(1)= o
%   x(2)= E[log-odds of P(o=1)]
%   x(3)= log V[log-odds of P(o=1)]
%   x(4)= E[log-volatility]
%   x(5)= log V[log-volatility]
%   - P: the perceptual model parameters vector, ie. P = [ka;om;th], using
%   the notation of [Mathys et al. 2010].
%   - u: u(1) = o
%   - in: options set in options.inF
% OUT:
%   - fx: the updated posterior sufficient statistics (having observed o).

if VBA_isWeird (u) % e.g., 1st trial
    fx = x;
    return
end
[fx] = f_VBvolatile0(x,P,u,in); % HGF update rule

author: MBB-team

repo: VBA-toolbox


text:
function r8_fall_test ( )

%*****************************************************************************80
%
%% R8_FALL_TEST tests R8_FALL.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 December 2014
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8_FALL_TEST\n' );
  fprintf ( 1, '  R8_FALL evaluates the falling factorial Fall(X,N).\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      X        N                     Exact' );
  fprintf ( 1, '                  Computed\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, x, n, f1 ] = r8_fall_values ( n_data );

    if ( n_data == 0 )
      break
    end

    f2 = r8_fall ( x, n );

    fprintf ( 1, '  %8.4f  %4d  %24.16g  %24.16g\n', x, n, f1, f2 );

  end

  return
end


text:
function [mixed, component1, component2] = MixSpeechWaveforms(wav1, wav2, SPR)

wav1 = wav1(:)';
n1 = length(wav1);
wav2 = wav2(:)';
n2 = length(wav2);

% scale wav2 to obtain desired SPR, the signal power ratio in dB
power1 = mean(wav1.^2);
power2 = mean(wav2.^2);
scale2 = sqrt(power1/power2 * 10^(-SPR/10));
if scale2<1
    wav2 = scale2*wav2;
else
    wav1 = wav1/scale2;
end

% if the two waveforms have different length, repeat the shorter one to
% match the longer one

if n1>n2
    nRepeat = ceil(n1/n2);
    wav2 = repmat(wav2, 1, nRepeat);
    wav2(n1+1:end) = [];
else
    nRepeat = ceil(n2/n1);
    wav1 = repmat(wav1, 1, nRepeat);
    wav1(n2+1:end) = [];
end

component1 = wav1;
component2 = wav2;
mixed = component1 + component2;

end

author: singaxiong

repo: SignalGraph


text:
function failed = runtest()
%RUNTEST Test Bayesian Adaptive Direct Search (BADS).
%  RUNTEST executes a few runs of the BADS optimization algorithm to
%  check that it is installed correctly, and returns the number of failed
%  tests.
%
%  See also BADS, BADS_EXAMPLES.

nvars = 3;                              % Number of dimensions
x0 = 4*ones(1,nvars);                  % Initial point
tolerr = [0.1 0.1 1 1];                   % Error tolerance

txt{1} = 'Test with deterministic function (ellipsoid)';
fprintf('%s.\n', txt{1});
fun = @(x) sum((x./(1:numel(x)).^2).^2);     % Objective function
[exitflag(1),err(1)] = testblock(fun,[],[],x0,0,0);

txt{2} = 'Test with deterministic function (sphere) and non-bound constraints';
fprintf('%s.\n', txt{2});
fun = @(x) sum(x.^2,2);
nonbcon = @(x) x(:,1) + x(:,2) < sqrt(2);     % Non-bound constraints
[exitflag(2),err(2)] = testblock(fun,[],nonbcon,x0,1,0);

txt{3} = 'Test with noisy function (noisy sphere)';
fprintf('%s.\n', txt{3});
fun = @(x) sum(x.^2) + randn();             % Noisy objective function
truefun = @(x) sum(x.^2);
[exitflag(3),err(3)] = testblock(fun,truefun,[],x0,0,0);

txt{4} = 'Test with heteroskedastic, specified noisy function (noisy sphere)';
fprintf('%s.\n', txt{4});
fun = @henoisysphere;           % Heteroskedastic noisy objective function
truefun = @(x) sum(x.^2);
[exitflag(4),err(4)] = testblock(fun,truefun,[],x0,0,1);

failed = 0;
fprintf('===========================================================================\n');
for i = 1:4
    fprintf('%s:', txt{i});
    if exitflag(i) >= 0 && err(i) < tolerr(i)
        fprintf('\tPASSED\n');
    else
        fprintf('\tFAILED\n');
        failed = failed + 1;
    end
end
fprintf('===========================================================================\n');
fprintf('\n');

if failed == 0
    display('BADS is working correctly. See bads_examples.m for usage examples; check out the BADS website;');
    display('consult the online FAQ; or digit ''help bads'' for more information. Enjoy!');
else
    display('BADS is not working correctly. Please check the online FAQ for more information.');
end

% %% Noisy sphere (FMINSEARCH)
%
% display('Comparison with FMINSEARCH (noisy sphere). Press any key to continue.')
% fun = @(x) sum(x.^2) + randn();             % Noisy objective function
% options = optimset('Display','iter');
% pause;
% [x,fval,exitflag,output] = fminsearch(fun,x0,options);
% display(['Final value (not-noisy): ' num2str(sum(x.^2),'%.3f') ' (true value: 0.0) with ' num2str(output.funcCount) ' fun evals.']);
%
% %% Noisy sphere (GA)
%
% if exist('ga.m','file')
%     display('Comparison with GA (noisy sphere). Press any key to continue.')
%     fun = @(x) sum(x.^2) + randn();             % Noisy objective function
%     options = gaoptimset('Display','iter','Generations',19);
%     pause;
%     rng(0);
%     [x,fval,exitFlag,output] = ga(fun,nvars,[],[],[],[],LB,UB,[],[],options);
%     display(['Final value (not-noisy): ' num2str(sum(x.^2),'%.3f')  ' (true value: 0.0) with ' num2str(output.funccount) ' fun evals.']);
% end

end

%--------------------------------------------------------------------------
function [exitflag,err] = testblock(fun,truefun,nonbcon,x0,fmin,henoise_flag)

nvars = numel(x0);
LB = -100*ones(1,nvars);                % Lower bound
UB = 100*ones(1,nvars);                 % Upper bound
PLB = -8*ones(1,nvars);                 % Plausible lower bound
PUB = 12*ones(1,nvars);                 % Plausible upper bound

options = bads('defaults');             % Default options
options.Debug = true;

if henoise_flag
    options.SpecifyTargetNoise = true;
    options.MaxFunEvals = 200;
else
    options.MaxFunEvals = 100;
end
[x,fval,exitflag,output] = bads(fun,x0,LB,UB,PLB,PUB,nonbcon,options);

if isempty(truefun)
    display(['Final value: ' num2str(fval,'%.3f') ' (true value: ' num2str(fmin) '), with ' num2str(output.funccount) ' fun evals.']);
    err = abs(fval - fmin);
else
    fval_true = truefun(x);
    display(['Final value (not-noisy): ' num2str(fval_true,'%.3f') ' (true value: ' num2str(fmin) ') with ' num2str(output.funccount) ' fun evals.']);
    err = abs(fval_true - fmin);
end
fprintf('\n');
end

%--------------------------------------------------------------------------
function [y,s] = henoisysphere(x)

y = sum(x.^2);
s = 2 + 1*sqrt(y);
y = y + s*randn();

end

author: acerbilab

repo: bads

save_path: github-repos/MATLAB/acerbilab-bads


text:
classdef AvePooling3D < dagnn.Filter
  properties
    method = 'avg'
    poolSize = [1 1 1]
  end

  methods
    function outputs = forward(obj, inputs, params)

      sz = size(inputs{1}); if numel(sz) < 4, sz(4) = 1; end
      nFrames = obj.poolSize(3) ;

      inputs{1} = reshape(inputs{1}, sz(1), sz(2), sz(3),  nFrames, sz(4) / nFrames ) ;
      inputs{1} = permute(inputs{1}, [1 2 4 3 5]);
      sz_in = size(inputs{1});
      outputs{1} = mean(inputs{1},1);
      outputs{1} = mean(outputs{1},2);
      outputs{1} = mean(outputs{1},3);
      outputs{1} = permute(outputs{1}, [1 2 4 5 3]);

%       [outputs{1}, ~]  = mex_maxpool3d(inputs{1},...
%         'pool',obj.poolSize, 'stride', obj.stride, 'pad', obj.pad);
%
%       outputs{1} = permute(outputs{1}, [1 2 4 3 5]);
%       sz_out = size(outputs{1});
%       if numel(sz_out) < 4, sz_out(4) = 1; end % fixes the case of time being pooled
% 	    nFrames = sz_out(4); % reset nframes
%       obj.net.meta.curNumFrames(obj.layerIndex) = nFrames ;
%       if numel(sz_out) < 5, sz_out(5) = 1; end % fixes the case of single batch
%
%       outputs{1} = reshape(outputs{1}, sz_out(1), sz_out(2), sz_out(3),  nFrames*sz_out(5) ) ;
     end

    function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)
      % currently doing forward and backward due to idx
      sz = size(inputs{1}); if numel(sz) < 4, sz(4) = 1; end
      nFrames = obj.poolSize(3) ;
      inputs{1} = reshape(inputs{1}, sz(1), sz(2), sz(3),  nFrames, sz(4) / nFrames ) ;
      inputs{1} = permute(inputs{1}, [1 2 3 5 4]);
      sz_in = size(inputs{1});
      for i=1:nFrames
          derInputs{1}(:,:,:,:,i) = vl_nnpool(inputs{1}(:,:,:,:,i), [sz(1),sz(2)], derOutputs{1}(:,:,:,:), ...
                               'pad', [0,0,0,0], ...
                               'stride', [1,1], ...
                               'method', 'avg') ;
      end
      derInputs{1} = reshape(derInputs{1}, sz(1), sz(2), sz(3),sz(4)) ;
%       nFramesIn = sz(4) / obj.net.meta.curBatchSize ;

%       inputs{1} = reshape(inputs{1}, sz(1), sz(2), sz(3),  nFramesIn, sz(4) / nFramesIn ) ;
%       inputs{1} = permute(inputs{1}, [1 2 4 3 5]);
%       sz_in = size(inputs{1});
%       [~, idx]  = mex_maxpool3d(inputs{1},...
%         'pool',obj.poolSize, 'stride', obj.stride, 'pad', obj.pad);
%
%       sz = size(derOutputs{1}); if numel(sz) < 4, sz(4) = 1; end
%       nFrames = sz(4) / obj.net.meta.curBatchSize ;
%
%
%       derOutputs{1} = reshape(derOutputs{1}, sz(1), sz(2), sz(3),  nFrames, sz(4) / nFrames ) ;
%       derOutputs{1} = permute(derOutputs{1}, [1 2 4 3 5]);
%
%
%       derInputs{1} = mex_maxpool3d(derOutputs{1}, idx, sz_in ,...
%         'pool',obj.poolSize, 'stride', obj.stride, 'pad', obj.pad);
%
%       derInputs{1} = permute(derInputs{1}, [1 2 4 3 5]);
%       sz_out = size(derInputs{1});
%       if numel(sz_out) < 4, sz_out(4) = 1; end % fixes the case of time being pooled
%       nFrames = sz_out(4); % reset nframes
%       obj.net.meta.curNumFrames(obj.layerIndex) = nFrames; % reset nframes
%
%       if numel(sz_out) < 5 , sz_out(5) = 1; end % fixes the case of single batch
%       derInputs{1} = reshape(derInputs{1}, sz_out(1), sz_out(2), sz_out(3),   nFrames*sz_out(5) ) ;
%       derInputs{1} = derOutputs{1};
      derParams = {};

    end

    function kernelSize = getKernelSize(obj)
      kernelSize = obj.poolSize ;
    end

    function outputSizes = getOutputSizes(obj, inputSizes)
      outputSizes = getOutputSizes@dagnn.Filter(obj, inputSizes) ;
      outputSizes{1}(3) = inputSizes{1}(3) ;
    end

    function obj = Pooling(varargin)
      obj.load(varargin) ;
    end
  end
end

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


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

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

% Last Modified by GUIDE v2.5 08-Feb-2010 17:59:44

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

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

% End initialization code - DO NOT EDIT

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

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

% Update handles structure
guidata(hObject, handles);

set(gcf, 'visible','off')

% question for password
%c = cell(1)
password='alhambra';
prompt = {'Enter password'};
dlg_title = 'Password';
num_lines = 1;
def = {'????','hsv'};
answer_x = inputdlg(prompt,dlg_title,num_lines,def);
answer_xx=cell2struct(answer_x, 'word',1);
answer=answer_xx.word;

if answer==password
    set(gcf, 'visible','on')
else
    close all
end

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

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

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


text:
% - This function is intended for image pre-processing
% - The function has five input arguments:-
% - FileName: the name of the input image.
% - PathName: the path of the input image.
% - Threshold: is set by default, you can change it

function BW=PreProcessing_General(FileName,Threshold)
%==========================================================================
% - This is to check whether the user needs to use automatic Thresholding;
% - or he may need to change the default value.
if nargin==1
    Threshold=0.35;
end
%==========================================================================
% - This is to read the input image.
global NROWS
global NCOLS
IN_IMG=imread(FileName);
NROWS=size(IN_IMG,1);
NCOLS=size(IN_IMG,2);
%==========================================================================
% - This is to apply image enhacement , waiting for control input from
% - the user.

% - This is to define the window size.

W_Size=3;
IN_IMG=medfilt2(IN_IMG,[W_Size W_Size]);

background = imopen(IN_IMG,strel('disk',3));
IN_IMG = IN_IMG + background;

%==========================================================================
% - In case you need to show the output after applying median filter
% - uncomment this part
% figure;imshow(IN_IMG);
% set(title('Median Filter'),'color','b');
%==========================================================================
% - This is to apply Otsu's method thresholding
% - Global image threshold using Otsu's method
% Threshold = graythresh(IN_IMG);
figure; imshow(IN_IMG,[]);
BW=im2bw(IN_IMG,Threshold);
% figure; imshow(BW,[]); pause;
BW = imcomplement(BW);
% figure; imshow(BW,[]); pause;
% SE = strel('disk',3);
% BW = imclose(BW,SE);
% figure; imshow(BW,[]); pause;
BW = imfill(BW,'holes');
% figure; imshow(BW,[]); pause;
SE2 = strel('disk',3);
BW = imopen(BW,SE2);
% figure; imshow(BW,[]); pause;
% BW = imclearborder(BW);
% figure; imshow(BW,[]); pause;

%==========================================================================
% - To display the output after applying Otsu (uncomment this part) ,
% - save the image in Alg_Output folder
% figure;imshow(BW);impixelinfo;
% set(title('Image Threshold'),'color','b');
%==========================================================================
[~,name,~] = fileparts(FileName);
imwrite(BW,['./Results/Step1_PreProcess/' name '_Pre.jpg'],'jpg');
%==========================================================================
end


text:
% DATASETSTOOLBOXES Loads in toolboxes for DATASETS.

importLatest('ndlutil');


text:
function [r,x,y,z] = elec_sphere_project(X,Y,Z,xo,yo,zo,varargin)

% elec_sphere_project - calculates spherical projections of electrode positions
%
% Usage: [r,x,y,z] = elec_sphere_project(X,Y,Z,xo,yo,zo,[estim],[plot])
%
% Notes:    The general formula for a sphere, with radius r is given by:
%
%           (x - xo)^2  +  (y - yo)^2  +  (z - zo)^2  =  r^2
%
%           This function takes arguments for cartesian co-ordinates
%           of X,Y,Z (assume Z > 0) and the center of the sphere (xo,yo,zo).
%           If (xo,yo,zo) are not provided, they are assumed (0,0,0).
%
%           Returned values are the fitted radius 'r' (constant)
%           and the (x,y,z) Cartesian co-ordinates on the projected sphere.
%
%           Options: estim - echo spherical radius estimates (default),
%                    plot  - plot the input/projected xyz on a sphere.
%

% $Revision: 1.1 $ $Date: 2009-04-28 22:13:55 $

% Licence:  GNU GPL, no express or implied warranties
% History:  02/2002, Darren.Weber_at_radiology.ucsf.edu
%                    adapted from elec_fit_sph
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% initialise centroid, unless input parameters defined
if ~exist('xo','var') xo = 0; else, if isempty(xo) xo = 0; end, end
if ~exist('yo','var') yo = 0; else, if isempty(yo) yo = 0; end, end
if ~exist('zo','var') zo = 0; else, if isempty(zo) zo = 0; end, end

if (nargin>6),        estim = varargin{1};
else                  estim = 1;
end
if (nargin>7),        plot = varargin{2};
else                  plot = 0;
end

eegversion = '$Revision: 1.1 $';
fprintf('ELEC_SPHERE_PROJECT [v %s]\n',eegversion(11:15));
fprintf('...projecting electrodes to spherical points\n');
tic;

% Initialise r0 as a rough guess at the sphere radius
rX = (max(X) - min(X)) / 2;
rY = (max(Y) - min(Y)) / 2;
rZ =  max(Z) - zo;
r0 = mean([ rX rY rZ ]);

if isequal(estim,1),
    fprintf('...initial spherical radius   = %f\n', r0); end

% perform least squares estimate of spherical radius (r)
options = optimset('fminsearch');
[r,fval,exitflag,output] = fminsearch('elec_sphere_fit_optim',...
                           r0, options, X, Y, Z, xo, yo, zo);
%fprintf('\n%s%f\n', 'Iterations = ', output.iterations);
%fprintf('\n%s%d\n', 'Exit = ', exitflag);

if isequal(estim,1),
    fprintf('...estimated spherical radius = %f\n', r); end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Find the projection point of X,Y,Z to the fitted sphere radius r

% Convert Cartesian X,Y,Z to spherical (radians)
theta = atan2( (Y-yo), (X-xo) );
phi = atan2( sqrt( (X-xo).^2 + (Y-yo).^2 ), (Z-zo) );
% do not recalc: r = sqrt( (X-xo).^2 + (Y-yo).^2 + (Z-zo).^2);

%   Recalculate X,Y,Z for constant r, given theta & phi.
R = ones(size(phi)) * r;
x = R .* sin(phi) .* cos(theta);
y = R .* sin(phi) .* sin(theta);
z = R .* cos(phi);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot the input & projected electrode positions on a sphere
if isequal(plot,1),
    figure('NumberTitle','off','Name','Electrode Placements');
    set(gca,'Projection','perspective');
    set(gca,'DataAspectRatio',[1 1 1]);

    hold on

    plot3(x,y,z,'b.');
    plot3(X,Y,Z,'ro');
    legend('input xyz','fitted sphere','Location','BestOutside');

    [Xs,Ys,Zs]=sphere;
    Xs = Xs * r;
    Ys = Ys * r;
    Zs = Zs * r;

    surf(Xs,Ys,Zs,...
        'EdgeColor','none',...
        'FaceColor',[0.7 0.7 0.7],...
        'FaceAlpha',0.4);
    view(2);
    rotate3d;

    axis tight; hold off;
end

t = toc; fprintf('...done (%6.2f sec).\n\n',t);

return

author: PatternRecognition

repo: OpenBMI


text:
function wav = readAlaw(file_name)

FILE = fopen( file_name );
if FILE < 0
    fprintf('File open error: %s\n', file_name);
    return;
end

data = fread(FILE, 'uint8');
wav = pcma2lin(data);
% plot(wav); pause;
% clear binData;
% binChars = dec2bin(data);
% for i=1:8
%     binData(:,i) = str2num(binChars(:,i));
% end

fclose(FILE);


text:
%% SOLAR SYSTEM EXAMPLE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This setup function configures an objectIndex that resembles our solar
% system in their orbital configuration.

% ADD THE PROGRAM PATHS
clear all; close all;
addpath('environment');
addpath('objects');
addpath('scenarios');

fprintf('[SETUP]\tAssembling the solar system example.\n');

%% SIMULATION PARAMETERS
[~, userdir]   = system('echo %USERPROFILE%'); % Get desktop path
sim_outputPath = strcat(userdir,'\desktop\OpenMAS_data');
sim_vebosity   = 1;
sim_warningDistance = 1;
sim_threadPool = 0;
sim_maxDuration = 92*60;
sim_timeStep    =  60;
sim_figureSet = {'fig','gif'};

%% SCENARIO PARAMETERS
sim_plotScenario = 1;
sim_agentOrbit  = 3;
sim_waypointOrbit = 10;
sim_offsetAngle = 0;
sim_agentVelocity = 0;
sim_noiseSigma = 0.0;

%% INITIALISE THE OBJECT SCENARIO
fprintf('[SETUP]\tAssigning object definitions:\n');

objectIndex = getScenario_earthOrbit('plot',sim_plotScenario,'scale',5E3);                 % Generate the earth

%% %%%%%% INITIALISE THE SIMULATION WITH THE OBJECT INDEX %%%%%%%%%%%%%%%%%
[DATA,META] = OMAS_initialise('objects',objectIndex,...
                             'duration',sim_maxDuration,...
                                   'dt',sim_timeStep,...
                              'figures',sim_figureSet,...
                      'warningDistance',sim_warningDistance,...
                            'verbosity',sim_vebosity,...
                           'threadPool',sim_threadPool,...
                           'outputPath',sim_outputPath);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clearvars -except DATA META
load(strcat(META.outputPath,'META.mat'));
load(strcat(META.outputPath,'EVENTS.mat'));

repo: OpenMAS


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Comparison of different learning methods of Hawkes processes
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear

options.N = 200; % the number of sequences
options.Nmax = 100; % the maximum number of events per sequence
options.Tmax = 50; % the maximum size of time window
options.tstep = 0.1;
options.dt = 0.1;
options.M = 250;
options.GenerationNum = 10;
D = 3; % the dimension of Hawkes processes
nTest = 1;
nSeg = 5;
nNum = options.N/nSeg;

disp('Approximate simulation of Hawkes processes via branching process')
disp('Complicated gaussian kernel')
para1.kernel = 'gauss';
para1.w = 1.5;
para1.landmark = 0:4:12;
L = length(para1.landmark);
para1.mu = rand(D,1)/D;
para1.A = zeros(D, D, L);
for l = 1:L
    para1.A(:,:,l) = (0.5^l)*(0.5+rand(D));
end
para1.A = 0.9*para1.A./max(abs(eig(sum(para1.A,3))));
para1.A = reshape(para1.A, [D, L, D]);
Seqs1 = Simulation_Branch_HP(para1, options);
%Seqs1 = Simulation_Thinning_HP(para1, options);

%%
disp('Learning Hawkes processes via different methods')
alg1.LowRank = 0;
alg1.Sparse = 1;
alg1.alphaS = 1;
alg1.GroupSparse = 0;
alg1.outer = 5;
alg1.rho = 0.1;
alg1.inner = 8;
alg1.thres = 1e-5;
alg1.Tmax = [];
alg1.storeErr = 0;
alg1.storeLL = 0;

alg2.alpha = 10000;
alg2.inner = 3;
alg2.inner_g = 100;
alg2.outer = 8;
alg2.thres = 1e-5;
alg2.Tmax = [];
Err = zeros(nTest, nSeg);

for n = 1:nTest
    for i = nSeg

        [A, Phi] = ImpactFunc( para1, options );

        disp('Maximum likelihood estimation and basis representation')
        model1 = Initialization_Basis(Seqs1);
        model1 = Learning_MLE_Basis( Seqs1(1:i*nNum), model1, alg1 );
        [A1, Phi1] = ImpactFunc( model1, options );

        disp('Maximum likelihood estimation and ODE')
        model2.M = 1000;
        model2.D = 2;
        model2.dt = 0.02;
        model2.g = rand(model2.M, model2.D);
        model2.g = model2.g./repmat(sum(model2.g),[model2.M,1]);
        model2.A = rand(D, model2.D, D)./(model2.D*D^2);
        model2.mu = rand(D,1)./D;
        model2 = Learning_MLE_ODE( Seqs1(1:i*nNum), model2, alg2 );
        [A2, Phi2] = ImpactFunc_ODE( model2 );

        disp('Least squares and discretization')
        model3.D = D;
        model3.h = 1;
        model3.k = floor(options.M * options.dt/model3.h);
        model3 = Initialization_Discrete(Seqs1(1:i*nNum));
        model3 = Learning_LS_Discrete( Seqs1(1:i*nNum), model3 );

        figure
        title('Complicated Gaussian kernels')
        for u = 1:D
            for v = 1:D
                subplot(D,D,D*(u-1)+v)
                hold on
                plot(options.dt*(0:(size(Phi,2)-1)), Phi(v,:,u), '-')
                plot(options.dt*(0:(size(Phi1,2)-1)), Phi1(v,:,u), '-')
                plot(options.dt*(0:(size(Phi2,2)-1)), Phi2(v,:,u), '-')
                plot(model3.h*(0:(size(model3.A,2)-1)), model3.A(v,:,u), '-')
                hold off
                axis tight
                legend('Real', 'MLE-Basis', 'MLE-ODE', 'LS')
                xlabel('Time interval between events')
                ylabel(['\phi', sprintf('%d%d', u, v)])
            end
        end

    end
end

author: HongtengXu

repo: Hawkes-Process-Toolkit


text:
function [ dat_out ] = prep_segmentation_filterbank( dat_in, varargin )

if iscell(varargin{:})
    opt=opt_cellToStruct(varargin{:});
elseif isstruct(varargin{:})
    opt=varargin{:};
end

time_interval=opt.interval;
num_cnt=length(dat_in);

for ii=1:num_cnt
    SMT{ii} = prep_segmentation(dat_in{ii}, {'interval', time_interval});
end

dat_out=SMT;

end


text:
function [net, gamma, logev] = evidence_weighted(net, x, t, eso_w, num)
%EVIDENCE Re-estimate hyperparameters using evidence approximation.
%
%	Description
%	[NET] = EVIDENCE(NET, X, T) re-estimates the hyperparameters ALPHA
%	and BETA by applying Bayesian re-estimation formulae for NUM
%	iterations. The hyperparameter ALPHA can be a simple scalar
%	associated with an isotropic prior on the weights, or can be a vector
%	in which each component is associated with a group of weights as
%	defined by the INDEX matrix in the NET data structure. These more
%	complex priors can be set up for an MLP using MLPPRIOR. Initial
%	values for the iterative re-estimation are taken from the network
%	data structure NET passed as an input argument, while the return
%	argument NET contains the re-estimated values.
%
%	[NET, GAMMA, LOGEV] = EVIDENCE(NET, X, T, NUM) allows the re-
%	estimation  formula to be applied for NUM cycles in which the re-
%	estimated values for the hyperparameters from each cycle are used to
%	re-evaluate the Hessian matrix for the next cycle.  The return value
%	GAMMA is the number of well-determined parameters and LOGEV is the
%	log of the evidence.
%
%	See also
%	MLPPRIOR, NETGRAD, NETHESS, DEMEV1, DEMARD
%

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

errstring = consist(net, '', x, t);
if ~isempty(errstring)
  error(errstring);
end

ndata = size(x, 1);
if nargin == 4
  num = 1;
end

if isfield(net,'beta')
    beta = net.beta;
else
    beta = 1;
end;

% Extract weights from network
pakstr = [net.type, 'pak'];
w = feval(pakstr, net);

% Evaluate data-dependent contribution to the Hessian matrix.
[h, dh] = nethess_weighted(w, net, x, t, eso_w);

% Now set the negative eigenvalues to zero.
[evec, evl] = eig(dh);
evl = evl.*(evl > 0);
% safe_evl is used to avoid taking log of zero
safe_evl = evl + eps.*(evl <= 0);

% Do the re-estimation.
for k = 1 : num
  [e, edata, eprior] = neterr_weighted(w, net, x, t, eso_w);
  h = nethess_weighted(w, net, x, t, eso_w, dh);
  % Re-estimate alpha.
  if size(net.alpha) == [1 1]
    % Evaluate number of well-determined parameters.
    if k == 1
      % Form vector of eigenvalues
      evl = diag(evl);
      safe_evl = diag(safe_evl);
    end
    B = beta*evl;
    gamma = sum(B./(B + net.alpha));
    net.alpha = 0.5*gamma/eprior;

    % Partially evaluate log evidence
    logev = e - 0.5*sum(log(safe_evl)) + 0.5*net.nwts*log(net.alpha) - ...
      0.5*ndata*log(2*pi);
  else
    ngroups = size(net.alpha, 1);
    gams = zeros(1, ngroups);
    logas = zeros(1, ngroups);
    traces = zeros(1, ngroups);
    % Reconstruct data hessian with negative eigenvalues set to zero.
    dh = evec*evl*evec';
    hinv = inv(nethess_weighted(w, net, x, t, eso_w, dh));
    for m = 1 : ngroups
      group_nweights = sum(net.index(:, m));
      gams(m) = group_nweights - ...
	        net.alpha(m)*sum(diag(hinv).*net.index(:,m));
      net.alpha(m) = real(gams(m)/(2*eprior(m)));
      % Weight alphas by number of weights in group
      logas(m) = 0.5*group_nweights*log(net.alpha(m));
      % Compute sum of evalues corresponding to group
      traces(m) = sum(log(safe_evl*net.index(:,m)));
    end
    gamma = sum(gams, 2);
    logev = e - 0.5*sum(traces) + sum(logas) - 0.5*ndata*log(2*pi);
  end
  % Re-estimate beta.
  if isfield(net, 'beta')
      net.beta = 0.5*(net.nout*ndata - gamma)/edata;
  end
  logev = logev + 0.5*ndata*log(beta);
end

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
% VGG MultiView Compute Library
%
% Conversions
%   vgg_KR_from_P         - extract K, R from P such that P = K*R*[eye(3) -t]
%   vgg_F_from_P          - fundamental matrix from 2 cameras
%   vgg_P_from_F          - 2 camera matrices from fundamental matrix
%   vgg_T_from_P          - trifocal tensor from 3 cameras
%   vgg_H_from_2P_plane   - inter-image homography from 2 cameras and 3D plane
%   vgg_H_from_P_plane    - projection matrix from image onto 3D plane
%   vgg_plane_from_2P_H   - 3D plane from 2 cameras and inter-image homography
%
% Multiview tensors from image correspondences
%   vgg_H_from_x_lin             - homography from points in 2 images, linear method
%   vgg_H_from_x_nonlin          - MLE of the above, by nonlinear method
%   vgg_Haffine_from_x_MLE       - MLE of affine transformation from points in 2 images, linear
%   vgg_F_from_7pts_2img         - fundamental matrix from 7 points in 2 images
%   vgg_PX_from_6pts_3img        - cameras and world points from 6 points in 3 images
%
% Preconditioning for estimation
%   vgg_conditioner_from_image - conditioning shift+scaling from image dimensions
%   vgg_conditioner_from_pts   - conditioning shift+scaling from image points
%
% Self-calibration and similar
%   vgg_signsPX_from_x         - swaps signs of P and X so that projection scales are positive
%   vgg_selfcalib_qaffine      - quasi-affine from projective reconstruction
%   vgg_selfcalib_metric_vansq - metric from projective and 3 orthogonal principal directions and square pixels
%
% Estimation
%   vgg_X_from_xP_lin          - 3D point from image projections and cameras, linear
%   vgg_X_from_xP_nonlin       - MLE of that, non-linear method
%   vgg_line3d_from_lP_lin     - 3D line segment from image line segments and cameras, linear
%   vgg_line3d_from_lP_nonlin  - MLE of that, non-linear method
%
% 3D lines representations
%   vgg_line3d_pv_from_XY      - Pluecker vector from 2 points on the line
%   vgg_line3d_pv_from_pm      - Pluecker matrix from Pluecker vector
%   vgg_line3d_pm_from_pv      - Pluecker vector from Pluecker matrix
%   vgg_line3d_Ppv             - rearrange camera matrix to project Pluecker vector to image line
%   vgg_line3d_pv_from_2planes - Pluecker vector from 2 planes meeting in the line
%   vgg_line3d_XY_from_pm      - 2 points on 3D line from Pluecker matrix
%   vgg_line3d_XY_from_pv      - 2 points on 3D line from Pluecker vector
%  (vgg_contreps               - dual of Pluecker matrix of 3D line)
%
% Auxiliary & miscellaneous
%   vgg_get_homg    - adding row of ones
%   vgg_get_nonhomg - dividing by the final coordinates
%   vgg_projective_basis_2d
%   vgg_rms_error
%   vgg_scatter_plot_homg
%   vgg_scatter_plot

author: jmmanley

repo: VGG-Multiple-View-Geometry


text:
function [params, s_new] = denoise_fica_gauss(params, s, state)
% FastICA gauss nonlinearity as DSS denoising function
%   [params, s_new] = denoise_fica_gauss(params, s, state)
%     params  Function specific modifiable parameters
%     params.a  Scale constant (default: 1)
%     state   DSS algorithm state
%     s       Source signal estimate, matrix of row vector signals
%     s_new   Denoised signal estimate

% Copyright (C) 2004, 2005 DSS MATLAB package team (dss@cis.hut.fi).
% Distributed by Laboratory of Computer and Information Science,
% Helsinki University of Technology. http://www.cis.hut.fi/projects/dss/.
% $Id$

if nargin<3 | ~isstruct(state)
    params.name = 'FastICA gaussian nonlinearity';
    params.description = '';
    params.param = {'a'};
    params.param_value ={1};
    params.param_type = {'scalar'};
    params.param_desc = {'Scaling constant'};
    params.approach = {'defl','symm'};
    params.alpha = {};
    params.beta = {};
    return;
end

if ~isfield(params, 'a')
  params.a = 1;
end
a = params.a;

s2=s.^2;
ex=exp(-a * s2/2);
gauss =  s.*ex;
beta = mean((1 - a * s2) .*ex, 2);
s_new = gauss - diag(beta) * s;

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function model = ResNet101_for_RFCN_VOC0712_OHEM(model)
% ResNet 101layers with OHEM training (finetuned from res3a)

model.solver_def_file        = fullfile(pwd, 'models', 'rfcn_prototxts', 'ResNet-101L_OHEM_res3a', 'solver_80k110k_lr1_3.prototxt');
model.test_net_def_file      = fullfile(pwd, 'models', 'rfcn_prototxts', 'ResNet-101L_OHEM_res3a', 'test.prototxt');

model.net_file               = fullfile(pwd, 'models', 'pre_trained_models', 'ResNet-101L', 'ResNet-101-model.caffemodel');
model.mean_image             = fullfile(pwd, 'models', 'pre_trained_models', 'ResNet-101L', 'mean_image');

end

repo: R-FCN


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  MATLAB Code for                                                  %
%                                                                   %
%  Multi-Objective Particle Swarm Optimization (MOPSO)              %
%  Version 1.0 - Feb. 2011                                          %
%                                                                   %
%  According to:                                                    %
%  Carlos A. Coello Coello et al.,                                  %
%  "Handling Multiple Objectives with Particle Swarm Optimization," %
%  IEEE Transactions on Evolutionary Computation, Vol. 8, No. 3,    %
%  pp. 256-279, June 2004.                                          %
%                                                                   %
%  Developed Using MATLAB R2009b (Version 7.9)                      %
%                                                                   %
%  Programmed By: S. Mostapha Kalami Heris                          %
%                                                                   %
%         e-Mail: sm.kalami@gmail.com                               %
%                 kalami@ee.kntu.ac.ir                              %
%                                                                   %
%       Homepage: http://www.kalami.ir                              %
%                                                                   %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clc;
clear;
close all;

%% Problem Definition

TestProblem=1;   % Set to 1, 2, or 3

switch TestProblem
    case 1
        CostFunction=@(x) MyCost1(x);
        nVar=5;
        VarMin=-4;
        VarMax=4;

    case 2
        CostFunction=@(x) MyCost2(x);
        nVar=3;
        VarMin=-5;
        VarMax=5;

    case 3
        CostFunction=@(x) MyCost3(x);
        nVar=2;
        VarMin=0;
        VarMax=1;
end

VarSize=[1 nVar];

VelMax=(VarMax-VarMin)/10;

%% MOPSO Settings

nPop=100;   % Population Size

nRep=100;   % Repository Size

MaxIt=100;  % Maximum Number of Iterations

phi1=2.05;
phi2=2.05;
phi=phi1+phi2;
chi=2/(phi-2+sqrt(phi^2-4*phi));

w=chi;              % Inertia Weight
wdamp=1;            % Inertia Weight Damping Ratio
c1=chi*phi1;        % Personal Learning Coefficient
c2=chi*phi2;        % Global Learning Coefficient

alpha=0.1;  % Grid Inflation Parameter

nGrid=10;   % Number of Grids per each Dimension

beta=4;     % Leader Selection Pressure Parameter

gamma=2;    % Extra (to be deleted) Repository Member Selection Pressure

%% Initialization

particle=CreateEmptyParticle(nPop);

for i=1:nPop
    particle(i).Velocity=0;
    particle(i).Position=unifrnd(VarMin,VarMax,VarSize);

    particle(i).Cost=CostFunction(particle(i).Position);

    particle(i).Best.Position=particle(i).Position;
    particle(i).Best.Cost=particle(i).Cost;
end

particle=DetermineDomination(particle);

rep=GetNonDominatedParticles(particle);

rep_costs=GetCosts(rep);
G=CreateHypercubes(rep_costs,nGrid,alpha);

for i=1:numel(rep)
    [rep(i).GridIndex rep(i).GridSubIndex]=GetGridIndex(rep(i),G);
end

%% MOPSO Main Loop

for it=1:MaxIt
    for i=1:nPop
        rep_h=SelectLeader(rep,beta);

        particle(i).Velocity=w*particle(i).Velocity ...
                             +c1*rand*(particle(i).Best.Position - particle(i).Position) ...
                             +c2*rand*(rep_h.Position -  particle(i).Position);

        particle(i).Velocity=min(max(particle(i).Velocity,-VelMax),+VelMax);

        particle(i).Position=particle(i).Position + particle(i).Velocity;

        flag=(particle(i).Position<VarMin | particle(i).Position>VarMax);
        particle(i).Velocity(flag)=-particle(i).Velocity(flag);

        particle(i).Position=min(max(particle(i).Position,VarMin),VarMax);

        particle(i).Cost=CostFunction(particle(i).Position);

        if Dominates(particle(i),particle(i).Best)
            particle(i).Best.Position=particle(i).Position;
            particle(i).Best.Cost=particle(i).Cost;

        elseif ~Dominates(particle(i).Best,particle(i))
            if rand<0.5
                particle(i).Best.Position=particle(i).Position;
                particle(i).Best.Cost=particle(i).Cost;
            end
        end

    end

    particle=DetermineDomination(particle);
    nd_particle=GetNonDominatedParticles(particle);

    rep=[rep
         nd_particle];

    rep=DetermineDomination(rep);
    rep=GetNonDominatedParticles(rep);

    for i=1:numel(rep)
        [rep(i).GridIndex rep(i).GridSubIndex]=GetGridIndex(rep(i),G);
    end

    if numel(rep)>nRep
        EXTRA=numel(rep)-nRep;
        rep=DeleteFromRep(rep,EXTRA,gamma);

        rep_costs=GetCosts(rep);
        G=CreateHypercubes(rep_costs,nGrid,alpha);

    end

    disp(['Iteration ' num2str(it) ': Number of Repository Particles = ' num2str(numel(rep))]);

    w=w*wdamp;
end

%% Results

costs=GetCosts(particle);
rep_costs=GetCosts(rep);

figure;

plot(costs(1,:),costs(2,:),'b.');
hold on;
plot(rep_costs(1,:),rep_costs(2,:),'rx');
legend('Main Population','Repository');

author: sfvsfv

repo: Mathematical-modeling


text:
function varargout = prod(varargin)
%PROD   Product integral of a DISKFUN.
%   PROD(F) returns exp( sum(log(F)) ).
%   PROD(F, DIM) returns the chebfun exp( sum(log(F), DIM) )
%
% See also DISKFUN/CUMPROD.

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

[varargout{1:nargout}] = prod@separableApprox(varargin{:});

end


text:
function imname = imNumToName(im, ext)
	imname = arrayfun(@(x) sprintf('img_%04d',x), im, 'UniformOutput', false);
	if(exist('ext', 'var'))
		imname = strcat(imname, '.', ext);
	end
	if(length(im) == 1)
		imname = imname{1};
	end
end

author: s-gupta

repo: rgbd

save_path: github-repos/MATLAB/s-gupta-rgbd


text:
function D = sqdistance(A, B, M)
% Square Euclidean or Mahalanobis distances between all sample pairs
% A: d x n1 data matrix
% B: d x n2 data matrix
% M: d x d  Mahalanobis matrix
% D: n1 x n2 pairwise square distance matrix
% Written by Michael Chen (sth4nth@gmail.com). July 2009.

if nargin == 1
    A = bsxfun(@minus,A,mean(A,2));
    S = full(sum(A.^2,1));
    D = full((-2)*(A'*A));
    D = bsxfun(@plus,D,S);
    D = bsxfun(@plus,D,S');
elseif nargin == 2
    m = (sum(A,2)+sum(B,2))/(size(A,2)+size(B,2));
    A = bsxfun(@minus,A,m);
    B = bsxfun(@minus,B,m);
    D = full((-2)*(A'*B));
    D = bsxfun(@plus,D,full(sum(B.^2,1)));
    D = bsxfun(@plus,D,full(sum(A.^2,1)'));
elseif nargin == 3
    m = (sum(A,2)+sum(B,2))/(size(A,2)+size(B,2));
    A = bsxfun(@minus,A,m);
    B = bsxfun(@minus,B,m);
    D = full((-2)*(A'*M*B));
    D = bsxfun(@plus,D,full(sum(B.*(M*B),1)));
    D = bsxfun(@plus,D,full(sum(A.*(M*A),1)'));
end

repo: mcbench-benchmarks


text:
function eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%EPS2PDF  Convert an eps file to pdf format using ghostscript
%
% Examples:
%   eps2pdf source dest
%   eps2pdf(source, dest, crop)
%   eps2pdf(source, dest, crop, append)
%   eps2pdf(source, dest, crop, append, gray)
%   eps2pdf(source, dest, crop, append, gray, quality)
%   eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%
% This function converts an eps file to pdf format. The output can be
% optionally cropped and also converted to grayscale. If the output pdf
% file already exists then the eps file can optionally be appended as a new
% page on the end of the eps file. The level of bitmap compression can also
% optionally be set.
%
% This function requires that you have ghostscript installed on your system.
% Ghostscript can be downloaded from: http://www.ghostscript.com
%
% Inputs:
%   source  - filename of the source eps file to convert. The filename is
%             assumed to already have the extension ".eps".
%   dest    - filename of the destination pdf file. The filename is assumed
%             to already have the extension ".pdf".
%   crop    - boolean indicating whether to crop the borders off the pdf.
%             Default: true.
%   append  - boolean indicating whether the eps should be appended to the
%             end of the pdf as a new page (if the pdf exists already).
%             Default: false.
%   gray    - boolean indicating whether the output pdf should be grayscale
%             or not. Default: false.
%   quality - scalar indicating the level of image bitmap quality to
%             output. A larger value gives a higher quality. quality > 100
%             gives lossless output. Default: ghostscript prepress default.
%   gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
%                multiple options are needed, enclose in call array: {'-a','-b'}

% Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015-

% Suggestion of appending pdf files provided by Matt C at:
% http://www.mathworks.com/matlabcentral/fileexchange/23629

% Thank you Fabio Viola for pointing out compression artifacts, leading to the quality setting.
% Thank you Scott for pointing out the subsampling of very small images, which was fixed for lossless compression settings.

% 09/12/11: Pass font path to ghostscript
% 26/02/15: If temp dir is not writable, use the dest folder for temp destination files (Javier Paredes)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve
%           some /findfont errors according to James Rankin, FEX Comment 23/01/15)
% 23/06/15: Added extra debug info in case of ghostscript error; code indentation
% 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova)
% 22/02/16: Bug fix from latest release of this file (workaround for issue #41)
% 20/03/17: Added informational message in case of GS croak (issue #186)
% 16/01/18: Improved appending of multiple EPS files into single PDF (issue #233; thanks @shartjen)
% 18/10/19: Workaround for GS 9.51+ .setpdfwrite removal problem (issue #285)
% 18/10/19: Warn when ignoring GS fontpath or quality options; clarified error messages
% 15/01/20: Added information about the GS/destination filepath in case of error (issue #294)
% 20/01/20: Attempted fix for issue #285: unsupported patch transparency in some Ghostscript versions
% 12/02/20: Improved fix for issue #285: add -dNOSAFER and -dALLOWPSTRANSPARENCY (thanks @linasstonys)
% 26/08/21: Added GS version to error message; fixed some problems with PDF append (issue #339)

    % Intialise the options string for ghostscript
    options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];

    % Set crop option
    if nargin < 3 || crop
        options = [options ' -dEPSCrop'];
    end

    % Set the font path
    fp = font_path();
    if ~isempty(fp)
        options = [options ' -sFONTPATH="' fp '"'];
    end

    % Set the grayscale option
    if nargin > 4 && gray
        options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
    end

    % Set the bitmap quality
    qualityOptions = '';
    if nargin > 5 && ~isempty(quality)
        qualityOptions = ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false';
        if quality > 100
            qualityOptions = [qualityOptions ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode'];
            qualityOptions = [qualityOptions ' -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
        else
            qualityOptions = [qualityOptions ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
            v = 1 + (quality < 80);
            quality = 1 - quality / 100;
            s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
            qualityOptions = [qualityOptions ' -c ".setpdfwrite << /ColorImageDict ' s ' /GrayImageDict ' s ' >> setdistillerparams"'];
        end
        options = [options qualityOptions];
    end

    % Enable users to specify optional ghostscript options (issue #36)
    if nargin > 6 && ~isempty(gs_options)
        if iscell(gs_options)
            gs_options = sprintf(' %s',gs_options{:});
        elseif ~ischar(gs_options)
            error('gs_options input argument must be a string or cell-array of strings');
        else
            gs_options = [' ' gs_options];
        end
        options = [options gs_options];
    end

    % Check if the output file exists
    if nargin > 3 && append && exist(dest, 'file') == 2
        % Store the original filesize for later use below
        try
            file_info = dir(dest);
            orig_bytes = file_info.bytes;
        catch
            orig_bytes = [];
        end
        % File exists - append current figure to the end
        tmp_nam = [tempname '.pdf'];
        [fpath,fname,fext] = fileparts(tmp_nam);
        try
            % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
            fid = fopen(tmp_nam,'w');
            fwrite(fid,1);
            fclose(fid);
            delete(tmp_nam);
        catch
            % Temp dir is not writable, so use the dest folder
            fpath = fileparts(dest);
            tmp_nam = fullfile(fpath,[fname fext]);
        end
        % Copy the original (dest) pdf file to temporary folder
        copyfile(dest, tmp_nam);
        % Produce an interim pdf of the source eps, rather than adding the eps directly (issue #233)
        % this will override the original (dest) pdf file
        orig_options = options;
        ghostscript([options ' -f "' source '"']);
        [~,fname] = fileparts(tempname);
        tmp_nam2 = fullfile(fpath,[fname fext]); % ensure using a writable folder (not necessarily tempdir)
        copyfile(dest, tmp_nam2);
        % Add the original pdf (tmp_nam) and interim pdf (dest=>tmp_nam2) as inputs to ghostscript
        %options = [options ' -f "' tmp_nam '" "' source '"'];  % append the source eps to dest pdf
        options = [options ' -f "' tmp_nam '" "' tmp_nam2 '"']; % append the interim pdf to dest pdf
        try
            % Convert to pdf using ghostscript
            [status, message] = ghostscript(options);
            % The output pdf should now be in dest

            % If the returned message is non-empty, a possible error may have
            % occured, so check the file size to ensure whether the file grew
            if ~isempty(message) && ~isempty(orig_bytes)
                file_info = dir(dest);
                new_bytes = file_info.bytes;
                if new_bytes < orig_bytes + 100
                    % Looks like nothing substantial (if anything) was appended to
                    % the original pdf, so try adding the eps file directly (issue #339)
                    options = [orig_options ' -f "' tmp_nam '" "' source '"'];  % append the source eps to dest pdf
                    [status, message] = ghostscript(options);
                end
            end

            % Delete the intermediate (temporary) files
            delete(tmp_nam);
            delete(tmp_nam2);
        catch me
            % Delete the intermediate files and rethrow the error
            delete(tmp_nam);
            delete(tmp_nam2);
            rethrow(me);
        end
    else
        % File doesn't exist or should be over-written
        % Add the source eps file as input to ghostscript
        options = [options ' -f "' source '"'];
        % Convert to pdf using ghostscript
        [status, message] = ghostscript(options);
    end

    % Check for error
    if status
        % Catch and correct undefined .setopacityalpha errors (issue #285)
        % (see explanation inside print2eps.m)
        if ~isempty(regexpi(message,'undefined in .setopacityalpha'))
            % First try with -dNOSAFER and -dALLOWPSTRANSPARENCY  (thanks @linasstonys)
            new_options = [options ' -dNOSAFER -dALLOWPSTRANSPARENCY'];
            [status, message] = ghostscript(new_options);
            if ~status  % hurray! (no error)
                return
            elseif isempty(regexpi(message,'undefined in .setopacityalpha'))  % still some other error
                options = new_options;
            else  % we still get a .setopacityalpha error
                % Remove the transparency and retry
                fstrm = read_write_entire_textfile(source);
                fstrm = regexprep(fstrm, '0?\.\d+ .setopacityalpha \w+\n', '');
                read_write_entire_textfile(source, fstrm);
                [status, message] = ghostscript(options);
                if ~status % hurray! (no error)
                    % Alert the user that transparency is not supported
                    warning('export_fig:GS:quality','Export_fig Face/Edge alpha transparancy is ignored - not supported by your Ghostscript version')
                    return
                end
            end
        end

        % Retry without the -sFONTPATH= option (this might solve some GS
        % /findfont errors according to James Rankin, FEX Comment 23/01/15)
        orig_options = options;
        if ~isempty(fp)
            options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' ');
            [status, message] = ghostscript(options);
            if ~status % hurray! (no error)
                warning('export_fig:GS:fontpath','Export_fig font option is ignored - not supported by your Ghostscript version')
                return
            end
        end

        % Retry without quality options (may solve problems with GS 9.51+, issue #285)
        if ~isempty(qualityOptions)
            options = strrep(orig_options, qualityOptions, '');
            [status, message] = ghostscript(options);
            if ~status % hurray! (no error)
                warning('export_fig:GS:quality','Export_fig quality option is ignored - not supported by your Ghostscript version')
                return
            end
        end

        % Report error
        if isempty(message)
            error(['Unable to generate pdf. Ensure that the destination folder (' fileparts(dest) ') is writable.']);
        elseif ~isempty(strfind(message,'/typecheck in /findfont')) %#ok<STREMP>
            % Suggest a workaround for issue #41 (missing font path)
            font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1'));
            fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name);
            %fpath = fileparts(mfilename('fullpath'));
            %gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt');
            [unused, gs_fonts_file] = user_string('gs_font_path'); %#ok<ASGLU>
            fprintf(2, '  try to add the font''s folder to your %s file\n\n', gs_fonts_file);
            error('export_fig error');
        else
            gs_options = strtrim(gs_options);
            fprintf(2, '\nGhostscript error: ');
            msg = regexprep(message, '^Error: /([^\n]+).*', '$1');
            if ~isempty(msg) && ~strcmp(msg,message)
                fprintf(2,'%s',msg);
            end
            fprintf(2, '\n * perhaps %s is open by another application\n', dest);
            try gs_version = str2num(evalc('ghostscript(''--version'');')); catch, gs_version = ''; end %#ok<ST2NM>
            if ~isempty(gs_version), gs_version = [' ' num2str(gs_version)]; end
            if ~isempty(gs_options)
                fprintf(2, ' * or maybe your Ghostscript version%s does not accept the extra "%s" option(s) that you requested\n', gs_version, gs_options);
            end
            fprintf(2, ' * or maybe you have another gs executable in your system''s path\n\n');
            fprintf(2, 'Ghostscript path: %s\n', user_string('ghostscript'));
            fprintf(2, 'Ghostscript options: %s\n\n', orig_options);
            error(message);
        end
    end
end

% Function to return (and create, where necessary) the font path
function fp = font_path()
    fp = user_string('gs_font_path');
    if ~isempty(fp)
        return
    end
    % Create the path
    % Start with the default path
    fp = getenv('GS_FONTPATH');
    % Add on the typical directories for a given OS
    if ispc
        if ~isempty(fp)
            fp = [fp ';'];
        end
        fp = [fp getenv('WINDIR') filesep 'Fonts'];
    else
        if ~isempty(fp)
            fp = [fp ':'];
        end
        fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
    end
    user_string('gs_font_path', fp);
end

author: ambropo

repo: VAR-Toolbox

save_path: github-repos/MATLAB/ambropo-VAR-Toolbox


text:
function [weights,location] = GaussQuad1d(ngp)
% Guass weights and abscissas.
% Taken from http://en.wikipedia.org/wiki/Gaussian_quadrature

% Data Table
switch ngp
    case{1} % ngp =1
        location = 0;
        weights = 2;
    case{2} % ngp =2
        location = [-sqrt(3)/3,sqrt(3)/3]';
        weights = [1,1]';
    case{3} % ngp =3
        location = [-sqrt(3/5),0,sqrt(3/5)]';
        weights = [5/9,8/9,5/9]';
    case{4} % ngp =4
        x1 = sqrt((3-2*sqrt(6/5))/7);
        x2 = sqrt((3+2*sqrt(6/5))/7);
        location = [-x1,-x2,x2,x1]';
        w1 = (18+sqrt(30))/36;
        w2 = (18-sqrt(30))/36;
        weights = [w1,w2,w2,w1]';
    case{5} % ngp =5
        x1 = (1/3)*sqrt(5-2*sqrt(10/7));
        x2 = (1/3)*sqrt(5+2*sqrt(10/7));
        x3 = 0;
        location = [-x1,-x2,x3,x2,x1]';
        w1 = (322 + 13*sqrt(70))/900;
        w2 = (322 - 13*sqrt(70))/900;
        w3 = 128/225;
        weights = [w1,w2,w3,w2,w1]';
    otherwise
        error('ngp max value = 5')
end

repo: Aero-matlab


text:
function gr_test06 ( node_num, node_coordinates, edge_num, edge_nodes );

%*****************************************************************************80
%
%% GR_TEST06 tests GR_GRF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 January 2011
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'GR_TEST06:\n' );
  fprintf ( 1, '  GR_GRF creates a GRF file from a graph.\n' );

  gr_grf ( node_num, node_coordinates, ...
    edge_num, edge_nodes );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Created the GRF file "graph.grf".\n' );

  return
end

repo: jburkardt-m


text:
function z = min( x, y, dim )

%   Disciplined convex/geometric programming information:
%       MAX is convex, log-log-concave, and nondecreasing in its first
%       two arguments. Thus when used in disciplined convex programs,
%       both arguments must be concave (or affine). In disciplined
%       geometric programs, both arguments must be log-concave/affine.

persistent remap remap_1 remap_2 remap_3
error( nargchk( 1, 3, nargin ) );
if nargin == 2,

    %
    % min( X, Y )
    %

    sx = size( x );
    sy = size( y );
    xs = all( sx == 1 );
    ys = all( sy == 1 );
    if xs,
        sz = sy;
    elseif ys || isequal( sx, sy ),
        sz = sx;
    else
        error( 'Array dimensions must match.' );
    end

    %
    % Determine the computation methods
    %

    if isempty( remap ),
        remap1 = cvx_remap( 'real' );
        remap1 = remap1' * remap1;
        remap2 = cvx_remap( 'log-concave' )' * cvx_remap( 'nonpositive' );
        remap3 = remap2';
        remap4 = cvx_remap( 'log-concave', 'real' );
        remap4 = remap4' * remap4;
        remap5 = cvx_remap( 'concave' );
        remap5 = remap5' * remap5;
        remap   = remap1 + ~remap1 .* ...
            ( 2 * remap2 + 3 * remap3 + ~( remap2 | remap3 ) .* ...
            ( 4 * remap4 + ~remap4 .* ( 5 * remap5 ) ) );
    end
    vx = cvx_classify( x );
    vy = cvx_classify( y );
    vr = remap( vx + size( remap, 1 ) * ( vy - 1 ) );
    vu = sort( vr(:) );
    vu = vu([true;diff(vu)~=0]);
    nv = length( vu );

    %
    % The cvx multi-objective problem
    %

    xt = x;
    yt = y;
    if nv ~= 1,
        z = cvx( sz, [] );
    end
    for k = 1 : nv,

        %
        % Select the category of expression to compute
        %

        if nv ~= 1,
            t = vr == vu( k );
            if ~xs,
                xt = cvx_subsref( x, t );
                sz = size( xt ); %#ok
            end
            if ~ys,
                yt = cvx_subsref( y, t );
                sz = size( yt ); %#ok
            end
        end

        %
        % Apply the appropriate computation
        %

        switch vu( k ),
        case 0,
            % Invalid
            error( 'Disciplined convex programming error:\n    Cannot perform the operation min( {%s}, {%s} )', cvx_class( xt, false, true ), cvx_class( yt, false, true ) );
        case 1,
            % constant
            cvx_optval = cvx( min( cvx_constant( xt ), cvx_constant( yt ) ) );
        case 2,
            % min( log-concave, nonpositive ) (no-op)
            cvx_optval = yt;
        case 3,
            % min( nonpositive, log-concave ) (no-op)
            cvx_optval = xt;
        case 4,
            % posy
            cvx_begin gp
                 hypograph variable zt( sz )
                xt >= zt; %#ok
                yt >= zt; %#ok
            cvx_end
        case 5,
            % non-posy
            cvx_begin
                hypograph variable zt( sz )
                xt >= zt; %#ok
                yt >= zt; %#ok
            cvx_end
        otherwise,
            error( 'Shouldn''t be here.' );
        end

        %
        % Store the results
        %

        if nv == 1,
            z = cvx_optval;
        else
            z = cvx_subsasgn( z, t, cvx_optval );
        end

    end

else

    %
    % min( X, [], dim )
    %

    if nargin > 1 && ~isempty( y ),
        error( 'min with two matrices to compare and a working dimension is not supported.' );
    end
    sx = size( x );
    if nargin < 2,
        dim = cvx_default_dimension( sx );
    elseif ~cvx_check_dimension( dim ),
        error( 'Third argument must be a positive integer.' );
    end

    %
    % Determine sizes, quick exit for empty arrays
    %

    sx = [ sx, ones( 1, dim - length( sx ) ) ];
    nx = sx( dim );
    if any( sx == 0 ),
        sx( dim ) = min( sx( dim ), 1 );
        z = zeros( sx );
        return
    end
    sy = sx;
    sy( dim ) = 1;

    %
    % Type check
    %

    if isempty( remap_3 ),
        remap_1 = cvx_remap( 'real' );
        remap_2 = cvx_remap( 'log-concave', 'real' );
        remap_3 = cvx_remap( 'concave' );
    end
    vx = cvx_reshape( cvx_classify( x ), sx );
    t1 = all( reshape( remap_1( vx ), sx ), dim );
    t2 = all( reshape( remap_2( vx ), sx ), dim );
    t3 = all( reshape( remap_3( vx ), sx ), dim );
    t3 = t3 & ~( t1 | t2 );
    t2 = t2 & ~t1;
    ta = t1 + ( 2 * t2 + 3 * t3 ) .* ~t1;
    nu = sort( ta(:) );
    nu = nu([true;diff(nu)~=0]);
    nk = length( nu );

    %
    % Quick exit for size 1
    %

    if nx == 1 && all( nu ),
        z = x;
        return
    end

    %
    % Permute and reshape, if needed
    %

    if dim > 1 && any( sx( 1 : dim - 1 ) > 1 ),
        perm = [ dim, 1 : dim - 1, dim + 1 : length( sx ) ];
        x   = permute( x,  perm );
        ta  = permute( ta, perm );
        sx  = sx(perm);
        sy  = sy(perm);
        dim = 1;
    else
        perm = [];
    end
    nv = prod( sx ) / nx;
    x  = reshape( x, nx, nv );

    %
    % Perform the computations
    %

    if nk ~= 1,
        z = cvx( [ 1, nv ], [] );
    end
    for k = 1 : nk,

        if nk == 1,
            xt = x;
        else
            tt = ta == nu( k );
            xt = cvx_subsref( x, ':', tt );
            nv = nnz( tt ); %#ok
        end

        switch nu( k ),
            case 0,
                error( 'Disciplined convex programming error:\n   Invalid computation: min( {%s} )', cvx_class( xt, false, true ) );
            case 1,
                cvx_optval = min( cvx_constant( xt ), [], dim );
            case 2,
                cvx_begin gp
                    hypograph variable zt( 1, nv )
                    xt >= ones(nx,1) * zt; %#ok
                cvx_end
            case 3,
                cvx_begin
                    hypograph variable zt( 1, nv )
                    xt >= ones(nx,1) * zt; %#ok
                cvx_end
            otherwise,
                error( 'Shouldn''t be here.' );
        end

        if nk == 1,
            z = cvx_optval;
        else
            z = cvx_subsasgn( z, tt, cvx_optval );
        end

    end

    %
    % Reverse the reshaping and permutation steps
    %

    z = reshape( z, sy );
    if ~isempty( perm ),
        z = ipermute( z, perm );
    end

end

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.

repo: REST


text:
% SIGNAL SYNTHESIS
%
% Estimates the time-domain signal from a given time-frequency distribution.
%
%
% The signal synthesis routine is limited to the following
% time-frequency distributions:
%
%    (i)   Short-Time Fourier Transform (STFT)
%    (ii)  Spectrogram
%    (iii) Wigner-Ville Distribution
%
% PARAMETERS:
%
%   TIME-FREQUENCY MATRIX
%
%	Input matrix containing the time-frequency distribution.
%
%   SIGNAL
%
%       Output synthesised (complex) signal from given time-frequency distribution.
%
%   WINDOW LENGTH
%
%      Length of the smoothing window used in the given distribution (or in the case of
%      of the WVD the lag window length).
%
%   ANALYSIS TYPE
%
%      Specifies which type of signal synthesis will be applied to the given TFD
%      matrix. The following analysis types are valid:
%
%      (i) STFT:
%
%         (a) Inverse Discrete Fourier Transform method.
%         (b) Overlap-Add method.
%         (c) Modified Short-Time Fourier Transform method.
%
%      (ii) Spectrogram:
%
%         Modified Spectrogram method
%
%      (iii) Wigner Ville Distribution:
%
%         Wigner Ville Distribution method. The original signal can be
%         specified to correct the phase of the synthesised signal.
%
%
%
%  See Also:  wvd, spec

author: HeLiangHIT


text:
function [sv,vis] = visibleSegment(s,d,imSize,mrg,lmin)

% VISIBLESEGMENT  Visible segment.
%   VISIBLESEGMENT(S,D,IMSIZE) returns the segment portion of segment S
%   that is visible in the image defined by IMSIZE. D is a vector of depths
%   of the two segment's endpoints.
%
%   VISIBLESEGMENT(...,MRG) restricts the image size to be smaller in MRG
%   pixels at its four borders. The default is MRG = 0 pix.
%
%   VISIBLESEGMENT(...,LMIN) sets all segments shorter than LMIN pixels to
%   be invisible. The default is LMIN = 1 pix.
%
%   [SV,VIS] = VISIBLESEGMENT(...) returns the visible segment SV and a
%   flag of visibility. In case of non visibility, the flag is set to false
%   and the output segment is SV = [0;0;0;0].
%
%   The function works for segment matrices S = [S1 S2 ... Sn] and D = [D1
%   D2 ... Dn], giving a segments matrix SV and a visibility vector VIS.

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

% input options and defaults
if nargin < 5
    lmin = 1;
    if nargin < 4
        mrg = 0;
    end
end

% init output arrays
n   = size(s,2);
sv  = zeros(4,n);
vis = false(1,n);

% loop all segments
for i = 1:n
    a = s(1:2,i); % endpoints
    b = s(3:4,i);
    ad = d(1,i);  % depths
    bd = d(2,i);

    if ad<0 && bd<0 % both depths negative -> not visible
        sv(:,i) = zeros(4,1);
        vis(i) = false;

    else

        u = normvec(b-a); % uncorrected direction
        if ad<0           % endpoint A is behind the camera
            a = b + 1e6*u;
        elseif bd<0       % endpoint B is behind the camera
            b = a - 1e6*u;
        end

        % trim segment at image borders, with margin
        ss = trimSegment([a;b],imSize,mrg);

        % check visibility and assign output
        if ...  % conditions for visibility (add with AND if needed)
                ~isempty(ss) ...           % no-null vector
                && (segLength(ss) >= lmin) % minimum length

            sv(:,i) = ss; % visible
            vis(i) = true;
        end
    end
end

return

%% test - generate 2 line handles
lmin = 10;
mrg = 0;
imSize = [100;100];
cla
axis([0,imSize(1),0,imSize(2)])
lh = line('color','r','linestyle','--')
yh = line('color','c','linewidth',3);

%% test - plot random lines
s = 300+randn(4,1)*400
% d = randn(2,1)

s = [-20;50;120;50]
d = [-1;-1]

[sv,vis] = visibleSegment(s,d,imSize,mrg,lmin)

set(lh,'xdata',s([1,3]),'ydata',s([2,4]))
set(yh,'xdata',sv([1,3]),'ydata',sv([2,4]))

% ========== 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