text:
%% Implementation of Decision-Based Algorithm for Removal of High-Density
%% Impulse Noises
%% Base Paper : "A New Fast and Efficient Decision-Based Algorithm for
%  Removal of High-Density Impulse Noises", IEEE Sigmal Pricessing Letter,
%  Vol. 14,No. 3, Mar 2007.
%% Function Y = DBAIN(x)
%% input    x = Given an Image
%%
%%  Example: Y = DBAIN(x);
%%      Posted date   : 23 - 10 - 2008
%%      Modified date :
%%
%% Developed By : K.Kannan (kannan.keizer@gmail.com)
%%                & Jeny Rajan (jenyrajan@gmail.com)
%%                  Medical Imaging Research Group (MIRG), NeST,
%%                  Trivandrum.
%%
%% Decision-Based Algorithm for Removal of High-Density Impulse Noises
function Y = DBA(x)

Y = double(x);
[R C] = size(x);
%% Implementation
for i = 2:R-1
    for j = 2:C-1
        clear tmp;
        tmp = Y(i-1:i+1,j-1:j+1);
        flg = 0;
        S = sort(tmp(:));
        if Y(i,j) == 0 || Y(i,j) == 255
            flg = 1;
        end
        if flg == 0 % if the Pixel is uncorrupted.
            if S(1) < Y(i,j) && Y(i,j) < S(5) && 0 < S(1) && S(9) < 255 % The
                % P(X,Y) is an uncorrupted pixel if  Pmin < P(X,Y) < Pmax,
                % Pmin > 0 and Pmax < 255; the pixel being processed is
                % left unchanged. Otherwise, P(X,Y) is a corrupted pixel.
                Y(i,j) = Y(i,j);
            end
        else % if the Pixel is corrupted.
            if S(1) < S(5) && S(5) < S(9) && 0 < S(5) && S(5) < 255 % If P(X,Y)
                % is a corrupted pixel, it is replaced by its median value
                % if Pmin < Pmed < Pmax and 0 < Pmed < 255.
                Y(i,j) = S(5);
            end
            if S(1) >= S(5) || S(5) >= S(9) || S(5) == 255 && S(5) == 0
                % If Pmin < Pmed < Pmax  is not satisfied or 255 < Pmed = 0,
                % then is a noisy pixel. In this case, the P(X,Y) is replaced
                % by the value of neighborhood pixel value.
                Y(i,j) = Y(i,j-1);
            end
        end
    end
end
%% Border Correction
Y(1,:) = Y(2,:);
Y(R,:) = Y(R-1,:);
Y(:,1) = Y(:,2);
Y(:,C) = Y(:,C-1);

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text:
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com

%%begin

% We will show how to make a mobile robot with "car-like" steering drive from
% one pose to another.

% The goal pose is
xg = [5 5 pi/2];

% and the starting pose is
x0 = [5 9 0]

% We use a Simulink model to represent the dynamics of the vehicle and to
% implement a pose controller
sl_drivepose

% We run the simulation
r = sim('sl_drivepose');
% and extract the trajectory of the robot
y = r.find('yout');

% which we plot
axis([0 10 0 10]); hold on; grid on
plot(y(:,1), y(:,2));
% and overlay the initial and final pose of the robot
plot_vehicle(x0, 'r'); plot_vehicle(xg, 'r');
% Note the complex path the robot had to follow, since it's motion is limited
% by the nature of the steering mechanism.

author: petercorke

repo: robotics-toolbox-matlab


text:
function varargout = WFTKernel(varargin)
% Function:             Windowed Fourier transofmr (Kernel)
% Initially Developed:  Dr Qian Kemao (16 May 2009)
% Last modified:        Dr Qian Kemao (17 May 2009)
% Version:              1.0
% Copyrights:           All rights reserved.
% Contact:              mkmqian@ntu.edu.sg (Dr Qian Kemao)

%WFTKERNEL M-file for WFTKernel.fig
%      WFTKERNEL, by itself, creates a new WFTKERNEL or raises the existing
%      singleton*.
%
%      H = WFTKERNEL returns the handle to a new WFTKERNEL or the handle to
%      the existing singleton*.
%
%      WFTKERNEL('Property','Value',...) creates a new WFTKERNEL using the
%      given property value pairs. Unrecognized properties are passed via
%      varargin to WFTKernel_OpeningFcn.  This calling syntax produces a
%      warning when there is an existing singleton*.
%
%      WFTKERNEL('CALLBACK') and WFTKERNEL('CALLBACK',hObject,...) call the
%      local function named CALLBACK in WFTKERNEL.M with the given input
%      arguments.
%
%      *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 WFTKernel

% Last Modified by GUIDE v2.5 16-May-2009 10:09:25

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @WFTKernel_OpeningFcn, ...
                   'gui_OutputFcn',  @WFTKernel_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 WFTKernel is made visible.
function WFTKernel_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   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

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

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

function edit_sigmax_Callback(hObject, eventdata, handles)
% hObject    handle to edit_sigmax (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 edit_sigmax as text
%        str2double(get(hObject,'String')) returns contents of edit_sigmax as a double

% --- Executes during object creation, after setting all properties.
function edit_sigmax_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_sigmax (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 edit_wxl_Callback(hObject, eventdata, handles)
% hObject    handle to edit_wxl (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 edit_wxl as text
%        str2double(get(hObject,'String')) returns contents of edit_wxl as a double

% --- Executes during object creation, after setting all properties.
function edit_wxl_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_wxl (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 edit_wxi_Callback(hObject, eventdata, handles)
% hObject    handle to edit_wxi (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 edit_wxi as text
%        str2double(get(hObject,'String')) returns contents of edit_wxi as a double

% --- Executes during object creation, after setting all properties.
function edit_wxi_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_wxi (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 edit_wxh_Callback(hObject, eventdata, handles)
% hObject    handle to edit_wxh (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 edit_wxh as text
%        str2double(get(hObject,'String')) returns contents of edit_wxh as a double

% --- Executes during object creation, after setting all properties.
function edit_wxh_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_wxh (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 edit_sigmay_Callback(hObject, eventdata, handles)
% hObject    handle to edit_sigmay (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 edit_sigmay as text
%        str2double(get(hObject,'String')) returns contents of edit_sigmay as a double

% --- Executes during object creation, after setting all properties.
function edit_sigmay_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_sigmay (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 edit_wyl_Callback(hObject, eventdata, handles)
% hObject    handle to edit_wyl (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 edit_wyl as text
%        str2double(get(hObject,'String')) returns contents of edit_wyl as a double

% --- Executes during object creation, after setting all properties.
function edit_wyl_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_wyl (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 edit_wyi_Callback(hObject, eventdata, handles)
% hObject    handle to edit_wyi (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 edit_wyi as text
%        str2double(get(hObject,'String')) returns contents of edit_wyi as a double

% --- Executes during object creation, after setting all properties.
function edit_wyi_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_wyi (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 edit_wyh_Callback(hObject, eventdata, handles)
% hObject    handle to edit_wyh (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 edit_wyh as text
%        str2double(get(hObject,'String')) returns contents of edit_wyh as a double

% --- Executes during object creation, after setting all properties.
function edit_wyh_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_wyh (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 edit_thr_Callback(hObject, eventdata, handles)
% hObject    handle to edit_thr (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 edit_thr as text
%        str2double(get(hObject,'String')) returns contents of edit_thr as a double

% --- Executes during object creation, after setting all properties.
function edit_thr_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_thr (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 button press in push_WFTRun.
function push_WFTRun_Callback(hObject, eventdata, handles)
% hObject    handle to push_WFTRun (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
load result
H=findobj('Tag','radiobutton_wff');   val=get(H,'Value');
if val==1
    g.AlgorithmType='wff';
else
    g.AlgorithmType='wfr';
end
H=findobj('Tag','edit_sigmax'); sigmax=str2num(get(H,'String'));
H=findobj('Tag','edit_sigmax'); sigmax=str2num(get(H,'String'));
H=findobj('Tag','edit_wxl');    wxl=str2num(get(H,'String'));
H=findobj('Tag','edit_wxi');    wxi=str2num(get(H,'String'));
H=findobj('Tag','edit_wxh');    wxh=str2num(get(H,'String'));
H=findobj('Tag','edit_sigmay'); sigmay=str2num(get(H,'String'));
H=findobj('Tag','edit_wyl');    wyl=str2num(get(H,'String'));
H=findobj('Tag','edit_wyi');    wyi=str2num(get(H,'String'));
H=findobj('Tag','edit_wyh');    wyh=str2num(get(H,'String'));
H=findobj('Tag','edit_thr');    thr=str2num(get(H,'String'));
g0=wft2fw(g.AlgorithmType,g.f,sigmax,wxl,wxi,wxh,sigmay,wyl,wyi,wyh,thr);
if strcmp(g.AlgorithmType,'wff')
    g.filtered=g0.filtered;
else
    g.wx=g0.wx;
    g.wy=g0.wy;
    g.r=g0.r;
    g.phase=g0.phase;
    g.filtered=g.r.*exp(sqrt(-1)*g.phase);
end
save result g;
H=findobj('Name','Windowed Fourier Transform (WFT)');figure(H);imagesc(angle(g.filtered));
H=findobj('Name','WFT Kernel');close(H);

author: Sable

repo: mcbench-benchmarks


text:
function I = domIntegral6(data)
%+========================================================================+
%|                                                                        |
%|              OPENDOM - LIBRARY FOR NUMERICAL INTEGRATION               |
%|           openDom is part of the GYPSILAB toolbox for Matlab           |
%|                                                                        |
%| COPYRIGHT : Matthieu Aussal & Francois Alouges (c) 2017-2018.          |
%| PROPERTY  : Centre de Mathematiques Appliquees, Ecole polytechnique,   |
%| route de Saclay, 91128 Palaiseau, France. All rights reserved.         |
%| LICENCE   : This program is free software, distributed in the hope that|
%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use,    |
%| redistribute and/or modify it under the terms of the GNU General Public|
%| License, as published by the Free Software Foundation (version 3 or    |
%| later,  http://www.gnu.org/licenses). For private use, dual licencing  |
%| is available, please contact us to activate a "pay for remove" option. |
%| CONTACT   : matthieu.aussal@polytechnique.edu                          |
%|             francois.alouges@polytechnique.edu                         |
%| WEBSITE   : www.cmap.polytechnique.fr/~aussal/gypsilab                 |
%|                                                                        |
%| Please acknowledge the gypsilab toolbox in programs or publications in |
%| which you use it.                                                      |
%|________________________________________________________________________|
%|   '&`   |                                                              |
%|    #    |   FILE       : domIntegral6.m                                |
%|    #    |   VERSION    : 0.61                                          |
%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |
%|  ( # )  |   CREATION   : 14.03.2017                                    |
%|  / 0 \  |   LAST MODIF : 05.09.2019                                    |
%| ( === ) |   SYNOPSIS   : Numerical integation with 6 input arguments   |
%|  `---'  |                                                              |
%+========================================================================+

%%% H-MATRIX BOUNDARY ELEMENT OPERATOR  --> \int_{mesh(x)} \int_{mesh(y)} psi(x)' f(x,y) psi(y) dxdy
if isa(data{1},'dom') && isa(data{2},'dom')
    % Domain with quadrature
    Xdom   = data{1};
    [X,Wx] = Xdom.qud;
    Nx     = size(X,1);
    Wx     = spdiags(Wx,0,Nx,Nx);

    % Domain with quadrature
    Ydom   = data{2};
    [Y,Wy] = Ydom.qud;
    Ny     = size(Y,1);
    Wy     = spdiags(Wy,0,Ny,Ny);

    % Finite element matrix with integration
    u  = data{3};
    Mu = u.uqm(Xdom);
    if iscell(Mu)
        Mu{1} = Mu{1}' * Wx;
        Mu{2} = Mu{2}' * Wx;
        Mu{3} = Mu{3}' * Wx;
    else
        Mu = Mu' * Wx;
    end

    % Green kernel
    green = data{4};

    % Finite element matrix with integration
    v  = data{5};
    Mv = v.uqm(Ydom);
    if iscell(Mv)
        Mv{1} = Wy * Mv{1};
        Mv{2} = Wy * Mv{2};
        Mv{3} = Wy * Mv{3};
    else
        Mv = Wy * Mv;
    end

    % Accuracy
    tol = data{6};

    % H-Matrix Integration
    if iscell(Mu) && ~iscell(green) && ~iscell(Mv)
        I{1} = hmx(u.unk,v.unk,Mu{1},X,green,Y,Mv,tol);
        I{2} = hmx(u.unk,v.unk,Mu{2},X,green,Y,Mv,tol);
        I{3} = hmx(u.unk,v.unk,Mu{3},X,green,Y,Mv,tol);

    elseif ~iscell(Mu) && iscell(green) && ~iscell(Mv)
        I{1} = hmx(u.unk,v.unk,Mu,X,green{1},Y,Mv,tol);
        I{2} = hmx(u.unk,v.unk,Mu,X,green{2},Y,Mv,tol);
        I{3} = hmx(u.unk,v.unk,Mu,X,green{3},Y,Mv,tol);

    elseif ~iscell(Mu) && ~iscell(green) && iscell(Mv)
        I{1} = hmx(u.unk,v.unk,Mu,X,green,Y,Mv{1},tol);
        I{2} = hmx(u.unk,v.unk,Mu,X,green,Y,Mv{2},tol);
        I{3} = hmx(u.unk,v.unk,Mu,X,green,Y,Mv{3},tol);

    else
        I = hmx(u.unk,v.unk,Mu,X,green,Y,Mv,tol);
    end

%%% FFM BOUNDARY ELEMENT INTEGRATION --> \int_{mesh(y)} f(x,y) psi(y) dy
elseif isnumeric(data{1}) && isa(data{2},'dom')
    % Evaluation points
    X  = data{1};
    Nx = size(X,1);
    Mx = speye(Nx,Nx);

    % Domain with quadrature
    Ydom   = data{2};
    [Y,Wy] = Ydom.qud;
    Ny     = size(Y,1);
    Wy     = spdiags(Wy,0,Ny,Ny);

    % Green kernel
    green = data{3};

    % Wave number
    k = data{4};

    % Integrated finite element matrix
    v  = data{5};
    Mv = v.uqm(Ydom);
    if iscell(Mv)
        Mv{1} = Wy * Mv{1};
        Mv{2} = Wy * Mv{2};
        Mv{3} = Wy * Mv{3};
    else
        Mv = Wy * Mv;
    end

    % Accuracy
    tol = data{6};

    % Fast & Furious integration
    if iscell(Mv) && iscell(green)
        I = ffm(Mx,X,green{1},k,Y,Mv{1},tol) + ...
            ffm(Mx,X,green{2},k,Y,Mv{2},tol) + ...
            ffm(Mx,X,green{3},k,Y,Mv{3},tol);

    elseif iscell(Mv) && ~iscell(green)
        I{1} = ffm(Mx,X,green,k,Y,Mv{1},tol);
        I{2} = ffm(Mx,X,green,k,Y,Mv{2},tol);
        I{3} = ffm(Mx,X,green,k,Y,Mv{3},tol);

    elseif ~iscell(Mv) && iscell(green)
        I{1} = ffm(Mx,X,green{1},k,Y,Mv,tol);
        I{2} = ffm(Mx,X,green{2},k,Y,Mv,tol);
        I{3} = ffm(Mx,X,green{3},k,Y,Mv,tol);

    else
        I = ffm(Mx,X,green,k,Y,Mv,tol);
    end

%%% FFM BOUNDARY ELEMENT INTEGRATION --> \int_{mesh(x)} psi(x)' f(x,y) dx
elseif isa(data{1},'dom') && isnumeric(data{2})
    % Domain with quadrature
    Xdom   = data{1};
    [X,Wx] = Xdom.qud;
    Nx     = size(X,1);
    Wx     = spdiags(Wx,0,Nx,Nx);

    % Evaluation points
    Y  = data{2};
    Ny = size(Y,1);
    My = speye(Ny,Ny);

    % Integrated finite element matrix
    u  = data{3};
    Mu = u.uqm(Xdom);
    if iscell(Mu)
        Mu{1} = Mu{1}' * Wx;
        Mu{2} = Mu{2}' * Wx;
        Mu{3} = Mu{3}' * Wx;
    else
        Mu = Mu' * Wx;
    end

    % Green kernel
    green = data{4};

    % Wave number
    k = data{5};

    % Accuracy
    tol = data{6};

    % Fast & Furious integration
    if iscell(Mu) && iscell(green)
        I = ffm(Mu{1},X,green{1},k,Y,My,tol) + ...
            ffm(Mu{2},X,green{2},k,Y,My,tol) + ...
            ffm(Mu{3},X,green{3},k,Y,My,tol) ;

    elseif iscell(Mu) && ~iscell(green)
        I{1} = ffm(Mu{1},X,green,k,Y,My,tol);
        I{2} = ffm(Mu{2},X,green,k,Y,My,tol);
        I{3} = ffm(Mu{3},X,green,k,Y,My,tol);

    elseif ~iscell(Mu) && iscell(green)
        I{1} = ffm(Mu,X,green{1},k,Y,My,tol);
        I{2} = ffm(Mu,X,green{2},k,Y,My,tol);
        I{3} = ffm(Mu,X,green{3},k,Y,My,tol);

    else
        I = ffm(Mu,X,green,k,Y,My,tol);
    end

else
    error('domIntegral6.m : unavailable case')
end
end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function [sDataPET] = correctPatient24_HN(pathDATA)
% -------------------------------------------------------------------------
% function [sDataPET] = correctPatient24_HN(pathDATA)
% -------------------------------------------------------------------------
% DESCRIPTION:
% Reason of existence of the function: the RTstruct of the PET scan of
% patient 24 is incomplete (most probably it was previously incorrectly
% processed by MIM). The problem is solved by copying and processing the
% 'contour' structure of the CT scan.
% -------------------------------------------------------------------------
% INPUTS:
% - pathDATA: Full path to the 'DATA' folder of the HN workspace.
% -------------------------------------------------------------------------
% OUTPUTS:
% - sData: Corrected sData.
% -------------------------------------------------------------------------
% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>
% -------------------------------------------------------------------------
% HISTORY:
% - Creation: July 2015
%--------------------------------------------------------------------------
% STATEMENT:
% This file is part of <https://github.com/mvallieres/radiomics/>,
% a package providing MATLAB programming tools for radiomics analysis.
% --> Copyright (C) 2015  Martin Vallieres
%
%    This package 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 package 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 package.  If not, see <http://www.gnu.org/licenses/>.
% -------------------------------------------------------------------------

startpath = pwd;
cd(pathDATA)
load('Patient24_CT'), sDataCT = sData;
load('Patient24_PET'), sDataPET = sData;

% ADJUSTING PET CONTOURS ACCORDING TO CT CONTOURS.
sDataPET{2}.scan.contour = sDataCT{2}.scan.contour;
nContour = length(sDataPET{2}.scan.contour);
downF = sDataPET{2}.scan.pixelW/sDataCT{2}.scan.pixelW;
offsetStart = round(abs(sDataPET{3}(1).ImagePositionPatient(2)-sDataCT{3}(1).ImagePositionPatient(2))*sDataCT{2}.scan.pixelW);
offsetEnd = round((size(sDataCT{2}.scan.volume,1)*sDataCT{2}.scan.pixelW - size(sDataPET{2}.scan.volume,1)*sDataPET{2}.scan.pixelW)/sDataCT{2}.scan.pixelW)-offsetStart;
for i = 1:nContour
    sDataPET{2}.scan.contour(i).boxBound(1:2,1) = round((sDataCT{2}.scan.contour(i).boxBound(1:2,1) - offsetStart)/downF); sDataPET{2}.scan.contour(i).boxBound(1:2,2) = round((sDataCT{2}.scan.contour(i).boxBound(1:2,2) - offsetEnd)/downF);
    boxBound = sDataPET{2}.scan.contour(i).boxBound;
    nSlices = size(sDataPET{2}.scan.contour(i).boxMask,3);
    sDataPET{2}.scan.contour(i).boxMask = zeros(boxBound(1,2)-boxBound(1,1)+1,boxBound(2,2)-boxBound(2,1)+1,nSlices);
    for j = 1:nSlices
        sDataPET{2}.scan.contour(i).boxMask(:,:,j) = imresize(sDataCT{2}.scan.contour(i).boxMask(:,:,j),[boxBound(1,2)-boxBound(1,1)+1,boxBound(2,2)-boxBound(2,1)+1],'nearest');
    end
end

cd(startpath)
end

author: mvallieres

repo: radiomics


text:
function scale = p29_scale ( neqn )

%*****************************************************************************80
%
%% P29_SCALE returns scale factors for problem p29.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NEQN, the number of equations.
%
%    Output, real SCALE(NEQN), the scaling factors.
%
  scale(1:neqn,1) = 1.0;

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function gegenbauer_poly_test ( )

%*****************************************************************************80
%
%% GEGENBAUER_POLY_TEST tests GEGENBAUER_POLY.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 October 2008
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'GEGENBAUER_POLY_TEST:\n' );
  fprintf ( 1, '  GEGENBAUER_POLY computes values of \n' );
  fprintf ( 1, '    the Gegenbauer polynomial.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '       N       A       X       GPV      GEGENBAUER\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, n, a, x, fx ] = gegenbauer_poly_values ( n_data );

    if ( n_data == 0 )
      break
    end

    c = gegenbauer_poly ( n, a, x );
    fx2 = c(n+1);

    fprintf ( 1, '  %6d  %8f  %8f  %12f  %12f\n', n, a, x, fx, fx2 );

  end

  return
end


text:
function phiFaceAverage = geometricMean(phi)
% This function gets the value of the field variable phi defined
% over the MeshStructure and calculates the geometric average on
% the cell faces, for a uniform mesh.
%
% SYNOPSIS:
%   phiFaceAverage = geometricMean(phi)
%
% PARAMETERS:
%
%
% RETURNS:
%
%
% EXAMPLE:
%
% SEE ALSO:
%

% Written by Ali A. Eftekhari
% See the license file

% extract data from the mesh structure

d = phi.domain.dimension;
if (d ==1) || (d==1.5) || (d==1.8)
    dx = phi.domain.cellsize.x;
    xvalue=exp((dx(1:end-1).*log(phi.value(1:end-1))+dx(2:end).*log(phi.value(2:end)))./(dx(2:end)+dx(1:end-1)));
    yvalue=[];
    zvalue=[];
elseif (d == 2) || (d == 2.5) || (d == 2.8)
    Nx = phi.domain.dims(1);
    Ny = phi.domain.dims(2);
    dx = repmat(phi.domain.cellsize.x, 1, Ny);
    dy = repmat(phi.domain.cellsize.y', Nx, 1);
	xvalue=exp((dx(1:end-1,:).*log(phi.value(1:end-1,2:end-1))+...
        dx(2:end,:).*log(phi.value(2:end,2:end-1)))./(dx(2:end,:)+dx(1:end-1,:)));
    yvalue=exp((dy(:,1:end-1).*log(phi.value(2:end-1,1:end-1))+...
        dy(:,2:end).*log(phi.value(2:end-1,2:end)))./(dy(:,2:end)+dy(:,1:end-1)));
    zvalue=[];
elseif (d == 3) || (d==3.2)
    Nx = phi.domain.dims(1);
    Ny = phi.domain.dims(2);
    Nz = phi.domain.dims(3);
    dx = repmat(phi.domain.cellsize.x, 1, Ny, Nz);
    dy = repmat(phi.domain.cellsize.y', Nx, 1, Nz);
    DZ = zeros(1,1,Nz+2);
    DZ(1,1,:) = phi.domain.cellsize.z;
    dz=repmat(DZ, Nx, Ny, 1);
    xvalue=exp((dx(1:end-1,:,:).*log(phi.value(1:end-1,2:end-1,2:end-1))+...
        dx(2:end,:,:).*log(phi.value(2:end,2:end-1,2:end-1)))./(dx(2:end,:,:)+dx(1:end-1,:,:)));
    yvalue=exp((dy(:,1:end-1,:).*log(phi.value(2:end-1,1:end-1,2:end-1))+...
        dy(:,2:end,:).*log(phi.value(2:end-1,2:end,2:end-1)))./(dy(:,1:end-1,:)+dy(:,2:end,:)));
    zvalue=exp((dz(:,:,1:end-1).*log(phi.value(2:end-1,2:end-1,1:end-1))+...
        dz(:,:,2:end).*log(phi.value(2:end-1,2:end-1,2:end)))./(dz(:,:,1:end-1)+dz(:,:,2:end)));
end
phiFaceAverage=FaceVariable(phi.domain, xvalue, yvalue, zvalue);

author: simulkade

repo: FVTool

save_path: github-repos/MATLAB/simulkade-FVTool


text:
function pdf = geometric_pdf ( x, a )

%*****************************************************************************80
%
%% GEOMETRIC_PDF evaluates the Geometric PDF.
%
%  Discussion:
%
%    PDF(X)(A) = A * ( 1 - A )**(X-1)
%
%    PDF(X)(A) is the probability that exactly X Bernoulli trials, each
%    with probability of success A, will be required to achieve
%    a single success.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer X, the number of trials.
%    0 < X
%
%    Input, real A, the probability of success on one trial.
%    0.0 <= A <= 1.0.
%
%    Output, real PDF, the value of the PDF.
%

%
%  Special cases.
%
  if ( x < 1 )

    pdf = 0.0;

  elseif ( a == 0.0 )

    pdf = 0.0;

  elseif ( a == 1.0 )

    if ( x == 1 )
      pdf = 1.0;
    else
      pdf = 0.0;
    end

  else

    pdf = a * ( 1.0 - a )^( x - 1 );

  end

  return
end


text:
function [params, result] = ortho_quasi(params, W, w)
% Quasi-orthogonalization
%   W = orthof(params, W)     for symmetric dss
%   w = orthof(params, W, w)  for deflation dss
%     params.alpha  For deflation...
%     W Matrix with projection vectors as rows. For deflation
%       algorithm only previously calculated projections are given.
%     w Currently iterated projection. Only for deflation algorithm.

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

if nargin<2
    params.name = 'Quasi-orthogonalization';
    params.description = 'Description of this function.';
    params.param = {'alpha'};
    params.param_type = {'scalar'};
    params.param_value = {0.1};
    params.param_desc = {'For deflation...'};
    return;
end

if ~isfield(params, 'alpha')
  % TODO: set alpha based on data dimension
  params.alpha = 0.1;
end

if nargin>2
  % per component quasi-orthogonalization
  w = w - params.alpha * W' * W * w;
  result = w / norm(w);
else
  % symmetric quasi-orthogonalization
  W = 3/2*W - W'*W*W'/2;
  result = W.*(sum(W.^2,2).^(-1/2)*ones(1,size(W,2)));
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function X_rec = recoverData(Z, U, K)
%RECOVERDATA Recovers an approximation of the original data when using the
%projected data
%   X_rec = RECOVERDATA(Z, U, K) recovers an approximation the
%   original data that has been reduced to K dimensions. It returns the
%   approximate reconstruction in X_rec.
%

% You need to return the following variables correctly.
X_rec = zeros(size(Z, 1), size(U, 1));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the approximation of the data by projecting back
%               onto the original space using the top K eigenvectors in U.
%
%               For the i-th example Z(i,:), the (approximate)
%               recovered data for dimension j is given as follows:
%                    v = Z(i, :)';
%                    recovered_j = v' * U(j, 1:K)';
%
%               Notice that U(j, 1:K) is a row vector.
%
U_reduce = U(:,1:K);
X_rec = Z*U_reduce';

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

end

repo: MachineLearningEx


text:
function values = generic_wizard(varargin)

api.Data     = get_option(varargin,'data',rand(1000,7));
api.Header   = get_option(varargin,'header','i am a header');
api.Columns  = get_option(varargin,'columns','');

if size(api.Columns,2) ~= size(api.Data,2)
  api.Columns = cellfun(@(x) ['Column' num2str(x)], ...
    num2cell(1:size(api.Data,2)),'UniformOutput',false);
end

api.Type     = get_option(varargin,'type','EBSD');

api.isPublishMode       = getMTEXpref('generatingHelpMode');

p = get(0,'MonitorPositions');
api = WizardEmptyGUIApi(api,'PageHeight',min(2/3*p(1,4),600));
api = GenericApi(api);

waitfor(api.hFigure);

values = api.getOptions();

end

author: mtex-toolbox

repo: mtex

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


text:
function FigSize(xdim,ydim)
% =======================================================================
% Sets the figure window to a desired size. The default is full screen
% =======================================================================
% FigSize(xdim,ydim)
% -----------------------------------------------------------------------
% OPTIONAL INPUT
%   - xdim: horizontal size (in cm)
%   - ydim: vertical size (in cm)
% =======================================================================
% Ambrogio Cesa Bianchi, March 2015
% ambrogio.cesabianchi@gmail.com

if nargin==0
    figure('units','normalized','outerposition',[0 0.1 1 0.9])
else
    % Get the position of the figure
    % [left bottom width height] [standard in px: 403 246   560   420]
    position = get(gcf, 'Position');

    % Place the figure on the south west corner of the screen (in cm)
    position(1) = 1;
    position(2) = 2;

    % xdim dimension in cm
    if exist('xdim','var')
        position(3) = xdim;
    end

    % ydim dimension in cm
    if exist ('ydim','var')
        position(4) = ydim;
    end

    % Apply rescaling
    set(gcf, 'units', 'centimeters', 'Position', position)
end

author: ambropo

repo: VAR-Toolbox

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


text:
classdef nnsoftmax < nntest
  properties (TestParameter)
    h = {1 2 3}
    w = {1 2}
  end
  methods (Test)
    function basic(test,h,w)
      d = 10 ;
      n = 3 ;
      x = test.randn(h,w,d,n,'single')/test.range ;
      y = vl_nnsoftmax(x) ;
      dzdy = test.randn(size(y),'single') ;
      dzdx = vl_nnsoftmax(x, dzdy) ;
      test.der(@(x) vl_nnsoftmax(x), x, dzdy, dzdx, 1e-2) ;
    end
  end
end

author: willard-yuan

repo: cnn-for-image-retrieval


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

% Last Modified by GUIDE v2.5 03-Dec-2018 17:15:45

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

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

    centerUIFigure(hObject);

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

	populateGUI(handles, stage);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, stage)
    set(handles.stageNameText,'String',stage.name);
    set(handles.dryMassText,'String',fullAccNum2Str(stage.getStageDryMass()));

    optVar = stage.getExistingOptVar();
	if(isempty(optVar))
        optVar = stage.getNewOptVar();
	end

    handles.optCheckbox.Value = double(optVar.getUseTfForVariable());

    [lb, ub] = optVar.getAllBndsForVariable();
    handles.lbText.String = fullAccNum2Str(lb);
    handles.ubText.String = fullAccNum2Str(ub);

    optCheckbox_Callback(handles.optCheckbox, [], handles);

% --- Outputs from this function are returned to the command line.
function varargout = lvd_EditStageGUI_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
        stage = getappdata(hObject, 'stage');

        name = handles.stageNameText.String;
        dryMass = str2double(handles.dryMassText.String);

        stage.name = name;
        stage.dryMass = dryMass;

        optVar = stage.getExistingOptVar();
        if(not(isempty(optVar)))
            stage.launchVehicle.lvdData.optimizer.vars.removeVariable(optVar);
        end
        optVar = stage.getNewOptVar();

        optDryMass = logical(handles.optCheckbox.Value);
        lbDryMass = str2double(handles.lbText.String);
        ubDryMass = str2double(handles.ubText.String);

        optVar.setUseTfForVariable(optDryMass);
        optVar.setBndsForVariable(lbDryMass,ubDryMass);
        stage.launchVehicle.lvdData.optimizer.vars.addVariable(optVar);

        varargout{1} = true;
        close(handles.lvd_EditStageGUI);
    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_EditStageGUI);
    else
        msgbox(errMsg,'Invalid Stage Inputs','error');
    end

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

    dryMass = str2double(get(handles.dryMassText,'String'));
    enteredStr = get(handles.dryMassText,'String');
    numberName = 'Dry Mass';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(dryMass, numberName, lb, ub, isInt, errMsg, enteredStr);

    lwrBnd = str2double(get(handles.lbText,'String'));
    enteredStr = get(handles.lbText,'String');
    numberName = 'Dry Mass (Lower Bound)';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(lwrBnd, numberName, lb, ub, isInt, errMsg, enteredStr);

    uprBnd = str2double(get(handles.ubText,'String'));
    enteredStr = get(handles.ubText,'String');
    numberName = 'Dry Mass (Upper Bound)';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(uprBnd, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        uprBnd = str2double(get(handles.ubText,'String'));
        enteredStr = get(handles.ubText,'String');
        numberName = 'Dry Mass (Upper Bound)';
        lb = lwrBnd;
        ub = Inf;
        isInt = false;
        errMsg = validateNumber(uprBnd, numberName, lb, ub, isInt, errMsg, enteredStr);
    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_EditStageGUI);

function stageNameText_Callback(hObject, eventdata, handles)
% hObject    handle to stageNameText (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 stageNameText as text
%        str2double(get(hObject,'String')) returns contents of stageNameText as a double

% --- Executes during object creation, after setting all properties.
function stageNameText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to stageNameText 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 dryMassText_Callback(hObject, eventdata, handles)
% hObject    handle to dryMassText (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 dryMassText as text
%        str2double(get(hObject,'String')) returns contents of dryMassText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function dryMassText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to dryMassText (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 button press in optCheckbox.
function optCheckbox_Callback(hObject, eventdata, handles)
% hObject    handle to optCheckbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of optCheckbox
    if(get(hObject,'Value'))
        handles.lbText.Enable = 'on';
        handles.ubText.Enable = 'on';
    else
        handles.lbText.Enable = 'off';
        handles.ubText.Enable = 'off';
    end

function lbText_Callback(hObject, eventdata, handles)
% hObject    handle to lbText (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 lbText as text
%        str2double(get(hObject,'String')) returns contents of lbText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function lbText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to lbText (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 ubText_Callback(hObject, eventdata, handles)
% hObject    handle to ubText (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 ubText as text
%        str2double(get(hObject,'String')) returns contents of ubText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function ubText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ubText (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_EditStageGUI or any of its controls.
function lvd_EditStageGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditStageGUI (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_EditStageGUI);
    end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function h=entropyDist(npd)
%
% Compute entropy estimate using nearest neighbor estimate
%

% Copyright (C) 2003 Alexander Ihler; distributable under GPL -- see README.txt

Ce = .57721566490153286;

pts = getPoints(npd);

[N1,N2] = size(pts);
[tmp,D] = knn(npd,pts,2);

Sr = N1* pi^(N1/2) / gamma((N1/2) + 1);
h = N1/N2 * sum( log(D) ) + log(Sr * (N2-1)/N1 ) + Ce;

author: ShapeNet

repo: RenderForCNN


text:
%**************************************************************
%* mex interface to Andy Liaw et al.'s C code (used in R package randomForest)
%* Added by Abhishek Jaiantilal ( abhishek.jaiantilal@colorado.edu )
%* License: GPLv2
%* Version: 0.02
%
% Calls Classification Random Forest
% A wrapper matlab file that calls the mex file
% This does training given the data and labels
% Documentation copied from R-packages pdf
% http://cran.r-project.org/web/packages/randomForest/randomForest.pdf
% Tutorial on getting this working in tutorial_ClassRF.m
%**************************************************************
% function model = classRF_train(X,Y,ntree,mtry, extra_options)
%
%___Options
% requires 2 arguments and the rest 3 are optional
% X: data matrix
% Y: target values
% ntree (optional): number of trees (default is 500). also if set to 0
%           will default to 500
% mtry (default is floor(sqrt(size(X,2))) D=number of features in X). also if set to 0
%           will default to 500
%
%
% Note: TRUE = 1 and FALSE = 0 below
% extra_options represent a structure containing various misc. options to
%      control the RF
%  extra_options.replace = 0 or 1 (default is 1) sampling with or without
%                           replacement
%  extra_options.classwt = priors of classes. Here the function first gets
%                       the labels in ascending order and assumes the
%                       priors are given in the same order. So if the class
%                       labels are [-1 1 2] and classwt is [0.1 2 3] then
%                       there is a 1-1 correspondence. (ascending order of
%                       class labels). Once this is set the freq of labels in
%                       train data also affects.
%  extra_options.cutoff (Classification only) = A vector of length equal to number of classes. The ?winning?
%                       class for an observation is the one with the maximum ratio of proportion
%                       of votes to cutoff. Default is 1/k where k is the number of classes (i.e., majority
%                       vote wins).
%  extra_options.strata = (not yet stable in code) variable that is used for stratified
%                       sampling. I don't yet know how this works. Disabled
%                       by default
%  extra_options.sampsize =  Size(s) of sample to draw. For classification,
%                   if sampsize is a vector of the length the number of strata, then sampling is stratified by strata,
%                   and the elements of sampsize indicate the numbers to be
%                   drawn from the strata.
%  extra_options.nodesize = Minimum size of terminal nodes. Setting this number larger causes smaller trees
%                   to be grown (and thus take less time). Note that the default values are different
%                   for classification (1) and regression (5).
%  extra_options.importance =  Should importance of predictors be assessed?
%  extra_options.localImp = Should casewise importance measure be computed? (Setting this to TRUE will
%                   override importance.)
%  extra_options.proximity = Should proximity measure among the rows be calculated?
%  extra_options.oob_prox = Should proximity be calculated only on 'out-of-bag' data?
%  extra_options.do_trace = If set to TRUE, give a more verbose output as randomForest is run. If set to
%                   some integer, then running output is printed for every
%                   do_trace trees.
%  extra_options.keep_inbag Should an n by ntree matrix be returned that keeps track of which samples are
%                   'in-bag' in which trees (but not how many times, if sampling with replacement)
%
% Options eliminated
% corr_bias which happens only for regression ommitted
% norm_votes - always set to return total votes for each class.
%
%___Returns model which has
% importance =  a matrix with nclass + 2 (for classification) or two (for regression) columns.
%       For classification, the first nclass columns are the class-specific measures
%       computed as mean decrease in accuracy. The nclass + 1st column is the
%       mean decrease in accuracy over all classes. The last column is the mean decrease
%       in Gini index. For Regression, the first column is the mean decrease in
%       accuracy and the second the mean decrease in MSE. If importance=FALSE,
%       the last measure is still returned as a vector.
% importanceSD = The ?standard errors? of the permutation-based importance measure. For classification,
%       a p by nclass + 1 matrix corresponding to the first nclass + 1
%       columns of the importance matrix. For regression, a length p vector.
% localImp = a p by n matrix containing the casewise importance measures, the [i,j] element
%       of which is the importance of i-th variable on the j-th case. NULL if
%       localImp=FALSE.
% ntree = number of trees grown.
% mtry  = number of predictors sampled for spliting at each node.
% votes (classification only) a matrix with one row for each input data point and one
%       column for each class, giving the fraction or number of ?votes? from the random
%       forest.
% oob_times number of times cases are 'out-of-bag' (and thus used in computing OOB error
%       estimate)
% proximity if proximity=TRUE when randomForest is called, a matrix of proximity
%       measures among the input (based on the frequency that pairs of data points are
%       in the same terminal nodes).
% errtr = first column is OOB Err rate, second is for class 1 and so on

function model=classRF_train(X,Y,ntree,mtry, extra_options)
    DEFAULTS_ON =0;
    %DEBUG_ON=0;

    TRUE=1;
    FALSE=0;

    orig_labels = sort(unique(Y));
    Y_new = Y;
    new_labels = 1:length(orig_labels);

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

    Y = Y_new;

    if exist('extra_options','var')
        if isfield(extra_options,'DEBUG_ON');  DEBUG_ON = extra_options.DEBUG_ON;    end
        if isfield(extra_options,'replace');  replace = extra_options.replace;       end
        if isfield(extra_options,'classwt');  classwt = extra_options.classwt;       end
        if isfield(extra_options,'cutoff');  cutoff = extra_options.cutoff;       end
        if isfield(extra_options,'strata');  strata = extra_options.strata;       end
        if isfield(extra_options,'sampsize');  sampsize = extra_options.sampsize;       end
        if isfield(extra_options,'nodesize');  nodesize = extra_options.nodesize;       end
        if isfield(extra_options,'importance');  importance = extra_options.importance;       end
        if isfield(extra_options,'localImp');  localImp = extra_options.localImp;       end
        if isfield(extra_options,'nPerm');  nPerm = extra_options.nPerm;       end
        if isfield(extra_options,'proximity');  proximity = extra_options.proximity;       end
        if isfield(extra_options,'oob_prox');  oob_prox = extra_options.oob_prox;       end
        %if isfield(extra_options,'norm_votes');  norm_votes = extra_options.norm_votes;       end
        if isfield(extra_options,'do_trace');  do_trace = extra_options.do_trace;       end
        %if isfield(extra_options,'corr_bias');  corr_bias = extra_options.corr_bias;       end
        if isfield(extra_options,'keep_inbag');  keep_inbag = extra_options.keep_inbag;       end
    end
    keep_forest=1; %always save the trees :)

    %set defaults if not already set
    if ~exist('DEBUG_ON','var')     DEBUG_ON=FALSE; end
    if ~exist('replace','var');     replace = TRUE; end
    %if ~exist('classwt','var');     classwt = []; end %will handle these three later
    %if ~exist('cutoff','var');      cutoff = 1; end
    %if ~exist('strata','var');      strata = 1; end
    if ~exist('sampsize','var');
        if (replace)
            sampsize = size(X,1);
        else
            sampsize = ceil(0.632*size(X,1));
        end;
    end
    if ~exist('nodesize','var');    nodesize = 1; end %classification=1, regression=5
    if ~exist('importance','var');  importance = FALSE; end
    if ~exist('localImp','var');    localImp = FALSE; end
    if ~exist('nPerm','var');       nPerm = 1; end
    %if ~exist('proximity','var');   proximity = 1; end  %will handle these two later
    %if ~exist('oob_prox','var');    oob_prox = 1; end
    %if ~exist('norm_votes','var');    norm_votes = TRUE; end
    if ~exist('do_trace','var');    do_trace = FALSE; end
    %if ~exist('corr_bias','var');   corr_bias = FALSE; end
    if ~exist('keep_inbag','var');  keep_inbag = FALSE; end

    if ~exist('ntree','var') | ntree<=0
		ntree=500;
        DEFAULTS_ON=1;
    end
    if ~exist('mtry','var') | mtry<=0 | mtry>size(X,2)
        mtry =floor(sqrt(size(X,2)));
    end

    addclass =isempty(Y);

    if (~addclass && length(unique(Y))<2)
        error('need atleast two classes for classification');
    end
    [N D] = size(X);

    if N==0; error(' data (X) has 0 rows');end

    if (mtry <1 || mtry > D)
        DEFAULTS_ON=1;
    end

    mtry = max(1,min(D,round(mtry)));

    if DEFAULTS_ON
        fprintf('\tSetting to defaults %d trees and mtry=%d\n',ntree,mtry);
    end

    if ~isempty(Y)
        if length(Y)~=N,
            error('Y size is not the same as X size');
        end
        addclass = FALSE;
    else
        if ~addclass,
            addclass=TRUE;
        end
        error('have to fill stuff here')
    end

    if ~isempty(find(isnan(X)));  error('NaNs in X');   end
    if ~isempty(find(isnan(Y)));  error('NaNs in Y');   end

    %now handle categories. Problem is that categories in R are more
    %enhanced. In this i ask the user to specify the column/features to
    %consider as categories, 1 if all the values are real values else
    %specify the number of categories here
    if exist ('extra_options','var') && isfield(extra_options,'categories')
        ncat = extra_options.categories;
    else
        ncat = ones(1,D);
    end

    maxcat = max(ncat);
    if maxcat>32
        error('Can not handle categorical predictors with more than 32 categories');
    end

    %classRF - line 88 in randomForest.default.R
    nclass = length(unique(Y));
    if ~exist('cutoff','var')
        cutoff = ones(1,nclass)* (1/nclass);
    else
        if sum(cutoff)>1 || sum(cutoff)<0 || length(find(cutoff<=0))>0 || length(cutoff)~=nclass
            error('Incorrect cutoff specified');
        end
    end
    if ~exist('classwt','var')
        classwt = ones(1,nclass);
        ipi=0;
    else
        if length(classwt)~=nclass
            error('Length of classwt not equal to the number of classes')
        end
        if ~isempty(find(classwt<=0))
            error('classwt must be positive');
        end
        ipi=1;
    end

    if ~exist('proximity','var')
        proximity = addclass;
        oob_prox = proximity;
    end

    if ~exist('oob_prox','var')
        oob_prox = proximity;
    end

    %i handle the below in the mex file
%     if proximity
%         prox = zeros(N,N);
%         proxts = 1;
%     else
%         prox = 1;
%         proxts = 1;
%     end

    %i handle the below in the mex file
    if localImp
        importance = TRUE;
%        impmat = zeors(D,N);
    else
%        impmat = 1;
    end

    if importance
        if (nPerm<1)
            nPerm = int32(1);
        else
            nPerm = int32(nPerm);
        end

        %classRF
%        impout = zeros(D,nclass+2);
%        impSD  = zeros(D,nclass+1);
    else
%        impout = zeros(D,1);
%        impSD =  1;
    end

    %i handle the below in the mex file
    %somewhere near line 157 in randomForest.default.R
    if addclass
%        nsample = 2*n;
    else
%        nsample = n;
    end

    Stratify = (length(sampsize)>1);
    if (~Stratify && sampsize>N)
        error('Sampsize too large')
    end

    if Stratify
        if ~exist('strata','var')
            strata = Y;
        end
        nsum = sum(sampsize);
        if ( ~isempty(find(sampsize<=0)) || nsum==0)
            error('Bad sampsize specification');
        end
    else
        nsum = sampsize;
    end
    %i handle the below in the mex file
    %nrnodes = 2*floor(nsum/nodesize)+1;
    %xtest = 1;
    %ytest = 1;
    %ntest = 1;
    %labelts = FALSE;
    %nt = ntree;

	%[ldau,rdau,nodestatus,nrnodes,upper,avnode,mbest,ndtree]=
    %keyboard

    if Stratify
        strata = int32(strata);
    else
        strata = int32(1);
    end

    Options = int32([addclass, importance, localImp, proximity, oob_prox, do_trace, keep_forest, replace, Stratify, keep_inbag]);

    if DEBUG_ON
        %print the parameters that i am sending in
        fprintf('size(x) %d\n',size(X));
        fprintf('size(y) %d\n',size(Y));
        fprintf('nclass %d\n',nclass);
        fprintf('size(ncat) %d\n',size(ncat));
        fprintf('maxcat %d\n',maxcat);
        fprintf('size(sampsize) %d\n',size(sampsize));
        fprintf('sampsize[0] %d\n',sampsize(1));
        fprintf('Stratify %d\n',Stratify);
        fprintf('Proximity %d\n',proximity);
        fprintf('oob_prox %d\n',oob_prox);
        fprintf('strata %d\n',strata);
        fprintf('ntree %d\n',ntree);
        fprintf('mtry %d\n',mtry);
        fprintf('ipi %d\n',ipi);
        fprintf('classwt %f\n',classwt);
        fprintf('cutoff %f\n',cutoff);
        fprintf('nodesize %f\n',nodesize);
    end

    [nrnodes,ntree,xbestsplit,classwt,cutoff,treemap,nodestatus,nodeclass,bestvar,ndbigtree,mtry ...
        outcl, counttr, prox, impmat, impout, impSD, errtr, inbag] ...
        = mexClassRF_train(X',int32(Y_new),length(unique(Y)),ntree,mtry,int32(ncat), ...
                           int32(maxcat), int32(sampsize), strata, Options, int32(ipi), ...
                           classwt, cutoff, int32(nodesize),int32(nsum));
 	model.nrnodes=nrnodes;
 	model.ntree=ntree;
 	model.xbestsplit=xbestsplit;
 	model.classwt=classwt;
 	model.cutoff=cutoff;
 	model.treemap=treemap;
 	model.nodestatus=nodestatus;
 	model.nodeclass=nodeclass;
 	model.bestvar = bestvar;
 	model.ndbigtree = ndbigtree;
    model.mtry = mtry;
    model.orig_labels=orig_labels;
    model.new_labels=new_labels;
    model.nclass = length(unique(Y));
    model.outcl = outcl;
    model.counttr = counttr;
    if proximity
        model.proximity = prox;
    else
        model.proximity = [];
    end
    model.localImp = impmat;
    model.importance = impout;
    model.importanceSD = impSD;
    model.errtr = errtr';
    model.inbag = inbag;
    model.votes = counttr';
    model.oob_times = sum(counttr)';
 	clear mexClassRF_train
    %keyboard
    1;

repo: sr-metric


text:
function grad = B_mixture_mse(input_layers, CostLayer)
predicted{1} = input_layers{1}.a;
predicted{2} = input_layers{2}.a;
ref{1} = input_layers{3}.a;
ref{2} = input_layers{4}.a;

[D,T,N] = size(ref{1});

ref_idx = CostLayer.ref_idx;

precision = class(gather(predicted{1}(1)));
if IsInGPU(predicted{1}(1))
    for i=1:length(predicted)
        grad{i} = gpuArray.zeros(size(predicted{1}), precision);
    end
else
    for i=1:length(predicted)
        grad{i} = zeros(size(predicted{1}), precision);
    end
end

for i=1:N
    idx = ref_idx(:,i);
    for j=1:length(idx)
        diff = predicted{j}(:,:,i) - ref{idx(j)}(:,:,i);
        grad{j}(:,:,i) = diff / T / N;
    end
end

end

author: singaxiong

repo: SignalGraph


text:
function e = rmModelSearchFit_oneGaussianNonlinear(p,Y,Xv,Yv,stim, hrf, scan_num, t)
% rmModelSearchFit_oneGaussianNonlinear - actual fit function of rmSearchFit
%
% error = rmModelSearchFit(p,Y,trends,Xgrid,YGrid,stimulusMatrix);
%
% Basic barebones fit of a single time-series. Error is returned in
% percentage: 100% is RSS of unfitted time-series. This way we can quantify
% the improvement of the fit independend of the variation in the raw
% time-series.
%
% 2006/06 SOD: wrote it.
% 2006/12 SOD: modifications for fmincon, this is litterally called >10000
% times so we cut every corner possible.
% 2010/02 SOD: evaluated lscov this did not improve performance here (using
% profiler)

% make RF (taken from rfGaussian2d)
Xv = Xv - p(1);   % positive x0 moves center right
Yv = Yv - p(2);   % positive y0 moves center up
RF = exp( (Yv.*Yv + Xv.*Xv) ./ (-2.*(p(3).^2)) );

% make prediction (taken from rfMakePrediction)
pred = (stim*RF).^p(4);

for scan = 1:numel(hrf)
    inds = scan_num == scan;
    pred(inds,:) = filter(hrf{scan}, 1, pred(inds,:));
end

X = [pred t];

% fit - inlining pinv
%b = pinv(X)*Y;
[U,S,V] = svd(X,0);

s = diag(S);
tol = numel(X) * eps(max(s));
r = sum(s > tol);
if (r == 0)
    pinvX = zeros(size(X'));
else
    s = diag(ones(r,1)./s(1:r));
    pinvX = V(:,1:r)*s*U(:,1:r)';
end
b = pinvX*Y;

% compute residual sum of squares (e)
% e = norm(Y - X*abs(b));
if b(1)>0,
    e = norm(Y - X*b);
else
    e = norm(Y).*(1+sum(abs(b(1))));
end
return;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
% VL_TEST_ECONOMIC_RELU
function vl_test_economic_relu()

x = randn(11,12,8,'single');
w = randn(5,6,8,9,'single');
b = randn(1,9,'single') ;

net.layers{1} = struct('type', 'conv', ...
                       'filters', w, ...
                       'biases', b, ...
                       'stride', 1, ...
                       'pad', 0);
net.layers{2} = struct('type', 'relu') ;

res = vl_simplenn(net, x) ;
dzdy = randn(size(res(end).x), 'like', res(end).x) ;
clear res ;

res_ = vl_simplenn(net, x, dzdy) ;
res__ = vl_simplenn(net, x, dzdy, [], 'conserveMemory', true) ;

a=whos('res_') ;
b=whos('res__') ;
assert(a.bytes > b.bytes) ;
vl_testsim(res_(1).dzdx,res__(1).dzdx,1e-4) ;
vl_testsim(res_(1).dzdw{1},res__(1).dzdw{1},1e-4) ;
vl_testsim(res_(1).dzdw{2},res__(1).dzdw{2},1e-4) ;


text:
function overall_mssim = ssim_mscale_new(img1, img2, K, window, level, weight, method)

% Multi-scale Structural Similarity Index (MS-SSIM)
% Z. Wang, E. P. Simoncelli and A. C. Bovik, "Multi-scale structural similarity
% for image quality assessment," Invited Paper, IEEE Asilomar Conference on
% Signals, Systems and Computers, Nov. 2003

if (nargin < 2 | nargin > 7)
   overall_mssim = -Inf;
   return;
end

if (~exist('K'))
   K = [0.01 0.03];
end

if (~exist('window'))
   window = fspecial('gaussian', 11, 1.5);
end

if (~exist('level'))
   level = 5;
end

if (~exist('weight'))
   weight = [0.0448 0.2856 0.3001 0.2363 0.1333];
end

if (~exist('method'))
   method = 'product';
end

if (size(img1) ~= size(img2))
   overall_mssim = -Inf;
   return;
end

[M N] = size(img1);
if ((M < 11) | (N < 11))
   overall_mssim = -Inf;
   return
end

if (length(K) ~= 2)
   overall_mssim = -Inf;
   return;
end

if (K(1) < 0 | K(2) < 0)
   overall_mssim = -Inf;
   return;
end

[H W] = size(window);

if ((H*W)<4 | (H>M) | (W>N))
   overall_mssim = -Inf;
   return;
end

if (level < 1)
   overall_mssim = -Inf;
   return
end

min_img_width = min(M, N)/(2^(level-1));
max_win_width = max(H, W);
if (min_img_width < max_win_width)
   overall_mssim = -Inf;
   return;
end

if (length(weight) ~= level | sum(weight) == 0)
   overall_mssim = -Inf;
   return;
end

if (method ~= 'wtd_sum' & method ~= 'product')
   overall_mssim = -Inf;
   return;
end

downsample_filter = ones(2)./4;
im1 = img1;
im2 = img2;
for l = 1:level
   [mssim_array(l) ssim_map_array{l} mcs_array(l) cs_map_array{l}] = ssim_index_new(im1, im2, K, window);
   [M N] = size(im1);
   filtered_im1 = filter2(downsample_filter, im1, 'valid');
   filtered_im2 = filter2(downsample_filter, im2, 'valid');
   clear im1, im2;
   im1 = filtered_im1(1:2:M-1, 1:2:N-1);
   im2 = filtered_im2(1:2:M-1, 1:2:N-1);
   ds_img_array1{l} = im1;
   ds_img_array2{l} = im2;
end

if (method == 'product')
%   overall_mssim = prod(mssim_array.^weight);
   overall_mssim = prod(mcs_array(1:level-1).^weight(1:level-1))*mssim_array(level);
else
   weight = weight./sum(weight);
   overall_mssim = sum(mcs_array(1:level-1).*weight(1:level-1)) + mssim_array(level);
end

author: thomas-koehler

repo: SupER


text:
function plotAxis = plotBackground(target,param)

hold on;

%%% Figure out the axis for the figure:
pixelDim = param.diagnostics.gifPixelDim;
axisRatio = pixelDim(2)/pixelDim(1);
xBnd = [-0.2*target.x, 1.2*target.x];
yBnd = xBnd*axisRatio;
plotAxis = [xBnd,yBnd];

%%% Set the color for the background and size of figure
set(gca,'Color',0.7*[1 1 1]);  %Grey
position = get(gcf,'Position');
position(3:4) = pixelDim;
set(gcf,'Position',position);

%%% Plot the ground
xGround = [-0.2*target.x, 1.2*target.x];
yGround = [0, 0];
brown = [0.5, 0.2, 0.1];  %Color for ground
plot(xGround, yGround,'color',brown,'LineWidth',6);

%%% Plot the tree, start position, and target position
drawTree(0.6*target.x, 0, 1);  %Plot a tree for scale
plot(0,0,'k.','MarkerSize',35);   %Start
plot(target.x,target.y,'ko','LineWidth',4,'MarkerSize',14)   %Finish

%%% Axis Stuff
xlabel('Horizontal Position')
ylabel('Vertical Position')
axis equal; axis(plotAxis); drawnow; hold off;

end

author: MatthewPeterKelly

repo: dscTutorials


text:
function [Phi,DPhi] = spm_dartel_integrate(U,t,K)
% Integrate a Dartel flow field
% FORMAT [Phi,DPhi] = spm_dartel_exp(U,t,K)
%     U    - name of flow field (nx x ny x nz x nt x 3)
%     t    - [t0 t1] Start and end time (values between 0 and 1)
%     K    - log2 of the Euler time steps to integrate the
%            flow field.
%
%     Phi  - deformation field (nx x ny x nz x 3)
%     DPhi - Jacobian determinant field (nx x ny x nz)
%
% The function integrates
%     Phi(x,t) = \int_{t_0}^{t_1} U(Phi(x,t),t) dt
% where U is a piecewise constant flow field
%
% Note: this function is ready for LDDMM-style flow fields, even
% though the none of the official Dartel tools can generate them
% yet.
% _______________________________________________________________________
%  Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% John Ashburner
% $Id: spm_dartel_integrate.m 5506 2013-05-14 17:13:43Z john $

if isa(U,'char'), U = nifti(U); end;
if isa(U,'nifti'), U = U.dat; end;

% Figure out which bits of flow field to use, the numbers of
% Euler time steps, and the scales.
nt  = size(U,4);
K   = ceil(log2(2^K/nt));
big = 2^12;
t   = min(max(t,0),1);
t0  = t(1);
t1  = t(2);
tt0 = t0*nt;
tt1 = t1*nt;
sc  = zeros(1,nt);
if t1>t0,
    for i=1:nt,
        sc(i) = max(round((min(tt1,i)-max(tt0,i-1))*big)/big,0);
    end
    ind = find(sc~=0);
else
    for i=1:nt,
        sc(i) = max(round((min(tt0,i)-max(tt1,i-1))*big)/big,0);
    end
    ind = fliplr(find(sc~=0));
end
if isempty(ind), % t0==t1
    ind = 1;
    sc  = 0;
    ts  = 0;
else
    sc = sc(ind);
    ts = zeros(1,numel(ind));
    for i=1:numel(ind),
        ts(i) = ceil(log2((2^K)*sc(i))-1/big);
        sc(i) = sc(i)*2^(K-ts(i));
    end
    if t0>t1, sc = -sc; end
end

% Do the integrations
if nargout==1,
    % Deformation field only
    u   = squeeze(single(U(:,:,:,ind(1),:)));
    Phi = dartel3('Exp',u,[ts(1), sc(1)]);
    for i=2:numel(ind),
        u   = squeeze(single(U(:,:,:,ind(i),:)));
        Phi = dartel3('comp',Phi,dartel3('Exp',u,[ts(i), sc(i)]));
    end
else
    % Deformation and Jacobian determinant fields
    u          = squeeze(single(U(:,:,:,ind(1),:)));
    [Phi,DPhi] = dartel3('Exp',u,[ts(1), sc(1), 1]);
    for i=2:numel(ind),
        u            = squeeze(single(U(:,:,:,ind(i),:)));
        [Phi1,DPhi1] = dartel3('Exp',u,[ts(i), sc(i), 1]);
        [Phi,DPhi]   = dartel3('comp',Phi,Phi1,DPhi,DPhi1);
        clear Phi1 DPhi1
    end
end


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   demo script for using short-hand version of the meshing wrappers
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% preparation
% user must add the path of iso2mesh to matlab path list
% addpath('../');

% user need to add the full path to .../iso2mesh/bin directory
% to windows/Linux/Unix PATH environment variable

%% load the sample data
load rat_head.mat

% volimage is a volumetric image such as an X-ray or MRI image
%% v2m is the short-hand version of vol2mesh

% mesh volimage at threshold level 0.05, max surface element size 3,
% maximum tetrahedral element volume 2

[node,elem,face]=v2m(volimage,0.05,3,2);

%% visualize the resulting mesh
subplot(211);
plotmesh(node,face);
axis equal;

%% alternatively, one can call vol2surf and surf2mesh separately

% v2s: shorthand version of vol2surf, s2m: shorthand version of surf2mesh

[node,face,regions,holes]=v2s(volimage,0.05,3);
[node,elem,face]=s2m(node,face,1,2);

%% visualize the resulting mesh
subplot(212)
plotmesh(node,face);
axis equal;

author: vigente

repo: gerardus

save_path: github-repos/MATLAB/vigente-gerardus


text:
function [classes,uStrings] = prtUtilStringsToClassNumbers(stringCell,uStrings)
%[classes,uniqueStrings] = prtUtilStringsToClassNumbers(stringCell)
%[classes,uniqueStrings] = prtUtilStringsToClassNumbers(stringCell,uStrings)
% xxx Need Help xxx

if nargin < 2
    [uStrings,~,classes] = unique(stringCell);
    return;
end
classes = nan(length(stringCell),1);
for i = 1:length(uStrings);
    classes(strcmpi(uStrings{i},stringCell)) = i;
end

author: covartech

repo: PRT

save_path: github-repos/MATLAB/covartech-PRT


text:
function m = cross(m1,m2)
% pointwise cross product of two vector3d
%
% Syntax
%   v = cross(v1,v2)
%
% Input
%  v1,v2 - @vector3d
%
% Output
%  v - @vector3d

m = cross@vector3d(m1,m2);

% switch from recirprocal to direct and vice verca
m.dispStyle = MillerConvention(-MillerConvention(m.dispStyle));


text:
function exportDVHData(command)
%GUI to export a DVH data file starting with a DVH plot of one or more VOI's.
%VOI's must be renamed to agree with a standard list stored in optS.defaultVOINames.
%DVH data may then be exported to a delimited text file.
%
%KU 04/14/2006
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

global planC;
global stateS;
persistent exportPlots;
indexS = planC{end};

uicolor              = [.9 .9 .9];
units = 'normalized';

%Get DVH data.
h = findobj('tag', 'DVHPlot');
ud = get(h, 'userdata');
plots = ud.plots;

for i=1:length(plots)
    strNames{i} = plots(i).struct;
end
strNames = {strNames{:}};

%Get list of standard VOI names.
okList = stateS.optS.defaultVOINames;

if nargin == 0
    command = 'init';
end

switch lower(command)
    case 'init'
        hFig = findobj('tag', 'DVHExportFigure');
        if ~isempty(hFig)
            delete(hFig);
        end
        screenSize = get(0,'ScreenSize');
        units = 'normalized';
        hFig = figure('Name', 'DVH Data Export', 'position',[screenSize(3)/10 screenSize(4)/8 screenSize(3)/10*8 screenSize(4)/10*5], 'MenuBar', 'none', 'NumberTitle', 'off', 'resize', 'off', 'Tag', 'DVHExportFigure');

        stateS.handles.figure = hFig;

        %Init List Boxes
        ud.handles.DVHList = uicontrol('units',units,'BackgroundColor',uicolor, 'Position',[.05 .10 .25 .85],'String', strNames, 'Style','listbox','Tag','DVHList');
        ud.handles.myDVHList = uicontrol('callback', 'exportDVHData(''SelectDVH'');','units',units,'BackgroundColor',uicolor, 'Position',[.35 .10 .25 .85], 'String', [], 'Style','listbox', 'Enable', 'on', 'Tag','myDVHList');

        %Make labels for listboxes
        uicontrol('units',units,'BackgroundColor',uicolor, 'Position',[.05 .95 .15 .04],'String', 'Calculated DVHs: ', 'Style','text', 'horizontalalignment', 'left');
        uicontrol('units',units,'BackgroundColor',uicolor, 'Position',[.35 .95 .15 .04],'String', 'Selected For Export: ', 'Style','text', 'horizontalalignment', 'left');

        %make buttons for adding and removing DVH's from list boxes.
        uicontrol('callback', 'exportDVHData(''addDVH'');', 'units',units,'BackgroundColor',uicolor, 'Position',[.3 .65 .05 .05],'String','-->', 'Style','pushbutton','Tag','DVHAdd');
        uicontrol('callback', 'exportDVHData(''removeDVH'');', 'units',units,'BackgroundColor',uicolor, 'Position',[.3 .55 .05 .05],'String','<--', 'Style','pushbutton','Tag','DVHRemove');

        %Make frame for checking and renaming VOI's.
        uicontrol('units',units,'BackgroundColor',uicolor, 'Position',[.65 .45 .3 .5],'String','frame', 'Style','frame','Tag','renameFrame');

        %Add pop-up menus for renaming VOI's.
        ud.handles.myDVHpopup = uicontrol('callback', 'exportDVHData(''SelectPopupDVH'');','units',units,'BackgroundColor',uicolor, 'Position',[.67 .67 .12 .05],'String', {''}, 'Style','popupmenu','Tag','myDVHpopup');
        ud.handles.okDVHList = uicontrol('units',units,'BackgroundColor',uicolor, 'Position',[.81 .67 .12 .05], 'String', okList, 'Style','popupmenu','Tag','okDVHList');
        %Make labels for pop-up menus.
        uicontrol('units',units,'BackgroundColor',uicolor, 'Position',[.66 .72 .13 .05],'String', 'Select VOI to rename', 'Style','text', 'horizontalalignment', 'left');
        uicontrol('units',units,'BackgroundColor',uicolor, 'Position',[.81 .72 .13 .05],'String', 'Select name from list', 'Style','text', 'horizontalalignment', 'left');

        %Make buttons for checking VOI names and renaming.
        uicontrol('callback', 'exportDVHData(''checknames'');', 'units',units,'BackgroundColor',uicolor, 'Position',[.70 .87 .2 .05],'String','Check VOI Names', 'Style','pushbutton','Tag','namecheck');
        uicontrol('callback', 'exportDVHData(''rename'');', 'units',units,'BackgroundColor',uicolor, 'Position',[.75 .50 .1 .05],'String','Rename', 'Style','pushbutton','Tag','rename');

        %Make buttons for export and cancel.
        uicontrol('callback', 'exportDVHData(''export'');', 'units',units,'BackgroundColor',uicolor, 'Position',[.65 .35 .1 .05],'String','Export', 'Style','pushbutton','Tag','export');
        uicontrol('callback', 'exportDVHData(''cancel'');', 'units',units,'BackgroundColor',uicolor, 'Position',[.85 .35 .1 .05],'String','Cancel', 'Style','pushbutton','Tag','cancel');
        set(hFig, 'userdata', ud);
        return;

    case 'adddvh' %add current DVH to the "selected for export" list.
        hFig = findobj('tag', 'DVHExportFigure');
        ud = get(hFig, 'userdata');
		index_selected = get(ud.handles.DVHList,'Value');
        exportList = get(findobj('tag', 'myDVHList'), 'String');
        if isempty(exportList)
            exportPlots = plots(index_selected);
        else
            for i = 1:length(exportPlots)
                if isequal(plots(index_selected).volsV, exportPlots(i).volsV)
                    warndlg('That DVH has already been selected for export!', 'Warning', 'modal');
                    break
                elseif i == length(exportPlots)
                    exportPlots = [exportPlots, plots(index_selected)];
                end
            end
        end
        for i=1:length(exportPlots)
            exportNames{i} = exportPlots(i).struct;
        end
        exportNames = {exportNames{:}};
        set(findobj('tag', 'myDVHList'), 'String', exportNames);
        set(findobj('tag', 'myDVHpopup'), 'String', exportNames);

    case 'removedvh' %Remove DVH from the "selected for export" list.
        hFig = findobj('tag', 'DVHExportFigure');
        exportList = get(findobj('tag', 'myDVHList'), 'String');
        if isempty(exportList)
            return
        end

        ud = get(hFig, 'userdata');
		index_selected = get(ud.handles.myDVHList,'Value');
        exportPlots(index_selected) = [];

        if length(exportPlots) >= 1
            for i=1:length(exportPlots)
                exportNames{i} = exportPlots(i).struct;
            end
            exportNames = {exportNames{:}};
            set(findobj('tag', 'myDVHList'), 'String', exportNames);
            set(findobj('tag', 'myDVHpopup'), 'String', exportNames);
        else
            set(findobj('tag', 'myDVHList'), 'String', []);
            set(findobj('tag', 'myDVHpopup'), 'String', {''});
        end

        %Fix index if now out of range.
        if index_selected > length(exportPlots) && length(exportPlots) >= 1
            set(findobj('tag', 'myDVHList'), 'Value', index_selected-1);
            set(findobj('tag', 'myDVHpopup'), 'Value', index_selected-1);
        end

    case 'checknames'   %Check VOI names against standard list in optS.defaultVOINames.
        exportList = get(findobj('tag', 'myDVHList'), 'String');
        if isempty(exportList)
            warndlg('No DVHs have been selected for export!', 'Warning', 'modal');
            return
        end

        k = 0;
        for i = 1:length(exportPlots)
            for j = 1:length(okList)
                if strcmpi(exportPlots(i).struct, okList{j})
                    break
                elseif j == length(okList)
                    k = k+1;
                    badNames{k} = exportPlots(i).struct;
                end
            end
        end

        if k == 0
            sentence1 = ('Ready for export!');
            Zmsgbox=msgbox(sentence1, 'modal');
            waitfor(Zmsgbox);
        else
            sentence1 = {'The following VOIs must be renamed before the DVHs can be exported:',...
                '',...
                badNames{:}};
            Zmsgbox=msgbox(sentence1);
            waitfor(Zmsgbox);
        end

    case 'selectdvh'   %Synchronize selected DVH in export list and pop-up menu.
        hFig = findobj('tag', 'DVHExportFigure');
        ud = get(hFig, 'userdata');
        index_selected = get(ud.handles.myDVHList,'Value');
        if index_selected >=1
            set(findobj('tag', 'myDVHpopup'), 'Value', index_selected);
        else
            set(findobj('tag', 'myDVHList'), 'Value', 1);
        end

    case 'selectpopupdvh'   %Synchronize selected DVH in export list and pop-up menu.
        hFig = findobj('tag', 'DVHExportFigure');
        ud = get(hFig, 'userdata');
        index_selected = get(ud.handles.myDVHpopup,'Value');
        set(findobj('tag', 'myDVHList'), 'Value', index_selected);

    case 'rename'   %Rename VOI's
        hFig = findobj('tag', 'DVHExportFigure');
        exportList = get(findobj('tag', 'myDVHList'), 'String');
        if isempty(exportList)
            warndlg('Nothing to rename!', 'Warning', 'modal');
            return
        end

        ud = get(hFig, 'userdata');
        export_index = get(ud.handles.myDVHpopup,'Value');
        OK_index = get(ud.handles.okDVHList,'Value');

        Zquestion=questdlg({'Please confirm:',...
            '',...
            ['The exported DVH for  "' exportPlots(export_index).struct '"  will be renamed  "' okList{OK_index} '."']},...
            'Confirm name change', 'Rename', 'Cancel', 'Cancel');

        if strcmpi(Zquestion, 'rename')
            exportPlots(export_index).struct = okList{OK_index};

            for i=1:length(exportPlots)
                    exportNames{i} = exportPlots(i).struct;
            end
            exportNames = {exportNames{:}};
            set(findobj('tag', 'myDVHList'), 'String', exportNames);
            set(findobj('tag', 'myDVHpopup'), 'String', exportNames);
        end

    case 'export'   %Export to file.
        exportList = get(findobj('tag', 'myDVHList'), 'String');
        if isempty(exportList)
            warndlg('No DVHs have been selected for export!', 'Warning', 'modal');
            return
        end

        k = 0;
        for i = 1:length(exportPlots)   %Check that all the names are OK.
            for j = 1:length(okList)
                if strcmpi(exportPlots(i).struct, okList{j})
                    break
                elseif j == length(okList)
                    k = k+1;
                    badNames{k} = exportPlots(i).struct;
                end
            end
        end

        if k == 0   %%%% All the names are OK.  Do the export!!!!
            exportData = [];
            dlmwrite('tempfile', length(exportPlots));
            for i = 1:length(exportPlots)
                exportData(i).struct = exportPlots(i).struct;
                exportData(i).numDoseVals = length(exportPlots(i).xVals);
                exportData(i).array(:,1) = exportPlots(i).xVals';

                %Convert dose units from Gy to cGy.
                exportData(i).array(:,1) = 100*(exportData(i).array(:,1));

                exportData(i).array(:,2) = exportPlots(i).yVals';
                exportData(i).array(:,3) = [0;exportPlots(i).volsV'];

                %Write to temporary file
                fid = fopen('tempfile', 'a');
                fprintf(fid, '\n%s\n', exportData(i).struct);
                fclose(fid);
                dlmwrite('tempfile', exportData(i).numDoseVals, '-append');
                dlmwrite('tempfile', exportData(i).array, '-append', 'delimiter', '\t', 'precision', 6);
            end
            %Save file
            [pathstr, name, ext] = fileparts(stateS.CERRFile);
            if strcmpi(ext, '.bz2')
                [pathstr, name, ext] = fileparts(fullfile(pathstr,name));
            end
            [fname, pname] = uiputfile('*.txt', 'Save as', fullfile(pathstr,name));
            if isequal(fname,0) || isequal(pname,0)
                CERRStatusString('Save cancelled. Ready.');
                delete tempfile;
                return;
            end
            saveFile = fullfile(pname, fname);
            copyfile('tempfile', saveFile);
            delete tempfile;
            hFig = findobj('tag', 'DVHExportFigure');
            delete(hFig);
        else
            sentence1 = {'The following VOIs must be renamed before the DVHs can be exported:',...
                '',...
                badNames{:}};
            Zmsgbox=msgbox(sentence1);
            waitfor(Zmsgbox);
        end

    case 'cancel'
        hFig = findobj('tag', 'DVHExportFigure');
        delete(hFig);
end

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function [anchorIDs, featIDs, PrQfeatIDs] = sampleAnchorAndFeatIDsToSplitMerge( Psi, data, algParams );
% Sample anchor ids and feature ids to perform split/merge move.
% Every split-merge move is defined by:
%   -- two *distinct* sequences (ii,jj), which we call "anchors"
%   -- two features, ki and kj, where F(ii,ki)=1 and F(jj,kj) = 1
% If ki == kj, we propose splitting these into two features,
%   otherwise, we merge ki and kj into a single feature.

F = Psi.F==1;
stateSeq = Psi.stateSeq;
ThetaM = Psi.ThetaM;

% ---------------------------------------------  select anchor sequences
if ~isfield( Psi, 'anchorIDs' )
    anchorIDs = randsample( data.N, 2 );
    else
    anchorIDs = Psi.anchorIDs;
end
ii = anchorIDs(1);
jj = anchorIDs(2);

if isfield( Psi, 'activeFeatIDs' )
    ki = Psi.activeFeatIDs(1);
    if length( Psi.activeFeatIDs ) > 1
        kj = Psi.activeFeatIDs(2);
    else
        kj = ki;
    end
end

% ---------------------------------------------  select feature IDs
switch algParams.SM.featSelectDistr
    case 'random'
        qs_ki = F(ii,:);
        if ~exist('ki','var')
            ki = multinomial_single_draw( qs_ki );
        end
        qs_kj = F(jj,:);
        if ~exist('kj','var')
            kj = multinomial_single_draw( qs_kj );
        end
    case 'splitBias'
        qs_ki = F(ii,:);
        if ~exist('ki','var')
            ki = multinomial_single_draw( qs_ki );
        end

        delta_ki = false( size(F,2) );
        delta_ki( ki ) = 1;

        qs_kj = F(jj,:) .* ~delta_ki;
        qs_kj( ki ) = F(jj,ki)*2*sum( qs_kj );
        if ~exist('kj','var')
            kj = multinomial_single_draw( qs_kj );
        end
    case 'splitBias+margLik'
        % Build cond distr. kj | ki, jj
        %  based on margLik ratio between ki and kj

        qs_ki = F(ii,:);
        if ~exist('ki','var')
            ki = multinomial_single_draw( qs_ki );
        end
        log_qs_kj = -inf( 1, size(F,2)  );
        for kk = find( F(jj,:) )
            if kk == ki
               continue;
            end
            log_qs_kj(kk) = ThetaM.calcMargLikRatio_MergeFeats( data, stateSeq, ki, kk );
        end
        M = max( log_qs_kj );
        if all( isinf(log_qs_kj) )
            qs_kj = zeros(1, size(F,2) );
            qs_kj(ki) = F(jj,ki);
        else
        qs_kj = exp( log_qs_kj - M );
        qs_kj( ki ) = F(jj,ki)*2*sum( qs_kj );
        qs_kj = qs_kj ./ sum( qs_kj );
        end
        % Final smoothing: take convex combo of 99% our qs and 1% us
        %   this avoids terrible reverse probabilities
        us = false( 1, size(F,2) );
        us( F(jj,:) ) = 1;
        us = us./sum(us);
        qs_kj = .99*qs_kj + 0.01*us;

        if ~exist('kj','var')
            kj = multinomial_single_draw( qs_kj );
        end
end
qs_ki = qs_ki ./ sum( qs_ki );
qs_kj = qs_kj ./ sum( qs_kj );
featIDs = [ki kj];

assert( ~any( isnan(qs_kj) ), 'ERROR: bad numerical calc of feat select distr.');

PrQfeatIDs = qs_ki( ki ) * qs_kj( kj );

author: michaelchughes

repo: NPBayesHMM


text:
%ADDPOSTPROC Add mapppings in POSTPROC field of a datafile
%
%   A = ADDPOSTPROC(A,MAPPING)
%   A = ADDPOSTPROC(A)
%
% INPUT
%   A        - Datafile
%   POSTPROC - Postprocessing mapping command
%
% OUTPUT
%   A       - Datafile
%
% DESCRIPTION
% Extends the set of mappings stored in A.POSTPROC.
% Existing mappings are extended sequentially:
%
%      A.POSTPROC = A.POSTPROC * MAPPING
%
% Mappings in A.POSTPROC are stored only and executed just
% after A is converted from a DATAFILE into a PRDATASET.
% The feature size of the datafile A is reset to the output
% size of PRMAPPING.
% The POSTPROC field of A can be reset by SETPOSTPROC.
%
% SEE ALSO (PRTools Guide)
% DATAFILES, SETPREPROC, SETPOSTPROC

author: marianux

repo: ecg-kit

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


text:
function [Overlap, NumInsts] = GetOverlap(Proposals, GTInsts)
GTInstsSize = size(GTInsts);
if iscell(GTInsts)
    InstFun = @(Index)CellFun(GTInsts,Index);
    NumInsts = max(GTInstsSize);
else
    if length(GTInstsSize) == 2
        NumInsts = 1;
    else
        NumInsts = GTInstsSize(3);
    end
    InstFun = @(Index)ThreeDMatFun(GTInsts,Index);

end
NumProposals = size(Proposals, 3);

Overlap = zeros(NumInsts, NumProposals);
for i = 1:NumProposals
    Proposal = Proposals(:,:,i);
    for j = 1:NumInsts
        GTInst = InstFun(j);
        Overlap(j,i) = sum(Proposal(:) & GTInst(:)) / sum(Proposal(:) | GTInst(:));
    end
end
end

function InstMask = CellFun(InstList, Index)
InstMask = InstList{Index};
end
function InstMask = ThreeDMatFun(InstList, Index)
InstMask = InstList(:,:,Index);
end
function InstMask = OneDMatFun(InstList, Index)
InstMask = InstList == Index;
end

author: KuangJuiHsu


text:
function net = resnet52_new_hope_RankLoss()

%----------------------load pretrained model----------------------
netStruct = load('./data/vgg19_coco_batch32_pool_shift_both_drop0.5/net-epoch-70.mat') ;
net = dagnn.DagNN.loadobj(netStruct.net) ;

for i = 1:36 %img cnn
    if(mod(i,2)==0)
        net.params(i).learningRate= 0.02;
    else net.params(i).learningRate= 0.001;
    end
    net.params(i).weightDecay=1;
end
net.params(1).learningRate = 0.0001;

net.addLayer('lrn1',dagnn.LRN('param',[4096,1e-8,1,0.5]),{'fc1_1bnx'},{'fc1bn_n'},{});
net.addLayer('lrn2',dagnn.LRN('param',[4096,1e-8,1,0.5]),{'fc5_2bnx'},{'fc2bn_n'},{});

%--for get harder sample
%net.addLayer('Multiple',dagnn.Multiple(),{'fc1bn_n','fc2bn_n'},{'Score'},{});

lossBlock = dagnn.RankLoss('rate',1);
net.addLayer('RankLoss',lossBlock,{'fc1bn_n','fc2bn_n'},'objective_f');

%net.conserveMemory = false;
%net.eval({'data',single(rand(224,224,3)),'data2',single(rand(1,1,20074))});
end

author: layumi

repo: Image-Text-Embedding


text:
function [expr morder] = sim_ex_bivarateCoupledOscillator(varargin)
% Simulation:  Bivariate Coupled Oscillator
%
% Description:
%
% Bivariate coupled oscillator example
%
% Author Credits:
%
% Tim Mullen, 2011
%
% References and Code:
%
% N/A
%
% ------------------------------------------------------------------------

% specify the default system of equations
expr_def = {...
    'x1(t) = 0.6*x1(t-1) +  0.65*x2(t-2)+ e1(t)' ...
    'x2(t) = 0.5*x2(t-1) + -0.3*x2(t-2) + e2(t)' ...
};

% set up argument definitions
arg_define(varargin, ...
    arg({'expr','DynamicalEquations'},expr_def,[],'System of equations'), ...
    arg({'morder','ModelOrder'},2,[1 Inf],'Model order. This is mandatory'));

if isempty(morder)
    error('SIFT:sim_examples:badParam','ModelOrder must be specified');
end

repo: REST


text:
function spm_dem_search_plot(DEM)
% plots visual search in extrinsic and intrinsic coordinates
% FORMAT spm_dem_search_plot(DEM)
%
% DEM - {DEM} structures from visual search simulations
%
% hidden causes and states
%==========================================================================
% x    - hidden states:
%   o(1) - oculomotor angle
%   o(2) - oculomotor angle
%   x(1) - relative amplitude of visual hypothesis 1
%   x(2) - relative amplitude of visual hypothesis 2
%   x(3) - ...
%
% v    - hidden causes
%
% g    - sensations:
%   g(1) - oculomotor angle (proprioception - x)
%   g(2) - oculomotor angle (proprioception - y)
%   g(3) - retinal input - channel 1
%   g(4) - retinal input - channel 2
%   g(5) - ...
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_dem_search_plot.m 4851 2012-08-20 15:03:48Z karl $

% Preliminaries
%--------------------------------------------------------------------------
clf, global STIM
N  = length(DEM);
S  = spm_read_vols(STIM.U);

% Stimulus
%======================================================================
Dx = STIM.U.dim(1)/2;
Dy = STIM.U.dim(2)/2;
a  = [];
q  = [];
c  = [];

for i = 1:N

    % i-th saccade - position
    %----------------------------------------------------------------------
    pU = DEM{i}.pU.x{1}(1:2,:)*16;
    qU = DEM{i}.qU.x{1}(1:2,:)*16;
    T  = length(pU);

    % conditional confidence
    %----------------------------------------------------------------------
    qC = DEM{i}.qU.S;
    for t = 1:length(qC)
        qV(t) = qC{t}(3,3);
    end

    % accumulate responses
    %----------------------------------------------------------------------
    a  = [a DEM{i}.qU.a{2}];                % action
    q  = [q DEM{i}.qU.x{1}(3:end,:)];       % hidden perceptual states
    c  = [c qV];                            % conditional variance

    % eye movements in extrinsic coordinates
    %======================================================================
    subplot(6,N,i)

    image((S + 1)*32), axis image off, hold on
    plot(qU(2,T) + Dy,qU(1,T) + Dx,'.g','Markersize',8)
    plot(pU(2,T) + Dy,pU(1,T) + Dx,'.r','Markersize',16)
    drawnow, hold off

    % salience map
    %======================================================================
    subplot(6,N,i + N*1)
    imagesc(DEM{i}.S), axis image off

    % sensory input
    %======================================================================
    subplot(6,N,i + N*3)

    % i-th saccade - sensory samples
    %----------------------------------------------------------------------
    o   = DEM{i}.pU.x{1}(:,T);
    s   = ADEM_sample_image(STIM.U,o,STIM.R);

    imagesc(s), axis image off

    % percept
    %======================================================================
    subplot(6,N,i + N*5)

    % i-th saccade - percept
    %----------------------------------------------------------------------
    qU    = DEM{i}.qU.x{1}(3:end,:);

    % hypotheses (0 < H < 1 = normalised neg-entropy)
    %----------------------------------------------------------------------
    h     = spm_softmax(qU(:,T),2);
    H     = 1 + h'*log(h)/log(length(h));

    % retinotopic predictions
    %----------------------------------------------------------------------
    s     = 0;
    for j = 1:length(h)
        s = s + h(j)*spm_read_vols(STIM.S{j});
    end
    image(s*H*64), axis image off

end

% set ButtonDownFcn
%--------------------------------------------------------------------------
t  = (1:length(a))*12;
subplot(6,1,3)
plot(t,a')
title('Action (EOG)','FontSize',16)
xlabel('time (ms)')
axis([1 t(end) -2 2])

subplot(6,1,5)
spm_plot_ci(q(1,:),c,t); hold on
plot(t,q), hold off
axis([1 t(end) -8 8])
title('Posterior belief','FontSize',16)
xlabel('time (ms)')

author: spm


text:
function q = p03_q ( m, c, w )

%*****************************************************************************80
%
%% P03_Q evaluates the integral for problem p03.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 August 2012
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Alan Genz,
%    A Package for Testing Multiple Integration Subroutines,
%    in Numerical Integration: Recent Developments, Software
%    and Applications,
%    edited by Patrick Keast and Graeme Fairweather,
%    Reidel, 1987, pages 337-340,
%    ISBN: 9027725144,
%    LC: QA299.3.N38.
%
%  Parameters:
%
%    Input, integer M, the dimension of the argument.
%
%    Input, real C(M), W(M), the problem parameters.
%
%    Output, real Q, the integral.
%
  c = c(:);
%
%  Here, we need to generate all possible DIM_NUM tuples with
%  values of 0 or 1.
%
  q = 0.0;
  rank = 0;
  ivec = zeros ( m, 1 );

  while ( 1 )

    [ rank, ivec ] = tuple_next ( 0, 1, m, rank, ivec );

    if ( rank == 0 )
      break
    end

    s = sum ( ivec(1:m) );

    q = q + r8_mop ( s ) / ( 1.0 + c(1:m,1)' * ivec(1:m,1) );

  end

  q = q / ( r8_factorial ( m ) * prod ( c(1:m) ) );

  return
end

author: johannesgerer

repo: jburkardt-m