text:
function [ y, m, d ] = day_carry_gregorian ( y, m, d )

%*****************************************************************************80
%
%% DAY_CARRY_GREGORIAN carries days to months in a Gregorian date.
%
%  Discussion:
%
%    While ( number of days in M ) < D:
%      decrease the day D by the number of days in the month M;
%      increase M by 1;
%      if necessary, adjust Y.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 December 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, integer M, integer D, the YMD date.
%
%    Output, integer Y, integer M, integer D, the YMD date.
%    On output, D is between 1 and the number of days in M.
%
  days = month_length_gregorian ( y, m );

  while ( days < d )

    d = d - days;
    m = m + 1;
    days = month_length_gregorian ( y, m );
%
%  Make sure the month isn't too big.
%
    [ y, m ] = month_carry_gregorian ( y, m );

  end

  return
end


text:
function [s,it]=display(a,tab,it)

  global display_tree_depth;
  if isempty(display_tree_depth) display_tree_depth=100; end;
  global display_tree_tab_step;
  if isempty(display_tree_tab_step) display_tree_tab_step=3; end;
  global display_tree_show_brackets;
  if isempty(display_tree_show_brackets) display_tree_show_brackets=1; end;

  % ----- tabulation stuff ----------
  print=0;  if nargin==1  tab=0; print=1; it=[]; end;
  tab_step=display_tree_tab_step;
  % ------ display tree ------------
  [s,it]=display(a.algorithm,tab,it);
  if  display_tree_show_brackets
    s=[s ones(1,tab+min(2,tab_step))*32 '{\n' ];
  end
  tab=tab+tab_step;
  i=length(it); v=it{i}; v=[v 1]; it{i}=v; %% add 1 to last row
  for i=1:length(a.child)
     [st it]=display(a.child{i},tab,it);
     if length(it{length(it)})<display_tree_depth
      s =[s ones(1,tab)*32 st];
     end

     j=length(it); v=it{j}; v(length(v))=v(length(v))+1;
     it{j}=v; %% increment last row
  end
  if  display_tree_show_brackets
    if  length(it{length(it)})>=display_tree_depth
     s=[s ones(1,tab)*32 '...\n'];
    end
    s =[s ones(1,tab-tab_step+min(2,tab_step))*32 '}\n' ];
  end
  tab=tab-tab_step;
  %% pop index of last item
  i=length(it); v=it{length(it)}; v=v(1:length(v)-1); it{i}=v;
  if print
   s=s(1:length(s)-2); % remove last carriage return
   it=deal(it(1:length(it)-1)); % remove last index to tree
   disp(sprintf(char(s)));
  end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function this = plot_design_matrix(this)
% plots the design matrix scaled for display
%
%   Y = MrGlm()
%   Y.plot_design_matrix()
%
% This is a method of class MrGlm.
%
% IN
%
% OUT
%
% EXAMPLE
%   plot_design_matrix
%
%   See also MrGlm

% Author:   Saskia Bollmann & Lars Kasper
% Created:  2018-05-08
% Copyright (C) 2018 Institute for Biomedical Engineering
%                    University of Zurich and ETH Zurich
%
% This file is part of the TAPAS UniQC Toolbox, which is released
% under the terms of the GNU General Public License (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/>.
%

figure;
imagesc(this.designMatrix);
colormap gray;
title('design matrix');

end

author: translationalneuromodeling

repo: tapas


text:
% Gdsft_test.m
% Test the Gdsft object

% create Gdsft object
if ~isvar('A'), printm 'setup Gdsft_test'
	N = [32 30];
	M = 201;
	omega = linspace(0, 10*2*pi, M)'; % crude spiral:
	omega = pi*[cos(omega) sin(omega)].*omega(:,[1 1])/max(omega);
	pl = 330;
	if im, clf, subplot(pl+1), plot(omega(:,1), omega(:,2), '.'), end
	n_shift = N/2;

	mask = true(N);
	mask(1:5) = false; % stress

	if 1 % non-mex version
		A = Gdsft(omega, N, 'n_shift', n_shift, 'mask', mask, ...
			'use_mex', 0, 'class', 'fatrix2');
		fatrix2_tests(A, 'complex', 1)
		test_adjoint(A, 'complex', 1, 'big', 1);
	end

	classes = {'Fatrix', 'fatrix2'};
	for ic=1:numel(classes)
		cl = classes{ic};
		A = Gdsft(omega, N, 'n_shift', n_shift, 'nthread', 2, ...
			'mask', mask, 'class', cl);

		fatrix2_tests(A, 'complex', 1)
		test_adjoint(A, 'complex', 1, 'big', 1);
	end
end

% test data
if ~isvar('x'), printm 'setup data'
	x = zeros(N);
	x(5:25,10:25) = 1;
	x(15:20,15:20) = 2;
	x(15,5) = 2;
end

% compare forward
if 1
	yt = dtft(x, omega, 'n_shift', n_shift);
	yd = A * [x(mask) x(mask)]; % test with two
	yd = yd(:,1);
	equivs(yt, yd, 'thresh', 1.3e-6)
%	printf('forward max%%diff = %g', max_percent_diff(yt, yd))
end

% compare adjoint
if 1
	xt = mask .* dtft_adj(yt, omega, N, n_shift);
	xd = A' * [yt yt]; % test with two
	xd = xd(:,1);
	xd = embed(xd, mask);
	equivs(xt, xd)
%	printf('back max%%diff = %g', max_percent_diff(xt, xd))
end

if 1, printm 'test adjoint'
	As = Gdsft(omega, [7 8], 'n_shift', n_shift);
	test_adjoint(As, 'complex', 1);
end

if 1 % look at norm for small problem: sqrt(MN) is loose bound
	pr [norm(As) sqrt(prod(size(As))) sqrt(prod(As.idim))]
	Ad = Gdft('mask', true(As.idim));
	pr [norm(Ad) sqrt(prod(size(As))) sqrt(prod(Ad.idim))]
end

author: JeffFessler

repo: mirt

save_path: github-repos/MATLAB/JeffFessler-mirt


text:
function res = ge(a,b)
%GE           Implements  a >= b  for Taylor, compares only a.x and b.x
%

% written  05/21/09     S.M. Rump
%

  if ~isa(a,'taylor')
    res = ( a>=reshape(b.t(1,:),b.size) );
  elseif ~isa(b,'taylor')
    res = ( reshape(a.t(1,:),a.size)>=b );
  else
    res = ( reshape(a.t(1,:),a.size)>=reshape(b.t(1,:),b.size) );
  end

repo: OpenMAS


text:
function result = wildcardsearch(rootdir, searchstr, casesensitive, strict)
% WILDCARDSEARCH Searches the file system for files matching a wildcard
% pattern.
%    WILDCARDSEARCH(ROOTDIR, SEARCHSTRING) Searches the file system from
%    the starting directory ROOTDIR for files and folders matching the
%    pattern SEARCHSTRING. The function WILDCARDSEARCH is similar to the
%    search file option in Explorer.
%
%    WILDCARDSEARCH(ROOTDIR, SEARCHSTRING, CASESENSITIVE) The extra boolean
%    CASESENSITIVE allows for case senstive searching of files and folders.
%
%    WILDCARDSEARCH(ROOTDIR, SEARCHSTRING, CASESENSITIVE, STRICT) The extra
%    boolean STRICT allows for only precise matches to be returned. The
%    default behaviour is loose.
%
%    Example:
%     rootdir = 'C:\'
%     searchstr = '*.jpg;*.tif';
%     files = wildcardsearch(rootdir, searchstr);
%
%    This wil return all JPG and TIF files on the C:\ drive and maybe some
%    folders or files also matching this pattern e.g. 'somefile.jpg.old'
%
%    Example:
%     rootdir = 'C:\'
%     searchstr = 'MatLab';
%     files = wildcardsearch(rootdir, searchstr, true);
%
%    This wil return only return files or folders matching the pattern
%    'MatLab'. This could also match a file named 'MatLabRC'.
%
%    Example:
%     rootdir = 'C:\'
%     searchstr = '*\matlab';
%     files = wildcardsearch(rootdir, searchstr, true, true);
%
%    This wil return only return files named exactly 'matlab'.
%
%    Example:
%     rootdir = 'C:\'
%     searchstr = '*\';
%     files = wildcardsearch(rootdir, searchstr, true, true);
%
%    To find only folders do a strict search and end your search string
%    with the file separator (\ on Windows, / on UNIX). The above example
%    will return a complete directory tree of the C-drive.
%
%    Have a look at the source code for more information. For more
%    info on this function and how to use it, bug reports, feature
%    requests, etc. feel free to contact the author.
%
%    See also REGEXPDIR

%==========================================================================
% B.C. Hamans (b.c.hamans@rad.umcn.nl)                                 2007
%==========================================================================

% Check input
error(nargchk(2, 4, nargin));

% Create the regular expression
beginstr='('; endstr=')';
if ~exist('strict','var'); strict = false; end
if strict; beginstr=['^' beginstr]; endstr=[endstr '$']; end
if ~exist('casesensitive','var'); casesensitive = false; end
if casesensitive; beginstr = ['(?-i)' beginstr]; end
regexpstr=[beginstr strrep(regexptranslate('wildcard', searchstr), pathsep, [endstr '|' beginstr]) endstr];

% Search
result = regexpdir(rootdir, regexpstr, true);

%==========================================================================
% Changelog:
% 03-09-2007 v1.00 (BCH)  Initial release
%==========================================================================

repo: REST


text:
function outp = newcnstr( prob, x, y, op )
persistent map_eq map_le map_ge map_ne

%
% Check problem
%

if ~isa( prob, 'cvxprob' ),
    error( 'A cvx problem must be created first.' );
end
global cvx___
p = index( prob );

%
% Check arguments
%

cx = isnumeric( x ) | isa( x, 'cvx' );
cy = isnumeric( y ) | isa( y, 'cvx' );
if ~cx,
    x = cvx_collapse( x, false, true );
    cx = isnumeric( x ) | isa( x, 'cvx' );
end
if ~cy,
    y = cvx_collapse( y, false, true );
    cy = isnumeric( y ) | isa( y, 'cvx' );
end
sx = size( x );
sy = size( y );
if ~cx || ~cy,
    if cx || cy || op(1) ~= '=',
        error( 'Invalid CVX constraint: {%s} %s {%s}', class( x ), op, class( y ) );
    elseif ~isequal( sx, sy ),
        error( 'The left- and right-hand sides have incompatible sizes.' );
    else
        nx = prod( sx );
        for k = 1 : nx,
            newcnstr( prob, x{k}, y{k}, op );
        end
        if nargout,
            outp = cvxcnst( prob );
        end
        return
    end
end
xs = all( sx == 1 );
ys = all( sy == 1 );
if ~xs && ~ys && ~isequal( sx, sy ),
    error( 'Matrix dimensions must agree.' );
end

%
% Check readlevel
%

tx = cvx_readlevel( x );
ty = cvx_readlevel( y );
tx = any( tx( : ) > p );
ty = any( ty( : ) > p );
if tx || ty,
    error( 'Constraints may not involve internal, read-only variables.' );
end

%
% Check for a dual reference
%

if isa( x, 'cvx' ),
    dx = getdual( x );
else
    dx = '';
end
if isa( y, 'cvx' ),
    dy = getdual( y );
else
    dy = '';
end
if isempty( dx ),
    dx = dy;
elseif ~isempty( dy ),
    error( [ 'Two dual variables found: "', dx, '","', dy, '"' ] );
end
if ~isempty( dx ),
    duals = cvx___.problems( p ).duals;
    try
        dual = builtin( 'subsref', duals, dx );
    catch
        nm = cvx_subs2str( dx );
        error( [ 'Dual variable "', nm(2:end), '" has not been declared.' ] );
    end
    if ~isempty( dual ),
        nm = cvx_subs2str( dx );
        error( [ 'Dual variable "', nm(2:end), '" already in use.' ] );
    end
end

%
% Handle the SDP case
%

sdp_mode = false;
mx = sx( 1 ) > 1 & sx( 2 ) > 1;
my = sy( 1 ) > 1 & sy( 2 ) > 1;
if op(1) ~= '=' && cvx___.problems( p ).sdp && ( mx || my ),

    if sx( 1 ) ~= sx( 2 ) || sy( 1 ) ~= sy( 2 ),
        error( 'SDP constraint must be square.' );
    elseif xs && cvx_isnonzero( x ),
        error( 'SDP constraint {scalar} %s {matrix} valid only if the scalar is zero.', op );
    elseif ys && cvx_isnonzero( y ),
        error( 'SDP constraint {matrix} %s {scalar} valid only if the scalar is zero.', op );
    elseif ~cvx_isaffine( x ) || ~cvx_isaffine( y ),
        error( 'Both sides of an SDP constraint must be affine.' );
    elseif op( 1 ) == '>',
        x = minus( x, y );
        y = semidefinite( size( x ), ~isreal( x ) );
        sz = size( x );
    else
        y = minus( y, x );
        x = semidefinite( size( y ), ~isreal( y ) );
        sz = size( y );
    end
    op = '==';
    sdp_mode = true;

else

    if isempty( map_ge ),
        temp    = cvx_remap( 'constant' );
        temp    = ~ ( temp' * temp );

        map_ne  = cvx_remap;

        map_eq2 = cvx_remap( 'log-affine' );
        map_eq2 = ( map_eq2' * map_eq2 ) & temp;
        map_eq3 = cvx_remap( 'affine' );
        map_eq3 = map_eq3' * map_eq3;
        map_eq  = 2 * map_eq2 + map_eq3;

        % Trivially feasible constraints
        map_ge1 = ( cvx_remap( 'log-concave' )' * cvx_remap( 'nonpositive' ) ) & temp;
        % Trivially infeasible constraints
        map_ge2 = ( cvx_remap( 'nonpositive' )' * cvx_remap( 'log-convex'  ) ) & temp;
        % Full geometric constraints
        map_ge3  = ( cvx_remap( 'log-concave' )' * cvx_remap( 'log-convex'  ) ) & temp;
        % Linear constraints
        map_ge4 = ( cvx_remap( 'concave' )' * cvx_remap( 'convex' ) ) & ~map_ge3;
        map_ge = map_ge4 + 2 * map_ge3 + 3 * map_ge2 + 4 * map_ge1;

        map_le = map_ge';
    end
    switch op(1),
        case '<',
            remap = map_le;
        case '>',
            remap = map_ge;
        case '~',
            remap = map_ne;
        otherwise,
            remap = map_eq;
    end
    vx = cvx_classify( x );
    vy = cvx_classify( y );
    vm = vx + size( remap, 1 ) * ( vy - 1 );
    vr = remap( vm );
    tt = vr( : ) == 0;
    if any( tt ),
        [ vu, vi ] = unique( vm );
        vi = vi( remap( vu ) == 0 );
        strs = {};
        xt = x; yt = y;
        for k = 1 : length( vi ),
            if any( sx ~= 1 ), xt = x(vi(k)); end
            if any( sy ~= 1 ), yt = y(vi(k)); end
            strs{k+1} = sprintf( '\n   Invalid constraint: {%s} %s {%s}', cvx_class( xt, false, true ), op, cvx_class( yt, false, true ) );
        end
        error( [ sprintf( 'Disciplined convex programming error:' ), strs{:} ] );
    end
    tt = vr( : ) == 2;
    if any( tt ),
        if all( tt ),
            x = log( x );
            y = log( y );
        else
            if isscalar( x ), x = x * ones(size(y)); end
            if isscalar( y ), y = y * ones(size(x)); end
            x( tt ) = log( x( tt ) );
            y( tt ) = log( y( tt ) );
        end
    end
    tt = vr( : ) == 3;
    if any( tt ),
        x( tt ) = 0;
        y( tt ) = 1 - 2 * ( op(1) == '<' );
    end
    tt = vr( : ) == 4;
    if any( tt ),
        x( tt ) = 0;
        y( tt ) = 1 - 2 * ( op(1) == '>' );
    end
end

%
% Eliminate lexical redundancies
%

if op(1) == '<',
    z = minus( y, x );
    op(1) = '>';
else
    z = minus( x, y );
end
if op( 1 ) == '=' || sdp_mode,
    cmode = 'full';
else
    cmode = 'magnitude';
end
[ zR, zL, zS ] = bcompress( z, cmode );
if sdp_mode,
    if isreal( zR ),
        nnq = 0.5 * sz( 1 ) * ( sz( 1 ) + 1 );
    else
        nnq = sz( 1 ) * sz( 1 );
    end
    if size( zR, 1 ) > nnq * prod( sz( 3 : end ) ),
        warning( 'CVX:UnsymmetricLMI', [ ...
            'This linear matrix inequality appears to be unsymmetric. This is\n', ...
            'very likely an error that will produce unexpected results. Please check\n', ...
            'the LMI; and, if necessary, re-enter the model.' ], 1 );
    end
end

%
% Add the (in)equalities
%

touch( prob, zL, op(1) == '=' );
mO = length( cvx___.equalities );
mN = length( zL );
cvx___.equalities = vertcat( cvx___.equalities, zL );
cvx___.needslack( end + 1 : end + mN, : ) = op( 1 ) ~= '=';

%
% Create the dual
%

if ~isempty( dx ),
    zI = cvx_invert_structure( zR )';
    zI = sparse( mO + 1 : mO + mN, 1 : mN, 1 ) * zI;
    zI = cvx( zS, zI );
    duals = cvx___.problems( p ).duals;
    duals = builtin( 'subsasgn', duals, dx, zI );
    cvx___.problems( p ).duals = duals;
end

%
% Create the output object
%

if nargout,
    outp = cvxcnst( prob );
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.


text:
function [F, isArrayValued] = quasi2cheb(F)
%QUASI2CHEB   Convert a quasimatrix to an array-valued CHEBFUN.
%   QUASI2CHEB(F) converts the quasimatrix F to an array-valued CHEBFUN by
%   taking the union of the domains of each of the columns.
%
%   [G, ISARRAYVALUED] = QUASI2CHEB(F) returns a second output with the value
%   TRUE if G is a CHEBFUN (i.e,. numel(G) == 1), and FALSE if G remains a
%   quasimatrix.
%
% See also QUASIMATRIX, CHEB2QUASI, NUM2CELL.

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

if ( numel(F) < 2 )
    % F is already a quasimatrix!
    isArrayValued = 1;
    return
end

% Unify the breakpoints:
F = restrict(F, get(F, 'domain'));

% Collect each column in a cell:
F = cheb2cell(F);

% Call CAT to collate the columns:
F = cat(2 - F{1}.isTransposed, F{:});

isArrayValued = numel(F) == 1;

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
%==========================================================================
% This is the testing code of IRCNN for color image demosaiking.
%
%  @inproceedings{zhang2017learning,
%    title={Learning Deep CNN Denoiser Prior for Image Restoration},
%    author={Zhang, Kai and Zuo, Wangmeng and Gu, Shuhang and Zhang, Lei},
%    booktitle={IEEE Conference on Computer Vision and Pattern Recognition},
%    pages={3929--3938},
%    year={2017},
%  }
%
% If you have any question, please feel free to contact with <Kai Zhang (cskaizhang@gmail.com)>.
%
% -----------McMaster18--------
% --Set18----Color Demosaiking-
% -----------------------------
% 01.tif  --  30.26dB  --  0.93
% 02.tif  --  35.26dB  --  0.94
% 03.tif  --  34.69dB  --  0.97
% 04.tif  --  38.37dB  --  0.99
% 05.tif  --  35.09dB  --  0.95
% 06.tif  --  39.19dB  --  0.97
% 07.tif  --  39.66dB  --  0.98
% 08.tif  --  39.44dB  --  0.97
% 09.tif  --  38.64dB  --  0.96
% 10.tif  --  39.51dB  --  0.97
% 11.tif  --  40.46dB  --  0.97
% 12.tif  --  38.86dB  --  0.96
% 13.tif  --  40.71dB  --  0.95
% 14.tif  --  38.99dB  --  0.96
% 15.tif  --  39.47dB  --  0.96
% 16.tif  --  34.39dB  --  0.95
% 17.tif  --  34.79dB  --  0.96
% 18.tif  --  36.21dB  --  0.96
% Average PSNR and SSIM
%    37.4447dB    0.9614

% ----------Kodak24-----------------
% ----Set24-----Color Demosaiking---
% ----------------------------------
% kodim01.png  --  40.30dB  --  0.99
% kodim02.png  --  39.79dB  --  0.97
% kodim03.png  --  43.63dB  --  0.98
% kodim04.png  --  41.21dB  --  0.98
% kodim05.png  --  39.24dB  --  0.99
% kodim06.png  --  40.54dB  --  0.99
% kodim07.png  --  43.26dB  --  0.99
% kodim08.png  --  37.70dB  --  0.98
% kodim09.png  --  42.07dB  --  0.97
% kodim10.png  --  42.03dB  --  0.98
% kodim11.png  --  40.55dB  --  0.98
% kodim12.png  --  42.96dB  --  0.98
% kodim13.png  --  36.94dB  --  0.98
% kodim14.png  --  38.98dB  --  0.98
% kodim15.png  --  40.59dB  --  0.97
% kodim16.png  --  43.05dB  --  0.99
% kodim17.png  --  41.38dB  --  0.98
% kodim18.png  --  38.15dB  --  0.98
% kodim19.png  --  40.63dB  --  0.98
% kodim20.png  --  41.30dB  --  0.98
% kodim21.png  --  40.27dB  --  0.98
% kodim22.png  --  39.14dB  --  0.98
% kodim23.png  --  43.05dB  --  0.98
% kodim24.png  --  36.22dB  --  0.98
% Average PSNR and SSIM
%    40.5409dB    0.9806
%
% by Kai Zhang (1/2018)
%==========================================================================

clear; clc;

addpath('utilities');
imageSets    = {'Set18','Set24'}; % testing dataset
setTest      = imageSets(1); % select the dataset

useGPU       = 1;

folderTest   = 'testsets';
folderResult = 'results';
folderModel  = 'models';
if ~exist(folderResult,'file')
    mkdir(folderResult);
end
setTestCur = cell2mat(setTest(1));
disp('--------------------------------------------');
disp(['----',setTestCur,'--Color Image Demosaiking--']);
disp('--------------------------------------------');
folderTestCur = fullfile(folderTest,setTestCur);

% folder to store results
folderResultCur = fullfile(folderResult, ['Demosaik_',setTestCur]);
if ~exist(folderResultCur,'file')
    mkdir(folderResultCur);
end

%% Noise level
noiselevel = 0; % default; noiselevel = 10; Isigma     = 10/255; Msigma     = 8;

%% parameter setting in HQS (tune the following parameters to obtain the best results)
%% -------------------important!------------------
% Parameter settings of IRCNN
% (1) image noise level: Isigma
Isigma     = 0.5/255; % default 0.5/255 for noise-free image, ****** from interval [1/255, 20/255] ******; e.g., 1/255, 2.55/255, 7/255, 11/255
% (2) noise level of the last denoiser: Msigma
Msigma     = 2; % default 2 for noise-free image, ****** from {1 2 3 4 5 7 9 11 13 15} ******
%--------------------------------------------------------

%% load denoisers
load(fullfile(folderModel,'modelcolor.mat'));

%% default parameter setting in HQS
totalIter   = 30; % default 30
lamda       = (Isigma^2)/3; % default 3, ****** from {1 2 3 4} ******
modelSigma1 = 49; % default 49
modelSigmaS = logspace(log10(modelSigma1),log10(Msigma),totalIter);
rho         = Isigma^2/((modelSigma1/255)^2);

ns          = min(25,max(ceil(modelSigmaS/2),1));
ns          = [ns(1)-1,ns];

ext                 =  {'*.jpg','*.png','*.bmp','*.tif'};
filepaths           =  [];
for i = 1 : length(ext)
    filepaths = cat(1,filepaths,dir(fullfile(folderTestCur, ext{i})));
end

PSNRs = zeros(1,length(filepaths));
SSIMs = zeros(1,length(filepaths));

for i = 1 : length(filepaths)

    label  = imread(fullfile(folderTestCur,filepaths(i).name));
    [~, Iname, ext] = fileparts(filepaths(i).name);
    label = im2single(label);

    % generate mask
    [B, y, mask] = mosaic_bayer(label, 'grbg', noiselevel);
    y    = single(y);
    mask = single(mask);
    z = linearlcc(B, 0);
    z =  single(z);

    z0          = z;
    if useGPU
        z       = gpuArray(z);
        y       = gpuArray(y);
    end

    for itern = 1:totalIter

        % step 1
        rho = lamda*255^2/(modelSigmaS(itern)^2);
        z   = (y+rho*z)./(mask+rho);

        if ns(itern+1)~=ns(itern)
            [net] = loadmodel(modelSigmaS(itern),CNNdenoiser);
            net = vl_simplenn_tidy(net);
            if useGPU
                net = vl_simplenn_move(net, 'gpu');
            end
        end

        % step 2
        res = vl_simplenn(net, z,[],[],'conserveMemory',true,'mode','test');
        residual = res(end).x;
        z = z - residual;

        %         imshow(z)
        %         title(int2str(itern))
        %         drawnow;
    end

    if useGPU
        output = im2uint8(gather(z));
        y      = im2uint8(gather(y));
    end

    %output(mask==1) = y(mask==1);

    [PSNR_Cur,SSIM_Cur] = Cal_PSNRSSIM(im2uint8(label),output,10,10);

    PSNRs(i) = PSNR_Cur;
    SSIMs(i) = SSIM_Cur;

    imshow(cat(2,y,output));
    drawnow;
    pause(0.001);

    disp([filepaths(i).name,'  --  ', num2str(PSNR_Cur,'%2.2f'),'dB  --  ', num2str(SSIM_Cur,'%2.2f')]);
    %     imwrite(y,fullfile(folderResultCur,[Iname,'_mosaik.png']));
    %     imwrite(output,fullfile(folderResultCur,[Iname,'_ircnn.png']));

end

disp('Average PSNR and SSIM')
disp([mean(PSNRs),mean(SSIMs)]);

author: cszn

repo: IRCNN

save_path: github-repos/MATLAB/cszn-IRCNN


text:
%                            [ADA,absd] = getada3(ADA, A,Ajc1,Aord, udsqr,K)
% GETADA3  Compute ADA(i,j) = (D(d^2)*A.t(:,i))' *A.t(:,j),
%   and exploit sparsity as much as possible.
%   absd - length m output vector, containing
%     absd(i) = abs((D(d^2)*A.t(:,i))' *abs(A.t(:,i)).
%     Hence, diag(ADA)./absd gives a measure of cancelation (in [0,1]).
%
% ******************** INTERNAL FUNCTION OF SEDUMI ********************
%
% See also sedumi, getada1, getada2

function [ADA,absd] = getada3(ADA, A,Ajc1,Aord, udsqr,K) %#ok
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
%   Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
%   CRL, McMaster University, Canada.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc.,  51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%

disp('The SeDuMi binaries are not installed.')
disp('In Matlab, launch "install_sedumi" in the folder you put the SeDuMi files.')
disp('For more information see the file Install.txt.')
error(' ')


text:
function mri = ft_defacevolume(cfg, mri)

% FT_DEFACEVOLUME allows you to de-identify an anatomical MRI by erasing specific
% regions, such as the face and ears. The interactive graphical user interface allows
% you to position a box over the anatomical data inside which all anatomical voxel
% values will be replaced by zero. You might have to call this function multiple
% times when both face and ears need to be removed. Following defacing, you should
% check the result with FT_SOURCEPLOT.
%
% Use as
%   mri = ft_defacevolume(cfg, mri)
%
% The configuration can contain the following options
%   cfg.method     = 'interactive', 'spm' (default = 'interactive')
%
% If you specify the box method, the following options apply
%   cfg.translate  = initial position of the center of the box (default = [0 0 0])
%   cfg.scale      = initial size of the box along each dimension (default is automatic)
%   cfg.rotate     = initial rotation of the box (default = [0 0 0])
%   cfg.selection  = which voxels to keep, can be 'inside' or 'outside' (default = 'outside')
%   cfg.smooth     = 'no' or the FWHM of the gaussian kernel in voxels (default = 'no')
%   cfg.keepbrain  = 'no' or 'yes', segment and retain the brain (default = 'no')
%   cfg.feedback   = 'no' or 'yes', whether to provide graphical feedback (default = 'no')
%
% If you specify no smoothing, the selected area will be zero-masked. If you
% specify a certain amount of smoothing (in voxels FWHM), the selected area will
% be replaced by a smoothed version of the data.
%
% The spm method does not have any options, it uses SPM_DEFACE from the
% SPM12 toolbox.
%
% See also FT_ANONYMIZEDATA, FT_DEFACEMESH, FT_ANALYSISPIPELINE, FT_SOURCEPLOT

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

% these are used by the ft_preamble/ft_postamble function and scripts
ft_revision = '$Id$';
ft_nargin   = nargin;
ft_nargout  = nargout;

% do the general setup of the function
ft_defaults
ft_preamble init
ft_preamble debug
ft_preamble loadvar    mri
ft_preamble provenance mri

% the ft_abort variable is set to true or false in ft_preamble_init
if ft_abort
  return
end

% for backward compatibility
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'box', 'interactive'});

% set the defaults
cfg.method         = ft_getopt(cfg, 'method', 'interactive');
cfg.rotate         = ft_getopt(cfg, 'rotate', [0 0 0]);
cfg.scale          = ft_getopt(cfg, 'scale'); % the automatic default is determined further down
cfg.translate      = ft_getopt(cfg, 'translate', [0 0 0]);
cfg.transformorder = ft_getopt(cfg, 'transformorder', {'scale', 'rotate', 'translate'}); % T*R*S
cfg.selection      = ft_getopt(cfg, 'selection', 'outside');
cfg.smooth         = ft_getopt(cfg, 'smooth', 'no');
cfg.keepbrain      = ft_getopt(cfg, 'keepbrain', 'no');
cfg.feedback       = ft_getopt(cfg, 'feedback', 'no');

ismri  = ft_datatype(mri, 'volume') && isfield(mri, 'anatomy');
ismesh = isfield(mri, 'pos'); % triangles are optional

if ismri
  % check if the input data is valid for this function
  mri = ft_checkdata(mri, 'datatype', 'volume', 'feedback', 'yes');
end

switch cfg.method
  case 'spm'
    % this requires SPM12 on the path
    ft_hastoolbox('spm12', 1);

    % defacing relies on coregistration, which relies on the MRI being reasonably aligned for SPM
    mri = ft_checkdata(mri, 'hascoordsys', 'yes');

    % remember the original transformation matrix and coordinate system
    original = [];
    original.transform = mri.transform;
    original.coordsys  = mri.coordsys;
    mri = ft_convert_coordsys(mri, 'acpc');

    filename1 = {[tempname '.nii']};
    ft_write_mri(filename1{1}, mri, 'dataformat', 'nifti');

    % % apply a least squares pre-alignment step in order to make spm_deface more robust
    % % this could be done conditional on the modality/contrast, which is part of the BIDS filename
    % template = spm_vol(fullfile(spm('Dir'),'canonical','avg152PD.nii'));
    % template = spm_vol(fullfile(spm('Dir'),'canonical','avg152T1.nii'));
    % template = spm_vol(fullfile(spm('Dir'),'canonical','avg152T2.nii'));
    % filevol = spm_vol(filename1{1});
    % M = spm_affreg(template, filevol);
    % spm_get_space(filename1{1}, M * filevol.mat);

    filename2 = spm_deface(filename1);
    mri = ft_read_mri(filename2{1});

    % put the original transformation matrix and coordinate system back
    mri.transform = original.transform;
    mri.coordsys = original.coordsys;

    % clean up the temporary files
    delete(filename1{1});
    delete(filename2{1});

  case 'interactive'
    % this is an alternative implementation of the interactive method usinf FT_INTERACTIVEREALIGN
    % it aligns a box to the MRI or mesh, and then removes the points inside that box

    if ismri
      % enhance the contrast of the volumetric data, see also FT_VOLUMEREALIGN
      dat  = double(mri.anatomy);
      dum  = unique(dat(:));
      dmin = dum(round(0.05*numel(dum))); % take the 5% value of the histogram
      dmax = dum(round(0.95*numel(dum))); % take the 95% value of the histogram
      dat  = (dat-dmin)./(dmax-dmin);
      mri.anatomy = dat;
    end

    % construct a box with a unit length expressed in the units of the input mri or mesh
    % rather than using a triangulation, this specifies polygons for each of the 6 edges of the box
    box.unit = mri.unit;
    box.pos = [
       1  1  1
       1 -1  1
      -1 -1  1
      -1  1  1
       1  1 -1
       1 -1 -1
      -1 -1 -1
      -1  1 -1
      ]/2;
    box.poly = [
      1 2 3 4
      1 5 6 2
      2 6 7 3
      3 7 8 4
      4 8 5 1
      5 8 7 6
      ];

    % the default is to scale the box to 75 mm (or equivalent)
    defaultscale = [75 75 75] * ft_scalingfactor('mm', mri.unit);
    surfaceonly = isfield(mri, 'tet') | isfield(mri, 'hex'); % only for tetrahedral or hexahedral meshes

    tmpcfg = keepfields(cfg, {'scale', 'rotate', 'translate', 'transformorder'});
    tmpcfg.scale = ft_getopt(cfg, 'scale', defaultscale);
    tmpcfg.showlight = 'no';
    tmpcfg.showalpha = 'no'; % do not use a global alpha level
    tmpcfg.showapply = 'no'; % do not show the apply button
    tmpcfg.template.axes = 'yes';
    if ismri
      tmpcfg.template.mri = mri;
    elseif ismesh
      tmpcfg.template.mesh = mri;
    end
    tmpcfg.individual.mesh = box;
    tmpcfg.individual.meshstyle = {'edgecolor', 'k', 'facecolor', 'y', 'facealpha', 0.3, 'surfaceonly', surfaceonly};
    tmpcfg = ft_interactiverealign(tmpcfg);

    % remember these for potential reuse outside of this function
    cfg.rotate    = tmpcfg.rotate;
    cfg.scale     = tmpcfg.scale;
    cfg.translate = tmpcfg.translate;

    % the template remains fixed, the individual is moved around
    R = rotate   (cfg.rotate);
    T = translate(cfg.translate);
    S = scale    (cfg.scale);
    % this is the transformation to get from the individual to the template
    transform = combine_transform(R, S, T, cfg.transformorder);

    if ismri
      % rather than converting the box to the MRI, do it the other way around
      [X, Y, Z] = ndgrid(1:mri.dim(1), 1:mri.dim(2), 1:mri.dim(3));
      voxpos = ft_warp_apply(mri.transform, [X(:) Y(:) Z(:)]);  % voxel positions in head coordinates
      voxpos = ft_warp_apply(inv(transform), voxpos);           % voxel positions in box coordinates

      remove = ...
        voxpos(:,1) > -0.5 & ...
        voxpos(:,1) < +0.5 & ...
        voxpos(:,2) > -0.5 & ...
        voxpos(:,2) < +0.5 & ...
        voxpos(:,3) > -0.5 & ...
        voxpos(:,3) < +0.5;

    elseif ismesh || issource
      % rather than converting the box to the mesh, do it the other way around
      meshpos = ft_warp_apply(inv(transform), mri.pos);         % vertex positions in box coordinates

      remove = ...
        meshpos(:,1) > -0.5 & ...
        meshpos(:,1) < +0.5 & ...
        meshpos(:,2) > -0.5 & ...
        meshpos(:,2) < +0.5 & ...
        meshpos(:,3) > -0.5 & ...
        meshpos(:,3) < +0.5;
    end

    if strcmp(cfg.selection, 'inside')
      % invert the selection, i.e., keep the voxels inside the box
      remove = ~remove;
    end

    if ismri
      if istrue(cfg.keepbrain)
        tmpcfg = [];
        tmpcfg.output = {'brain'};
        seg = ft_volumesegment(tmpcfg, mri);
        fprintf('keeping voxels in brain segmentation\n');
        % keep the tissue of the brain
        remove(seg.brain) = 0;
        clear seg
      end

      if istrue(cfg.feedback)
        tmpmri = keepfields(mri, {'anatomy', 'transform', 'coordsys', 'units', 'dim'});
        tmpmri.remove = remove;
        tmpcfg = [];
        tmpcfg.funparameter = 'remove';
        ft_sourceplot(tmpcfg, tmpmri);
      end

      if isequal(cfg.smooth, 'no')
        fprintf('zero-filling %.0f%% of the volume\n', 100*mean(remove));
        mri.anatomy(remove) = 0;
      else
        tmp = mri.anatomy;
        tmp = (1 + 0.5.*randn(size(tmp))).*tmp; % add 50% noise to each voxel
        tmp = volumesmooth(tmp, cfg.smooth, 'anatomy');
        fprintf('smoothing %.0f%% of the volume\n', 100*mean(remove));
        mri.anatomy(remove) = tmp(remove);
      end

    elseif ismesh
      % determine all fields that might need to be defaced
      fn = setdiff(fieldnames(mri), ignorefields('deface'));
      dimord = cell(size(fn));
      for i=1:numel(fn)
        dimord{i} = getdimord(mri, fn{i});
      end
      % this applies to headshapes and meshes in general
      fprintf('keeping %d and removing %d vertices in the mesh\n', sum(remove==0), sum(remove==1));
      if isfield(mri, 'tri')
        [mri.pos, mri.tri] = remove_vertices(mri.pos, mri.tri, remove);
      elseif isfield(mri, 'tet')
        [mri.pos, mri.tet] = remove_vertices(mri.pos, mri.tet, remove);
      elseif isfield(mri, 'hex')
        [mri.pos, mri.hex] = remove_vertices(mri.pos, mri.hex, remove);
      else
        mri.pos = mri.pos(~remove,1:3);
      end
      for i=1:numel(fn)
        dimtok = tokenize(dimord{i}, '_');
        % do some sanity checks
        if any(strcmp(dimtok, '{pos}'))
          ft_error('not supported');
        end
        if numel(dimtok)>5
          ft_error('too many dimensions');
        end
        % remove the same positions from each matching dimension
        if numel(dimtok)>0 && strcmp(dimtok{1}, 'pos')
          mri.(fn{i}) = mri.(fn{i})(~remove,:,:,:,:);
        end
        if numel(dimtok)>1 && strcmp(dimtok{2}, 'pos')
          mri.(fn{i}) = mri.(fn{i})(:,~remove,:,:,:);
        end
        if numel(dimtok)>2 && strcmp(dimtok{3}, 'pos')
          mri.(fn{i}) = mri.(fn{i})(:,:,~remove,:,:);
        end
        if numel(dimtok)>3 && strcmp(dimtok{4}, 'pos')
          mri.(fn{i}) = mri.(fn{i})(:,:,:,~remove,:);
        end
        if numel(dimtok)>4 && strcmp(dimtok{5}, 'pos')
          mri.(fn{i}) = mri.(fn{i})(:,:,:,:,~remove);
        end
      end % for fn
      mri = removefields(mri, {'dim', 'transform'}); % these fields don't apply any more
    end % ismesh

  otherwise
    ft_error('unsupported method');
end % switch method

% do the general cleanup and bookkeeping at the end of the function
ft_postamble debug
ft_postamble previous mri
ft_postamble provenance mri
ft_postamble history mri
ft_postamble savevar mri

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function varargout = lvd_EditFixedInFrameVectorGUI(varargin)
% LVD_EDITFIXEDINFRAMEVECTORGUI MATLAB code for lvd_EditFixedInFrameVectorGUI.fig
%      LVD_EDITFIXEDINFRAMEVECTORGUI, by itself, creates a new LVD_EDITFIXEDINFRAMEVECTORGUI or raises the existing
%      singleton*.
%
%      H = LVD_EDITFIXEDINFRAMEVECTORGUI returns the handle to a new LVD_EDITFIXEDINFRAMEVECTORGUI or the handle to
%      the existing singleton*.
%
%      LVD_EDITFIXEDINFRAMEVECTORGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in LVD_EDITFIXEDINFRAMEVECTORGUI.M with the given input arguments.
%
%      LVD_EDITFIXEDINFRAMEVECTORGUI('Property','Value',...) creates a new LVD_EDITFIXEDINFRAMEVECTORGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before lvd_EditFixedInFrameVectorGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to lvd_EditFixedInFrameVectorGUI_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 lvd_EditFixedInFrameVectorGUI

% Last Modified by GUIDE v2.5 12-Jan-2021 12:32:12

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @lvd_EditFixedInFrameVectorGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @lvd_EditFixedInFrameVectorGUI_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 lvd_EditFixedInFrameVectorGUI is made visible.
function lvd_EditFixedInFrameVectorGUI_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 lvd_EditFixedInFrameVectorGUI (see VARARGIN)

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

    centerUIFigure(hObject);

    vector = varargin{1};
    setappdata(hObject, 'vector', vector);

    lvdData = varargin{2};
    setappdata(hObject, 'lvdData', lvdData);

	populateGUI(handles, vector);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, vector)
    set(handles.vectorNameText,'String',vector.getName());
    setappdata(handles.lvd_EditFixedInFrameVectorGUI,'frame',vector.frame);

    frame = vector.getFrame();
    handles.refFrameTypeCombo.String = ReferenceFrameEnum.getListBoxStr();
    handles.refFrameTypeCombo.Value = ReferenceFrameEnum.getIndForName(frame.typeEnum.name);
    handles.setFrameOptionsButton.TooltipString = sprintf('Current Frame: %s', frame.getNameStr());

    rVect = vector.getRVect();
    set(handles.xCoordText,'String',fullAccNum2Str(rVect(1)));
    set(handles.yCoordText,'String',fullAccNum2Str(rVect(2)));
    set(handles.zCoordText,'String',fullAccNum2Str(rVect(3)));

    handles.vectorLineColorCombo.String = ColorSpecEnum.getListboxStr();
    handles.vectorLineColorCombo.Value = ColorSpecEnum.getIndForName(vector.lineColor.name);

    handles.vectorLineSpecCombo.String = LineSpecEnum.getListboxStr();
    handles.vectorLineSpecCombo.Value = LineSpecEnum.getIndForName(vector.lineSpec.name);

% --- Outputs from this function are returned to the command line.
function varargout = lvd_EditFixedInFrameVectorGUI_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
    if(isempty(handles))
        varargout{1} = false;
    else
        vector = getappdata(hObject, 'vector');

        vector.setName(handles.vectorNameText.String);

        x = str2double(get(handles.xCoordText,'String'));
        y = str2double(get(handles.yCoordText,'String'));
        z = str2double(get(handles.zCoordText,'String'));
        vector.setRVect([x;y;z]);

        vector.frame = getappdata(hObject,'frame');

        str = handles.vectorLineColorCombo.String{handles.vectorLineColorCombo.Value};
        vector.lineColor = ColorSpecEnum.getEnumForListboxStr(str);

        str = handles.vectorLineSpecCombo.String{handles.vectorLineSpecCombo.Value};
        vector.lineSpec = LineSpecEnum.getEnumForListboxStr(str);

        varargout{1} = true;
        close(handles.lvd_EditFixedInFrameVectorGUI);
    end

% --- Executes on button press in saveAndCloseButton.
function saveAndCloseButton_Callback(hObject, eventdata, handles)
% hObject    handle to saveAndCloseButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    errMsg = validateInputs(handles);

    if(isempty(errMsg))
        uiresume(handles.lvd_EditFixedInFrameVectorGUI);
    else
        msgbox(errMsg,'Invalid Vector Inputs','error');
    end

function errMsg = validateInputs(handles)
    errMsg = {};

    xval = str2double(get(handles.xCoordText,'String'));
    enteredStr = get(handles.xCoordText,'String');
    numberName = 'X Coordinate';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(xval, numberName, lb, ub, isInt, errMsg, enteredStr);

    yval = str2double(get(handles.yCoordText,'String'));
    enteredStr = get(handles.yCoordText,'String');
    numberName = 'Y Coordinate';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(yval, numberName, lb, ub, isInt, errMsg, enteredStr);

    zval = str2double(get(handles.zCoordText,'String'));
    enteredStr = get(handles.zCoordText,'String');
    numberName = 'Z Coordinate';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(zval, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(normVector([xval, yval, zval]) == 0)
        errMsg{end+1} = 'The magnitude of the vector must be greater than 0.';
    end

    if(isempty(strtrim(handles.vectorNameText.String)))
        errMsg{end+1} = 'Vector name must contain more than white space and must not be empty.';
    end

% --- Executes on button press in cancelButton.
function cancelButton_Callback(hObject, eventdata, handles)
% hObject    handle to cancelButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    close(handles.lvd_EditFixedInFrameVectorGUI);

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

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

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

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

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

% Hints: get(hObject,'String') returns contents of xCoordText as text
%        str2double(get(hObject,'String')) returns contents of xCoordText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

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

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

% --- Executes on key press with focus on lvd_EditFixedInFrameVectorGUI or any of its controls.
function lvd_EditFixedInFrameVectorGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditFixedInFrameVectorGUI (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
    switch(eventdata.Key)
        case 'return'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'enter'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'escape'
            close(handles.lvd_EditFixedInFrameVectorGUI);
    end

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

% Hints: get(hObject,'String') returns contents of yCoordText as text
%        str2double(get(hObject,'String')) returns contents of yCoordText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

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

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

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

% Hints: get(hObject,'String') returns contents of zCoordText as text
%        str2double(get(hObject,'String')) returns contents of zCoordText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

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

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

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

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

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

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

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

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

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

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

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

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

function frameUpdated(handles)
    lvdData = getappdata(handles.lvd_EditFixedInFrameVectorGUI, 'lvdData');

    frame = getappdata(handles.lvd_EditFixedInFrameVectorGUI,'frame'); %curElemSet
    bodyInfo = frame.getOriginBody();

    if(isempty(bodyInfo))
        bodyInfo = LvdData.getDefaultInitialBodyInfo(lvdData.celBodyData);
    end

    contents = cellstr(get(handles.refFrameTypeCombo,'String'));
    selFrameType = contents{get(handles.refFrameTypeCombo,'Value')};
    refFrameEnum = ReferenceFrameEnum.getEnumForListboxStr(selFrameType);

    switch refFrameEnum
        case ReferenceFrameEnum.BodyCenteredInertial
            newFrame = bodyInfo.getBodyCenteredInertialFrame();

        case ReferenceFrameEnum.BodyFixedRotating
            newFrame = bodyInfo.getBodyFixedFrame();

        case ReferenceFrameEnum.TwoBodyRotating
            if(frame.typeEnum == ReferenceFrameEnum.TwoBodyRotating)
                newFrame = frame;
            else
                if(not(isempty(bodyInfo.childrenBodyInfo)))
                    primaryBody = bodyInfo;
                    secondaryBody = bodyInfo.childrenBodyInfo(1);
                else
                    primaryBody = bodyInfo.getParBodyInfo();
                    secondaryBody = bodyInfo;
                end

                originPt = TwoBodyRotatingFrameOriginEnum.Primary;

                newFrame = TwoBodyRotatingFrame(primaryBody, secondaryBody, originPt, bodyInfo.celBodyData);
            end

        case ReferenceFrameEnum.UserDefined
            numFrames = lvdData.geometry.refFrames.getNumRefFrames();
            if(numFrames >= 1)
                geometricFrame = lvdData.geometry.refFrames.getRefFrameAtInd(1);
                newFrame = UserDefinedGeometricFrame(geometricFrame, lvdData);
            else
                newFrame = bodyInfo.getBodyCenteredInertialFrame();
                warndlg('There are no geometric frames available.  A body-centered inertial frame will be selected instead.');
            end

        otherwise
            error('Unknown reference frame type: %s', string(refFrameEnum));
    end

    if(not(isempty(newFrame)) && newFrame.typeEnum ~= refFrameEnum)
        refFrameEnum = newFrame.typeEnum;
        handles.refFrameTypeCombo.Value = ReferenceFrameEnum.getIndForName(refFrameEnum.name);
    end

    setappdata(handles.lvd_EditFixedInFrameVectorGUI,'frame',newFrame);
    handles.setFrameOptionsButton.TooltipString = sprintf('Current Frame: %s', newFrame.getNameStr());

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

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

% --- Executes on button press in setFrameOptionsButton.
function setFrameOptionsButton_Callback(hObject, eventdata, handles)
% hObject    handle to setFrameOptionsButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    frame = getappdata(handles.lvd_EditFixedInFrameVectorGUI,'frame');

    newFrame = frame.editFrameDialogUI(EditReferenceFrameContextEnum.ForGeometry);

    setappdata(handles.lvd_EditFixedInFrameVectorGUI,'frame',newFrame);

    frameUpdated(handles);

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function value = r4_acosh ( x )

%*****************************************************************************80
%
%% R4_ACOSH evaluates the arc-hyperbolic cosine of an R4 argument.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 September 2011
%
%  Author:
%
%    Original FORTRAN77 version by Wayne Fullerton.
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Wayne Fullerton,
%    Portable Special Function Routines,
%    in Portability of Numerical Software,
%    edited by Wayne Cowell,
%    Lecture Notes in Computer Science, Volume 57,
%    Springer 1977,
%    ISBN: 978-3-540-08446-4,
%    LC: QA297.W65.
%
%  Parameters:
%
%    Input, real X, the argument.
%
%    Output, real VALUE, the arc-hyperbolic cosine of X.
%
  persistent dln2;
  persistent xmax;

  if ( isempty ( xmax ) )
    dln2 = 0.69314718055994530941723212145818;
    xmax = 1.0 / sqrt ( r4_tiny ( ) );
  end

  if ( x < 1.0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R4_ACOSH - Fatal error!\n' );
    fprintf ( 1, '  X < 1.0\n' );
    error ( 'R4_ACOSH - Fatal error!' )
  elseif ( x < xmax )
    value = log ( x + sqrt ( x * x - 1.0 ) );
  else
    value = dln2 + log ( x );
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [] = system_name2(block)

% Callback processing function for mask parameter
% - number of <Requirement name> used in the System
set_param(block, 'LinkStatus', 'none');
load_system('Simulink'); % Load Simulink library (background)
load_system('MIL_Test');

No = str2double(get_param(block,'No')); % Get # of VF-s
OldNo = length(find_system(block, 'regexp', 'on','LookUnderMasks','all','Name','<Requirement name>'));

if OldNo > No  % Remove
    % Redraw all the lines and Reset the in-out ports of all related block
    % Remove all the lines from Bus Selector
    In_B4a = get_param([block '/Bus Creator4'], 'Inputs');
    In_B4a = str2num(In_B4a);
    SigFrBS_l = get_param([block '/Bus Selector'], 'LineHandles');
    for i = 1:In_B4a
    delete_line(SigFrBS_l.Outport(i));
    end
end
for i = 1:max(No,OldNo)
    if OldNo > No && i > No && i <= OldNo % Remove
        % Remove lines
        set_param([block '/Bus Creator'], 'Inputs', num2str(No));
        SigAtTLines = get_param([block '/<Requirement name>' num2str(i)],'LineHandles');
        delete_line(SigAtTLines.Inport(1));
        delete_line(SigAtTLines.Outport(1));
        %delete_line([block '/Arbitration'],['In' num2str(i) '/' num2str(1)],['Collect Verdicts/' num2str(i)]);

        % Redraw the lines from Bus Selector
        % Find how many VFs in the Requirement block, which will be deleted

        NoVF = length(find_system([block '/<Requirement name>' num2str(i)], 'regexp', 'on','LookUnderMasks','all','Name','<Preconditions name>'));
        No_In_o = length(find_system([block '/Arbitration'], 'regexp', 'on','LookUnderMasks','all','Name','In'));
        delete_line([block '/Arbitration'],['Memory/' num2str(1)],['Collect Verdicts/' num2str(No_In_o+1)]);
        % Delete Signals from Bus Selector
        SigFrBS_n = get_param([block '/Bus Selector'], 'OutputSignals');
        % delete the number of VFs singals in Arbitration
        for j = 1:NoVF
                No_In = length(find_system([block '/Arbitration'], 'regexp', 'on','LookUnderMasks','all','Name','In'));
                delete_line([block '/Arbitration'],['In' num2str(No_In) '/' num2str(1)],['Collect Verdicts/' num2str(No_In)]);
                delete_block([block '/Arbitration/In' num2str(No_In)]);
                p = strcat(',','signal',num2str(i),'.signal',num2str(j),'.signal1');
                SigFrBS_n = strrep(SigFrBS_n,p,'');
        end
        % Redesign the Verdicts Collection
        set_param([block '/Arbitration/Collect Verdicts'], 'Inputs', num2str(No_In_o-NoVF+1));
        add_line([block '/Arbitration'],['Memory/' num2str(1)],['Collect Verdicts/' num2str(No_In_o-NoVF+1)],'autorouting','on');
        % Reset the inports of Bus Creator4 and Selector
        set_param([block '/Bus Creator4'], 'Inputs', num2str(No_In_o-NoVF));
        set_param([block '/Bus Selector'], 'OutputSignals',SigFrBS_n);
        % Remove blocks
        delete_block([block '/<Requirement name>' num2str(i)]);

    elseif No > OldNo && i > OldNo && i <= No % Add
        % Add blocks
        add_block('MIL_Test/Validation Function/Test Evaluation Architecture/<system name>/<Requirement name>',[block '/<Requirement name>' num2str(i)]);
        set_param([block '/<Requirement name>' num2str(i)], 'LinkStatus', 'none');
        if i == 2
             pos = get_param([block '/<Requirement name>'], 'Position');
        else pos = get_param([block '/<Requirement name>' num2str(i-1)], 'Position');
        end
        pos1 = pos(1);
        pos3 = pos(3);
        pos2 = pos(2)+80;
        pos4 = pos(4)+80;
        set_param([block '/<Requirement name>' num2str(i)], 'Position',[pos1 pos2 pos3 pos4]);
        set_param([block '/Bus Creator'], 'Inputs', num2str(i));

        % Add Inports of Bus Creator4
        In_B4 = get_param([block '/Bus Creator4'], 'Inputs');
        In_B4 = str2num(In_B4)+1;
        set_param([block '/Bus Creator4'], 'Inputs', num2str(In_B4));

        % Add Outports of Bus Selector
        % OutSignal of Bus Seletor
        %Signal1 = 'signal1.signal1.signal1';
        %for j = 2 : i
        SignalP = strcat(',','signal',num2str(i),'.signal1.signal1');
        %Signal1 = strcat(Signal1,SignalP);
        Signal1 = get_param([block '/Bus Selector'], 'OutputSignals');
        Signal1 = strcat(Signal1,SignalP);
        %end
        set_param([block '/Bus Selector'], 'OutputSignals',Signal1)

        % Add lines
        add_line(block,['<Requirement name>' num2str(i) '/1'],['Bus Creator/' num2str(i)],'autorouting','on');
        add_line(block,['Signal Conversion/1'],['<Requirement name>' num2str(i) '/1'],'autorouting','on');

        % Add lines between Bus Selector and Bus Creator4
        %add_line(block,['Bus Selector/' num2str(i)],['Bus Creator4/' num2str(i)],'autorouting','on');
        add_line(block,['Bus Selector/' num2str(In_B4)],['Bus Creator4/' num2str(In_B4)],'autorouting','on');
        % Add Input to Arbitration
        add_block('Simulink/Ports & Subsystems/In1',[block '/Arbitration/In' num2str(In_B4)]);
        if i == 2
             posi = get_param([block '/Arbitration/In1'], 'Position');
        else
            In_in = In_B4-1;
            posi = get_param([block '/Arbitration/In' num2str(In_in)], 'Position');
        end
        pos1 = posi(1);
        pos3 = posi(3);
        pos2 = posi(2)+40;
        pos4 = posi(4)+40;
        set_param([block '/Arbitration/In' num2str(In_B4)], 'Position',[pos1 pos2 pos3 pos4]);

        % fix position of Memory
        fix_pos([block '/Arbitration/Collect Verdicts'],[block '/Arbitration/Memory'],0,10);

        % Add Line from Bus Selector to Arbitration
        add_line(block,['Bus Selector/' num2str(In_B4)],['Arbitration/' num2str(In_B4)],'autorouting','on');

        % Set Inputports of 'Collect Verdicts'
        In_CV = In_B4+1;
        set_param([block '/Arbitration/Collect Verdicts'], 'Inputs', num2str(In_CV));

        % Put the Memory Outsignal always in the last Inport of Collect
        % Verdicts
        delete_line([block '/Arbitration'],['Memory/' num2str(1)],['Collect Verdicts/' num2str(In_B4)]);
        add_line([block '/Arbitration'],['Memory/' num2str(1)],['Collect Verdicts/' num2str(In_CV)],'autorouting','on');

        % Add line from 'in' to 'Collect Verdicts', which happens in the
        % undersystem Arbitration
        add_line([block '/Arbitration'],['In' num2str(In_B4) '/' num2str(1)],['Collect Verdicts/' num2str(In_B4)],'autorouting','on');
    end
end

% Remove Outport of Bus Selector & Input of Bus Creator4

if OldNo > No  % Remove
    % Redraw all the lines and Reset the in-out ports of all related block
    % Add Line from Bus Selector to Arbitration
    SigF_N = get_param([block '/Bus Selector'], 'OutputSignals');
    N_SigF= length(findstr(SigF_N, ','))+1;
   for j = 1:N_SigF
    add_line(block,['Bus Selector/' num2str(j)],['Arbitration/' num2str(j)],'autorouting','on');
    % Add lines between Bus Selector and Bus Creator4
    add_line(block,['Bus Selector/' num2str(j)],['Bus Creator4/' num2str(j)],'autorouting','on');
   end
end

author: Sable

repo: mcbench-benchmarks


text:
function plot_size_distribution_datasets()
colormap = [
228, 229, 97
163, 163, 163
218, 71, 56
219, 135, 45
145, 92, 146
83, 136, 173
106,61,154
225, 119, 174
142, 195, 129
51,160,44
223, 200, 51
92, 172, 158
177,89,40
177,89,40
188, 128, 189
177,89,40
251,154,153
31,120,180]./255;

  box_size_bins = 0:10:600;
  box_size_bin_centers = (box_size_bins(1:(end-1)) + box_size_bins(2:end)) / 2;
  box_size_bins(1) = -inf;
  box_size_bins(end) = inf;
  num_bins = numel(box_size_bins) - 1;

  handles = [];
  legend_labels = {};

  figure; hold on;

  load('data/pascal_voc07_test_annotations.mat');
  gt_w = [pos.x2] - [pos.x1] + 1;
  gt_h = [pos.y2] - [pos.y1] + 1;
  areas = sqrt(gt_w .* gt_h);
  [gt_h,arg_hist] = histc(areas, box_size_bins);
  assert(min(arg_hist) >= 1);
  assert(max(arg_hist) <= numel(box_size_bins) - 1);
  gt_h = gt_h(1:end-1)';
  gt_h = gt_h / sum(gt_h);
  handles(end+1) = plot(box_size_bin_centers, gt_h, '-', ...
    'LineWidth', 1.5, 'Color', colormap(1,:), 'MarkerSize', 10);
  legend_labels{end+1} = 'VOC test 2007';

  val = load('data/ILSVRC2013_val_annotations.mat');
  pos = val.pos;
  gt_w = [pos.x2] - [pos.x1] + 1;
  gt_h = [pos.y2] - [pos.y1] + 1;
  areas = sqrt(gt_w .* gt_h);
  [gt_h,arg_hist] = histc(areas, box_size_bins);
  assert(min(arg_hist) >= 1);
  assert(max(arg_hist) <= numel(box_size_bins) - 1);
  gt_h = gt_h(1:end-1)';
  gt_h = gt_h / sum(gt_h);
  handles(end+1) = plot(box_size_bin_centers, gt_h, '-', ...
    'LineWidth', 1.5, 'Color', colormap(2,:), 'MarkerSize', 10);
  legend_labels{end+1} = 'ILSVRC val 2013';

  val = load('data/coco2014_val_annotations.mat');
  pos = val.pos;
  gt_w = [pos.x2] - [pos.x1] + 1;
  gt_h = [pos.y2] - [pos.y1] + 1;
  areas = sqrt(gt_w .* gt_h);
  [gt_h,arg_hist] = histc(areas, box_size_bins);
  assert(min(arg_hist) >= 1);
  assert(max(arg_hist) <= numel(box_size_bins) - 1);
  gt_h = gt_h(1:end-1)';
  gt_h = gt_h / sum(gt_h);
  handles(end+1) = plot(box_size_bin_centers, gt_h, '-', ...
    'LineWidth', 1.5, 'Color', colormap(3,:), 'MarkerSize', 10);
  legend_labels{end+1} = 'COCO val 2014';

  legend(legend_labels, 'Location', 'northeast');
  legend boxoff;
  xlabel('sqrt(annotation area)');
  ylabel('frequency');
  xlim([0, 400]);
  hei = 10;
  wid = 8;
  set(gcf, 'Units','centimeters', 'Position',[0 0 wid hei]);
  set(gcf, 'PaperPositionMode','auto');
  printpdf('figures/datasets_size_histogram.pdf')

end

function h = get_size_statistics(candidates, im_size, box_size_bins)
  boxes = candidates;
  w = boxes(:,3) - boxes(:,1) + 1;
  h = boxes(:,4) - boxes(:,2) + 1;
  areas = sqrt(w .* h ./ prod(im_size));
  [h,arg_hist] = histc(areas, box_size_bins);

  assert(min(arg_hist) >= 1);
  assert(max(arg_hist) <= numel(box_size_bins) - 1);

  assert(h(end) == 0);
  h = h(1:end-1)';
end

author: hosang

repo: detection-proposals


text:
function [data,units] = compute_angle_shortest_wing(trx,n)

flies = trx.exp2flies{n};
nflies = numel(flies);
data = cell(1,nflies);
for i = 1:nflies,
  fly = flies(i);

  data{i} = -trx(fly).wing_anglel;
  idx = trx(fly).wing_lengthr_mm < trx(fly).wing_lengthl_mm;
  data{i}(idx) = trx(fly).wing_angler(idx);

end
units = parseunits('rad');

author: kristinbranson

repo: JAABA


text:
function colorposneg
% colorposneg
% Use colormap which shows negative values green & blue, positive values yellow & red, zero white
caxis('auto');
C = caxis;
C2 = max(C(2),0);
C1 = min(C(1),0);
R = max(-C1,C2);
caxis([-R,R])
q = (C2-C1)/(2*R);
colormap(posneg(round(100/q)))

%%%%%%%%
function J = posneg(m)
%     colormap similar to jet, but with white instead of green in the center
if nargin < 1
   m = size(get(gcf,'colormap'),1);
end
x = linspace(-2.5,2.5,m)';        % consider x in [-2.5,2.5]
f = @(x) max(0,min(1,2-abs(x)));  % function for green
J = [f(x-1),f(x),f(x+1)];

author: angeloyeo

repo: gongdols

save_path: github-repos/MATLAB/angeloyeo-gongdols


text:
function layer = genNetworkLSTMEncoderDecoder(para)
if isfield(para, 'LastActivation4MSE')==0
    para.LastActivation4MSE = 'linear';
end

layer{1}.name = 'Input';        % this is an input layer
layer{end}.inputIdx = 1;    % specifies the index of GCC in Visible_tr
layer{end}.dim = [1 1]*double(para.inputDim);             % [input dim; output dim];

if isfield(para, 'useFbank') && para.useFbank
    MelWindow = mel_window_FE(40, 256, 16000)';
    MelWindow(:,end+1) = 0;
    layer{end+1}.name = 'Affine';
    layer{end}.prev = -1;
    layer{end}.W = MelWindow;
    layer{end}.b = zeros(40,1);
    layer{end}.dim = [40 layer{end-1}.dim(1)];
    layer{end}.update = 0;

    layer{end+1}.name = 'log';
    layer{end}.prev = -1;
    layer{end}.const = 1e-7;
    layer{end}.dim = [1 1]*layer{end-1}.dim(1);
end

layer{end+1}.name = 'delta';
layer{end}.prev = -1;
layer{end}.dim = [3 1]*layer{end-1}.dim(1);

layer{end+1}.name = 'Affine';
layer{end}.prev = -1;
layer{end}.W = [];
layer{end}.b = [];
layer{end}.dim = [1 1]*layer{end-1}.dim(1);
layer{end}.update = 0;

layerLSTM = genNetworkLSTM(para);
for i=1:length(layerLSTM)
    layerLSTM{i} = rmfield(layerLSTM{i}, 'next');
end

layerLSTM = layerLSTM(2:end);

layerLSTM{1}.prev = -1;
layerLSTM{1}.dim(2) = layer{end}.dim(1);

layer = [layer layerLSTM];

if isfield(para, 'labelDelay')
    layer{end}.labelDelay = para.labelDelay;
end
if isfield(para, 'costFrameSelection');
    layer{end}.costFrameSelection = para.costFrameSelection;
end

layer{end-2}.name = 'multi_softmax';
layer{end-2}.TaskVocabSizes = para.outputDim/para.ngram_len;

layer{end}.name = 'multi_cross_entropy';
layer{end}.TaskVocabSizes = para.outputDim/para.ngram_len;
layer = FinishLayer(layer);
end

author: singaxiong

repo: SignalGraph


text:
%%***************************************************************
%% linsysolve: solve linear system to get dy, and direction
%%             corresponding to unrestricted variables.
%%
%% [xx,coeff,L,resnrm] = linsysolve(schur,UU,EE,Bmat,rhs);
%%
%% child functions: mybicgstable.m
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%***************************************************************

   function [xx,coeff,L,resnrm] = HSDlinsysolve(par,schur,UU,EE,Bmat,rhs);

    global solve_ok msg
    global nnzmat nnzmatold matfct_options matfct_options_old use_LU
    global Lsymb

    spdensity  = par.spdensity;
    printlevel = par.printlevel;
    iter       = par.iter;

    m = length(schur);
    if (iter==1); use_LU = 0; matfct_options_old = ''; end
    if isempty(nnzmatold); nnzmatold = 0; end
%%
%% diagonal perturbation
%% old: pertdiag = 1e-15*max(1,diagschur);
%%
    diagschur = abs(full(diag(schur)));
    const = 1e-2/max(1,norm(par.dy2));
    alpha = max(1e-14,min(1e-10,const*norm(par.rp))/(1+norm(diagschur.*par.dy2)));
    pertdiag = alpha*max(1e-8,diagschur); %% Note: alpha is close to 1e-15.
    mexschurfun(schur,pertdiag);
    %%if (printlevel); fprintf(' %3.1e ',alpha); end
    if (par.depconstr) | (min(diagschur) < min([1e-20*max(diagschur), 1e-4]))
       lambda = 0.1*min(1e-14,const*norm(par.rp)/(1+norm(par.diagAAt.*par.dy2)));
       mexschurfun(schur,lambda*par.diagAAt);
       if (printlevel); fprintf('#'); end
    end
    if (max(diagschur)/min(diagschur) > 1e14) & (par.blkdim(2) == 0) ...
       & (iter > 10)
       tol = 1e-6;
       idx = find(diagschur < tol); len = length(idx);
       pertdiagschur = zeros(m,1);
       if (len > 0 & len < 5) & (norm(rhs(idx)) < tol)
          pertdiagschur(idx) = 1*ones(length(idx),1);
          mexschurfun(schur,pertdiagschur);
          if (printlevel); fprintf('$'); end
       end
    end
%%
%%
%%
    UU = [UU, Bmat];
    if ~isempty(EE)
       len = max(max(EE(:,1)),max(EE(:,2)));
    else
       len = 0;
    end
    tmp = [len+1,len+3,-1; len+2,len+4,1; len+3,len+1,1; len+4,len+2,-1;
           len+2,len+2,par.addschur];  %% this is the -inverse
    EE = [EE; tmp];
    ncolU = size(UU,2);
%%
%% assemble coefficient matrix
%%
    if isempty(EE)
       coeff.mat22 = [];
    else
       coeff.mat22 = spconvert(EE);
    end
    coeff.mat12 = UU;
    coeff.mat11 = schur; %% important to use perturbed schur matrix
%%
%% pad rhs with zero vector
%% decide which solution methods to use
%%
    rhs = [rhs; zeros(m+ncolU-length(rhs),1)];
    if (ncolU > 300); use_LU = 1; end
%%
%% Cholesky factorization
%%
    L = []; resnrm = []; xx = inf*ones(m,1);
    if (~use_LU)
       nnzmat = mexnnz(coeff.mat11);
       nnzmatdiff = (nnzmat ~= nnzmatold);
       solve_ok = 1;  solvesys = 1;
       if (nnzmat > spdensity*m^2) | (m < 500)
          matfct_options = 'chol';
       else
          matfct_options = 'spchol';
       end
       if (printlevel > 2); fprintf(' %s',matfct_options); end
       if strcmp(matfct_options,'chol')
          if issparse(schur); schur = full(schur); end;
          if (iter<=5); %%--- to fix strange anonmaly in Matlab
             mexschurfun(schur,1e-20,2);
          end
          L.matfct_options = 'chol';
          [L.R,indef] = chol(schur);
          L.perm = [1:m];
      elseif strcmp(matfct_options,'spchol')
          if ~issparse(schur); schur = sparse(schur); end;
          L.matfct_options = 'spchol';
          [L.R,indef,L.perm] = chol(schur,'vector');
          L.Rt = L.R';
       end
       if (indef)
          solve_ok = -2; solvesys = 0;
          msg = 'HSDlinsysolve: Schur complement matrix not positive definite';
          if (printlevel); fprintf('\n  %s',msg); end
       end
       if (solvesys)
          if (ncolU)
             tmp = coeff.mat12'*linsysolvefun(L,coeff.mat12)-coeff.mat22;
	     if issparse(tmp); tmp = full(tmp); end
             [L.Ml,L.Mu,L.Mp] = lu(tmp);
             tol = 1e-16;
             condest = max(abs(diag(L.Mu)))/min(abs(diag(L.Mu)));
             idx = find(abs(diag(L.Mu)) < tol);
             if ~isempty(idx) | (condest > 1e30*sqrt(norm(par.diagAAt))); %% default=1e25
                solvesys = 0; solve_ok = -4;
                use_LU = 1;
                msg = 'SMW too ill-conditioned, switch to LDL factor';
                if (printlevel); fprintf('\n  %s, %2.1e.',msg,condest); end
             end
          end
          if (solvesys)
             [xx,resnrm,solve_ok] = HSDbicgstab(coeff,rhs,L,[],[],printlevel);
             if (solve_ok<=0) & (printlevel)
                fprintf('\n  warning: HSDbicgstab fails: %3.1f.',solve_ok);
             end
          end
       end
       if (solve_ok < 0)
          if (m < 6000 & strcmp(matfct_options,'chol')) | ...
             (m < 1e5 & strcmp(matfct_options,'spchol'))
             use_LU = 1;
             if (printlevel); fprintf('\n  switch to LDL factor'); end
          end
       end
    end
%%
%% symmetric indefinite LDL factorization
%%
    if (use_LU)
       nnzmat = mexnnz(coeff.mat11)+mexnnz(coeff.mat12);
       nnzmatdiff = (nnzmat ~= nnzmatold);
       solve_ok = 1;
       if ~isempty(coeff.mat22)
          raugmat = [coeff.mat11, coeff.mat12; coeff.mat12', coeff.mat22];
       else
          raugmat = coeff.mat11;
       end
       if (nnzmat > spdensity*m^2) | (m+ncolU < 500)
          matfct_options = 'ldl';
       else
          matfct_options = 'spldl';
       end
       if (printlevel > 2); fprintf(' %s ',matfct_options); end
       if strcmp(matfct_options,'ldl')
          if issparse(raugmat); raugmat = full(raugmat); end
          L.matfct_options = 'ldl';
          [L.L,L.D] = ldl(raugmat);
          L.perm = [1:length(raugmat)]';
       elseif strcmp(matfct_options,'spldl')
          if ~issparse(raugmat); raugmat = sparse(raugmat); end
          L.matfct_options = 'spldl';
          [L.L,L.D,L.perm] = ldl(raugmat,'vector');
          L.Lt = L.L';
       end
       [xx,resnrm,solve_ok] = HSDbicgstab(coeff,rhs,L,[],[],printlevel);
       if (solve_ok<=0) & (printlevel)
          fprintf('\n  warning: HSDbicgstab fails: %3.1f,',solve_ok);
       end
    end
    if (printlevel>=3); fprintf('%2.0f ',length(resnrm)-1); end
%%
    nnzmatold = nnzmat; matfct_options_old = matfct_options;
%%***************************************************************


text:
function chud_pi_test ( )

%*****************************************************************************80
%
%% CHUD_PI_TEST tests the CHUD_PI function.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 February 2012
%
%  Author:
%
%    John Burkardt
%
  clear all

  fprintf ( 1, '\n' );
  fprintf ( 1, 'CHUD_PI_TEST\n' );
  fprintf ( 1, '  CHUD_PI computes the value of pi using the \n' );
  fprintf ( 1, '  Chudnovsky approach.\n' );
%
%  Get pi to 10, 20, 40, 80 decimal digits:
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Request PI to 10, 20, 40, 80 digits.\n' );
  fprintf ( 1, '\n' );
%
%  Trying to print P out neatly using concatenation fails here,
%  although it works in AGM_PI_TEST.
%
%  The procedure for printing out the D-digit representation of
%  a symbolic variable (if you are not willing to simply name
%  the variable and have its value plop out on the screen) is
%  not apparent to me!
%
  d = 10;

  for i = 1 : 4

    p = chud_pi ( d );

    fprintf ( 1, '  Request %6d digits:', d );
    p
    d = d * 2;

  end
%
%  Timings.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  How long does it take to compute PI to D digits?\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '          Digits    Seconds\n' );
  fprintf ( 1, '\n' );
  d = 2;
  for i = 1 : 13
    tic
    p = chud_pi ( d );
    t = toc;
    fprintf ( 1, '  %2d  %10d  %14g\n', i, d, t );
    d = d * 2;
  end

  return
end


text:
function [Conn peaks] = hlp_filterConns(Conn, varargin)
%
% Apply a set of selection rules to a connectivity matrix
%
% Inputs:
%
%   Conn        Connectivity structure with subfields Conn.(connmethod)
%               containing [nchs x nchs x num_freqs x num_times]
%               connectivity matrices
%
% Optional:
%
%       'connThresh'    [real]. Absolute thresholding to apply after
%                               significance thresholding. Can be be a
%                               scalar or a matrix of same size as
%                               EEG.CAT.Conn.(connmethod). Can be logical C(C~=thresh) = 0 or real-valued C(C<thresh)=0
%       'prcThresh'     -     [real] The upper percent [1-100] of filtered
%                             connections to keep {def: 100}
%       'method'              cell array of dimensionality reduction methods to apply in a specified order. e.g.,
%                             {'freq','net','time','peak'} will first integrate over freq, then find peak over time.
%                             If method is a string, then this is taken to be the compression global dimension reduction
%                             method applied to all dims in the order {'time','freq',...}.
%                             allowed methods:  'mean', 'net', 'peak', 'getrange'
%        ...
%

% Outputs:
%
%   Conn        filtered connectivity structure
%   peaks       frequency peaks (if method = 'peak')
%
% See Also: est_mvarConnectivity()
%
% References:
%
% [1] Mullen T (2010) The Source Information Flow Toolbox (SIFT):
%   Theoretical Handbook and User Manual.
%   Available at: http://www.sccn.ucsd.edu/wiki/Sift/
%
%
% Author: Tim Mullen 2008, 2010, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

% This function is part of the Source Information Flow Toolbox (SIFT)
%
% 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, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

% ----------------------------------------------------------
% TODO:
% need to provide ability to specify order in which dim-compression
% methods are applied. e.g., {3,'net',4,'peak'} would first
% integrate over the third dimension (frequency) and then find the peaks
% over the 4th dim (time)
% ONE OPTION:  allow 'method' = a cell array as above
% ----------------------------------------------------------
% Key point, need to have EEG.CAT.dims = {'chans','chans','freq','times'}
% or some such...
%

if nargin<1
    help hlp_filterConns;
    return;
end

% parse inputs
g = finputcheck(varargin,...
   {'connmethods', ''          {}          {}; ...      % cell array of connectivity method names. If empty, we use all of them
    'connThresh'   ''          []          0; ...       % absolute thresholding to apply after significance thresholding. can be a scalar or a matrix of same size as EEG.CAT.C. Can be logical C(C~=thresh) = 0 or real-valued C(C<thresh)=0
    'prcThresh'    'real'      [eps 100]   100;...      % top percentile of connections to keep
    'frange'       'real'      []          [];...       % same units as Conn.freqs
    'trange'       'real'      []          [];...       % same units as EEG.CAT.times
    'sigThresh'    ''          []          [];...       % can be a scalar or a matrix of same size as EEG.CAT.C. Can be logical C(C~=thresh) = 0 or real-valued C(C<thresh)=0
    'badchans'     'integer'   []          [];...
    'method'       ''          ''          '';...       % cell array of dimensionality reduction methods to apply in a specified order.
                                                        % e.g. {'freq','net','time','peak'} will first integrate over freq, then find peak over time.
                                                        % If method is a string, then this is taken to be the compression global dimension reduction
                                                        % method applied to all dims in the order {'time','freq',...}
                                                        % Allowed compression methods are:
                                                        % 'net'         (integrate)
                                                        % 'mean'        (average)
                                                        % 'peak'        (1-D peak search along given dim)
                                                        % 'peak2d'      (2-D peak search)
                                                        % 'getrange'    (extract a data range from given dimension)
                                                        % 'maxmag'      (1-D max magnitude (max of absval) along given dimension)
                                                        % 'max'         (1-D max along given dimension)
                                                        % 'min'         (1-D min along given dimension)

    'peakWidth'    'integer'   []          2;...
    'chanlocs'     ''          []          [];...
    'distRad'      'real'      []          [];...
    'strictRad'    'boolean'   []          1;...
    'metric',      'string'    []          'manhattan';...
    'diags',       'string'    {'off','on'} 'on'; ...
    'freqdim',     'real'      []          []; ...
    'timedim',     'real'      []          []; ...
    'verb',        'boolean'   []          1; ...
    },'hlp_filterConns','error','quiet');

if ischar(g)
    error(g);
end

if isempty(g.connmethods)
    g.connmethods = hlp_getConnMethodNames(Conn);
end

nmethods = 3;

if ~isempty(g.timedim)
    timedim = g.timedim;
elseif isfield(Conn,'dims')
    timedim=find(ismember_bc(Conn.dims,'time'));
else
    timedim = [];
end

if ~isempty(g.freqdim)
    freqdim = g.freqdim;
elseif isfield(Conn,'dims')
    freqdim=find(ismember_bc(Conn.dims,'freq'));
else
    freqdim = [];
end

if isempty(freqdim)
    if g.verb
        disp('warning: no ''freq'' entry found in Conn.dims -- assuming dim 3');
    end
    freqdim = 3;
end
if isempty(timedim)
    if g.verb
        disp('warning: no ''time'' entry found in Conn.dims -- assuming dim 4');
    end
    timedim = 4;
end

if ischar(g.method),
    ONEMETHOD = true;
    g.method = {'time',g.method,'freq',g.method};
else
    ONEMETHOD = false;
end

if isempty(g.frange)
    g.frange = [Conn.freqs(1) Conn.freqs(end)];
end

if isempty(g.trange)
    g.trange = [Conn.erWinCenterTimes(1) Conn.erWinCenterTimes(end)];
end

if length(Conn.freqs)==1
    Conn.freqs = repmat(Conn.freqs,1,2);
end

if length(Conn.erWinCenterTimes)==1
    Conn.erWinCenterTimes = repmat(Conn.erWinCenterTimes,1,2);
    Conn.winCenterTimes = repmat(Conn.winCenterTimes,1,2);
end

if isnan(g.frange)
    g.frange = [];
end

if isnan(g.trange)
    g.trange = [];
end

frangeidx = getindex(Conn.freqs,g.frange);
trangeidx = getindex(Conn.erWinCenterTimes,g.trange);

for m=1:length(g.connmethods)
    connmethod = g.connmethods{m};

    if length(size(Conn.(connmethod)))>5
        error('Connectivity Matrix cannot be greater than 4-D!');
    end

    C = Conn.(connmethod);  % make copy of connectivity matrix

    % apply significance thresholding
    if ~isempty(g.sigThresh)
        if islogical(g.sigThresh) && isequal(size(C),size(g.sigThresh))
            C(~g.sigThresh)=0;
        else
            C(C<g.sigThresh) = 0;
        end
    end

    if ~all(cellfun(@isempty,g.method(2:2:end))) && ~strcmpi(g.method{2},'thresh')
        if ~isempty(g.trange) && ~isempty(g.frange) && ONEMETHOD && isequal(g.method{2},'peak2d')
            % apply 2D peak identification
            if g.verb
                fprintf('applying method=%s to dim=%s and %s\n',g.method{2},g.method{1},g.method{3});
            end
            C = collapseDim(C,'dim',4,'range',trangeidx, ...
                'method','getrange');     % extract time range
            C = collapseDim(C,'dim',3,'range',frangeidx, ...
                'method','getrange');     % extract freq range
            [C peaks] = collapseDim(C,'dim',4,'range',[], 'method','peak2d', ...
                'peakWidth',g.peakWidth,'minpeakheight',g.connThresh); % find peaks
        else

            for mm=1:2:length(g.method)

                curmethod = g.method{mm};

                if ~ismember_bc(curmethod,{'time','freq'})
                    error('unknown method %s',curmethod);
                end

                % collapse time dim
                if ~isempty(g.trange) && (isequal(curmethod,'time'))
                    if g.verb
                        fprintf('applying method=%s to dim=%s\n',g.method{mm+1},g.method{mm});
                    end
                    [C peaks.times] = collapseDim(C,'dim',timedim,...
                        'range',trangeidx,'method',g.method{mm+1},...
                        'dx',Conn.erWinCenterTimes(2)-Conn.erWinCenterTimes(1),'peakWidth',g.peakWidth, ...
                        'minpeakheight',g.connThresh);
                end

                % collapse freq dim
                if ~isempty(g.frange) && (isequal(curmethod,'freq'))
                    if g.verb
                        fprintf('applying method=%s to dim=%s\n',g.method{mm+1},g.method{mm});
                    end
                    [C peaks.freqs] = collapseDim(C,'dim',freqdim,...
                        'range',frangeidx,'method',g.method{mm+1},...
                        'dx',Conn.freqs(2)-Conn.freqs(1),'peakWidth',g.peakWidth, ...
                        'minpeakheight',g.connThresh);
                end

            end

        end
    end

    sz=size(C);
    if all(sz(3:end)==1)
        C = squeeze(C);
    end

    % remove diagonals
    if strcmpi(g.diags,'off')
        for q=1:size(C,3)
            C(:,:,q)=C(:,:,q).*~eye(size(C(:,:,q)));
        end
    end

    % apply connectivity threshold
    if g.connThresh
        C(C<g.connThresh) = 0;
    end

    % apply percentile threshold
    if ~isempty(g.prcThresh) && g.prcThresh<100
        % get specified percentile
        prc = prctile(C(:),100-g.prcThresh);
        C(C<prc)=0;
    end

    Conn.(connmethod) = C;

end

if ~isempty(frangeidx) && size(C,3)==1
    % frequency dimension has been collapsed
    % replace with median frequency within collapsed interval
    Conn.collapsedFreqs = Conn.freqs(frangeidx(1):frangeidx(end));
    Conn.freqs          = median(Conn.collapsedFreqs);
else
    Conn.freqs          = Conn.freqs(frangeidx(1):frangeidx(end));
end

if ~isempty(trangeidx) &&size(C,4)==1
    % time dimension has been collapsed
    % replace with median time point within collapsed interval
    Conn.collapsedTimes     = Conn.erWinCenterTimes(trangeidx(1):trangeidx(end));
    Conn.erWinCenterTimes   = median(Conn.collapsedTimes);
    Conn.winCenterTimes     = median(Conn.winCenterTimes(trangeidx(1):trangeidx(end)));
else
    Conn.erWinCenterTimes   = Conn.erWinCenterTimes(trangeidx(1):trangeidx(end));
    Conn.winCenterTimes     = Conn.winCenterTimes(trangeidx(1):trangeidx(end));
end


text:
% Demonstration of generative model functions.
%
% See GENERATIVE_MODEL and EVALUATE_GENERATIVE_MODEL for further details
% and interpretation.

clear
close all
clc

data = load('demo_generative_models_data');
A     = data.A;
Aseed = data.Aseed;
D     = data.D;

% get cardinality of network
n = length(A);

% set model type
modeltype = 'sptl';

% set whether the model is based on powerlaw or exponentials
modelvar = [{'powerlaw'},{'powerlaw'}];

% choose some model parameters
nparams = 100;
params = unifrnd(-10,0,nparams,1);

% generate synthetic networks and energy for the neighbors model;
[B,E,K] = evaluate_generative_model(Aseed,A,D,modeltype,modelvar,params);
X = [E,K];

% show scatterplot of parameter values versus energy and KS statistics
names = [...
    {'energy'},...
    {'degree'},...
    {'clustering'},...
    {'betweenness'},...
    {'edge length'}];

f = figure(...
    'units','inches',...
    'position',[2,2,4,4]);
for i = 1:size(X,2)
    subplot(3,2,i);
    scatter(params,X(:,i),100,X(:,i),'filled');
    set(gca,...
        'ylim',[0,1],...
        'clim',[0,1]);
    colormap(jet);
    xlabel('geometric parameter, \eta');
    ylabel(names{i});
end


text:
%% Basic Geometric Drawing
% In this demo, we show how to:
%
% * Draw a line by using the function |cv.line|
% * Draw an ellipse by using the function |cv.ellipse|
% * Draw a rectangle by using the function |cv.rectangle|
% * Draw a circle by using the function |cv.circle|
% * Draw a filled polygon by using the function |cv.fillPoly|
%
% Sources:
%
% * <https://docs.opencv.org/3.2.0/d3/d96/tutorial_basic_geometric_drawing.html>
% * <https://github.com/opencv/opencv/blob/3.2.0/samples/cpp/tutorial_code/core/Matrix/Drawing_1.cpp>
%

%%
% image size
W = 400;

%% Atom
img1 = zeros(W,W,3,'uint8');
for ang=-45:45:90
    img1 = cv.ellipse(img1, [W W]/2, [W/4 W/16], ...
        'Angle',ang, 'Color',[0 0 255], 'Thickness',2);
end
img1 = cv.circle(img1, [W W]/2, W/32, ...
    'Color',[255 0 0], 'Thickness','Filled');

figure(1), imshow(img1)
title('Atom')

%% Rook
img2 = zeros(W,W,3,'uint8');
pts = [
       W/4   7*W/8  ;
     3*W/4   7*W/8  ;
     3*W/4  13*W/16 ;
    11*W/16 13*W/16 ;
    19*W/32  3*W/8  ;
     3*W/4   3*W/8  ;
     3*W/4     W/8  ;
    26*W/40    W/8  ;
    26*W/40    W/4  ;
    22*W/40    W/4  ;
    22*W/40    W/8  ;
    18*W/40    W/8  ;
    18*W/40    W/4  ;
    14*W/40    W/4  ;
    14*W/40    W/8  ;
       W/4     W/8  ;
       W/4   3*W/8  ;
    13*W/32  3*W/8  ;
     5*W/16 13*W/16 ;
       W/4  13*W/16 ;
];
img2 = cv.fillPoly(img2, {pts}, 'Color',[255 255 255]);
img2 = cv.rectangle(img2, [0 7*W/8], [W W], ...
    'Color',[255 255 0], 'Thickness','Filled');
img2 = cv.line(img2, [0 15*W/16], [W 15*W/16]);
img2 = cv.line(img2, [W/4 7*W/8], [W/4 W]);
img2 = cv.line(img2, [W/2 7*W/8], [W/2 W]);
img2 = cv.line(img2, [3*W/4 7*W/8], [3*W/4 W]);

figure(2), imshow(img2)
title('Rook')

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
function [mv] = mv_openFig(mv);
% mv_openFig(view, voxels, scans, dt, ROIname);
%
% For MultiVoxel UI: Open the interface figure,  attaching
% menus and updating the mv data structure. (Use
% er_voxelData to get an mv structure from a mrVista
% ROI).
%
%
%
% ras,  04/05

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% open figure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figName = sprintf('%s Voxel Data  [scans %s,  session %s]', ...
                   mv.roi.name, num2str(mv.params.scans), ...
                   mv.params.sessionCode);,

mv.ui.fig = figure('Name', figName, ...
           'Units', 'Normalized', ...
           'Position', [0.2 0.4 0.4 0.4], ...
           'MenuBar', 'none', ...
           'NumberTitle', 'off', ...
           'Color', 'w');

% add menus
mv = mv_plotsMenu(mv, mv.ui.fig);
mv = mv_viewMenu(mv, mv.ui.fig);
mv = mv_analysisMenu(mv, mv.ui.fig);
mv = mv_settingsMenu(mv, mv.ui.fig);
mv = mv_xformMenu(mv, mv.ui.fig);
mv = mv_conditionsMenu(mv, mv.ui.fig);
mv = mv_helpMenu(mv, mv.ui.fig);

% add a control panel for visualizing GLMs (maybe other things too)
mv = mv_glmPanel(mv);

% clear axes
cla;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set mv struct as userdata of fig
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
set(mv.ui.fig, 'UserData', mv);

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
%
%       HDR Toolbox demo 5:
%	   1) Load "Bottles_Small.hdr" HDR image
%      2) Activate the Interactive HDR Visualization tool
%      3) Write a .png file with the latest clicked exposure using
%      InteractiveHDRVis
%
%       Author: Francesco Banterle
%       Copyright June 2012 (c)
%
%
clear all;

disp('1) Load "Bottles_Small.hdr" HDR image');
img = hdrimread('demos/Bottles_Small.hdr');

disp('2) Activate the Interactive HDR Visualization tool');
[img_cur_exp, exposure] = AExposureGUI(img);

disp('3)  Write a .png file with the latest clicked exposure using InteractiveHDRVis');
imwrite(GammaTMO(img_cur_exp, 2.2, 0.0, 0), 'demos/output/Venice01_int_vis.png');

author: banterle


text:
function out = gpuBlockSmallXtY(X, Y)

g = gpuDevice;
bytesGPU = g.AvailableMemory;
infoX = whos('X');
infoY = whos('Y');
[hX, wX] = size(X);
[hY, wY] = size(Y); % hY should be equal to hX
% the dimensions of out will be wX-by-wY
bytesPerRowX = infoX.bytes/hX;
bytesPerRowY = infoY.bytes/hY;
% theoretically, to keep the result and {X', X, and Y} in GPU memory
% bytesRequired = bytesPerRowX*wY + batchSize*(2*bytesPerRowX+bytesPerRowY);
batchSize = floor((bytesGPU-bytesPerRowX*wY)/(2*bytesPerRowX+bytesPerRowY));
batchSize = floor(batchSize/8); % just to be on the safe side
% also, interestingly with smaller batches the code runs slightly faster
nBatches = ceil(hX/batchSize);

startIdx = 1:batchSize:hX;
endIdx = startIdx + batchSize-1;
endIdx = min(endIdx, hX);

out = gpuArray(zeros([wX, wY], 'like', X));
for iBatch = 1:nBatches
%     fprintf('Batch %d/%d\n', iBatch, nBatches);
    batchX = gpuArray(X(startIdx(iBatch):endIdx(iBatch), :));
    batchY = gpuArray(Y(startIdx(iBatch):endIdx(iBatch), :));
    out = out + batchX'*batchY;

% MK - this is an annoying line of code, but it helps Matlab to do memory
% management on the GPU properly. Otherwise I get OUT OF MEMORY errors
% maybe it is just my GPU is a bit unstable
    wait(gpuDevice);
end

out = gather(out);

return

author: cortex-lab


text:
function kern = linardKernExpandParam(kern, params)

% LINARDKERNEXPANDPARAM Create kernel structure from LINARD kernel's parameters.
% FORMAT
% DESC returns a automatic relevance determination linear kernel 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 kern : the kernel structure in which the parameters are to be
% placed.
% ARG param : vector of parameters which are to be placed in the
% kernel structure.
% RETURN kern : kernel structure with the given parameters in the
% relevant locations.
%
% SEEALSO : linardKernParamInit, linardKernExtractParam, kernExpandParam
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006

% KERN

kern.variance = params(1);
kern.inputScales = params(2:end);

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat