text:
function ezlabels(command)
    %
    %   GUI input for labels and titles
    %
    %   typing 'ezlabels' from the command line opens an
    %   interactive dialogue box, allowing the user to specify
    %   axes labels and the figure title as well as the Font, Size, Weight
    %   and Angle using pulldown menus.
    %
    %   Note: This function uses the ten standard postscript fonts
    %         available on most platforms.  Not all font
    %         combinations are available on all platforms and/or
    %         hardcopy devices.
    %
    %   Richard G. Cobb    3/96
    %   rcobb@afit.af.mil
    %
    if nargin < 1
        siblines(4)=get(gca,'Title');
        siblines(3)=get(gca,'Xlabel');
        siblines(2)=get(gca,'Ylabel');
        siblines(1)=get(gca,'Zlabel');
        %
        haold=gcf;
        T1=['Avant Garde           ';...
            'Bookman               ';...
            'Courier               ';...
            'Helvetica             ';...
            'Helvetica Narrow      ';...
            'New Century Schoolbook';...
            'Palatino              ';...
            'Symbol                ';...
            'Times                 ';...
            'Zapf Chancery         ';...
            'Zapf Dingbats         '];
        T2=['cyan   ';'magenta';'green  ';'red    ';'yellow ';...
            'blue   ';'black  ';'white  '];
        T5=['Normal ';...
            'Light  ';...
            'Demi   ';...
            'Bold   '];
        T4=['Normal ';'Italic ';'Oblique'];
        T3=['10';'12';'16';'20';'24';'30'];

        si=[0 0 0 0 0 0]';si2=si;
        si(1:length(siblines))=siblines;
        leginp=figure_w_normalized_uicontrolunits('Color',[0.9 0.9 0.9],'NumberTitle','off','Name',...
            'EZ LABELS',...
            'NextPlot','new',...
            'Units','Normalized',...
            'Position',[.1 .1  .4 .1+.05*length(siblines)]);
        sfactor=.25/(.1+.05*length(siblines));
        axis off
        axis([0,1,0,1])
        Y = linspace(0,.75,length(siblines))';
        ui=[0 0 0 0 0 0]'; bi=[0 0 0 0 0 0]';
        for i=1:length(siblines)
            examps(i)=text(0,[Y(i)],get(siblines(i),'string'),...
                'FontName',get(siblines(i),'FontName'),...
                'Color',get(siblines(i),'Color') ,...
                'FontSize',get(siblines(i),'FontSize'),...
                'FontAngle',get(siblines(i),'FontAngle'),...
                'FontWeight',get(siblines(i),'FontWeight'));
            ui(i) = uicontrol('Parent',leginp,...
                'style','edit',...
                'string',get(siblines(i),'string'),...
                'units','normalized',...
                'position',[.35 (Y(i)+.1)/1.2 .3 .1*sfactor]);
            bi(i) = uicontrol('Style','checkbox','Units','Normalized',...
                'Position',[.28 (Y(i)+.1)/1.2 .05 .1*sfactor],...
                'Visible','on');
        end

        si2(1:length(examps))=examps;
        mi(1) = uicontrol('Style','Popup','Units','Normalized',...
            'Position',[.7 .8 .25 .1*sfactor],...
            'String',T1,...
            'Visible','on',...
            'HorizontalAlignment', 'left',...
            'Callback','ezlabels(1)');
        li(1) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.7 .8 .25 .1*sfactor],...
            'String','Fontname',...
            'Visible','on',...
            'Callback','ezlabels(8)');
        mi(2) = uicontrol('Style','Popup','Units','Normalized',...
            'Position',[.7 .6 .25 .1*sfactor],...
            'String',T2,...
            'Visible','on',...
            'HorizontalAlignment', 'left',...
            'Callback','ezlabels(2)');
        li(2) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.7 .6 .25 .1*sfactor],...
            'String','Color',...
            'Visible','on',...
            'Callback','ezlabels(9)');

        mi(3) = uicontrol('Style','Popup','Units','Normalized',...
            'Position',[.7 .4 .25 .1*sfactor],...
            'String',T3,...
            'Visible','on',...
            'HorizontalAlignment', 'left',...
            'Callback','ezlabels(3)');
        li(3) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.7 .4 .25 .1*sfactor],...
            'String','FontSize',...
            'Visible','on',...
            'Callback','ezlabels(10)');

        mi(4) = uicontrol('Style','Popup','Units','Normalized',...
            'Position',[.7 .2 .25 .1*sfactor],...
            'String',T4,...
            'Visible','off',...
            'HorizontalAlignment', 'left',...
            'Callback','ezlabels(4)');
        li(4) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.7 .2 .25 .1*sfactor],...
            'String','Fontangle',...
            'Visible','on',...
            'Callback','ezlabels(7)');
        mi(5) = uicontrol('Style','Popup','Units','Normalized',...
            'Position',[.7 0 .25 .1*sfactor],...
            'String',T5,...
            'Visible','off',...
            'HorizontalAlignment', 'left',...
            'Callback','ezlabels(12)');
        li(5) = uicontrol('Style','pushbutton','Units','Normalized',...
            'Position',[.7 0 .25 .1*sfactor],...
            'String','Fontweight',...
            'Visible','on',...
            'Callback','ezlabels(11)');

        uicontrol('Parent',leginp,...
            'style','text',...
            'string','Title',...
            'units','normalized',...
            'position',[.4 ((max(Y)+.1)/1.2)+.1*sfactor .2 .07*sfactor],...
            'BackgroundColor',[ 0 0 0 ],...
            'ForegroundColor',[ 0 1 0 ]);
        uicontrol('Parent',leginp,...
            'style','text',...
            'string','Xlabel',...
            'units','normalized',...
            'position',[.4 ((Y(3)+.1)/1.2)+.1*sfactor .2 .07*sfactor],...
            'BackgroundColor',[ 0 0 0 ],...
            'ForegroundColor',[ 0 1 0 ]);

        uicontrol('Parent',leginp,...
            'style','text',...
            'string','Ylabel',...
            'units','normalized',...
            'position',[.4 ((Y(2)+.1)/1.2)+.1*sfactor .2 .07*sfactor],...
            'BackgroundColor',[ 0 0 0 ],...
            'ForegroundColor',[ 0 1 0 ]);
        uicontrol('Parent',leginp,...
            'style','text',...
            'string','Zlabel',...
            'units','normalized',...
            'position',[.4 ((Y(1)+.1)/1.2)+.1*sfactor .2 .07*sfactor],...
            'BackgroundColor',[ 0 0 0 ],...
            'ForegroundColor',[ 0 1 0 ]);

        uicontrol('Parent',leginp,...
            'style','pushbutton',...
            'string','Close',...
            'units','normalized',...
            'position',[.3 .92 .15 .07*sfactor],...
             'Callback','delete(gcf)');

        uicontrol('Parent',leginp,...
            'style','pushbutton',...
            'string','Add Labels',...
            'units','normalized',...
            'position',[.5 .92 .2 .07*sfactor],...
             'Callback','ezlabels(6)');

        mh=zeros(size(ui));mh(1:5)=mi;mh(6)=haold;
        lh=zeros(size(ui));lh(1:5)=li;
        set(leginp,'UserData',[si ui bi mh si2 lh]);

    elseif command==1
        T1=['Avant Garde           ';...
            'Bookman               ';...
            'Courier               ';...
            'Helvetica             ';...
            'Helvetica Narrow      ';...
            'New Century Schoolbook';...
            'Palatino              ';...
            'Symbol                ';...
            'Times                 ';...
            'Zapf Chancery         ';...
            'Zapf Dingbats         '];

        handles = get(gcf,'UserData');
        checked=zeros(4,1);
        for i=1:4
            checked(i)=get(handles(i,3),'Value');
        end
        for i=find(checked)
            set(handles(i,1),'Fontname',deblank(T1(get(handles(1,4),'Value'),:)))
            set(handles(i,5),'Fontname',deblank(T1(get(handles(1,4),'Value'),:)))
        end
        refresh
        refresh(handles(6,4))
        set(handles(1,4),'Visible', 'off')
        set(handles(1,6),'Visible', 'on')

    elseif command==2
        T2=['cyan   ';'magenta';'green  ';'red    ';'yellow ';...
            'blue   ';'black  ';'white  '];
        handles = get(gcf,'UserData');
        checked=zeros(4,1);
        for i=1:4
            checked(i)=get(handles(i,3),'Value');
        end
        for i=find(checked)
            set(handles(i,1),'Color',T2(get(handles(2,4),'Value'),:))
            set(handles(i,5),'Color',T2(get(handles(2,4),'Value'),:))
        end
        set(handles(2,4),'Visible', 'off')
        set(handles(2,6),'Visible', 'on')

    elseif command==3
        T3=['10';'12';'16';'20';'24';'30'];
        handles = get(gcf,'UserData');
        checked=zeros(4,1);
        for i=1:4
            checked(i)=get(handles(i,3),'Value');
        end
        for i=find(checked)
            set(handles(i,1),'FontSize',eval(T3(get(handles(3,4),'Value'),:)))
            set(handles(i,5),'FontSize',eval(T3(get(handles(3,4),'Value'),:)))
        end
        refresh
        refresh(handles(6,4))
        set(handles(3,4),'Visible', 'off')
        set(handles(3,6),'Visible', 'on')

    elseif command==4
        T4=['normal ';'italic ';'oblique'];
        handles = get(gcf,'UserData');
        checked=zeros(4,1);
        for i=1:4
            checked(i)=get(handles(i,3),'Value');
        end
        for i=find(checked)
            set(handles(i,1),'FontAngle',T4(get(handles(4,4),'Value'),:))
            set(handles(i,5),'FontAngle',T4(get(handles(4,4),'Value'),:))
        end
        refresh
        refresh(handles(6,4))
        set(handles(4,4),'Visible', 'off')
        set(handles(4,6),'Visible', 'on')
    elseif command==12
        T5=['Normal ';...
            'Light  ';...
            'Demi   ';...
            'Bold   '];
        handles = get(gcf,'UserData');
        checked=zeros(4,1);
        for i=1:4
            checked(i)=get(handles(i,3),'Value');
        end
        for i=find(checked)
            set(handles(i,1),'FontWeight',T5(get(handles(5,4),'Value'),:))
            set(handles(i,5),'FontWeight',T5(get(handles(5,4),'Value'),:))
        end
        refresh
        refresh(handles(6,4))
        set(handles(5,4),'Visible', 'off')
        set(handles(5,6),'Visible', 'on')

    elseif command == 5

    elseif command == 6
        handles = get(gcf,'UserData');
        for i=1:4
            set(handles(i,1),'string', get(handles(i,2),'string'))
            set(handles(i,5),'string', get(handles(i,2),'string'))
        end
    elseif command == 7
        handles = get(gcf,'UserData');
        set(handles(4,6),'Visible', 'off')
        set(handles(4,4),'Visible', 'on')
    elseif command == 8
        handles = get(gcf,'UserData');
        set(handles(1,6),'Visible', 'off')
        set(handles(1,4),'Visible', 'on')
    elseif command == 9
        handles = get(gcf,'UserData');
        set(handles(2,6),'Visible', 'off')
        set(handles(2,4),'Visible', 'on')
    elseif command == 10
        handles = get(gcf,'UserData');
        set(handles(3,6),'Visible', 'off')
        set(handles(3,4),'Visible', 'on')
    elseif command == 11
        handles = get(gcf,'UserData');
        set(handles(5,6),'Visible', 'off')
        set(handles(5,4),'Visible', 'on')

    end

author: CelsoReyes


text:
clear all; close all; clc;
% Problem setup parameters
rng('default');
% Create the directory for storing results
[status_code,message,message_id] = mkdir('bin');

% We will load the details of this setup from a helper function
problem = barbara_problem();
num_training_patches = size(problem.training_patches, 2);
% we will use only 1000 training patches
chosen_training_patches = randperm(num_training_patches, 500);
% We will now train the dictionary
% Create the learning algorithm
trainer = spx.dictlearn.KSVD_OMP(problem.D, problem.N);
% We fix the sparsity level of representations
ksvd.K = 4;
trainer.InitialDictionary = problem.initial_dictionary;
% Option for not touching the  DC component atom
trainer.SpecialAtoms = 1;
% We want OMP to stop when residual is small
trainer.StopOnResidualNorm = true;
trainer.StopOnResNormStable = true;
%ksvd.MaxIterations = 10;
% Learn dictionary
trainer.train(problem.training_patches(:,chosen_training_patches));
% Get the learnt dictionary
learnt_dict = trainer.Dict;

save('bin/ex_barbara_ksvd.mat', 'learnt_dict');

author: indigits

repo: sparse-plex


text:
function [params, names] = rbfExtractParam(model)

% RBFEXTRACTPARAM Wrapper for NETLAB's rbfpak.
% FORMAT
% DESC returns a vector of all the weights and biases from a
% RBF network model. For single hidden layer models the
% function is a wrapper for the rbfpak command.
% ARG model : the model from which we wish to extract the weights
% and biases.
% RETURN params : vector of all the weights and biases returned by
% the model. The structure is governed by rbfpak.
% RETURN names : optional additional returned cell array of the
% names of the parameters.
%
% SEEALSO : rbfpak, rbfCreate, rbfExpandParam, modelExtractParam
%
% COPYRIGHT : Neil D. Lawrence, 2006, 2007, 2008

% MLTOOLS

params = rbfpak(model);
if nargout > 1
  counter = 0;
  for j = 1:size(model.c, 2)
    for i = 1:size(model.c, 1)
      counter = counter + 1;
      names{counter} = ['Input centre ' num2str(i) '-' num2str(j)];
    end
  end
  for j = 1:size(model.wi, 2)
    counter = counter + 1;
    names{counter} = ['Hidden node width ' num2str(j)];
  end
  for j = 1:size(model.w2, 2)
    for i = 1:size(model.w2, 1)
      counter = counter + 1;
      names{counter} = ['Output weight ' num2str(i) '-' num2str(j)];
    end
  end
  for j = 1:size(model.b2, 2)
    counter = counter + 1;
    names{counter} = ['Output node bias ' num2str(j)];
  end
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function result = CRA_enterFunc(alpha,beta,gamma,lambda,numK,maxIter,flag,inputPath)

    %% ======================================================================
    %%STEP 1: load the data
    fprintf('start load the data...\n');
    [TrainData, TestData, TrainLabel, TestLabel, numX, numS] = CRA_loadData(inputPath);

    numM = size(TrainData,1);                % input data feature dimensions

    %% ======================================================================
    %%STEP 2: Initialize the parameter
    fprintf('start initialize the parameter...\n');
    theta = CRA_initialize(numK, numM, numS, numX,TrainData,TrainLabel,TestData);    % Randomly initialize the parameters

    %% ======================================================================
    %%STEP 3: Training the parameters W1 W2 b1 b2 C
    fprintf('start training the parameter...\n');
    [opttheta, cost] = CRA_Train(numM,numK,numS,numX,maxIter,alpha,beta,gamma,lambda,TrainData,TestData,TrainLabel,theta);

    %% ======================================================================
    %%STEP4: get parameters W1 W2 W11 W22 b1 b2 b11 b22 after training
    fprintf('get the parameter...\n');
    W1 = reshape(opttheta(1:numK*numM), numK, numM);
    b1 = opttheta(2*numK*numM+1:2*numK*numM+numK);
    C = reshape(opttheta(2*numK*numM+numK+numM+1:end), numS, numK);

    %% ======================================================================
    %%STEP4: Testing
    fprintf('testing the model...\n');
    hiddeninputs_train = sigmoid(W1 * TrainData + b1 * ones(1, size(TrainData,2)));
    hiddeninputs_test = sigmoid(W1 * TestData + b1 * ones(1, size(TestData,2)));
    if flag == 1
        predict = CRA_test(hiddeninputs_train, hiddeninputs_test, TrainLabel, TestLabel, numX, numS, C);
    else
        predict = CRA_test_LR(hiddeninputs_train, hiddeninputs_test, TrainLabel, TestLabel, numX, numS);
    end
    result=predict;
    clear hiddeninputs_train hiddeninputs_test
end

author: FuzhenZhuang

repo: Transfer-Learning-Toolkit


text:
function bin = imCropLabel(img, label)
%IMCROPLABEL Extract the portion of image that contains the specified label
%
%   BIN = imCropLabel(IMG, LABEL)
%   Crops the regions in original label image IMG that corresponds to the
%   label given by the index LABEL. Works for 2D and 3D images.
%   The result is a binary image. A 1-pixel thick boundary is left around
%   the binary result, unless the label touches original image borders.
%
%   Example
%     % read and segment a demo image
%     img = imread('coins.png');
%     bin = imFillHoles(imOtsuThreshold(img));
%     lbl = bwlabel(bin, 4);
%     % crop region corresponding to label 3
%     bin3 = imCropLabel(lbl, 3);
%     imshow(bin3);
%
%   See also
%   imcrop, label2rgb, imFindLabels
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2013-04-02,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2013 INRA - Cepia Software Platform.

% get image size and dimension
dim = size(img);
nd = length(dim);

% binarize image
bin = img == label;

if nd == 2
    % first array direction
    l1 = sum(bin, 2);
    i0(1) = find(l1, 1, 'first');
    i1(1) = find(l1, 1, 'last');

    % second array direction
    l1 = sum(bin, 1);
    i0(2) = find(l1, 1, 'first');
    i1(2) = find(l1, 1, 'last');

    % try to add one pixel if not outside boundary
    inds = i0 > 1;
    i0(inds) = i0(inds) - 1;
    inds = i1 < dim;
    i1(inds) = i1(inds) + 1;

    % extract only the necessary part of image
    bin = bin(i0(1):i1(1), i0(2):i1(2));

elseif nd == 3
    % first array direction
    l1 = sum(sum(bin, 2), 3);
    i0(1) = find(l1, 1, 'first');
    i1(1) = find(l1, 1, 'last');

    % second array direction
    l1 = sum(sum(bin, 1), 3);
    i0(2) = find(l1, 1, 'first');
    i1(2) = find(l1, 1, 'last');

    % third array direction
    l1 = sum(sum(bin, 1), 2);
    i0(3) = find(l1, 1, 'first');
    i1(3) = find(l1, 1, 'last');

    % try to add one pixel if not outside boundary
    inds = i0 > 1;
    i0(inds) = i0(inds) - 1;
    inds = i1 < dim;
    i1(inds) = i1(inds) + 1;

    % extract only the necessary part of image
    bin = bin(i0(1):i1(1), i0(2):i1(2), i0(3):i1(3));

else
    error('Can not manage dimensions other than 2 or 3');
end

author: mattools

repo: matImage

save_path: github-repos/MATLAB/mattools-matImage


text:
function [K,H] = calc_Laplacians(I,seg_map,M,eta,beta1,beta2)
[rows,cols,B] = size(I);
N = rows*cols;

if isempty(seg_map)
    [W,Neighbors] = image2graph(I,eta,1e-9);
else
    [W,Neighbors] = image2graph(double(seg_map),1e-3,1e-9);
end

D = diag(sum(W,2));
L = D - W;
L = sparse(L);
K = L - beta2/beta1*speye(N);

W = ones(M,M);
D = diag(sum(W,2));
H = D - W;

W = diag(ones(1,B-1),-1) + diag(ones(1,B-1),1);
D = diag(sum(W,2));
G = D - W;
G = sparse(G);

author: zhouyuanzxcv

repo: Hyperspectral


text:
classdef GUI < handle
%GUI - The class of the main figure of PlatEMO.

%------------------------------- 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".
%--------------------------------------------------------------------------

    properties(SetAccess = private)
        app = struct();     % All the components
        icon;               % Icons
        algList;            % Algorithm list
        proList;            % Problem list
        metList;            % Metric list
    end
    methods
        %% Establish the figure window
        function obj = GUI()
            % Load the data
            obj.icon = load(fullfile(fileparts(mfilename('fullpath')),'GUI'),'-mat');
            obj.readList();

            % Create the window
            obj.app.figure   = uifigure('Name','PlatEMO v4.1','Position',[0 0 1200 650],'Interruptible','off','icon',obj.icon.logo1,'BusyAction','cancel','Visible','off','WindowButtonMotionFcn',@(~,~)[]);
            obj.app.maingrid = uigridlayout(obj.app.figure,'RowHeight',{25,80,'1x'},'ColumnWidth',{'1x'},'Padding',[0 0 0 0],'RowSpacing',0);

            % Create the tab buttons
            obj.app.grid(1)    = GUI.APP(1,1,uigridlayout(obj.app.maingrid,'RowHeight',{'1x'},'ColumnWidth',{80,80,'1x',100},'Padding',[0 0 0 0],'ColumnSpacing',0,'BackgroundColor',[0 .25 .45]));
            tempPanel          = GUI.APP(1,1,uipanel(obj.app.grid(1),'BorderType','none','BackgroundColor',[0 .25 .45]));
            obj.app.buttonT(1) = uibutton(tempPanel,'Position',[-5 -5 90 35],'Text','Modules','FontSize',14,'FontColor','k','BackgroundColor',[.94 .94 .94],'ButtonpushedFcn',{@obj.cb_tab,1});
            tempPanel          = GUI.APP(1,2,uipanel(obj.app.grid(1),'BorderType','none','BackgroundColor',[0 .25 .45]));
            obj.app.buttonT(2) = uibutton(tempPanel,'Position',[-5 -5 90 35],'Text','Support','FontSize',14,'FontColor','w','BackgroundColor',[0 .25 .45],'ButtonpushedFcn',{@obj.cb_tab,2});
            tempPanel          = GUI.APP(1,4,uipanel(obj.app.grid(1),'BorderType','none','BackgroundColor',[0 .25 .45]));
            tempImage          = uiimage(tempPanel,'Position',[0 3 99 21],'ImageSource',obj.icon.bar);
            tempPanel2         = uipanel(tempPanel,'Position',[13 4 18 18],'BorderType','none','BackgroundColor',[.549 .6627 .7529]);
            obj.app.buttonT(3) = uibutton(tempPanel2,'Position',[-2 -2 24 24],'Text','','Icon',obj.icon.researchgate,'BackgroundColor',[.549 .6627 .7529],'Tooltip','ResearchGate','ButtonpushedFcn',@(~,~)web('https://www.researchgate.net/publication/312061859','-browser'));
            tempPanel2         = uipanel(tempPanel,'Position',[43 4 18 18],'BorderType','none','BackgroundColor',[.549 .6627 .7529]);
            obj.app.buttonT(4) = uibutton(tempPanel2,'Position',[-2 -2 24 24],'Text','','Icon',obj.icon.github,'BackgroundColor',[.549 .6627 .7529],'Tooltip','GitHub','ButtonpushedFcn',@(~,~)web('https://github.com/BIMK/PlatEMO','-browser'));
            tempPanel2         = uipanel(tempPanel,'Position',[73 4 18 18],'BorderType','none','BackgroundColor',[.549 .6627 .7529]);
            obj.app.buttonT(5) = uibutton(tempPanel2,'Position',[-2 -2 24 24],'Text','','Icon',obj.icon.qq,'BackgroundColor',[.549 .6627 .7529],'Tooltip','QQ','ButtonpushedFcn',@(~,~)web('https://jq.qq.com/?_wv=1027&k=cA5nUOl4','-browser'));

            % Create the menu
            obj.app.grid(2)   = GUI.APP(2,1,uigridlayout(obj.app.maingrid,'RowHeight',{'1x',13,1},'ColumnWidth',{1,75,75,75,'1x',13,1},'Padding',[0 0 0 5],'RowSpacing',5));
            obj.app.button(1) = GUI.APP([1 2],2,uibutton(obj.app.grid(2),'Text',{'Test','Module'},'VerticalAlignment','bottom','FontSize',11,'Icon',obj.icon.test,'IconAlignment','top','Tooltip',{'Test one algorithm on a problem with specified parameter settings.','You can analyse the result and study the performance of the algorithm from various aspects.'},'ButtonpushedFcn',{@obj.cb_module,1}));
            obj.app.button(2) = GUI.APP([1 2],3,uibutton(obj.app.grid(2),'Text',{'Application','Module'},'VerticalAlignment','bottom','FontSize',11,'Icon',obj.icon.application,'IconAlignment','top','Tooltip',{'Use algorithms to solve your own problem.','You can design your own problem and solve it by the suggested algorithms.'},'ButtonpushedFcn',{@obj.cb_module,2}));
            obj.app.button(3) = GUI.APP([1 2],4,uibutton(obj.app.grid(2),'Text',{'Experiment','Module'},'VerticalAlignment','bottom','FontSize',11,'Icon',obj.icon.experiment,'IconAlignment','top','Tooltip',{'Do experiment on multiple algorithms and problems.','You can observe the statistical results shown in a table and save it as an Excel or LaTeX table.'},'ButtonpushedFcn',{@obj.cb_module,3}));
            obj.app.button(4) = GUI.APP([1 2],2,uibutton(obj.app.grid(2),'Visible',false,'Text',{'About','PlatEMO'},'VerticalAlignment','bottom','FontSize',11,'Icon',obj.icon.author,'IconAlignment','top','ButtonpushedFcn',@obj.cb_author));
            obj.app.button(5) = GUI.APP([1 2],3,uibutton(obj.app.grid(2),'Visible',false,'Text',{'User','Manual'},'VerticalAlignment','bottom','FontSize',11,'Icon',obj.icon.help,'IconAlignment','top','ButtonpushedFcn',@(~,~)web(['file://',fullfile(fileparts(fileparts(mfilename('fullpath'))),'manual.pdf')],'-browser')));
            obj.app.tip       = GUI.APP(2,6,uiimage(obj.app.grid(2),'ImageSource',obj.icon.tip2,'ImageClickedFcn',@obj.cb_fold,'UserData',true));
            tempLine          = GUI.APP(3,[1 7],uipanel(obj.app.grid(2),'BackgroundColor',[.8 .8 .8]));

            % Create the modules
            movegui(obj.app.figure,'center');
            obj.app.figure.addlistener('CurrentPoint','PostSet',@obj.cb_motion);
            obj.cb_module([],[],obj.icon.GUIsetting);
            obj.app.figure.Visible = 'on';
        end
    end
	methods(Access = private)
        %% Change the menu buttons
        function cb_tab(obj,~,~,type)
            switch type
                case 1
                    [obj.app.button(1:3).Visible] = deal(true);
                    [obj.app.button(4:5).Visible] = deal(false);
                    obj.app.buttonT(1).BackgroundColor = [.94 .94 .94];
                    obj.app.buttonT(1).FontColor       = 'k';
                    obj.app.buttonT(2).BackgroundColor = [0 .25 .45];
                    obj.app.buttonT(2).FontColor       = 'w';
                case 2
                    [obj.app.button(1:3).Visible] = deal(false);
                    [obj.app.button(4:5).Visible] = deal(true);
                    obj.app.buttonT(1).BackgroundColor = [0 .25 .45];
                    obj.app.buttonT(1).FontColor       = 'w';
                    obj.app.buttonT(2).BackgroundColor = [.94 .94 .94];
                    obj.app.buttonT(2).FontColor       = 'k';
            end
            obj.app.maingrid.RowHeight = {25,80,'1x'};
        end
        %% Fold or unfold the menu
        function cb_fold(obj,~,~)
            obj.app.tip.UserData = ~obj.app.tip.UserData;
            if obj.app.tip.UserData
                obj.app.tip.ImageSource = obj.icon.tip2;
            else
                obj.app.tip.ImageSource = obj.icon.tip1;
                obj.app.buttonT(1).BackgroundColor = [0 .25 .45];
                obj.app.buttonT(1).FontColor       = 'w';
                obj.app.buttonT(2).BackgroundColor = [0 .25 .45];
                obj.app.buttonT(2).FontColor       = 'w';
                obj.app.maingrid.RowHeight         = {25,0,'1x'};
            end
        end
        %% Hide the menu when moving out of it
        function cb_motion(obj,~,~)
            if obj.app.maingrid.RowHeight{2} > 0 && ~obj.app.tip.UserData && obj.app.figure.CurrentPoint(2) < obj.app.figure.Position(4)-105
                obj.app.buttonT(1).BackgroundColor = [0 .25 .45];
                obj.app.buttonT(1).FontColor       = 'w';
                obj.app.buttonT(2).BackgroundColor = [0 .25 .45];
                obj.app.buttonT(2).FontColor       = 'w';
                obj.app.maingrid.RowHeight         = {25,0,'1x'};
            end
        end
        %% Read the function lists
        function readList(obj)
            % Read the algorithm list
            LabelStr    = {'none','single','multi','many','real','integer','label','binary','permutation','large','constrained','expensive','multimodal','sparse','dynamic','multitask','bilevel','robust'};
            obj.algList = obj.readList2('Algorithms',LabelStr);
            obj.proList = obj.readList2('Problems',LabelStr);
            obj.metList = obj.readList2('Metrics',[LabelStr,'min','max']);
        end
        function List = readList2(obj,folder,LabelStr)
            List    = {};
            Folders = split(genpath(fullfile(fileparts(mfilename('fullpath')),'..',folder)),pathsep);
            for i = 1 : length(Folders)
                Files = what(Folders{i});
                Files = Files.m;
                for j = 1 : length(Files)
                    f = fopen(Files{j});
                    fgetl(f);
                    str = regexprep(fgetl(f),'^\s*%\s*','','once');
                    fclose(f);
                    labelstr = regexp(str,'(?<=<).*?(?=>)','match');
                    if ~isempty(labelstr)
                        label = false(length(labelstr),length(LabelStr));
                        for k = 1 : length(labelstr)
                            label(k,:) = ismember(LabelStr,split(labelstr{k},'/'));
                        end
                        if any(label(:))
                            List = [List;{label},Files{j}(1:end-2)];
                        end
                    end
                end
            end
        end
        %% Change the module
        function cb_module(obj,~,~,GUIsetting)
            name = {'module_test','module_app','module_exp'};
            for i = 1 : length(name)
                if isfield(obj.app,name{i})
                    obj.app.(name{i}).app.maingrid.Visible = i==GUIsetting;
                elseif i == GUIsetting
                    obj.app.(name{i}) = feval(name{i},obj);
                end
            end
            save(fullfile(fileparts(mfilename('fullpath')),'GUI'),'GUIsetting','-append');
        end
        %% Show the figure of about PlatEMO
        function cb_author(obj,~,~)
            P = obj.app.figure.Position;
            C = obj.app.figure.CurrentPoint;
            f = uifigure('Name','About PlatEMO','Position',[P(1)+C(1) P(2)+C(2)-220 290 200],'Color','w','icon',obj.icon.logo1,'Resize','off');
            uiimage(f,'Position',[145 40 150 150],'ImageSource',obj.icon.logo2);
            uilabel(f,'Position',[10 160 170 30],'Text',obj.app.figure.Name,'HorizontalAlignment','left','FontSize',18);
            uilabel(f,'Position',[10 130 160 40],'Text',{'Evolutionary Multi-Objective','Optimization Platform'},'HorizontalAlignment','left','FontSize',12,'FontAngle','italic','FontColor',[.4 .4 .4]);
            uilabel(f,'Position',[10 80 150 40],'Text',{'Copyright (c) 2023','BIMK Group'},'HorizontalAlignment','left','FontSize',12);
            uilabel(f,'Position',[10 20 150 50],'Text',{'<Contact>','field910921@gmail.com','bimk.ahu.edu.cn'},'HorizontalAlignment','left','FontSize',12);
            uibutton(f,'Position',[210 10 70 22],'Text','OK','ButtonpushedFcn',@(~,~)delete(f));
        end
    end
    methods(Static)
        %% Generate a component
        function app = APP(row,column,app)
            app.Layout.Row    = row;
            app.Layout.Column = column;
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
%MINC Minimum combining classifier
%
% 	W = MINC(V)
% 	W = V*MINC
%
% INPUT
%   V     Set of classifiers
%
% OUTPUT
%   W    Minimum combining classifier on V
%
% DESCRIPTION
% If V = [V1,V2,V3, ... ] is a set of classifiers trained on the
% same classes and W is the minimum combiner: it selects the class
% with the minimum of the outputs of the input classifiers. This
% might also be used as A*[V1,V2,V3]*MINC in which A is a dataset to
% be classified. Consequently, if S is a dissimilarity matrix with
% class feature labels (e.g. S = A*PROXM(A,'d')) then S*MINC*LABELD
% is the nearest neighbor classifier.
%
% If it is desired to operate on posterior probabilities then the
% input classifiers should be extended like V = V*CLASSC;
%
% The base classifiers may be combined in a stacked way (operating
% in the same feature space by V = [V1,V2,V3, ... ] or in a parallel
% way (operating in different feature spaces) by V = [V1;V2;V3; ... ]
%
% SEE ALSO (PRTools Guide)
% MAPPINGS, DATASETS, VOTEC, MAXC, MEANC, MEDIANC, PRODC,
% AVERAGEC, STACKED, PARALLEL
%
% EXAMPLES
% See PREX_COMBINING

% Copyright: R.P.W. Duin, duin@ph.tn.tudelft.nl
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands

% $Id: minc.m,v 1.2 2006/03/08 22:06:58 duin Exp $

function w = minc(p1)

	type = 'min'; % define the operation processed by FIXEDCC.

	% define the name of the combiner.
	% this is the general procedure for all possible calls of fixed combiners
	% handled by FIXEDCC
	name = 'Minimum combiner';

	if nargin == 0
		w = prmapping('fixedcc','combiner',{[],type,name});
	else
		w = fixedcc(p1,[],type,name);
	end

	if isa(w,'prmapping')
		w = setname(w,name);
	end

return

author: marianux

repo: ecg-kit

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


text:
%% Copyright (C) 2014, 2016 Colin B. Macdonald
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy 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 software 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 software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @defmethod @@sym xor (@var{x}, @var{y})
%% Logical xor of symbolic arrays.
%%
%% Examples:
%% @example
%% @group
%% xor(sym(true), sym(true))
%%   @result{} ans = (sym) False
%% @end group
%%
%% @group
%% syms x y
%% xor (x, y)
%%   @result{} (sym) x ⊻ y
%% @end group
%% @end example
%%
%% @seealso{@@sym/and, @@sym/or, @@sym/not, @@sym/eq, @@sym/ne,
%%          @@sym/logical, @@sym/isAlways}
%% @end defmethod

function r = xor(x, y)

  if (nargin ~= 2)
    print_usage ();
  end

  r = elementwise_op ('Xor', sym(x), sym(y));

end

%!shared t, f
%! t = sym(true);
%! f = sym(false);

%!test
%! % simple
%! assert (isequal (xor(t, f), t))
%! assert (isequal (xor(t, t), f))

%!test
%! % array
%! w = [t t f f];
%! z = [t f t f];
%! assert (isequal (xor(w, z), [f t t f]))

%!xtest
%! % output is sym even for scalar t/f
%! % ₣IXME: should match other bool fcns
%! assert (isa (xor(t, f), 'sym'))

%!test
%! % eqns
%! syms x
%! e = xor(x == 4, x == 5);
%! assert (isequal (subs(e, x, [3 4 5 6]), [f t t f]))

%!test
%! % eqns, exclusive
%! syms x
%! e = xor(x == 3, x^2 == 9);
%! assert (isequal (subs(e, x, [-3 0 3]), [t f f]))

%!error xor (sym('x'), 1, 2)

repo: octsympy


text:
classdef TestDenoise_TVL1
    %TestDenoise_TVL1

    properties (Constant)
        im = fullfile(mexopencv.root(),'test','lena.jpg');
    end

    methods (Static)
        function test_1
            img = cv.imread(TestDenoise_TVL1.im, ...
                'Grayscale',true, 'ReduceScale',2);
            images = repmat({img},1,5);
            out = cv.denoise_TVL1(images, 'Lambda',1.0, 'NIters',30);
            validateattributes(out, {class(img)}, {'size',size(img)});
        end

        function test_2
            % we use IMNOISE from Image Processing Toolbox
            if ~mexopencv.require('images')
                error('mexopencv:testskip', 'toolbox');
            end

            img = cv.imread(TestDenoise_TVL1.im, ...
                'Grayscale',true, 'ReduceScale',2);
            images = cell(1,5);
            for i=1:numel(images)
                images{i} = imnoise(img, 'gaussian');
            end
            out = cv.denoise_TVL1(images, 'Lambda',1.0, 'NIters',30);
            validateattributes(out, {class(img)}, {'size',size(img)});
        end

        function test_3
            img = cv.imread(TestDenoise_TVL1.im, ...
                'Grayscale',true, 'ReduceScale',2);
            images = cell(1,5);
            for i=1:numel(images)
                images{i} = make_noisy(img, 20, 0.02);
            end
            out = cv.denoise_TVL1(images);
            validateattributes(out, {class(img)}, {'size',size(img)});
        end

        function test_4
            img = cv.imread(TestDenoise_TVL1.im, ...
                'Grayscale',true, 'ReduceScale',2);
            images = cell(1,5);
            for i=1:numel(images)
                images{i} = make_spotty(img);
            end
            out = cv.denoise_TVL1(images);
            validateattributes(out, {class(img)}, {'size',size(img)});
        end

        function test_error_argnum
            try
                cv.denoise_TVL1();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end

% https://github.com/opencv/opencv/blob/3.1.0/modules/photo/test/test_denoise_tvl1.cpp

function noisy = make_noisy(img, sigma, pepper_salt_ratio)
    noise = uint8(randn(size(img))*sigma + 128);
    noisy = uint8(double(img) + double(noise) - 128);
    noise = uint8((randn(size(noise))*2)*255);
    mask = randi([0 round(1/pepper_salt_ratio)], size(img), 'uint8');
    mask(:,1:fix(end/2)) = 1;
    noise(mask~=0) = 128;
    noisy = uint8(double(noisy) + double(noise) - 128);
end

function img = make_spotty(img, r, n)
    if nargin < 3, n = 1000; end
    if nargin < 2, r = 3; end
    for i=1:n
        x = randi([1 size(img,2)-r-1]);
        y = randi([1 size(img,1)-r-1]);
        img(x:x+r, y:y+r) = randi([0 1])*255;
    end
end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
 function [xs, info] = pwls_pcg(x, G, W, yi, nder1, R, ...
		M, niter, stepper)
%function [xs, info] = pwls_pcg(x, G, W, yi, nder1, R, ...
%		M, niter, stepper)
%
% weighted least squares with convex non-quadratic penalty
% via preconditioned conjugate gradient algorithm
% cost(x) = (y-Gx)'W(y-Gx)/2 - n'(y-Gx) + R(x)
%
% in
%	x	[np,1]		initial estimate
%	G	[nd,np]		system matrix
%	W	[nd,nd]		data weighting matrix, usually diag_sp(wi)
%	yi	[nd,1]		noisy data
%	nder1	[nn,1]		linear term (obsolete: use "0")
%	R			penalty object (see Reg1.m)
%	M	[np,np]		preconditioner (use "1" if none)
%	niter			# total iterations
%	stepper			method for step-size line search
%				use {} for a good default
% out
%	xs	[np,niter]	estimates each iteration
%	info	[niter, 3]	gamma, step, time
%
% Copyright 1996-7, Jeff Fessler, The University of Michigan

warning 'pwls_pcg is obsolete; use pwls_pcg1 instead'

if nargin < 8, help(mfilename), error args, end

cpu etic

if isempty(nder1), nder1 = 0; end
if isempty(M), M = 1; end
if nder1 ~= 0, error 'nder1 = 0 required', end

if ~isvar('stepper') || isempty(stepper)
	stepper = {'qs', 3};	% quad surr with this # of subiterations
end

xs = zeros(length(x), niter);
xs(:,1) = x;

info = zeros(niter,3);

%
% initialize projections
%
Gx = G * x;

oldinprod = 0;

% iterate
for ii=2:niter
	ticker(mfilename, ii, niter)

	%
	% (negative) gradient
	%
	ngrad = G' * (W * (yi-Gx) - nder1);

	pgrad = R.cgrad(R, x);
	ngrad = ngrad - pgrad;

	%
	% preconditioned gradient
	pregrad = M * ngrad;

	% direction
	newinprod = ngrad' * pregrad;
	if ii == 2
		ddir = pregrad;
		gamma = 0;
	else
		if oldinprod == 0
			warn 'inprod=0. going nowhere!'
			gamma = 0;
		else
			gamma = newinprod / oldinprod;	% Fletcher-Reeves
%			gamma = (newinprod - oldgrad' * pregrad) / oldinprod;
		end
		ddir = pregrad + gamma * ddir;
	end
	oldgrad = ngrad;
	oldinprod = newinprod;

	% check if descent direction
	if real(ddir' * ngrad) < 0
		warning 'wrong direction'
		keyboard
%		ddir = pregrad;	% revert
%		oldinprod = 0;	% reset
	end

	% step size in search direction
	Gdir = G * ddir;
%	Cdir = R.C * ddir;

	% one step based on quadratic surrogate for penalty
	if streq(stepper{1}, 'qs1')
%		pdenom = Cdir' * (R.wpot(R.wt, Cdir) .* Cdir); % cannot be?
		pdenom = (abs(ddir).^2)' * R.denom(R, x);
		denom = Gdir'*(W*Gdir) + pdenom;
		if denom == 0
			warning 'found exact solution???  step=0 now!?'
			step = 0;
		else
			step = real((ddir' * grad) / denom);
		end

	% iteratively minimize \Half || y-G (x+alf*ddir) ||_W^2 + R(x + alf*ddir)
	elseif streq(stepper{1}, 'qs')
		nsub = stepper{2};
		dGWGd = Gdir'*(W*Gdir);
		dGWr = Gdir'*(W*(yi-Gx));
		step = 0;
		for is=1:nsub
%			pdenom = Cdir' * (R.wpot(R.wt, Cdir) .* Cdir);
			pdenom = (abs(ddir).^2)' * R.denom(R, x+step*ddir);
			denom = dGWGd + pdenom;
			pgrad = R.cgrad(R, x + step * ddir);
			step = step - (-dGWr + step * dGWGd + ddir' * pgrad) ...
				/ denom;
%			printf('%d-%d %g', ii, is, step)
		end

	else
		error 'bad stepper'
	end

	if step < 0
		warning('downhill?')
		keyboard
	end

	% update
	Gx	= Gx  + step * Gdir;
%	Cx	= Cx  + step * Cdir;
	x	= x + step * ddir;
	xs(:,ii) = x;

	info(ii,1) = gamma;
	info(ii,2) = step;
	info(ii,3) = cpu('etoc');	% accum. time
end

author: JeffFessler

repo: mirt

save_path: github-repos/MATLAB/JeffFessler-mirt


text:
function x=stdtinv(p,v)
% Inverse Cumulative Distribution Function (CDF) of the Standardized T
% distribution; Maps [0,1] to a standardized Students-t with V degrees of freedom
%
% USAGE:
%   X = stdtinv(P,V)
%
% INPUTS:
%   P     - Values to be inverted, P in [0,1]
%   V     - Degree of freedom parameters, either scalar or size(X)
%
% OUTPUTS:
%   X     - Standardized T distributed random variables corresponding to P
%
% COMMENTS:
%   V>2
%
% REFERENCES:
%   [1] Cassella and Berger (1990) 'Statistical Interence'
%
% See also STDTCDF, STDTINV, STDTRND, STDTLOGLIK, TPDF

% Copyright:
% Kevin Sheppard
% kevin.sheppard@economics.ox.ac.uk
% Revision: 3    Date: 9/1/2005

if nargin~=2
    error('2 inputs required')
end

[err, errtext, sizeOut, v] = iscompatible(1,v,size(p));
if err
    error(errtext)
end

x=tinv(p,v);

stdev=sqrt(v./(v-2));
stdev(v<=2)=NaN;
x=x./stdev;

author: bashtage

repo: mfe-toolbox


% params
totalNum = 7385291;
bValue = 3000;
lamda = 0.5;
qFile = '/home/yinhuan/Data/mapModel/kitti_10/weightVector.txt';
visFilesDir = '/home/yinhuan/Data/mapModel/kitti_10/visMatrix/';
maxQ = 48;
minQ = 1;

splitLength_0 = 50;
saveResultsDir_0 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/0/';
saveReIndexFile_0 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/index/0.txt';
saveNewQFile_0 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/weight/0.txt';

splitLength_1 = 100;
saveResultsDir_1 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/1/';
saveReIndexFile_1 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/index/1.txt';
saveNewQFile_1 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/weight/1.txt';

splitLength_2 = 200;
saveResultsDir_2 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/2/';
saveReIndexFile_2 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/index/2.txt';
saveNewQFile_2 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/weight/2.txt';

splitLength_3 = 400;
saveResultsDir_3 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/3/';
saveReIndexFile_3 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/index/3.txt';
saveNewQFile_3 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/weight/3.txt';

splitLength_4 = 800;
saveResultsDir_4 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/4/';
saveReIndexFile_4 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/index/4.txt';
saveNewQFile_4 = '/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/weight/4.txt';

%% iteration of optimization

visCells_origin = fromVisDirToCells(visFilesDir);

[ epsilon_soft_0, time_sum_0  ] = Uniform_loopCompress_Cells( lamda, qFile, visCells_origin, splitLength_0, totalNum, bValue, saveResultsDir_0 );
min_cost_0 = get_min_cost(minQ, maxQ, saveResultsDir_0, qFile, lamda, epsilon_soft_0);
[totalNum_0, visCells_0] = deleteZeroPoints_Cells( qFile, visCells_origin, saveResultsDir_0, saveReIndexFile_0, saveNewQFile_0 );

[ epsilon_soft_1, time_sum_1  ] = Uniform_loopCompress_Cells( lamda, saveNewQFile_0, visCells_0, splitLength_1, totalNum_0, bValue, saveResultsDir_1 );
min_cost_1 = get_min_cost(minQ, maxQ, saveResultsDir_1, saveNewQFile_0, lamda, epsilon_soft_1);
[totalNum_1, visCells_1] = deleteZeroPoints_Cells( saveNewQFile_0, visCells_0, saveResultsDir_1, saveReIndexFile_1, saveNewQFile_1 );

[ epsilon_soft_2, time_sum_2  ] = Uniform_loopCompress_Cells( lamda, saveNewQFile_1, visCells_1, splitLength_2, totalNum_1, bValue, saveResultsDir_2 );
min_cost_2 = get_min_cost(minQ, maxQ, saveResultsDir_2, saveNewQFile_1, lamda, epsilon_soft_2);
[totalNum_2, visCells_2] = deleteZeroPoints_Cells( saveNewQFile_1, visCells_1, saveResultsDir_2, saveReIndexFile_2, saveNewQFile_2 );

[ epsilon_soft_3, time_sum_3  ] = Uniform_loopCompress_Cells( lamda, saveNewQFile_2, visCells_2, splitLength_3, totalNum_2, bValue, saveResultsDir_3 );
min_cost_3 = get_min_cost(minQ, maxQ, saveResultsDir_3, saveNewQFile_2, lamda, epsilon_soft_3);
[totalNum_3, visCells_3] = deleteZeroPoints_Cells( saveNewQFile_2, visCells_2, saveResultsDir_3, saveReIndexFile_3, saveNewQFile_3 );

[ epsilon_soft_4, time_sum_4  ] = Uniform_loopCompress_Cells( lamda, saveNewQFile_3, visCells_3, splitLength_4, totalNum_3, bValue, saveResultsDir_4 );
min_cost_4 = get_min_cost(minQ, maxQ, saveResultsDir_4, saveNewQFile_3, lamda, epsilon_soft_4);
[totalNum_4, visCells_4] = deleteZeroPoints_Cells( saveNewQFile_3, visCells_3, saveResultsDir_4, saveReIndexFile_4, saveNewQFile_4 );

%% save the results

compressIndex_3 = anal_reindex_last(saveResultsDir_4, saveReIndexFile_3);
compressIndex_2 = anal_reindex_middle(compressIndex_3, saveReIndexFile_2);
compressIndex_1 = anal_reindex_middle(compressIndex_2, saveReIndexFile_1);
compressIndex_0 = anal_reindex_middle(compressIndex_1, saveReIndexFile_0);

dlmwrite('/home/yinhuan/Data/mapModel/kitti_10/iter_b_3000/compressIndex_final.txt', compressIndex_0, 'precision', '%d');


text:
function V = vmp_read_volume(info)
% function for readingV MP BrainVoyager ( .vmp ) volume file
%
% volume = vmp_read_volume(file-header)
%
% examples:
% 1: info = vmp_read_volumegipl_read_header()
%    V = gvmp_read_volume(info);
%    imshow(squeeze(V(:,:,round(end/2))),[]);
%
% 2: V = vmp_read_volume('test.vmp');

if(~isstruct(info)), info=vmp_read_header(info); end

fp = fopen(info.Filename, 'rb', 'ieee-le');
if (fp == -1)
    error('The file was not found or could not be oppened')
end
% check version type
if fread(fp, 1, 'int16') ~= 3
    fclose(fp);
    error('Only version 3 files are supported')
end

% check number of maps
if fread(fp, 1, 'int32') ~= 1
    fclose(fp);
    error('Only vmp file with one map are supported')
end

% check number of maps
stat_type = fread(fp, 1, 'int32');
if stat_type ~= 1 & stat_type ~= 4
    fclose(fp);
    error('Only F and t tests are supported')
end

% skip a few fields
fseek(fp, 17, 'cof');

df1 = fread(fp, 1, 'int32');
df2 = fread(fp, 1, 'int32');

% skip a few fields
fseek(fp, 21, 'cof');
while true
    if fread(fp, 1, 'int8') == 0
        break
    end
end
fseek(fp, 12, 'cof');

% find the dimensions
x_start = fread(fp, 1, 'int32');
x_stop  = fread(fp, 1, 'int32');
DimX    = (x_stop - x_start) / 3;

y_start = fread(fp, 1, 'int32');
y_stop  = fread(fp, 1, 'int32');
DimY    = (y_stop - y_start) / 3;

z_start = fread(fp, 1, 'int32');
z_stop  = fread(fp, 1, 'int32');
DimZ    = (z_stop - z_start) / 3;

fseek(fp, 4, 'cof');

% read the data
len = (3*DimX+1) * (3*DimY+1) * (3*DimZ+1);
V = fread(fp, len, 'float');

fclose(fp);

author: tomdoel

repo: pulmonarytoolkit


text:
function varargout = lvd_editNonSeqEventGUI(varargin)
% LVD_EDITNONSEQEVENTGUI MATLAB code for lvd_editNonSeqEventGUI.fig
%      LVD_EDITNONSEQEVENTGUI, by itself, creates a new LVD_EDITNONSEQEVENTGUI or raises the existing
%      singleton*.
%
%      H = LVD_EDITNONSEQEVENTGUI returns the handle to a new LVD_EDITNONSEQEVENTGUI or the handle to
%      the existing singleton*.
%
%      LVD_EDITNONSEQEVENTGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in LVD_EDITNONSEQEVENTGUI.M with the given input arguments.
%
%      LVD_EDITNONSEQEVENTGUI('Property','Value',...) creates a new LVD_EDITNONSEQEVENTGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before lvd_editNonSeqEventGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to lvd_editNonSeqEventGUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help lvd_editNonSeqEventGUI

% Last Modified by GUIDE v2.5 05-Dec-2018 14:25:39

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @lvd_editNonSeqEventGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @lvd_editNonSeqEventGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before lvd_editNonSeqEventGUI is made visible.
function lvd_editNonSeqEventGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to lvd_editNonSeqEventGUI (see VARARGIN)

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

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

    lvdData = varargin{2};
    setappdata(hObject, 'lvdData', lvdData);

    populateGUI(nonSeqEvt, lvdData, handles);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(nonSeqEvt, lvdData, handles)
    handles.eventNameLabel.String = nonSeqEvt.evt.name;

    listBoxStr = vertcat(' ',lvdData.script.getListboxStr());
    handles.lwrBndEvtCombo.String = listBoxStr;

    if(not(isempty(nonSeqEvt.lwrBndEvt)))
        handles.lwrBndEvtCombo.Value = lvdData.script.getNumOfEvent(nonSeqEvt.lwrBndEvt) + 1;
    else
        handles.lwrBndEvtCombo.Value = 1;
    end

    listBoxStr = vertcat(' ',lvdData.script.getListboxStr());
    handles.uprBndEvtCombo.String = listBoxStr;

    if(not(isempty(nonSeqEvt.uprBndEvt)))
        handles.uprBndEvtCombo.Value = lvdData.script.getNumOfEvent(nonSeqEvt.uprBndEvt) + 1;
    else
        handles.uprBndEvtCombo.Value = 1;
    end

    handles.maxExecsText.String = num2str(nonSeqEvt.maxNumExecs);

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

% Get default command line output from handles structure
    if(isempty(handles))
        varargout{1} = [];
    else
        lvdData = getappdata(handles.lvd_editNonSeqEventGUI, 'lvdData');
        nonSeqEvt = getappdata(handles.lvd_editNonSeqEventGUI, 'nonSeqEvt');

        lwrBndValue = handles.lwrBndEvtCombo.Value;
        if(lwrBndValue == 1)
            lwrBndEvt = LaunchVehicleEvent.empty(1,0);
        else
            lwrBndEvtNum = lwrBndValue - 1;
            lwrBndEvt = lvdData.script.getEventForInd(lwrBndEvtNum);
        end
        nonSeqEvt.lwrBndEvt = lwrBndEvt;

        uprBndValue = handles.uprBndEvtCombo.Value;
        if(uprBndValue == 1)
            uprBndEvt = LaunchVehicleEvent.empty(1,0);
        else
            uprBndEvtNum = uprBndValue - 1;
            uprBndEvt = lvdData.script.getEventForInd(uprBndEvtNum);
        end
        nonSeqEvt.uprBndEvt = uprBndEvt;

        nonSeqEvt.maxNumExecs = str2double(handles.maxExecsText.String);
        nonSeqEvt.numExecsRemaining = str2double(handles.maxExecsText.String);

        close(handles.lvd_editNonSeqEventGUI);
    end

% --- Executes on button press in saveAndCloseButton.
function saveAndCloseButton_Callback(hObject, eventdata, handles)
% hObject    handle to saveAndCloseButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    errMsg = validateInputs(handles);

    if(isempty(errMsg))
       uiresume(handles.lvd_editNonSeqEventGUI);
    else
        msgbox(errMsg,'Errors were found while editing the non-sequential event.','error');
    end

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

    value = str2double(get(handles.maxExecsText,'String'));
    enteredStr = get(handles.maxExecsText,'String');
    numberName = 'Max. Number of Executions';
    lb = 1;
    ub = Inf;
    isInt = true;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

% --- Executes on selection change in lwrBndEvtCombo.
function lwrBndEvtCombo_Callback(hObject, eventdata, handles)
% hObject    handle to lwrBndEvtCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns lwrBndEvtCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from lwrBndEvtCombo

% --- Executes during object creation, after setting all properties.
function lwrBndEvtCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to lwrBndEvtCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

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

% --- Executes on selection change in uprBndEvtCombo.
function uprBndEvtCombo_Callback(hObject, eventdata, handles)
% hObject    handle to uprBndEvtCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns uprBndEvtCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from uprBndEvtCombo

% --- Executes during object creation, after setting all properties.
function uprBndEvtCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to uprBndEvtCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

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

function maxExecsText_Callback(hObject, eventdata, handles)
% hObject    handle to maxExecsText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of maxExecsText as text
%        str2double(get(hObject,'String')) returns contents of maxExecsText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

% --- Executes during object creation, after setting all properties.
function maxExecsText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to maxExecsText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

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

% --- Executes on button press in editEventButton.
function editEventButton_Callback(hObject, eventdata, handles)
% hObject    handle to editEventButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    nonSeqEvt = getappdata(handles.lvd_editNonSeqEventGUI, 'nonSeqEvt');
    event = nonSeqEvt.evt;

%     lvd_editEventGUI(event, true);
    output = AppDesignerGUIOutput({false});
    lvd_editEventGUI_App(event, true, output);

    handles.eventNameLabel.String = nonSeqEvt.evt.name;

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
%% MULTIGRID OF FOR THE STOKES EQNS IN 2D
%
% This example is to show the convergence of multigrid methods for various
% finite element approximation of the Stokes equation on the unit square:
%
%       -div(mu*grad u) + grad p = f in \Omega,
%                        - div u = 0  in \Omega,
%                              u = g_D  on \Gamma.
%
% with the pure Dirichlet boundary condition.
%
% Reference
%
% M. Wang and L. Chen. Multigrid Methods for the Stokes equations
% using Distributive Gauss-Seidel Relaxations based on the Least Squares
% Commutator. Journal of Scientific Computing. 56(2): 409-431, 2013.

clear variables;
close all;

%% Setting
[node,elem] = squaremesh([0,1,0,1],0.125);
% [node,elem] = circlemesh(0,0,1,0.25);
% [node,elem] = uniformrefine(node,elem);
bdFlag = setboundary(node,elem,'Dirichlet');
mesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);
figure;
showmesh(node,elem); pause(0.5);
% pde
pde = Stokesdata1;
%  pde = StokesZulehnerdata;
option.L0 = 0;
option.maxIt = 4;
option.printlevel = 1;
option.plotflag = 0;
option.rateflag = 0;

%% MG options
option.solver = 'asmg';
option.smoothingstep = 2;
option.smootherbarSp = 'SGS';

%% CR-P0 element
disp('CR-P0')
option.elemType = 'CRP0';
femStokes(mesh,pde,option);

%% P2-P0 element
disp('P2-P0')
option.elemType = 'P2P0';
femStokes(mesh,pde,option);

%% P2-P1 element
disp('P2-P1')
option.elemType = 'P2P1';
option.solver = 'asmg';
femStokes(mesh,pde,option);

%% isoP2-P0 element
disp('isoP2-P0')
option.elemType = 'isoP2P0';
femStokes(mesh,pde,option);

%% isoP2-P1 element
disp('isoP2-P1')
option.elemType = 'isoP2P1';
femStokes(mesh,pde,option);

%% P1b-P1 element
disp('P1b-P1')
option.elemType = 'P1bP1';
femStokes(mesh,pde,option);

repo: ifem


text:
function [yData,betas,P,errors] = tsne_d(D, parameters)
%TSNE_D Performs symmetric t-SNE on the pairwise Euclidean distance matrix D
%
%   [yData,betas,P,errors] = tsne_d(D, parameters)
%
% The function performs symmetric t-SNE on the NxN pairwise
% distance matrix D to construct an embedding with no_dims dimensions
% (default = 2). An initial solution obtained from an other dimensionality
% reduction technique may be specified in initial_solution.
% The perplexity of the Gaussian kernel that is employed can be specified
% through perplexity.
%
%
%   Input variables:
%
%       D -> NxN distance matrix
%       parameters -> structure containing non-default parameters
%
%
%   Output variables:
%
%       yData -> Nx2 (or Nx3) array of embedded values
%       betas -> list of individual area parameters
%       P -> sparse transition matrix
%       errors -> D_{KL}(P || Q) as a function of iteration
%
%
% (C) Laurens van der Maaten, 2010
% University of California, San Diego
%
%  Modified by Gordon J. Berman, 2014
%  Princeton University

    no_dims = parameters.num_tsne_dim;
    perplexity = parameters.perplexity;
    sigmaTolerance = parameters.sigmaTolerance;
    relTol = parameters.relTol;

    if numel(no_dims) > 1
        initial_solution = true;
        yData = no_dims;
        no_dims = size(ydata, 2);
    else
        initial_solution = false;
    end

    D = D / max(D(:));
    [P,betas] = d2p_sparse(D .^ 2, perplexity, sigmaTolerance);
    P(isnan(P)) = 0;

    clear D

    % Run t-SNE
    if initial_solution
        [yData,errors] = tsne_p_sparse(P, parameters, yData, relTol);
    else
        [yData,errors] = tsne_p_sparse(P, parameters, no_dims, relTol);
    end

author: gordonberman

repo: MotionMapper


text:
classdef LRN < dagnn.ElementWise
  properties
    param = [5 1 0.0001/5 0.75]
    % PARAM = [N KAPPA ALPHA BETA], and N is the size of the window.
  end

  methods
    function outputs = forward(obj, inputs, params)
      outputs{1} = vl_nnnormalize(inputs{1}, obj.param) ;
    end

    function [derInputs, derParams] = backward(obj, inputs, param, derOutputs)
      derInputs{1} = vl_nnnormalize(inputs{1}, obj.param, derOutputs{1}) ;
      derParams = {} ;
    end

    function obj = LRN(varargin)
      obj.load(varargin) ;
    end
  end
end

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text:
function tests = tapas_physio_filter_cardiac_test()
% Tests whether bandpass filter on PPU example data works as expected
%
%   tests = tapas_physio_filter_cardiac_test()
%
% IN
%
% OUT
%
% EXAMPLE
%   tapas_physio_filter_cardiac_test
%
%   See also

% Author:   Lars Kasper
% Created:  2019-07-02
% Copyright (C) 2019 TNU, Institute for Biomedical Engineering,
%                    University of Zurich and ETH Zurich.
%
% This file is part of the TAPAS PhysIO Toolbox, which is released under
% the terms of the GNU General Public License (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/>.

tests = functiontests(localfunctions);
end

function test_philips_ppu7t_filter_cheby2(testCase)
%% Compares previously saved Chebychev Type 2 IIR-filtered cropped cardiac
% time course with current re-run of same batch from Philips 7T PPU data
% run GE example and extract physio

pathPhysioPublic = fullfile(fileparts(mfilename('fullpath')), '..', '..', '..');
pathExamples =  fullfile(pathPhysioPublic, '..', 'examples');

pathCurrentExample = fullfile(pathExamples, 'Philips/PPU7T');
cd(pathCurrentExample); % for prepending absolute paths correctly
fileExample = fullfile(pathCurrentExample, 'philips_ppu7t_spm_job.m');
run(fileExample); % retrieve matlabbatch

% remove unnecessary verbosity and processing of resp data
matlabbatch{1}.spm.tools.physio.verbose.level = 0;
matlabbatch{1}.spm.tools.physio.log_files.respiration = {''};

physio = tapas_physio_job2physio(matlabbatch{1}.spm.tools.physio);

%% Run and test for cheby2 filter
physio.preproc.cardiac.filter.type = 'cheby2';
physio.preproc.cardiac.filter.include = 1;
physio.preproc.cardiac.filter.passband = [0.5 3];
physio.preproc.cardiac.filter.stopband = [0.4 3.9];
actPhysio = tapas_physio_main_create_regressors(physio);

% load physio from reference data
fileReferenceData = fullfile(pathExamples, 'TestReferenceResults', 'preproc', ...
    'physio_filter_cardiac_cheby2.mat');
load(fileReferenceData, 'physio');
expPhysio = physio;

% extract cpulse from actual and expected solution and compare
actSolution = actPhysio.ons_secs.c;
expSolution = expPhysio.ons_secs.c;

verifyEqual(testCase, actSolution, expSolution);
end

function test_philips_ppu7t_filter_butter(testCase)
%% Compares previously saved butterworth-filtered cropped cardiac time course
% with current re-run of same batch from Philips 7T PPU data

% run GE example and extract physio
pathPhysioPublic = fullfile(fileparts(mfilename('fullpath')), '..', '..', '..');
% TODO: Make generic!
pathExamples =  fullfile(pathPhysioPublic, '..', 'examples');

pathCurrentExample = fullfile(pathExamples, 'Philips/PPU7T');
cd(pathCurrentExample); % for prepending absolute paths correctly
fileExample = fullfile(pathCurrentExample, 'philips_ppu7t_spm_job.m');
run(fileExample); % retrieve matlabbatch

% remove unnecessary verbosity and processing of resp data
matlabbatch{1}.spm.tools.physio.verbose.level = 0;
matlabbatch{1}.spm.tools.physio.log_files.respiration = {''};

physio = tapas_physio_job2physio(matlabbatch{1}.spm.tools.physio);

%% run and test for butterworth filter
physio.preproc.cardiac.filter.include = 1;
physio.preproc.cardiac.filter.type = 'butter';
physio.preproc.cardiac.filter.passband = [0.6 3];
physio.preproc.cardiac.filter.stopband = [];
actPhysio = tapas_physio_main_create_regressors(physio);

% load physio from reference data
fileReferenceData = fullfile(pathExamples, 'TestReferenceResults', 'preproc', ...
    'physio_filter_cardiac_butter.mat');
load(fileReferenceData, 'physio');
expPhysio = physio;

% extract cpulse from actual and expected solution and compare
actSolution = actPhysio.ons_secs.c;
expSolution = expPhysio.ons_secs.c;

verifyEqual(testCase, actSolution, expSolution);
end

author: translationalneuromodeling

repo: tapas


text:
function adc=makeAdc(num,varargin)
%makeAdc Create a ADC readout event.
%   adc=makeAdc(n, 'Dwell', dwell) Create ADC with n samples
%   with given dwell time.
%
%   adc=makeAdc(n, 'Duration', dur) Create ADC with n
%   samples and specified total duration.
%
%   adc=makeAdc(..., 'Delay', d) Create ADC with initial delay.
%
%   adc=makeAdc(n, sys, ...) Create ADC considering system properties
%   given in sys. For example, adcDeadTime can be taken into account by
%   making sure that both the before the ADC is as least as long as
%   adcDeadTime and another period of adcDeadTime is added after sampling
%   is finished.
%
%   See also  Sequence.addBlock

persistent parser
if isempty(parser)
    parser = inputParser;
    parser.FunctionName = 'makeAdc';

    addRequired(parser,'numSamples',@(x)(isnumeric(x) && (fix(x)-x)==0));
    addOptional(parser,'system',mr.opts(),@isstruct);
    addParamValue(parser,'dwell',0,@isnumeric);
    addParamValue(parser,'duration',0,@isnumeric);
    addParamValue(parser,'delay',0,@isnumeric);
    addParamValue(parser,'freqOffset',0,@isnumeric);
    addParamValue(parser,'phaseOffset',0,@isnumeric);
end

parse(parser,num,varargin{:});

opt = parser.Results;
adc.type = 'adc';
adc.numSamples = num;
adc.dwell = opt.dwell;
adc.delay = opt.delay;
adc.freqOffset = opt.freqOffset;
adc.phaseOffset = opt.phaseOffset;
adc.deadTime = opt.system.adcDeadTime;

if (opt.dwell==0 && opt.duration==0) || (opt.dwell>0 && opt.duration>0)
    error('Either dwell or duration must be defined');
end

if opt.duration > 0
    adc.dwell = opt.duration/opt.numSamples;
end
if opt.dwell > 0
    adc.duration = opt.dwell*opt.numSamples;
end
if adc.deadTime > adc.delay
    adc.delay = adc.deadTime; % adcDeadTime is added before the actual sampling (and also second time after the sampling period)
end

end

author: pulseq

repo: pulseq

save_path: github-repos/MATLAB/pulseq-pulseq


text:
function res = polynomialTransform2d(pts, coeffs)
%POLYNOMIALTRANSFORM2D Apply a polynomial transform to a set of points.
%
%   RES = polynomialTransform2d(PTS, COEFFS)
%   Transforms the input points PTS given as a N-by-2 array of coordinates
%   using the polynomial transform defined by PARAMS.
%   PARAMS given as [a0 b0 a1 b1 ... an bn]
%
%   Example
%   coeffs = [0 0  1 0  0 1   0.1 0  0 0  0 0.1];
%       %     cte   x    y     x^2   x*y   y^2
%   pts = rand(200, 2) * 2 - 1;
%   pts2 = polynomialTransform2d(pts, coeffs);
%   figure; hold on;
%   drawPoint(pts);
%   drawPoint(pts2, 'g');
%
%   See also
%     transformPoint, fitPolynomialTransform2d

% ------
% Author: David Legland
% E-mail: david.legland@grignon.inra.fr
% Created: 2013-09-04, using Matlab 7.9.0.529 (R2009b)
% Copyright 2013-2022 INRA - Cepia Software Platform

x = pts(:,1);
y = pts(:,2);
nPoints = length(x);

xCoeffs = coeffs(1:2:end);
yCoeffs = coeffs(2:2:end);
nCoeffs = length(xCoeffs);

% allocate memory for result
x2 = zeros(nPoints, 1);
y2 = zeros(nPoints, 1);

% degree from coefficient number
degree = sqrt(9/4 - 4*(1 - nCoeffs)/2) - 1.5;

% iterate over degrees
iCoeff = 0;
for iDegree = 0:degree

    % iterate over binomial coefficients of a given degree
    for k = 0:iDegree
        iCoeff = iCoeff + 1;
        tmp = power(x, iDegree-k) .* power(y, k);
        x2 = x2 + xCoeffs(iCoeff) .* tmp;
        y2 = y2 + yCoeffs(iCoeff) .* tmp;
    end
end

res = [x2 y2];

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function [scoreF,score0] = argmax_fit_token(Mfit_init,lib)
% ARGMAX_FIT_TOKEN Fit a parse to an image, with token-level parameters
% only
%
%  Mfit_init : instance of class MotorProgramFit
%
% Output:
%  scoreF : final score
%  score0 : initial score
%

    % set up objective function
    Mfit = Mfit_init.copy();
    fmin = @(theta) myscore(theta,Mfit,lib);

    % Set-up the optimization problem
    [theta0,lb,ub] = model_to_vec_fit_token(Mfit);
    options = optimset('Display','off');
    options = optimset(options,'Display','iter');
    options = optimset(options,'TolFun',1e-4,'Algorithm','active-set');

    % Run the optimization
    score0 = -fmin(theta0);
    try
        thetaF = fmincon(fmin,theta0,[],[],[],[],lb,ub,[],options);
    catch
        fprintf(1,'*Warning*: optimization failed. Error caught.\n');
        thetaF = theta0;
    end
    scoreF = -fmin(thetaF);

    refill(thetaF,Mfit_init);

end

function refill(theta,M)
    vec_to_model_fit_token(theta,M);
end

% fill the MotorProgram with parameters
% and then score
function minscore = myscore(theta,Mfit,lib)
    Qfit = Mfit.copy(); % we don't want to modify the shared MotorProgramFit base
    refill(theta,Qfit);
    ll = scoreMP_fit(Qfit,lib);
    minscore = -ll;
end

author: brendenlake

repo: BPL

save_path: github-repos/MATLAB/brendenlake-BPL


text:
% Read point cloud from PLY file and return coordinates
function [X, Y, Z] = readPointCloud(plyFile, s)
    if (nargin < 2) s = 1; end;

    ptCloud = pcread(plyFile);
    N = ptCloud.Count;
    if (s<=1)
        idx = randsample(N, round(N*s))';
    else
        idx = randsample(N, s)';
    end
    X = ptCloud.Location(idx,1)';
    Y = ptCloud.Location(idx,2)';
    Z = ptCloud.Location(idx,3)';

    X = double(X); Y = double(Y); Z = double(Z);
end

author: intellhave

repo: SDRSAC

save_path: github-repos/MATLAB/intellhave-SDRSAC


text:
function [z,e]=oneoutnn(x,iil)

[m,n]=size(x);
d=zeros(m,m);
v=double(x)*double(x');
for i=1:m;
    for j=1:m;
        d(i,j)=sqrt(v(i,i)+v(j,j)-2*v(i,j));
    end;
    d(i,i)=10000000000000;
end;
[a,b]=min(d);
e=iil(b');
c=iil-e;
e(:,2)=iil;
z=0;
for i=1:m;
    if c(i)~=0;
        z=z+1;
    end;
end;

author: Sable

repo: mcbench-benchmarks


text:
function pot = convert_to_pot(CPD, pot_type, domain, evidence)
% CONVERT_TO_POT Convert a tabular CPD to one or more potentials
% pots = convert_to_pot(CPD, pot_type, domain, evidence)
%
% pots{i} = CPD evaluated using evidence(domain(:,i))
% If 'domains' is a single row vector, pots will be an object, not a cell array.

ncases = size(domain,2);
assert(ncases==1); % not yet vectorized

sz = dom_sizes(CPD);
ns = zeros(1, max(domain));
ns(domain) = sz;

local_ev = evidence(domain);
obs_bitv = ~isemptycell(local_ev);
odom = domain(obs_bitv);
T = convert_to_table(CPD, domain, local_ev, obs_bitv);

switch pot_type
 case 'u',
  pot = upot(domain, sz, T, 0*myones(sz));
 case 'd',
  ns(odom) = 1;
  pot = dpot(domain, ns(domain), T);
 case {'c','g'},
  % Since we want the output to be a Gaussian, the whole family must be observed.
  % In other words, the potential is really just a constant.
  p = T;
  %p = prob_node(CPD, evidence(domain(end)), evidence(domain(1:end-1)));
  ns(domain) = 0;
  pot = cpot(domain, ns(domain), log(p));
 case 'cg',
  T = T(:);
  ns(odom) = 1;
  can = cell(1, length(T));
  for i=1:length(T)
    can{i} = cpot([], [], log(T(i)));
  end
  pot = cgpot(domain, [], ns, can);
 otherwise,
  error(['unrecognized pot type ' pot_type])
end

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function vCubo = homo2cubo(vHomo)
% homochoric to cubochoric coordinates
%
% Transforms homochoric coordinates of quaternions into cubochoric
% coordinates. This mpas the ball of radius (3*pi/4)^(1/3)) to the cube
% with edge length pi^(2/3).
%
% Input
%  xyz - homochoric coordinates (x,y,z) of N points of the ball
%
% Output
%  XYZ - cubochoric coordinates (X,Y,Z) of N points of the cube
%

% the actual mapping is only defined on one pyramid Pz (z>=abs(x),z>=abs(y))
% map other points by:
%  1. transform coordinates, so that we get a point of Pz
%  2. map the point
%  3. apply the inverse transformation

% for each point find out, which pyramid it lies in (1,2,3,4,5,6)
rId = cuboRegionId(vHomo);

% define permutaions (and inverse ones) for each region (pyramid)
permRegion  = [2 3 1; 3 2 1; 1 3 2; 3 1 2; 1 2 3; 2 1 3];
ipermRegion = [3 1 2; 3 2 1; 1 3 2; 2 3 1; 1 2 3; 2 1 3];

% apply the permutation on each row
vHomo = vHomo(sub2ind(size(vHomo), ...
  (1:size(vHomo,1)).' * [1 1 1] ,permRegion(rId,:)));

% map each point
p = sqrt(sum(vHomo.^2,2));
D = sqrt(2 ./ (1 + abs(vHomo(:,3)) ./ p));
E = sqrt(2 * vHomo(:,1).^2 + vHomo(:,2).^2);
F = sqrt(abs(vHomo(:,1)) + E);
G = sign(vHomo(:,1));
H = sqrt(pi / 12);
I = (6 / pi)^(1/6);
K = D .* sqrt(E) .* F .* I;

vCubo(:,1) = K .* G .* H;
vCubo(:,2) = K ./ H .* (G .* atan(vHomo(:,2)./vHomo(:,1)) - atan(vHomo(:,2)./E));
vCubo(:,3) = sign(vHomo(:,3)) .* p ./ I^2;

% overwrite points with division by zero (occurs along the axes)
isNull = (vHomo(:,1)==0);
vCubo(isNull,:) = vHomo(isNull,:) / (6/pi)^(1/3);

% apply the inverse permutations
vCubo = vCubo(sub2ind(size(vCubo), ...
  (1:size(vCubo,1)).' * [1 1 1] , ipermRegion(rId,:)));

end

author: mtex-toolbox

repo: mtex

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


text:
function J = computeCost(X, y, theta)
% J = COMPUTECOST(X, y, theta) computes the cost for linear regression
% using theta as the parameter for linear regression to fit the data
% points in X and y

m = length(y);

i = 1:m;
J = (1/(2*m)) * sum( ((theta(1) + theta(2) .* X(i,2)) - y(i)) .^ 2); % Un-Vectorized

end

author: atinesh-s

repo: Coursera-Machine-Learning-Stanford


text:
%kPlot2D '2D Plot Object Menuform'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros Plot2D.pane file
%
% Parameters:
% MultiChoice: plot2DXOrientation 'X Orientation', default: 1: 'x orientation'
%    Choices are:
%   1: 'Width'
%   2: 'Height'
%   3: 'Depth'
%   4: 'Time'
%   5: 'Elements'
% Integer: plot2DWidthOffset 'Width Offset', default: 0: 'width offset'
% Integer: plot2DHeightOffset 'Height Offset', default: 0: 'height offset'
% Integer: plot2DDepthOffset 'Depth Offset', default: 0: 'depth offset'
% Integer: plot2DTimeOffset 'Time Offset', default: 0: 'time offset'
% Integer: plot2DElementsOffset 'Elements Offset', default: 0: 'elements offset'
%
% Example: kPlot2D( {'plot2DXOrientation',1;'plot2DWidthOffset',0;'plot2DHeightOffset',0;'plot2DDepthOffset',0;'plot2DTimeOffset',0;'plot2DElementsOffset',0})
%
% Khoros helpfile follows below:
%
% A 2D plot visual object supports the display of a 2D plot.
% .begin tagged
% .item "Plot Type"
% This list selection lets you set the plot type of the 2D plot object.
% Choices include: "Line Plot," "Discrete," "Bar Graph," "Polymarker," and
% "Line Marker."  Line Plot is a simple line graph.  Discrete displays a set of
% vertical lines, from each (x,y) point down to the X axis.  Bar Graph
% displays the usual bar graph.  Polymarker displays a single marker at
% each (x,y) location.  Line Marker is a combination of Line Plot and
% Polymarker, resulting in a "connect the dots" display.
% .item "Line Type"
% There are seven line types available: "Solid," "Dotted," "Dot Dash,"
% "Short Dash," "Long Dash," "Odd Dash," and "Grid Dotted."  The line
% type is not used with Polymarker or color marker plots.
% .item "Marker Type"
% This list selection allows you to control the marker type that is used
% with Polymarker, line marker, and colormarker plots.  There is a wide
% variety of marker types that may be used.
% .item "Color Origination"
% When this attribute is set to "Use Foreground Color," the plot is colored in
% the foreground color.   When set to "Use Data Values," the plot is colored
% according to the plot data.
% .item "Foreground Color"
% This string list lets you select (or type) the foreground color of the
% 2D plot.  It is not used with plot types that are automatically
% colored according to the "D" values in the plot data, which include
% color marker and colorline plots.
% .item "X Orientation"
% This toggle only takes effect when the plot data input is provided via
% a data object (as opposed to an array of Coords).  Furthermore, it
% only applies when the plot data is stored in the value segment of the
% data object (as opposed to the location segment of the data object).
% It dictates how the 2D plot data is to be extracted from the value
% segment of the data object.  The 2D plot data is always extracted as a
% single line, but that line may be oriented by width, height, depth,
% time, or elements (see manual for more details).
% .item "Width, Height, Depth, Time, And Elements Offsets"
% These integer values may be set in conjunction with the "X
% Orientation" toggle.  When "X Orientation" is "not" set to
% "Width," the "Width Offset" may be used to specify the width offset at
% which the line of plot data is to be extracted.  Similarly, "Height
% Offset," "Depth Offset," "Time Offset," and "Elements Offset" may be
% used to specify offsets into height, depth, time, and elements.  Note
% that an offset may only be used when that dimension of the value data
% is greater than 1.
% .end tagged

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

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

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function op = prox_l1_and_sum( q, b, nColumns, zeroID, useMex )

%PROX_L1_AND_SUM    L1 norm with sum(X)=b constraints
%    OP = PROX_L1_AND_SUM( Q ) implements the nonsmooth function
%        OP(X) = norm(Q.*X,1) with constraints
%    Q is optional; if omitted, Q=1 is assumed. But if Q is supplied,
%    then it must be a positive real scalar (or must be same size as X).
%
%    OP = PROX_L1_AND_SUM( Q, B )
%       includes the constraints that sum(X(:)) == B
%       (Default: B=1)
%
%    OP = PROX_L1_AND_SUM( Q, B, nColumns )
%       takes the input vector X and reshapes it to have nColumns
%       and applies this prox to every column
%
%    OP = PROX_L1_AND_SUM( Q, B, nColumns, zeroID )
%       if zeroID == true (it is false by default)
%       then after reshaping X, enforces that X(i,i) = 0
%
%    OP = PROX_L1_AND_SUM( Q, B, nColumns, zeroID, useMex)
%       toggle the usage of prox_l1_and_sum_worker_mex.cc for the computation.
%       useMex defaults to true
%
%
% If available and compiled, this uses TFOCS/mexFiles/prox_l1_and_sum_worker_mex.cc.
% It also checks for TFOCS/mexFiles/shrink_mex2.cc to use as a slower backup.
% To control the number of threads these use, run
%
%   `prox_l1_and_sum_worker_mex(struct('num_threads', 4))`
%
% when constructing your problem.  This will cache the number of threads internally
% and use that number of threads until you restart MATLAB.
%
% Often useful for sparse subpsace clustering (SSC)
%   See, e.g., https://github.com/stephenbeckr/SSC

% Nov 2017, Stephen.Becker@Colorado.edu
% 18 Nov 2018, optimizations by jamesfolberth@gmail.com

if nargin == 0
    q = 1;
elseif ~isnumeric( q ) || ~isreal( q ) ||  any( q(:) < 0) || all(q(:)==0) || numel( q ) ~= 1
    error( 'Argument must be positive.' );
end
if nargin < 2 || isempty(b), b = 1; else, assert( numel(b) == 1 ); end
if nargin < 3 || isempty( nColumns), nColumns = 1;
else assert( numel(nColumns) == 1 && nColumns >= 1 ); end
if nargin < 4 || isempty( zeroID ), zeroID = false; end
if nargin < 5, useMex = true; end

if zeroID && nColumns == 1
    warning('TFOCS:prox_l1_and_sum:zeroDiag',...
        'You requested enforcing zero diagonals but did not set nColumns>1 which is probably a mistake');
end

if useMex
    if 3~=exist('prox_l1_and_sum_worker_mex','file')
        addpath( fullfile( tfocs_where, 'mexFiles' ) );
    end
    if 3==exist('prox_l1_and_sum_worker_mex','file')
        op = tfocs_prox( @(x)f(q,x), @(x,t)prox_f_using_worker(q,b,nColumns,zeroID,x,t) , 'vector' );
        return;
    end
    % else fall back to optimized MATLAB approach
end

% 3/15/18, adding:
%JMF 17 Nov 2018: determine if we have shrink_mex once when constructing the prox handle
if useMex
    if 3~=exist('shrink_mex2','file')
        addpath( fullfile( tfocs_where, 'mexFiles' ) );
    end
    if 3~=exist('shrink_mex2','file')
        useMex = false;
    end
end
if useMex
    %shrink  = @(x,tq) shrink_mex(x,tq); %NOTE: shrink_mex doesn't handle vector tq properly
    shrink  = @(x,tq) shrink_mex2(x,tq);
    shrink_nu = @(x,tq,nu) shrink_mex2(x,tq,nu);
else
    shrink  = @(x,tq) sign(x).*max( bsxfun(@minus,abs(x),tq), 0 );
    shrink_nu = @(x,tq,nu) shrink(bsxfun(@minus,x,nu),tq);
end

% This is Matlab and Octave compatible code
op = tfocs_prox( @(x)f(q,x), @(x,t)prox_f(q,b,nColumns,zeroID,shrink,shrink_nu,x,t) , 'vector' );

end

% These are now subroutines, that are NOT in the same scope
function v = f(qq,x)
    v = norm( qq(:).*x(:), 1 );
end

function x = prox_f(qq,b,nColumns,zeroID,shrink,shrink_nu,x,t) % stepsize is t
    tq = t .* qq; % March 2012, allowing vectorized stepsizes
    tq = reshape(tq, [1 numel(tq)]);

    if zeroID && nColumns > 1
        x   = reshape( x, [], nColumns );
        nRows   = size(x,1);
        if nColumns > nRows
            error('Cannot zero out the diagonal if columns > rows');
        end

        x = prox_l1sum_zeroID_matricized( x, tq, b, shrink_nu );

        x = reshape(x, nRows*nColumns, 1);

    else
        if nColumns > 1
            x   = reshape( x, [], nColumns );
            nRows   = size(x,1);

            x = prox_l1sum_matricized( x, tq, b, shrink_nu );

            x = reshape(x, nRows*nColumns, 1);
        else
            x   = prox_l1sum( x, tq, b, shrink_nu );
        end
    end
end

function x = prox_f_using_worker(qq,b,nColumns,zeroID,x,t) % stepsize is t
    tq = t .* qq; % March 2012, allowing vectorized stepsizes

    if nColumns > 1 % matrix
        x = reshape(x, [], nColumns);
        nRows = size(x,1);

        if zeroID && nColumns > nRows
            error('Cannot zero out the diagonal if columns > rows');
        end

        x = prox_l1_and_sum_worker_mex(x, tq, b, zeroID);

        x = reshape(x, nRows*nColumns, 1);

    else % vector
        x = prox_l1_and_sum_worker_mex(x, tq, b);
    end
end

% Main algorithmic part: if x0 is length n, takes O(n log n) time
function x = prox_l1sum( x0, lambda, b, shrink_nu )

    brk_pts = sort( [x0-lambda;x0+lambda], 'descend' );

    xnu     = @(nu) shrink_nu( x0 , lambda, nu );
    h       = @(x) sum(x) - b; % want to solve h(nu) = 0

    % Bisection
    lwrBnd       = 0;
    uprBnd       = length(brk_pts) + 1;
    iMax         = ceil( log2(length(brk_pts)) ) + 1;
    PRINT = false; % set to "true" for debugging purposes
    if PRINT
        dispp = @disp;
        printf = @fprintf;
    else
        dispp = @(varargin) 1;
        printf = @(varargin) 1;
    end
    dispp(' ');
    for i = 1:iMax
        if uprBnd - lwrBnd <= 1
            dispp('Bounds are too close; breaking');
            break;
        end
        j = round( (lwrBnd+uprBnd)/2 );
        %printf('j is %d (bounds were [%d,%d])\n', j, lwrBnd,uprBnd ); %
        if j==lwrBnd
            dispp('j==lwrBnd, so increasing');
            j = j+1;
        elseif j==uprBnd
            dispp('j==uprBnd, so increasing');
            j = j-1;
        end

        a   = brk_pts(j);
        x   = xnu(a);  % the prox
        p   = h(x);

        if p > 0
            uprBnd = j;
        elseif p < 0
            lwrBnd = j;
        end
        if PRINT
            % Don't rely on redefinition of printf,
            % since then we would still calculate find(~x)
            % which is slow
            printf('i=%2d, a = %6.3f, p = %8.3f, zeros ', i, a, p );
            if n < 100, printf('%d ', find(~x) ); end
            printf('\n');
        end
    end

    % Now, determine linear part, which we infer from two points.
    % If lwr/upr bounds are infinite, we take special care
    % e.g., we make a new "a" slightly lower/bigger, and use this
    % to extract linear part.
    if lwrBnd == 0
        a2 = brk_pts( uprBnd );
        a1 = a2 - 10; % arbitrary
        aBounds = [a1,a2];
    elseif uprBnd == length(brk_pts) + 1
        a1 = brk_pts( lwrBnd );
        a2 = a1 + 10; % arbitrary
        aBounds = [a1,a2];
    else
        % In general case, we can infer linear part from the two break points
        a1 = brk_pts( lwrBnd );
        a2 = brk_pts( uprBnd );
        aBounds = [a1,a2];
    end

    % Now we have the support, find exact value
    x       = xnu(( aBounds(1)+aBounds(2))/2 );  % to find the support
    supp    = find(x);

    sgn     = sign(x);
    nu      = ( sum(x0(supp) - lambda*sgn(supp) ) - b )/length(supp);

    x   = xnu( nu );

end

% This variant can handle several columns at once,
% and it takes exactly log2(n) iterations, as it doesn't stop early
%   since different columns might stop at different steps and that's
%   not easy to detect efficiently.
function x = prox_l1sum_matricized( x0, lambda, b, shrink_nu )

    brk_pts = sort( [x0-lambda;x0+lambda], 'descend' );

    xnu     = @(nu) shrink_nu( x0 , lambda, nu );

    h       = @(x) sum(x) - b; % want to solve h(nu) = 0

    nCols        = size( x0, 2 ); % allow matrices
    LDA          = size( brk_pts, 1 );
    offsets      = (0:nCols-1)*LDA;%i.e., [0, LDA, 2*LDA, ... ];
    num_brk_pts = LDA;

    lwrBnd       = zeros(1,nCols);
    uprBnd       = (length(brk_pts) + 1)*ones(1,nCols);
    iMax         = ceil( log2(length(brk_pts)) ) + 1;

    for i = 1:iMax

        j = round(mean([lwrBnd;uprBnd]));
        ind = find( j==lwrBnd );
        j( ind ) = j( ind ) + 1;
        ind = find( j==uprBnd );
        j( ind ) = j( ind ) - 1;

        a   = brk_pts(j+offsets); % need the offsets to correct it here
        x   = xnu(a);  % the prox
        p   = h(x);

        ind = find( p > 0 );
        uprBnd(ind) = j(ind);
        ind = find( p < 0 );
        lwrBnd(ind) = j(ind);

    end

    [a1,a2]     = deal( zeros(1,nCols) );
    ind = find( lwrBnd == 0 );
    a2(ind) = brk_pts( uprBnd(ind) + offsets(ind) );
    a1(ind) = a2(ind) + 10;
    ind2 = ind;

    ind = find( uprBnd == num_brk_pts + 1 );
    a1(ind) = brk_pts( lwrBnd(ind) + offsets(ind) );
    a2(ind) = a1(ind) - 10;

    indOther = setdiff( 1:nCols, [ind2,ind] );
    a1(indOther)    = brk_pts( lwrBnd(indOther) + offsets(indOther) );
    a2(indOther)    = brk_pts( uprBnd(indOther) + offsets(indOther) );

    a  = mean( [a1;a2] );
    x       = xnu( a );

    nu      = zeros(1,nCols);
    sgn     = sign(x);
    if numel(lambda) > 1
        for col = 1:nCols
            supp    = find( sgn(:,col) );
            nu(col)      = ( sum(x0(supp,col) - lambda(col)*sgn(supp,col) ) - b )/length(supp);
        end
    else
         for col = 1:nCols
            supp    = find( sgn(:,col) );
            nu(col)      = ( sum(x0(supp,col) - lambda*sgn(supp,col) ) - b )/length(supp);
        end
    end
    x   = xnu( nu );

end

% This variant can handle several columns at once,
% and it takes exactly log2(n) iterations, as it doesn't stop early
%   since different columns might stop at different steps and that's
%   not easy to detect efficiently.
%
% This hacks "tricks" the implementation into ignoring the diagonal to avoid an extra copy
function x = prox_l1sum_zeroID_matricized( x0, lambda, b, shrink_nu )

    [nRows, nCols] = size(x0);
    diag_inds = nRows*(0:nCols-1) + (1:nCols);

    % Sort all possible break points
    % We account for ignoring the diagonal by setting the diagonals to -inf,
    % so they're at the bottom of the sorted matrix.  We then need to handle the offsets
    % appropriately.

    brk_pts_minus = x0 - lambda; brk_pts_minus(diag_inds) = -inf;
    brk_pts_plus = x0 + lambda; brk_pts_plus(diag_inds) = -inf;
    brk_pts = [brk_pts_minus; brk_pts_plus];

    %brk_pts = [x0 - lambda; x0 + lambda];
    %inf_inds = [2*nRows*(0:nCols-1) + (1:nCols),
    %            2*nRows*(0:nCols-1) + (1:nCols) + nRows];
    %brk_pts(inf_inds) = -inf;

    brk_pts = sort( brk_pts, 'descend' );

    xnu     = @(nu) shrink_nu( x0, lambda, nu );

    h       = @(x) sum(x) - x(diag_inds) - b; % want to solve h(nu) = 0

    LDA          = size( brk_pts, 1 );
    offsets      = (0:nCols-1)*LDA;%i.e., [0, LDA, 2*LDA, ... ];
    num_brk_pts = LDA - 2;

    lwrBnd       = zeros(1,nCols);
    uprBnd       = (num_brk_pts + 1 )*ones(1,nCols);
    iMax         = ceil( log2(num_brk_pts) ) + 1;

    for i = 1:iMax

        j = round(mean([lwrBnd;uprBnd]));
        ind = find( j==lwrBnd );
        j( ind ) = j( ind ) + 1;
        ind = find( j==uprBnd );
        j( ind ) = j( ind ) - 1;

        a   = brk_pts(j+offsets); % need the offsets to correct it here
        x   = xnu(a);  % the prox
        p   = h(x);

        ind = find( p > 0 );
        uprBnd(ind) = j(ind);
        ind = find( p < 0 );
        lwrBnd(ind) = j(ind);

    end

    [a1,a2]     = deal( zeros(1,nCols) );
    ind = find( lwrBnd == 0 );
    a2(ind) = brk_pts( uprBnd(ind) + offsets(ind) );
    a1(ind) = a2(ind) + 10;
    ind2 = ind;

    ind = find( uprBnd == num_brk_pts + 1 );
    a1(ind) = brk_pts( lwrBnd(ind) + offsets(ind) );
    a2(ind) = a1(ind) - 10;

    indOther = setdiff( 1:nCols, [ind2,ind] );
    a1(indOther)    = brk_pts( lwrBnd(indOther) + offsets(indOther) );
    a2(indOther)    = brk_pts( uprBnd(indOther) + offsets(indOther) );

    a  = mean( [a1;a2] );
    x       = xnu( a );

    sgn     = sign(x);
    supp = (sgn ~= 0); supp(diag_inds) = 0;

    nu      = zeros(1,nCols);
    if numel(lambda) > 1
        for col = 1:nCols
            nu(col)      = ( sum(x0(supp(:,col),col) - lambda(col)*sgn(supp(:,col),col) ) - b )/sum(supp(:,col));
        end
    else
        UNSAFE_BUT_FAST = true;
        if UNSAFE_BUT_FAST
            % some MATLAB hackery to vectorize the below loop
            % Note that due to roundoff in the first cumsum, this is not necessarily safe
            % With data that are changing signs randomly, the numerical issues should be kept at bay.
            % In initial experiments, this seems to be okay.
            num_supp = sum(supp,1);
            sumthing = cumsum(x0(supp) - lambda*sgn(supp)); % possible numerical issues!
            inds = cumsum(num_supp);
            numerator = sumthing(inds) - b;
            numerator(2:nCols) = numerator(2:nCols) - sumthing(inds(1:nCols-1));
            nu = numerator.' ./ num_supp;
        else
            for col = 1:nCols
                nu(col)      = ( sum(x0(supp(:,col),col) - lambda*sgn(supp(:,col),col) ) - b )/sum(supp(:,col));
            end
        end
    end

    x   = xnu( nu );

    x(diag_inds) = 0;

end

author: cvxr

repo: TFOCS

save_path: github-repos/MATLAB/cvxr-TFOCS