text:
function [ cdf ] = gsp_erdos_renyi_warp( ss , N , p )

cutoff=4; % parameter to approximate the non-compactly supported distribution (the free convolution) by a compactly supported one, just for numerical purposes
% To do: pass a parameter

num_pts=length(ss);
if num_pts > 2
    delta=min(ss(2:num_pts)-ss(1:(num_pts-1)));
else
    delta=.1;
end

cdf=zeros(size(ss));

for k=1:num_pts
    if ss(k) > (p*N-cutoff*sqrt(p*(1-p)*N)-delta)
        if ss(k) <= (p*N+cutoff*sqrt(p*(1-p)*N)+delta)
            xx=(p*N-cutoff*sqrt(p*(1-p)*N)-2*delta):delta:ss(k);
            cdf(k)=trapz(xx,sqrt(1/((1-p)*N*p))*gsp_free_conv_norm_semi((xx-p*N)/(sqrt(p*(1-p)*N))));
        else
            cdf(k)=1;
        end
    end
end

end


text:
% BTF ordering toolbox:
%
% Primary functions:
%
%   btf        - permute a square sparse matrix into upper block triangular form
%   maxtrans   - permute the columns of a sparse matrix so it has a zero-free diagonal
%   strongcomp - symmetric permutation to upper block triangular form
%
% Other:
%   btf_install - compile and install BTF for use in MATLAB.
%   btf_demo    - demo for BTF
%   drawbtf     - plot the BTF form of a matrix
%   btf_make    - compile BTF for use in MATLAB
%
% Example:
%   q = maxtrans (A)
%   [p,q,r] = btf (A)
%   [p,r] = strongcomp (A)

% Copyright 2004-2007, Tim Davis, University of Florida

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
% STD_FINDSAMEICA - find groups of datasets with identical ICA decomposiotions
%                     (search identical weight*sphere matrices)
%
% Usage:
%        >> clusters = std_findsameica(ALLEEG);
%        >> clusters = std_findsameica(ALLEEG,icathreshold);
% Inputs:
%   ALLEEG           - a vector of loaded EEG dataset structures of all sets
%                      in the STUDY set.
%   icathreshold     - Threshold to compare icaweights. Default 2e-4.
%
% Outputs:
%   cluster - cell array of groups of datasets
%   indices - cluster index for each dataset
%
% Authors:  Arnaud Delorme, SCCN, INC, UCSD, July 2009-
% 2016 change: as of May 2016, the function now compares the product of the
%              weight and the sphere matrices instead of just the weight
%              matrices.

% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, arno@sccn.ucsd.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

% Coding notes: Useful information on functions and global variables used.

function [cluster, inds] = std_findsameica(ALLEEG, varargin)

% 6/2/2014 Ramon : Allow ica threshold as input.
if nargin == 1
    icathreshold = 2e-4;
elseif nargin == 2
    icathreshold = varargin{1};
end

cluster = { [1] };
inds = [1];
for index = 2:length(ALLEEG)

    found = 0;
    for c = 1:length(cluster)
        w1 = ALLEEG(cluster{c}(1)).icaweights*ALLEEG(cluster{c}(1)).icasphere;
        w2 = ALLEEG(index).icaweights*ALLEEG(index).icasphere;
        if all(size(w1) == size(w2))
            %if isequal(ALLEEG(cluster{c}(1)).icaweights, ALLEEG(index).icaweights)
            if sum(sum(abs(w1-w2))) < icathreshold
                cluster{c}(end+1) = index;
                inds(index) = c;
                found = 1;
                break;
            end
        end
    end
    if ~found
        cluster{end+1} = index;
        inds(index) = index;
    end
end

author: sccn

repo: eeglab

save_path: github-repos/MATLAB/sccn-eeglab


text:
function vw= loadCorAnal(vw, corAnalFile, computeIfNeeded)
% Loads corAnal (coherence analysis) file and fills co, amp, and ph slots
% in the view structure.
%
% vw = loadCorAnal(vw, [corAnalFile], [computeIfNeeded=1])
%
% If you change this function make parallel changes in:
%   loadCorAnal, loadResStdMap, loadStdMap, loadMeanMap
%
% corAnalFile: path to the corAnal file. If it is empty, assumes
%			   it is 'corAnal.mat' in the view's dataDir.
%			   If it's one of 'ask' or 'dialog', pops up a dialog to let
%			   the user select.
%
% computeIfNeeded: if 1, and the corAnalFile is not found, will compute it
%			   for all scans in the view's current data type. Otherwise,
%			   just warns the user and returns an unmodified view.
%			   [Default: 1]
%
% djh, 1/9/98
% dbr, 6/23/99  Modified to use fullfile for NT/Unix platform
%               compatibility.
% djh, 2/2001, mrLoadRet 3.0
% create the full corAnalFile if dataType not original
% sod, 7/2005,  Added option to look for CorAnal file (ask param).
% will be used from fileMenu but other calls will remain the same.
% ras, 7/2007,  added computeIfNeeded argument.
if notDefined('vw'),		vw = getCurView;		end
if notDefined('corAnalFile')
	corAnalFile = fullfile(dataDir(vw), 'corAnal.mat');
end

if notDefined('computeIfNeeded'), computeIfNeeded = 0; end % Making this ==1 breaks a bunch of stuff in the Flat view as far as I can tell ARW 080807
if notDefined('loadMap'), loadMap=0;    end

if ismember(lower(corAnalFile), {'ask' 'dialog' 'select'})
	corAnalFile = getPathStrDialog(dataDir(vw), ...
					['Choose CorAnal map file name'],['*.mat']);
end

if ~exist(corAnalFile,'file')
     corAnalFile = fullfile(dataDir(vw), corAnalFile);
end

verbose = prefsVerboseCheck;

if ~exist(corAnalFile,'file')
	msg = sprintf('corAnal file %s not found. \n', corAnalFile);

	if computeIfNeeded==1
		% compute it
		if verbose > 1,
			fprintf('[%s]: %s\n', mfilename, msg);
			disp('Computing Coherence Analysis ...')
		end
		vw = computeCorAnal(vw, 0);
	else
		% % just warn the user
		% warning(msg);
	end

	return;
end

if verbose > 0
	fprintf('[%s]: Loading from %s ... ', mfilename, corAnalFile);
end

load(corAnalFile); % loads co, amp, ph

if verbose > 0
	fprintf('done.\n');
end

% check that the corAnal fields are the appropriate size
checkSize(vw, co);
checkSize(vw, amp);
checkSize(vw, ph);

% assign to view
vw.co = co;
vw.amp = amp;
vw.ph = ph;
if notDefined('map')~=1, vw.map=map; end
return;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
% - This function is part of ERPLAB Toolbox -

function varargout = linespecGUI(varargin)

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
      'gui_Singleton',  gui_Singleton, ...
      'gui_OpeningFcn', @linespecGUI_OpeningFcn, ...
      'gui_OutputFcn',  @linespecGUI_OutputFcn, ...
      'gui_LayoutFcn',  [] , ...
      'gui_Callback',   []);
if nargin && ischar(varargin{1})
      gui_State.gui_Callback = str2func(varargin{1});
end

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

% --------------------------------------------------------------------------------------------
function linespecGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% handles.output = [];
handles.fulltext =[];
handles.output   =[];

try
      def = varargin{1};
catch
      def = [];
end
try
        nbin = varargin{2};
catch
        nbin = 1;
end
try
        lwidth = varargin{3};
catch
        lwidth = 1;
end

defs       = {'-' '-.' '--' ':'};% sorted according 1st erplab's version
defcol     = getcolorcellerps; %{'k' 'r' 'b' 'g' 'c' 'm' 'y' 'w' };

if isempty(def)
        %       defcolor = repmat({'k' 'r' 'b' 'g' 'c' 'm' 'y' },1, nbin);% sorted according 1st erplab's version
        %       defs     = {'-' '-.' '--' ':'};% sorted according 1st erplab's version
        %       d = repmat(defs',1,length(defcolor));
        %       defstyle = reshape(d',1,length(defcolor)*length(defs));

        defcolor  = repmat(defcol,1, 1*length(defs));% sorted according 1st erplab's version
        d = repmat(defs',1, 1*length(defcol));
        defstyle = reshape(d',1, numel(d));
else
        defcolor = regexp(def,'\w*','match');
        defcolor = [defcolor{:}];
        defstyle = regexp(def,'\W*','match');
        defstyle = [defstyle{:}];
        if isempty(defcolor)
                defcolor  = repmat(defcol,1, ERP.nbin*length(defs));% sorted according 1st erplab's version
                d = repmat(defs',1, ERP.nbin*length(defcol));
                defstyle = reshape(d',1, numel(d));
        end
        if isempty(defstyle)
                d = repmat(defs',1, ERP.nbin*length(defcol));
                defstyle = reshape(d',1, numel(d));
        end
end

COLORDATA  = colores(defcolor);
STYLEDATA  = estilos(defstyle);
set(handles.popupmenu_lwidth,'String', {1:20})
set(handles.popupmenu_lwidth,'Value', lwidth)

handles.defcolor  = defcolor;
handles.defstyle  = defstyle;
handles.COLORDATA = COLORDATA;
handles.STYLEDATA = STYLEDATA;
handles.nbin = nbin;

setlistbox_color(hObject, handles, COLORDATA, nbin )
setlistbox_style(hObject, handles, STYLEDATA, nbin )

for k=1:length(defcol)
      switch defcol{k}
            case 'k'
                  cwrd = 'BLACK';
            case 'r'
                  cwrd = 'RED';
            case 'b'
                  cwrd = 'BLUE';
            case 'g'
                  cwrd = 'GREEN';
            case 'c'
                  cwrd = 'CYAN';
            case 'm'
                  cwrd = 'MAGENTA';
            case 'y'
                  cwrd = 'YELLOW';
            case 'w'
                  cwrd = 'WHITE';
            otherwise
                  error('color error...')
      end
        set(handles.(['pushbutton_color' num2str(k)]),'UserData', cwrd)
        setcolorbuttons(k, cwrd, hObject, eventdata, handles);
end

% defs       = {'-' '-.' '--' ':'};
% solid   dash-dot   dashed   dotted
for k=1:length(defs)
        switch defs{k}
                case '-'
                        lwrd = 'solid';
                case '-.'
                        lwrd = 'dash-dot';
                case '--'
                        lwrd = 'dashed';
                case ':'
                        lwrd = 'dotted';
                otherwise
                        error('line error...')
        end
        set(handles.(['pushbutton_line' num2str(k)]),'String', defs{k})
        set(handles.(['pushbutton_line' num2str(k)]),'UserData', lwrd)
        %setlinebuttons(k, lwrd, hObject, eventdata, handles);
end

%
% Name & version
%
version = geterplabversion;
set(handles.gui_chassis,'Name', ['ERPLAB ' version '   -   Line specifications GUI'],'WindowStyle','modal')

%
% Color GUI
%
handles = painterplab(handles);

%
% Set font size
%
handles = setfonterplab(handles);

% Update handles structure
guidata(hObject, handles);

% help
% helpbutton

drawnow
uiwait(handles.gui_chassis);

% --------------------------------------------------------------------------------------------
function varargout = linespecGUI_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;

% The figure can be deleted now
delete(handles.gui_chassis);
pause(0.1)

% --------------------------------------------------------------------------------------------
function setcolorbuttons(ind, colorword, hObject, eventdata, handles)
try
      [img,map]    = imread(['erplab_' colorword '.jpg']);
      colormap(map)
      [row,column] = size(img);
      p = get(handles.(['pushbutton_color' num2str(ind)]),'Position');
      w = p(3); % width
      h = p(4); % hight
      steprow   = ceil(row/(5*h));
      stecolu   = ceil(column/(10*w));
      imgbutton = img(1:steprow:end,1:stecolu:end,:);
      set(handles.(['pushbutton_color' num2str(ind)]),'String','')
      set(handles.(['pushbutton_color' num2str(ind)]),'CData',imgbutton);
      set(handles.(['pushbutton_color' num2str(ind)]),'Position', [p(1) p(2) p(3)*1.25 p(4)*1.25]);
catch
      %set(handles.pushbutton_help,'String','Help');
      set(handles.(['pushbutton_color' num2str(ind)]),'String', lower(colorword(1:2)));
end

% % --------------------------------------------------------------------------------------------
% function setlinebuttons(ind, lineword, hObject, eventdata, handles)
% try
%       [img,map]    = imread(['erplab_' colorword '.jpg']);
%       colormap(map)
%       [row,column] = size(img);
%       p = get(handles.(['pushbutton_color' num2str(ind)]),'Position');
%       w = p(3); % width
%       h = p(4); % hight
%       steprow   = ceil(row/(5*h));
%       stecolu   = ceil(column/(10*w));
%       imgbutton = img(1:steprow:end,1:stecolu:end,:);
%       set(handles.(['pushbutton_color' num2str(ind)]),'String','')
%       set(handles.(['pushbutton_color' num2str(ind)]),'CData',imgbutton);
%       set(handles.(['pushbutton_color' num2str(ind)]),'Position', [p(1) p(2) p(3)*1.25 p(4)*1.25]);
% catch
%       %set(handles.pushbutton_help,'String','Help');
%       set(handles.(['pushbutton_color' num2str(ind)]),'String', lower(colorword(1:2)));
% end

% --------------------------------------------------------------------------------------------
function COLORDATA  = colores(defcolor)
% COLORDATA = struct(1);
for i=1:length(defcolor);
      %COLORDATA(i).colorname    = defcolor{i};
      COLORDATA(i).colorchar    = defcolor{i};

      switch defcolor{i}
            case 'k'
                  COLORDATA(i).colorname    = 'black';
                  COLORDATA(i).colorhtmlcode = '#000000';
            case 'r'
                  COLORDATA(i).colorname     = 'red';
                  COLORDATA(i).colorhtmlcode = '#FF0000';
            case 'b'
                  COLORDATA(i).colorname    = 'blue';
                  COLORDATA(i).colorhtmlcode = '#0000FF';
            case 'g'
                  COLORDATA(i).colorname    = 'green';
                  COLORDATA(i).colorhtmlcode = '#009000';
            case 'c'
                  COLORDATA(i).colorname    = 'cyan';
                  COLORDATA(i).colorhtmlcode = '#00FFFF';
            case 'm'
                  COLORDATA(i).colorname    = 'magenta';
                  COLORDATA(i).colorhtmlcode = '#FF00FF';
            case 'y'
                  COLORDATA(i).colorname    = 'yellow';
                  %COLORDATA(i).colorhtmlcode = '#FFFF00';     %
                  COLORDATA(i).colorhtmlcode = '#FFD700';     % or gold #FDD017
            case 'w'
                  COLORDATA(i).colorname    = 'white';
                  COLORDATA(i).colorhtmlcode = '#F1F1F1';     % winter white?
            otherwise
                  COLORDATA(i).colorname    = 'black';
                  COLORDATA(i).colorhtmlcode = '#000000';
      end
end
% --------------------------------------------------------------------------------------------
function STYLEDATA  = estilos(defstyle)
% STYLEDATA = struct(1);
for i=1:length(defstyle);
      %STYLEDATA(i).colorname    = defcolor{i};
      %STYLEDATA(i).colorchar    = defcolor{i};
      switch defstyle{i}
            case {'-',''}
                  STYLEDATA(i).line     = 'solid';
                  STYLEDATA(i).style    = '-';
            case '-.'
                  STYLEDATA(i).line     = 'dash-dot';
                  STYLEDATA(i).style    = '-.';
            case '--'
                  STYLEDATA(i).line    = 'dashed';
                  STYLEDATA(i).style    = '--';
            case ':'
                  STYLEDATA(i).line    = 'dotted';
                  STYLEDATA(i).style    = ':';
            otherwise
                  STYLEDATA(i).line     = 'dot';
                  STYLEDATA(i).style    = '-';
      end
end

% --------------------------------------------------------------------------------------------
function setlistbox_color(hObject, handles, COLORDATA, nbin )
strhtml = cell(1);
maxdig  = length(num2str(length(COLORDATA)))+1;
for i=1:length(COLORDATA)
      % strhtml{i} = sprintf('%s', colorhtmlcode{i}, upper(colorhtmlbase{i}));
      numstr = num2str(i);
      if i<=nbin
            item = ['L' repmat('0',1,maxdig-length(numstr))  numstr ':'];
      else
            item = ['empty..:'];
            %item = [item(1:maxdig+1) ':']
      end
      strhtml{i} = sprintf('%s%s', item,...
            COLORDATA(i).colorhtmlcode, upper(COLORDATA(i).colorname));
end
set( handles.listbox_color, 'String', strhtml)

%handles.COLORDATA = COLORDATA;
% Update handles structure
guidata(hObject, handles);

% --------------------------------------------------------------------------------------------
function setlistbox_style(hObject, handles, STYLEDATA, nbin )
strhtml = cell(1);
maxdig  = length(num2str(length(STYLEDATA)))+1;
for i=1:length(STYLEDATA)
      % strhtml{i} = sprintf('%s', colorhtmlcode{i}, upper(colorhtmlbase{i}));
      numstr = num2str(i);
      if i<=nbin
             item = ['L' repmat('0',1,maxdig-length(numstr))  numstr ':'];
      else
            item = 'empty..:';
            %item = [item(1:maxdig+1) ':'];
      end
      %strhtml{i} = sprintf('%s%s', item, repmat(STYLEDATA(i).line,1,16));
            strhtml{i} = sprintf('%s%s', item,...
            STYLEDATA(i).line);

end
set( handles.listbox_style, 'String', strhtml)

%handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

% --------------------------------------------------------------------------------------------
function listbox_color_Callback(hObject, eventdata, handles)

% --------------------------------------------------------------------------------------------
function listbox_color_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
      set(hObject,'BackgroundColor','white');
end

% --------------------------------------------------------------------------------------------
function pushbutton_up_color_Callback(hObject, eventdata, handles)
COLORDATA = handles.COLORDATA;
nbin = handles.nbin;
currline = get(handles.listbox_color, 'Value'); % current line

ncolor = length(COLORDATA);
if nnz(~bitand(currline>1,currline<=ncolor))==0
      aux = COLORDATA(currline);
      COLORDATA(currline) = COLORDATA(currline-1);
      COLORDATA(currline-1) = aux;
      setlistbox_color(hObject, handles, COLORDATA, nbin )
      set(handles.listbox_color, 'Value', currline-1); % current line
end

handles.COLORDATA = COLORDATA;
% Update handles structure
guidata(hObject, handles);

% fulltext = get(handles.listbox_color, 'String');
% fulltext = regexprep(fulltext,'.*?','');
% indxline = length(fulltext);
% fulltext = char(fulltext); % string matrix
% currline = get(handles.listbox_color, 'Value'); % current line
%
% if nnz(~bitand(currline>1,currline<=indxline))==0
%
%       aux = fulltext(currline,:);
%       fulltext(currline,:) = fulltext(currline-1,:);
%       fulltext(currline-1,:) = aux;
%       %fulltext(currline,:) = [];
%       fulltext = cellstr(fulltext); % cell string
%
%       set(handles.listbox_color, 'String', fulltext);
%       %handles.lastlineclicked = {};
%
%       % Update handles structure
%       %guidata(hObject, handles);
%
%       %set(handles.edit_numeric, 'string','')
%       %set(handles.edit_string, 'string','')
%       %set(handles.edit_binindex, 'string','')
%       %set(handles.edit_bindescription, 'string','')
%       %indxline = length(fulltext);
%       currline = currline-1;
%       if currline<1
%             currline = 1;
%       end
%
%       set(handles.listbox_color, 'Value', currline);
%       %listbox_Callback(hObject, eventdata, handles)
%
%
%
%
%
%
%
%
%       handles.fulltext = fulltext;
%       %handles.listname = [];
%
%       % Update handles structure
%       guidata(hObject, handles);
% end

% --------------------------------------------------------------------------------------------
function pushbutton_down_color_Callback(hObject, eventdata, handles)
COLORDATA = handles.COLORDATA;
nbin = handles.nbin;
currline = get(handles.listbox_color, 'Value'); % current line

ncolor = length(COLORDATA);
if nnz(~bitand(currline>=1,currline<ncolor))==0
      aux = COLORDATA(currline);
      COLORDATA(currline) = COLORDATA(currline+1);
      COLORDATA(currline+1) = aux;
      setlistbox_color(hObject, handles, COLORDATA, nbin )
      set(handles.listbox_color, 'Value', currline+1); % current line
end

handles.COLORDATA = COLORDATA;
% Update handles structure
guidata(hObject, handles);

% fulltext = get(handles.listbox_color, 'String');
% indxline = length(fulltext);
% fulltext = char(fulltext); % string matrix
% currline = get(handles.listbox_color, 'Value'); % current line
%
% if nnz(~bitand(currline>=1,currline<indxline))==0
%
%       aux = fulltext(currline,:);
%       fulltext(currline,:) = fulltext(currline+1,:);
%       fulltext(currline+1,:) = aux;
%       %fulltext(currline,:) = [];
%       fulltext = cellstr(fulltext); % cell string
%
%       set(handles.listbox_color, 'String', fulltext);
%       %handles.lastlineclicked = {};
%
%       % Update handles structure
%       %guidata(hObject, handles);
%
%       %set(handles.edit_numeric, 'string','')
%       %set(handles.edit_string, 'string','')
%       %set(handles.edit_binindex, 'string','')
%       %set(handles.edit_bindescription, 'string','')
%       indxline = length(fulltext);
%       currline = currline + 1;
%       if currline>indxline
%             currline = indxline;
%       end
%
%       set(handles.listbox_color, 'Value', currline);
%       %listbox_Callback(hObject, eventdata, handles)
%
%       handles.fulltext = fulltext;
%       %handles.listname = [];
%
%       % Update handles structure
%       guidata(hObject, handles);
% end

% --------------------------------------------------------------------------------------------
function pushbutton_default_color_Callback(hObject, eventdata, handles)
nbin      = handles.nbin;
defcolor  = handles.defcolor;
COLORDATA = colores(defcolor);
setlistbox_color(hObject, handles, COLORDATA, nbin )
handles.COLORDATA = COLORDATA;
% Update handles structure
guidata(hObject, handles);

% --------------------------------------------------------------------------------------------
function pushbutton_up_style_Callback(hObject, eventdata, handles)
STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
currline = get(handles.listbox_style, 'Value'); % current line
ncolor = length(STYLEDATA);
if nnz(~bitand(currline>1,currline<=ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = STYLEDATA(currline-1);
      STYLEDATA(currline-1) = aux;
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      set(handles.listbox_style, 'Value', currline-1); % current line
end

handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

% --------------------------------------------------------------------------------------------
function pushbutton_down_style_Callback(hObject, eventdata, handles)
STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
currline = get(handles.listbox_style, 'Value'); % current line

ncolor = length(STYLEDATA);
if nnz(~bitand(currline>=1,currline<ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = STYLEDATA(currline+1);
      STYLEDATA(currline+1) = aux;
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      set(handles.listbox_style, 'Value', currline+1); % current line
end
handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);
% --------------------------------------------------------------------------------------------
function pushbutton_default_style_Callback(hObject, eventdata, handles)
nbin      = handles.nbin;
defstyle  = handles.defstyle;
STYLEDATA = estilos(defstyle);
setlistbox_style(hObject, handles, STYLEDATA, nbin )
handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);
handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_top_color_Callback(hObject, eventdata, handles)
COLORDATA = handles.COLORDATA;
nbin = handles.nbin;
currline = get(handles.listbox_color, 'Value'); % current line
ncolor = length(COLORDATA);
if nnz(~bitand(currline>1,currline<=ncolor))==0
      aux = COLORDATA(currline);
      COLORDATA(currline) = [];
      COLORDATA = [aux COLORDATA];
      setlistbox_color(hObject, handles, COLORDATA, nbin )
      set(handles.listbox_color, 'Value', 1); % current line
end

handles.COLORDATA = COLORDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_top_style_Callback(hObject, eventdata, handles)
STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
currline = get(handles.listbox_style, 'Value'); % current line
ncolor = length(STYLEDATA);
if nnz(~bitand(currline>1,currline<=ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = [];
      STYLEDATA = [aux STYLEDATA];
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      set(handles.listbox_style, 'Value', 1); % current line
end

handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color1_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = 'BLUE';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);
% % %     'empty..:MAGENTA'

%--------------------------------------------------------------------------
function pushbutton_color2_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = '';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color3_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = '';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color4_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = '';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color5_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = '';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color6_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = '';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color7_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)
% % % colorbtn = '';
% % colorbtn = get(hObject, 'UserData');
% % % v = get(handles.listbox_color, 'Value');
% % currline = get(handles.listbox_color, 'Value'); % current line
% % s = get(handles.listbox_color, 'String');
% % w = regexp(s, '\w+$', 'match');
% % w = [w{:}];
% % ind = find(ismember(w, colorbtn), 1, 'last');
% %
% % COLORDATA = handles.COLORDATA;
% % nbin = handles.nbin;
% % % currline = get(handles.listbox_color, 'Value'); % current line
% %
% % ncolor = length(COLORDATA);
% %
% % if nnz(~bitand(currline>=1,currline<=ncolor))==0
% %       aux = COLORDATA(currline);
% %       COLORDATA(currline) = COLORDATA(ind);
% %       COLORDATA(ind) = aux;
% %       setlistbox_color(hObject, handles, COLORDATA, nbin )
% %       %set(handles.listbox_color, 'Value', 1);
% % end
% % handles.COLORDATA = COLORDATA;
% % % Update handles structure
% % guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_color8_Callback(hObject, eventdata, handles)
ReplaceColoratList(hObject, eventdata, handles)

%--------------------------------------------------------------------------
function ReplaceColoratList(hObject, eventdata, handles)
% colorbtn = '';
colorbtn = get(hObject, 'UserData');
% v = get(handles.listbox_color, 'Value');
currline = get(handles.listbox_color, 'Value'); % current line
s = get(handles.listbox_color, 'String');
w = regexp(s, '\w+$', 'match');
w = [w{:}];
ind = find(ismember(w, colorbtn), 1, 'last');

COLORDATA = handles.COLORDATA;
nbin = handles.nbin;
% currline = get(handles.listbox_color, 'Value'); % current line

ncolor = length(COLORDATA);

if nnz(~bitand(currline>=1,currline<=ncolor))==0
      aux = COLORDATA(currline);
      COLORDATA(currline) = COLORDATA(ind);
      COLORDATA(ind) = aux;
      setlistbox_color(hObject, handles, COLORDATA, nbin )
      %set(handles.listbox_color, 'Value', 1);
end
handles.COLORDATA = COLORDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_line1_Callback(hObject, eventdata, handles)
linebtn = get(hObject, 'UserData');
% v = get(handles.listbox_color, 'Value');
currline = get(handles.listbox_style, 'Value'); % current line
s = get(handles.listbox_style, 'String');
% w = regexp(s, '\w+$', 'match');
w = regexp(s, '\w+-*\w*$', 'match');
w = [w{:}];
ind = find(ismember(w, linebtn), 1, 'last');

STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
% currline = get(handles.listbox_style, 'Value'); % current line

ncolor = length(STYLEDATA);

if nnz(~bitand(currline>=1,currline<=ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = STYLEDATA(ind);
      STYLEDATA(ind) = aux;
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      %set(handles.listbox_style, 'Value', 1); % current line
end

handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_line2_Callback(hObject, eventdata, handles)
linebtn = get(hObject, 'UserData');
% v = get(handles.listbox_color, 'Value');
currline = get(handles.listbox_style, 'Value'); % current line
s = get(handles.listbox_style, 'String');
% w = regexp(s, '\w+$', 'match');
w = regexp(s, '\w+-*\w*$', 'match');
w = [w{:}];
ind = find(ismember(w, linebtn), 1, 'last');

STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
% currline = get(handles.listbox_style, 'Value'); % current line

ncolor = length(STYLEDATA);

if nnz(~bitand(currline>=1,currline<=ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = STYLEDATA(ind);
      STYLEDATA(ind) = aux;
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      %set(handles.listbox_style, 'Value', 1); % current line
end

handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_line3_Callback(hObject, eventdata, handles)
linebtn = get(hObject, 'UserData');
% v = get(handles.listbox_color, 'Value');
currline = get(handles.listbox_style, 'Value'); % current line
s = get(handles.listbox_style, 'String');
% w = regexp(s, '\w+$', 'match');
w = regexp(s, '\w+-*\w*$', 'match');
w = [w{:}];
ind = find(ismember(w, linebtn), 1, 'last');

STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
% currline = get(handles.listbox_style, 'Value'); % current line

ncolor = length(STYLEDATA);

if nnz(~bitand(currline>=1,currline<=ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = STYLEDATA(ind);
      STYLEDATA(ind) = aux;
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      %set(handles.listbox_style, 'Value', 1); % current line
end

handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

%--------------------------------------------------------------------------
function pushbutton_line4_Callback(hObject, eventdata, handles)
linebtn = get(hObject, 'UserData');
% v = get(handles.listbox_color, 'Value');
currline = get(handles.listbox_style, 'Value'); % current line
s = get(handles.listbox_style, 'String');
% w = regexp(s, '\w+$', 'match');
w = regexp(s, '\w+-*\w*$', 'match');
w = [w{:}];
ind = find(ismember(w, linebtn), 1, 'last');

STYLEDATA = handles.STYLEDATA;
nbin = handles.nbin;
% currline = get(handles.listbox_style, 'Value'); % current line

ncolor = length(STYLEDATA);

if nnz(~bitand(currline>=1,currline<=ncolor))==0
      aux = STYLEDATA(currline);
      STYLEDATA(currline) = STYLEDATA(ind);
      STYLEDATA(ind) = aux;
      setlistbox_style(hObject, handles, STYLEDATA, nbin )
      %set(handles.listbox_style, 'Value', 1); % current line
end

handles.STYLEDATA = STYLEDATA;
% Update handles structure
guidata(hObject, handles);

% --------------------------------------------------------------------------------------------
function pushbutton_cancel_Callback(hObject, eventdata, handles)
handles.output= [];
% Update handles structure
guidata(hObject, handles);
uiresume(handles.gui_chassis);

% --------------------------------------------------------------------------------------------
function pushbutton_ok_Callback(hObject, eventdata, handles)

%colorlist = get( handles.listbox_color, 'String');
%colorlist = lower(regexprep(colorlist,'','','ignorecase')');
%colorlist = lower(regexprep(colorlist,'.*?','');
%'.*?','');
lwidth    = get(handles.popupmenu_lwidth,'Value');
COLORDATA = handles.COLORDATA;
STYLEDATA = handles.STYLEDATA;
output    = cellstr([char({COLORDATA.colorchar}') char({STYLEDATA(1:length(COLORDATA)).style}')])';
%[xxx indx] = ismember_bc2(colorlist, {COLORDATA.colorname});
%handles.output = {COLORDATA(indx).colorchar};
handles.output = {output lwidth};
% Update handles structure
guidata(hObject, handles);
uiresume(handles.gui_chassis);

% --------------------------------------------------------------------------------------------
function listbox_style_Callback(hObject, eventdata, handles)

% --------------------------------------------------------------------------------------------
function listbox_style_CreateFcn(hObject, eventdata, handles)

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

% --------------------------------------------------------------------------------------------
function popupmenu_lwidth_Callback(hObject, eventdata, handles)

% --------------------------------------------------------------------------------------------
function popupmenu_lwidth_CreateFcn(hObject, eventdata, handles)

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

%--------------------------------------------------------------------------
function gui_chassis_CloseRequestFcn(hObject, eventdata, handles)
if isequal(get(handles.gui_chassis, 'waitstatus'), 'waiting')
      % The GUI is still in UIWAIT, us UIRESUME
      uiresume(handles.gui_chassis);
else
      % The GUI is no longer waiting, just close it
      delete(handles.gui_chassis);
end

author: ucdavis

repo: erplab

save_path: github-repos/MATLAB/ucdavis-erplab


text:
function f_x = ParFor15(in1)
%PARFOR15
%    F_X = PARFOR15(IN1)

%    This function was generated by the Symbolic Math Toolbox version 8.2.
%    20-Sep-2019 09:35:38

u = in1(:,1);
ux = in1(:,4);
uxxx = in1(:,6);
f_x = ((ux.*-2.895413584232186e19+uxxx.*2.08074189217307e18+u.*ux.*2.276967144755718e19).*-1.483125065871422e-16)./u;

author: dynamicslab

repo: SINDy-PI


text:
% KUKA sunrise toolbox example.
% moving end-effector of the robot on a circle.

% Copy right: Mohammad SAFEEA
% 16th-Oct-2017

clear all;
close all;
clc;

% Initial configuration
jPos={pi / 180 * 30, pi / 180 * 30, 0, -pi / 180 * 60, 0,...
                        pi / 180 * 90, 0};
% Start the KST, move robot to initial configuration, start directServo function
% [tKuka,flag]=startDaDirectServo(jPos );
%
% if flag==false
%     fprintf('Can not connect to KST \n');
%     fprintf('Program terminated \n');
%     return;
% end

% calculate current position of flange point of the robot
qs=zeros(7,1);
for i=1:7
    qs(i)=jPos{i};
end
        TefTool=eye(4);
        T0=directKinematics(qs,TefTool); % EEF frame transformation matrix
        p0=T0(1:3,4);
        Tt=T0;

% parameters of the circle:
r=0.15; % radius of the circle

% Joint space control

figure ();
    [Ttemp,J]=directKinematics(qs,TefTool);
    vec=Ttemp(1:3,4);
    plot3(vec(1,:),vec(2,:),vec(3,:));

pause(0.1);

        a=datevec(now);
        time0=a(6)+a(5)*60+a(4)*60*60; % calculate time at this instant

        deltaT0=2;

        theangleVec=[];
        timeVec=[];
% dls solver parameters
        n=10;
        lambda=0.1;
        TefTool=eye(4);

while true

    % Calculate the elapsed time
        a=datevec(now);
        timeNow=a(6)+a(5)*60+a(4)*60*60; % calculate time at this instant
        deltaT=timeNow-time0; % elapsed is zero at first excution

    % calculate position of servo point
    if deltaT<deltaT0
        accel=0.4;
        w=accel*deltaT;
        theta=0.5*accel*deltaT*deltaT;
    else
        accel=0.4;
        theta0=0.5*accel*deltaT0*deltaT0;
        theta=w*(deltaT-deltaT0)+theta0;
    end

    if theta>2.5*pi
        break;
    end

    x=p0(1)+r*(cos(theta)-1);
    y=p0(2)+r*sin(theta);
    z=p0(3);
    p=[x;y;z];
    % calculate target transform
    Tt(1:3,4)=p;

    [ qs ] = kukaDLSSolver( qs, Tt, TefTool,n,lambda );

    [Ttemp,J]=directKinematics(qs,TefTool);
    vec=[vec,Ttemp(1:3,4)];
    plot3(vec(1,:),vec(2,:),vec(3,:))
    axis equal;
    pause(0.001);
    theangleVec=[theangleVec,theta];
    timeVec=[timeVec,deltaT];
end
figure;
plot(timeVec,theangleVec())
% close(figureHandle);
    % turn off the server
%     net_turnOffServer( tKuka );
%     fclose(tKuka);

repo: KST-Kuka-Sunrise-Toolbox


text:
%TSPOF_GA Fixed Open Traveling Salesman Problem (TSP) Genetic Algorithm (GA)
%   Finds a (near) optimal solution to a variation of the TSP by setting up
%   a GA to search for the shortest route (least distance for the salesman
%   to travel from a FIXED START to a FIXED END while visiting the other
%   cities exactly once)
%
% Summary:
%     1. A single salesman starts at the first point, ends at the last
%        point, and travels to each of the remaining cities in between, but
%        does not close the loop by returning to the city he started from
%     2. Each city is visited by the salesman exactly once
%
% Note: The Fixed Start is taken to be the first XY point, and the Fixed
%   End is taken to be the last XY point
%
% Input:
%     XY (float) is an Nx2 matrix of city locations, where N is the number of cities
%     DMAT (float) is an NxN matrix of point to point distances/costs
%     POPSIZE (scalar integer) is the size of the population (should be divisible by 4)
%     NUMITER (scalar integer) is the number of desired iterations for the algorithm to run
%     SHOWPROG (scalar logical) shows the GA progress if true
%     SHOWRESULT (scalar logical) shows the GA results if true
%
% Output:
%     OPTROUTE (integer array) is the best route found by the algorithm
%     MINDIST (scalar float) is the cost of the best route
%
% Example:
%     n = 50;
%     xy = 10*rand(n,2);
%     popSize = 60;
%     numIter = 1e4;
%     showProg = 1;
%     showResult = 1;
%     a = meshgrid(1:n);
%     dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),n,n);
%     [optRoute,minDist] = tspof_ga(xy,dmat,popSize,numIter,showProg,showResult);
%
% Example:
%     n = 50;
%     phi = (sqrt(5)-1)/2;
%     theta = 2*pi*phi*(0:n-1);
%     rho = (1:n).^phi;
%     [x,y] = pol2cart(theta(:),rho(:));
%     xy = 10*([x y]-min([x;y]))/(max([x;y])-min([x;y]));
%     popSize = 60;
%     numIter = 1e4;
%     showProg = 1;
%     showResult = 1;
%     a = meshgrid(1:n);
%     dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),n,n);
%     [optRoute,minDist] = tspof_ga(xy,dmat,popSize,numIter,showProg,showResult);
%
% Example:
%     n = 50;
%     xyz = 10*rand(n,3);
%     popSize = 60;
%     numIter = 1e4;
%     showProg = 1;
%     showResult = 1;
%     a = meshgrid(1:n);
%     dmat = reshape(sqrt(sum((xyz(a,:)-xyz(a',:)).^2,2)),n,n);
%     [optRoute,minDist] = tspof_ga(xyz,dmat,popSize,numIter,showProg,showResult);
%
% See also: tsp_ga, tsp_nn, tspo_ga, tspofs_ga, distmat
%
% Author: Joseph Kirk
% Email: jdkirk630@gmail.com
% Release: 1.3
% Release Date: 11/07/11
function varargout = tspof_ga(xy,dmat,popSize,numIter,showProg,showResult)

% Process Inputs and Initialize Defaults
nargs = 6;
for k = nargin:nargs-1
    switch k
        case 0
            xy = 10*rand(50,2);
        case 1
            N = size(xy,1);
            a = meshgrid(1:N);
            dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),N,N);
        case 2
            popSize = 100;
        case 3
            numIter = 1e4;
        case 4
            showProg = 1;
        case 5
            showResult = 1;
        otherwise
    end
end

% Verify Inputs
[N,dims] = size(xy);
[nr,nc] = size(dmat);
if N ~= nr || N ~= nc
    error('Invalid XY or DMAT inputs!')
end
n = N - 2; % Separate Start and End Cities

% Sanity Checks
popSize = 4*ceil(popSize/4);
numIter = max(1,round(real(numIter(1))));
showProg = logical(showProg(1));
showResult = logical(showResult(1));

% Initialize the Population
pop = zeros(popSize,n);
pop(1,:) = (1:n) + 1;
for k = 2:popSize
    pop(k,:) = randperm(n) + 1;
end

% Run the GA
globalMin = Inf;
totalDist = zeros(1,popSize);
distHistory = zeros(1,numIter);
tmpPop = zeros(4,n);
newPop = zeros(popSize,n);
if showProg
    pfig = figure('Name','TSPOF_GA | Current Best Solution','Numbertitle','off');
end
for iter = 1:numIter
    % Evaluate Each Population Member (Calculate Total Distance)
    for p = 1:popSize
        d = dmat(1,pop(p,1)); % Add Start Distance
        for k = 2:n
            d = d + dmat(pop(p,k-1),pop(p,k));
        end
        d = d + dmat(pop(p,n),N); % Add End Distance
        totalDist(p) = d;
    end

    % Find the Best Route in the Population
    [minDist,index] = min(totalDist);
    distHistory(iter) = minDist;
    if minDist < globalMin
        globalMin = minDist;
        optRoute = pop(index,:);
        if showProg
            % Plot the Best Route
            figure(pfig);
            rte = [1 optRoute N];
            if dims > 2
                plot3(xy(rte,1),xy(rte,2),xy(rte,3),'r.-',...
                    xy([1 N],1),xy([1 N],2),xy([1 N],3),'ro');
            else
                plot(xy(rte,1),xy(rte,2),'r.-',xy([1 N],1),xy([1 N],2),'ro');
            end
            title(sprintf('Total Distance = %1.4f, Iteration = %d',minDist,iter));
        end
    end

    % Genetic Algorithm Operators
    randomOrder = randperm(popSize);
    for p = 4:4:popSize
        rtes = pop(randomOrder(p-3:p),:);
        dists = totalDist(randomOrder(p-3:p));
        [ignore,idx] = min(dists); %#ok
        bestOf4Route = rtes(idx,:);
        routeInsertionPoints = sort(ceil(n*rand(1,2)));
        I = routeInsertionPoints(1);
        J = routeInsertionPoints(2);
        for k = 1:4 % Mutate the Best to get Three New Routes
            tmpPop(k,:) = bestOf4Route;
            switch k
                case 2 % Flip
                    tmpPop(k,I:J) = tmpPop(k,J:-1:I);
                case 3 % Swap
                    tmpPop(k,[I J]) = tmpPop(k,[J I]);
                case 4 % Slide
                    tmpPop(k,I:J) = tmpPop(k,[I+1:J I]);
                otherwise % Do Nothing
            end
        end
        newPop(p-3:p,:) = tmpPop;
    end
    pop = newPop;
end

if showResult
    % Plots the GA Results
    figure('Name','TSPOF_GA | Results','Numbertitle','off');
    subplot(2,2,1);
    pclr = ~get(0,'DefaultAxesColor');
    if dims > 2, plot3(xy(:,1),xy(:,2),xy(:,3),'.','Color',pclr);
    else plot(xy(:,1),xy(:,2),'.','Color',pclr); end
    title('City Locations');
    subplot(2,2,2);
    imagesc(dmat([1 optRoute N],[1 optRoute N]));
    title('Distance Matrix');
    subplot(2,2,3);
    rte = [1 optRoute N];
    if dims > 2
        plot3(xy(rte,1),xy(rte,2),xy(rte,3),'r.-',...
            xy([1 N],1),xy([1 N],2),xy([1 N],3),'ro');
    else
        plot(xy(rte,1),xy(rte,2),'r.-',xy([1 N],1),xy([1 N],2),'ro');
    end
    title(sprintf('Total Distance = %1.4f',minDist));
    subplot(2,2,4);
    plot(distHistory,'b','LineWidth',2);
    title('Best Solution History');
    set(gca,'XLim',[0 numIter+1],'YLim',[0 1.1*max([1 distHistory])]);
end

% Return Outputs
if nargout
    varargout{1} = optRoute;
    varargout{2} = minDist;
end

author: Sable

repo: mcbench-benchmarks


text:
function [V, Q, policy] = mdp_bellman_operator_with_Q(P, PR, discount, Vprev)

% mdp_bellman_operator Applies the Bellman operator on the value function Vprev
%                      Returns a new value function and a Vprev-improving policy
% Arguments ---------------------------------------------------------------
% Let S = number of states, A = number of actions
%   P(SxSxA) = transition matrix
%              P could be an array with 3 dimensions or
%              a cell array (1xA), each cell containing a matrix (SxS) possibly sparse
%   PR(SxA) = reward matrix
%              PR could be an array with 2 dimensions or
%              a sparse matrix
%   discount = discount rate, in ]0, 1]
%   Vprev(S) = value function
% Evaluation --------------------------------------------------------------
%   V(S)   = new value function
%   policy(S) = Vprev-improving policy

% MDPtoolbox: Markov Decision Processes Toolbox
% Copyright (C) 2009  INRA
% Redistribution and use in source and binary forms, with or without modification,
% are permitted provided that the following conditions are met:
%    * Redistributions of source code must retain the above copyright notice,
%      this list of conditions and the following disclaimer.
%    * Redistributions in binary form must reproduce the above copyright notice,
%      this list of conditions and the following disclaimer in the documentation
%      and/or other materials provided with the distribution.
%    * Neither the name of the <ORGANIZATION> nor the names of its contributors
%      may be used to endorse or promote products derived from this software
%      without specific prior written permission.
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
% IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
% INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
% LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
% OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
% OF THE POSSIBILITY OF SUCH DAMAGE.

if iscell(P); S = size(P{1},1); else S = size(P,1); end;
if discount <= 0 || discount > 1
     disp('--------------------------------------------------------')
     disp('MDP Toolbox ERROR: Discount rate must be in ]0; 1]')
     disp('--------------------------------------------------------')
elseif size(Vprev,1) ~= S
    disp('--------------------------------------------------------')
    disp('MDP Toolbox ERROR: Vprev must have the same dimension as P')
    disp('--------------------------------------------------------')
else

    if iscell(P)
        A = length(P);
        for a=1:A
            Q(:,a) = PR(:,a) + discount*P{a}*Vprev;
        end
    else
        A = size(PR,2);
        for a=1:A
            Q(:,a) = PR(:,a) + discount*P(:,:,a)*Vprev;
        end
    end
    [V, policy] = max(Q,[],2);

end;

author: matthieukomorowski


text:
% Load data taken from Structure IO
function data = loadStructureIOdata(directory, frameIDs)

% Get image file list
imageFiles  = dir(fullfile(directory, 'color', '*.jpg'));
depthFiles = dir(fullfile(directory, 'depth', '*.png'));

% Set default frames to go through
if length(frameIDs) == 0
    frameIDs = 1:length(imageFiles);
end

% Loop through all image files to get corresponding image and depth names
count = 0;
data.depthTimestamp = zeros(1,length(depthFiles));
data.imageTimestamp = zeros(1,length(imageFiles));
for frameID = frameIDs
    count = count + 1;
    timestr = regexp(imageFiles(frameID).name,'\d+T\d+\.\d+\.\d+\.\d+-','match');
    timeArr = sscanf(timestr{1}, '%dT%d.%d.%d.%d-');
    data.imageTimestamp(frameID) = timeArr(1)*24*3600000 + timeArr(2)*3600000+timeArr(3)*60000+timeArr(4)*1000+timeArr(5);

    timestr = regexp(depthFiles(frameID).name,'\d+T\d+\.\d+\.\d+\.\d+-','match');
    timeArr = sscanf(timestr{1}, '%dT%d.%d.%d.%d-');
    data.depthTimestamp(frameID) = timeArr(1)*24*3600000 + timeArr(2)*3600000+timeArr(3)*60000+timeArr(4)*1000+timeArr(5);

    data.imageAll{count} = fullfile(fullfile(directory, 'color', imageFiles(frameID).name));
    data.depthAll{count} = fullfile(fullfile(directory, 'depth', depthFiles(frameID).name));
end

% Grab camera data
data.K = reshape(readValuesFromTxt(fullfile(directory, 'intrinsics.txt')), 3, 3)';
if exist(fullfile(directory, 'intrinsics_d2c.txt'),'file')
   depthCam = readValuesFromTxt(fullfile(directory, 'intrinsics_d2c.txt'));
   data.Kdepth = reshape(depthCam(1:9), 3, 3)';
   data.RT_d2c = reshape(depthCam(10:21), 4, 3)';
else
   data.image = data.imageAll;
   data.depth = data.depthAll;

end

author: jianxiongxiao

repo: ProfXkit


text:
function roomhyp = sample_roomtype7(n, lines, vp, imgwidth, imgheight)
% sample n room hyps
% 3 ways to create hypothesis
% recipe1: 1,right 2,top, junc2type,2
% recipe2: 1,right 3,top,right, junc2type,1
% recipe3: 2,top 3,top,right, junc2type,4

lc = [lines.lineclass]; % 0,1,2,3
lr = [lines.leftorright]; % 1 if right, -1 if left, 0 if neither
tb = [lines.above_horizon]; % 1 if above, -1 if below, 0 if neither

oneright = find((lc==1) & (lr==1));
twotop = find((lc==2) & (tb==1));
threetopright = find((lc==3) & (tb==1) & (lr==1));

linecode{1} = oneright;
linecode{2} = twotop;
linecode{3} = threetopright;

% recipe: [linecode1 linecode2 junc2type]
recipe(1,:) = [1 2 2];
recipe(2,:) = [1 3 1];
recipe(3,:) = [2 3 4];

%
% for i = 1:length(linecode),
%     num_linecode(i) = length(linecode{i});
% end
if (length(linecode{1})<1 || length(linecode{2})<1) && ...
   (length(linecode{1})<1 || length(linecode{3})<1) && ...
   (length(linecode{2})<1 || length(linecode{3})<1)
    roomhyp = [];
    return; % fail
end

count = 0;
num_continue_without_progress = 0;
while count < n && num_continue_without_progress < 30
    use_recipe_num = randsample(size(recipe,1), 1); % 1, 2, or 3
    cur_recipe = recipe(use_recipe_num,:);

    l1 = linecode{cur_recipe(1)};
    l2 = linecode{cur_recipe(2)};
    if length(l1)<1 || length(l2)<1
        num_continue_without_progress = num_continue_without_progress + 1;
        continue;
    end

    ls1 = l1(randsample(length(l1),1));
    ls2 = l2(randsample(length(l2),1));
    [cornerpt degen] = line_intersect(...
                        lines(ls1).point1, lines(ls1).point2, ...
                        lines(ls2).point1, lines(ls2).point2);
    if degen==1
        num_continue_without_progress = num_continue_without_progress + 1;
        continue;
    end
    type = getjunctype(cornerpt, lines(ls1), lines(ls2));
    if type ~= cur_recipe(3)
        num_continue_without_progress = num_continue_without_progress + 1;
        continue;
    end

    % check if inside img
    MARGIN = 5;
    if ~is_in_image(cornerpt, imgwidth, imgheight, MARGIN)
        num_continue_without_progress = num_continue_without_progress + 1;
        continue;
    end

    % found a valid way to generate a room hyp
    count = count+1;
    num_continue_without_progress = 0;
    roomhyp(count).corner(4).pt = []; % up to 4 corners
    roomhyp(count).corner(2).pt = cornerpt;
    roomhyp(count).type = 7;

%     global img;
%     disp_vanish(img, lines([ls1 ls2]), vp);
%     plot(cornerpt(1), cornerpt(2), 'x');
%     pause;
%     close;
end

if ~exist('roomhyp','var')
    roomhyp = [];
end

author: zouchuhang

repo: LayoutNet


text:
function savejmesh(node,face,elem,fname,varargin)
%
% savejmesh(node,face,elem,fname,opt)
%
% export a mesh to the JMesh format defined in http://github.com/fangq/jmesh
%
% author: Qianqian Fang, <q.fang at neu.edu>
% date: 2011/10/06
%
% input:
%      node: node list, dimension (nn,3)
%      face: can be empty, surface face element list, dimension (be,3)
%      elem: can be empty, tetrahedral element list, dimension (ne,4)
%      fname: output file name; if file name has a suffix .bmsh,
%           the mesh data will be saved in the binary jmesh format; otherwise,
%           the file will be saved as a text-based jmesh (which is a plain
%           JSON file)
%      opt: additional parameters in the form of 'parameter',value pairs
%           valid parameters include:
%           'Dimension': 2 - a 2D mesh, 3 - a 3D mesh
%           'Author': a string to set the author of the mesh
%           'MeshTitle': a string to set the title of the mesh
%           'MeshTag': a value as the tag of the mesh data
%           'Comment': a string as the additional note for the mesh data
%           'MeshTag': a value as the tag of the mesh data
%           'Flexible': 0 (default)- use dimension-specific data containers
%                 (MeshVertex3, MeshTet4 ...). 1 - use flexible mesh data
%                 containers (MeshNode, MeshSurf, MeshElem)
%           'Header': 1 - include _DataInfo_ header, 0 - do not include
%
%           please type 'help savejson' and 'help savebj' to see additional
%           supported options
%
% examples:
%
%    [no,fc,el]=meshabox([0 0 0],[60,30,40],3,10);
%    savejmesh(no,fc,[],'box_surf.jmsh','dimension',3);
%    savejmesh(no,fc,el,'box_zlib.jmsh','compression','zlib');
%    savejmesh(no,fc,el,'box.bmsh','dimension',3);
%    savejmesh(no,fc,el,'box_zlib.bmsh','dimension',3,'compression','zlib');
%    savejmesh(no,[],el,'box_elem.jmsh','flexible',1) %sue MeshNode/MeshSurf/MeshElem
%    mesh=loadbj('box.bmsh')
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

if(nargin==2)
   fname=face;
   face=[];
   elem=[];
end

if(nargin==3)
   fname=elem;
   elem=[];
end

if(length(varargin)==1 && ischar(varargin{1}))
   opt=struct('FileName',varargin{1});
else
   opt=varargin2struct(varargin{:});
end

meshdim=jsonopt('Dimension',size(node,2),opt);

if(jsonopt('Header',1,opt)==1) % use metadata header
    mesh.(encodevarname('_DataInfo_'))=struct();

    metadata.JMeshVersion=0.5;
    metadata.Dimension=meshdim;
    metadata.CreationTime=datestr(now);
    metadata.Comment=['Created by Iso2Mesh ' iso2meshver '(http://iso2mesh.sf.net)'];
    metadata.AnnotationFormat='https://github.com/NeuroJSON/jmesh/blob/master/JMesh_specification.md';
    metadata.SerialFormat='http://json.org';
    metadata.Parser=struct('Python',[], ...
                           'MATLAB','https://github.com/NeuroJSON/jsonlab', ...
                           'JavaScript',[],...
                           'CPP', 'https://github.com/NeuroJSON/json',...
                           'C', []);
    metadata.Parser.Python={'https://pypi.org/project/jdata','https://pypi.org/project/bjdata'};
    metadata.Parser.JavaScript={'https://github.com/NeuroJSON/jsdata','https://github.com/NeuroJSON/js-bjdata'};
    metadata.Parser.C={'https://github.com/DaveGamble/cJSON','https://github.com/NeuroJSON/ubj'};
end

if(jsonopt('Flexible',0,opt)==1) % a user-defined mesh
    mesh.MeshNode=node;
    if(~isempty(face))
        mesh.MeshSurf=face;
    end
    if(~isempty(elem))
        mesh.MeshElem=elem;
    end
elseif(meshdim==3) % a 3D mesh
    nd=size(node);
    if(nd(2)<3)
        error('expecting 3 or more columns in node');
    end
    mesh.MeshVertex3=node(:,1:3);
    if(nd(2)>3)
        mesh.MeshVertex3=struct('Data',mesh.MeshVertex3,'Properties',struct('Value',node(:,4:end)));
    end
    if(~isempty(face))
        nd=size(face);
        if(nd(2)<3)
            error('expecting 3 or more columns in face');
        end
        mesh.MeshTri3=face(:,1:3);
        if(nd(2)>3)
            mesh.MeshTri3=struct('Data',mesh.MeshTri3,'Properties',struct('Value',face(:,4:end)));
        end
    end
    if(~isempty(elem))
        nd=size(elem);
        if(nd(2)<4)
            error('expecting 4 or more columns in elem');
        end
        mesh.MeshTet4=elem(:,1:4);
        if(nd(2)>4)
            mesh.MeshTet4=struct('Data',mesh.MeshTet4,'Properties',struct('Value',elem(:,5:end)));
        end
    end
elseif(meshdim==2) % a 2D mesh
    nd=size(node);
    if(nd(2)<2)
        error('expecting 2 or more columns in node');
    end
    mesh.MeshVertex2=node(:,1:2);
    if(nd(2)>2)
        mesh.MeshVertex2=struct('Data',mesh.MeshVertex2,'Properties',struct('Value',node(:,3:end)));
    end
    if(~isempty(face))
        nd=size(face);
        if(nd(2)<3)
            error('expecting 3 or more columns in face');
        end
        mesh.MeshTri3=face(:,1:3);
        if(nd(2)>3)
            mesh.MeshTri3=struct('Data',mesh.MeshTri3,'Properties',struct('Value',face(:,4:end)));
        end
    end
    if(~isempty(elem))
        warning('elem is redundant in a 2D mesh, skip');
    end
else
    error('the specified Dimension is not supported, please remove to save data to a general format');
end

author=jsonopt('Author','',opt);
if(~isempty(author))
    metadata.Author=author;
end

title=jsonopt('MeshTitle','',opt);
if(~isempty(title))
    metadata.MeshTitle=title;
end

tag=jsonopt('MeshTag',[],opt);
if(~isempty(tag))
    metadata.MeshTag=tag;
end

comm=jsonopt('Comment','',opt);
if(~isempty(comm))
    metadata.Comment=comm;
end

if(exist('metadata','var')) % use metadata
    mesh.(encodevarname('_DataInfo_'))=metadata;
end

if(~isempty(regexp(fname,'\.bmsh$', 'once')) || ~isempty(regexp(fname,'\.bmesh$', 'once')))
   savebj('',mesh,'FileName',fname,varargin{:});
else
   savejson('',mesh,'FileName',fname,varargin{:});
end

author: fangq


text:
function compute_rotation_classes(expidx, image_set)

fprintf('rcnn_compute_rotation_classes()\n');

p = exp_params(expidx);

pidxs = p.pidxs;

[~,parts] = util_get_parts24();

num_joints = length(pidxs);

spatidxs = {[22 17],[22 16],[22 23],[22 4],[22 5],[16 14],[17 19],[4 2],[5 7],[2 0],[7 9],[14 12],[19 21]};
% convert spatidxs to 0-14 format
n = 1;
for pidx = pidxs
    for i = 1:length(spatidxs)
        if spatidxs{i}(1) == pidx
            spatidxs{i}(1) = n;
        end
        if spatidxs{i}(2) == pidx
            spatidxs{i}(2) = n;
        end
    end
    n = n + 1;
end
% build incidence map
% adjacent joints
adjc = cell(num_joints, 1);
for n = 1:length(spatidxs)
    edge = spatidxs{n};
    v1 = edge(1);
    v2 = edge(2);
    adjc{v1} = unique([adjc{v1} v2]);
    adjc{v2} = unique([adjc{v2} v1]);
end

GT = p.([image_set 'GT']);
load(GT, 'annolist');

if isfield(p, 'idpr_cache_dir')
    clusters_cache_dir = p.idpr_cache_dir;
else
    clusters_cache_dir = [p.expDir '/' p.shortName '/data'];
end

try
    load([clusters_cache_dir '/clusters'],'clusters');
catch
    % compute clusters
    vecs = cell(num_joints, 1);
    for i = 1:num_joints
        vecs{i} = zeros(length(annolist), length(adjc{i})*2+1);
    end

    sz = zeros(num_joints, 1);

    for imgidx = 1:length(annolist)
    %    if imgidx == 12220 % outlier
    %        continue;
    %    end

        fprintf('.');

        assert(length(annolist(imgidx).annorect) == 1);
        %for ridx = 1:length(annolist(imgidx).annorect)
        ridx = 1;

        rect = annolist(imgidx).annorect(ridx);
        joints = get_joints(rect, pidxs, parts);

        for idx = 1:num_joints
            [vec, no_points] = compute_pairwise_vec(joints, adjc, idx);
            if ~no_points
                sz(idx) = sz(idx) + 1;
                vecs{idx}(sz(idx), :) = [vec', imgidx];
            end
        end

        %img = imread(annolist(imgidx).image.name);
        %vis_pred(img, joints(:,:));
        %pause;
        if (~mod(imgidx, 100))
            fprintf(' %d/%d\n',imgidx,length(annolist));
        end
    end

    clusters = cell(num_joints, 1);
    for idx = 1:num_joints
        vecs{idx} = vecs{idx}(1:sz, :);
    end

    for idx = 1:num_joints
        num_clasters = p.idpr_num_clusters(idx);
        clusters{idx} = cluster_rotation_classes(vecs{idx}(:,1:end-1), num_clasters, false);
    end

    mkdir_if_missing(clusters_cache_dir);
    save([clusters_cache_dir '/clusters'], 'clusters', 'vecs', '-v7.3');
end

pairwise_classes = cell(length(annolist), 1);
skip_class = sum(p.idpr_num_clusters) + 1;

% now compute pairwise class for all images
for imgidx = 1:length(annolist)
    fprintf('.');

    ridx = 1;

    rect = annolist(imgidx).annorect(ridx);
    joints = get_joints(rect, pidxs, parts);

    pairwise_class = ones(num_joints, 3) * 1e6;
    for idx = 1:num_joints
        [vec, no_points] = compute_pairwise_vec(joints, adjc, idx);
        pj = joints(idx, :);
        pairwise_class(idx, 1:2) = pj;
        if ~no_points
            diff = bsxfun(@minus, clusters{idx}, vec');
            [~, min_dist] = min(sum(diff.^2, 2));
            pairwise_class(idx, 3) = compute_idpr_class(idx, min_dist, p.idpr_num_clusters);
        elseif ~isnan(pj(1))
            pairwise_class(idx, 3) = skip_class;
        end
    end
    pairwise_classes{imgidx} = pairwise_class;

    if (~mod(imgidx, 100))
        fprintf(' %d/%d\n',imgidx,length(annolist));
    end
end

cache_dir = [p.expDir '/' p.shortName '/data'];
mkdir_if_missing(cache_dir);
save([cache_dir '/pairwise_classes'],'pairwise_classes', '-v7.3');

function [vec, no_points] = compute_pairwise_vec(joints, adjc, idx)
    pj = joints(idx, :);
    no_points = isnan(pj(1));
    vec = zeros(length(adjc{idx})*2, 1);
    n = 0;
    for adj = adjc{idx}
        pa = joints(adj, :);
        vec(n*2+1:n*2+2) = pa - pj;
        no_points = no_points | isnan(pa(1)) | (abs(vec(1)) > 300) | (abs(vec(2)) > 300);
        n = n + 1;
    end

function joints = get_joints(rect, pidxs, parts)
    points = rect.annopoints.point;
    joints = NaN(14, 2);
    n = 1;
    for pidx = pidxs
        annopoint_idxs = parts(pidx+1).pos;
        assert(annopoint_idxs(1) == annopoint_idxs(2));
        pt = util_get_annopoint_by_id(points, annopoint_idxs(1));
        if (~isempty(pt))
            joints(n, :) = [pt.x pt.y];
        end
        n = n + 1;
    end

function res = compute_idpr_class(joint_no, joint_class, num_clusters)
res = sum(num_clusters(1:joint_no-1))+joint_class;

author: eldar

repo: deepcut

save_path: github-repos/MATLAB/eldar-deepcut


text:
function img_data=load_img_from_ds_info(img_data_info, img_idx)

assert(~isempty(img_idx));

img_file=img_data_info.img_files{img_idx};
one_data_dir_idx=img_data_info.data_dir_idxes_img(img_idx);
one_data_dir=img_data_info.data_dirs{one_data_dir_idx};

full_img_file=fullfile(one_data_dir, img_file);
img_data=read_img_rgb(full_img_file, 'uint8');

end

author: guosheng

repo: refinenet

save_path: github-repos/MATLAB/guosheng-refinenet


text:
function varargout = velocity(C,varargin)
% computes the elastic wave velocity(km/s) from
% the elastic stiffness Cijkl tensor and density (g/cm3)
%
% Input
%  C   - elasticity @stiffnessTensor Cijkl (UNITS GPa) @tensor
%  x   - list of propagation directions (@vector3d)
%  rho - material density (UNITS g/cm3)
%
% Output
%  vp  - velocity of the p--wave (UNITS km/s)
%  vs1 - velocity of the s1--wave (UNITS km/s)
%  vs2 - velocity of the s2--wave (UNITS km/s)
%  pp  - polarisation of the p--wave (particle movement, vibration direction)
%  ps1 - polarisation of the s1--wave (particle movement, vibration direction)
%  ps2 - polarisation of the s2--wave (particle movement, vibration direction)
%

% take formula using complience
[varargout{1:nargout}] = velocity(inv(C),varargin{:});

author: mtex-toolbox

repo: mtex

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


text:
function test_bug1708

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY test_bug1708 ft_denoise_synthetic

% reported bug is that ft_denoise_synthetic leads to nans in coilpos and
% coilori

% try to reproduce first
load(dccnpath('/home/common/matlab/fieldtrip/data/test/latest/raw/meg/preproc_ctf275.mat'));

cfg  = [];
cfg.gradient = 'none';
data = ft_denoise_synthetic(cfg, data);

cfg = [];
cfg.gradient = 'G3BR';
data = ft_denoise_synthetic(cfg, data);

assert(all(isfinite(data.grad.coilori(:))));
assert(all(isfinite(data.grad.coilpos(:))));
assert(all(isfinite(data.grad.chanori(:))));
assert(all(isfinite(data.grad.chanpos(:))));

%%%% SOMEHOW the test data got lost along the way, therefore it seems
%%%% wisest to just uncomment the next section.
% load('test_bug1708.mat');
%
% avgData2 = ft_denoise_synthetic(cfg, avgData); % this confirmed the bug
%
% % however avgData had G1BR balancing, could it be caused by the fact that
% % this balancing is not undone?
%
% cfg = [];
% cfg.gradient = 'none';
% avgData3 = ft_denoise_synthetic(cfg, avgData);
% cfg.gradient = 'G3BR';
% avgData4 = ft_denoise_synthetic(cfg, avgData3);
%
% % this indeed seems to be the case


text:
function [gamma]=wildual(g,M,L)
%WILDUAL  Wilson dual window
%   Usage:  gamma=wildual(g,M);
%           gamma=wildual(g,M,L);
%
%   Input parameters:
%         g     : Gabor window.
%         M     : Number of modulations.
%         L     : Length of window. (optional)
%   Output parameters:
%         gamma : Canonical dual window.
%
%   `wildual(g,M)` returns the dual window of the Wilson or WMDCT basis with
%   window *g*, parameter *M* and length equal to the length of the window *g*.
%
%   The window *g* may be a vector of numerical values, a text string or a
%   cell array. See the help of |wilwin| for more details.
%
%   If the length of *g* is equal to $2\cdot M$ then the input window is
%   assumed to be an FIR window. In this case, the dual window also has
%   length of $2\cdot M$. Otherwise the smallest possible transform length is
%   chosen as the window length.
%
%   `wildual(g,M,L)` does the same, but now *L* is used as the length of the
%   Wilson basis.
%
%   The input window *g* must be real and whole-point even. If *g* is not
%   whole-point even, then reconstruction using the dual window will not be
%   perfect. For a random window *g*, the window closest to *g* that satisfies
%   these restrictions can be found by ::
%
%     g_wpe = real(peven(g));
%
%   All windows in the toolbox satisfies these restrictions unless
%   clearly stated otherwise.
%
%   See also:  dwilt, wilwin, wmdct, wilorth, isevenfunction

%   AUTHOR : Peter L. Søndergaard.
%   TESTING: TEST_DWILT
%   REFERENCE: OK

complainif_argnonotinrange(nargin,2,3,mfilename);

if nargin==2
    L=[];
end;

%% ------ step 2: Verify a, M and L
if isempty(L)
    if isnumeric(g)
        % Use the window length
        Ls=length(g);
    else
        % Use the smallest possible length
        Ls=1;
    end;

    % ----- step 2b : Verify M and get L from the window length ----------
    L=dwiltlength(Ls,M);

else

    % ----- step 2a : Verify M and get L

    Luser=dwiltlength(L,M);
    if Luser~=L
        error(['%s: Incorrect transform length L=%i specified. Next valid length ' ...
               'is L=%i. See the help of DWILTLENGTH for the requirements.'],...
              upper(mfilename),L,Luser);
    end;

end;

%% ----- step 3 : Determine the window

[g,info]=wilwin(g,M,L,upper(mfilename));

if L<info.gl
  error('%s: Window is too long.',upper(mfilename));
end;

%% ----- call gabdual ----------------
a=M;

g=fir2long(g,L);
gamma=2*comp_gabdual_long(g,a,2*M);

author: ltfat

repo: ltfat

save_path: github-repos/MATLAB/ltfat-ltfat


text:
function [nyear,ncoef]=decode_coeff_pointer(np);
%USAGE:  [nyear,ncoef]=decode_coeff_pointer(np);
%
% Decode igrf10syn gh pointer to extract year number and ncoef
% 1<=ncoef<=120 for nyear=1:19
% 1<=ncoef<=195 for nyear=20:24
%
% np=(nyear-1)*120+ncoef for np<=np1_max
% np=np1_max+(nyear-19)*195+ncoef; for nyear=20:24
%
% year=1995+(nyear-1)*5;
%
np1_max=2280;
if np<=np1_max
    nyear=floor(np/120)+1;
    ncoef=np-(nyear-1)*120;
    if ncoef==0
        ncoef=120;
        nyear=nyear+1;
    end
elseif np<=3255
   np2=np-np1_max;
   nyear=floor(np2/195)+1;
   ncoef=np2-(nyear-1)*195;
   if ncoef==0
       ncoef=195;
       nyear=nyear+1;
   end
   nyear=19+nyear;
else
    error('np>3255!')
end
return


text:
function varargout = cfg_get_defaults(defstr, varargin)

% function varargout = cfg_get_defaults(defspec, varargin)
% Get/set defaults for various properties of matlabbatch utilities.
% The values can be modified permanently by editing the file
% private/cfg_mlbatch_defaults.m
% or for the current MATLAB session by calling
% cfg_get_defaults(defspec, defval).
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: cfg_get_defaults.m 1862 2008-06-30 14:12:49Z volkmar $

rev = '$Rev: 1862 $'; %#ok

persistent local_def;
if isempty(local_def)
   local_def = cfg_mlbatch_defaults;
end;

% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');

if nargin == 1
    try
        varargout{1} = subsref(local_def, subs);
    catch
        varargout{1} = [];
    end
else
    local_def = subsasgn(local_def, subs, varargin{1});
end;

author: spm


text:
function GUI = sessionGUI_addStudy(study, session, studyDir);
% Add a study to the mrVista GUI, selecting it in the process, and
% initializing with one session.
%
% <GUI> = sessionGUI_addStudy(<study=dialog>, <session=dialog>, <studyDir=''>);
%
% This function will update or create the saved studies file
% (saved in the mrVista 2 repository: mrVista2/study/studies.mat)
% with the new session, as well as adding it to the GUI.
%
%
% ras, 07/06.
mrGlobals2;

if notDefined('studyDir'), studyDir = ''; end

if notDefined('study')              % dialog
    study = inputdlg({'Name of the new study'}, mfilename);
    if isempty(study), return; end
    study = study{1};
end

if notDefined('session')            % dialog
    p = 'Select a first session to add to this study ';
    session = sessionSelectDialog(1, p);
end

% create the new study
n = length(GUI.studies) + 1; % index into new study
GUI.studies(n) = studyCreate(study);
GUI.studies(n).studyDir = studyDir;

% select the study
GUI = sessionGUI_selectStudy(study);

% add the first session to it
GUI = sessionGUI_addSession(session);

% save the updated studies file
studyPath = studySave(GUI.studies);
fprintf('Studies file %s updated.\n', studyPath);

return


text:
function y = vl_nncrop(x, crop, dzdy, inputSize)
%VL_NNCROP CNN crop.
%   Y = VL_NNCROP(X, CROP) crops the input X spatially. CROP specifies the
%   amount of cropping as [TOP, BOTTOM, LEFT, RIGHT].
%
%   DZDX = VL_NNCROP(X, CROP, DZDY) computes the derivative DZDX of the
%   function projected on the output derivative DZDY. DZDX has the same
%   dimension as X and DZDY the same dimension as Y.
%
%   DZDX = VL_NNCROP([], CROP, DZDY, INPUTSIZE) is an alternative to
%   the previous call in which X is omitted and its size is passed as
%   INPUTSIZE.

% Copyright (C) 2015 Sebastien Ehrhardt and Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

if nargin < 4
  sz = [size(x,1) size(x,2) size(x,3) size(x,4)] ;
else
  sz = inputSize ;
end

sv = 1 + crop(1) : sz(1) - crop(2) ;
su = 1 + crop(3) : sz(2) - crop(4) ;

if nargin <= 2 || isempty(dzdy)
  y = x(sv, su, :, :) ;
else
  if isa(dzdy, 'gpuArray')
    y = gpuArray.zeros(sz, classUnderlying(dzdy)) ;
  else
    y = zeros(sz, class(dzdy)) ;
  end
  y(sv, su, :, :) = dzdy ;
end

author: willard-yuan

repo: cnn-for-image-retrieval


text:
function img = connectivity_constraint(img, thr, sz, ind_max)
% remove small nonzero pixels
if ~exist('thr', 'var') || isempty(thr)
    thr = 0.01;
end
if ~exist('sz', 'var')||isemtpy(sz)
    sz = 5;
end
if ~exist('ind_max', 'var')||isemtpy(ctr)
    [~, ind_max] = max(img(:));
end
se = strel('square', sz);
ai_open = imopen(img, se);

temp = full(ai_open>max(img(:))*thr);
l = bwlabel(temp, 4);   % remove disconnected components
% [~, ind_max] = max(ai_open(:));

img(l(:)~=l(ind_max)) = 0;

author: zhoupc


text:
% Defines a gene
%
% Author: Jonathan Karr
% Affilitation: Covert Lab, Department of Bioengineering, Stanford University
% Last updated: 5/7/2009
classdef Gene < edu.stanford.covert.cell.kb.ssRNA

    properties
        genome                      = edu.stanford.covert.cell.kb.Genome.empty(0, 0);
        transcriptionUnits          = edu.stanford.covert.cell.kb.TranscriptionUnit.empty(0, 0);
        proteinMonomers             = edu.stanford.covert.cell.kb.ProteinMonomer.empty(0, 0);
        stableModificationReactions = edu.stanford.covert.cell.kb.Reaction.empty(0, 0);
        aminoAcid                   = edu.stanford.covert.cell.kb.Metabolite.empty(0, 0);
        compartment                 = edu.stanford.covert.cell.kb.Compartment.empty(0, 0);
    end

    properties %(SetAccess = protected)
        halfLife
        sequence

        symbol
        synonyms
        type
        startCodon
        codons
        startCoordinate
        endCoordinate
        direction
        essential
        expression
    end

    %computed properties
    properties %(SetAccess = protected)
        dnaSequence
        fivePrimeCoordinate
        threePrimeCoordinate
        synthesisRate

        matureBaseCount
        matureMolecularWeight
        matureDecayReaction

        aminoacylatedBaseCount
        aminoacylatedMolecularWeight
        aminoacylatedDecayReaction

        features
    end

    methods
        %constructor
        function this = Gene(knowledgeBase, wid, wholeCellModelID, name, ...
                symbol, synonyms, type, startCodon, codons, ...
                startCoordinate, sequenceLength, direction, essential, halfLife, ...
                expression, comments, crossReferences)

            if nargin == 0; return; end;

            this = edu.stanford.covert.cell.kb.Gene.empty(size(wid, 1), 0);
            this(size(wid, 1), 1) = edu.stanford.covert.cell.kb.Gene;
            for i = 1:size(wid, 1)
                this(i, 1).idx = i;
                this(i, 1).knowledgeBase = knowledgeBase;
                this(i, 1).wid = wid(i);
                this(i, 1).wholeCellModelID = wholeCellModelID{i};
                this(i, 1).name = name{i};
                if exist('comments', 'var') && ~isempty(comments); this(i, 1).comments = comments{i}; end;
                if exist('crossReferences', 'var')
                    if size(crossReferences,1) > 1
                        this(i, 1).crossReferences = crossReferences(i);
                    else
                        this(i, 1).crossReferences = struct;
                        fields = fieldnames(crossReferences);
                        for j = 1:size(fields, 1)
                            values = crossReferences.(fields{j});
                            this(i, 1).crossReferences.(fields{j}) = values(i);
                        end
                    end
                end

                this(i, 1).symbol = symbol{i};
                this(i, 1).synonyms = strsplit(';', synonyms{i});
                this(i, 1).type = type{i};
                this(i, 1).startCodon = startCodon(i);
                this(i, 1).codons = strsplit(';', codons{i});
                this(i, 1).startCoordinate = startCoordinate(i);
                this(i, 1).endCoordinate = startCoordinate(i) + sequenceLength(i) - 1;
                this(i, 1).direction = direction(i);
                this(i, 1).essential = essential{i};
                this(i, 1).expression = expression(i, :);
                this(i, 1).halfLife = halfLife(i);
            end
        end

        function serializeLinks(this)
            for i = 1:numel(this)
                this(i).genome                      = this.serializeLinksHelper(this(i).genome);
                this(i).transcriptionUnits          = this.serializeLinksHelper(this(i).transcriptionUnits);
                this(i).proteinMonomers             = this.serializeLinksHelper(this(i).proteinMonomers);
                this(i).stableModificationReactions = this.serializeLinksHelper(this(i).stableModificationReactions);
                this(i).aminoAcid                   = this.serializeLinksHelper(this(i).aminoAcid);
                this(i).compartment                 = this.serializeLinksHelper(this(i).compartment);

                serializeLinks@edu.stanford.covert.cell.kb.ssRNA(this(i));
            end
        end

        function deserializeLinks(this, kb)
            for i = 1:numel(this)
                this(i).genome                      = this.deserializeLinksHelper(this(i).genome, kb.genome);
                this(i).transcriptionUnits          = this.deserializeLinksHelper(this(i).transcriptionUnits, kb.transcriptionUnits);
                this(i).proteinMonomers             = this.deserializeLinksHelper(this(i).proteinMonomers, kb.proteinMonomers);
                this(i).stableModificationReactions = this.deserializeLinksHelper(this(i).stableModificationReactions, kb.reactions);
                this(i).aminoAcid                   = this.deserializeLinksHelper(this(i).aminoAcid, kb.metabolites);
                this(i).compartment                 = this.deserializeLinksHelper(this(i).compartment, kb.compartments);

                deserializeLinks@edu.stanford.covert.cell.kb.ssRNA(this(i), kb);
            end
        end

        function deleteLinks(this)
            for i = 1:numel(this)
                this(i).genome                      = [];
                this(i).transcriptionUnits          = [];
                this(i).proteinMonomers             = [];
                this(i).stableModificationReactions = [];
                this(i).aminoAcid                   = [];
                this(i).compartment                 = [];

                deleteLinks@edu.stanford.covert.cell.kb.ssRNA(this(i));
            end
        end

        function value = get.fivePrimeCoordinate(this)
            %retrieve
            if ~isempty(this.fivePrimeCoordinate)
                value = this.fivePrimeCoordinate;
                return;
            end

            %compute
            if this.direction
                value = this.startCoordinate;
            else
                value = this.endCoordinate;
            end

            %store
            this.fivePrimeCoordinate = value;
        end

        function value = get.threePrimeCoordinate(this)
            %retrieve
            if ~isempty(this.threePrimeCoordinate)
                value = this.threePrimeCoordinate;
                return;
            end

            %compute
            if this.direction
                value = this.endCoordinate;
            else
                value = this.startCoordinate;
            end

            %store
            this.threePrimeCoordinate = value;
        end

        function value = get.dnaSequence(this)
            %retrieve
            if ~isempty(this.dnaSequence)
                value = this.dnaSequence;
                return;
            end

            %compute
            if this.direction
                value = this.genome.sequence(this.startCoordinate:this.endCoordinate);
            else
                value = seqrcomplement(this.genome.sequence(this.startCoordinate:this.endCoordinate));
            end

            %store
            this.dnaSequence = value;
        end

        function value = get.sequence(this)
            %retrieve
            if ~isempty(this.sequence)
                value = this.sequence;
                return;
            end

            %compute
            value = this.dnaSequence;
            value(this.dnaSequence == 'A') = 'U';
            value(this.dnaSequence == 'C') = 'G';
            value(this.dnaSequence == 'G') = 'C';
            value(this.dnaSequence == 'T') = 'A';

            %store
            this.sequence = value;
        end

        function value = get.matureBaseCount(this)
            %retrieve
            if ~isempty(this.matureBaseCount)
                value = this.matureBaseCount;
                return;
            end

            %compute
            value = this.baseCount;

            if isempty(this.stableModificationReactions)
                return;
            end

            modifications = zeros(size(value));
            for i = 1:length(this.stableModificationReactions)
                reaction = this.stableModificationReactions(i);

                for j = 1:length(reaction.metabolites)
                    if any(this.knowledgeBase.modifiedNMPIndexs == reaction.metabolites(j).idx) || ...
                            (any(this.knowledgeBase.nmpIndexs == reaction.metabolites(j).idx) && reaction.metaboliteCoefficients(j) < 0)

                        modifications([reaction.metabolites(j).idx]) = ...
                            modifications([reaction.metabolites(j).idx]) + ...
                            reaction.metaboliteCoefficients(j)';
                    end
                end
            end

            value = value + modifications;

            %store
            this.matureBaseCount = value;
        end

        function value = get.matureMolecularWeight(this)
            % import classes
            import edu.stanford.covert.util.ConstantUtil;

            %retrieve
            if ~isempty(this.matureMolecularWeight)
                value = this.matureMolecularWeight;
                return;
            end

            %compute
            molecularWeightHO = ConstantUtil.elements.H + ConstantUtil.elements.O;

            baseCount = this.matureBaseCount;

            metabolicMolecularWeights = this.knowledgeBase.metaboliteMolecularWeights;

            value = baseCount * metabolicMolecularWeights - ...
                molecularWeightHO * max(0, this.sequenceLength - strcmp(this.sequenceTopology, 'linear'));

            %store
            this.matureMolecularWeight = value;
        end

        function value = get.matureDecayReaction(this)
            %retrieve
            if ~isempty(this.matureDecayReaction)
                value = this.matureDecayReaction;
                return;
            end

            %compute
            value = this.matureBaseCount;
            value(this.knowledgeBase.waterIndexs)    = value(this.knowledgeBase.waterIndexs)    - max(0, this.sequenceLength - strcmp(this.sequenceTopology, 'linear'));
            value(this.knowledgeBase.hydrogenIndexs) = value(this.knowledgeBase.hydrogenIndexs) + max(0, this.sequenceLength - strcmp(this.sequenceTopology, 'linear'));

            %store
            this.matureDecayReaction = value;
        end

        function value = get.aminoacylatedBaseCount(this)
            %retrieve
            if ~isempty(this.aminoacylatedBaseCount)
                value = this.aminoacylatedBaseCount;
                return;
            end

            %compute
            value = this.matureBaseCount;
            if ~isempty(this.aminoAcid)
                value(this.aminoAcid.idx) = value(this.aminoAcid.idx) + 1;
            end

            %store
            this.aminoacylatedBaseCount = value;
        end

        function value = get.aminoacylatedMolecularWeight(this)
            import edu.stanford.covert.util.ConstantUtil;

            %retrieve
            if ~isempty(this.aminoacylatedMolecularWeight)
                value = this.aminoacylatedMolecularWeight;
                return;
            end

            %compute
            value = this.matureMolecularWeight;
            if ~isempty(this.aminoAcid)
                molecularWeightHO = ConstantUtil.elements.H + ConstantUtil.elements.O;
                value = value + this.aminoAcid.molecularWeight - molecularWeightHO;
            end

            %store
            this.aminoacylatedMolecularWeight = value;
        end

        function value = get.aminoacylatedDecayReaction(this)
            %retrieve
            if ~isempty(this.aminoacylatedDecayReaction)
                value = this.aminoacylatedDecayReaction;
                return;
            end

            %compute
            value = this.matureDecayReaction;
            if ~isempty(this.aminoAcid)
                value(this.aminoAcid.idx) = value(this.aminoAcid.idx) + 1;
                value(this.knowledgeBase.waterIndexs)    = value(this.knowledgeBase.waterIndexs)    - 1;
                value(this.knowledgeBase.hydrogenIndexs) = value(this.knowledgeBase.hydrogenIndexs) + 1;
            end

            %store
            this.aminoacylatedDecayReaction = value;
        end

        function value = get.synthesisRate(this)
            %retrieve
            if ~isempty(this.synthesisRate)
                value = this.synthesisRate;
                return;
            end

            %compute
            value = log(2) / this.halfLife * this.expression;

            %store
            this.synthesisRate = value;
        end

        function value = get.features(this)
            %retrieve
            if ~isempty(this.features)
                value = this.features;
                return;
            end

            %compute
            featureStartCoordinates = [this.genome.features.startCoordinate];
            featureEndCoordinates = [this.genome.features.endCoordinate];
            value = this.genome.features(...
                (this.startCoordinate > featureStartCoordinates & this.startCoordinate < featureEndCoordinates) | ...
                (this.endCoordinate   > featureStartCoordinates & this.endCoordinate   < featureEndCoordinates) | ...
                (this.startCoordinate < featureStartCoordinates & this.endCoordinate   > featureEndCoordinates));

            %store
            this.features = value;
        end
    end
end

author: CovertLab

repo: WholeCell

save_path: github-repos/MATLAB/CovertLab-WholeCell


text:
function [tau] = ReasTaucalc(xk,EqMag,xmeff,bgdiff,P)
	% routine to claculate the look ahead time for clustered events gives tau back
    %
    %   xk:    factor used in xmeff
    %   xmeff: "effective" lower magnitude cutoff for the catalog.
    %   bgdiff:  difference in time
    %   P :    confidence that you are observing the next event in  the sequence (default is 0.95)
    %

	%ORIGINAL FROM ZMAP: NEEDS WORK FOR MAPSEIS
	%SUBFUNCTION: ReasenbergDeclus.m MIGHT NOT BE NEEDED
	%---------------------------------------------------

	%Adopted for MapSeis (small changes)

	%tauclac.m                                         A.Allmann

	deltam = (1-xk)*EqMag-xmeff;        %delta in magnitude
    if deltam<0
        deltam=0;
    end

	denom  = 10^((deltam-1)*2/3);              %expected rate of aftershocks
	top    = -log(1-P)*bgdiff;
	tau    = top/denom;                        %equation out of Raesenberg paper

end

author: CelsoReyes


text:
function engine = set_fields(engine, varargin)
% SET_FIELDS Set the fields for a generic engine
% engine = set_fields(engine, name/value pairs)
%
% e.g., engine = set_fields(engine, 'maximize', 1)

args = varargin;
nargs = length(args);
for i=1:2:nargs
  switch args{i},
   case 'maximize',
     engine.maximize = args{i+1};
     engine.jtree_engine = set_fields(engine.jtree_engine, 'maximize', args{i+1});
     engine.jtree_engine1 = set_fields(engine.jtree_engine1, 'maximize', args{i+1});
  end
end

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function W=watdet3(watermarkim,originalim);

a=marked-image1;
[ca ch cv cd]=dwt2(a,'db1');
imshow(ca);


text:
function out = resample_flow(uv, sz, method)
% function out = resample_flow(uv, factor, method)
%RESAMPLE_FLOW   Resample flow field
%   OUT = RESAMPLE_FLOW(IN, FACTOR[, METHOD]) resamples (resizes) the flow
%   field IN using a factor of FACTOR.  The optional argument METHOD
%   specifies the interpolation method ('bilinear' (default) or
%   'bicubic').
%
%   This is a private member function of the class 'clg_2d_optical_flow'.
%
%   Author:  Stefan Roth, Department of Computer Science, TU Darmstadt
%   Contact: sroth@cs.tu-darmstadt.de
%   $Date$
%   $Revision$

% Copyright 2004-2007, Brown University, Providence, RI. USA
% Copyright 2007-2010 TU Darmstadt, Darmstadt, Germany.
%
%                          All Rights Reserved
%
% All commercial use of this software, whether direct or indirect, is
% strictly prohibited including, without limitation, incorporation into in
% a commercial product, use in a commercial service, or production of other
% artifacts for commercial purposes.
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for research purposes is hereby granted without fee,
% provided that the above copyright notice appears in all copies and that
% both that copyright notice and this permission notice appear in
% supporting documentation, and that the name of the author and Brown
% University not be used in advertising or publicity pertaining to
% distribution of the software without specific, written prior permission.
%
% For commercial uses contact the Technology Venture Office of Brown University
%
% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO
% THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
% FITNESS FOR ANY PARTICULAR PURPOSE.  IN NO EVENT SHALL THE AUTHOR OR
% BROWN UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
% DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
% PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
% ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
% THIS SOFTWARE.

  % Make bilinear the default method
  if (nargin < 3)
    method = 'bilinear';
%     method = 'bicubic';
  end
%
%   % Resize u and v
%   tmp_u = ximresize(uv(:, :, 1), factor, method);
%   tmp_v = ximresize(uv(:, :, 2), factor, method);
%   out = cat(3, tmp_u, tmp_v)*factor;
%
  ratio = sz(1) / size(uv,1);
  u     = imresize(uv(:,:,1), sz, method)*ratio;
  v     = imresize(uv(:,:,2), sz, method)*ratio;
  out   = cat(3, u, v);

author: kristinbranson

repo: JAABA


text:
function [out] = ReedSolomon(random,codeRS,Tx);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                                                                       %
%%     Name: ReedSolomon.m                                               %
%%                                                                       %
%%     Description: The Reed-Solomon encoder is realized according to    %
%%      the standard.                                                    %
%%                                                                       %
%%     Parameters:                                                       %
%%      Sequence of bits to endoe with the algorithm.                    %
%%                                                                       %
%%     Result: It gives back the encoded bits according to the need      %
%%      and also following the modulation.                               %
%%                                                                       %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 m = 8;                          % Number of bits per symbol
 n = codeRS(1);                  % Length of the codeword
 k = codeRS(2);                  % Number of information symbols

 % To realize the Reed-Solomon code, the information is needed in decimal.

  random = reshape(random,8,length(random)/8)';
  random = bi2de(random,'left-msb');

if Tx==1
    % 36 bytes are needed with a stuffed zero at the end of the vector:
     yk=[random' 0];

    % The Galois vector is generated, the generating polynomial of the
    % code. Then the symbols are encoded with Reed-Solomon.
    msg = gf([yk],m);
    if n==k                      % bypass for BPSK
        codeRS = msg;
    elseif n~=k
        codeRS = rsenc(msg,n,k);
    end
    out = codeRS.x;

elseif Tx==0
    yk = random;            % In the receiver, nothing needs to be completed.

    msg = gf([yk],m);           % In this case, the encoding is undone.
    if n==k
        codeRS = yk;
    elseif n~=k
        codeRS = rsdec(msg',n,k);
        codeRS = codeRS.x;
    end
    out = codeRS(1:end-1);
end

% The binary data to continue working:
 out = double (out);
 out = de2bi (out,8,'left-msb');

% Serial the data for the next step.
 out = reshape (out', 1, length(out)*8);


text:
function options = setoptions(varargin)

start = 1;
if (~isempty(varargin) && isstruct(varargin{1}))
    options = varargin{1};
    start = start+1;
else
    %defaults
    options.feature_select = 10000;
    options.subsample = 0.2;
    options.out_bag_estimate = false;
    options.lasso_alpha = 1.0;
end

for iter=start:2:length(varargin)

    if (strcmpi(varargin{iter},'SelectFeatures'))
        options.feature_select = varargin{iter+1};
    elseif (strcmpi(varargin{iter},'Subsample'))
        options.subsample = varargin{iter+1};
    elseif (strcmpi(varargin{iter},'LassoAlpha'))
        options.lasso_alpha = varargin{iter+1};
    elseif (strcmpi(varargin{iter},'OutBagEstimate'))
        options.subsample = varargin{iter+1};
    else
        error(['Unknown option ',varargin{iter}]);
    end

end;

author: konstantinberlin

repo: malware-windows-audit-log-detection