text:
classdef SVM
% Definition of SVM model and fuctions used in MCEA/D

%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

% This function is written by Masaya Nakata

    properties
        Problem           % Problem instance defined by PlatEMO
        index             % Index of sub-problem
        x                 % SVM input
        label             % Class of training input
        mdl               % SVM model
        C                 % SVM parameter C
        gamma             % SVM parameter gamma
    end

    methods
        %% Constructor
        function obj = SVM(Problem)
            if nargin == 1
                obj(1, Problem.N) = SVM;
                for i = 1 : length(obj)
                    obj(i).index        = i;
                    obj(i).Problem      = Problem;
                    obj(i).C            = 1.0;
                    obj(i).gamma        = 1.0;
                    obj(i).x            = [];
                    obj(i).label        = [];
                    obj(i).mdl;
                end
            end
        end

        %% Model-construction
        function obj = ModelConstruction(obj, A, B_i, W, Z)
            % Initialization
            indices = [1 : length(A)];
            for i = 1 : length(A)
                obj.x(i, :)     = A(i).dec;
                obj.label(i, 1) = -1;
            end

            % Get the set of current best solutions of neighbor sub-problems
            C_i = [];
            for i = 1 : length(B_i)
                % Calculate scalarization funcion values
                g_data            = max(abs(A(indices).objs - repmat(Z, length(indices), 1)) .* W(B_i(i), :), [], 2);

                % Get the set of current best solution avoiding duplicative selection
                [~, sorted_index] = sort(g_data);
                for j = 1 : length(sorted_index)
                    if ~ismember(sorted_index(j), C_i)
                        C_i = [C_i, sorted_index(j)];
                        obj.label(sorted_index(j), 1) = 1;
                        break
                    end
                end
            end

            % Train SVM
            uniformed_xdata = zeros(length(obj.label), obj.Problem.D);
            for i = 1 : length(obj.label)
                uniformed_xdata(i, :) = obj.UniformInput(obj.x(i, :));
            end
            sigma           = sqrt(1 / (2 * obj.gamma));
            obj.mdl         = fitcsvm(uniformed_xdata, obj.label, 'BoxConstraint', obj.C, 'KernelScale', sigma, 'KernelFunction', 'rbf');
        end

        %% Predict the class of input and get the decision score function value
        function [predicted_class, score] = PredictClass(obj, x)
            % Uniform the input
            uniformed_x = obj.UniformInput(x);

            % Predict the class of input
            [predicted_class, score_list] = obj.mdl.predict(uniformed_x);

            % Return the decision score function value
            score = score_list(2);
        end

        %% Uniform the input
        function uniformed_x = UniformInput(obj, x)
            uniformed_x = ones(1, obj.Problem.D);
            for i = 1 : obj.Problem.D
                x_min = obj.Problem.lower(i);
                x_max = obj.Problem.upper(i);
                uniformed_x(i) = (x(i) - x_min) / (x_max - x_min);
            end
        end

    end
end


text:
function out=isreal(x)

s=builtin('size',x);
out=true;
sx=prod(s);
for ii=1:sx
 ival=x(ii).ival;
 if any(ival~='0')
  out=false;
  break;
 end
end

author: opencobra

repo: cobratoolbox


text:
classdef MOPSOCD < ALGORITHM
% <multi> <real/integer>
% MOPSO with crowding distance

%------------------------------- Reference --------------------------------
% C. R. Raquel and P. C. Naval Jr, An effective use of crowding distance in
% multiobjective particle swarm optimization, Proceedings of the Annual
% Conference on Genetic and Evolutionary Computation, 2005, 257-264.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        function main(Algorithm,Problem)
            %% Generate random population
            Population = Problem.Initialization();
            Archive    = UpdateArchive(Population,Problem.N);
            Pbest      = Population;

            %% Optimization
            while Algorithm.NotTerminated(Archive)
                Gbest      = Archive(randi(ceil(length(Archive)*0.1),1,Problem.N));
                Population = Operator(Problem,Population,Pbest,Gbest);
                Archive    = UpdateArchive([Archive,Population],Problem.N);
                Pbest      = UpdatePbest(Pbest,Population);
            end
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function [node,elem,face]=s2m(v,f,keepratio,maxvol,method,regions,holes,varargin)
%
% [node,elem,face]=s2m(v,f,keepratio,maxvol,method)
% [node,elem,face]=s2m(v,f,keepratio,maxvol,'tetgen',regions,holes)
%
% volumetric mesh generation from a closed surface, shortcut for surf2mesh
%
% author: Qianqian Fang (q.fang at neu.edu)
%
% inputs and outputs are similar to those defined in surf2mesh
%
% if method='cgalpoly', s2m will call cgals2m and keepratio should be a
% structure (as the 'opt' input in cgals2m)
%
% input default values:
%       method: if ignored, iso2mesh uses surf2mesh ('tetgen') to do the
%               tetrahedral mesh generation
%       regions,holes: if ignored, iso2mesh assumes both are empty
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

if(nargin>=5 && strcmp(method,'cgalpoly'))
    [node,elem,face]=cgals2m(v,f,keepratio,maxvol);
    return;
end
if(nargin<=5)
    regions=[];
end
if(nargin<=6)
    holes=[];
end
if(nargin>=5)
    if(nargin>=8)
        [node,elem,face]=surf2mesh(v,f,[],[],keepratio,maxvol,regions,holes,0,method,varargin{:});
    else
        [node,elem,face]=surf2mesh(v,f,[],[],keepratio,maxvol,regions,holes,0,method);
    end
else
    [node,elem,face]=surf2mesh(v,f,[],[],keepratio,maxvol,regions,holes);
end

author: fangq


text:
function check3Color(img)
%
%
%        check3Color(img)
%
%
%        Input:
%           -img: an image to be tested if it is a three color channels
%           image
%
%     Copyright (C) 2011  Francesco Banterle
%
%     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/>.
%

%is a three color channels image?
if(size(img, 3) ~= 3)
    error('The image has to be a three color channels image.');
end

end

author: banterle


text:
function [ PH CH colorScale] = plotSeries(varargin)
%
% [ PH CH colorList ] = plotSeries(AH,x,y,s,colormap,OPTIONS)
%
% Plots x and y data with each column of y color-coded according to scalar
% values defined in s.  plotSeries is particularly useful to illustrate how
% a x-y dataset *changes* in response to some value, s.
%
% Colormap can be defined by a string or a four-column matrix.  When a string
% is used or the argument is left empty, the colormap spans all values of
% s, linearly.  When a four-column matrix is provided, the first column
% corresponds to potential values of s, the other three define the corresponding
% RGB values.  The RGB values used for each column of y are interpolated
% from the rows of colormap, so there is no requirement for the number of
% rows of colormap to match up w/ the length of s.
%
% If length(s) > 1, then a colorbar will be included as a legend for the
% line coloring.
%
% Optional lineseries specifications (OPTIONS) will be applied to all
% plots.
%
% plotSeries outputs a list of plotHandles (PH), a colorbar handle, (CH),
% and the colorList used for the plot.  The colorList output can be used
% directly as the colormap argument for other calls to plotSeries,
% providing a mechanism to easily produce multiple plots using similar
% coloring schemes.
%
%  Example (cut and paste into the command-line):
%
%  % Show how sinc function changes as a function of s
%  s = 1:10;
%  x = (-1:1e-3:1).';
%  y = sinc(x*s);
%  figure; plotSeries(x,y,s,'jet','LineWidth',2);
%  xlabel('x-values');ylabel('y-values');
%
%  Inputs:  AH         - [1x1]       [OPTIONAL]  Axes handle
%           x          - [NxS / Nx1] X-coordinate data
%           y          - [NxS]       Y-coordinate data
%           s          - [1xS]       Scalar value associated with each data series
%                                    (length(s) = size(y,2))
%           colormap   - [Cx4]       Colormap to use for dataset coloring.
%                                    Can be colormap string OR four-column
%                                    colormap with 1st column corresponding to
%                                    potential s values and 3 remaining columns
%                                    corresponding to color.  Note that the
%                                    colormap will be interpolated to find
%                                    the appropriate color for each
%                                    dataset. ([] for 'default' colormap)
%           OPTIONS    -             Optional arguments for plot command
%
%  Outputs: PH         - [Sx1] Plot handle
%           CH         - [1x1] Colorbar handle
%           colorScale - [Sx4] Colormap w/ 1st column corresponding to
%                              s values and 3 remaining columns corresponding to color
%
%  N - Number of x-y coordinates to plot for each dataset
%  S - Number of datasets
%  C - Number of colors provided in colormap
%
% Copyright (c) 2011, Hidden Solutions, LLC
% All rights reserved.
%
% 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 Hidden Solutions, LLC nor the names of any
%      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 HIDDEN SOLUTIONS, LLC 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.
%
% Author: James S. Hall (Hidden Solutions, LLC)
% Date:   17 October 2011
%

% Determine axes handle
if numel(varargin{1}) == 1 && ishandle(varargin{1})
  % If provided, pop AH from list of arguments
  AH       = varargin{1};
  varargin = varargin(2:end);
else
  % Assign current axes
  AH = gca;
end

% Assign x,y,z arguments
x = varargin{1};
y = varargin{2};
z = varargin{3};

% Force to column vectors (if appropriate)
if size(y,1) == 1
  y = y(:);
end
if size(z,1) == 1
  z = z(:);
end

% Generate colorList for plots
if length(varargin)>3 && ~isempty(varargin{4})
  if ischar(varargin{4})
    % If string provided, use as name of colormap
    cmap       = colormap(varargin{4});
    colorScale = [((0:1/(size(cmap,1)-1):1).'*range(z))+min(z) cmap];
  elseif size(varargin{4},2) == 4
    % Assign colormap to axes
    colorScale = varargin{4};
  end
  % Assign colormap to axes
  colormap(AH,colorScale(:,2:4));
else
  % Use default colormap
  cmap       = colormap();
  colorScale = [((0:1/(size(cmap,1)-1):1).'*range(z))+min(z) cmap];
end

% Determine colors to use for each plot
if length(z) > 1
  % Sort colors for interp1
  [cSort cInd] = sort(colorScale(:,1));
  colorScale   = colorScale(cInd,:);
  colorList    = interp1(colorScale(:,1),colorScale(:,2:4),z,'linear',nan);
  % Force s values outside of colorScale(:,1) range to max/min colorScale
  colorList(isnan(colorList(:,1))&z<min(colorScale(:,1)),:) = repmat(colorScale(1,:),sum(isnan(colorList(:,1))&z<min(colorScale(:,1))),1);
  colorList(isnan(colorList(:,1))&z>max(colorScale(:,1)),:) = repmat(colorScale(end,:),sum(isnan(colorList(:,1))&z<min(colorScale(:,1))),1);
else
  % Only one s value provided, use for all plots
  colorList = repmat(colorScale(1,2:4),size(y,2),1);
end

% Plot data
PH = plot(AH,x,y,varargin{5:end});

% Color-code data
for pp = 1:length(PH)
  set(PH(pp),'Color',colorList(pp,:));
end

if length(z) > 1
  % Add colorbar
  caxis([min(z) max(z)]);
  CH = colorbar;
end

end

author: Sable

repo: mcbench-benchmarks


text:
function quad = fit_bounding_quad(ptlist, ori, vp)

[pleft pright pbot2 ptop2 pbot3 ptop3 pleft3 pright3] = ...
    getextremepoints(ptlist, vp);

if ori==1
%     quad.pt(1,1:2) = line_intersect(ptop2, vp{2}, ptop3, vp{3}); % top
%     quad.pt(2,1:2) = line_intersect(ptop2, vp{2}, pbot3, vp{3}); % t2b3
%     quad.pt(3,1:2) = line_intersect(pbot2, vp{2}, ptop3, vp{3}); % b2t3
%     quad.pt(4,1:2) = line_intersect(pbot2, vp{2}, pbot3, vp{3}); % bot
    quad.pt(1,1:2) = line_intersect(ptop2, vp{2}, pleft3, vp{3}); % topleft
    quad.pt(2,1:2) = line_intersect(ptop2, vp{2}, pright3, vp{3}); % topright
    quad.pt(3,1:2) = line_intersect(pbot2, vp{2}, pleft3, vp{3}); % botleft
    quad.pt(4,1:2) = line_intersect(pbot2, vp{2}, pright3, vp{3}); % botleft
    if quad.pt(1,1)>quad.pt(2,1) % || quad.pt(3,1)>quad.pt(4,1)
        quad.pt = quad.pt([2 1 4 3],:);
    end
elseif ori==2
    quad.pt(1,1:2) = line_intersect(pleft,  vp{1}, ptop3, vp{3});  % topleft
    quad.pt(2,1:2) = line_intersect(pright, vp{1}, ptop3, vp{3}); % topright
    quad.pt(3,1:2) = line_intersect(pleft,  vp{1}, pbot3, vp{3});  % botleft
    quad.pt(4,1:2) = line_intersect(pright, vp{1}, pbot3, vp{3}); % botright
    if quad.pt(1,2)>quad.pt(3,2) % || quad.pt(2,2)>quad.pt(4,2)
        quad.pt = quad.pt([3 4 1 2],:);
    end
elseif ori==3
    quad.pt(1,1:2) = line_intersect(pleft,  vp{1}, ptop2, vp{2});  % topleft
    quad.pt(2,1:2) = line_intersect(pright, vp{1}, ptop2, vp{2}); % topright
    quad.pt(3,1:2) = line_intersect(pleft,  vp{1}, pbot2, vp{2});  % botleft
    quad.pt(4,1:2) = line_intersect(pright, vp{1}, pbot2, vp{2}); % botright
end

% % % % % %
% % % % % pt = line_intersect(pleft,vp{1},ptop2,vp{2});
% % % % % junc2(1).pt = pt;
% % % % % junc2(1).type = 1;
% % % % % junc2(1).hclass = 2;
% % % % % junc2(1).vclass = 1;
% % % % % junc2(1).regionid = getregionid(pt(1),pt(2),vp);
% % % % %
% % % % % pt = line_intersect(pright,vp{1},ptop2,vp{2});
% % % % % junc2(2).pt = pt;
% % % % % junc2(2).type = 2;
% % % % % junc2(2).hclass = 2;
% % % % % junc2(2).vclass = 1;
% % % % % junc2(2).regionid = getregionid(pt(1),pt(2),vp);
% % % % %
% % % % % pt = line_intersect(pleft,vp{1},ptop3,vp{3});
% % % % % junc2(3).pt = pt;
% % % % % junc2(3).type = 1;
% % % % % junc2(3).hclass = 3;
% % % % % junc2(3).vclass = 1;
% % % % % junc2(3).regionid = getregionid(pt(1),pt(2),vp);
% % % % %
% % % % % pt = line_intersect(pright,vp{1},ptop3,vp{3});
% % % % % junc2(4).pt = pt;
% % % % % junc2(4).type = 2;
% % % % % junc2(4).hclass = 3;
% % % % % junc2(4).vclass = 1;
% % % % % junc2(4).regionid = getregionid(pt(1),pt(2),vp);
% % % % %
% % % % % %
% % % % % pt = line_intersect(pleft,vp{1},pbot2,vp{2});
% % % % % junc2(5).pt = pt;
% % % % % junc2(5).type = 3;
% % % % % junc2(5).hclass = 2;
% % % % % junc2(5).vclass = 1;
% % % % % junc2(5).regionid = getregionid(pt(1),pt(2),vp);
% % % % %
% % % % % pt = line_intersect(pright,vp{1},pbot2,vp{2});
% % % % % junc2(6).pt = pt;
% % % % % junc2(6).type = 4;
% % % % % junc2(6).hclass = 2;
% % % % % junc2(6).vclass = 1;
% % % % % junc2(6).regionid = getregionid(pt(1),pt(2),vp);
% % % % %
% % % % % pt = line_intersect(pleft,vp{1},pbot3,vp{3});
% % % % % junc2(7).pt = pt;
% % % % % junc2(7).type = 3;
% % % % % junc2(7).hclass = 3;
% % % % % junc2(7).vclass = 1;
% % % % % junc2(7).regionid = getregionid(pt(1),pt(2),vp);
% % % % %
% % % % % pt = line_intersect(pright,vp{1},pbot3,vp{3});
% % % % % junc2(8).pt = pt;
% % % % % junc2(8).type = 4;
% % % % % junc2(8).hclass = 3;
% % % % % junc2(8).vclass = 1;
% % % % % junc2(8).regionid = getregionid(pt(1),pt(2),vp);
% % % % %
% % % % % %
% % % % % pt = line_intersect(ptop2,vp{2},ptop3,vp{3});
% % % % % junc2(9).pt = pt;
% % % % % junc2(9).type = 1;
% % % % % junc2(9).hclass = 3;
% % % % % junc2(9).vclass = 2;
% % % % % junc2(9).regionid = getregionid(pt(1),pt(2),vp);
% % % % %
% % % % % pt = line_intersect(pbot2,vp{2},pbot3,vp{3});
% % % % % junc2(10).pt = pt;
% % % % % junc2(10).type = 3;
% % % % % junc2(10).hclass = 3;
% % % % % junc2(10).vclass = 2;
% % % % % junc2(10).regionid = getregionid(pt(1),pt(2),vp);
% % % % %
% % % % % % ***** TODO: junc11,12: type???
% % % % % pt = line_intersect(ptop2,vp{2},ptop3,vp{3});
% % % % % junc2(11).pt = pt;
% % % % % junc2(11).type = 2;
% % % % % junc2(11).hclass = 3;
% % % % % junc2(11).vclass = 2;
% % % % % junc2(11).regionid = getregionid(pt(1),pt(2),vp);
% % % % %
% % % % % pt = line_intersect(pbot2,vp{2},pbot3,vp{3});
% % % % % junc2(12).pt = pt;
% % % % % junc2(12).type = 4;
% % % % % junc2(12).hclass = 3;
% % % % % junc2(12).vclass = 2;
% % % % % junc2(12).regionid = getregionid(pt(1),pt(2),vp);
% % % % %

author: zouchuhang

repo: LayoutNet


text:
function vw = viewSetROI(vw,param,val,varargin)
%Organize methods for setting view parameters.
%
% This function is wrapped by viewSet. It should not be called by anything
% else other than viewSet.
%
% This function retrieves information from the view that relates to a
% specific component of the application.
%
% We assume that input comes to us already fixed and does not need to be
% formatted again.

if notDefined('vw'),  error('No view defined.'); end
if notDefined('param'), error('No parameter defined'); end
if notDefined('val'),   val = []; end

mrGlobals;

switch param

    case 'roi'
        vw = loadROI(vw, val);
    case 'rois'
        % Set ROI field in view struct. ROIs should be a struct.
        % Example: vw = viewSet(vw, 'ROIs', rois);
        vw.ROIs = val;
    case 'selectedroi'
        vw = selectROI(vw, val);
    case 'selroicolor'
        % Set the color of the currently selected or the requested ROI.
        % This can be a Matlab character for a color ('c', 'w', 'b', etc)
        % or an RGB triplet.
        %   vw = viewSet(vw, 'Selected ROI color', [1 0 0]);
        %   roi = 1; col = 'r'; vw = viewSet(vw, 'Selected ROI color', col, roi);
        if isempty(varargin) || isempty(varargin{1}),
            roi = vw.selectedROI;
        else
            roi = varargin{1};
        end
        vw.ROIs(roi).color = val;
    case 'roioptions'
        if ~isempty(val) && isstruct(val)
            vw = roiSetOptions(vw,val);
        else
            vw = roiSetOptions(vw);
        end
    case 'filledperimeter'
        vw.ui.filledPerimeter = val;
    case 'maskrois'
        vw.ui.maskROIs = val;
    case 'roivertinds'
        msh  = viewGet(vw, 'currentmesh');
        if isempty(msh), return; end

        % Parse varargin for ROIs and prefs
        if isempty(varargin) || isempty(varargin{1}),
            roi = vw.selectedROI;
        else
            roi = varargin{1};
            if isstruct(varargin{end}) && isfield(varargin{end}, 'layerMapMode');
                prefs = varargin{end};
            else
                prefs = mrmPreferences;
            end
        end
        % get ROI mapMode
        if isequal(prefs.layerMapMode, 'layer1'), roiMapMode = 'layer1';
        else roiMapMode = 'any';  end
        vw.ROIs(roi).roiVertInds.(msh.name).(roiMapMode) = val;

    case 'showrois'
        % Select one or more ROIs to show on meshes
        %   -2 = show all ROIs
        %   -1 = show selected ROIs
        %    0 = hide all ROIs
        %   >0 = show those ROIs (e.g., if showROIs = [1 3], then show ROIs
        %           1 and 3).
        % Examples:
        %   vw = viewSet(vw, 'Show ROIs', [1 2]) % show ROIs 1 and 2
        %   vw = viewSet(vw, 'Show ROIs', -2)    % show all ROIs
        if ~checkfields(vw, 'ui'), vw.ui = []; end;
        vw.ui.showROIs = val;

    case 'hidevolumerois'
        % Specifiy whether to show ROIs in volume or gray view. We
        % sometimes choose not to show them because if we click around in
        % the GUI, redrawing the ROIs can be slow.
        %
        % Examples:
        %   vw = viewSet(vw, 'Hide Volume ROIs', true)
        %   vw = viewSet(vw, 'Hide Volume ROIs', false)
        if ~checkfields(vw, 'ui'), vw.ui = []; end
        vw.ui.hideVolumeROIs = val;

    case 'roidrawmethod'
        % Specify how the ROIs will be visualized.
        % Options:
        % 'perimeter'               % outlined ROI
        % 'filled perimeter'        % outlined ROI, but thicker
        % 'boxes'                   % filled in ROI
        % 'patches'                 % translucent patches
        %
        % Examples:
        %   vw = viewSet(vw, 'roidrawmethod', 'filled perimeter')
        if ~checkfields(vw, 'ui'), vw.ui = []; end
        vw.ui.roiDrawMethod = val;
    case 'roiname'
        if isempty(varargin) || isempty(varargin{1})
            roi = vw.selectedROI;
        else
            roi = varargin{1};
        end
        vw.ROIs(roi).name = val;
    case 'roicoords'
        if isempty(varargin)||isempty(varargin{1}), roi = vw.selectedROI;
        else                                        roi = varargin{1}; end

        vw.ROIs(roi).coords = val;

    case 'roimodified'
        if isempty(varargin)||isempty(varargin{1}), roi = vw.selectedROI;
        else                                        roi = varargin{1}; end
        vw.ROIs(roi).modified = val;

    case 'roicomments'
        if isempty(varargin) || isempty(varargin{1})
            roi = vw.selectedROI;
        else
            roi = varargin{1};
        end
        vw.ROIs(roi).comments = val;

    otherwise
        error('Unknown view parameter %s.', param);

end %switch

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function [fallback,dodge_x,dodge_color,dodge_lightness,dodge_ind,dodge_n]=dodge_comp(x,color,lightness,uni_color,uni_lightness)

if iscell(x)
    %If x is given as cell, we don't do the advanced dodging
    fallback=true;
    uni_x=1;
else
    fallback=false;
    uni_x=unique(x);
    %Here we need to implement a loose 'unique' because of
    %potential numerical errors
    uni_x(diff(uni_x)<1e-10)=[];

    %Fallback if there are too many unique x values (dodging only makes
    %sense for discrete x values)... 4000 x unique values is already a lot
    %but quick enough to compute below
    if numel(uni_x)>2000
        fallback=true;
        uni_x=1;
    end
end

N=length(uni_x)*length(uni_color)*length(uni_lightness);

%Initialize return values
dodge_x=zeros(N,1);
if iscell(color)
    dodge_color=cell(N,1);
else
    dodge_color=zeros(N,1);
end
if iscell(lightness)
    dodge_lightness=cell(N,1);
else
    dodge_lightness=zeros(N,1);
end
dodge_ind=zeros(N,1);
dodge_n=zeros(N,1);

ind=1;

%Loop over unique X values and count how many lightness and color values
%there are for each (unless we are in fallback in which case we plan for
%all possible lightness and colors).
for ind_x=1:length(uni_x)

    if ~fallback
        %And here we have a loose selection also because of
        %potential numerical errors
        sel=abs(x-uni_x(ind_x))<1e-10;
    end

    temp_ind=1;

    for ind_color=1:length(uni_color)

        if ~fallback
            sel_color=sel & multi_sel(color,uni_color{ind_color});
        end

        %loop over lightness
        for ind_lightness=1:length(uni_lightness)

            if ~fallback
                sel_lightness=sel_color & multi_sel(lightness,uni_lightness{ind_lightness});
            end

            if fallback || any(sel_lightness)
                dodge_x(ind)=uni_x(ind_x);
                if iscell(color)
                    dodge_color{ind}=uni_color{ind_color};
                else
                    dodge_color(ind)=uni_color{ind_color};
                end
                if iscell(lightness)
                    dodge_lightness{ind}=uni_lightness{ind_lightness};
                else
                    dodge_lightness(ind)=uni_lightness{ind_lightness};
                end
                dodge_ind(ind)=temp_ind;

                temp_ind=temp_ind+1;
                ind=ind+1;
            end
        end
    end

    dodge_n(ind-(temp_ind-1):ind-1)=temp_ind-1;

end

dodge_x=dodge_x(1:ind-1);
dodge_color=dodge_color(1:ind-1);
dodge_lightness=dodge_lightness(1:ind-1);
dodge_ind=dodge_ind(1:ind-1);
dodge_n=dodge_n(1:ind-1);

end

author: piermorel

repo: gramm

save_path: github-repos/MATLAB/piermorel-gramm


text:
% add the path of RBM code
addpath('..');

% load CBCL train
load 'faces.train.mat';
X = X_tra;

% shuffle the training data
perm_idx = randperm (size(X,1));
X = X(perm_idx, :);

% construct RBM and use default configurations
R = default_rbm (size(X, 2), 300);

% use continuous values
R.data.binary = 0;

% set grbm parameters
R.grbm.do_vsample = 1;
R.grbm.do_normalize = 0;
R.grbm.do_normalize_std = 1;
R.grbm.learn_sigmas = 1;

% max. 100 epochs
R.iteration.n_epochs = 100;

% set the stopping criterion
R.stop.criterion = 1;
R.stop.recon_error.tolerate_count = 1000;

% save the intermediate data after every epoch
R.hook.per_epoch = {@save_intermediate, {'grbm_faces.mat'}};

% print learining process
R.verbose = 1;

% display the progress
R.debug.do_display = 0;
R.debug.display_interval = 5;
R.debug.display_fid = 1;
R.debug.display_function = @visualize_grbm;

% train RBM
fprintf(1, 'Training GB-RBM\n');
tic;
R = train_rbm (R, X);
fprintf(1, 'Training is done after %f seconds\n', toc);

% grab some samples from RBM
S = grbm_sample(normrnd(zeros(10,size(X,2)), ones(10,size(X,2))), R, 30, 1000);

figure;
for i=1:10
    subplot(10, 1, i);
    visualize_adv(squeeze(S(i,:,:)), 0, 1, 30, 0, 0);
end

author: kyunghyuncho

repo: deepmat


text:
function btv_test03 ( )

%*****************************************************************************80
%
%% BTV_TEST03 tests BURGERS_TIME_VISCOUS with the gaussian initial condition.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 April 2012
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BTV_TEST03\n' );
  fprintf ( 1, '  Test BURGERS_TIME_VISCOUS with the gaussian initial condition.\n' );
  fprintf ( 1, '  Use a Neumann condition on the right.\n' );

  nx = 81;
  nt = 200;
  t_max = 2.0;
  nu = 0.01;
  bc = 3;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Initial condition: gaussian\n' );
  fprintf ( 1, '  Number of space nodes = %d\n', nx );
  fprintf ( 1, '  Number of time steps = %d\n', nt );
  fprintf ( 1, '  Final time T_MAX = %g\n', t_max );
  fprintf ( 1, '  Viscosity = %g\n', nu );
  fprintf ( 1, '  Boundary condition = %d\n', bc );

  U = burgers_time_viscous ( @ic_gaussian, nx, nt, t_max, nu, bc );

  x = linspace ( -1.0, +1.0, nx );

  figure ( 3 )

  plot ( x, U(1:50:(nt+1),:), 'Linewidth', 3 )
  grid on
  xlabel ( '<-- X -->' )
  ylabel ( '<-- U(X,T) -->' )
  title ( 'Burgers equation solutions over time, initial condition gaussian' )

  filename = 'btv_test03.png';
  print ( '-dpng', filename )
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Saved plot as "%s"\n', filename );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function r8mat_write ( output_filename, m, n, table )

%*****************************************************************************80
%
%% R8MAT_WRITE writes an R8MAT file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 August 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string OUTPUT_FILENAME, the output filename.
%
%    Input, integer M, the spatial dimension.
%
%    Input, integer N, the number of points.
%
%    Input, real TABLE(M,N), the points.
%

%
%  Open the file.
%
  output_unit = fopen ( output_filename, 'wt' );

  if ( output_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8MAT_WRITE - Error!\n' );
    fprintf ( 1, '  Could not open the output file.\n' );
    error ( 'R8MAT_WRITE - Error!' );
    return;
  end
%
%  Write the data.
%
  for j = 1 : n
    for i = 1 : m
      fprintf ( output_unit, '  %24.16f', table(i,j) );
    end
    fprintf ( output_unit, '\n' );
  end
%
%  Close the file.
%
  fclose ( output_unit );

  return
end


text:
function line_num = sphere_llq_line_num ( lat_num, long_num )

%*****************************************************************************80
%
%% SPHERE_LLQ_LINE_NUM counts lines for a latitude/longitude quadrilateral grid.
%
%  Discussion:
%
%    The number returned is the number of pairs of points to be connected.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 October 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer LAT_NUM, LONG_NUM, the number of latitude and
%    longitude lines to draw.  The latitudes do not include the North and South
%    poles, which will be included automatically, so LAT_NUM = 5, for instance,
%    will result in points along 7 lines of latitude.
%
%    Output, integer LINE_NUM, the number of grid lines.
%
  line_num = long_num * ( lat_num + 1 ) ...
           + lat_num * long_num;

  return
end


text:
function [traj, infStates] = tapas_hhmm(r, p, varargin)
% Estimates a hierarchical hidden Markov model (HHMM)
%
% This function can be called in two ways:
%
% (1) hhmm(r, p)
%
%     where r is the structure generated by fitModel and p is the parameter vector in native space;
%
% (2) hhmm(r, ptrans, 'trans')
%
%     where r is the structure generated by fitModel, ptrans is the parameter vector in
%     transformed space, and 'trans' is a flag indicating this.
%
% --------------------------------------------------------------------------------------------------
% Copyright (C) 2013 Christoph Mathys, TNU, UZH & ETHZ
%
% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public
% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version). For further details, see the file
% COPYING or <http://www.gnu.org/licenses/>.

% Transform paramaters back to their native space if needed
if ~isempty(varargin) && strcmp(varargin{1},'trans');
    [p pstruct] = hhmm_transp(r, p);
end

% Fixed configuration elements
%
% Number of possible outcomes
m = r.c_prc.n_outcomes;

% Get model tree (N is for node)
N = pstruct.N;

% Check constraints
if ~isempty(N{1}.V)
    error('tapas:hgf:hhmm:IllegEntryProbRoot', 'Illegal entry probability for root node.');
end

for id = 1:length(N)
    if isempty(N{id}.A) == isempty(N{id}.B)
        error('tapas:hgf:hhmm:IllegCombOfAB', 'Illegal combination of A and B for node no. %d.', id);
    end

    if length(N{id}.children(:)) ~= size(N{id}.A,2)
        error('tapas:hgf:hhmm:NumOfChildIncons', 'Number of children inconsistent with A for node no. %d.', id);
    end

    if ~isempty(N{id}.A) && any(sum(N{id}.A,2)>1)
        error('tapas:hgf:hhmm:IllegA', 'Illegal transition matrix A for node no. %d: row sums have to be less than or equal to 1.', id);
    end

    if ~isempty(N{id}.A)
        for cid = N{id}.children
            cidx = find(N{id}.children==cid);
            if ~isempty(N{cid}.children) && N{id}.A(cidx,cidx) ~= 0
                error('tapas:hgf:hhmm:IllegASelf', 'Illegal transition matrix A for node no. %d: only production nodes may have self-transitions.', id);
            end
        end
    end

    if ~isempty(N{id}.B) && sum(N{id}.B(:))~=1
        error('tapas:hgf:hhmm:IllegB', 'Illegal outcome contingency vector B for node no. %d.', id);
    end

    if ~isempty(N{id}.children)
        Vsum = 0;
        for cid = N{id}.children
            Vsum = Vsum + N{cid}.V;
        end

        if Vsum ~= 1
            error('tapas:hgf:hhmm:IllegV', 'Illegal vertical transition probabilities V from node no. %d.', id);
        end
    end
end

% Flatten the tree into one large transition matrix
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

% Find production nodes
pn = [];
for id = 1:length(N)
    if isempty(N{id}.children)
        pn = [pn, id];
    end
end
flatDim = length(pn);

% Initialize outcome contingency matrix
Bflat = NaN(m,flatDim);

% Fill Bflat
for i = 1:flatDim
    Bflat(:,i) = N{pn(i)}.B';
end

% Check Bflat
if any(~isfinite(Bflat(:)))
    error('tapas:hgf:hhmm:NoOutConMat', 'Could not construct outcome contingency matrix.');
end

% Initialize flattened transitioned matrix
Aflat = NaN(flatDim);

% Fill Aflat
for i = 1:flatDim
    for j = 1:flatDim
        if N{pn(i)}.parent == N{pn(j)}.parent
            % If the production nodes are siblings, read out
            % their parent's A matrix
            pid = N{pn(i)}.parent;
            idx = find(N{pid}.children==pn(i));
            jdx = find(N{pid}.children==pn(j));
            Aflat(i,j) = N{pid}.A(idx,jdx);
        else
            % Otherwise, determine their lowest common ancestor
            % and use that to calculate the transition probability
            caid = ca(N,pn(i),pn(j));
            tp = 1;

            nid  = pn(i);
            pid  = N{nid}.parent;
            nidx = find(N{pid}.children==nid);

            % Move up to one node below lowest common ancestor from start node pn(i)
            while pid ~= caid
                aend = 1-sum(N{pid}.A(nidx,:));
                tp = tp*aend;

                nid = pid;
                pid = N{nid}.parent;
                nidx = find(N{pid}.children==nid);
            end

            % Do the horizontal transition to the ancestral line of target node pn(j)
            ancj = anc(N,pn(j));
            while ancj(1) ~= caid
                ancj(1) = [];
            end
            ancj(1) = [];

            caidxi = nidx;
            caidxj = find(N{caid}.children==ancj(1));
            tp = tp*N{caid}.A(caidxi,caidxj);

            % Go down to the target node pn(j)
            ancj(1) = [];
            while ~isempty(ancj)
                tp = tp*N{ancj(1)}.V;
                ancj(1) = [];
            end

            Aflat(i,j) = tp;
        end
    end
end

% Check Aflat
if any(~isfinite(Aflat(:)))
    error('tapas:hgf:hhmm:NoFlatTransMat', 'Could not flatten transition matrix.');
end

% Calculate prior probabilities of production nodes
pnp = NaN(1,flatDim);
for i = 1:flatDim
    anci = anc(N,pn(i));
    anci(1) = [];
    p = 1;
    while ~isempty(anci)
        p = p*N{anci(1)}.V;
        anci(1) = [];
    end
    pnp(i) = p;
end

% Check pnp
if sum(pnp) ~= 1
    error('tapas:hgf:hhmm:NoPriorProdNodes', 'Cannot calculate prior probabilities of production nodes.');
end

% Input and number of trials
u = r.u(:,1);
n = length(u);

% Initialize alpha-prime
alpr = NaN(n,flatDim);

% alpr(1,:)
altmp = pnp.*Bflat(u(1),:);
llh = sum(altmp);
alpr(1,:) = altmp./llh;

% Pass through alpha-prime update loop
for k = 2:1:n
    if not(ismember(k, r.ign))

        %%%%%%%%%%%%%%%%%%%%%%
        % Effect of input u(k)
        %%%%%%%%%%%%%%%%%%%%%%

        altmp = Bflat(u(k),:).*(alpr(k-1,:)*Aflat);
        llh = sum(altmp);
        alpr(k,:) = altmp./llh;
    else
        alpr(k,:) = alpr(k-1,:);
    end
end

% Predicted states
alprhat = [pnp; alpr];
alprhat(end,:) = [];

% Create result data structure
traj = struct;

traj.alpr    = alpr;
traj.alprhat = alprhat;

% Create matrix needed by observation model
infStates = traj.alpr;

end % function hhmm

% ----------------------------------------------------------------------------------------
% Find lowest common ancestor of nodes
function ca = ca(N,ida,idb)
    % Find ancestors of ida and idb
    anca = anc(N,ida);
    ancb = anc(N,idb);

    % Determine lowest common ancestor
    ca = NaN;
    aa = anca(1);
    ab = ancb(1);
    while aa == ab && ~isempty(anca) && ~isempty(ancb)
        ca = aa;
        anca(1) = [];
        ancb(1) = [];
        aa = anca(1);
        ab = ancb(1);
    end

    if aa == ab
        ca = aa;
    end
end

% ----------------------------------------------------------------------------------------
% Find ancestors of a node
function anc = anc(N,id)
    anc = id;
    idt = N{id}.parent;
    while ~isempty(idt)
        anc = [idt, anc];
        idt = N{idt}.parent;
    end
end

author: translationalneuromodeling

repo: tapas


text:
function [rec,prec,ap] = VOCevaldet(VOCopts,id,cls,draw,display_progress)

if nargin < 5
    display_progress = true;
end

% load test set
[gtids,t]=textread(sprintf(VOCopts.imgsetpath,VOCopts.testset),'%s %d');

% load ground truth objects
tic;
npos=0;
gt(length(gtids))=struct('BB',[],'diff',[],'det',[]);
for i=1:length(gtids)
    % display progress
    if display_progress && toc>1
        fprintf('%s: pr: load: %d/%d\n',cls,i,length(gtids));
        drawnow;
        tic;
    end

    % read annotation
    rec=PASreadrecord(sprintf(VOCopts.annopath,gtids{i}));

    % extract objects of class
    clsinds=strmatch(cls,{rec.objects(:).class},'exact');
    gt(i).BB=cat(1,rec.objects(clsinds).bbox)';
    gt(i).diff=[rec.objects(clsinds).difficult];
    gt(i).det=false(length(clsinds),1);
    npos=npos+sum(~gt(i).diff);
end

% load results
[ids,confidence,b1,b2,b3,b4]=textread(sprintf(VOCopts.detrespath,id,cls),'%s %f %f %f %f %f');
BB=[b1 b2 b3 b4]';

% sort detections by decreasing confidence
[sc,si]=sort(-confidence);
ids=ids(si);
BB=BB(:,si);

% assign detections to ground truth objects
nd=length(confidence);
tp=zeros(nd,1);
fp=zeros(nd,1);
tic;
for d=1:nd
    % display progress
    if display_progress && toc>1
        fprintf('%s: pr: compute: %d/%d\n',cls,d,nd);
        drawnow;
        tic;
    end

    % find ground truth image
    i=strmatch(ids{d},gtids,'exact');
    if isempty(i)
        error('unrecognized image "%s"',ids{d});
    elseif length(i)>1
        error('multiple image "%s"',ids{d});
    end

    % assign detection to ground truth object if any
    bb=BB(:,d);
    ovmax=-inf;
    for j=1:size(gt(i).BB,2)
        bbgt=gt(i).BB(:,j);
        bi=[max(bb(1),bbgt(1)) ; max(bb(2),bbgt(2)) ; min(bb(3),bbgt(3)) ; min(bb(4),bbgt(4))];
        iw=bi(3)-bi(1)+1;
        ih=bi(4)-bi(2)+1;
        if iw>0 & ih>0
            % compute overlap as area of intersection / area of union
            ua=(bb(3)-bb(1)+1)*(bb(4)-bb(2)+1)+...
               (bbgt(3)-bbgt(1)+1)*(bbgt(4)-bbgt(2)+1)-...
               iw*ih;
            ov=iw*ih/ua;
            if ov>ovmax
                ovmax=ov;
                jmax=j;
            end
        end
    end
    % assign detection as true positive/don't care/false positive
    if ovmax>=VOCopts.minoverlap
        if ~gt(i).diff(jmax)
            if ~gt(i).det(jmax)
                tp(d)=1;            % true positive
		gt(i).det(jmax)=true;
            else
                fp(d)=1;            % false positive (multiple detection)
            end
        end
    else
        fp(d)=1;                    % false positive
    end
end

% compute precision/recall
fp=cumsum(fp);
tp=cumsum(tp);
rec=tp/npos;
prec=tp./(fp+tp);

% compute average precision

ap=0;
for t=0:0.1:1
    p=max(prec(rec>=t));
    if isempty(p)
        p=0;
    end
    ap=ap+p/11;
end

if draw
    % plot precision/recall
    plot(rec,prec,'-');
    grid;
    xlabel 'recall'
    ylabel 'precision'
    title(sprintf('class: %s, subset: %s, AP = %.3f',cls,VOCopts.testset,ap));
end

author: ShaoqingRen


text:
function k = mlpardKernDiagCompute(kern, x)

% MLPARDKERNDIAGCOMPUTE Compute diagonal of MLPARD kernel.
% FORMAT
% DESC computes the diagonal of the kernel matrix for the automatic relevance determination multi-layer perceptron kernel given a design matrix of inputs.
% ARG kern : the kernel structure for which the matrix is computed.
% ARG x : input data matrix in the form of a design matrix.
% RETURN k : a vector containing the diagonal of the kernel matrix
% computed at the given points.
%
% SEEALSO : mlpardKernParamInit, kernDiagCompute, kernCreate, mlpardKernCompute
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006

% KERN

scales = sparse(diag(sqrt(kern.inputScales)));
x = x*scales;
numer = sum(x.*x, 2)*kern.weightVariance + kern.biasVariance;
denom = numer+1;
k = kern.variance*2/pi*asin(numer./denom);

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function sout = cvx_profile( flag )

% CVX_PROFILE	CVX-specific profiler control.
%    This is a function used for internal CVX development to help determine
%    performance limits within the CVX code itself, by turning off the profiler
%    when the solver is being called. End users will likely not find this
%    function to be useful.

global cvx___
cvx_global
s = cvx___.profile;
if nargin == 1,
    if isnumeric(flag) || islogical(flag),
        ns = double(flag) ~= 0;
    elseif ischar(flag) && size(flag,1) == 1,
        switch lower(flag),
            case { 'true', 'on' },
                ns = true;
            case { 'false', 'off' },
                ns = false;
            otherwise,
                cvx_throw( 'String arugment must be ''true''/''on'' or ''false''/''off''.' );
        end
    else
        cvx_throw( 'Argument must be a numeric scalar or a string.' );
    end
    if cvx___.profile ~= ns,
        cvx___.profile = ns;
        stat = profile('status');
        if ns && ~isempty( cvx___.problems ) && ~isequal( stat.ProfilerStatus, 'on' ),
            profile on
        elseif ~ns && isequal( stat.ProfilerStatus, 'on' ),
            profile off
        end
    end
end
if nargin == 0 || nargout > 0,
    sout = s;
end

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

author: yu-jiang

repo: radpbook

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


text:
classdef AllEdges2CutEdgesComputer < handle

    properties (GetAccess = public, SetAccess = private)
        nCutEdgeByElem
    end

   properties (Access = private)
        isEdgeCutInElem
   end

   methods (Access = public)

       function obj = AllEdges2CutEdgesComputer(cParams)
          obj.init(cParams)
       end

       function edge = compute(obj,allEdges)
            nElem = size(allEdges,1);
            allEdges = transpose(allEdges);
            cutEdges = allEdges(obj.isEdgeCutInElem);
            cutEdges = reshape(cutEdges,obj.nCutEdgeByElem,nElem);
            edge     = transpose(cutEdges);
       end

   end

   methods (Access = private)

       function init(obj,cParams)
           obj.isEdgeCutInElem = cParams.isEdgeCutInElem;
           obj.nCutEdgeByElem = unique(sum(obj.isEdgeCutInElem,1));
       end

   end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
%%*******************************************************************
%% schurmat_sblk: compute Schur complement matrix corresponding to
%%                SDP blocks.
%%
%% symm = 0, HKM
%%      = 1, NT
%%*****************************************************************
%% SDPT3: version 4.0
%% Copyright (c) 1997 by
%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************

   function schur = schurmat_sblk(blk,At,par,schur,p,X,Y)

   global  nnzschur nzlistschur

   iter = par.iter;
   smallblkdim = par.smallblkdim;

   if isempty(smallblkdim); smallblkdim = 50; end
   if (nargin == 7); symm = 0; else; symm = 1; Y = X; end;
   m = length(schur);
   pblk = blk(p,:);
   if (iter == 1)
      nnzschur(size(blk,1),1) = m*m;
      nzlistschur = cell(size(blk,1),1);
   end
%%
   if (max(pblk{2}) > smallblkdim) | (length(pblk{2}) <= 10)
      %%
      %% compute schur for matrices that are very sparse.
      %%
      m1 = size(At{p,1},2);
      if issparse(schur); schur = full(schur); end;
      J = min(m1, max(find(par.nzlistA{p,1} < inf))-1);
      if (J > 0)
         if issparse(X{p}) & ~issparse(Y{p}); X{p} = full(X{p}); end
         if ~issparse(X{p}) & issparse(Y{p}); Y{p} = full(Y{p}); end
         if (iter <= 3)
            [schur,nnzschur(p),nzlisttmp] = mexschur(pblk,At{p,1},par.nzlistA{p,1},...
            par.nzlistA{p,2},par.permA(p,:),Y{p},X{p},J,symm,schur);
            if (nnzschur(p) == mexnnz(nzlisttmp))
               nzlistschur{p} = nzlisttmp;
            else
               nzlistschur{p} = [];
            end
         else
            if isempty(nzlistschur{p})
               schur = mexschur(pblk,At{p,1},par.nzlistA{p,1},...
               par.nzlistA{p,2},par.permA(p,:),Y{p},X{p},J,symm,schur);
            else
               schur = mexschur(pblk,At{p,1},par.nzlistA{p,1},...
               par.nzlistA{p,2},par.permA(p,:),Y{p},X{p},J,symm,schur,nzlistschur{p});
            end
         end
      end
      %%
      %% compute schur for matrices that are not so sparse or dense.
      %%
      if (m1 < m) %% for low rank constraints
         ss = [0, cumsum(pblk{3})];
         len = sum(pblk{3});
         dd = At{p,3};
         DD = spconvert([dd(:,2:4); len,len,0]);
         XVD = X{p}*At{p,2}*DD;
         YVD = Y{p}*At{p,2}*DD;
      end
      L = max(find(par.nzlistAsum{p,1} < inf)) -1;
      if (J < L)
         len = par.nzlistAsum{p,1}(J+1); list = par.nzlistAsum{p,2}(1:len,:);
      end
      if (m1 > 0)
         for k = J+1:m
            if (k<=m1)
               isspAk = par.isspA(p,k);
               Ak = mexsmat(blk,At,isspAk,p,k);
               if (k <= L)
                  idx1 = par.nzlistAsum{p,1}(k)+1; idx2 = par.nzlistAsum{p,1}(k+1);
                  list = [list; par.nzlistAsum{p,2}(idx1:idx2,:)];
                  list = sortrows(list,[2 1]);
                  tmp = Prod3(pblk,X{p},Ak,Y{p},symm,list);
               else
                  tmp = Prod3(pblk,X{p},Ak,Y{p},symm);
               end
            else %%--- for low rank constraints
               idx = [ss(k-m1)+1 :ss(k-m1+1)];
               tmp = XVD(:,idx)* (Y{p}*At{p,2}(:,idx))';
            end
            if (~symm)
               tmp = 0.5*(mexsvec(pblk,tmp) + mexsvec(pblk,tmp'));
            else
               tmp = mexsvec(pblk,tmp);
            end
            permk = par.permA(p,k);
            idx  = par.permA(p,1:min(k,m1));
            tmp2 = schur(idx,permk) + mexinprod(blk,At,tmp,min(k,m1),p);
            schur(idx,permk) = tmp2;
            schur(permk,idx) = tmp2';
         end
      end
      if (m1 < m) %% for low rank constraints
         m2 = m - m1;
         XVtmp = XVD'*At{p,2};
         YVtmp = At{p,2}'*YVD;
         for k = 1:m2
            idx0 = [ss(k)+1 : ss(k+1)];
            tmp = XVtmp(:,idx0) .* YVtmp(:,idx0);
            tmp = tmp*ones(length(idx0),1);
            tmp3 = schur(m1+[1:m2],m1+k) + mexqops(pblk{3},tmp,ones(length(tmp),1),1);
            schur(m1+[1:m2],m1+k) = tmp3;
         end
      end
   else
      %%--- for SDP block where each sub-block is small dimensional
      if issparse(X{p}) & ~issparse(Y{p}); Y{p} = sparse(Y{p}); end
      if ~issparse(X{p}) & issparse(Y{p}); X{p} = sparse(X{p}); end
      tmp = mexskron(pblk,X{p},Y{p});
      schurtmp = At{p,1}'*tmp*At{p,1};
      %% schurtmp = 0.5*(schurtmp + schurtmp');
      if (norm(par.permA(p,:)-[1:m]) > 0)
         Perm = spconvert([(1:m)', par.permA(p,:)', ones(m,1)]);
         schur = schur + Perm'*schurtmp*Perm;
      else
         schur = schur + schurtmp;
      end
   end
%%*******************************************************************

author: shamilmamedov


text:
classdef S2AxisFieldTri < S2AxisField
% a class represeneting a function on the sphere

  properties
    tri       % S2Triangulation
    values = vector3d  % function values
  end

  properties (Dependent = true)
    vertices
    antipodal
  end

  methods

    function sVF = S2AxisFieldTri(nodes,values)
      % initialize a spherical vector field

      if nargin == 0, return; end

      if isa(nodes,'function_handle')
        n = equispacedS2Grid('resolution',1.5*degree);
        values = nodes(n);
        nodes = n;
      end

      if isa(nodes,'S2Triangulation')
        sVF.tri = nodes;
      else
        sVF.tri = S2Triangulation(nodes);
      end

      sVF.values = values;

    end

    function v = get.vertices(S2F)
      v = S2F.tri.vertices;
    end

    function v = get.antipodal(S2F)
      v = S2F.tri.antipodal;
    end

    function S2F = set.vertices(S2F,v)
      if ~isempty(S2F.values), S2F.values = S2F.eval(v); end
      S2F.tri.vertices = v;
      S2F.tri.update;
    end

  end

end

author: mtex-toolbox

repo: mtex

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


text:
clear all;
close all;
clc;
result = merge_results('ssc_nn_omp');
plot_bench_results(result, 'ssc_nn_omp');

author: indigits

repo: sparse-plex


text:
function [dist,binned,stats] = CircularDistribution(angles,varargin)

%CircularDistribution - Compute circular distribution and statistics.
%
%  USAGE
%
%    [dist,binned,stats] = CircularDistribution(angles,<options>)
%
%    angles         angles in radians
%    <options>      optional list of property-value pairs (see table below)
%
%    =========================================================================
%     Properties    Values
%    -------------------------------------------------------------------------
%     'nBins'       number of bins (default = 100)
%     'smooth'      standard deviation of Gaussian kernel (default = 0)
%     'groups'      groups for multiple circular distributions (see below)
%    =========================================================================
%
%  OUTPUT
%
%    dist           circular distribution (one column per group)
%    binned         centers of the angular bins
%    stats.m        mean angle (one per group)
%    stats.mode     distribution mode (one per group)
%    stats.r        mean resultant length (one per group)
%    stats.k        concentration (one per group)
%    stats.p        p-value for Rayleigh test (one per group)
%
%  NOTE
%
%    For multiple circular distributions, groups can be indicated in two different
%    manners:
%
%     - a vector of group IDs (one per angle)
%     - a logical matrix (one line per angle, one column per group), where
%       the element (i,j) is 1 iff angle i belongs to group j
%
%    The vector form is convenient when each angle can only belong to one group.
%    The matrix form is useful when a single angle can belong to multiple groups.
%
%  SEE
%
%    See also PlotCircularDistribution.

% Copyright (C) 2011-2012 by Michaël Zugaro
%
% 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.

% Default values
nBins = 100;
smooth = 0;

% Check number of parameters
if nargin < 1 | mod(length(varargin),2) ~= 0,
  error('Incorrect number of parameters (type ''help CircularDistribution'' for details).');
end

% Check parameter size
if ~isdvector(angles),
	error('Incorrect angles (type ''help CircularDistribution'' for details).');
end
angles = angles(:);
groups = ones(size(angles));

% Parse parameter list
for i = 1:2:length(varargin),
  if ~ischar(varargin{i}),
    error(['Parameter ' num2str(i+2) ' is not a property (type ''help CircularDistribution'' for details).']);
  end
  switch(lower(varargin{i})),
    case 'nbins',
      nBins = varargin{i+1};
      if ~isiscalar(nBins,'>0'),
        error('Incorrect value for property ''nBins'' (type ''help CircularDistribution'' for details).');
      end
    case 'smooth',
      smooth = varargin{i+1};
      if ~isdscalar(smooth,'>=0'),
        error('Incorrect value for property ''smooth'' (type ''help CircularDistribution'' for details).');
      end
    case 'groups',
      groups = varargin{i+1};
      if ~isdvector(groups,'>0') && ~islmatrix(groups),
        error('Incorrect value for property ''groups'' (type ''help CircularDistribution'' for details).');
      end
      if isdvector(groups), groups = groups(:); end
      if length(angles) ~= size(groups,1),
        error('Phases and groups have different numbers of lines (type ''help CircularDistribution'' for details).');
      end
    otherwise,
      error(['Unknown property ''' num2str(varargin{i}) ''' (type ''help CircularDistribution'' for details).']);
  end
end

% Angle bins
binned = linspace(0,2*pi,nBins+1)';binned(end) = [];
binSize = binned(2)-binned(1);
binned = binned + binSize/2;

% Groups: transform vector form into matrix form
if isdvector(groups),
	groupIDs = unique(groups);
	nGroups = max(groupIDs);
	g = groups;
	groups = logical(zeros(length(g),nGroups));
	for i = 1:nGroups,
		groups(g==i,i) = 1;
	end
end

% Loop through groups
nGroups = size(groups,2);
for i = 1:nGroups,
	% Distribution
	p = angles(groups(:,i));
	h = Smooth(hist(p,binned),smooth);h = h/sum(h);
	dist(:,i) = h;
	% Stats
	if ~isempty(p)
      [stats.m(i)] = circ_mean(p);
      [stats.r(i)] = circ_r(p);
	  stats.k(i) = Concentration(p);
	  n = sum(groups(:,i));
	  R = stats.r(i)*n;
	  stats.p(i) = exp(sqrt(1+4*n+4*(n^2-R^2))-(1+2*n)); % Zar, Biostatistical Analysis, p. 617
	  x = find(h==max(h));x = x(1);
	  stats.mode(i) = binned(x);
	else
	  stats.m(i)=NaN;
	  stats.r(i)=NaN;
	  stats.k(i)=NaN;
	  stats.p(i)=NaN;
	  stats.mode(i)=NaN;
	end
end

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
classdef MaOEADDFC < ALGORITHM
% <multi/many> <real/integer/label/binary/permutation>
% Many-objective evolutionary algorithm based on directional diversity and
% favorable convergence
% K --- 5 --- The number of neighbors for estimating density
% L --- 3 --- The number of candidates for convergence-based selection

%------------------------------- Reference --------------------------------
% J. Cheng, G. G. Yen, and G. Zhang, A many-objective evolutionary
% algorithm with enhanced mating and environmental selections, IEEE
% Transactions on Evolutionary Computation, 2015, 19(4): 592-605.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        function main(Algorithm,Problem)
            %% Parameter setting
            [K,L] = Algorithm.ParameterSet(5,3);

            %% Generate random population
            Population = Problem.Initialization();
            Zmin       = min(Population.objs,[],1);

            %% Optimization
            while Algorithm.NotTerminated(Population)
                MatingPool = MatingSelection(Population.objs,Zmin);
                Offspring  = OperatorGA(Problem,Population(MatingPool));
                Zmin       = min([Zmin;Offspring.objs],[],1);
                Population = EnvironmentalSelection([Population,Offspring],Zmin,Problem.N,K,L);
            end
        end
    end
end

author: BIMK


text:
function s = ymdf_to_s_roman ( y, m, d, f )

%*****************************************************************************80
%
%% YMDF_TO_S_ROMAN writes a Roman YMDF date into a string.
%
%  Example:
%
%     Y  M   D  F    S
%    --  -  --  ---  -----------------------------------
%    56  4   1  0.1  Kalends Aprilis DVI AUC
%    56  4   2  0.2  Ante diem iv Nones Aprilis DVI AUC
%    56  4   3  0.3  Ante diem iii Nones Aprilis DVI AUC
%    56  4   4  0.4  Pridie Nones Aprilis DVI AUC
%    56  4   5  0.5  Nones Aprilis DVI AUC
%    56  4   6  0.6  Ante diem viii Ides Aprilis DVI AUC
%    56  4   7  0.7  Ante diem vii Ides Aprilis DVI AUC
%    56  4   8  0.8  Ante diem vi Ides Aprilis DVI AUC
%    56  4   9  0.9  Ante diem v Ides Aprilis DVI AUC
%    56  4  10  0.0  Ante diem iv Ides Aprilis DVI AUC
%    56  4  11  0.0  Ante diem iii Ides Aprilis DVI AUC
%    56  4  12  0.0  Pridie Ides Aprilis DVI AUC
%    56  4  13  0.0  Ides Aprilis DVI AUC
%    56  4  14  0.0  Ante diem xvii Kalends Maius DVI AUC
%    56  4  15  0.0  Ante diem xvi Kalends Maius DVI AUC
%    ...
%    56  4  28  0.0  Ante diem iv Kalends Maius DVI AUC
%    56  4  29  0.0  Ante diem iii Kalends Maius DVI AUC
%    56  4  30  0.0  Pridie Kalends Maius DVI AUC
%
%  Discussion:
%
%    "AUC" means "ab urbe condita", or "from the founding of the city".
%
%    At the moment, we ignore F.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 March 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, M, D, real F, the YMDF date.
%
%    Output, string S, a string representing the date.
%

%
%  Check the input.
%
  [ y2, m2, d2, ierror ] = ymd_check_roman ( y, m, d );

  if ( ierror ~= 0 )
    s = '?';
    return
  end

  s_month = month_to_month_name_roman ( m2 );
%
%  Get the next month's name.
%
  m3 = i4_wrap ( m2 + 1, 1, 12 );
  s_month_next = month_to_month_name_roman ( m3 );

  nones = month_to_nones_roman ( m2 );
  ides = month_to_ides_roman ( m2 );
  last = month_length_roman ( y2, m2 );

  if ( d2 == 1 )
    s = [ 'Kalends ', s_month ];
  elseif ( d2 < nones - 1 )
    jday = nones + 1 - d2;
    s_day = i4_to_roman ( jday );
    s = [ 'Ante diem ', s_day, ' Nones ', s_month ];
  elseif ( d2 == nones - 1 )
    s = [ 'Pridie Nones ', s_month ];
  elseif ( d2 == nones )
    s = [ 'Nones ', s_month ];
  elseif ( d2 < ides - 1 )
    jday = ides + 1 - d2;
    s_day = i4_to_roman ( jday );
    s = [ 'Ante diem ', s_day, ' Ides ', s_month ];
  elseif ( d2 == ides - 1 )
    s = [ 'Pridie Ides ', s_month ];
  elseif ( d2 == ides )
    s = [ 'Ides ', s_month ];
  elseif ( m2 == 2 && year_is_leap_roman ( y2 ) )

    if ( d2 < 25 )
      jday = last + 1 - d2;
      s_day = i4_to_roman ( jday );
      s = [ 'Ante diem ', s_day, ' Kalends ', s_month_next ];
    elseif ( d2 == 25 )
      jday = last + 2 - d2;
      s_day = i4_to_roman ( jday );
      s = [ 'Ante diem Bis ', s_day, ' Kalends ', s_month_next ];
    elseif ( d2 < last )
      jday = last + 2 - d2;
      s_day = i4_to_roman ( jday );
      s = [ 'Ante diem ', s_day, ' Kalends ', s_month_next ];
    else
      s = [ 'Pridie Kalends ', s_month_next ];
    end

  elseif ( d2 < last )
    jday = last + 2 - d2;
    s_day = i4_to_roman ( jday );
    s = [ 'Ante diem ', s_day, ' Kalends ', s_month_next ];
  else
    s = [ 'Pridie Kalends ', s_month_next ];
  end

  s_year = i4_to_roman ( y2 );
  s = [ s, ' ', s_year, ' AUC' ];

  s = s_blanks_delete ( s );

  return
end


text:
function ComputingTopOpt_2Stage
% checkout: git checkout origin/master -- path/to/file
% PENDING: AUTOMATIZE THIS FUNCTION WITH GID PICTUREsss
rho0Name = 'TFM.mat';
jumpTo2ndPart = false;

if jumpTo2ndPart == false

%     fileName = 'jaCantilever';
%     % Data input
%     s.testName = [fileName,'.m'];
%     s.x1       = 2;
%     s.y1       = 1;
%     s.N        = 150;
%     s.M        = 75;
%     s.P        = -100;
%     s.DoF      = 2;
%
%     FEMWriter = FEMInputWriter(s);
%     FEMWriter.createTest;

    fileName = 'test_anisotropy_cantilever';
    s = Settings(fileName);
    s.warningHoleBC = false;
    s.printIncrementalIter = false;
    s.printChangingFilter = false;
    s.printing = false;
    translator = SettingsTranslator();
    translator.translate(s);
    fileName = translator.fileName;
    settings  = SettingsTopOptProblem(fileName);
    topOptSolver = TopOpt_Problem(settings);
    while topOptSolver.incrementalScheme.hasNext()
        topOptSolver.incrementalScheme.next();
        topOptSolver.optimizer.solveProblem();
    end

    rho0 = topOptSolver.designVariable.value;
    save(rho0Name,'rho0');

    % GiD Image Capturer:
%     outPutImageName = '"testgidpic"';
%     gidPath = '/home/joseantonio/GiDx64/gid-15.0.4/';
%     tclFile = 'callGiDCapturer.tcl';
%     tclFileTocall = 'CaptureImage3.tcl';
%     fid = fopen('/home/joseantonio/Documentos/GitHub/Swan/PostProcess/ImageCapturer/callGiDCapturer.tcl','w+');
%     fprintf(fid,['set path "/home/joseantonio/Documentos/GitHub/Swan/PostProcess/ImageCapturer','"\n']);
%     fprintf(fid,['set tclFile "',tclFileTocall,'"\n']);
%     fprintf(fid,['source $path$tclFile \n']);
%     fprintf(fid,['set output ',outPutImageName,' \n']);
%     fprintf(fid,['set inputFile "',fileName,'"\n']);
%     fprintf(fid,['CaptureImage $inputFile $output \n']);
%     fclose(fid);
%     command = [gidPath,'gid_offscreen -offscreen -t "source ',tclFile,'"'];
%     system(command);
%     inputImage  = [' ',outPutImageName,'.png'];
%     outPutImage = inputImage;
%     convert     = 'convert -crop 442x442+0+0 -gravity Center';
%     command = strcat(convert,' ',inputImage,' ',outPutImage);
%     system(command);
else
    load(rho0Name);
    fileName = 'test_anisotropy_cantilever_rho0';

    s = Settings(fileName);
    s.warningHoleBC = false;
    s.printIncrementalIter = false;
    s.printChangingFilter = false;
    s.printing = false;
    translator = SettingsTranslator();
    translator.translate(s);
    fileName = translator.fileName;
    settings  = SettingsTopOptProblem(fileName);
    DesignVariable = convertCharsToStrings(settings.designVarSettings.type);
    if  DesignVariable == "Density"
        settings.designVarSettings.creatorSettings.type = 'Given';
        settings.designVarSettings.creatorSettings.rho0 = rho0;
    elseif DesignVariable == "LevelSet"
        settings.designVarSettings.initialCase = 'given';
        settings.designVarSettings.creatorSettings.value = rho0;
    end
    topOptSolver = TopOpt_Problem(settings);
    while topOptSolver.incrementalScheme.hasNext()
        topOptSolver.incrementalScheme.next();
        topOptSolver.optimizer.solveProblem();
    end
end

end


text:
function [cl] = m32cl(m3)
% Convert volume from cubic meters to centiliters.
% Chad Greene 2012
cl = m3*100000;


text:
function [val, pdf] = Sampling1DDistribution(distr, u)
%
%
%        distr = Sampling1DDistribution(distr, u)
%
%
%        Input:
%           -distr: 1D distribution
%           -u: a random value in [0,1]
%
%        Output:
%           -val: index in the distribution of a u-value
%           -pdf: PDF of u
%
%     Copyright (C) 2011  Francesco Banterle
%
%     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/>.
%

[p, val] = min(abs(distr.CDF - u));
pdf = distr.PDF(val);

end

author: banterle


text:
function tests = test_ft_specest_hilbert

% MEM 1gb
% WALLTIME 00:10:00
% DEPENDENCY ft_specest_hilbert

if nargout
  % assume that this is called by RUNTESTS
  tests = functiontests(localfunctions);
else
  % assume that this is called from the command line
  fn = localfunctions;
  for i=1:numel(fn)
    feval(fn{i});
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function testOptions(testCase)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

fsample = 1000;
nchan   = 8;
nsample = 1000;

dat     = randn(nchan, nsample) + 1 + linspace(0,1,nsample);
time    = (0:(nsample-1))/fsample;
verbose = false;
freqoi  = (10:10:100)';
width   = 5;

result = {};

% first explore the different filter types and orders
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but',   'bpfiltord', 2,   'bpfiltdir', 'twopass', 'timeoi', time);
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but',   'bpfiltord', 2,   'bpfiltdir', 'twopass', 'timeoi', time(1:2:end));
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but',   'bpfiltord', 3,   'bpfiltdir', 'twopass', 'timeoi', time(1:2:end));

% bpfiltdir=twopass is the default, use a different filter order for the following ones
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 1, 'bpfiltdir', 'onepass');
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 1, 'bpfiltdir', 'onepass-reverse');
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 1, 'bpfiltdir', 'twopass');
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 1, 'bpfiltdir', 'twopass-reverse');
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 1, 'bpfiltdir', 'twopass-average');

% padtype=zero is the default, use a different filter order for the following ones
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 2, 'bpfiltdir', 'twopass', 'pad', 2, 'padtype', 'zero'      );
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 2, 'bpfiltdir', 'twopass', 'pad', 2, 'padtype', 'mean'      );
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 2, 'bpfiltdir', 'twopass', 'pad', 2, 'padtype', 'localmean' );
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 2, 'bpfiltdir', 'twopass', 'pad', 2, 'padtype', 'edge'      );
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 2, 'bpfiltdir', 'twopass', 'pad', 2, 'padtype', 'mirror'    );

% polyorder=0 is the default, use a different filter order for the following ones
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 3, 'bpfiltdir', 'twopass', 'polyorder', 0);
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 3, 'bpfiltdir', 'twopass', 'polyorder', 1);
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 3, 'bpfiltdir', 'twopass', 'polyorder', 2);
result{end+1} = ft_specest_hilbert(dat, time, 'verbose', verbose, 'freqoi', freqoi, 'width', width, 'bpfilttype', 'but', 'bpfiltord', 3, 'bpfiltdir', 'twopass', 'polyorder', 3);

% all iterations were done with (slightly) different options, hence the results should not be equal
for i=1:numel(result)
  for j=(i+1):numel(result)
    assert(~isequal(result{i}, result{j}), 'the results %d and %d should not be equal', i, j);
  end
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [ state ] = getPin3State( t )
%% This function is used to get the state of the input pin 3
%     on the media flange, of the KUKA iiwa 7 R 800.

%% Syntax:
% [ state ] = getPin3State( t )

%% About:
% This function is used to get the state of the input pin number 3
%  on the media flange, of the KUKA iiwa 7 R 800.

%% Arreguments:
% t: is the TCP/IP connection.
% state:  represents the state of the input-pin. It is an integer equal to
% 1 when the pin state is true, or it is an integer equal to 0 when the
% pin state is false. Otherwise, if the pin is not connected the return
% value is empty.

% Copyright, Mohammad SAFEEA, 9th of May 2017

theCommand='getPin3';
fprintf(t, theCommand);
message=fgets(t);
state=str2num(message);
end

repo: KST-Kuka-Sunrise-Toolbox


text:
%IM_ROTATE Fixed mapping for image rotation
%
%	B = IM_ROTATE(A,ALF)
%	B = A*IM_ROTATE([],ALF)
%	B = A*IM_ROTATE(ALF)
%
% INPUT
%   A        Dataset with object images (possibly multi-band)
%   ALF      Rotation angle (in radians),
%            default: rotation to main axis
%
% OUTPUT
%   B        Dataset with rotated object images
%
% DESCRIPTION
% The objects stored as images in the dataset or datafile A are rotated
% using the IMROTATE command.
%
% SEE ALSO (PRTools Guide)
% DATASETS, DATAFILES, DIP_IMAGE

% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands

function b = im_rotate(varargin)

	argin = shiftargin(varargin,'vector');
  argin = setdefaults(argin,[],[]);
  if mapping_task(argin,'definition')
    b = define_mapping(argin,'fixed');
    b = setname(b,'Image rotate');
  else
    [a,alf] = deal(argin{:});
    if isa(a,'prdataset') % allows datafiles too
%       error('Command cannot be used for datasets as it may change image size')
%     elseif isdatafile(a)
      isobjim(a);
      b = filtim(a,mfilename,{alf});
      b = setfeatsize(b,getfeatsize(a));
    elseif isa(a,'double') || isa(a,'dip_image') % here we have a single image

      a = double(a);

      if isempty(alf)
        m = im_moments(a,'central',[1 2 0; 1 0 2]');
        C = [m(2) m(1); m(1) m(3)];
        [E,D] = preig(C); [dummy,ind] = sort(diag(D));
        alf = atan2(E(2,ind(1)),E(1,ind(1)))+pi/2;
      end

      b = imrotate(a,alf*360/(2*pi),'bilinear','crop');

    end

  end

return

author: marianux

repo: ecg-kit

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


text:
% AGENT CONTROL INPUT TRAJECTORIES
function [currentFigure,figureHandle] = GetFigure_inputs(SIM,objectIndex,DATA,currentFigure)
% Draws the seperations of all agents from each other, neglecting waypoint
% objects.

figureHandle = [];

% SANITY CHECK 1
if DATA.totalAgents == 0
    warning('No agent data available.');
    return
else
    % LOGICALLY SELECT THE AGENTS FROM THE OBJECT INDEX
    agentObjectIndex = objectIndex([SIM.OBJECTS.type] == OMAS_objectType.agent); % The agents themselves
end

iter = 0;
for ID1 = 1:SIM.totalAgents
    % TRY TO GET THE REQUIRED PROPERTIES
    try
       testA = agentObjectIndex{ID1}.DATA.inputNames;
       testB = agentObjectIndex{ID1}.DATA.inputs;
    catch
       iter = iter + 1;
    end
end

% SANITY CHECK 2
if iter == SIM.totalAgents
    warning('No agents have input timeseries stored in (agent).DATA.inputs. Use the "DATA.inputNames" and "DATA.inputs" fields if desired.');
    return
end

% Declare title string for figure
figurePath = strcat(SIM.outputPath,'inputs');

% FIGURE META PROPERTIES
figureHandle = figure('Name','OpenMAS control inputs');
setappdata(figureHandle, 'SubplotDefaultAxesLocation', [0.1, 0.1, 0.85, 0.85]);
set(figureHandle,'Position', DATA.figureProperties.windowSettings);        % [x y width height]
set(figureHandle,'Color',DATA.figureProperties.figureColor);               % Background colour
plotCellA = 1; plotCellWidth = 4;                                          % The width of each figure, the start of the plot

% FOR EACH AGENT'S PERSPECTIVE
for ID1 = 1:SIM.totalAgents
    % GET EVALUATION OBJECT
    evalAgent = agentObjectIndex{ID1};
    % CHECK SKIP CONDITION
    if isempty(evalAgent.DATA)
        warning('[OUTPUT]\tProperty .DATA is empty for agent %s',evalAgent.name);
        continue
    end

    % GET TH AGENT-LOCAL 'DATA' STRUCTURE
    inputTrajectories = evalAgent.DATA.inputs;
    inputCount = size(inputTrajectories,1);

    % BUILD THE SUB-PLOT
    plotCellB = double(ID1*plotCellWidth);                                         % The end of the plot
    plotLocation = subplot(double(DATA.totalAgents),plotCellWidth,[plotCellA plotCellB]);
    set(plotLocation,...
        'Color',DATA.figureProperties.axesColor,...
        'GridLineStyle','--',...
        'GridAlpha',0.25,...
        'GridColor','k');
    hold on;

    % LEGEND LABELS
    legendEntries = cell(inputCount,1);
    numericLabelling = 1;
    if isfield(evalAgent.DATA,'inputNames')
        if length(evalAgent.DATA.inputNames) ~= inputCount
            warning('Incorrect number of input labels for agent %s, reverting to numeric labelling',simName);
            numericLabelling = 1;
        else
            % FETCH THE INPUT LABEL
            for entry = 1:size(inputTrajectories,1)
                legendEntries{entry} = evalAgent.DATA.inputNames{entry};
            end
            numericLabelling = 0;
        end
    end
    if numericLabelling
        % DEFAULT TO GENERIC NAMING
        for entry = 1:size(inputTrajectories,1)
            legendEntries{entry} = sprintf('Input %s',num2str(entry));
        end
    end

    % PLOT THE SEPERATION DATA ON CURRENT FIGURE
    plot(plotLocation,...
         DATA.timeVector(:,1:SIM.TIME.endStep),...
         inputTrajectories(:,1:SIM.TIME.endStep),...
        'LineStyle','-',...
        'LineWidth',DATA.figureProperties.lineWidth);
    % Y-Label
    ylabel(plotLocation,...
        sprintf('Inputs \n [ID-%s]',num2str(evalAgent.objectID)),...
        'Interpreter',DATA.figureProperties.interpreter,...
        'fontname',DATA.figureProperties.fontName,...
        'fontweight',DATA.figureProperties.fontWeight,...
        'fontSize',DATA.figureProperties.axisFontSize,...
        'FontSmoothing','On');
    % Axes
    set(plotLocation,...
        'TickLabelInterpreter',DATA.figureProperties.interpreter,...
        'fontname',DATA.figureProperties.fontName,...
        'Fontweight',DATA.figureProperties.fontWeight,...
        'FontSize',DATA.figureProperties.axisFontSize,...
        'FontSmoothing','on',...
        'Color',DATA.figureProperties.axesColor,...
        'GridLineStyle','--',...
        'GridAlpha',0.25,...
        'GridColor','k');
    % Legend
    legend(legendEntries,...
        'Location','eastoutside',...
        'fontname',DATA.figureProperties.fontName,...
        'Interpreter',DATA.figureProperties.interpreter);

    grid on; box on; grid minor;
    % Show the timestep difference in the figure
    %plotLocation.XAxis.MinorTickValues = plotLocation.XAxis.Limits(1):SIM.TIME.dt:plotLocation.XAxis.Limits(2);
    % ADD FIGURE TITLE TO FIRST PLOT HEADER
    if plotCellA == 1
        % Title
        title(plotLocation,sprintf('Agent control trajectories over a period of %ss',num2str(SIM.TIME.endTime)),...
            'Interpreter',DATA.figureProperties.interpreter,...
            'fontname',DATA.figureProperties.fontName,...
            'fontweight',DATA.figureProperties.fontWeight,...
            'fontsize',DATA.figureProperties.titleFontSize);               % Append title to first subplot
    end
    % Prevent overlap of x-label
    if ID1 == DATA.totalAgents
        % X-Label
        xlabel(plotLocation,'t (s)',...
            'Interpreter', DATA.figureProperties.interpreter,...
            'fontname',DATA.figureProperties.fontName,...
            'fontweight',DATA.figureProperties.fontWeight,...
            'fontSize',DATA.figureProperties.axisFontSize,...
            'FontSmoothing','On');
    else
        set(plotLocation,'XTickLabel',[]);
    end
    % Define the x-limits
    xlim([SIM.TIME.startTime,SIM.TIME.endTime]);                           % Ensures plot alignment/sizing
    plotCellA = plotCellA + plotCellWidth; % Move to next subplot location
end
hold off;

% SAVE THE OUTPUT FIGURE
savefig(figureHandle,figurePath);

% Publish as .pdf if requested
if DATA.figureProperties.publish
	GetFigurePDF(figureHandle,figurePath);
end

% INCREMENT THE FIGURE INDEX
DATA.figureProperties.alignment = DATA.figureProperties.alignment + DATA.figureProperties.spacing;
currentFigure = currentFigure + 1;
end

repo: OpenMAS


text:
% This file serves as a template of defining the topology of the
% beamforming network with cross entropy training.
% You should create a copy for each of your experiments and name them
% differently.
%
% References:
% [1] Xiong Xiao, Shinji Watanabe, Hakan Erdogan, Liang Lu, John Hershey,
% Michael L. Seltzer, Guoguo Chen, Yu Zhang, Michael Mandel, Dong Yu, "Deep
% beamforming networks for multi-channel speech recognition", in ICASSP
% 2016.
% [2] Xiong Xiao, Shinji Watanabe, Eng Siong Chng, Haizhou Li, "Beamforming
% Networks Using Spatial Covariance Features for Far-field Speech
% Recognition", in APSIPA 2016.
%
% Created by Xiong Xiao, Temasek Laboratories, NTU, Singapore.
% Last Modified: 29 Nov 2016
%
function para = ConfigMaskBFnetCE(para)
para.topology.fs = 16000;   % sampling rate
if isfield(para.topology, 'useChannel')
    if length(para.topology.useChannel)==1      % if useChannel is an integer, use it as the number of channels
        para.topology.nCh = para.topology.useChannel;
    else                                        % is useChannel is an integer array, use the specified channel indexes
        para.topology.nCh = length(para.topology.useChannel);
    end
else
    para.topology.nCh = 2;      % by default use 2 channels
end
para.topology = SetDefaultValue(para.topology, 'useFileName', 0);   % by default load waveforms into memory. If data is too big, we can also use wave file names
para.topology = SetDefaultValue(para.topology, 'nChMask', 1);   % by default use only 1 channel for mask prediction

% define the input type:
%   if set to 1, we will use raw waveform as input and need to define the
%   parameters for extracting features (such as GCC) and generating complex
%   Fourier transform of the input channels.
%   if set to 0, we will load precomputed features and Fourier
%   coefficients.
para.topology = SetDefaultValue(para.topology, 'useWav', 1);    % by default, we use waveform as input to the network

para.topology.fft_len = 512;
para.topology.freqBin = (0:1/para.topology.fft_len:0.5)*2*pi;
para.topology.nFreqBin = length(para.topology.freqBin);
if para.topology.useWav
    % define the parameters for extracting Fourier coefficients
    para.topology.frame_len = para.topology.fs * 0.025;
    para.topology.frame_shift = para.topology.fs * 0.01;
    para.topology.removeDC = 0;     % do not remove DC for faster speed.
    para.topology.win_type = 'hamming';
end

% define the mask predicting subnet type
para.topology = SetDefaultValue(para.topology, 'MaskNetType', 'LSTM');
switch para.topology.MaskNetType
    case 'DNN'
        para.topology = SetDefaultValue(para.topology, 'hiddenLayerSizeMask', [1024]);
        para.topology = SetDefaultValue(para.topology, 'contextSizeMask', 11);  % for DNN, we use 11 frames of consecutive frames
    case 'LSTM'
        para.topology = SetDefaultValue(para.topology, 'hiddenLayerSizeMask', [512]);
        para.topology = SetDefaultValue(para.topology, 'useDeltaMask', 1);    % for LSTM, we use delta features without splicing
end

% define the BF subnet type
para.topology = SetDefaultValue(para.topology, 'BfNetType', 'MVDR');      % choose frame DNN or LSTM, default is DNN
switch para.topology.BfNetType
    case 'MVDR'     % use the MVDR formula to obtain beamforming weights

    case 'DNN'      % use DNN to predict beamforming weights
        para.topology = SetDefaultValue(para.topology, 'hiddenLayerSizeBF', [1024]);
    case 'LSTM'
        para.topology = SetDefaultValue(para.topology, 'hiddenLayerSizeBF', [1024]);
end
para.topology.bf_weight_dim = (para.topology.fft_len/2+1) * para.topology.nCh * 2;  % number of dimensions for weight matrix

% define the AM subnet type
para.topology = SetDefaultValue(para.topology, 'AmNetType', 'DNN');      % choose frame DNN or LSTM, default is DNN
switch para.topology.AmNetType
    case 'DNN'
        para.topology = SetDefaultValue(para.topology, 'hiddenLayerSizeAM', [1024]);
    case 'LSTM'
        para.topology = SetDefaultValue(para.topology, 'hiddenLayerSizeAM', [1024]);
end
para.topology = SetDefaultValue(para.topology, 'nSenone', 100);
para.topology = SetDefaultValue(para.topology, 'nFbank', 40);

% define the initialized subnets. Just put the path to the fields. Note
% that you can only set either initalAM_CE or initalAM_RBM.

% initial network for mask predicting subnet.
para.topology = SetDefaultValue(para.topology, 'initialMask', '');
% initial network for beamforming predicting subnet. You need to make sure
% that the topology in the initialized network is the same as the topology
% of beamforming subnet defined above.
para.topology = SetDefaultValue(para.topology, 'initialBF', '');
% initial network for acoustic model trained by cross entropy
para.topology = SetDefaultValue(para.topology, 'initialAM_CE', '');
% initial network for acoustic model trained by RBM
para.topology = SetDefaultValue(para.topology, 'initialAM_RBM', '');

% tell the network whether we should update the Mask subnet, the BF subnet, the AM subnet,
% or all of them.
para.topology = SetDefaultValue(para.topology, 'updateMask', 1);
para.topology = SetDefaultValue(para.topology, 'updateBF', 1);
para.topology = SetDefaultValue(para.topology, 'updateAM', 1);

end

author: singaxiong

repo: SignalGraph


text:
function [D,nn_list] = compute_nn_distance(X,nbr_nn, options)

% compute_nn_distance - compute the distance to the nearest neighbors
%
%   [D,nn_list] = compute_nn_distance(X,nbr_nn, options);
%
% X is a (d,n) set of n points in R^d
% nbr_nn is the number of nearest neighbors to retrieve.
%
%   You can set Y=options.Y, otherwise the algorithm assumes
%       the target points are Y=X.
%
% D is a (n,nbr_nn) matrix of distance, D(i,j) is distance between point
%   Y(:,i) and point X(nn_list(i,j),:)
% nn_list(i,:) is the set of nearst neighbors
%
%   options.use_nntools = 0 force the use of the slow matlab code
%       for nearest neighbors computations.
%
%   options.exlude_self = 1 to avoid taking a point it self neighbor
%       (works only when Y=X).
%
%   If you set options.pca_numvecs < d, then a preprocessing step of
%       dimensionnality reduction is performed
%
%   Copyright (c) 2006 Gabriel Peyr?

options.null = 0;

if isfield(options, 'use_nntools')
    use_nntools = options.use_nntools;
else
    use_nntools = 1;
end
if isfield(options, 'exlude_self')
    exlude_self = options.exlude_self;
else
    exlude_self = 0;
end

if isfield(options, 'Y')
    Y = options.Y;
else
    Y = [];
end
if exlude_self && ~isempty(Y)
    warning('You can not use exlude_self with options.Y enabled.');
end

if nargin<2
    nbr_nn = size(X,2);
end

nbr_nn = min(nbr_nn,size(X,2));

d = size(X,1);
n = size(X,2);
if d>2*n
    warning('Matrix seems to be of wrong dimension, should be dimension x nbr_points');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% dimensionnality reduction for fast search
if isfield(options, 'pca_numvecs')
    m = options.pca_numvecs;
else
    m = d;
end
if m>0 && m<d
    %%% perform dimensionnality reduction
    [P,tmp,v,Psi] = pca(X,m);
    X = X - repmat(Psi,[1,size(X,2)]);
    X = P' * X;
    if ~isempty(Y)
        Y = Y - repmat(Psi,[1,size(Y,2)]);
        Y = P' * Y;
    end
    d = m;
end

if not(exist('nn_prepare')==3) && use_nntools
    warning('TSTool not installed, use slow Matlab code instead.');
    use_nntools = 0;
end

if isempty(Y)
    %%% compute distance from X to X %%%
    if exlude_self==0
        nbr_nn = nbr_nn - 1;
    end
    if use_nntools
        % use fast mex code
        atria = nn_prepare(X');
        [nn_list,D] = nn_search(X', atria, 1:n, nbr_nn, 0);
    else
        % use slow matlab code
        D1 = sqrt( compute_distance_matrix(X) );
        D1 = D1 + diag( Inf + zeros(size(D1,1),1) );
        % find closest points
        [D,nn_list] = sort(D1);
        D = D(1:nbr_nn,:)';
        nn_list = nn_list(1:nbr_nn,:)';
    end
    if exlude_self==0
        % add self reference
        nn_list = [(1:n)', nn_list];
        D = [zeros(n,1), D];
    end
else
    %%% compute distances from Y to X %%%
    if exist('nn_prepare')>0 && use_nntools
        % use fast mex code
        atria = nn_prepare(X');
        [nn_list,D] = nn_search(X', atria, Y', nbr_nn, 0);
    else
        % use slow matlab code
        D1 = sqrt( compute_distance_matrix(X,Y) );
        % find closest points
        [D,nn_list] = sort(D1,2);
        D = D(:,1:nbr_nn)';
        nn_list = nn_list(:,1:nbr_nn)';
    end
end

author: gpeyre

repo: matlab-toolboxes


text:
classdef DOC1 < PROBLEM
% <multi> <real> <constrained>
% Benchmark MOP with constraints in both decision and objective spaces

%------------------------------- Reference --------------------------------
% Z. Liu and Y. Wang, Handling constrained multiobjective optimization
% problems with constraints in both the decision and objective spaces. IEEE
% Transactions on Evolutionary Computation, 2019, 23(5): 870-884.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        %% Default settings of the problem
        function Setting(obj)
            obj.M = 2;
            obj.D = 6;
            obj.lower    = [0 78 33 27 27 27];
            obj.upper    = [1 102 45 45 45 45];
            obj.encoding = ones(1,obj.D);
        end
        %% Calculate objective values and constraint violations
        function Population = Evaluation(obj,varargin)
            X = varargin{1};
            X = max(min(X,repmat(obj.upper,size(X,1),1)),repmat(obj.lower,size(X,1),1));
            g = 5.3578547 * X(:, 4).^2 + 0.8356891 * X(:, 2).* X(:, 6) + 37.293239 * X(:, 2) - 40792.141+30665.5386717834 +1;
            PopObj(:,1) = X(:,1);
            PopObj(:,2) = g.*(1-sqrt(PopObj(:,1))./g);
            % Constraints in objective space
            PopCon(:,1) = max( -(PopObj(:,1).^2 + PopObj(:,2).^2-1), 0);
            % Constraints in decision space
            PopCon(:,2) = + 85.334407 + 0.0056858 * X(:, 3).* X(:, 6) + 0.0006262 * X(:, 2).* X(:, 5) - 0.0022053 * X(:, 4).* X(:, 6) - 92;
            PopCon(:,3) = -85.334407 - 0.0056858 * X(:, 3).* X(:, 6) - 0.0006262 * X(:, 2).* X(:, 5) + 0.0022053 * X(:, 4).* X(:, 6);
            PopCon(:,4) = + 80.51249 + 0.0071317 * X(:, 3).* X(:, 6) + 0.0029955 * X(:, 2).* X(:, 3) + 0.0021813 * X(:, 4).^2 - 110;
            PopCon(:,5) = -80.51249 - 0.0071317 * X(:, 3).* X(:, 6) - 0.0029955 * X(:, 2).* X(:, 3) - 0.0021813 * X(:, 4).^2 + 90;
            PopCon(:,6) = + 9.300961 + 0.0047026 * X(:, 4).* X(:, 6) + 0.0012547 * X(:, 2).* X(:, 4) + 0.0019085 * X(:, 4) .* X(:, 5) - 25;
            PopCon(:,7) = -9.300961 - 0.0047026 * X(:, 4).* X(:, 6) - 0.0012547 * X(:, 2).* X(:, 4) - 0.0019085 * X(:, 4) .* X(:, 5) + 20;
            Population  = SOLUTION(X,PopObj,PopCon,varargin{2:end});
            obj.FE      = obj.FE + length(Population);
        end
        %% Generate points on the Pareto front
        function R = GetOptimum(obj,N)
            R = UniformPoint(N,2);
            R = R./repmat(sqrt(sum(R.^2,2)),1,2);
        end
        %% Generate the image of Pareto front
        function R = GetPF(obj)
            R = obj.GetOptimum(100);
        end
    end
end

repo: PlatEMO


text:
% [] = XXXX()
%
% -----------------------------Definition---------------------------------%
%
% description
%
% usage :
%
% -----------------------------Input--------------------------------------%
%
% XX : description + dimension
%
% -----------------------------Output-------------------------------------%
%
% XX : description + dimension
%
% -----------------------------References---------------------------------%
%
% [1] : XXX
%
%
%   Project : BCI-EEG
%
%   author : A. Barachant
%   date : 2011-XXXX
%   version : 1.0
%   status : a terminer
%   CEA/GRENOBLE-LETI/DTBS
%
%   See also MEAN, MEDIAN, RIEMANN_MEAN, REIMANN_MEDIAN, RIEMANN_TRIMMED_MEAN.

% [EOF: XXX.m]

function C = mean_covariances(COV,method_mean,arg_mean)

if (nargin<2)||(isempty(method_mean))
    method_mean = 'arithmetic';
end
if (nargin<3)
    arg_mean = {};
end

switch method_mean
    case 'riemann'
        C = riemann_mean(COV,arg_mean);
    case 'riemanndiag'
        C = riemann_diag_mean(COV,arg_mean);
    case 'riemanntrim'
        C = riemann_trimmed_mean(COV,arg_mean);
    case 'median'
        C = median(COV,3);
    case 'riemannmed'
        C = riemann_median(COV,arg_mean);
    case 'logeuclid'
        C = logeuclid_mean(COV);
    case 'opttransp'
        C = opttransp_mean(COV);
    case 'ld'
        C = logdet_mean(COV);
    case 'geodesic'
        C = geodesic_mean(COV,arg_mean);
    case 'harmonic'
        iCOV = zeros(size(COV));
        for i=1:size(COV,3)
            iCOV(:,:,i) = inv(COV(:,:,i));
        end
        C = inv(mean(iCOV,3));
    case 'geometric'
        B = COV(:,:,1);
        for i=2:size(COV,3)
            B = B*COV(:,:,i);
        end
        C = B^(1/size(COV,3));
    otherwise
        C = mean(COV,3);
end

author: alexandrebarachant

repo: covariancetoolbox


clear all;
clc;

addpath('../utils');
addpath('../models');
addpath('../vital');

run ../matconvnet/matlab/vl_setupnn ;

global gpu;
gpu=true;

test_seq='Bolt';
conf = genConfig('otb',test_seq);

net=fullfile('../models/otbModel.mat');

result = vital_run(conf.imgList, conf.gt(1,:), net, true);


text:
function idx= cspselect_equalPerClass(score, ~, nComponents)
%CSPSELECT_EQUALPERCLASS - Select equally many CSP components for each class
%
%Synopsis:
% CI = select_fixedNumber(SCORE, ~, NCOMP)
%
%Arguments:
% SCORE  - score of components
% NCOMPS - number of components (total number depends on MODE)
%
%Returns:
% CI     - index of components
%
%See also processing/proc_csp

idx= [1:nComponents, length(score)-nComponents+1:length(score)]';

author: bbci