text:
function [labv, labh] = testImageGraphCuts(spdata, edata, adjlist, vclassifierSP, hclassifierSP, eclassifier, ecal)

% probability of superpixel main labels
pvSP = test_boosted_dt_mc(vclassifierSP, spdata);
pvSP = 1 ./ (1+exp(-pvSP));
pvSP = pvSP ./ repmat(sum(pvSP, 2), 1, size(pvSP, 2));
[tmp, vmax] = max(pvSP, [], 2);

% probability of superpixel sub labels
phSP = test_boosted_dt_mc(hclassifierSP, spdata);
phSP = 1 ./ (1+exp(-phSP));
phSP = phSP ./ repmat(sum(phSP, 2), 1, size(phSP, 2));
[tmp, hmax] = max(phSP, [], 2);

% edge probability
pE = test_boosted_dt_mc(eclassifier, edata);
pE = 1 ./ (1+exp(ecal(1)*pE+ecal(2)));

%labv = alphaExpansion(pvSP, pE, adjlist);
labh = hmax;
labv = vmax;
% vind = find(labv==2);
% vaind = find((labv(adjlist(:, 1)) == 2) & (labv(adjlist(:, 2)) == 2));
% adjlisth = adjlist(vaind, :);
% for k = 1:size(adjlisth, 1)
%     s1 = find(adjlisth(k, 1)==vind);
%     s2 = find(adjlisth(k, 2)==vind);
%     adjlisth(k, :) = [s1 s2];
% end
% pEh = pE(vaind);
% phSP = phSP(vind, :);
%
% labh = hmax;
% tmplabh = alphaExpansion(phSP, pEh, adjlisth);
% labh(vind) = tmplabh;

%labh = alphaExpansion(phSP, pE, adjlist);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function lab = alphaExpansion(plab, pE, adjlist)

nsp = size(plab, 1);
nadj = size(adjlist, 1);

epenalty = max(log(pE)-log(1-pE), 0);% -log(1-pE); %

[tmp, lab] = max(plab, [], 2);
success = 1;
while success
    success = 0;
    for y = 1:3
        aux = find(lab(adjlist(:,1))~=lab(adjlist(:, 2)));
        naux = numel(aux);
        nnodes = nsp + naux;

        STE = zeros(2, nnodes);
        STE(1, 1:nsp) = -log(plab(:, y)');
        aind = find(lab==y);
        naind = find(lab~=y);
        STE(2, aind) = Inf;
        STE(2, naind) = -log(plab(nsp*(lab(naind)-1)+naind)); % -log P(current label)
        STE(2, nsp+1:end) = epenalty(aux);

        % nodes include main nodes and aux nodes for dealing with edges
        % between different-label nodes
        E_n = zeros(2, nadj+naux);
        E_n(1:2, 1:nadj) = adjlist';
        E_n(2, (nadj+1):(nadj+naux)) = E_n(2, aux);
        E_n(2, aux) = nsp+[1:naux];
        E_n(1, (nadj+1):(nadj+naux)) = E_n(2, aux);

        E_w = zeros(2, nadj+naux);
        for k = setdiff([1:nadj], aux')
            if lab(adjlist(k, 1)==y)
                E_w(:, k) = 0;
            else
                E_w(:, k) = epenalty(k);
            end
        end
        for k = 1:numel(aux)
            k1 = aux(k);
            k2 = k+nadj;
            if lab(adjlist(k1, 1)~=y)
                E_w(:, k) = epenalty(k1);
            end
            if lab(adjlist(k1, 2)~=y)
                E_w(:, k2) = epenalty(k1);
            end
        end

        [cut, flow] = vgg_graph_maxflow(uint32(nnodes), int16(100*STE), uint32(E_n), int16(100*E_w));

        lab2 = lab;
        lab2(logical(cut(1:nsp))) = y;

        energy1 = sum(-log(plab(nsp*(lab-1)+[1:nsp]'))) + sum(epenalty(aux));

        aux2 = find(lab2(adjlist(:,1))~=lab2(adjlist(:, 2)));
        energy2 = sum(-log(plab(nsp*(lab2-1)+[1:nsp]'))) + sum(epenalty(aux2));

        if energy2 < energy1
            %disp(['Energy 1 = ' num2str(energy1) '   Energy 2 = ' num2str(energy2)]);
            lab = lab2;
            success = 1;
        end
    end
end

author: zouchuhang

repo: LayoutNet


text:
function [R1,t1] = invert_transformation(R,t)
R1      = R';
t1      = - R'*t;
end

author: MIT-SPARK

repo: CertifiablyRobustPerception


text:
%     Steffen Urban email: steffen.urban@kit.edu
%     Copyright (C) 2014  Steffen Urban
%
%     This program is free software; you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation; either version 2 of the License, or
%     (at your option) any later version.
%
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License along
%     with this program; if not, write to the Free Software Foundation, Inc.,
%     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

% 04.03.2014 by Steffen Urban
% this is a modified file from
% Davide Scaramuzzas Toolbox OcamCalib
% original filename: click_calib.m

function click_calibUrban(calib_data)

calib_data.calibrated = 0; %this flag is - when the camera has not yet been calibrated

if isempty(calib_data.n_ima),
    data_calib(calib_data);
end;

check_active_images(calib_data);

if isempty(calib_data.I{calib_data.ind_active(1)}),
    ima_read_calib(calib_data);
    if isempty(calib_data.ind_read),
        disp('Cannot extract corners without images');
        return;
    end;
end;

fprintf(1,'\nExtraction of the grid corners on the images\n');

if isempty(calib_data.map), calib_data.map = gray(256); end;

if ~isempty(calib_data.dX),
    dX_default = calib_data.dX;
end;

if ~isempty(calib_data.dY),
    dY_default = calib_data.dY;
end;

if ~isempty(calib_data.n_sq_x),
    n_sq_x_default = calib_data.n_sq_x;
end;

if ~isempty(calib_data.n_sq_y),
    n_sq_y_default = calib_data.n_sq_y;
end;

if ~isempty(calib_data.taylor_order),
    calib_data.taylor_order_default = calib_data.taylor_order;
end;

if ~exist('dX_default')|~exist('dY_default');
    dX_default = 30;
    dY_default = 30;
end;

if ~exist('n_sq_x_default')|~exist('n_sq_y_default'),
    n_sq_x_default = 10;
    n_sq_y_default = 10;
end;

if ~exist('wintx_default')|~exist('winty_default'),
    wintx_default = max(round(calib_data.ocam_model.width/128),round(calib_data.ocam_model.height/96));
    winty_default = wintx_default;
    clear wintx winty
end;

if ~exist('xc_default'),
    xc_default = round(calib_data.ocam_model.height/2);
end;

if ~exist('yc_default'),
    yc_default = round(calib_data.ocam_model.width/2);
end;

if ~exist('taylor_order_default')
    calib_data.taylor_order_default=4;
end;

if ~exist('wintx') | ~exist('winty'),
    for kk = 1:calib_data.n_ima,
        eval(['clear wintx_' num2str(kk)]);
        eval(['clear winty_' num2str(kk)]);
    end;

end;

if ~exist('dont_ask'),
    dont_ask = 0;
end;

if ~isempty(calib_data.ima_proc)
    fprintf(1,'\nCurrently, corners have been extracted for the following image(s): %s\n',num2str(calib_data.ima_proc));
    suppress_image = input('  Do you want to suppress the current image(s) ([] = no, other = yes)? ','s');
    if isempty(suppress_image),
        ima_numbers = input('Type a vector containing the Images to add (e.g. [1 2 3]) = ');
        for i=ima_numbers
            if ~isempty(find(calib_data.ima_proc==i)),
                fprintf(1,'\nyou have already extracted corners from image %d',i);
                replace_image = input(', are you sure you want to replace this image ([] = yes, other = no)?\n','s');
                if isempty(replace_image)
                    calib_data.ima_proc=calib_data.ima_proc(find(calib_data.ima_proc~=i));
                else
                    ima_numbers(find(ima_numbers==i))=0;
                end
            end
        end
        ima_numbers= ima_numbers(find(ima_numbers~=0));
    else
        calib_data.ima_proc=[];
        ima_numbers=[];
        answer = input('\nType the images you want to process (e.g. [1 2 3], [] = all images) = ');
        if isempty(answer)
            ima_numbers = 1:calib_data.n_ima;
        else
            ima_numbers=answer;
        end
    end;
else
    answer=input('\nType the images you want to process (e.g. [1 2 3], [] = all images) = ');
    if isempty(answer)
        ima_numbers = 1:calib_data.n_ima;
    else
        ima_numbers=answer;
    end
end;

manual_squares=1;

if manual_squares,
    calib_data.n_sq_x = input(['Number of squares along the X direction ([]=' num2str(n_sq_x_default) ') = ']); %6
    if isempty(calib_data.n_sq_x), calib_data.n_sq_x = n_sq_x_default; end;
    calib_data.n_sq_y = input(['Number of squares along the Y direction ([]=' num2str(n_sq_y_default) ') = ']); %6
    if isempty(calib_data.n_sq_y), calib_data.n_sq_y = n_sq_y_default; end;
end;

num_points=(calib_data.n_sq_x+1)*(calib_data.n_sq_y+1);

n_sq_x_default = calib_data.n_sq_x;
n_sq_y_default = calib_data.n_sq_y;

if (isempty(calib_data.dX))|(isempty(calib_data.dY)), % This question is now asked only once
    % Enter the size of each square

    calib_data.dX = input(['Size dX of each square along the X direction ([]=' num2str(dX_default) 'mm) = ']);
    calib_data.dY = input(['Size dY of each square along the Y direction ([]=' num2str(dY_default) 'mm) = ']);
    if isempty(calib_data.dX), calib_data.dX = dX_default; else dX_default = calib_data.dX; end;
    if isempty(calib_data.dY), calib_data.dY = dY_default; else dY_default = calib_data.dY; end;

else

    fprintf(1,['Size of each square along the X direction: dX=' num2str(calib_data.dX) 'mm\n']);
    fprintf(1,['Size of each square along the Y direction: dY=' num2str(calib_data.dY) 'mm   (Note: To reset the size of the squares, clear the variables dX and dY)\n']);
    %fprintf(1,'Note: To reset the size of the squares, clear the variables dX and dY\n');

end;

square_vert_side=calib_data.dX; %mm
square_horiz_side=calib_data.dY; %mm
num_vert_square=calib_data.n_sq_x;
num_horiz_square=calib_data.n_sq_y;

calib_data.ocam_model.xc=input(['X coordinate (along height) of the omnidirectional image center = ([]=' num2str(xc_default) ') = ']);
calib_data.ocam_model.yc=input(['Y coordinate (along width) of the omnidirectional image center = ([]=' num2str(yc_default) ') = ']);
if isempty(calib_data.ocam_model.xc), calib_data.ocam_model.xc = xc_default; else xc_default = calib_data.ocam_model.xc; end;
if isempty(calib_data.ocam_model.yc), calib_data.ocam_model.yc = yc_default; else yc_default = calib_data.ocam_model.yc; end;
% xc=385.48;
% yc=516.36;

fprintf(1,'\nEXTRACTION OF THE GRID CORNERS\n');
fprintf(1,'Do you want to use the automatic image selection\n');
answer=input('or do you want to process the images individually ( [] = automatic, other = individual )? ','s');

if isempty(answer)
    use_video_mode = 1;
    %% ================
    %  added code steffen urban
    use_corner_find = 1;
    %% ================
else
    use_video_mode = 0;
    fprintf(1,'Do you want to use the automatic corner extraction\n');
    answer=input('or do you want to extract all the points manually ( [] = automatic, other = manual )? ','s');

    % If you opted for the AUTOMATIC extraction
    if isempty(answer)
        use_automatic   = 1;
        %% ================
        %  added code steffen urban
        use_corner_find = 1;
        %% ================
    else
        use_automatic = 0;
    end

    fprintf(1,'\n');
    % If you opted for the MANUAL extraction
    if use_automatic == 0 %IF manual Extraction
        answer=input('Do you want your clicking to be assisted by a corner detector ( [] = yes, other = no )? ','s');
        if isempty(answer)
            use_corner_find=1;
            disp('Window size for corner finder (wintx and winty): ');
            calib_data.wintx = input(['wintx ([] = ' num2str(wintx_default) ') = ']);
            if isempty(calib_data.wintx), calib_data.wintx = wintx_default; end;
            calib_data.wintx = round(calib_data.wintx);
            calib_data.winty = input(['winty ([] = ' num2str(winty_default) ') = ']);
            if isempty(calib_data.winty), calib_data.winty = winty_default; end;
            winty = round(calib_data.winty);
            fprintf(1,'Window size = %dx%d\n',2*calib_data.wintx+1,2*calib_data.winty+1);

        else
            %% ================
            %  added code steffen urban
            use_corner_find = 1;
            %% ================
        end
    end
end

%Arranging the pixel of the world
calib_data.Xt=[];
calib_data.Yt=[];
for i=0:calib_data.n_sq_x
    for j=0:calib_data.n_sq_y
        calib_data.Yt=[calib_data.Yt;j*calib_data.dY];
        calib_data.Xt=[calib_data.Xt;i*calib_data.dX];
    end
end

if use_video_mode == 0
    for kk = ima_numbers,
        if ~isempty(calib_data.I{kk})
            if use_automatic == 0 %IF manual extraction
                click_ima_calib(kk,use_corner_find,calib_data);
            else %IF automatic extraction
                click_ima_calib_rufli(kk,use_corner_find,calib_data);
                %click_ima_calib_vladimir
            end
            calib_data.active_images(kk) = 1;
            calib_data.ima_proc= sort([calib_data.ima_proc, kk]);
        end;
    end;
else
    count = 0;
    for kk = ima_numbers

        [callBack, x, y]  = get_checkerboard_cornersUrban(kk,use_corner_find,calib_data);

        if callBack == 1
            count = count + 1;
            calib_data.Xp_abs(:,:,kk) = x;
            calib_data.Yp_abs(:,:,kk) = y;
            calib_data.active_images(kk) = 1;
            calib_data.ima_proc= sort([calib_data.ima_proc, kk]);
        end
    end
end

check_active_images(calib_data);

fprintf(1,'\nCorner extraction finished.\n');

end

author: urbste

repo: ImprovedOcamCalib


text:
function [ sStudy ] = db_parse_study( studiesDir, studySubDir, sizeProgress )
% DB_PARSE_DIR_STUDY: Parse a study directory.
%
% USAGE:  sStudy = db_parse_study(studiesDir, studySubDir, sizeProgress);
%
% INPUT:
%     - studiesDir   : Top-level studies directory (protocol/data/)
%     - studySubDir  : Study subdirectory
%     - sizeProgress : The full process increments the available progress bar by this amount
% OUTPUT:
%     - sStudy : array of Study structures (one entry for each subdirectory with a brainstormstudy file),
%                or [] if no brainstormstudy was found in directory

% NOTES:
% In a study subdirectory (=condition) there is :
%     - '*_brainstormstudy*.mat' : One and only one
%     - '*_channel*.mat'         : One and only one
%     - '*_headmodel*.mat'       : any number
%     - '*_data*.mat'            : any number
%     - '*_result*.mat'          : any number
%     - '*_linkresult*.mat'      : any number
%     - '*_presults*.mat'        : any number
%     - '*_pdata*.mat'           : any number
%     - '*_ptimefreq*.mat'       : any number
%     - '*_dipoles*.mat'         : any number
%     - 'Default' directory      : Defaults files for current study subdirectory
%                                  => May contain : '*_channel*.mat' and '*_headmodel*.mat' files
%     - Any number of subdirectories, that will be interpreted as sub-conditions (processed recursively)
% All the .MAT files in the directory are associated with the current study.
%
% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2008-2022

%% ===== PARSE INPUTS =====
if ~file_exist(bst_fullfile(studiesDir, studySubDir))
    error('Path in argument does not exist, or is not a directory');
end
if (nargin < 3) || isempty(sizeProgress)
    sizeProgress = [];
end

%% ===== LOOK FOR STUDY DEFINITION =====
% List 'brainstormstudy*.mat' files in the studySubDir directory
studyFiles = dir(bst_fullfile(studiesDir, studySubDir, 'brainstormstudy*.mat'));
% List all '*.mat' files and subcondition directories in the studySubDir directory
allFiles = dir(bst_fullfile(studiesDir, studySubDir, '*'));
% If there is no subject definition file : ignore the directory (but process subdirectories)
if isempty(studyFiles)
    studyMat = [];
% If there is more that one subject definition file : warning and ignore the directory (but process subdirectories)
elseif (length(studyFiles) > 1)
    studyMat = [];
    warning('Brainstorm:InvalidDirectory','There is more than one brainstormstudy file in directory ''%s'' : ignoring directory.', bst_fullfile(studiesDir, studySubDir));
else
    % Then there is only one file in studyFiles list
    studyFile = studyFiles(1);
    % Open file and get subject description
    try
        studyMat = load(bst_fullfile(studiesDir, studySubDir, studyFile.name));
    catch
        warning('Brainstorm:InvalidFile', 'Cannot open file ''%s'' : ignoring study', bst_fullfile(studiesDir, studySubDir, studyFile.name));
        studyMat = [];
    end
end

%% ===== READ STUDY DESCRIPTION =====
BadTrials = {};
if ~isempty(studyMat)
    % Initialize returned variable
    sStudy = db_template('Study');
    % ==== STUDY DESCRIPTION ====
    % Store subject's .MAT filename
    sStudy(1).FileName = bst_fullfile(studySubDir, studyFile.name);
    % Subject file
    if ismember(studySubDir, {bst_get('DirAnalysisInter'), bst_get('DirDefaultStudy')})
        sStudy(1).BrainStormSubject = bst_fullfile(bst_get('DirDefaultSubject'), 'brainstormsubject.mat');
    else
        sStudy(1).BrainStormSubject = bst_fullfile(bst_fileparts(studySubDir,1), 'brainstormsubject.mat');
    end
    % Name
    if isfield(studyMat, 'Name')
        sStudy(1).Name = studyMat.Name;
    end
    % DateOfStudy
    if isfield(studyMat, 'DateOfStudy')
        sStudy(1).DateOfStudy = studyMat.DateOfStudy;
    end
    % Bad trials
    if isfield(studyMat, 'BadTrials')
        % Remove files that do not exist from the list of bad trials
        if ~isempty(studyMat.BadTrials)
            iRemove = find(~ismember(studyMat.BadTrials, {allFiles.name}));
            if ~isempty(iRemove)
                studyMat.BadTrials(iRemove) = [];
                bst_save(bst_fullfile(studiesDir, sStudy(1).FileName), studyMat, 'v7');
            end
        end
        % Keep list of bad trials for parsing the rest of the folder
        BadTrials = studyMat.BadTrials;
    end

    % ==== STUDY CONDITION ====
    % The study subdirectory has a structure 'subject/condition/subcondition/...'
    % To get the conditions list : split the filename, and eliminate the first part (subject)
    conditionsList = str_split(studySubDir);
    conditionsList(1) = [];
    sStudy(1).Condition = conditionsList;
else
    sStudy = repmat(db_template('Study'), 0);
end

%% ===== READ ALL FILES IN FOLDER =====
% Exclude from the list of files:
%    - Files starting with a '.'
%    - ANALYSIS INTER directory
%    - ROOT DEFAULT STUDY directory
%    - Any other study folder that is immediately in the "data" folder
dirFiles = repmat(allFiles,0);
for iFile = 1:length(allFiles)
    if (allFiles(iFile).name(1) ~= '.') && ~strcmpi(allFiles(iFile).name, bst_get('DirAnalysisInter')) ...
                                        && ~(isempty(studySubDir) && strcmpi(allFiles(iFile).name, bst_get('DirDefaultStudy')))
        dirFiles(end+1,1) = allFiles(iFile);
    end
end
if isempty(dirFiles)
    return;
end
% Find channel file ('channel' tag)
isChannelFile = ~cellfun(@(c)isempty([strfind(lower(c),'_channel'), strfind(lower(c),'channel_')]), {dirFiles.name});
% Reorder directory files (put channel files first)
dirFiles = cat(1, dirFiles(isChannelFile), dirFiles(~isChannelFile));
% Initialize list of trials
trialFiles = {};
trialData = [];
trialInd = {};

% Progress bar?
isProgressBar = bst_progress('isvisible') && ~isempty(sizeProgress);
startValue = bst_progress('get');
curValue = startValue;
% Process all the files
for iFile = 1:length(dirFiles)
    % Increment progress bar
    if isProgressBar
        tmpValue = round(startValue + (iFile-1)/length(dirFiles) * sizeProgress);
        if (curValue ~= tmpValue)
            bst_progress('set', curValue);
            curValue = tmpValue;
        end
    end
    % Directories : recursively call this function, to add subconditions studies
    if (dirFiles(iFile).isdir)
        % Append studies in the subdirectory to the sStudy array
        sStudy = [sStudy, db_parse_study(studiesDir, bst_fullfile(studySubDir, dirFiles(iFile).name), round(sizeProgress / length(dirFiles)))];

    % Files (only if there is a brainstormstudy file in current directory)
    elseif ~isempty(studyMat)
        % Reconstruct filename
        filenameRelative = bst_fullfile(studySubDir, dirFiles(iFile).name);
        filenameFull     = bst_fullfile(studiesDir, studySubDir, dirFiles(iFile).name);
        % Determine filetype
        fileType = file_gettype(filenameFull);
        if isempty(fileType)
            continue;
        end
        % Process file
        switch(fileType)
            case 'channel'
                % Try to load channel info
                channelInfo = io_getChannelInfo(filenameRelative);
                % If a channel file was found : copy channel information
                if ~isempty(channelInfo)
                    sStudy(1).Channel = channelInfo;
                end
            case 'noisecov'
                % Try to load noisecov info
                noisecovInfo = io_getNoisecovInfo(filenameRelative);
                % If a channel file was found : copy channel information
                if ~isempty(noisecovInfo)
                    sStudy(1).NoiseCov(1) = noisecovInfo;
                end
            case 'ndatacov'
                % Try to load noisecov info
                noisecovInfo = io_getNoisecovInfo(filenameRelative);
                % If a channel file was found : copy channel information
                if ~isempty(noisecovInfo)
                    sStudy(1).NoiseCov(2) = noisecovInfo;
                end

            case {'data', 'spike'}
%                 % Get data filename without the trial block
%                 [groupName, iTrial] = str_remove_trial(filenameRelative);
%                 dataInfo = [];
%                 % If it is a trial in a group of trials
%                 if ~isempty(groupName)
%                     iTrialGroup = find(strcmpi(groupName, trialFiles));
%                     % Not existing in the trial group
%                     if isempty(iTrialGroup)
%                         trialFiles{end+1} = groupName;
%                         trialData(end+1) = length(sStudy(1).Data) + 1;
%                         trialInd{end+1} = iTrial;
%                     % Existing in the trial group
%                     elseif ~isempty(iTrial)
%                         dataInfo = sStudy(1).Data(trialData(iTrialGroup));
%                         dataInfo.Comment = strrep(dataInfo.Comment, ['(#' num2str(trialInd{iTrialGroup}) ')'], ['(#' num2str(iTrial) ')']);
%                         dataInfo.FileName = filenameRelative;
%                     end
%                 end
                % Try to load channel info
%                 if isempty(dataInfo)
                    dataInfo = io_getDataInfo(filenameRelative);
                    if ~isempty(dataInfo) && isempty(dataInfo.Comment)
                        dataInfo.Comment = '';
                    end
%                 end
                % If a data file was found : copy data information
                if ~isempty(dataInfo)
                    % Bad trial ?
                    if ~isempty(BadTrials)
                        dataInfo.BadTrial = ismember(dirFiles(iFile).name, BadTrials);
                    else
                        dataInfo.BadTrial = 0;
                    end
                    % Copy file description
                    sStudy(1).Data(end+1) = dataInfo;
                % Else : file is not valid : rename it to avoid it slowing the parsing
                else
                    fullfilename = bst_fullfile(studiesDir, filenameRelative);
                    file_move(fullfilename, [fullfilename, '.bak']);
                end

            case 'dipoles'
                % Try to load channel info
                dipolesInfo = io_getDipolesInfo(filenameRelative);
                % If a data file was found : copy data information
                if ~isempty(dipolesInfo)
                    sStudy(1).Dipoles(end+1) = dipolesInfo;
                % Else : file is not valid : rename it to avoid it slowing the parsing
                else
                    fullfilename = bst_fullfile(studiesDir, filenameRelative);
                    file_move(fullfilename, [fullfilename, '.bak']);
                end
            case 'timefreq'
                % Try to load channel info
                timefreqInfo = io_getTimefreqInfo(filenameRelative);
                % If a data file was found : copy data information
                if ~isempty(timefreqInfo)
                    sStudy(1).Timefreq(end+1) = timefreqInfo;
                % Else : file is not valid : rename it to avoid it slowing the parsing
                else
                    fullfilename = bst_fullfile(studiesDir, filenameRelative);
                    file_move(fullfilename, [fullfilename, '.bak']);
                end
            case 'headmodel'
                % Try to load headmodel info
                headModelInfo = io_getHeadModelInfo(filenameRelative);
                % If a data file was found : copy headmodel information
                if ~isempty(headModelInfo)
                    sStudy(1).HeadModel(end+1) = headModelInfo;
                end
            case 'results'
                % Try to load result info
                resultsInfo = io_getResultInfo(filenameRelative);
                % If a data file was found : copy information
                if ~isempty(resultsInfo)
                    % Mark if it is a link-results file
                    resultsInfo.isLink = 0;
                    % Store file in study list
                    sStudy(1).Result(end+1) = resultsInfo;
                % Else : file is not valid : rename it to avoid it slowing the parsing
                else
                    fullfilename = bst_fullfile(studiesDir, filenameRelative);
                    file_move(fullfilename, [fullfilename, '.bak']);
                end

            case 'linkresults'
                % Remove file
                file_delete(bst_fullfile(studiesDir, filenameRelative), 1);
                disp(['Old linkresults file deleted: ', filenameRelative]);

            case {'presults', 'pdata', 'ptimefreq', 'pmatrix'}
                % Try to load result info
                statInfo = io_getStatInfo(filenameRelative, fileType);
                % If a data file was found : copy headmodel information
                if ~isempty(statInfo)
                    sStudy(1).Stat(end+1) = statInfo;
                % Else : file is not valid : rename it to avoid it slowing the parsing
                else
                    fullfilename = bst_fullfile(studiesDir, filenameRelative);
                    file_move(fullfilename, [fullfilename, '.bak']);
                end
            case 'matrix'
                % Try to load headmodel info
                matrixInfo = io_getMatrixInfo(filenameRelative);
                % If a data file was found : copy headmodel information
                if ~isempty(matrixInfo)
                    sStudy(1).Matrix(end+1) = matrixInfo;
                end
            case 'image'
                [fPath, fBase, fExt] = bst_fileparts(filenameRelative);
                sStudy(1).Image(end+1) = struct('FileName', filenameRelative, ...
                                                'Comment',  [fBase, fExt]);
            case 'videolink'
                % Load file info
                try
                    % Try to load information
                    warning off MATLAB:load:variableNotFound
                    infoMat = load(bst_fullfile(studiesDir, filenameRelative), 'Comment');
                    warning on MATLAB:load:variableNotFound
                    fileComment = infoMat.Comment;
                catch
                    [fPath, fBase, fExt] = bst_fileparts(filenameRelative);
                    fileComment = [fBase, fExt];
                end
                % Create structure
                sStudy(1).Image(end+1) = struct('FileName', filenameRelative, ...
                                                'Comment',  fileComment);
        end
    end
end
% Set progress bar to the end
if isProgressBar
    bst_progress('set', round(startValue + sizeProgress));
end

% Select study defaults in the processed files
if ~isempty(studyMat)
    % HeadModel : last file
    if ~isempty(sStudy(1).HeadModel)
        sStudy(1).iHeadModel = length(sStudy(1).HeadModel);
    else
        sStudy(1).iHeadModel = [];
    end
end

return

%% ===================================================================================
%  === HELPER FUNCTIONS ==============================================================
%  ===================================================================================
    % CHANNEL : Load channel*.mat file information from a relative filename
    % Return a Channel structure :
    %    |- FileName
    %    |- Comment
    %    |- nbChannels

    % or an empty structure if error
    function sInfo = io_getChannelInfo(relativeFilename)
        sInfo = repmat(db_template('Channel'),0);
        % Check if the file exists, and load information fields
        if file_exist(bst_fullfile(studiesDir, relativeFilename))
            try
                % Try to load whole file
                warning off MATLAB:load:variableNotFound
                infoMat = load(bst_fullfile(studiesDir, relativeFilename),'Channel','Comment');
                warning on MATLAB:load:variableNotFound
                % Process all the channels, to count canals of each type
                sInfo(1).nbChannels = length(infoMat.Channel);
                channelList = infoMat.Channel;
                % Comment field
                if isfield(infoMat, 'Comment')
                    sInfo(1).Comment = infoMat.Comment;
                else
                    % Build channel name
                    [tmp__, chComment] = bst_fileparts(relativeFilename);
                    chComment = lower(chComment);
                    chComment = strrep(chComment, '_channel', '');
                    chComment = strrep(chComment, 'channel_', '');
                    chComment = strrep(chComment, 'channel', '');
                    if ~isempty(chComment)
                        sInfo(1).Comment = chComment;
                    else
                        sInfo(1).Comment = sprintf('Channels ', sInfo(1).nbChannels);
                    end
                end
                if isempty(strfind(sInfo(1).Comment, ')'))
                    sInfo(1).Comment = sprintf('%s (%d)', sInfo(1).Comment, sInfo(1).nbChannels);
                end
                % Copy filename
                sInfo(1).FileName = relativeFilename;
                % Get all available modalities
                if ~isempty(channelList)
                    [sInfo(1).Modalities, sInfo(1).DisplayableSensorTypes] = channel_get_modalities(channelList);
                end
            catch
                % An error occured during the 'load' operation
                warning('Cannot open file ''%s''.', bst_fullfile(studiesDir, relativeFilename));
                sInfo = [];
            end
        else
            % File does not exist
            warning('File ''%s'' was not found.', bst_fullfile(studiesDir, relativeFilename));
            sInfo = [];
        end
    end

    % HEADMODEL : Load *headmodel*.mat file information from a relative filename
    % Return a Headmodel info structure :
    %    |- FileName
    %    |- Comment
    %    |- HeadModelType
    %    |- MEGMethod
    %    |- EEGMethod
    %    |- ECOGMethod
    %    |- SEEGMethod
    % or an empty structure if error
    function sInfo = io_getHeadModelInfo(relativeFilename)
        sInfo = repmat(db_template('HeadModel'),0);
        % Check if the file exists, and load information fields
        if file_exist(bst_fullfile(studiesDir, relativeFilename))
            try
                % Try to load information
                warning off MATLAB:load:variableNotFound
                infoMat = in_bst_headmodel(bst_fullfile(studiesDir, relativeFilename), 0, ...
                    'Comment', 'HeadModelType', 'MEGMethod', 'EEGMethod', 'ECOGMethod', 'SEEGMethod');
                warning on MATLAB:load:variableNotFound
                % Try to copy information
                if isfield(infoMat, 'Comment')
                    sInfo(1).Comment = infoMat.Comment;
                end
                if isfield(infoMat, 'HeadModelType')
                    sInfo(1).HeadModelType = infoMat.HeadModelType;
                end
                if isfield(infoMat, 'MEGMethod')
                    sInfo(1).MEGMethod   = infoMat.MEGMethod;
                end
                if isfield(infoMat, 'EEGMethod')
                    sInfo(1).EEGMethod   = infoMat.EEGMethod;
                end
                if isfield(infoMat, 'ECOGMethod')
                    sInfo(1).ECOGMethod   = infoMat.ECOGMethod;
                end
                if isfield(infoMat, 'SEEGMethod')
                    sInfo(1).SEEGMethod   = infoMat.SEEGMethod;
                end
                % Copy filename
                sInfo(1).FileName = relativeFilename;
            catch
                % An error occured during the 'load' operation
                warning('Cannot open file ''%s''.', bst_fullfile(studiesDir, relativeFilename));
                sInfo = [];
            end
        else
            % File does not exist
            warning('File ''%s'' was not found.', bst_fullfile(studiesDir, relativeFilename));
            sInfo = [];
        end
    end

    % DATA : Load *data*.mat file information from a relative filename
    % Return a Data info structure :
    %    |- FileName
    %    |- Comment
    % or an empty structure if error
    function sInfo = io_getDataInfo(relativeFilename)
        sInfo = repmat(db_template('Data'),0);
        % Check if the file exists, and load information fields
        if file_exist(bst_fullfile(studiesDir, relativeFilename))
            try
                % Try to load information
                infoMat = in_bst_data(bst_fullfile(studiesDir, relativeFilename), 'Comment', 'DataType');
                % Copy information (required fields)
                sInfo(1).Comment  = infoMat.Comment;
                sInfo(1).FileName = relativeFilename;
                sInfo(1).DataType = infoMat.DataType;
            catch
                % An error occured during the 'load' operation
                warning('Cannot open file ''%s''.', bst_fullfile(studiesDir, relativeFilename));
                sInfo = [];
            end
        else
            % File does not exist
            warning('File ''%s'' was not found.', bst_fullfile(studiesDir, relativeFilename));
            sInfo = [];
        end
    end

    % DIPOLES : Load *dipoles*.mat file information from a relative filename
    % Return a Dipoles info structure :
    %    |- FileName
    %    |- Comment
    %    |- DataFile
    % or an empty structure if error
    function sInfo = io_getDipolesInfo(relativeFilename)
        sInfo = repmat(db_template('Dipoles'),0);
        % Check if the file exists, and load information fields
        if file_exist(bst_fullfile(studiesDir, relativeFilename))
            try
                % Try to load information
                warning off MATLAB:load:variableNotFound
                infoMat = load(bst_fullfile(studiesDir, relativeFilename), 'Comment', 'DataFile');
                warning on MATLAB:load:variableNotFound
                % Check if data was loaded
                if ~all(isfield(infoMat, 'Comment'))
                    warning('File "%s" is not a valid result file. Appending ''.bak'' at the filename...', relativeFilename);
                    return
                end
                % Copy information (required fields)
                sInfo(1).Comment  = infoMat.Comment;
                sInfo(1).FileName = relativeFilename;
                sInfo(1).DataFile = infoMat.DataFile;
            catch
                % An error occured during the 'load' operation
                warning('Cannot open file ''%s''.', bst_fullfile(studiesDir, relativeFilename));
                sInfo = [];
            end
        else
            % File does not exist
            warning('File ''%s'' was not found.', bst_fullfile(studiesDir, relativeFilename));
            sInfo = [];
        end
    end

    % TIMEFREQ : Load *timefreq*.mat file information from a relative filename
    % Return a Timefreq info structure :
    %    |- FileName
    %    |- Comment
    %    |- DataFile
    % or an empty structure if error
    function sInfo = io_getTimefreqInfo(relativeFilename)
        sInfo = repmat(db_template('Timefreq'),0);
        % Check if the file exists, and load information fields
        if file_exist(bst_fullfile(studiesDir, relativeFilename))
            try
                % Try to load information
                warning off MATLAB:load:variableNotFound
                infoMat = load(bst_fullfile(studiesDir, relativeFilename), 'Comment', 'DataFile', 'DataType');
                warning on MATLAB:load:variableNotFound
                % Check if data was loaded
                if ~all(isfield(infoMat, 'Comment'))
                    warning('File "%s" is not a valid result file. Appending ''.bak'' at the filename...', relativeFilename);
                    return
                end
                % Copy information (required fields)
                sInfo(1).Comment  = infoMat.Comment;
                sInfo(1).FileName = relativeFilename;
                sInfo(1).DataFile = infoMat.DataFile;
                sInfo(1).DataType = infoMat.DataType;
            catch
                % An error occured during the 'load' operation
                warning('Cannot open file ''%s''.', bst_fullfile(studiesDir, relativeFilename));
                sInfo = [];
            end
        else
            % File does not exist
            warning('File ''%s'' was not found.', bst_fullfile(studiesDir, relativeFilename));
            sInfo = [];
        end
    end

    % STAT : Load pdata, presults, ptimefreq file information from a relative filename
    % Return a Data info structure :
    %    |- FileName
    %    |- Comment
    %    |- Type
    % or an empty structure if error
    function sInfo = io_getStatInfo(relativeFilename, fileType)
        sInfo = repmat(db_template('Stat'),0);
        % Check if the file exists, and load information fields
        if file_exist(bst_fullfile(studiesDir, relativeFilename))
            try
                % Try to load information
                warning off MATLAB:load:variableNotFound
                infoMat = load(bst_fullfile(studiesDir, relativeFilename), 'Comment', 'Type');
                warning on MATLAB:load:variableNotFound
                % Check if data was loaded
                if ~all(isfield(infoMat, {'Comment'}))
                    warning('File "%s" is not a valid stat file. Appending ''.bak'' at the filename...', relativeFilename);
                    return
                end
                % Copy information (required fields)
                sInfo(1).Comment    = infoMat.Comment;
                sInfo(1).FileName   = relativeFilename;
                % Type
                if isfield(infoMat, 'Type')
                    sInfo(1).Type = infoMat.Type;
                else
                    switch(fileType)
                        case 'pdata',      sInfo(1).Type = 'data';
                        case 'presults',   sInfo(1).Type = 'results';
                        case 'ptimefreq',  sInfo(1).Type = 'timefreq';
                        case 'pmatrix',    sInfo(1).Type = 'matrix';
                    end
                end
            catch
                % An error occured during the 'load' operation
                warning('Cannot open file ''%s''.', bst_fullfile(studiesDir, relativeFilename));
                sInfo = [];
            end
        else
            % File does not exist
            warning('File ''%s'' was not found.', bst_fullfile(studiesDir, relativeFilename));
            sInfo = [];
        end
    end

    % RESULT : Load *result*.mat file information from a relative filename
    % Return a Result info structure :
    %    |- FileName
    %    |- Comment
    %    |- DataFile
    % or an empty structure if error
    function sInfo = io_getResultInfo(relativeFilename)
        sInfo = repmat(db_template('Results'),0);
        % Check if the file exists, and load information fields
        if file_exist(bst_fullfile(studiesDir, relativeFilename))
            try
                % Try to load information
                warning off MATLAB:load:variableNotFound
                infoMat = load(bst_fullfile(studiesDir, relativeFilename), 'Comment', 'DataFile', 'HeadModelType');
                warning on MATLAB:load:variableNotFound
                % Check if data was loaded
                if ~all(isfield(infoMat, {'DataFile', 'Comment'}))
                    warning('File "%s" is not a valid result file. Appending ''.bak'' at the filename...', relativeFilename);
                    return
                end
                % Create results structure
                sInfo(1).Comment  = infoMat.Comment;
                sInfo(1).DataFile = infoMat.DataFile;
                sInfo(1).FileName = relativeFilename;
                if isfield(infoMat, 'HeadModelType') && ~isempty(infoMat.HeadModelType)
                    sInfo(1).HeadModelType = infoMat.HeadModelType;
                else
                    sInfo(1).HeadModelType = 'surface';
                end
            catch
                % An error occured during the 'load' operation
                warning('Cannot open file ''%s''.', bst_fullfile(studiesDir, relativeFilename));
                sInfo = [];
            end
        else
            % File does not exist
            warning('File ''%s'' was not found.', bst_fullfile(studiesDir, relativeFilename));
            sInfo = [];
        end
    end

    % NOISECOV : Load *noisecov*.mat file information from a relative filename
    % Return a NoiseCov info structure :
    %    |- FileName
    %    |- Comment
    % or an empty structure if error
    function sInfo = io_getNoisecovInfo(relativeFilename)
        sInfo = repmat(db_template('NoiseCov'),0);
        % Check if the file exists, and load information fields
        if file_exist(bst_fullfile(studiesDir, relativeFilename))
            try
                % Try to load information
                warning off MATLAB:load:variableNotFound
                infoMat = load(bst_fullfile(studiesDir, relativeFilename), 'Comment');
                warning on MATLAB:load:variableNotFound
                % Check if data was loaded
                if ~all(isfield(infoMat, {'Comment'}))
                    warning('File "%s" is not a valid brainstorm file. Appending ''.bak'' at the filename...', relativeFilename);
                    return
                end
                % Create results structure
                sInfo(1).Comment  = infoMat.Comment;
                sInfo(1).FileName = relativeFilename;
            catch
                % An error occured during the 'load' operation
                warning('Cannot open file ''%s''.', bst_fullfile(studiesDir, relativeFilename));
                sInfo = [];
            end
        else
            % File does not exist
            warning('File ''%s'' was not found.', bst_fullfile(studiesDir, relativeFilename));
            sInfo = [];
        end
    end

    % MATRIX : Load *matrix*.mat file information from a relative filename
    % Return a Matrix info structure :
    %    |- FileName
    %    |- Comment
    % or an empty structure if error
    function sInfo = io_getMatrixInfo(relativeFilename)
        sInfo = repmat(db_template('Matrix'),0);
        % Check if the file exists, and load information fields
        if file_exist(bst_fullfile(studiesDir, relativeFilename))
            try
                % Try to load information
                warning off MATLAB:load:variableNotFound
                infoMat = load(bst_fullfile(studiesDir, relativeFilename), 'Comment');
                warning on MATLAB:load:variableNotFound
                % Check if data was loaded
                if ~all(isfield(infoMat, {'Comment'}))
                    warning('File "%s" is not a valid brainstorm file. Appending ''.bak'' at the filename...', relativeFilename);
                    return
                end
                % Create results structure
                sInfo(1).Comment  = infoMat.Comment;
                sInfo(1).FileName = relativeFilename;
            catch
                % An error occured during the 'load' operation
                warning('Cannot open file ''%s''.', bst_fullfile(studiesDir, relativeFilename));
                sInfo = [];
            end
        else
            % File does not exist
            warning('File ''%s'' was not found.', bst_fullfile(studiesDir, relativeFilename));
            sInfo = [];
        end
    end

end

author: brainstorm-tools


text:
function [accumX, uniqIndices] = aggregateMatrix(X, indices)
%%%
% Fast way of aggregating column vectors based on indices which contain repetitive values.
%   X = [101:105; 11:15];
%   indices = [1 4 4 2 2]
% aggregateMatrix(X, indices) returns:
%   accumX =
%     101   209   205
%      11    29    25
%   uniqIndices = [1 2 4]
%
% Thang Luong @ 2015, <lmthang@stanford.edu>
%%%

    [uniqIndices, ~, J] = unique(indices);
    numUniqIndices = length(uniqIndices);
    numEmbGrads = length(indices);

    if numEmbGrads==1
        accumX = X;
    else
        sparseMatrix = zeros(numEmbGrads, numUniqIndices,'double', 'gpuArray');
        sparseIndices = sub2ind([numEmbGrads, numUniqIndices], 1:numEmbGrads, J');
        sparseMatrix(sparseIndices) = ones(numEmbGrads, 1);
        accumX = X*sparseMatrix;
    end
end

author: jiweil

repo: Hierarchical-Neural-Autoencoder


text:
function p = hexagon_shape_2d ( angle )

%*****************************************************************************80
%
%% HEXAGON_SHAPE_2D returns points on the unit regular hexagon in 2D.
%
%  Diagram:
%
%      120_____60
%        /     \
%    180/       \0
%       \       /
%        \_____/
%      240     300
%
%  Discussion:
%
%    The unit regular hexagon has radius 1.  The radius is the distance from
%    the center to any vertex, and it is also the length of any side.
%    An example of a unit hexagon is the convex hull of the points:
%
%      (   1,              0 ),
%      (   0.5,   sqrt (3)/2 ),
%      ( - 0.5,   sqrt (3)/2 ),
%      ( - 1,              0 ),
%      ( - 0.5, - sqrt (3)/2 ),
%      (   0.5, - sqrt (3)/2 ).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 May 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real ANGLE, the angle, in degrees, of the point.
%
%    Output, real P(2,1), the coordinates of the point.
%

%
%  Ensure that 0 <= ANGLE < 360.
%
  angle2 = r8_modp ( angle, 360.0 );
%
%  y = - sqrt(3) * x + sqrt(3)
%
  if ( 0.0 <= angle2 & angle2 <= 60.0 )

    p(1,1) = sqrt ( 3.0 ) / ( tan_deg ( angle2 ) + sqrt ( 3.0 ) );
    p(2,1) = tan_deg ( angle2 ) * p(1,1);
%
%  y = sqrt(3) / 2
%
  elseif ( angle2 <= 120.0 )

    p(2,1) = sqrt ( 3.0 ) / 2.0;
    p(1,1) = cot_deg ( angle2 ) * p(2,1);
%
%  y = sqrt(3) * x + sqrt(3)
%
  elseif ( angle2 <= 180.0 )

    p(1,1) = sqrt ( 3.0 ) / ( tan_deg ( angle2 ) - sqrt ( 3.0 ) );
    p(2,1) = tan_deg ( angle2 ) * p(1,1);
%
%  y = - sqrt(3) * x - sqrt(3)
%
  elseif ( angle2 <= 240.0 )

    p(1,1) = - sqrt ( 3.0 ) / ( tan_deg ( angle2 ) + sqrt ( 3.0 ) );
    p(2,1) = tan_deg ( angle2 ) * p(1,1);
%
%  y = - sqrt(3) / 2
%
  elseif ( angle2 <= 300.0 )

    p(2,1) = - sqrt ( 3.0 ) / 2.0;
    p(1,1) = cot_deg ( angle2 ) * p(2,1);
%
%  y = sqrt(3) * x - sqrt(3)
%
  elseif ( angle2 <= 360.0 )

    p(1,1) = - sqrt ( 3.0 ) / ( tan_deg ( angle2 ) - sqrt ( 3.0 ) );
    p(2,1) = tan_deg ( angle2 ) * p(1,1);

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
%kSeparator 'Separator Object Menuform'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros Separator.pane file
%
% Parameters:
%
% Example: kSeparator( {})
%
% Khoros helpfile follows below:
%
% .begin tagged
%
% .item "The Separator GUI Object"
% The Khoros pixmap object is used on Khoros graphical user interfaces whenever
% a dividing line is desired for visual effect.  A vertical separator is a
% straight line that spans the height of its parent; a horizontal separator is
% a straight line that spans the width of its parent.
%
% .item "Separator Type"
% The separator line may be solid or dashed.
%
% .item "Separator Orientation"
% The separator may have a horizontal or vertical orientation.
%
% .end tagged

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

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

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function [J] = kcal2J(kcal)
% Convert energy or work from kilocalories to joules.
% Chad A. Greene 2012
J = kcal*4186.8;

author: Sable

repo: mcbench-benchmarks


text:
function f = goldstein_price_xy ( x, y )

%*****************************************************************************80
%
%% GOLDSTEIN_PRICE_XY evaluates the Goldstein-Price polynomial.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 February 2008
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Zbigniew Michalewicz,
%    Genetic Algorithms + Data Structures = Evolution Programs,
%    Third Edition,
%    Springer Verlag, 1996,
%    ISBN: 3-540-60676-9,
%    LC: QA76.618.M53.
%
%  Parameters:
%
%    Input, real X, Y, the arguments of the function.
%
%    Output, real F, the value of the function at X.
%
  a = x + y + 1.0;

  b = 19.0 - 14.0 * x + 3.0 * x * x - 14.0 * y ...
    + 6.0 * x * y + 3.0 * y * y;

  c = 2.0 * x - 3.0 * y;

  d = 18.0 - 32.0 * x + 12.0 * x * x + 48.0 * y ...
    - 36.0 * x * y + 27.0 * y * y;

  f = ( 1.0 + a * a * b ) * ( 30.0 + c * c * d );

  return
end


text:
function [z_ic A T mean_z] = myICA(z,NUM,varargin)
%--------------------------------------------------------------------------
% Syntax:       z_ic = myICA(z,NUM);
%               z_ic = myICA(z,NUM,'true');
%               z_ic = myICA(z,NUM,'false');
%               [z_ic A T mean_z] = myICA(z,NUM);
%               [z_ic A T mean_z] = myICA(z,NUM,'true');
%               [z_ic A T mean_z] = myICA(z,NUM,'false');
%
% Inputs:       z is an M x N matrix containing N samples of an
%               M-dimensional multivariate random variable
%
%               NUM is the desired number of independent components.
%
%               display can be {'true','false'}. The default is 'true'.
%
% Outputs:      z_ic is a NUM x N matrix containing the NUM independent
%               components (scaled to have variance 1) of each of the N
%               samples in z.
%
%               A and T are the ICA transformation matrices such that:
%               z_LD = T \ pinv(A) * z_ic + repmat(mean_z,1,size(z,2));
%               is the NUM-dimensional ICA approximation of z
%
%               mean_z is the M x 1 sample mean vector of z.
%
% Description:  This function performs independent component analysis (ICA)
%               on the input samples of a multivariate random variable and
%               returns the NUM independent components of each sample.
%
% Author:       Brian Moore
%               brimoor@umich.edu
%
% Date:         July 20, 2012
%--------------------------------------------------------------------------

eps = 1e-4; % Convergence criteria
maxSamples = 1000; % Max number of data points in sample mean calculations
maxIters = 100; % Maximum number of iterations allowed

% Parse user input
if (nargin == 3)
    display = varargin{1};
else
    display = 'true';
end

% Center and whiten the input data
[z_cw T mean_z] = myCenterAndWhiten(z);

% Get data dimension
[m,n] = size(z_cw);

if (n > maxSamples)
    % Draw maxSamples data points at random for sample mean calculations
    z_cw_trimmed = z_cw(:,randperm(n,maxSamples));
else
    % Use all data points for sample mean calculations
    z_cw_trimmed = z_cw;
end

% Choose random weights initially
w = rand(NUM,m);
for i = 1:NUM
    w(i,:) = w(i,:) / norm(w(i,:));
end

% Initialize loop variables
err = ones(NUM,1);
its = 0;

while ((max(err) > eps) && (its < maxIters))
    % Increment iteration counter
    its = its + 1;

    % Save last weight matrix
    w_old = w;

    % for each weight vector
    for i = 1:NUM
        % Last independent components
        si = w_old(i,:) * z_cw_trimmed;

        % Compute negentropy scores
        % negentropy function : f(u) = -exp(-u^2/2)
        g = si .* exp(-0.5 * (si.^2));
        gp = -1.0 * ((si.^2) .* exp(-0.5 * (si.^2)));

        % Update weights in the direction of maximum negentropy
        w(i,:) = mean(z_cw_trimmed .* repmat(g,m,1),2)' - mean(gp) * w_old(i,:);

        % Normalize weight vector
        w(i,:) = w(i,:) / norm(w(i,:));
    end

    % Decorrelate weight vectors
    [U,S,~] = svd(w,'econ');
    Sinv = diag(1./diag(S));
    w = U * Sinv * U' * w;

    % Compute innovation
    for i = 1:NUM
        err(i) = 1 - w(i,:) * w_old(i,:)';
    end

    % Display innovation
    if strcmpi(display,'true')
        disp(['Iteration ' num2str(its) ': max(1 - <w' num2str(its) ',w' num2str(its-1) '>) = ' num2str(max(err))])
    end
end

% Return transformation matrix
A = w;

% Compute independent components
z_ic = A * z_cw;


text:
function [TorF, vstr, rdate] = have_feature_knitro()
%HAVE_FEATURE_KNITRO  Detect availability/version info for Artelys Knitro
%
%   Feature detection function implementing 'knitro' tag for HAVE_FEATURE
%   to detect availability/version of Artelys Knitro, a nonlinear
%   programming solver (https://www.artelys.com/solvers/knitro/).
%
%   See also HAVE_FEATURE, NLPS_MASTER, KNITROMATLAB.

%   MP-Opt-Model
%   Copyright (c) 2004-2020, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MP-Opt-Model.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://github.com/MATPOWER/mp-opt-model for more info.

tmp = have_feature('knitromatlab', 'all');
if tmp.av
    TorF = tmp.av;
    vstr = tmp.vstr;
    rdate = tmp.date;
else
    tmp = have_feature('ktrlink', 'all');
    if tmp.av
        TorF = tmp.av;
        vstr = tmp.vstr;
        rdate = tmp.date;
    else
        TorF = 0;
        vstr = '';
        rdate = '';
    end
end

author: MATPOWER

repo: matpower

save_path: github-repos/MATLAB/MATPOWER-matpower


text:
function [w,rho] = mh(A)
% Computes the Metropolis-Hastings heuristic edge weights
%
% [W,RHO] = MH(A) gives a vector of the Metropolis-Hastings edge weights
% for a graphb described by the incidence matrix A (NxM). N is the number
% of nodes, and M is the number of edges. Each column of A has exactly one
% +1 and one -1. RHO is computed from the weights W as follows:
%    RHO = max(abs(eig( eye(n,n) - (1/n)*ones(n,n) - A*W*A' ))).
%
% The M.-H. weight on an edge is one over the maximum of the degrees of the
% adjacent nodes.
%
% For more details, see the references:
% "Fast linear iterations for distributed averaging" by L. Xiao and S. Boyd
% "Fastest mixing Markov chain on a graph" by S. Boyd, P. Diaconis, and L. Xiao
% "Convex Optimization of Graph Laplacian Eigenvalues" by S. Boyd
%
% Almir Mutapcic 08/29/06

% degrees of the nodes
n = size(A,1);
Lunw = A*A';          % unweighted Laplacian matrix
degs = diag(Lunw);

% Metropolis-Hastings weights
mh_degs = abs(A)'*diag(degs);
w = 1./max(mh_degs,[],2);

% compute the norm
if nargout > 1,
    rho = norm( eye(n) - A*diag(w)*A' - (1/n)*ones(n) );
end

author: yu-jiang

repo: radpbook

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


text:
% book : Signals and Systems Laboratory with MATLAB
% authors : Alex Palamides & Anastasia Veloni
%
%
%
%
% problem 8- Use the Laplace Transform to solve the differential equation
%
% y'''(t)+y'(t)-2y(t)=dirac(t),  y(0)=2, y'(0)=3 , y''(0)=1

syms t s Y
y0=1;
yd0=3;
y2d0=1;

x=dirac(t);
X=laplace(x,s);

Y1=s*Y-y0;
Y2=s*Y1-yd0;
Y3=s*Y2-y2d0;

G=Y3+Y1-2*Y-X;
Y=solve(G,Y);

y=ilaplace(Y,t);

ezplot(y,[0 5])
legend('Solution y(t)')


text:
function [V, converged, i] = newtonpf_I_cart(Ybus, Sbus, V0, ref, pv, pq, mpopt)
%NEWTONPF_I_CART  Solves power flow using full Newton's method (current/cartesian)
%   [V, CONVERGED, I] = NEWTONPF_I_CART(YBUS, SBUS, V0, REF, PV, PQ, MPOPT)
%
%   Solves for bus voltages using a full Newton-Raphson method, using nodal
%   current balance equations and cartesian coordinate representation of
%   voltages, given the following inputs:
%       YBUS  - full system admittance matrix (for all buses)
%       SBUS  - handle to function that returns the complex bus power
%               injection vector (for all buses), given the bus voltage
%               magnitude vector (for all buses)
%       V0    - initial vector of complex bus voltages
%       REF   - bus index of reference bus (voltage ang reference & gen slack)
%       PV    - vector of bus indices for PV buses
%       PQ    - vector of bus indices for PQ buses
%       MPOPT - (optional) MATPOWER option struct, used to set the
%               termination tolerance, maximum number of iterations, and
%               output options (see MPOPTION for details).
%
%   The bus voltage vector contains the set point for generator
%   (including ref bus) buses, and the reference angle of the swing
%   bus, as well as an initial guess for remaining magnitudes and
%   angles.
%
%   Returns the final complex voltages, a flag which indicates whether it
%   converged or not, and the number of iterations performed.
%
%   See also RUNPF, NEWTONPF, NEWTONPF_S_CART, NEWTONPF_I_POLAR.

%   MATPOWER
%   Copyright (c) 1996-2019, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%   and Baljinnyam Sereeter, Delft University of Technology
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

%% default arguments
if nargin < 7
    mpopt = mpoption;
end

%% options
tol         = mpopt.pf.tol;
max_it      = mpopt.pf.nr.max_it;
lin_solver  = mpopt.pf.nr.lin_solver;

%% initialize
converged = 0;
i = 0;
V = V0;
Vm = abs(V);
Vmpv = Vm(pv);
n = length(V0);

%% set up indexing for updating V
npv = length(pv);
npq = length(pq);
j1 = 1;         j2 = npv;           %% j1:j2 - Q of pv buses
j3 = j2 + 1;    j4 = j2 + npq;      %% j3:j4 - Vr of pq buses
j5 = j4 + 1;    j6 = j4 + npv;      %% j5:j6 - Vr of pv buses
j7 = j6 + 1;    j8 = j6 + npq;      %% j7:j8 - Vi of pq buses
j9 = j8 + 1;    j10= j8 + npv;      %% j9:j10- Vi of pv buses

%% evaluate F(x0)
Sb = Sbus(Vm);
Sb(pv) = real(Sb(pv)) + 1j * imag(V(pv) .* conj(Ybus(pv, :) * V));
mis = Ybus * V - conj(Sb ./ V);
F = [   real(mis([pv; pq]));
        imag(mis([pv; pq]));
        V(pv) .* conj(V(pv)) - Vmpv.^2  ];

%% check tolerance
normF = norm(F, inf);
if mpopt.verbose > 1
    fprintf('\n it   max Ir & Ii mismatch (p.u.)');
    fprintf('\n----  ---------------------------');
    fprintf('\n%3d        %10.3e', i, normF);
end
if normF < tol
    converged = 1;
    if mpopt.verbose > 1
        fprintf('\nConverged!\n');
    end
end

%% attempt to pick fastest linear solver, if not specified
if isempty(lin_solver)
    nx = length(F);
    if nx <= 10 || have_feature('octave')
        lin_solver = '\';       %% default \ operator
    else    %% MATLAB and nx > 10 or Octave and nx > 2000
        lin_solver = 'LU3';     %% LU decomp with 3 output args, AMD ordering
    end
end

%% do Newton iterations
while (~converged && i < max_it)
    %% update iteration counter
    i = i + 1;

    %% evaluate Jacobian
    dImis_dQ = sparse(pv, pv, 1j./conj(V(pv)), n, n);
    dV2_dVr = sparse(1:npv, npq+(1:npv), 2*real(V(pv)), npv, npv+npq);
    dV2_dVi = sparse(1:npv, npq+(1:npv), 2*imag(V(pv)), npv, npv+npq);
    [dImis_dVr, dImis_dVi] = dImis_dV(Sb, Ybus, V, 1);

    %% handling of derivatives for voltage dependent loads
    %% (not yet implemented) goes here

    j11 = real(dImis_dQ([pv; pq], pv));
    j12 = real(dImis_dVr([pv; pq], [pq; pv]));
    j13 = real(dImis_dVi([pv; pq], [pq; pv]));
    j21 = imag(dImis_dQ([pv; pq], pv));
    j22 = imag(dImis_dVr([pv; pq], [pq; pv]));
    j23 = imag(dImis_dVi([pv; pq], [pq; pv]));
    j31 = sparse(npv, npv);
    j32 = dV2_dVr;
    j33 = dV2_dVi;

    J = [   j11 j12 j13;
            j21 j22 j23;
            j31 j32 j33;    ];

    %% compute update step
    dx = mplinsolve(J, -F, lin_solver);

    %% update voltage
    if npv
        V(pv) = V(pv) + dx(j5:j6) + 1j * dx(j9:j10);
        Sb(pv) = real(Sb(pv)) + 1j * (imag(Sb(pv)) + dx(j1:j2));
    end
    if npq
        V(pq) = V(pq) + dx(j3:j4) + 1j * dx(j7:j8);
    end

    %% evalute F(x)
    mis = Ybus * V - conj(Sb ./ V);
    F = [   real(mis([pv; pq]));
            imag(mis([pv; pq]));
            V(pv) .* conj(V(pv)) - Vmpv.^2  ];

    %% check for convergence
    normF = norm(F, inf);
    if mpopt.verbose > 1
        fprintf('\n%3d        %10.3e', i, normF);
    end
    if normF < tol
        converged = 1;
        if mpopt.verbose
            fprintf('\nNewton''s method power flow (current balance, cartesian) converged in %d iterations.\n', i);
        end
    end
end

if mpopt.verbose
    if ~converged
        fprintf('\nNewton''s method power flow (current balance, cartesian) did not converge in %d iterations.\n', i);
    end
end


text:
% VL_CUMMAX  Cumulative maximum
%   If X is a vector, VL_CUMMAX(X) is the vector with the cumulative
%   maximum of X. If X is a matrix, VL_CUMMAX(X) is the matrix of the
%   cumulative maximum of the columns of X. If X is a multi-dimensional
%   array, VL_CUMMAX(X) operates along the first non-singleton
%   dimension.
%
%   The function is analogous to CUMSUM() and CUMPROD(), but it
%   computes the cumulative maximum rather than the cumulative sum or
%   product.
%
%   The array X can be of any numeric class.
%
%   Example::
%     The cumulative maximum VL_CUMMAX([1 2 3 2 1]) is the vector
%     [1 2 3 3 3].
%
%   See also: CUMSUM(), CUMPROD(), VL_HELP().

% Author: Andrea Vedaldi

% Copyright

author: yihui-he

repo: panorama

save_path: github-repos/MATLAB/yihui-he-panorama


text:
function allbbs = show_top_transfers(models,grid,target_directory,finalstruct)%final_boxes,final_maxos)
%Show the top detections on a set of images
%NOTE his also writes out bus transfer files (which can clobber
%good results!)

VOCinit;

%finalstruct.basedir = sprintf('/nfs/baikal/tmalisie/labelme400/www/voc/iccv11/%s/',...
%                  VOCopts.dataset);

%finalstruct.basedir = '/nfs/baikal/tmalisie/labelme400/www/voc/iccv11/VOC2007/newones/';
models = add_sizes_to_models(models);

gridsave = grid;
if isfield(finalstruct,'friendclass')
  for i = 1:length(models)
    models{i}.friendclass = finalstruct.friendclass;
  end
end

allbbs = cell(0,1);
%final_boxes = final.final_boxes;
final_boxes = finalstruct.unclipped_boxes;
final_maxos = finalstruct.final_maxos;

VOCinit;

%if enabled we show images
saveimages = 0;

%% prune grid to contain only images from target_directory
[cur_set, gt] = textread(sprintf(VOCopts.imgsetpath,target_directory),['%s' ...
                    ' %d']);

if 0
  fprintf(1,'HACK: choosing only the subset which contains true positives\n');
  %% prune grid to contain only images from target_directory
  [cur_set, gt] = textread(sprintf(VOCopts.clsimgsetpath,models{1}.cls,target_directory),['%s' ...
                    ' %d']);
  cur_set = cur_set(gt==1);
end

gridids = cellfun2(@(x)x.curid,grid);
goods = find(ismember(gridids,cur_set));
grid = grid(goods);

imids = cell(1,length(final_boxes));
for i = 1:length(final_boxes)
  imids{i} = [];
  if size(final_boxes{i},1) > 0
    imids{i} = i * ones(size(final_boxes{i},1),1);
    %final_boxes{i}(:,5) = i;
  end
end

bbs = cat(1,final_boxes{:});
imids = cat(1,imids{:});
moses = [final_maxos{:}];
[aa,bb] = sort(bbs(:,end),'descend');

%% only good ones now!
%bb = bb(moses(bb)>.5);

if 0
  fprintf(1,'Only segmentation ones here\n');
  %% get ones with segmentation only
  ids = cellfun2(@(x)x.curid,models(bbs(bb,6)));
  VOCinit
  has_seg = cellfun(@(x)fileexists(sprintf('%s/%s/SegmentationObject/%s.png',...
                                           VOCopts.datadir, ...
                                           VOCopts.dataset,x)),ids);
  bb = bb(find(has_seg));
end

if 0
  %% get ones with 3d model only
  ids = cellfun2(@(x)sprintf('%s.%d.png',x.curid,x.objectid),models(bbs(bb,6)));
  VOCinit

  extradir = '/nfs/hn22/tmalisie/ddip/renderings/';
  has_3d = cellfun(@(x)fileexists(sprintf('%s/%s.%d.chair-3d.png', ...
                                          extradir,...
                                          x.curid, ...
                                          x.objectid)),models(bbs(bb,6)));

  bb = bb(find(has_3d));
end

counter = 1;
maxk = 40;
KKK = [1 1];

counter = 1;%20;
for k = 1:maxk
  k
  %figure(1)
  %clf
  for i = 1:prod(KKK)
    if counter > length(bb)
      break;
    end
    curb = bb(counter);
    curid = grid{imids(curb)}.curid;
    %curid = grid{bbs(curb,5)}.curid;
    I = im2double(imread(sprintf(VOCopts.imgpath,curid)));
    gtrecs = PASreadrecord(sprintf(VOCopts.annopath,curid));
    businds = find(ismember({gtrecs.objects.class},{'bus'}) & ~[gtrecs.objects.difficult]);
    gtbbs = cat(1,gtrecs.objects.bbox);
    gtbbs = gtbbs(businds,:);

    bbox = bbs(curb,:);

    TARGET_BUS = -1;
    if length(businds) > 0

      [alpha,beta] = max(getosmatrix_bb(gtbbs,bbox));
      TARGET_BUS = businds(beta);
    end

    if length(moses) > 0
      stuff.os = moses(curb);
    else
      stuff.os = 0;
    end
    stuff.score = bbs(curb,end);
    stuff.curid = curid;
    stuff.rank = counter;

    extra = '';

    if ismember(models{1}.models_name,{'dalal'})
      extra='-dalal';
    end

    estring = '';
    if exist('betas','var')
      estring = 'withbetas';
    end

    stuff.filer = sprintf(['/nfs/baikal/tmalisie/labelme400/www/voc/'...
                    'segxfer/%s%s-on-%s-%s-%d.eps'],...
                          models{1}.cls,extra,target_directory,estring,k);

    ccc = bbox(6);

    %curb = final_boxes{imids(curb)};
    %curb = final_boxes{bbox(5)};

    %curb = grid{bbox(5)}.bboxes;
    %curb = nms_within_exemplars(curb,.5);

    %[alpha,beta] = sort(curb(:,end),'descend');
    %curb = curb(beta(1:min(5,length(beta))),:);

    target_image_id = imids(bb(counter));
    target_cluster_id = bbs(bb(counter),5);

    allbb = finalstruct.raw_boxes{target_image_id};
    osmat = getosmatrix_bb(allbb,bbs(bb(counter),:));
    goods = find(osmat>.5);
    allbb = allbb(goods,:);
    allbb(:,end) = allbb(:,end);
    %allbb = calibrate_boxes(allbb,finalstruct.M.betas);
    allbb = esvm_nms_within_exemplars(allbb,.5);
    [alpha,beta] = sort(allbb(:,end),'descend');
    allbb = allbb(beta,:);

    %rawhits = ...
    %    finalstruct.nbrlist{target_image_id}{target_cluster_id};
    %curb = finalstruct.pre_nms_boxes{target_image_id}(rawhits,:);

    %[alpha,beta] = sort(curb(:,end),'descend');
    %curb = curb(beta,:);

    sumI = I*0;
    countI = zeros(size(I,1),size(I,2),1);
    ooo = cell(0,1);

    mean0 = mean(allbb,1);
    curoses = getosmatrix_bb(mean0(1,:),allbb);

    if 0
    for zzz = 1:min(1,size(allbb,1))

      exemplar_overlay = exemplar_inpaint(allbb(zzz,:), ...
                                          models{allbb(zzz,6)}, ...
                                          stuff);

      ooo{end+1} = exemplar_overlay;
      %if sum(1-exemplar_overlay.alphamask(:)) > 0
      try
      sumI = sumI + curoses(zzz)*allbb(zzz,end)* ...
             exemplar_overlay.segI;
      catch
      end
      %keyboard

      countI = countI + ...
               curoses(zzz)*allbb(zzz,end);%*exemplar_overlay.mask;
                                           %   break;
                                           % end
    end
    sumI = sumI ./ repmat(countI,[1 1 3]);

    end
    exemplar_overlay = exemplar_inpaint(allbb(1,:), ...
                                        models{allbb(1,6)}, ...
                                        stuff);

    allbb(1,end)

    if TARGET_BUS > -1
      %% load GT for test
      %gtfiles = dir(sprintf(['/nfs/baikal/tmalisie/buslabeling/' ...
      %                '%s*mat'],curid));
      gtmat = load(sprintf(['/nfs/baikal/tmalisie/finalbuslabeling/' ...
                    '%s.%d.mat'],curid,TARGET_BUS));

      %   clear gtmat
      % for i = 1:length(gtfiles)
      %   gtmat{i} = load(sprintf('/nfs/baikal/tmalisie/buslabeling/%s',gtfiles(i).name));
      % end
      %segs = cellfun2(@(x)x.res.seg,gtmat);
      %seg=sum(cat(3,segs{:}),3);
      seg = gtmat.res.seg;
      gtim = faces2colors(seg);

      shower = I;
      fg = repmat(double(seg~=0),[1 1 3]);

      shower(find(fg)) = shower(find(fg))*.0 + 1.0*gtim(find(fg));
      gtim = shower;
      gtim(repmat(seg==0,[1 1 3]))=0;

    else
      gtim = zeros(size(I,1),size(I,2));
    end

    if 0 %size(exemplar_overlay.friendbb,1) == 0
      counter = counter + 1;
      continue
    end

    figure(1)
    clf

    NR=show_hits_figure_iccv(models,allbb(1,:),I, ...
                          exemplar_overlay.segI,exemplar_overlay,gtim);

    %NR=show_hits_figure_iccv(models,allbb(zzz,:),I, ...
    %                      exemplar_overlay.segI,exemplar_overlay,gtim);

    drawnow

     output.I = I;
     output.result = exemplar_overlay.segI;

     if 0
       %% WARNING this is for buses
     imagesc(exemplar_overlay.overlay2.segI)
     masky = exemplar_overlay.overlay2.mask;
     [uu,vv] = find(masky);
     masky(min(uu):max(uu),min(vv):max(vv)) = ...
         imresize(exemplar_overlay.overlay2.alphamask,[range(uu)+1 range(vv)+1],'nearest');

     %masky(find(masky)) = exemplar_overlay.overlay2.alphamask(i2);
     output.result = (exemplar_overlay.overlay2.segI.*repmat(masky,[1 1 3]));
     output.WARNINGgt = gtim;
    end
     % try
     %   dfile = sprintf('/nfs/onega_no_backups/users/ashrivas/buses/%s.mat',curid);
     %   dresult = load(dfile);
     %   output.dresult = dresult.rim;
     % catch
        output.dresult = []; %2*ones(size(output.I,1),size(output.I,2));
     % end

     save(sprintf('/nfs/baikal/tmalisie/iccvres/finalbusmats/%05d.mat', ...
                  k),'output');

     %if isfield(finalstruct,'basedir')
     calib_string = '';
     if isfield(finalstruct,'M') && length(finalstruct.M)>0 && isfield(finalstruct.M,'betas')
       calib_string = '-calibrated';
     end

     filer = sprintf('%s/transfers/%s_%s%s_%05d.pdf',VOCopts.wwwdir,models{1}.cls,models{1}.models_name,calib_string,k);
     set(gcf,'PaperPosition',[0 0 2*NR(1) 2*NR(2)],...
             'PaperSize',[2*NR(1) 2*NR(2)]);

     %print(gcf,'-dpdf',filer);
     filer2 = filer;
     filer2(end-2:end) = 'png';
     [bd,tmp,tmp] = fileparts(filer2);
     if ~exist(bd,'dir')
       mkdir(bd);
     end
     print(gcf,'-dpng',filer2);

     allbbs{end+1} = allbb;
     allbb(1,7)

    %paintfiler = ...
    %     sprintf('%s/%s.%d.%s.png',basedir, ...
    %             curm.curid, curm.objectid, curm.cls);
    % imwrite(Ipaint,paintfiler);

    % curm = models{bbox(6)};
    % basedir = '/nfs/baikal/tmalisie/labelme400/www/voc/exemplars/';
    % paintfiler = ...
    %     sprintf('%s/%s.%d.%s.png',basedir, ...
    %             curm.curid, curm.objectid, curm.cls);
    % imwrite(Ipaint,paintfiler);

    %imagesc(I)
    %plot_bbox(bbox,'',color,color);

    %plot_bbox(bbs(curb,:));
    %axis image
    %axis off
    %title(sprintf('I=%s\nE=%s.%d s=%.3f os=%.3f',grid{bbs(curb,5)}.curid,models{bbs(curb,6)}.curid,models{bbs(curb,6)}.objectid,bbs(curb,end),moses(curb)));
    counter = counter+1;

  end
end

author: quantombone

repo: exemplarsvm


text:
%
% Load library from a file,
% as specified in the function defaultps
%
function lib = loadlib()
    ps = defaultps;
    load(ps.libname,'lib');
    assert(isa(lib,'Library'));
end

author: brendenlake

repo: BPL

save_path: github-repos/MATLAB/brendenlake-BPL


text:
function output_image = PTKSimpleRegionGrowing(threshold_image, start_points_global, reporting)
    % PTKSimpleRegionGrowing. Performs 3D region growing through the supplied
    %     binary threshold image, starting from the specified points
    %
    %
    %     Syntax:
    %         output_image = PTKSimpleRegionGrowing(threshold_image, start_points_global, reporting)
    %
    %         Inputs:
    %         ------
    %             threshold_image - The threshold image in a PTKImage class. 1s
    %                 represents voxels which are connected
    %             start_points - an array of points, where each point is a
    %                 coordinate in the form [i, j, k]. The region growing will
    %                 begin from all these points simultaneously
    %             reporting - an object implementing CoreReportingInterface
    %                             for reporting progress and warnings
    %
    %         Outputs:
    %         -------
    %             output_image - A binary PTKImage containing the segmented region
    %                 of all voxels connected to the starting points
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2012.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    % Check the input image is of the correct form
    if ~isa(threshold_image, 'PTKImage')
        error('Requires a PTKImage as input');
    end

    if exist('reporting', 'var')
        reporting.ShowProgress('Region growing');
    end

    output_image = threshold_image.BlankCopy;
    segmented_image = zeros(threshold_image.ImageSize, 'uint8');

    [linear_offsets, ~] = MimImageCoordinateUtilities.GetLinearOffsets(threshold_image.ImageSize);
    start_points_matrix = cell2mat(start_points_global');
    start_points_matrix = threshold_image.GlobalToLocalCoordinates(start_points_matrix);
    next_points = MimImageCoordinateUtilities.FastSub2ind(threshold_image.ImageSize, start_points_matrix(:, 1), start_points_matrix(:, 2), start_points_matrix(:, 3));

    threshold_image = logical(threshold_image.RawImage);
    number_points = length(segmented_image(:));

    number_of_points_to_grow = sum(threshold_image(:));
    iteration = 0;

    while ~isempty(next_points)
        if mod(iteration, 100) == 0
            points_to_do = sum(threshold_image(:));
            reporting.UpdateProgressStage(number_of_points_to_grow - points_to_do, number_of_points_to_grow);
        end
        iteration = iteration + 1;
        all_points = GetNeighbouringPoints(next_points, linear_offsets);
        all_points = all_points(all_points > 0 & all_points <= number_points);

        list_of_neighbours_indices = all_points(threshold_image(all_points))';
        segmented_image(list_of_neighbours_indices) = 1;
        threshold_image(list_of_neighbours_indices) = false;

        next_points = list_of_neighbours_indices';
    end
    output_image.ChangeRawImage(segmented_image);

    if exist('reporting', 'var')
        reporting.CompleteProgress;
    end
 end

function list_of_point_indices = GetNeighbouringPoints(point_indices, linear_offsets)
    list_of_point_indices = repmat(point_indices, 1, 6) + repmat(linear_offsets, length(point_indices), 1);
    list_of_point_indices = unique(list_of_point_indices(:));
end

author: tomdoel

repo: pulmonarytoolkit


text:
function cvx_optpnt = convex_poly_coeffs( deg, mm ) %#ok

%CONVEX_POLY_COEFFS   Coefficients of convex degree-n polynomials.
%   CONVEX_POLY_COEFFS(DEG), where DEG is a nonnegative integer, creates a
%   CVX vector variable of length DEG+1 and treats its values as
%   coefficients of a polynomial (in the same sense as POLYVAL). It then
%   constraints those coefficients to guarantee that the resulting
%   polynomial will be convex; that is, its second derivative will be
%   nonnegative over the entire real line. That is, given the declaration
%       variable p(deg+1)
%       p == convex_poly_coeffs(deg)
%   the value of P that results will satisfy
%       POLYVAL([DEG:-1:2].*[DEG-1:-1:1].*P(1:END-2),X)>=0
%   for any real value of X.
%
%   CONVEX_POLY_COEFFS(DEG,MM), where MM is a real vector of length 2,
%   constrains convexity only over the interval MM(1) <= X <= MM(2).
%   That is, given a declaration
%       variable p(deg+1)
%       p == nonneg_poly_coeffs(deg,mm)
%   the value of P that results will satisfy
%       POLYVAL([DEG:-1:2].*[DEG-1:-1:1].*P(1:END-2),X)>=0
%   between MM(1) and MM(2), inclusive. It may be negative outside that
%   interval. Note that MM(1) must be less than MM(2) for this constraint
%   to have any effect.
%
%   Disciplined convex programming information:
%       CONVEX_POLY_COEFFS is a cvx set specification. See the user guide
%       for details on how to use sets.

narginchk(1,2);

%
% Check argument
%

if ~cvx_check_dimension( deg, true ),
    error( 'Argument must be a nonnegative integer.' );
elseif rem( deg, 2 ) ~= 0 && deg ~= 1,
    error( 'Degree must be 0, 1, or even.' );
end

% Check range argument
%

if nargin < 2 || isempty( mm ),
    mm = [ -Inf, +Inf ];
else
    if ~isa( mm, 'double' ) || ~isreal( mm ) || ndims( mm ) > 2 || numel( mm ) ~= 2 && size( mm, 2 ) ~= 2, %#ok
        error( 'Second argument must be a range [ xmin xmax ] or a matrix of them.' );
    end
    mm = reshape( mm, 0.5 * numel( mm ), 2 );
    m1 = mm(:,1);
    m2 = mm(:,2);
    if any( ( m1 == m2 ) & isinf( m1 ) ),
        error( 'Intervals [-Inf,-Inf] and [+Inf,+Inf] are not accepted.' );
    end
end

%
% Construct set
%

cvx_begin set
    variable coeffs(deg+1);
    if deg >= 2,
        ((deg:-1:2).*(deg-1:-1:1))'.*coeffs(1:end-2,:) == nonneg_poly_coeffs(deg-2,mm); %#ok
    end
cvx_end

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

author: cvxr

repo: CVX

save_path: github-repos/MATLAB/cvxr-CVX


text:
function tests = test_gifti
% Unit Tests for gifti
%__________________________________________________________________________
% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging

% $Id: test_gifti.m 6516 2015-08-07 17:28:33Z guillaume $

tests = functiontests(localfunctions);

function test_gifti_constructor(testCase)
import matlab.unittest.constraints.*
g1 = gifti;
g2 = gifti(fullfile(spm('Dir'),'canonical','cortex_20484.surf.gii'));
g3 = gifti(g2);
s  = struct(g3);
g4 = gifti(s);
g5 = gifti(rand(16,1));

testCase.verifyThat(g1, IsOfClass('gifti'));
testCase.verifyThat(fieldnames(g1), IsEmpty);

testCase.verifyThat(g2, IsOfClass('gifti'));
testCase.verifyThat(s, HasField('faces'));
testCase.verifyThat(s, HasField('vertices'));
testCase.verifyThat(s, HasField('mat'));

testCase.verifyThat(g3, IsOfClass('gifti'));
testCase.verifyThat(g3, IsEqualTo(g2));

testCase.verifyThat(s, IsOfClass('struct'));
testCase.verifyThat(s, HasField('faces'));
testCase.verifyThat(s, HasField('vertices'));
testCase.verifyThat(s, HasField('mat'));

testCase.verifyThat(g4, IsOfClass('gifti'));
testCase.verifyThat(struct(g4), IsEqualTo(s));

testCase.verifyThat(g5, IsOfClass('gifti'));
testCase.verifyThat(g5, HasField('cdata'));

function test_gifti_accessor(testCase)
import matlab.unittest.constraints.*
g1 = gifti(fullfile(spm('Dir'),'canonical','cortex_8196.surf.gii'));
s.faces    = g1.faces;
s.vertices = g1.vertices;
s.mat      = g1.mat;
testCase.verifyEqual(s.faces(1000,:), g1.faces(1000,:));
testCase.verifyEqual(s.vertices(1000,:), g1.vertices(1000,:));
testCase.verifyEqual(s.mat(:,4), g1.mat(:,4));

cdata = single(rand(16,1));
g2 = gifti(cdata);
testCase.verifyEqual(cdata,g2.cdata);
testCase.verifyEqual(cdata(8),g2.cdata(8));
testCase.verifyEqual(cdata(8,1),g2.cdata(8,1));

function test_gifti_mutator(testCase)
import matlab.unittest.constraints.*
g = gifti(fullfile(spm('Dir'),'canonical','cortex_5124.surf.gii'));
g.mat = eye(4);
g.mat(logical(eye(4))) = 2;
g.mat(4,4) = 1;
testCase.verifyEqual(g.mat, diag([2 2 2 1]));

faces = g.faces;
faces = faces(:,[2 1 3]);
g.faces = faces;
g.faces(64,:) = [1 2 3];
g.faces(:,1) = faces(:,1);
testCase.verifyEqual(g.faces(64,:), [faces(64,1) 2 3]);

vertices = g.vertices;
vertices = vertices(:,[2 1 3]);
g.vertices = vertices;
g.vertices(64,:) = zeros(1,3);
g.vertices(:,2:3) = ones(size(vertices,1),2);
testCase.verifyEqual(g.vertices(64,:), single([0 1 1]));

g.cdata = rand(size(g.vertices,1),1);
g.cdata(1) = pi;
g.cdata(2:end) = exp(1);
testCase.verifyEqual(g.cdata(1), single(pi));

function test_gifti_export(testCase)
import matlab.unittest.constraints.*
mri = load('mri');
g = gifti(isosurface(smooth3(squeeze(mri.D)),5));
s = export(g);
testCase.verifyThat(s, HasField('vertices'));
testCase.verifyThat(s, HasField('faces'));
s = export(g,'matlab');
testCase.verifyThat(s, HasField('vertices'));
testCase.verifyThat(s, HasField('faces'));
s = export(g,'patch');
testCase.verifyThat(s, HasField('vertices'));
testCase.verifyThat(s, HasField('faces'));
testCase.verifyThat(s, ~HasField('mat'));
s = export(g,'fieldtrip');
testCase.verifyThat(s, HasField('pnt'));
testCase.verifyThat(s, HasField('tri'));
s = export(g,'spm');
testCase.verifyThat(s, HasField('vert'));
testCase.verifyThat(s, HasField('face'));

function test_gifti_load(testCase)
import matlab.unittest.constraints.*
d = fullfile(spm('Dir'),'canonical');
files = dir(fullfile(d,'*.gii'));
for i=1:numel(files)
    g = gifti(fullfile(d,files(i).name));
    testCase.verifyThat(evalc('g'), ~IsEmpty); % check display()
end

function test_gifti_save(testCase)
mri = load('mri');
g = gifti(isosurface(smooth3(squeeze(mri.D)),5));
g.cdata = rand(size(g.vertices,1),1);
basename = tempname;
file = [basename '.gii'];
save(g,file,'ASCII');
g = gifti(file);
delete(file);
save(g,file,'Base64Binary');
g = gifti(file);
delete(file);
save(g,file,'GZipBase64Binary');
g = gifti(file);
delete(file);
save(g,file,'ExternalFileBinary');
g = gifti(file);
delete(file);
delete([basename '.dat']);

author: spm


text:
function value = fibonacci2_determinant ( n )

%*****************************************************************************80
%
%% FIBONACCI2_CONDITION returns the L1 condition of the FIBONACCI2 matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 April 2015
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of A.
%
%    Output, real VALUE, the L1 condition.
%
  if ( n == 1 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'FIBONACCI2_CONDITION - Fatal error!\n' );
    fprintf ( 1, '  The condition number is infinite for N=1\n' );
    error ( 'FIBONACCI2_CONDITION - Fatal error!' )
  end

  if ( n == 1 )
    a_norm = 0.0;
  elseif ( n == 2 )
    a_norm = 2.0;
  else
    a_norm = 3.0;
  end
  b_norm = n;
  value = a_norm * b_norm;

  return
end


text:
function [w,backAzimuth,trigger,staLat,staLon,origLat,origLon] = demo(TC)

%DEMO
% DEMO(THREECOMP) Loads demo waveforms and plots a station map of data used
% in the demo.

% LOAD DEMO WAVEFORMS
load('private/demo_waveforms.mat');

% SET TRIGGER TIMES
% These times represent crude surface wave picks on the
% transverse component
trigger =datenum({'2000/06/26 15:44:06'
'2000/06/26 15:43:39'
'2000/06/26 15:43:49'
'2000/06/26 15:44:07'
'2000/06/26 15:44:43'
'2000/06/26 15:44:05'
'2000/06/26 15:44:36'
'2000/06/26 15:43:54'
'2000/06/26 15:44:03'
'2000/06/26 15:43:44'
'2000/06/26 15:43:44'
'2000/06/26 15:44:02'
'2000/06/26 15:44:07'
'2000/06/26 15:43:59'});

% STATION LOCATIONS AND NAMES
staLat = get(w(:,1),'STATIONLATITUDE');
staLon = get(w(:,1),'STATIONLONGITUDE');
origLat = get(w(:,1),'ORIGINLATITUDE');
origLon = get(w(:,1),'ORIGINLONGITUDE');
staName = get(w(:,1),'STATION');

% PLOT MAP OF DEMO DATA
cookbooks.threecomp_cookbook_map(threecomp,w,backAzimuth);

clear TC

author: geoscience-community-codes

repo: GISMO


text:
function test_ft_sourceanalysis

% WALLTIME 00:10:00
% MEM 2gb
% DEPENDENCY ft_sourceanalysis
% DATATYPE comp timelock freq

fs = 500;
nchan = 32;
start_time = -1; % seconds
end_time = 2.5; % seconds
nsamples = (end_time - start_time) * fs + 1;

data = [];
data.time{1} = linspace(start_time, end_time, nsamples);
data.trial{1} = randn(nchan,nsamples);
data.sampleinfo = [1 nsamples];
data.label = cellstr(num2str((1:nchan).'));

% construct a set of electrodes randomly distributed over the upper hemisphere
data.elec.label = data.label;
data.elec.unit = 'cm';
data.elec.tra = eye(nchan);
data.elec.elecpos = randn(nchan,3);
data.elec.elecpos(:,3) = abs(data.elec.elecpos(:,3));
for i=1:nchan
  data.elec.elecpos(i,:) = 10*data.elec.elecpos(i,:)/norm(data.elec.elecpos(i,:));
end
data.elec.chanpos = data.elec.elecpos;

% make an explicit geometry with 4 surfaces
% the radius of each follows the BESA defaults
geometry = [];
geometry(1).pos  = data.elec.elecpos*71/85; % brain
geometry(1).unit = data.elec.unit;
geometry(2).pos  = data.elec.elecpos*72/85; % csf
geometry(2).unit = data.elec.unit;
geometry(3).pos  = data.elec.elecpos*79/85; % skull
geometry(3).unit = data.elec.unit;
geometry(4).pos  = data.elec.elecpos*85/85; % scalp
geometry(4).unit = data.elec.unit;

% fit a 4-sphere concentric model to the geometry
headmodel = ft_headmodel_concentricspheres(geometry, 'conductivity', [0.33 1.00 0.042 0.33]);

% test for comp type
cfg = [];
cfg.updatesens = 'no';
comp = ft_componentanalysis(cfg,data);
ft_checkdata(comp, 'datatype', 'comp');

cfg = [];
cfg.xgrid = 'auto';
cfg.ygrid = 'auto';
cfg.zgrid = 'auto';
cfg.resolution = 1; % cm
cfg.component = [1 2 5];
cfg.headmodel = headmodel;
cfg.method = 'rv';
sourceout = ft_sourceanalysis(cfg, comp);

% test for timelock type
cfg = [];
timelock = ft_timelockanalysis(cfg, data);
ft_checkdata(timelock, 'datatype', 'timelock');

cfg = [];
cfg.xgrid = 'auto';
cfg.ygrid = 'auto';
cfg.zgrid = 'auto';
cfg.resolution = 1; % cm
cfg.latency = [0 1];
cfg.headmodel = headmodel;
sourceout = ft_sourceanalysis(cfg, timelock);

% test for freq type
cfg = [];
cfg.method = 'mtmfft';
cfg.taper = 'dpss';
cfg.tapsmofrq = 2;
cfg.output = 'fourier';
freq = ft_freqanalysis(cfg, data);
ft_checkdata(freq, 'datatype', 'freq');

cfg = [];
cfg.xgrid = 'auto';
cfg.ygrid = 'auto';
cfg.zgrid = 'auto';
cfg.resolution = 1; % cm
cfg.frequency = 10; % Hz
cfg.headmodel = headmodel;
sourceout = ft_sourceanalysis(cfg, freq);

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function myTab = findOrCreateTab(fig, look_here_containers, create_here_tabgroup, title, varargin)
    % FINDORCREATETAB return handle to a specified tab. if the tab doesn't exist, it is created
    %
    % tabH = FINDORCREATETAB( FIG, CONTAINER_TAG, TITLE, OPTS)
    %    FIG is a figure handle. The uitab with the Title "TITLE" will be returned only tabs
    %    belonging to this figure are returned. If the tab doesn't already exist, it will be
    %    created with the title TITLE within the container identified by the CONTAINER_TAG.
    %
    %    OPTS can be 'deleteable',
    %    CONTAINER_TAG can be the handle to a container, too.
    %

    import callbacks.copytab

    assert(isgraphics(look_here_containers) && isvalid(look_here_containers), 'expected valid container');

    deleteable= ismember('deleteable',varargin);
    if deleteable
        myTag='CopytabToFigDeleteable';
    else
        myTag='CopyTabToFig';
    end

    if ischarlike(create_here_tabgroup)
        myContainer=findobj(fig,'Type','uitabgroup','-and','Tag',create_here_tabgroup);
    elseif isgraphics(create_here_tabgroup) && isvalid(create_here_tabgroup)
        myContainer=create_here_tabgroup;
        assert(ancestor(myContainer,'figure')==fig);
    else
        error('unspecified container');
    end

    myTab=findobj(look_here_containers, 'Title', title, '-and', 'Type', 'uitab');

    if isempty(myTab)
        myTab=uitab(myContainer, 'Title',title);

        contextMenus = findobj(fig.Children,'flat','Tag',myTag,'-and','Type','uicontextmenu');

        if isempty(contextMenus)
            contextMenus=uicontextmenu(fig,'Tag',myTag);
            uimenu(contextMenus,'Label','Copy Contents to new figure (static)','Callback',@copytab)
            if deleteable
                uimenu(contextMenus,'Label','Close Tab','Callback',@(src,ev)delete(gco));
            end
        end
        myTab.UIContextMenu=contextMenus;
    end
end

author: CelsoReyes


text:
% Copyright 2011 Zdenek Kalal
%
% This file is part of TLD.
%
% TLD 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.
%
% TLD 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 TLD.  If not, see <http://www.gnu.org/licenses/>.

function bb = bb_click(tld,img)
% Create

if isfield(tld,'handle')
     h = get(gca,'Children'); delete(h(1:end-1));
    set(tld.handle,'cdata',img);
else
    imshow(img);
end
text(10,10,'Define bounding box and double click inside.','color','white');
h = imrect;
p = wait(h);
bb = [p(1); p(2);p(1)+p(3); p(2)+p(4)];
% [c,r,p] = impixel(img);
% if length(c) ~= 2,
%     bb = [];
%     return;
% end
% bb = [c(1); r(1); c(2); r(2)];

repo: OpenTLD


text:
function [lbeta lgamma method] = betaq_up_v2(q, n, P)
% computes the _UPPER_ bound (as good as it can find) for the beta_q function:
%   beta_q = min Q(B), s.t. P(B) >= q
%
%   where
%
%	P ~ Gsn( x_0,	I_n )
%	Q ~ Gsn( 0, (1+A^2) I_n )
%
%	And x_0 something that is ||x_0||^2 = n A^2
%
%	Taking x_0 = [A, ... A] we get
%
%	P[ dP/dQ >= gamma ] = P(  sum (Z_i - 1/A)^2 <= pp  )
%	Q[ dP/dQ >= gamma ] = P(  sum (Z_i - sqrt(1+A^2)/A)^2 <= qq )
%
%	pp = ((1 + A^2) n - gammatil) / A^2
%	qq = ((1 + A^2) n - gammatil) / ((1+A^2) A^2)
%
%	gammatil = [ log gamma - n/2 log (1+A^2) ] 2 (1 + A^2) / log e
%
%
% Idea for the upper bound: take any \gamma s.t. P_\gamma >= q. Then Q_\gamma >= \beta_q
% Or for high gamma: \beta_q <= 1/gamma;

% conversion A->P. Old versions are all in terms of ``amplitude'' A.
A = sqrt(P);

pp0 = ncx2inv(q, n, n/A^2);
iter = 1;
while 1;
	pgam = ncx2cdf(pp0, n, n/A^2);

	if (pgam >= q)
		break
	end

	delta = q - pgam;
	%
	% For q > .5 this is underestimate => we will undershoot.
	%
	pp0 = pp0 + delta/ncx2pdf(pp0, n, n/A^2);
	iter = iter + 1;
end

delta = pgam - q;

gammatil = (1 + A^2) * n - A^2 * pp0;
lgamma = gammatil * log2(exp(1)) / (2  + 2*A^2) + n/2 *log2 (1 + A^2);
qq0 = ((1+A^2) * n - gammatil) / ((1+A^2)*A^2);

%
% The funny property of ncx2cdf is that it returns pretty consistent results up until
% it starts returning 0's. So we believe it until term0. After that we use simple 1/gamma
% upper bound.
%
% TODO: change 1/gamma bound to a large deviation chernoff-type one.
%	04/18/2007: done. (see various comparisons in script_optimize_upper)
%
% 05/02/2007: all upper bounding is deprecated, now we simply use ncx2log() which
%	works for all values of interest.
%
term1 = ncx2cdf(qq0, n, n*(1 + 1/A^2));

if (term1 == 0)
	%
	% This is the old upper bound beta <= 1/gamma
	%
	%lbeta =  -lgamma;

	lbeta = log2(exp(1)) * ncx2log(qq0, n, n*(1 + 1/A^2));

    if (lbeta > -1240)
       	if (lbeta > -lgamma)
    		disp('ERROR: precise value of lbeta is above 1/gamma ');
        	error('betaq_up_v2');
    	end
        msg = 'PREC_LOG';
    else

    %
	% LARGE-DEVIATIONS method: if everything else fails
	%
	pstar = A^2/2;
	sn = qq0/n;

	s = warning('off', 'optim:fminunc:SwitchingMethod');
	opts = optimset('Display', 'off');
	[popt fopt] = ...
		fminunc(@(p)( -1/2 * log(2*abs(p)+1) - abs(p)/(2*abs(p)+1) * (1+ 1/A^2) + abs(p)*sn ), ...
			pstar, opts);
	warning(s);

	lbeta_ld = fopt * log2(exp(1)) * n;
	lbeta_gamma = -lgamma;

	if (lbeta_gamma > lbeta_ld)
		lbeta = lbeta_ld;
		msg = 'LARGE-DEV';
		method = 2;
	else
		lbeta = lbeta_gamma;
		msg = 'GAMMA';
		method = 1;
	end;

    end;

	disp(sprintf('betaq_up(q = %g, n = %d, A = %g): %s: iter = %d, delta = %.1g, lbeta = %.2f', ...
			q, n, A, msg, iter, delta, lbeta));
else
	lbeta = log2(term1);
	method = 0;
	disp(sprintf('betaq_up(q = %g, n = %d, A = %g): PRECISE: iter = %d, delta = %.1g, lbeta = %.2f (loose: %.1f %% worse) ', ...
			q, n, A, iter, delta, lbeta, 100*(-lgamma-lbeta)/(-lbeta)));
end;

author: yp-mit

repo: spectre

save_path: github-repos/MATLAB/yp-mit-spectre


text:
%
% Generate a random polynomial
%
% Syntax: >> p = RandomPolynomial(variables,degree,terms)
%     or  >> p = prand(variables,degree,terms)
%
% Input: variables --- (cell or string) variables
%           degree --- (integer or vector) tuple degree bound
%                                  for the random polynomial
%            terms --- (integer/string, optional) number of terms or 'all',
%                       if missing, produce all terms in univariate case
%                       or random number of terms in multivariate case
%
%  Output:          p --- (string) random polynomial
%
% Example:  >>  p = prand({'x','y'},[5,2],4)
%           p =
%                -2*x^2 + 9*x^3*y^2 - 9*x^4*y^2 + 8*x^5*y^2

author: zarathustr

repo: LibQPEP

save_path: github-repos/MATLAB/zarathustr-LibQPEP