text:
classdef plotlystream < handle
    % Interface to Plotly's real-time graphing API.
    % Initialize a Stream object with a stream_id found in
    % {plotly_domain}/settings. Real-time graphs are
    % initialized with a call to plotly that embeds your unique
    % `stream_id`s in each of the graph's traces. The plotlystream
    % class plots data to these traces, as identified with the unique
    % stream_id, in real-time. Every viewer of the graph sees
    % the same data at the same time.

    %----CLASS PROPERTIES----%
    properties
        Response
        Specs
    end

    properties (Access=private)
        URL
        ErrorURL
        Connection
        ErrorConnection
        Stream
        ErrorStream
    end

    %----CLASS METHODS----%
    methods

        %----CONSTRUCTOR---%
        function obj = plotlystream(request)

            %default stream settings
            obj.Specs.Token = '';

            %look for specified streaming domain
            try
                config = loadplotlyconfig;
                obj.Specs.Host  = config.plotly_streaming_domain;
            catch
                obj.Specs.Host = 'http://stream.plot.ly';
            end

            %check if ssl is enabled
            if any(strfind(obj.Specs.Host,'https://') == 1)
                obj.Specs.SSLEnabled = true;
            else
                obj.Specs.SSLEnabled = false;
            end

            %add http if not present on host
            if ~obj.Specs.SSLEnabled
                if ~any(strfind(obj.Specs.Host,'http://') == 1)
                    obj.Specs.Host = ['http://' obj.Specs.Host];
                end
            end

            %specify handler
            if obj.Specs.SSLEnabled
                obj.Specs.Handler = sun.net.www.protocol.https.Handler;
            else
                obj.Specs.Handler = sun.net.www.protocol.http.Handler;
            end

            %initialize connection settings
            obj.Specs.ReconnectOn = {'','200','408'};
            obj.Specs.Timeout = 500;
            obj.Specs.Chunklen = 14;
            obj.Specs.Closed = true;
            obj.Specs.ConnectAttempts = 0;
            obj.Specs.ConnectDelay = 1;
            obj.Specs.MaxConnectAttempts = 5;

            %initialize output response
            obj.Response = '';

            %check for correct input structure
            if nargin > 0

                if ischar(request)

                    obj.Specs.Token = request;

                elseif isstruct(request)

                    %check for tokens (required)
                    if (isfield(request,'token'))
                        obj.Specs.Token = request.token;
                    else
                        error(['Oops! You did not properly specify a stream token! Please check out the ', ....
                            'online documentation found @ plot.ly/matlab for more information or contact ',...
                            'chuck@plot.ly']);
                    end

                    if isfield(request,'host')
                        obj.Specs.Host = request.host;
                    end

                    if isfield(request,'timeout')
                        obj.Specs.Timeout = request.timeout;
                    end

                    if isfield(request,'handler')
                        obj.Specs.Handler= request.handler;
                    end

                    if isfield(request,'chunklen')
                        obj.Specs.Chunklen= request.chunklen;
                    end
                else
                    error(['Oops! It appears that the specified input argument used to ',...
                        'initialize the plotlystream object was not of type char or struct. ',...
                        'Please check out the online documentation found @ plot.ly/matlab ',...
                        'for more information or contact chuck@plot.ly']);
                end

            else
                error(['Oops! You did not properly specify a stream token! Please check out the ', ....
                    'online documentation found @ plot.ly/matlab for more information or contact ',...
                    'chuck@plot.ly']);
            end
        end

        %-----------OPEN STREAM-----------%
        function obj = open(obj)

            try obj.connect;

                %Connection successful!
                fprintf('\n[Connection Successful]\n\n');

                %update state
                obj.resetretries;
                obj.Specs.Closed = false;

            catch ME

                error(['Oops! The following error occured when trying to write to the stream: ',...
                    ME.message '. Please check the online documentation ', ...
                    'found @ plot.ly/matlab for more information or contact chuck@plot.ly']);
            end

        end

        %-----------CONNECT TO STREAM-----------%
        function obj = connect(obj)
            obj.URL = java.net.URL([],obj.Specs.Host,obj.Specs.Handler);

            % Get the proxy information using MathWorks facilities for unified proxy
            % preference settings.
            mwtcp = com.mathworks.net.transport.MWTransportClientPropertiesFactory.create();
            proxy = mwtcp.getProxy();

            % Open a connection to the URL.
            if isempty(proxy)
                obj.Connection = obj.URL.openConnection(); %throws an I/O exception
            else
                obj.Connection = obj.URL.openConnection(proxy); %throws an I/O exception
            end

            obj.Connection.setChunkedStreamingMode(obj.Specs.Chunklen)
            obj.Connection.setRequestMethod('POST');
            obj.Connection.setDoOutput(true);
            obj.Connection.setReadTimeout(obj.Specs.Timeout);
            obj.Connection.setRequestProperty('plotly-streamtoken', obj.Specs.Token);
            obj.Stream = obj.Connection.getOutputStream; %throws an I/O exception
        end

        %-----------WRITE STREAM-----------%
        function obj = write(obj,request)

            if nargin ~= 2
                error(['Oops! It appears that not enough input arguments were ',...
                    'specified to the write method of your plotlystream object. ',...
                    'Please check out the online documentation found @ plot.ly/matlab ',...
                    'for more information or contact chuck@plot.ly']);
            else
                if ~isstruct(request)
                    error(['Oops! It appears that the input argument to the write method ',...
                        'of your plotlystream object is not a structure array as required.  ',...
                        'Please check out the online documentation found @ plot.ly/matlab ',...
                        'for more information or contact chuck@plot.ly']);
                end

                body = request;

                %make sure we did not close the stream
                if(~obj.Specs.Closed)
                    try
                        %write to stream
                        obj.Stream.write(unicode2native(sprintf([m2json(body) '\n']),''));
                    catch ME

                        %error due to stream not being open (creation of Stream object)
                        if(strcmp(ME.message, 'Attempt to reference field of non-structure array.'))
                            error(['Oops! A connection has not yet been established. Please open',...
                                ' a connection by firsting calling the ''open'' method of your',...
                                ' plotlystream object.']);
                        else

                            %---reconnect---%
                            obj.getresponse;
                            if any(strcmp(obj.Specs.ReconnectOn,obj.Response))
                                if~strcmp(obj.Response,'')
                                    fprintf(['\n[Connection Failed due to HTTP error: ' obj.Response '] Reconnecting...\n\n']);
                                else
                                    fprintf('\n[Connection Failed] Reconnecting...\n\n');
                                end
                                obj.reconnect;

                                %add recursion call to not drop data
                                obj.write(body);
                            else
                                error(['Oops! The following error occured when trying to write to the stream: ',...
                                    ME.message '. No attempt to reconnect was made beacause the response code ',...
                                    'of: ' obj.Response ' did not match any of the response codes specified in ',...
                                    'the obj.Specs.ReconnectOn parameter. Please check out the online documentation ', ...
                                    'found @ plot.ly/matlab for more information or contact chuck@plot.ly']);
                            end
                        end
                    end
                else
                    error(['Oops! The connection is closed. Please open ',...
                        'a connection by calling the ''open'' method of your ',...
                        'plotlystream object.']);
                end
            end
        end

        %-----------CLOSE STREAM-----------%
        function obj = close(obj)
            try
                obj.Stream.close;
            catch ME
                if(strcmp(ME.message, 'Attempt to reference field of non-structure array.'))
                    error(['Oops! A connection has not yet been established. Please open',...
                        ' a connection by firsting calling the ''open'' method of your',...
                        ' plotlystream object.']);
                end
            end
            %update reconnect state
            obj.resetretries;
            obj.Specs.Closed = true;
        end

        %-----------RECONNECT-----------%
        function obj = reconnect(obj)
            try
                obj.Specs.ConnectAttempts = obj.Specs.ConnectAttempts + 1;

                %try to connect
                obj.connect;

                %Connection successful!
                fprintf('\n[Connection Successful]\n\n');

                %update state
                obj.resetretries;
                obj.Specs.Closed = false;
            catch
                if(obj.Specs.ConnectAttempts <= obj.Specs.MaxConnectAttempts)
                    fprintf(['\n[Connection Failed] Attempt:' num2str(obj.Specs.ConnectAttempts) ' to reconnect...'])
                    pause(obj.Specs.ConnectDelay);
                    obj.Specs.ConnectDelay = 2*obj.Specs.ConnectDelay; %delay grows by factor of 2
                    obj.reconnect;
                else
                    fprintf('\n');
                    error(['Oops! All attempts to reconnect were unsuccessful. ',...
                        'Please check out the online documentation found @ plot.ly/matlab ',...
                        'for more information or contact chuck@plot.ly']);
                end
            end
        end

        %-----------GET RESPONSE-----------%
        function obj = getresponse(obj)
            try
                obj.Response = num2str(obj.Connection.getResponseCode);
            catch ME
                if(strcmp(ME.message, 'Attempt to reference field of non-structure array.'))
                    error(['Oops! A connection has not yet been established. Please open',...
                        ' a connection by firsting calling the ''open'' method of your',...
                        ' plotlystream object.']);
                end
            end
        end

        %-----------RESET RETRIES-----------%
        function obj = resetretries(obj)
            %reset the connect counter and delay
            obj.Specs.ConnectAttempts = 0;
            obj.Specs.ConnectDelay = 1;
        end

    end
end

author: plotly


text:
%describres the results of a classification for a single file
classdef AssessmentDetailedClassificationResult < handle
    properties (Access = public)
        annotations;
        segments;
        classificationResult ClassificationResult;
        missedEvents;
    end

    properties (Dependent)
        fileName;
    end

    methods
        function fn = get.fileName(obj)
            fn = obj.classificationResult.table.file.fileName;
        end
    end

    methods (Access = public)
        function obj = AssessmentDetailedClassificationResult(annotations, segments,...
                classificationResult, postProcessingAlgorithm)
            if nargin > 0
                obj.annotations = annotations;
                obj.segments = segments;
                obj.classificationResult = classificationResult;
                obj.createMissedEvents(postProcessingAlgorithm);
            end
        end

        function labels = getAllTruthLabels(obj)
            labels = vertcat(obj.classificationResult.truthClasses);
        end

        function labels = getAllPredictedLabels(obj)
            labels = vertcat(obj.classificationResult.predictedClasses);
        end
    end

    methods (Access = private)
        function createMissedEvents(obj,postProcessingAlgorithm)
            if obj.shouldUseEventDetection()
                resultsComputer = DetectionResultsComputer();
                events = obj.createEventsWithEventIdxs(obj.segments);
                detectionResults = resultsComputer.computeDetectionResults({events},obj.annotations);
                obj.missedEvents = detectionResults.missedEvents;
                if isa(postProcessingAlgorithm, 'LabelMapper')
                    obj.mapMissedEvents(postProcessingAlgorithm);
                end
            end
        end

        function shouldUseEventDetection = shouldUseEventDetection(obj)
            shouldUseEventDetection = false;
            if ~isempty(obj.segments)
                firstSegment = obj.segments(1);
                shouldUseEventDetection = ~isempty(firstSegment.eventIdx);
            end
        end

        function events = createEventsWithEventIdxs(~,segments)
            nEvents = length(segments);
            events = repmat(Event,1,nEvents);
            for i = 1 : nEvents
                segment = segments(i);
                events(i) = Event(segment.eventIdx,segment.label);
            end
        end

        function mapMissedEvents(obj,labelMapper)
            for j = 1 : length(obj.missedEvents)
                obj.missedEvents(j).label = labelMapper.mappingForLabel(obj.missedEvents(j).label);
            end
        end
    end
end

author: avenix

repo: WDK

save_path: github-repos/MATLAB/avenix-WDK


text:
function [x,N] = makesig(SigName,N)
% [x,N] = makesig(SigName,N) Creates artificial test signal identical to the
%     standard test signals proposed and used by D. Donoho and I. Johnstone
%     in WaveLab (- a matlab toolbox developed by Donoho et al. the statistics
%     department at Stanford University).
%
%    Input:  SigName - Name of the desired signal (Default 'all')
%                        'AllSig' (Returns a matrix with all the signals)
%                        'HeaviSine'
%                        'Bumps'
%                        'Blocks'
%                        'Doppler'
%                        'Ramp'
%                        'Cusp'
%                        'Sing'
%                        'HiSine'
%                        'LoSine'
%                        'LinChirp'
%                        'TwoChirp'
%                        'QuadChirp'
%                        'MishMash'
%                        'WernerSorrows' (Heisenberg)
%                        'Leopold' (Kronecker)
%            N       - Length in samples of the desired signal (Default 512)
%
%    Output: x   - vector/matrix of test signals
%            N   - length of signal returned
%
%    See also:
%
%    References:
%            WaveLab can be accessed at
%            www_url: http://playfair.stanford.edu/~wavelab/
%            Also see various articles by D.L. Donoho et al. at
%            web_url: http://playfair.stanford.edu/
%
%Author: Jan Erik Odegard  <odegard@ece.rice.edu>
%This m-file is a copy of the  code provided with WaveLab
%customized to be consistent with RWT.

if(nargin < 1)
  SigName = 'AllSig';
  N = 512;
elseif(nargin == 1)
  N = 512;
end;
t = (1:N) ./N;
x = [];
y = [];
if(strcmp(SigName,'HeaviSine') | strcmp(SigName,'AllSig')),
  y = 4.*sin(4*pi.*t);
  y = y - sign(t - .3) - sign(.72 - t);
end;
x = [x;y];
y = [];
if(strcmp(SigName,'Bumps') | strcmp(SigName,'AllSig')),
  pos = [ .1 .13 .15 .23 .25 .40 .44 .65  .76 .78 .81];
  hgt = [ 4  5   3   4  5  4.2 2.1 4.3  3.1 5.1 4.2];
  wth = [.005 .005 .006 .01 .01 .03 .01 .01  .005 .008 .005];
  y = zeros(size(t));
  for j =1:length(pos)
    y = y + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4;
  end
end;
x = [x;y];
y = [];
if(strcmp(SigName,'Blocks') | strcmp(SigName,'AllSig')),
  pos = [ .1 .13 .15 .23 .25 .40 .44 .65  .76 .78 .81];
  hgt = [4 (-5) 3 (-4) 5 (-4.2) 2.1 4.3  (-3.1) 2.1 (-4.2)];
  y = zeros(size(t));
  for j=1:length(pos)
    y = y + (1 + sign(t-pos(j))).*(hgt(j)/2) ;
  end
end;
x = [x;y];
y = [];
if(strcmp(SigName,'Doppler') | strcmp(SigName,'AllSig')),
  y = sqrt(t.*(1-t)).*sin((2*pi*1.05) ./(t+.05));
end;
x = [x;y];
y = [];
if(strcmp(SigName,'Ramp') | strcmp(SigName,'AllSig')),
  y = t - (t >= .37);
end;
x = [x;y];
y = [];
if(strcmp(SigName,'Cusp') | strcmp(SigName,'AllSig')),
  y = sqrt(abs(t - .37));
end;
x = [x;y];
y = [];
if(strcmp(SigName,'Sing') | strcmp(SigName,'AllSig')),
  k = floor(N * .37);
  y = 1 ./abs(t - (k+.5)/N);
end;
x = [x;y];
y = [];
if(strcmp(SigName,'HiSine') | strcmp(SigName,'AllSig')),
  y = sin( pi * (N * .6902) .* t);
end;
x = [x;y];
y = [];
if(strcmp(SigName,'LoSine') | strcmp(SigName,'AllSig')),
  y = sin( pi * (N * .3333) .* t);
end;
x = [x;y];
y = [];
if(strcmp(SigName,'LinChirp') | strcmp(SigName,'AllSig')),
  y = sin(pi .* t .* ((N .* .125) .* t));
end;
x = [x;y];
y = [];
if(strcmp(SigName,'TwoChirp') | strcmp(SigName,'AllSig')),
  y = sin(pi .* t .* (N .* t)) + sin((pi/3) .* t .* (N .* t));
end;
x = [x;y];
y = [];
if(strcmp(SigName,'QuadChirp') | strcmp(SigName,'AllSig')),
  y = sin( (pi/3) .* t .* (N .* t.^2));
end;
x = [x;y];
y = [];
if(strcmp(SigName,'MishMash') | strcmp(SigName,'AllSig')),
  % QuadChirp + LinChirp + HiSine
  y = sin( (pi/3) .* t .* (N .* t.^2)) ;
  y = y +  sin( pi * (N * .6902) .* t);
  y = y +  sin(pi .* t .* (N .* .125 .* t));
end;
x = [x;y];
y = [];
if(strcmp(SigName,'WernerSorrows') | strcmp(SigName,'AllSig')),
  y = sin( pi .* t .* (N/2 .* t.^2)) ;
  y = y +  sin( pi * (N * .6902) .* t);
  y = y +  sin(pi .* t .* (N .* t));
  pos = [ .1 .13 .15 .23 .25 .40 .44 .65  .76 .78 .81];
  hgt = [ 4  5   3   4  5  4.2 2.1 4.3  3.1 5.1 4.2];
  wth = [.005 .005 .006 .01 .01 .03 .01 .01  .005 .008 .005];
  for j =1:length(pos)
    y = y + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4;
  end
end;
x = [x;y];
y = [];
if(strcmp(SigName,'Leopold') | strcmp(SigName,'AllSig')),
  y = (t == floor(.37 * N)/N); 		% Kronecker
end;
x = [x;y];
y = [];

%  disp(sprintf('MakeSignal: I don*t recognize << %s>>',SigName))
%  disp('Allowable SigNames are:')
%  disp('AllSig'),
%  disp('HeaviSine'),
%  disp('Bumps'),
%  disp('Blocks'),
%  disp('Doppler'),
%  disp('Ramp'),
%  disp('Cusp'),
%  disp('Crease'),
%  disp('Sing'),
%  disp('HiSine'),
%  disp('LoSine'),
%  disp('LinChirp'),
%  disp('TwoChirp'),
%  disp('QuadChirp'),
%  disp('MishMash'),
%  disp('WernerSorrows'),
%  disp('Leopold'),
%end

author: ricedsp


text:
classdef MimSegmentationButton < GemButton
    % MimSegmentationButton. Part of the gui for the TD MIM Toolkit.
    %
    %     This class is used internally within the TD MIM Toolkit to help
    %     build the user interface.
    %
    %     MimSegmentationButton is used to build a button control representing a plugin,
    %     with a backgroud image preview of the segmentation
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        RootButtonWidth = 20;
        RootButtonHeight = 20;
    end

    properties (Access = protected)
        LoadManualSegmentationCallback
    end

    methods
        function obj = MimSegmentationButton(parent, name, load_manual_segmentation_callback)
            tooltip_string = ['<HTML>' name];

            button_text = ['<HTML><P ALIGN = RIGHT>', name];
            tag = name;
            obj = obj@GemButton(parent, button_text, tooltip_string, tag, []);
            obj.LoadManualSegmentationCallback = load_manual_segmentation_callback;
            obj.Callback = @obj.ButtonPressed;

            % Calculate the button size, based on plugin properties
            obj.ButtonWidth = 6*obj.RootButtonWidth;
            obj.ButtonHeight = 2*obj.RootButtonHeight;
        end

        function AddPreviewImage(obj, preview_fetcher, window, level)
            if ~isempty(preview_fetcher)
                preview_image = preview_fetcher.GetPluginPreview(obj.Tag);
            else
                preview_image = [];
            end
            if isempty(obj.Position)
                button_size = [obj.ButtonWidth, obj.ButtonHeight];
            else
                button_size = obj.Position(3:4);
            end
            preview_image_raw = MimImageUtilities.GetButtonImage(preview_image, button_size(1), button_size(2), window, level, 1, obj.BackgroundColour, obj.UnSelectedColour);
            obj.ChangeImage(preview_image_raw);
        end

        function height = GetRequestedHeight(obj, width)
            % Returns a value for the height of the object

            height = obj.ButtonHeight;
        end

        function ButtonPressed(obj, name)
            obj.LoadManualSegmentationCallback(name);
        end

    end
end

author: tomdoel

repo: pulmonarytoolkit


text:
function confMatrixShow( CM, types, pvPairs, nDigits, showCnts )
% Used to display a confusion matrix.
%
% See confMatrix for general format and info on confusion matricies. This
% function normalizes the CM before displaying, hence all values range in
% [0,1] and rows sum to 1.
%
% USAGE
%  confMatrixShow( CM, [types], [pvPairs], [nDigits], [showCnts] )
%
% INPUTS
%  CM          - [nTypes x nTypes] confusion array -- see confMatrix
%  types       - [] cell array of length nTypes of text labels
%  pvPairs     - [{'FontSize',20}] parameter / value list for text.m
%  nDigits     - [2] number of digits after decimal to display
%  showCnts    - [0] show total count per row to the right
%
% OUTPUTS
%
% EXAMPLE
%  CM = randint2(6,6,[1,100])+eye(6)*500;
%  types = { 'anger','disgust','fear','joy','sadness','surprise' };
%  confMatrixShow( CM, types, {'FontSize',20}, [], 0 )
%  title('confusion matrix','FontSize',24);
%
% See also confMatrix, imLabel, dispMatrixIm
%
% Piotr's Computer Vision Matlab Toolbox      Version 2.50
% Copyright 2014 Piotr Dollar.  [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]

if( nargin<2 ); types=[]; end
if( nargin<3 || isempty(pvPairs)); pvPairs = {'FontSize',20}; end
if( nargin<4 || isempty(nDigits)); nDigits=2; end
if( nargin<5 || isempty(showCnts)); showCnts=0; end
if( nDigits<1 || nDigits>10 ); error('too few or too many digits'); end
if( any(CM(:)<0) ); error( 'CM must have non-negative entries' ); end

% normalize and round appropriately
cnts = sum(CM,2);
CM = CM ./ repmat( cnts+eps, [1 size(CM,2)] );
CM = round(CM*10^nDigits) / 10^nDigits;

% display as image using dispMatrixIm
dispMatrixIm(CM,'maxM',1,'maxLen',nDigits+1,'show0',0,...
  'fStr','%f','invert',1,'pvPairs',pvPairs); axis square;

% now add type labels
if( ~isempty(types) )
  imLabel( types, 'left', 0, pvPairs );
  imLabel( types, 'bottom', -35, pvPairs );
  if(showCnts), imLabel(int2str2(cnts),'right',0,pvPairs); end
end

author: pdollar

repo: toolbox

save_path: github-repos/MATLAB/pdollar-toolbox


text:
% FDR - compute false detection rate mask
%
% Usage:
%   >> [p_fdr, p_masked] = fdr( pvals, alpha);
%
% Inputs:
%   pvals   - vector or array of p-values
%   alpha   - threshold value (non-corrected). If no alpha is given
%             each p-value is used as its own alpha and FDR corrected
%             array is returned.
%   fdrtype - ['parametric'|'nonParametric'] FDR type. Default is
%             'parametric'.
%
% Outputs:
%   p_fdr    - pvalue used for threshold (based on independence
%              or positive dependence of measurements)
%   p_masked - p-value thresholded. Same size as pvals. Can only be 0 or 1.
%
% Author: Arnaud Delorme, SCCN, 2008-
%         Based on a function by Tom Nichols
%
% Reference: Bejamini & Yekutieli (2001) The Annals of Statistics

% Copyright (C) 2002 Arnaud Delorme, Salk Institute, arno@salk.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.

function [pID, p_masked] = fdr(pvals, q, fdrType);

if nargin < 3, fdrType = 'parametric'; end
if isempty(pvals), pID = []; return; end
p = sort(pvals(:));
V = length(p);
I = (1:V)';

cVID = 1;
cVN = sum(1./(1:V));

if nargin < 2
    pID = ones(size(pvals));
    thresholds = exp(linspace(log(0.1),log(0.000001), 1000));
    for index = 1:length(thresholds)
        [tmp p_masked] = fdr(pvals, thresholds(index));
        pID(p_masked) = thresholds(index);
    end
else
    if strcmpi(fdrType, 'parametric')
        pID = p(max(find(p<=I/V*q/cVID))); % standard FDR
    else
        pID = p(max(find(p<=I/V*q/cVN)));  % non-parametric FDR
    end
end
if isempty(pID), pID = 0; end

if nargout > 1
    p_masked = pvals<=pID;
end

author: sccn

repo: eeglab

save_path: github-repos/MATLAB/sccn-eeglab


text:
classdef MOSSETracker < handle
    %MOSSETRACKER  MOSSE filter based tracker
    %
    % Correlation filter based tracking using MOSSE filters
    % (Minimum Output Sum of Squared Error), described in [Bolme2010].
    %
    % The target object appearance is modeled using adaptive correlation
    % filters, and tracking is performed via convolution.
    %
    % The filters are learnt online in an adaptive manner for visual tracking.
    %
    % ## Sources:
    %
    % * https://github.com/opencv/opencv/blob/3.3.1/samples/python/mosse.py
    %
    % ## References
    % [Bolme2010]:
    % > David S. Bolme et al.
    % > "Visual Object Tracking using Adaptive Correlation Filters"
    % > [PDF](http://www.cs.colostate.edu/~draper/papers/bolme_cvpr10.pdf)
    %

    properties
        % criteria for successful tracking, psr > min_psr
        % A value between [20,60] indicates very strong peaks,
        % less than 7 indicates bad track quality.
        min_psr = 8.0;
    end

    properties (Access = private)
        % Hanning window used when preprocessing images
        win
        % Fourier transform of 2D Gaussian shaped peak centered on target
        G
        % correlation filters/kernels
        H1
        H2
        H
        % last image of target
        last_img
        % last correlation response
        last_resp
    end

    properties (SetAccess = private)
        % center [x,y] of tracked object rectangle
        pos
        % size [w,h] of tracked object rectangle
        siz
        % Peak-to-Sidelobe Ratio (PSR)
        psr
    end

    properties (Dependent, SetAccess = private)
        % tracked object position, as a `[x y w h]` rectangle
        bbox
    end

    methods
        function obj = MOSSETracker(frame, rect)
            %MOSSETRACKER  Constructor
            %
            %     obj = MOSSETracker(frame, rect)
            %
            % ## Input
            % * __frame__ first frame with target to track
            % * __rect__ rectangle around target object `[x,y,w,h]`
            %

            % center and size of object rectangle (after DFT optimal padding)
            obj.siz = arrayfun(@(s) cv.getOptimalDFTSize(s), rect(3:4));
            obj.pos = floor((2*rect(1:2) + rect(3:4) - obj.siz) / 2);
            obj.pos = obj.pos + 0.5 * (obj.siz - 1);

            % create Hanning window of same size as rect
            obj.win = cv.createHanningWindow(obj.siz, 'Type','single');

            % create Gaussian shaped peak, centered and of same size as rect
            % (Kronecker delta with 1 at target center, 0 elsewhere)
            g = zeros(obj.siz(2), obj.siz(1), 'single');
            g(floor(end/2),floor(end/2)) = 1;
            g = cv.GaussianBlur(g, 'KSize',[-1 -1], 'SigmaX',2.0);
            g = g / max(g(:));

            % initialize correlation filters
            obj.G = cv.dft(g, 'ComplexOutput',true);
            obj.H1 = zeros(size(obj.G), class(obj.G));
            obj.H2 = zeros(size(obj.G), class(obj.G));

            % train filters on a bunch of augmented images
            % by applying small random affine perturbations
            img = cv.getRectSubPix(frame, obj.siz, obj.pos);
            for i=1:128
                a = obj.preprocess(random_warp(img));
                obj.update_kernels(a);
            end

            % process first frame
            obj.update(frame);
        end

        function update(obj, frame, rate)
            %UPDATE  Track object in new frame and update filters
            %
            %     obj.update(frame)
            %     obj.update(frame, rate)
            %
            % ## Input
            % * __frame__ new frame in which to track object
            % * __rate__ learning rate in [0,1] range, default 0.125
            %

            % crop and process image from current position
            obj.last_img = cv.getRectSubPix(frame, obj.siz, obj.pos);
            img = obj.preprocess(obj.last_img);

            % track target by correlating filter over image
            [obj.last_resp, d, obj.psr] = obj.correlate(img);

            % check that response peack is strong enough (using PSR)
            if obj.psr <= obj.min_psr
                return;
            end

            % update object position
            obj.pos = obj.pos + d;

            % crop and process image from new position
            obj.last_img = cv.getRectSubPix(frame, obj.siz, obj.pos);
            img = obj.preprocess(obj.last_img);

            % online update (filter training)
            if nargin < 3, rate = 0.125; end
            obj.update_kernels(img, rate);
        end

        function [img, f, resp] = visualize_state(obj)
            %VISUALIZE_STATE  Visualize tracker state
            %
            %     [img, f, resp] = obj.visualize_state()
            %
            % ## Output
            % * __img__ cropped object image
            % * __f__ correlation filter, 0-freq centered and 8-bit normalized
            % * __resp__ correlation response, 8-bit normalized and clipped
            %

            % image
            img = obj.last_img;

            % kernel
            f = cv.dft(obj.H, 'Inverse',true, 'Scale',true, 'RealOutput',true);
            f = circshift(f, floor(-[size(f,1) size(f,2)]/2));
            if true
                f = (f - min(f(:))) / (max(f(:)) - min(f(:)));
            else
                f = cv.normalize(f, 'NormType','MinMax');
            end
            f = uint8(255 * f);

            % response
            if true
                resp = obj.last_resp / max(obj.last_resp(:));
            else
                resp = cv.normalize(obj.last_resp, 'NormType','Inf');
            end
            resp = uint8(255 * min(max(resp, 0), 1));
        end

        function vis = draw_object(obj, vis)
            %DRAW_OBJECT  Draw current location of tracked object
            %
            %     vis = obj.draw_object(vis)
            %
            % ## Input
            % * __vis__ input image
            %
            % ## Output
            % * __vis__ output image with drawn object
            %

            clr = {'Color',[0 0 255]};
            p1 = fix(obj.pos - 0.5 * obj.siz);
            p2 = fix(obj.pos + 0.5 * obj.siz);

            % draw location
            vis = cv.rectangle(vis, p1, p2, 'Thickness',2, clr{:});
            if obj.psr > obj.min_psr
                % good track, draw center
                vis = cv.circle(vis, fix(obj.pos), 2, 'Thickness',-1, clr{:});
            else
                % bad track, draw cross
                vis = cv.line(vis, [p1; p2(1) p1(2)], [p2; p1(1) p2(2)], clr{:});
            end

            % draw PSR value
            vis = cv.putText(vis, sprintf('PSR: %.2f', obj.psr), ...
                [p1(1) p2(2)+16], 'FontFace','HersheyPlain', ...
                'Thickness',2, 'LineType','AA', clr{:});
        end

        function bbox = get.bbox(obj)
            p1 = obj.pos - 0.5 * obj.siz;
            p2 = obj.pos + 0.5 * obj.siz;
            bbox = cv.Rect.from2points(p1, p2);
        end
    end

    methods (Access = private)
        function img = preprocess(obj, img)
            %PREPROCESS  Process input frame
            %
            %     img = obj.preprocess(img)
            %
            % ## Input
            % * __img__ input image
            %
            % ## Output
            % * __img__ output processed image
            %

            % log transform, normalize, and multiply by Hanning window
            img = log(single(img) + 1);
            if true
                img = img / norm(img(:));
            elseif true
                img = cv.normalize(img, 'NormType','L2');
            else
                img = (img - mean(img(:))) / std(img(:));
            end
            img = img .* obj.win;
        end

        function [resp, d, psr] = correlate(obj, img)
            %CORRELATE  Correlate filter over image and find peak in response
            %
            %     [resp, d, psr] = obj.correlate(img)
            %
            % ## Input
            % * __img__ processed image
            %
            % ## Output
            % * __resp__ correlation response
            % * __d__ offset of peak location from center `[x,y]`
            % * __psr__ PSR value, a measure of correlation peak strength. Can
            %   be used to stop the online update if PSR is too low, which is
            %   an indication the the object is occluded or tracking has
            %   failed.
            %

            % correlation (performed in frequency domain)
            resp = cv.mulSpectrums(cv.dft(img, 'ComplexOutput',true), ...
                obj.H, 'ConjB',true);
            resp = cv.dft(resp, 'Inverse',true, 'Scale',true, 'RealOutput',true);

            % max value location in correlation response
            [mval, midx] = max(resp(:));
            [my,mx] = ind2sub(size(resp), midx);
            mloc = [mx my]; %TODO: -1 ??

            % offset from center
            d = mloc - floor([size(resp,2) size(resp,1)] / 2);

            % compute PSR
            sidelobe = cv.rectangle(resp, mloc-5, mloc+5, ...
                'Color',NaN, 'Thickness',-1);
            sidelobe = sidelobe(~isnan(sidelobe));
            psr = (mval - mean(sidelobe)) / std(sidelobe);
        end

        function update_kernels(obj, img, rate)
            %UPDATE_KERNELS  Update correlation kernels
            %
            %     obj.update_kernels(img)
            %     obj.update_kernels(img, rate)
            %
            % ## Input
            % * __img__ processed image
            % * __rate__ learning rate
            %

            F = cv.dft(img, 'ComplexOutput',true);
            H_1 = cv.mulSpectrums(obj.G, F, 'ConjB',true);
            H_2 = cv.mulSpectrums(    F, F, 'ConjB',true);

            if nargin < 3
                % initialization phase
                obj.H1 = obj.H1 + H_1;
                obj.H2 = obj.H2 + H_2;
            else
                % update phase
                obj.H1 = obj.H1 * (1 - rate) + H_1 * rate;
                obj.H2 = obj.H2 * (1 - rate) + H_2 * rate;
            end

            obj.H = complex(obj.H1(:,:,1), obj.H1(:,:,2)) ./ ...
                    complex(obj.H2(:,:,1), obj.H2(:,:,2));
            obj.H = cat(3, real(obj.H), -imag(obj.H));
        end
    end
end

function img = random_warp(img, coef)
    %RANDOM_WARP  Warp image using a random affine transformation
    %
    %     img = random_warp(img)
    %     img = random_warp(img, coef)
    %
    % ## Input
    % * __img__ input image
    %
    % ## Output
    % * __img__ output warped image
    % * __coef__ randomness coefficient, default 0.2
    %

    if nargin < 2, coef = 0.2; end
    ang = (rand() - 0.5) * coef;
    T = [cos(ang) -sin(ang); sin(ang) cos(ang)];
    T = T + (rand(2) - 0.5) * coef;

    sz = [size(img,2); size(img,1)];
    c = fix(sz / 2);
    T(:,3) = c - T * c;

    img = cv.warpAffine(img, T, 'DSize',sz, 'BorderType','Reflect');
end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
% mff_importpnsset - import information from MFF 'pnsSet.xml' file
%
% Usage:
%   chaninfo = mff_importpnsset(mffFile);
%
% Inputs:
%  mffFile - filename/foldername for the MFF file
%
% Output:
%  chaninfo - EEGLAB channel location structure

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

function [chaninfo, rVal] = mff_importpnsset(mffFile)

chanlocs = [];
rVal = true;

p = fileparts(which('mff_importsignal.m'));
warning('off', 'MATLAB:Java:DuplicateClass');
javaaddpath(fullfile(p, 'MFF-1.2.2-jar-with-dependencies.jar'));
warning('on', 'MATLAB:Java:DuplicateClass');

% Create an MFFFactory object.
mfffactorydelegate = javaObject('com.egi.services.mff.api.LocalMFFFactoryDelegate');
mfffactory = javaObject('com.egi.services.mff.api.MFFFactory', mfffactorydelegate);

% Create Signal object and read in event track file.
% Note that 3 is the value associated with the event track resource type.
pnsURI = fullfile(mffFile, 'pnsSet.xml');
pnsType = javaObject('com.egi.services.mff.api.MFFResourceType', javaMethod('valueOf', 'com.egi.services.mff.api.MFFResourceType$MFFResourceTypes', 'kMFF_RT_PNSSet'));
pns = mfffactory.openResourceAtURI(pnsURI, pnsType);

chaninfo = [];
if ~isempty(pns)

    if pns.loadResource()

        sensors = pns.getPNSSensors();

        if ~isempty(sensors )

            for iSensor = 1:sensors.size
                sensor = sensors.get(iSensor-1);
                chaninfo(iSensor).labels = char(sensor.getName);
                chaninfo(iSensor).type   = 'PNS';
            end

        end
    else
        fprintf('Error: pnsSet ressource is null\n');
        rVal = false;
    end

else

    rVal = false;

end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function  [fx,dfdx,dfdP] = f_Qlearn2(x,P,u,in)
% evolution function of q-values of a RL agent (2-armed bandit problem)
% [fx,dfdx,dfdP] = f_Qlearn2(x,P,u,in)
% Here, there are only two q-values to evolve, i.e. there are only two
% actions to reinforce (2-armed bandit problem).
% IN:
%   - x_t : q-values (2x1)
%   - P : (inverse-sigmoid) learning-rate
%   - u : u(1)=previous action (1 or 0), u(2)=feedback
%   - in : [useless]
% OUT:
%   - fx: evolved q-values (2x1)
%   - dfdx/dfdP: gradient of the q-values evolution function, wrt q-avlues
%   and evolution parameter, respectively.

alpha = 1./(1+exp(-P)); % learning rate is bounded between 0 and 1.
fx = zeros(2,1);
pe = u(2)-x; % prediction error
fx(1) = x(1) + alpha*pe(1)*u(1);
fx(2) = x(2) + alpha*pe(2)*(1-u(1));
% gradients' derivation
if u(1)==1
    dfdx = [1-alpha, 0;
            0, 1];
    dfdP = [alpha*(1-alpha)*pe(1),0];
else
    dfdx = [1, 0;
            0, 1-alpha];
    dfdP = [0,alpha*(1-alpha)*pe(2)];
end

author: MBB-team

repo: VBA-toolbox


text:
% This class defines how a graph is updated.
% It manages learning rate decay, momentum, gradient and weigth clipping,
% etc.

classdef GraphLearnerSGD
    properties
        % learning rate scheme
        learningRateDecayScheme = 'expDecay';    % [expDecay | decayIfNoImprovement]
        initLearningRate = 1e-2;
        minLearnRate = 1e-4;
        learningRate = 1e-2;
        learningRateDecayPerMilestone = 0.999;
        learningRateDecayPerItr = 0.999;
        nHourSeen = 0;
        reduceLREveryXHour = 0.5;
        nextMilestone = 0.5;

        % momentum scheme
        momentumIncreaseScheme= 'exp';
        initMomentum = 0;
        maxMomentum = 0.9;
        momentum = 0;
        momentumIncreaseSpeed = 1.01;

        rmspropDecay = 0;   % reserved for future

        gradientClipThreshold = 0;
        weightClipThreshold = 0;

        monitorWeightNorm = 0;

        % cache of gradients in previous minibatch
        updateHistory;
    end
    methods
        function obj = GraphLearnerSGD(sigGraph)
            % initialize the update structure used for momentum
            for k=1:length(sigGraph.WeightUpdateOrder)
                obj.updateHistory{k}.W = 0;
                obj.updateHistory{k}.b = 0;
            end
        end

        function obj = accumulateTrainDataDuration(obj, nHourSeen)
            obj.nHourSeen = obj.nHourSeen + nHourSeen;
        end

        function obj = updateLearningRateEndOfBlock(obj)
            if obj.nHourSeen > obj.nextMilestone
                obj.learningRate     = obj.learningRate * obj.learningRateDecayPerMilestone;   % Learning rate for biases of hidden units
                fprintf('Trained with %2.2f hours of data, reducing learning rate to %f\n', obj.nHourSeen, obj.learningRate);
                obj.nextMilestone = obj.nextMilestone + obj.reduceLREveryXHour;
            end
        end

        function obj = updateLearningRateEndOfIteration(obj)
            switch obj.learningRateDecayScheme
                case 'decayIfNoImprovement'     % if CV cost does not decrease, reduce the learning rate
                    % to be implemented
                case 'expDecay'     % decay the learning rate no matter what happens to the CV cost. Run until a preset number of iterations is finished.
                    obj.learningRate = obj.learningRate * obj.learningRateDecayPerItr;
            end
        end
        function sigGraph = updateGraph(obj, sigGraph)
            WeightUpdateOrder = sigGraph.WeightUpdateOrder;
            layer = sigGraph.layer;
            curr_momentum = obj.momentum;

            total_weight_norm = 0;

            if isnan(layer{end}.a)
                % Sometimes, we get nan cost function. Then we should ignore current mismatch.
                % Cases that causes nan cost function: 1) in single precision, if the
                % input of softmax is too big, it will cause nan as the exp(input) is inf.
                fprintf('Warning: nan cost detected, abort updating graph!\n');
                return;
            end

            for i=1:length(WeightUpdateOrder)
                Lidx = WeightUpdateOrder{i};
                [~, isTranspose] = obj.VerifyTiedLayers(layer(Lidx));

                % collect gradients
                gradW = layer{Lidx(1)}.gradW;
                if sum(isnan(gradW(:)))
                    pause(0.1);
                end
                for k=2:length(Lidx)
                    if isTranspose(k)
                        gradW = gradW + layer{Lidx(k)}.gradW';
                    else
                        gradW = gradW + layer{Lidx(k)}.gradW;
                    end
                end

                if obj.gradientClipThreshold > 0
                    gradW = max(-obj.gradientClipThreshold, gradW);
                    gradW = min(obj.gradientClipThreshold, gradW);
                end

                %     if obj.rmspropDecay > 0
                %         layer{k}.gradW_avg_square = layer{k}.gradW_avg_square * para.rmsprop_decay + ...
                %             layer{k}.gradW.^2 * (1-para.rmsprop_decay);
                %         element_learning_rate = 1./(sqrt(layer{k}.gradW_avg_square)+para.rmsprop_damping);
                %         element_learning_rate = element_learning_rate / ...
                %             sum(sum(element_learning_rate))*numel(element_learning_rate);
                %         update{k}.W = update{k}.W * curr_momentum + ...
                %             gradW.*element_learning_rate * learning_rate;
                %     else
                if issparse(gradW)==0      % apply momentum only when gradient is not sparse
                    obj.updateHistory{i}.W =obj.updateHistory{i}.W * curr_momentum + gradW * obj.learningRate;
                else
                    obj.updateHistory{i}.W = gradW * learning_rate;
                end

                if obj.monitorWeightNorm
                    weight_norm_old = mean(mean(layer{Lidx(1)}.W.^2)) * length(Lidx);
                end

                if issparse(obj.updateHistory{i}.W)
                    layer{Lidx(1)}.W = AddSpMatMat(-1,obj.updateHistory{i}.W, 1, layer{Lidx(1)}.W, 0);
                else
                    layer{Lidx(1)}.W = layer{Lidx(1)}.W - obj.updateHistory{i}.W;
                end

                if obj.weightClipThreshold > 0
                    % sometimes the weight will explode, so we need to add a limit to the value of the weights, e.g. +-10
                    layer{Lidx(1)}.W = max(-obj.weightClipThreshold,layer{Lidx(1)}.W);
                    layer{Lidx(1)}.W = min(obj.weightClipThreshold,layer{Lidx(1)}.W);
                end

                for k=2:length(Lidx)   % copy weights to other tied layers
                    if isTranspose(k)
                        layer{Lidx(k)}.W = layer{Lidx(1)}.W';
                    else
                        layer{Lidx(k)}.W = layer{Lidx(1)}.W;
                    end
                end

                if obj.monitorWeightNorm
                    weight_norm = mean(mean(layer{Lidx(1)}.W.^2)) * length(Lidx);
                    total_weight_norm = total_weight_norm + weight_norm;
                    if weight_norm/weight_norm_old > 1.5
                        fprintf('Warning: layer %d weight norm increases too fast: old norm: %f, new norm %f\n',k,weight_norm_old, weight_norm);
                    end
                end

                has_bias = isprop(layer{Lidx(1)}, 'gradB');

                if has_bias
                    gradB = layer{Lidx(1)}.gradB;
                    for k=2:length(Lidx)
                        if ~isTranspose(k)      % if the layer is a transpose of first layer, its gradB is not used and its b won't be trained
                            gradB = gradB + layer{Lidx(k)}.gradB;
                        end
                    end
                    if obj.rmspropDecay > 0
                        %             layer{k}.gradb_avg_square = layer{k}.gradb_avg_square * para.rmsprop_decay + ...
                        %                 layer{k}.gradB.^2 * (1-para.rmsprop_decay);
                        %             element_learning_rate = 1./(sqrt(layer{k}.gradb_avg_square)+para.rmsprop_damping);
                        %             element_learning_rate = element_learning_rate / ...
                        %                 sum(sum(element_learning_rate))*numel(element_learning_rate);
                        %            obj.updateHistory{k}.b =obj.updateHistory{k}.b * curr_momentum + ...
                        %                 layer{k}.gradB.*element_learning_rate * learning_rate;
                    else
                        if curr_momentum>0
                            obj.updateHistory{i}.b =obj.updateHistory{i}.b * curr_momentum + gradB * obj.learningRate;
                        else
                            obj.updateHistory{i}.b = gradB * obj.learningRate;
                        end
                    end
                    layer{Lidx(1)}.b = layer{Lidx(1)}.b -obj.updateHistory{i}.b;
                    for k=2:length(Lidx)   % copy biases to other tied layers
                        if ~isTranspose(k)
                            layer{Lidx(k)}.b = layer{Lidx(1)}.b;
                        end
                    end
                end
            end
            sigGraph.layer = layer;
        end

    end
    methods (Access = protected)
        function [dimMismatch, isTranspose] = VerifyTiedLayers(obj,tiedLayers)

            for j=1:length(tiedLayers)
                dim(:,j) = tiedLayers{j}.dim;
            end
            dimMismatch = [];
            isTranspose = [];
            for j=2:length(tiedLayers)
                if sum(abs(dim(:,j)-dim(:,1)))
                    if sum(abs(dim(end:-1:1,j)-dim(:,1)))
                        dimMismatch(j) = 1;
                        fprintf('Error: dimension mismatch between layers that share the same weight matrix\n');
                    else
                        isTranspose(j) = 1;
                    end
                else
                    isTranspose(j) = 0;
                end
            end

        end
    end
end

author: singaxiong

repo: SignalGraph


text:
classdef prtClassKnn < prtClass
    % prtClassKnn  K-nearest neighbors classifier
    %
    %    CLASSIFIER = prtClassKnn returns a K-nearest neighbors classifier
    %
    %    CLASSIFIER = prtClassKnn(PROPERTY1, VALUE1, ...) constructs a
    %    prtClassKnn object CLASSIFIER with properties as specified by
    %    PROPERTY/VALUE pairs.
    %
    %    A prtClassKnn object inherits all properties from the abstract class
    %    prtClass. In addition is has the following properties:
    %
    %    k                  - The number of neigbors to be considered
    %    distanceFunction   - The function to be used to compute the
    %                         distance from samples to cluster centers.
    %                         It must be a function handle of the form:
    %                         @(x1,x2)distFun(x1,x2). Most prtDistance*
    %                         functions will work.
    %
    %    For information on the  K-nearest neighbors classifier algorithm, please
    %    refer to the following URL:
    %
    %    http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm
    %
    %    A prtClassKnn object inherits the TRAIN, RUN, CROSSVALIDATE and
    %    KFOLDS methods from prtAction. It also inherits the PLOT method
    %    from prtClass.
    %
    %    Example:
    %
    %     TestDataSet = prtDataGenUnimodal;      % Create some test and
    %     TrainingDataSet = prtDataGenUnimodal;  % training data
    %     classifier = prtClassKnn;           % Create a classifier
    %     classifier = classifier.train(TrainingDataSet);    % Train
    %     classified = run(classifier, TestDataSet);         % Test
    %     classifier.plot;
    %
    %    See also prtClass, prtClassLogisticDiscriminant, prtClassBagging,
    %    prtClassMap, prtClassCap, prtClassBinaryToMaryOneVsAll, prtClassDlrt,
    %    prtClassPlsda, prtClassFld, prtClassRvm, prtClassGlrt,  prtClass

    properties (SetAccess=private)

        name = 'K-Nearest Neighbor'   % K-Nearest Neighbor
        nameAbbreviation = 'KNN'      % KNN
        isNativeMary = true;          % true

    end

    properties

        k = 3;   % The number of neighbors to consider in the voting

        distanceFunction = @(x1,x2)prtDistanceEuclidean(x1,x2);   % Function handle to compute distance
    end

    methods
        function Obj = prtClassKnn(varargin)
            Obj = prtUtilAssignStringValuePairs(Obj,varargin{:});
            Obj.verboseStorage = true;
        end
        function Obj = set.k(Obj,val)
            if ~prtUtilIsPositiveScalarInteger(val)
                error('prt:prtClassKnn:k','k must be a positive scalar integer');
            end
            Obj.k = val;
        end

        function Obj = set.distanceFunction(Obj,val)
            if ~isa(val,'function_handle')
                error('prt:prtClassKnn:distanceFunction','distanceFunction must be a function handle');
            end
            Obj.distanceFunction = val;
        end
    end

    methods (Access=protected, Hidden = true)
        function Obj = preTrainProcessing(Obj,DataSet)
            if ~Obj.verboseStorage
                warning('prtClassKnn:verboseStorage:false','prtClassKnn requires verboseStorage to be true; overriding manual settings');
            end
            Obj.verboseStorage = true;
            Obj = preTrainProcessing@prtClass(Obj,DataSet);
        end
        function Obj = trainAction(Obj,twiddle)
            %Do nothing; we've already specified "verboseStorage = true",
            %so the ".dataSet" field will be set when it comes time to test
        end

        function ClassifierResults = runAction(Obj,PrtDataSet)

            x = getObservations(PrtDataSet);
            n = PrtDataSet.nObservations;

            nClasses = Obj.dataSet.nClasses;
            uClasses = Obj.dataSet.uniqueClasses;
            labels = getTargets(Obj.dataSet);
            y = zeros(n,nClasses);

            xTrain = getObservations(Obj.dataSet);

            largestMatrixSize = prtOptionsGet('prtOptionsComputation','largestMatrixSize');
            memBlock = max(floor(largestMatrixSize/size(xTrain,1)),1);

            if n > memBlock
                for start = 1:memBlock:n
                    indices = start:min(start+memBlock-1,n);

                    distanceMat = feval(Obj.distanceFunction,xTrain,x(indices,:));

                    [twiddle,I] = sort(distanceMat,1,'ascend');
                    I = I(1:Obj.k,:);
                    L = labels(I);

                    % MATLAB indexing is inexplicably different if I is
                    % 1xN or (k>1)xN
                    if Obj.k ~= 1
                        L = L';
                    end

                    for class = 1:nClasses
                        y(indices,class) = sum(L == uClasses(class),2);
                    end
                end
            else
                distanceMat = feval(Obj.distanceFunction,xTrain,x);

                [twiddle,I] = sort(distanceMat,1,'ascend');
                I = I(1:Obj.k,:);
                L = labels(I);

                % MATLAB indexing is inexplicably different if I is
                % 1xN or (k>1)xN
                if Obj.k ~= 1
                    L = L';
                end

                for class = 1:nClasses
                    y(:,class) = sum(L == uClasses(class),2);
                end
            end

            [Etc.nVotes,Etc.MapGuessInd] = max(y,[],2);
            Etc.MapGuess = uClasses(Etc.MapGuessInd);
            ClassifierResults = PrtDataSet;
            ClassifierResults.X = y;

        end

    end
end

author: covartech

repo: PRT

save_path: github-repos/MATLAB/covartech-PRT


text:
filename='Cantileverbeam_Tetrahedra_Linear_Structured_SYM';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance'};
weights = [1];
constraint = {'volume'};
optimizer = 'PROJECTED GRADIENT';
incrementFactor = 1;
designVariable = 'Density';
filterType = 'P1';
constraint_case = 'INEQUALITY';
line_search_initiator = 'INCREASING LAST STEP';
showBC = true;

nsteps = 10;
Vfrac_final = 0.1;
Perimeter_target = 1;
optimality_final = 1e-3;
constr_final =1e-3;

Vfrac_initial = 1;
optimality_initial = 1e-3;
constr_initial = 1e-3;
TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;
TOL.nu_plus = 1/3;
TOL.nu_minus = 1/3;

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function plot_hht(x,Ts)
% Plot the HHT.
% plot_hht(x,Ts)
%
% :: Syntax
%    The array x is the input signal and Ts is the sampling period.
%    Example on use: [x,Fs] = wavread('Hum.wav');
%                    plot_hht(x(1:6000),1/Fs);
% Func : emd

% Get HHT.
imf = emd(x);
for k = 1:length(imf)
   b(k) = sum(imf{k}.*imf{k});
   th   = angle(hilbert(imf{k}));
   d{k} = diff(th)/Ts/(2*pi);
end
[u,v] = sort(-b);
b     = 1-b/max(b);

% Set time-frequency plots.
N = length(x);
c = linspace(0,(N-2)*Ts,N-1);
for k = v(1:2)
   figure, plot(c,d{k},'k.','Color',b([k k k]),'MarkerSize',3);
   set(gca,'FontSize',8,'XLim',[0 c(end)],'YLim',[0 1/2/Ts]); xlabel('Time'), ylabel('Frequency');
end

% Set IMF plots.
M = length(imf);
N = length(x);
c = linspace(0,(N-1)*Ts,N);
for k1 = 0:4:M-1
   figure
   for k2 = 1:min(4,M-k1), subplot(4,1,k2), plot(c,imf{k1+k2}); set(gca,'FontSize',8,'XLim',[0 c(end)]); end
   xlabel('Time');
end

author: Sable

repo: mcbench-benchmarks


text:
% sgwt_check_connected : Check connectedness of graph
%
% function r=sgwt_check_connected(A)
%
% returns 1 if graph is connected, 0 otherwise
% Uses boost graph library breadth first search
%
% Inputs :
% A - adjacency matrix
%
% Outputs :
% r - result
%

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

function r=sgwt_check_connected(A)
  d=bfs(A,1);
  r=~any(d==-1);

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


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

%%
clear; close all; clc;

%% Syntax
% |[groupIndexVertices,groupIndexFaces]=groupVertices(F,V,waitBarOption);|

%% Description
% This function takes in a description of a tesselation, consisting of an
% array F (faces or elements), and V (vertices). The output is represents
% the group index for each point in groupIndexVertices and the group index
% of each face in groupIndexFaces. Vertices which are connected to the same
% mesh obtain the same group indes. Face indices are derived from the
% vertex indices.

%% Examples

%% Example 1: Seperating patch data into groups

%%
% Creating test data consisting of seperates sets faces and vertices

numGroups=3;
F_cell=cell(1,numGroups);
V_cell=cell(1,numGroups);
for q=1:1:numGroups
    switch q
        case 1
            [F,V]=geoSphere(3,1);
        case 2
            [F,V]=stanford_bunny('g');
        case 3
            [F,V]=graphicsModels(3);
    end
%     [F,V]=subtri(F,V,1);
    V=V-mean(V,1);
    V=V./max(V(:));
    V(:,1)=V(:,1)+q*2;
    F_cell{q}=F;
    V_cell{q}=V;
end
[F,V]=joinElementSets(F_cell,V_cell);

%%
% Using |groupVertices| to split the vertices into groups
[groupIndexVertices,groupIndexFaces]=groupVertices(F,V,1);

%%
% Visualizing the resulting grouping

cFigure;
subplot(2,1,1); hold on;
title('Ungrouped')
gpatch(F,V,'kw','none');
axisGeom;
camlight headlight;

subplot(2,1,2); hold on;
title('Grouped')
gpatch(F,V,'kw','none');
scatterV(V,15,groupIndexVertices,'filled');
axisGeom;
camlight headlight;
colormap gjet; icolorbar;
drawnow;

%%
% If desired a second output can be requisted which represents the face
% groupings.

cFigure;
title('Grouped faces')
gpatch(F,V,groupIndexFaces,'none');
axisGeom;
camlight headlight;
colormap gjet; icolorbar;
drawnow;

%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
% GET THE QUATERNION BETWEEN TWO VECTORS
function [q] = qArgument(u,v)
q = zeros(4,1);
% Normalise the quaternion
u = u/norm(u);
v = v/norm(v);
% Get the axis vector
q(2:4) = cross(u,v);
% Define the rotation about that vector
q(1) = sqrt((norm(u)^2)*(norm(v)^2)) + dot(u,v);
% Normalise the quaternion
[q] = unit(q);
end

repo: OpenMAS