text:
function nav=readblq(nav,obsr,obsb,fname)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%read ocean tide loading parameter(otlp) for rover and base
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
global glc
idx=strfind(fname,glc.sep); fname0=fname(idx(end)+1:end);
fprintf('Info:reading blq file %s...',fname0);
ns=0;

if obsr.n>0,sta(1)=obsr.sta;ns=1;end
if obsb.n>0,sta(2)=obsb.sta;ns=2;end
if ns==0,return;end

for i=1:ns
    fid=fopen(fname);
    sta_name=upper(sta(i).name);
    while ~feof(fid)
        line=fgets(fid);
        if ~isempty(strfind(line,'-cmc')),break;end
    end

    while ~feof(fid)
        line=fgets(fid);
        if ~isempty(strfind(line,'$$'))||size(line,2)<=2,continue;end
        name=upper(line(3:6));
        if isempty(strfind(sta_name,name)),continue;end

        [otlp,fid,stat]=decode_blqdata(fid);

        if stat==1
            nav.otlp(:,:,i)=otlp';
        end
    end
    fclose(fid);
end

fprintf('over\n');

return

repo: GINav


text:
function stroud_test26 ( )

%*****************************************************************************80
%
%% TEST26 tests QMULT_1D.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 April 2009
%
%  Author:
%
%    John Burkardt
%
  num = function_1d_num ( );

  a = -1.0;
  b = 1.0;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST26\n' );
  fprintf ( 1, '  QMULT_1D approximates an integral on a\n' );
  fprintf ( 1, '    one-dimensional interval.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  We use the interval:\n' );
  fprintf ( 1, '  A = %f\n', a );
  fprintf ( 1, '  B = %f\n', b );
  fprintf ( 1, '\n' );
  fprintf ( 1, '    F(X)     QMULT_1D\n' );
  fprintf ( 1, '\n' );

  for i = 1 : num

    function_1d_set ( 'SET', i );

    result = qmult_1d ( 'function_1d', a, b );

    fname = function_1d_name ( i );

    fprintf ( 1, '  %s  %12f\n', fname, result );

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function res = uminusFactorized( xi )
%UMINUSFACTORIZED Unary minus for a tangent tensor.
%   RES = UMINUSFACTORIZED( XI ) performs unary minus operation
%   on the tangent tensor XI given in factorized form
%
%   See also addFactorized
%

%   GeomCG Tensor Completion. Copyright 2013 by
%   Michael Steinlechner
%   Questions and contact: michael.steinlechner@epfl.ch
%   BSD 2-clause license, see LICENSE.txt

        res.Y_tilde =  -xi.Y_tilde;
        res.U1_tilde = -xi.U1_tilde;
        res.U2_tilde = -xi.U2_tilde;
        res.U3_tilde = -xi.U3_tilde;
end

author: andrewssobral


text:
function pBar = bst_progress(varargin)
% bst_progress: Manage the Brainstorm progress bar
%
% USAGE : pBar = bst_progress('start', title, msg, valStart, valStop) : Create a progress bar with start and stop bounds
%         pBar = bst_progress('start', title, msg)                    : Create a progress bar (unlimited)
%         pBar = bst_progress('stop')        : stop and hide progress bar
%         pBar = bst_progress('inc', valInc) : increment of 'valInc' the position of the progress bar
%         pBar = bst_progress('set', pos)    : set the position
%          pos = bst_progress('get')         : get the position
%         pBar = bst_progress('text', txt)   : set the text
%    isVisible = bst_progress('isvisible')   : return 1 if progress bar is visible, 0 else
%         pBar = bst_progress('show')        : display previously defined progress bar
%         pBar = bst_progress('hide')        : hide progress bar
%         pBar = bst_progress('setimage', imagefile) : display an image in the wait bar
%         pBar = bst_progress('setlink', url)        : clicking on the image opens a browser to display the url
%         pBar = bst_progress('removeimage')         : Remove the image from the wait bar

% NOTES : The window is created once, and then never deleted, just hidden.
%         Progress bar is represented by a structure:
%            |- jWindow
%            |- jLabel
%            |- jProgressBar
%
% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c)2000-2020 University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2008-2013

% JAVA imports
import org.brainstorm.icon.*;
import java.awt.Dimension;

global GlobalData;

%% ===== PARSE INPUTS =====
if ((nargin >= 1) && ischar(varargin{1}))
    commandName = varargin{1};
else
    error('Usage : bst_progress(commandName, parameters)');
end

%% ===== GET OR CREATE PROGRESS BAR =====
% Do nothing in case of server mode
if ~isempty(GlobalData) && ~isempty(GlobalData.Program) && isfield(GlobalData.Program, 'GuiLevel') && (GlobalData.Program.GuiLevel == -1)
    if ismember(lower(commandName), {'pos','isvisible'})
        pBar = 0;
    else
        pBar = [];
    end
    return;
end
% If running in NOGUI mode: just display the message in the command window
if ~bst_get('isGUI')
    switch lower(commandName)
        case 'start',     disp(['PROGRESS> ' varargin{2} ': ' varargin{3}]); pBar = [];
        case 'text',      disp(['PROGRESS> ' varargin{2}]); pBar = [];
        case 'get',       pBar = 1;
        case 'isvisible', pBar = 0;
    end
    return;
end
% Get progress bar
if ~isempty(GlobalData) && ~isempty(GlobalData.Program) && isfield(GlobalData.Program, 'ProgressBar') && ~isempty(GlobalData.Program.ProgressBar)
    pBar = GlobalData.Program.ProgressBar;
else
    pBar = [];
end
% Get Brainstorm GUI context
jBstFrame = bst_get('BstFrame');
if isempty(jBstFrame)
    return
end

% Default window size
if isempty(pBar) || strcmpi(commandName, 'removeimage') || (strcmpi(commandName, 'stop') && pBar.isImage)
    DefaultSize = java_scaled('dimension', 350, 130);
end

% If progress bar was not created yet : create it
if isempty(pBar)
    % If action=isvisible: no need to create the progress bar
    if strcmpi(commandName, 'isvisible')
        pBar = 0;
        return
    end
    % Create a JDialog, if possible dependent of the main Brainstorm JFrame
    pBar.jWindow = java_create('javax.swing.JDialog');
    % Set icon
    try
        pBar.jWindow.setIconImage(IconLoader.ICON_APP.getImage());
    catch
        % Old matlab... just ignore...
    end
    % Set as always-on-top / non-focusable
    pBar.jWindow.setAlwaysOnTop(1);
    pBar.jWindow.setFocusable(0);
    pBar.jWindow.setFocusableWindowState(0);
    % Non-modal
    pBar.jWindow.setModal(0);

    % Closing callback
%     if bst_iscompiled()
        pBar.jWindow.setDefaultCloseOperation(pBar.jWindow.HIDE_ON_CLOSE);
%     else
%         pBar.jWindow.setDefaultCloseOperation(pBar.jWindow.DO_NOTHING_ON_CLOSE);
%         java_setcb(pBar.jWindow, 'WindowClosingCallback', @(h,ev)CloseCallback);
%     end

    % Configure window
    pBar.jWindow.setPreferredSize(DefaultSize);
    % Main panel
    pBar.jPanel = java_create('javax.swing.JPanel');
    pBar.jPanel.setLayout(java_create('java.awt.GridBagLayout'));

    % Create objects
    pBar.isImage = 0;
    pBar.jImage = java_create('javax.swing.JLabel');
    pBar.jLabel = java_create('javax.swing.JLabel', 'Ljava.lang.String;', '...');
    pBar.jLabel.setFont(bst_get('Font'));
    pBar.jProgressBar = java_create('javax.swing.JProgressBar', 'II', 0, 99);
    % Update constraints
    UpdateConstraints(0);

    % Add the main Panel
    pBar.jWindow.getContentPane.add(pBar.jPanel);
    pBar.jWindow.pack();
    % Set window size and location
    %pBar.jWindow.setLocationRelativeTo(pBar.jWindow.getParent());
    jLoc = jBstFrame.getLocation();
    jSize = jBstFrame.getSize();
    pos = [jLoc.getX() + ((jSize.getWidth() - DefaultSize.getWidth()) / 2), ...
           jLoc.getY() + ((jSize.getHeight() - DefaultSize.getHeight()) / 2)];
    pBar.jWindow.setLocation(pos(1), pos(2));
    % Save progress bar
    GlobalData.Program.ProgressBar = pBar;
end

% Linux: need to print something on the command window (don't know why...)
if strcmpi(commandName, 'stop') && ismember(computer('arch'), {'glnx86', 'glnxa64'})
    drawnow();
    fprintf(' ');
    fprintf('\b');
    drawnow();
    % The dialog needs to be displayed for a short period before being hidden
    pause(0.05);
end

%% ===== SWITCH BETWEEN COMMANDS =====
switch (lower(commandName))
    % ==== START ====
    case 'start'
        % Set as "always on top"
        java_call(pBar.jWindow, 'setAlwaysOnTop', 'Z', 1);
        java_call(pBar.jWindow, 'setFocusable',   'Z', 0);
        java_call(pBar.jWindow, 'setFocusableWindowState', 'Z', 0);
        % Call: bst_progress(''start'', title, msg)
        if (nargin == 3) && ischar(varargin{3}) && ischar(varargin{2})
            % Get window title and comment
            wndTitle    = varargin{2};
            msg = varargin{3};
            % Set Progress bar in inderminate mode
            pBar.jProgressBar.setIndeterminate(1);
            pBar.jProgressBar.setStringPainted(0);
            % Set progress bar bounds
            pBar.jProgressBar.setMinimum(0);
            pBar.jProgressBar.setMaximum(100);
            % Set initial value to start
            pBar.jProgressBar.setValue(0);

        % Call: bst_progress(''start'', title, msg, start, stop)
        elseif ((nargin == 5) && ischar(varargin{2}) && ischar(varargin{3}) && isnumeric(varargin{4}) && isnumeric(varargin{5}))
            % Get window title and comment
            wndTitle = varargin{2};
            msg = varargin{3};
            % Set Progress bar in derminate mode
            pBar.jProgressBar.setIndeterminate(0);
            pBar.jProgressBar.setStringPainted(1);
            % Get progress bar bounds
            valStart = varargin{4};
            valStop  = varargin{5};
            % Test bounds
            if ( (valStart >= valStop) || (valStop <= 0) )
                % Set indeterminate bounds
                pBar.jProgressBar.setIndeterminate(1);
                pBar.jProgressBar.setStringPainted(0);
                valStart = 0;
                valStop  = 100;
            end
            % Set progress bar bounds
            pBar.jProgressBar.setMinimum(valStart);
            pBar.jProgressBar.setMaximum(valStop);
            % Set initial value to start
            pBar.jProgressBar.setValue(valStart);

        else
            error(['Usage : bst_progress(''start'', title, comment) ' 10 '        bst_progress(''start'', title, comment, valStart, valStop)']);
        end
        % Set window title
        pBar.jWindow.setTitle(wndTitle);
        % Set window comment (central label)
        pBar.jLabel.setText(msg);
        % Show window
        java_call(pBar.jWindow, 'setVisible', 'Z', 1);
        % Set watch cursor
        jBstFrame.setCursor(java_create('java.awt.Cursor', 'I', java.awt.Cursor.WAIT_CURSOR));

    % ==== STOP ====
    case 'stop'
        % Remove the "always on top" status
        java_call(pBar.jWindow, 'setAlwaysOnTop', 'Z', 0);
        java_call(pBar.jWindow, 'setFocusable',   'Z', 1);
        java_call(pBar.jWindow, 'setFocusableWindowState', 'Z', 1);
        % Hide window
        java_call(pBar.jWindow, 'setVisible', 'Z', 0);
        % Restore cursor
        jBstFrame.setCursor([]);
        % Remove image
        if pBar.isImage
            GlobalData.Program.ProgressBar.isImage = 0;
            pBar.jImage.setIcon([]);
            java_setcb(pBar.jImage, 'MouseClickedCallback', []);
            UpdateConstraints(0);
            pBar.jWindow.setPreferredSize(DefaultSize);
            pBar.jWindow.pack();
        end

    % ==== INCREMENT ====
    case 'inc'
        % Parse arguments
        if ((nargin == 2) && isnumeric(varargin{2}))
            valInc = varargin{2};
        else
            error('Usage : bst_progress(''inc'', valInc)');
        end
        % Get current value
        curValue = pBar.jProgressBar.getValue();
        % Get the incremented progress bar position
        newVal = min(curValue + valInc, pBar.jProgressBar.getMaximum());
        pBar.jProgressBar.setValue(newVal);

    % ==== SET POSITION ====
    case 'set'
        % Parse arguments
        if ((nargin == 2) && isnumeric(varargin{2}))
            newVal = varargin{2};
        else
            error('Usage : bst_progress(''set'', pos)');
        end
        % Get current value
        curValue = pBar.jProgressBar.getValue();
        % Get the incremented progress bar position
        if (curValue ~= newVal)
            newVal = min(newVal, pBar.jProgressBar.getMaximum());
            pBar.jProgressBar.setValue(newVal);
        end

    % ==== GET POSITION ====
    case 'get'
        % Get the incremented progress bar position
        pBar = pBar.jProgressBar.getValue();

    % ==== SET TEXT ====
    case 'text'
        % Parse arguments
        if ((nargin == 2) && ischar(varargin{2}))
            % Set new label
            pBar.jLabel.setText(varargin{2});
        else
            % Get label
            pBar.jLabel.getText();
        end

    % ==== IS VISIBLE ====
    case 'isvisible'
        pBar = pBar.jWindow.isVisible();

    % ==== SHOW ====
    case 'show'
        % Set as "always on top"
        java_call(pBar.jWindow, 'setAlwaysOnTop', 'Z', 1);
        java_call(pBar.jWindow, 'setFocusable',   'Z', 0);
        java_call(pBar.jWindow, 'setFocusableWindowState', 'Z', 0);
        % Show window
        java_call(pBar.jWindow, 'setVisible', 'Z', 1);
        % Set watch cursor
        jBstFrame.setCursor(java_create('java.awt.Cursor', 'I', java.awt.Cursor.WAIT_CURSOR));

    % ==== HIDE ====
    case 'hide'
        % Remove the "always on top" status
        java_call(pBar.jWindow, 'setAlwaysOnTop', 'Z', 0);
        java_call(pBar.jWindow, 'setFocusable',   'Z', 1);
        java_call(pBar.jWindow, 'setFocusableWindowState', 'Z', 1);
        % Hide window
        java_call(pBar.jWindow, 'setVisible', 'Z', 0);
        % Restore cursor
        jBstFrame.setCursor([]);

    % ==== SET IMAGE ====
    case 'setimage'
        % Get image path
        imagefile = varargin{2};
        if ~file_exist(imagefile)
            imagefile = bst_fullfile(bst_get('BrainstormDocDir'), imagefile);
        end
        if ~file_exist(imagefile)
            warning(['Image not found: ' imagefile]);
            return
        end
        % Image in label
        pBar.jImage.setIcon(javax.swing.ImageIcon(imagefile));
        GlobalData.Program.ProgressBar.isImage = 1;
        % Extend size of the frame
        UpdateConstraints(1);
        pBar.jWindow.setPreferredSize([]);
        pBar.jWindow.pack();

    % ==== SET LINK ====
    case 'setlink'
        url = varargin{2};
        java_setcb(pBar.jImage, 'MouseClickedCallback', @(h,ev)web(url, '-browser'));

    % ==== REMOVE IMAGE ====
    case 'removeimage'
        % Remove image
        GlobalData.Program.ProgressBar.isImage = 0;
        pBar.jImage.setIcon([]);
        java_setcb(pBar.jImage, 'MouseClickedCallback', []);
        UpdateConstraints(0);
        pBar.jWindow.setPreferredSize(DefaultSize);
        pBar.jWindow.pack();
end

%% ===== ADD COMPONENTS =====
    function UpdateConstraints(isImage)
        import java.awt.GridBagConstraints;
        import java.awt.Insets;
        % Remove all components
        pBar.jPanel.removeAll();
        % Generic constraints
        c = GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        c.gridx = 1;
        c.weightx = 1;
        % IMAGE
        c.gridy = 1;
        c.weighty = isImage;
        c.insets = Insets(0,0,0,0);
        pBar.jPanel.add(pBar.jImage, c);
        % TEXT
        c.gridy = 2;
        c.weighty = ~isImage;
        c.insets = Insets(5,12,5,12);
        pBar.jPanel.add(pBar.jLabel, c);
        % PROGRESS BAR
        c.gridy = 3;
        c.weighty = 0;
        c.insets = Insets(0,12,9,12);
        pBar.jPanel.add(pBar.jProgressBar, c);
%         % CANCEL BUTTON
%         c.gridy = 4;
%         c.weighty = 0;
%         c.insets = Insets(0,12,9,12);
%         c.weightx = 0;
%         pBar.jPanel.add(pBar.jButtonCancel, c);
    end

%     %% ===== CLOSE CALLBACK =====
%     function CloseCallback()
%         % Hide progress bar
%         %java_call(pBar.jWindow, 'setVisible', 'Z', 0);
%         bst_progress('stop');
%
%         if bst_iscompiled()
%             try
%                 % Get command window
%                 cmdWindow = com.mathworks.mde.cmdwin.CmdWin.getInstance();
%                 cmdWindow.grabFocus();
%                 %2) Wait for focus transfer to complete (up to 2 seconds)
%                 focustransferTimer = tic;
%                 while ~cmdWindow.isFocusOwner
%                     pause(0.1);  %Pause some small interval
%                     if (toc(focustransferTimer) > 2)
%                         error('Error transferring focus for CTRL+C press.')
%                     end
%                 end
%
%                 %3) Use Java robot to execute a CTRL+C in the (now focused) command window.
%
%                 %3.1)  Setup a timer to relase CTRL + C in 0.3 second
%                 %  Try to reuse an existing timer if possible (this would be a holdover
%                 %  from a previous execution)
%                 t_all = timerfindall;
%                 releaseTimer = [];
%                 ix_timer = 1;
%                 while isempty(releaseTimer) && (ix_timer<= length(t_all))
%                     if isequal(t_all(ix_timer).TimerFcn, @releaseCtrl_C)
%                         releaseTimer = t_all(ix_timer);
%                     end
%                     ix_timer = ix_timer+1;
%                 end
%                 if isempty(releaseTimer)
%                     releaseTimer = timer;
%                     releaseTimer.TimerFcn = @(h,ev)releaseCtrl_C;
%                 end
%                 releaseTimer.StartDelay = 0.3;
%                 start(releaseTimer);
%
%                 %3.2)  Press press CTRL+C
%                 pressCtrl_C();
%             catch
%                 disp('BST> Could not post a CTRL+C signal in the command window.');
%             end
%         end
%     end
%
%     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%     function pressCtrl_C()
%         SimKey = java.awt.Robot;
%         SimKey.keyPress(java.awt.event.KeyEvent.VK_CONTROL);
%         SimKey.keyPress(java.awt.event.KeyEvent.VK_C);
%     end
%
%     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%     function releaseCtrl_C()
%         SimKey = java.awt.Robot;
%         SimKey.keyRelease(java.awt.event.KeyEvent.VK_CONTROL);
%         SimKey.keyRelease(java.awt.event.KeyEvent.VK_C);
%         jBstFrame.setVisible(1);
%     end

end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [i,j] = argmax2(x)
%ARGMAX2  Index of maximum element of matrix.
% [i,j] = ARGMAX2(x) returns indices (i,j) such that x(i,j) == max(x(:)).
%
% See also ARGMAX.

[colmax,i] = max(x);
[ignore,j] = max(colmax);
i = i(j);

repo: lrslibrary


text:
function [ polyg, Features] = getcandboxlayoutSingle( layout, vp, h, w, integData )
% getcandoxlayout Get box layout candidates and their features.
%
% INPUT:
%    vp- vanishing points h,w- height width of image
%    integData - integral images for features.

%OUTPUT:
% polyg - box layout candidates, each candidate as five polygons corresponding to left/middle/right walls, floor and ceiling
% Features -for each box layout candidate

%Features:-
%line-membership features:1:20
%correct label confidence: 21-25
%label entropy :26 -30
%weighted line-memership features:31-40
%surface label confidence :41 -75

numf=75;

samps=10;gtexist=0;
% [layout]=getLayouts(vp,h,w,samps);

numL=size(layout,1);

Features=zeros(numL,numf);
polyg=cell(numL,5);

cnt=1;quantsiz=500;
if numL > 0
    for lay=1:size(layout,1)
        Ra=[layout(lay,1) layout(lay,2)];
        Rb=[layout(lay,3) layout(lay,4)];
        Rc=[layout(lay,5) layout(lay,6)];
        Rd=[layout(lay,7) layout(lay,8)];
        Polyg=[];
        tot_area = 0;

        cond1=inpolygon(vp(3,1),vp(3,2),[Ra(1); Rb(1); Rc(1); Rd(1); Ra(1)],[Ra(2); Rb(2); Rc(2); Rd(2);Ra(2)]) & ...
            ~(inpolygon(vp(2,1),vp(2,2),[Ra(1); Rb(1); Rc(1); Rd(1);Ra(1)],[Ra(2); Rb(2); Rc(2); Rd(2);Ra(2)])) & ...
            ~(inpolygon(vp(1,2),vp(1,2),[Ra(1); Rb(1); Rc(1); Rd(1);Ra(1)],[Ra(2); Rb(2); Rc(2); Rd(2);Ra(2)]));

        lines1=[Ra(1) Rb(1) Ra(2) Rb(2);...
            Rc(1) Rd(1) Rc(2) Rd(2);...
            Rb(1) Rc(1) Rb(2) Rc(2);...
            Ra(1) Rd(1) Ra(2) Rd(2)];
        lines2=[vp(2,1) vp(3,1) vp(2,2) vp(3,2);...
            [vp(2,1) vp(3,1) vp(2,2) vp(3,2)];...
            [vp(1,1) vp(3,1) vp(1,2) vp(3,2)];...
            [vp(1,1) vp(3,1) vp(1,2) vp(3,2)]];
        [inxs inys]=IntersectLines(lines1,lines2);

        cond2=inxs(1) < vp(3,1) & inxs(2) > vp(3,1) & inys(3) < vp(3,2) & inys(4) > vp(3,2);

        %1 floor
        [tempimg tpolyg parea]=getface(Rd,Ra,vp,w,h,0,1,0);
        Polyg{1}=[tpolyg];
        if numel(find(isnan(tpolyg))) >0
            error('debug me');
        end
        tot_area = tot_area+parea;

        %2 middlewall
        [tempimg tpolyg trapez parea]=getmiddlewall(Ra,Rb,Rc,Rd,vp,w,h,0,1,0);
        Polyg{2}=[tpolyg];
        if numel(find(isnan(tpolyg))) >0
            error('debug me');
        end
        tot_area = tot_area+parea;

        %3 right wall
        [tempimg tpolyg parea]=getface(Rc,Rd,vp,w,h,0,1,0);
        Polyg{3}=[tpolyg];
        if numel(find(isnan(tpolyg))) >0
            error('debug me');
        end
        tot_area = tot_area+parea;

        %4 left wall
        [tempimg tpolyg parea]=getface(Ra,Rb,vp,w,h,0,1,0);
        Polyg{4}=[tpolyg];
        if numel(find(isnan(tpolyg))) >0
            error('debug me');
        end
        tot_area = tot_area+parea;

        %5 ceiling
        [tempimg tpolyg parea]=getface(Rb,Rc,vp,w,h,0,1,0);
        Polyg{5}=[tpolyg];
        if numel(find(isnan(tpolyg))) >0
            error('debug me');
        end
        tot_area = tot_area+parea;
        cond3=(numel(Polyg{1})+numel(Polyg{2})+numel(Polyg{3})+numel(Polyg{4})+numel(Polyg{5})) > 0;

        % zyd new code
        if cond1 & cond2 & ~cond3
            Polyg{2} = [640 1; 640 640; 1 640; 1 1];
            cond3 = 1;
            tot_area = w*h;
        end

        if (tot_area/w/h)<0.8 | (tot_area/w/h) > 1.2 | ~cond1 | ~cond2 | ~cond3
            continue;
        else

            for f=1:5
                polyg{cnt,f}=Polyg{f};
            end
            [Polyg]=clipPolyg(Polyg,h,w);
            if numel(Polyg)>0
                %                     tic
                [features] =getLayoutfeats(Polyg,integData,vp,h,w,0,quantsiz);
                %                     toc
            end

            Features(cnt,:)=features;

            cnt=cnt+1;
        end

    end

    Features(cnt:end,:)=[];
    polyg(cnt:end,:)=[];

    if size(Features,1)~=size(polyg,1)
        disp('stop');
        keyboard;
    end

end
end

author: zouchuhang

repo: LayoutNet


text:
function [pinit,pflow,names,M,U,Y] = mci_lds_group_data (lds)
% Generate LDS data for a group of subjects
% FORMAT [pinit,pflow,names,M,U,Y] = mci_lds_group_data (lds)
%
% lds        Data structure with fields:
%
% .R         R.pE, R.pC prior over initial conds
% .sd        Standard deviation of observation noise
% .Nsub      Number of subjects
% .Nobs      Number of observations per subject
% .model     'lds_real','forward',etc.
% .flow_par  'fixed' or 'random'
% .init_par  'fixed' or 'random'
%
% pinit      Initial params
% pflow      Flow params
% names      names of parameters
% M          Cell of models
% U          Cell of inputs
% Y          Cell of data
%__________________________________________________________________________
% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging

% Will Penny
% $Id: mci_lds_group_data.m 6548 2015-09-11 12:39:47Z will $

R=lds.R; sd=lds.sd; Nsub=lds.Nsub;
Nobs=lds.Nobs; model=lds.model;
d=length(R.pE);

% Set Flow Parameters
if strcmp(model,'lds_real')
    r=linspace(0.3,0.9,d);
    T=100;
    q=(1/T)*log(r);
    pflow=log(-q);
else

    Mtmp.name=model;
    Mtmp.sd=sd;
    Mtmp.d=d;
    Mtmp.drop=0.5;
    %Mtmp.t=[1:400]'/4;
    Mtmp.t=[1:25]'/0.25;
    Mtmp.int='sundials';

    Mtmp=mci_lds_struct(Mtmp);
    if strcmp(lds.flow_par,'fixed')
%         PP.self=Mtmp.sd_self*randn(d,1);
%         PP.between=Mtmp.sd_between*randn(Mtmp.Nb,1);
%         pflow=spm_vec(PP);

        Pt = [-0.04,-0.01,-0.005,-0.01,0.01,0.01,0.01]';
        pflow = mci_lds_par2lat (Pt,Mtmp);
    else
        for n=1:Nsub,
            PP.self=Mtmp.sd_self*randn(d,1);
            PP.between=Mtmp.sd_between*randn(Mtmp.Nb,1);
            pflow(:,n)=spm_vec(PP);
        end
    end
end

if strcmp(lds.init_par,'fixed')
    R0 = spm_normrnd(R.pE,R.pC,1);
end
for n=1:Nsub,

    % Sample initial states from prior
    if strcmp(lds.init_par,'random')
        R0 = spm_normrnd(R.pE,R.pC,1);
    end
    pinit(:,n)=R0;
    switch model
        case 'lds_real'
            [M{n},U{n},y] = irlds_init (d,sd,R0,pflow);
        otherwise
            Mtmp.R=R0;
            [M{n},U{n}] = mci_lds_struct (Mtmp);

            if strcmp(lds.flow_par,'fixed')
                y = mci_lds_gen (M{n},U{n},pflow);
            else
                y = mci_lds_gen (M{n},U{n},pflow(:,n));
            end
    end

    if lds.Nobs==M{n}.N
        Y{n}.y=y;
        Y{n}.ind=1:M{n}.N;
    else
        % Thin observations to selected time points
        rind=randperm(M{n}.N);
        ind=rind(1:Nobs);
        Y{n}.y=y(ind,:);
        Y{n}.ind=ind;
    end

end

if strcmp(model,'forward')

    for j=1:d,
        jn=int2str(j);
        names{j}=['a_{',jn,jn,'}'];
    end
    for i=1:d-1,
        jn=int2str(i);
        j1n=int2str(i+1);
        names{i+j}=['a_{',j1n,jn,'}'];
    end

end

author: spm


text:
function ObjVal = FoxHoles(x,mydata)

[A,B] = size(x);
Top=double(0);
Top1=double(0);
C=[-32,-16,0,16,32,-32,-16,0,16,32,-32,-16,0,16,32,-32,-16,0,16,32,-32,-16,0,16,32;
    -32,-32,-32,-32,-32,-16,-16,-16,-16,-16,0,0,0,0,0,16,16,16,16,16,32,32,32,32,32];

for i=1:A
    for k=1:25
        for j=1:B
          Top1=Top1+power((double(x(i,j))-double(C(j,k))),6);
        end;
        Top=double(Top+(1/(Top1+k)));
        Top1=0;
     end;
ObjVal(i)= double(1/(0.002+Top));
Top=0;
end
ObjVal=ObjVal';

function y=power(x,a)
y=double(x^a);
  return

author: Sable

repo: mcbench-benchmarks


text:
function [FIT MCMC_LastState]=stat_ubsplsm(varargin)
% univariate b-spline smoothing with fPCA

% Y = cell array of [numChans x numChans x T] connectivities for each subject
% K = number of knots
% Q = number of fpca basis functions

% output:
% fit_distrib: cell array of [numChans x numChans x T x iterations]
%              posterior distribution for each subject

% Author: Tim Mullen and Wes Thompson, 2010-12, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

% This function is part of the Source Information Flow Toolbox (SIFT)
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

arg_define([0 1],varargin, ...
    arg_norep({'Y','TSData'},mandatory,[],sprintf(['Cell array of data to smooth.\n' ...
              'Generally, Y is a cell array where Y{i} is the T x 1 vector of time-varying (or freq-varying) connectivity for the kth channel pair of the sth subject.\n' ...
              'e.g. Y = {s1(1,1) s1(1,2) s1(1,3) ... s1(N,1) s1(N,2) s1(N,3) ... \n' ...
              '          s2(1,1) s2(1,2) s2(1,3) ... } \n'])), ...
    arg({'smoothingLayout','MatrixElementsToSmooth'},{'diagonals','off-diagonals'},{'diagonals','off-diagonals'},'Which parts of the matrix to smooth. Diagonals (e.g. auto-connectivity) and off-diagonals (e.g. cross-connectivity) will be smoothed separately','type','logical'), ...
    arg_sub({'mcmc_opts','MCMC'},{}, ...
    {...
        arg_sub({'mcmc_init','InitMCMC'},{},@stat_ubsplsm_init,'Initialize MCMC','suppress','verb') ...
        arg_sub({'mcmc_run','RunMCMC'},{},@stat_ubsplsm_mcmc,'MCMC runtime options','suppress','verb') ...
    },'Perform Markov Chain Monte Carlo estimation'), ...
    arg_norep({'MCMC_InitState'},struct([]),[],'Object containing initial state of Gibbs sampler. If supplied, this overrides mcmc_init'), ...
    arg({'verb','VerbosityLevel'},2,{int32(0) int32(1) int32(2)},'Verbosity level. 0 = no output, 1 = text, 2 = graphical') ...
    );

% initialize some vars
init_mcmc = isempty(g.MCMC_InitState);
nsubj=length(Y);

% determine the number of variables for each subject
m_i=zeros(nsubj,1);
for i=1:nsubj
    m_i(i)=size(Y{i},1);
end

% determining smoothing layout
smoothDiags     = ismember_bc('diagonals',g.smoothingLayout);
smoothOffDiags  = ismember_bc('off-diagonals',g.smoothingLayout);

%% get smoothed time-varying connectivity coefficients

% Diagonals and off-diagonals often have different variances, so we smooth
% them separately

% smooth diagonals
% -------------------------------------------------------------------------
if smoothDiags
    if verb==2
        multiWaitbar('Smoothing Diagonals','Reset', ...
                     hlp_getNextUniqueColor('reset'));
    end

    % extract self-connectivity for each subject
    CPairs=cell(sum(m_i),1);
    ind=0;
    for i=1:nsubj
        for j=1:m_i(i)
            ind=ind+1;
            CPairs{ind}=squeeze(Y{i}(j,j,:));
        end
    end

    % initialize MCMC
    if init_mcmc
        MCMC_InitState = stat_ubsplsm_init('Y',mcmc_opts.mcmc_init,'verb',verb);
    end

    % perform the smoothing
    [fit_diag MCMC_LastState.diag]=stat_ubsplsm_mcmc('Y',CPairs,mcmc_opts.mcmc_run, ...
                                        'verb',verb,'MCMC_InitState',MCMC_InitState.diag);
end

% smooth off-diagonals
% -------------------------------------------------------------------------
if smoothOffDiags
    if verb
        multiWaitbar('Smoothing Off-Diagonals',1/3);
    end

    % count the total number of pairs
    m_offdiag=sum(m_i.^2-m_i);

    % extract cross-connectivity off-diagonal
    % elements for each subject
    CPairs=cell(m_offdiag,1);
    ind=0;
    for i=1:nsubj
        for j1=1:m_i(i)
            for j2=1:m_i(i)
                if j1~=j2
                    ind=ind+1;
                    CPairs{ind}=squeeze(Y{i}(j1,j2,:));
                end
            end
        end
    end

    % initialize MCMC
    if init_mcmc
        MCMC_InitState = stat_ubsplsm_init('Y',mcmc_opts.mcmc_init,'verb',verb);
    end

    % perform the smoothing
    [fit_offdiag MCMC_LastState.offdiag]=stat_ubsplsm_mcmc('Y',CPairs,mcmc_opts.mcmc_run, ...
                                         'verb',verb,'MCMC_InitState',MCMC_InitState.offdiag);
end

% store data in [nchs x nchs x time x distribution]
if verb
    multiwaitbar('Creating final data matrices...',2/3);
end
FIT = cell(1,nsubj);
ind=0;
ind_diag = 0;
for i=1:nsubj
    FIT{i} = zeros(m_i(i),m_i(i),size(fit_offdiag,1),niterToKeep);

    for j1=1:m_i(i)
        for j2=1:m_i(i)
            if j1~=j2
                ind=ind+1;
                FIT{i}(j1,j2,:,:)=squeeze(fit_offdiag(:,ind,:));
            elseif niters~=0
                ind_diag = ind_diag+1;
                FIT{i}(j1,j2,:,:)=squeeze(fit_diag(:,ind_diag,:));
            end
        end
    end
end

if verb
    multiWaitbar('CloseAll');
    pause(0.1);
end

repo: REST


text:
function m=pesq2mos(p)
%PESQ2MOS convert PESQ speech quality scores to MOS m=(p)
%Inputs:    p  is a matrix of PESQ scores
%
%Outputs:   m  is a matrix, the same size as p, of MOS scores
%
% The PESQ measure is defined in [2]. The mapping function, defined in [3],
% converts raw PESQ scores (which lie in the range -0.5 to 4.5) onto the
% MOS-LQO (Mean Opinion Score - Listening Quality Objective [2]) scale in the
% range 1 to 5. The MOS scale is defined in [1] as
%           5=Excellent, 4=Good, 3=Fair, 2=Poor, 1=Bad.
%
% Refs: [1]	ITU-T. Methods for subjective determination of transmission quality.
%           Recommendation P.800, Aug. 1996.
%       [2]	ITU-T. Mean opinion score (MOS) terminology.
%           Recommendation P.800.1, July 2006.
%       [2]	ITU-T. Perceptual evaluation of speech quality (PESQ), an objective
%           method for end-to-end speech quality assessment of narrowband telephone
%           networks and speech codecs. Recommendation P.862, Feb. 2001.
%       [3]	ITU-T. Mapping function for transforming P.862 raw result scores to MOS-LQO.
%           Recommendation P.862.1, Nov. 2003.

%      Copyright (C) Mike Brookes 2012-2013
%      Version: $Id: pesq2mos.m 3289 2013-08-01 13:56:02Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
persistent a b c d
if isempty(a)
    a=0.999;
    b=4.999-a;
    c=-1.4945;
    d=4.6607;
end
if nargout>0
    m=a+b./(1+exp(c*p+d));
else
    if nargin<1 || isempty(p)
        pp=linspace(-0.5,4.5,100);
    else
        pp=p;
    end
    plot(pp,pesq2mos(pp));
    xlabel('PESQ (P.862)');
    ylabel('Mean Opimion Score (MOS)');
end

author: jtkim-kaist

repo: VAD

save_path: github-repos/MATLAB/jtkim-kaist-VAD


text:
function [Y,Xpad] = kuwahara(X,WINSZ,progress)
% [Y,Xpad] = KUWAHARA(X[,WINSZ][,progress])
% perform kuwahara nonlinear edge-preserving filtering on an intensity
% image
%
% * If no window size WINSZ is specified, the default is 5.
% * Setting progress to a nonzero value causes KUWAHARA to display
%   the current row it is processing.
%
% Description:
% The Kuwahara filter works on a window divided into 4 overlapping
% subwindows (typically 5x5 pixels, see below). In each subwindow, the mean and
% variance are computed. The output value (located at the center of the
% window) is set to the mean of the subwindow with the smallest variance.
%
%    ( a  a  ab   b  b)
%    ( a  a  ab   b  b)
%    (ac ac abcd bd bd)
%    ( c  c  cd   d  d)
%    ( c  c  cd   d  d)
%
% Notes:
% Image is converted to double format for processing.
%
% References:
% http://www.incx.nec.co.jp/imap-vision/library/wouter/kuwahara.html
%
% Copyright Art Barnes, 2005 artbarnes<at>ieee<dot>org

if nargin >= 3
    verboseFlag = true;
else
    verboseFlag = false;
end

if nargin < 2
    WINSZ = 5;
end

if ~isa(X,'double')
    X = im2double(X);
end

PADDING = floor(WINSZ/2);

Xpad = padarray(X,[PADDING PADDING],'replicate');
[padRows,padCols] = size(Xpad);
Y = zeros(size(X));

nRowIters = length((PADDING+1):(padRows-PADDING));
count = 1;
for i = (PADDING+1):(padRows-PADDING)
    for j = (PADDING+1):(padCols-PADDING)
        % window & subwindows
        W = Xpad((i-PADDING):(i+PADDING),(j-PADDING):(j+PADDING));
        Wnw = W(1:(PADDING+1),1:(PADDING+1));
        Wne = W(1:(PADDING+1),(PADDING+1):WINSZ);
        Wsw = W((PADDING+1):WINSZ,1:(PADDING+1));
        Wse = W((PADDING+1):WINSZ,(PADDING+1):WINSZ);

        % find the variances
        s = var([Wnw(:) Wne(:) Wsw(:) Wse(:)]);
        m = mean([Wnw(:) Wne(:) Wsw(:) Wse(:)]);
        [y,k] = min(s);

        % assign the mean of the subwindow with the least variance to
        % the center pixel
        Y(i,j) = m(k);
    end

    if verboseFlag
        fprintf('Kuwahara: %d/%d\n',count,nRowIters);
        count = count + 1;
    end
end


text:
function im = screenShotRGB(x0,y0,widthSS, heightSS)
%screenShotRGB  Make a screenshot using Java.
%   im = screenShotRGB; make a screen capture of the entire screen, it returns
%   a RGB color image  with 'uint8' class elements.
%   im = screenShotRGB(x0,y0,widthSS, heightSS); makes a screenshot of the
%   rectangle defined by the botton-left point (x0, y0) in the screen
%   coordinates, and its width, and its height.
%
%   For example, make a screen shot of the entire screen, plot and save it to a
%   file:
%     im = screenShotRGB; % make the screenshot
%     imwrite(im,'screenShot.png');
%     figure
%     image(im);
%     axis equal, axis tight
%     axis off
%
%   screenShotRGB use the Java class 'Robot' to make the capture.

%   For more information about the Robot class see
%   http://www.mathworks.com/support/solutions/en/data/1-90E06C/?solution=1-90E06C
%   http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Robot.html#cr
%   eateScreenCapture%28java.awt.Rectangle%29

%   Matlab version by Daniel Mena 12-2009.

trash = java.awt.Toolkit.getDefaultToolkit();
screenSize = trash.getScreenSize();
widthScreen = screenSize.getWidth();
heightScreen = screenSize.getHeight();
if nargin == 0
    x0 = 0;
    y0 = 0;
    widthSS = widthScreen;
    heightSS = heightScreen;
else
% %
%     if (widthSS+x0 > (widthScreen)) || (heightSS+y0 > (heightScreen))
%         error('Rectangle is outside the screen.');
%     end
%     if (x0 > widthScreen) || (y0 > heightScreen)
%         error('Origin of the Rectangle is outside the screen.')
%     end
%     if (x0 < 0) || (y0 < 0)
%         error('x0 and y0 must be  positive.')
%     end
% %     y0=heightScreen-(heightSS+y0);
end
im = zeros(heightSS,widthSS,3,'uint8');
r = java.awt.Robot;
bimg = r.createScreenCapture(java.awt.Rectangle(x0, y0, widthSS, heightSS));
RGBA = bimg.getRGB(0,0,widthSS,heightSS,[],0,widthSS); % RGBA has int32 elements
RGBA = typecast(RGBA, 'uint8');

im(:,:,1) = reshape(RGBA(3:4:end),widthSS,heightSS).';
im(:,:,2) = reshape(RGBA(2:4:end),widthSS,heightSS).';
im(:,:,3) = reshape(RGBA(1:4:end),widthSS,heightSS).';

author: angeloyeo

repo: gongdols

save_path: github-repos/MATLAB/angeloyeo-gongdols


text:
function [outputData] = computeSaleaeOutput(matfile,varargin)
	% Processes Saleae output files. This is for data collected with Saleae Logic 1.x software, NOT 2.x.
	% Biafra Ahanonu
	% started: 2014.01.03 [19:13:01]
	% inputs
		% matfile - Str: path to Mat-file with Salaea outputs
	% outputs
		% outputData - table consisting of session times, frame clock (digital channel 0), and events in each channel or analog values in that frame.

	[outputData] = ciapkg.behavior.computeSaleaeOutput(matfile,'passArgs', varargin);
end

author: bahanonu

repo: ciatah

save_path: github-repos/MATLAB/bahanonu-ciatah


text:
function c = martin_phase(N)
% phase colormap as found in a tool from Martin Uecker (muecker@gwdg.de)

    if nargin < 1
        N = 64;
    end

phase = linspace(0,2*pi,N);

c = zeros(N,3);
c(:,1) = sin(phase);
c(:,2) = sin(phase + 120 * pi/180);
c(:,3) = sin(phase + 240 * pi/180);

c = (c + 1)/2;

end

author: leoliuf

repo: MRiLab

save_path: github-repos/MATLAB/leoliuf-MRiLab


text:
function [Problem,Constraints,Objectives] = ITERoptimoptset(Spec)

LBX0UB = [Spec.MyDesignTypVals,Spec.MyDesignTypVals,Spec.MyDesignTypVals];
Xnames=Spec.MyDesignXnames;

active_decX = false(length(Xnames),1);
active_decX(1:5) = true;

% defaults assume (from hist AC;~ min, median, max):
LBX0UBbase= [   12  40  70  ;% Disc Loading (kg/m2)
    .15     .25     .4  ;% Power to Weight (kW/kg)
    .03     .075    .15 ;% Solidity
    200     220     238 ;% Tip Speed (m/s)
    .08     .17     .275;% Fuel Fraction
    2       5       7   ;% Blades
    -20     -8      0   ;% Twist  (deg)
    0       0       .4  ;% Thrust to Weight
    0       0       2   ;% Sp. Wing Area (m2/tonne)
    6       7       9   ];% Wing AR

nBuiltInVars = size(LBX0UBbase,1);
LBX0UB(1:nBuiltInVars,1) = LBX0UBbase(:,1);
LBX0UB(1:nBuiltInVars,3) = LBX0UBbase(:,3);

X0 = LBX0UB(:,2);
LB = LBX0UB(:,1);
UB = LBX0UB(:,3);

%%
totalncons = Spec.nPPrequirements + Spec.nnonl;
active_constraints = true(totalncons,1);
extra_margins = zeros(totalncons,1);
useBEA = false(Spec.nPPrequirements,1);

nObj = Spec.nObj;
single_objective_weightings = ones(nObj,1);
ObjLabels = Spec.Objlabels;

for ii = 1:nObj
    if strncmpi('Obj_max',func2str(Spec.Objfuncs{ii}),7)
        single_objective_weightings(ii) = -1;
    end
end

nCons = totalncons;

conLabels = [Spec.PPlabels;Spec.nonllabels];

Problem.x0 =    X0;
Problem.Aineq = [];
Problem.bineq = [];
Problem.Aeq =   [];
Problem.beq =   [];
Problem.lb =    LB;
Problem.ub =    UB;
Problem.XLabels = Xnames;
Problem.activeX = active_decX;

Constraints.nCons = nCons;
Constraints.conLabels = conLabels;
Constraints.active_cons = active_constraints;
Constraints.useBEA = useBEA;
Constraints.margins = extra_margins;

Objectives.weightings = single_objective_weightings;
Objectives.nObj = nObj;
Objectives.ObjLabels = ObjLabels;


text:
%MINENCLOSINGCIRCLE  Finds a circle of the minimum area enclosing a 2D point set
%
%     [center,radius] = cv.minEnclosingCircle(points)
%
% ## Input
% * __points__ Input vector of 2D points, stored in numeric array
%   (Nx2/Nx1x2/1xNx2) or cell array of 2-element vectors (`{[x,y], ...}`).
%
% ## Output
% * __center__ Output center of circle `[x,y]`.
% * __radius__ Output radius of circle `r`.
%
% The function finds the minimal enclosing circle of a 2D point set using an
% iterative algorithm.
%
% See also: cv.minEnclosingTriangle
%

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
classdef RWMOP35 < PROBLEM
% <multi> <real> <constrained>
% Synchronous pptimal pulse-width modulation of 13-level inverters

%------------------------------- Reference --------------------------------
% A. Kumar, G. Wu, M. Ali, Q. Luo, R. Mallipeddi, P. Suganthan, and S. Das,
% A benchmark-suite of real-world constrained multi-objective optimization
% problems and some baseline results, Swarm and Evolutionary Computation,
% 2021, 67: 100961.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        %% Initialization
        function Setting(obj)
            obj.M        = 2;
            obj.D        = 30;
            obj.lower    = zeros(1,30);
            obj.upper    = 90*ones(1,30);
            obj.encoding = ones(1,obj.D);
        end
        %% Evaluate multiple solutions
        function Population = Evaluation(obj,varargin)
            x = varargin{1};
            m = 0.32;
            s = [1,1,1,-1,1,-1,1,-1,1,1,1,1,-1,-1,-1,-1,1,-1,1,-1,1,1,1,1,-1,-1,-1,1,-1,1];
            k = [5,7,11,13,17,19,23,25,29,31,35,37,41,43,47,49,53,55,59,61,65,67,71,73,77,79,83,85,91,95,97];
            % Objective function
            for i = 1 : size(x,1)
                su = 0;
                for j = 1 : 31
                    su2 = 0;
                    for l = 1 : size(x,2)
                        su2 = su2 + s(l).*cos(k(j).*x(i,l)*pi/180);
                    end
                    su = su + su2.^2./k(j).^4;
                end
                f(i,1) = (su).^0.5./(sum(1./k.^4)).^0.5;
            end
            f(:,2) = (sum(s.*cos(x*pi/180),2)-m).^2;
            % Constraints
            for i = 1 : size(x,2)-1
                g(:,i) = x(:,i)-x(:,i+1)+1e-6;
            end
            Population = SOLUTION(varargin{1},f,g,varargin{2:end});
            obj.FE     = obj.FE + length(Population);
        end
        %% Generate a point for hypervolume calculation
        function R = GetOptimum(obj,~)
            R = [1.9499692e+00   1.1076986e+01];
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
clear all;
close all;
path(path, './code');


text:
def PlotFrame(aedat, numPlots, distributeBy, minTime, maxTime, transpose, flipVertical, flipHorizontal)

%{
Takes 'aedat' - a data structure containing an imported .aedat file,
as created by ImportAedat, and creates a series of images from selected
frames.
The number of subplots is given by the numPlots parameter.
'distributeBy' can either be 'time' or 'events', to decide how the points
around which data is rendered are chosen.
The frame events are then chosen as those nearest to the time points.
If the 'distributeBy' is 'time' then if the further parameters 'minTime'
and 'maxTime' are used then the time window used is only between
those limits.
flipVertical is assumed true, so that y=0 is considered the top of the image.
%}

if ~exist('distributeBy', 'var')
	distributeBy = 'time';
end

if ~exist('numPlots', 'var')
	numPlots = 12;
end

% This function assumes that aedat3 frame timestamps have been simplified
timeStamps = aedat.data.frame.timeStampStart;
% This function plots all frames, assuming that they are valid;
% it assumes that reset read subtraction has been performed
numFrames = length(aedat.data.frame.samples);
if numFrames < numPlots
	numPlots = numFrames;
end

if numFrames == numPlots
	distributeBy = 'events';
end

% Distribute plots in a raster with a 3:4 ratio
numPlotsX = round(sqrt(numPlots / 3 * 4));
numPlotsY = ceil(numPlots / numPlotsX);

if strcmpi(distributeBy, 'time')
    if ~exist('minTime', 'var') || (exist('minTime', 'var') && minTime == 0)
        minTime = min(timeStamps);
    else
        minTime = minTime * 1e6;
    end
    if ~exist('maxTime', 'var') || (exist('maxTime', 'var') && maxTime == 0)
        maxTime = max(timeStamps);
    else
        maxTime = maxTime * 1e6;
    end

	totalTime = maxTime - minTime;
	timeStep = totalTime / numPlots;
	timePoints = minTime + timeStep * 0.5 : timeStep : maxTime;
else % distribute by event number
	framesPerStep = numFrames / numPlots;
	timePoints = timeStamps(ceil(framesPerStep * 0.5 : framesPerStep : numFrames));
end

if numPlots > 1
    figure
end
for plotCount = 1 : numPlots
	if numPlots > 1
        subplot(numPlotsY, numPlotsX, plotCount);
	end
	hold all
	% Find eventIndex nearest to timePoint
	frameIndex = find(timeStamps >= timePoints(plotCount), 1, 'first');
	% Ignore colour for now ...
	if exist('transpose', 'var') && transpose
        imagesc(aedat.data.frame.samples{frameIndex}')
    else
        imagesc(aedat.data.frame.samples{frameIndex})
	end
    colormap('gray')
	axis equal tight
	if ~exist('flipVertical', 'var') || ~flipVertical
		set(gca, 'YDir', 'reverse')
	end
	if exist('flipHorizontal', 'var') && flipHorizontal
		set(gca, 'XDir', 'reverse')
	end
	title(['Time: ' num2str(round(double(timeStamps(frameIndex)) / 1000) /1000) ' s; frame number: ' num2str(frameIndex)])
end

author: panpanfei


text:
function varargout = time_response_localwfs_sbl(X,xs,src,conf)
%TIME_RESPONSE_LOCALWFS_SBL time response for local WFS
%
%   Usage: [s,t] = time_response_localwfs_sbl(X,xs,src,conf)
%
%   Input parameters:
%       X           - listener position / m
%       xs          - position of virtual source / m
%       src         - source type of the virtual source
%                         'pw' -plane wave
%                         'ps' - point source
%                         'fs' - focused source
%       conf        - configuration struct (see SFS_config)
%
%   Output parameters:
%       s           - simulated time response
%       t           - corresponding time axis / s
%
%   TIME_RESPONSE_LOCALWFS_SBL(X,xs,src,conf) simulates the impulse response of
%   a source synthesized by local WFS using spatial bandwidth limitation at the
%   given virtual microphone position X.
%   The length in samples of the impulse response is given by conf.N. The
%   actual calculation is done via sound_field_imp() and a loop over time t. A
%   similar result can be achieved by using ir_localwfs() in combination with
%   dummy_irs().
%
%   See also: ir_localwfs, sound_field_imp, freq_response_localwfs_vss

%*****************************************************************************
% The MIT License (MIT)                                                      *
%                                                                            *
% Copyright (c) 2010-2019 SFS Toolbox Developers                             *
%                                                                            *
% Permission is hereby granted,  free of charge,  to any person  obtaining a *
% copy of this software and associated documentation files (the "Software"), *
% to deal in the Software without  restriction, including without limitation *
% the rights  to use, copy, modify, merge,  publish, distribute, sublicense, *
% and/or  sell copies of  the Software,  and to permit  persons to whom  the *
% Software is furnished to do so, subject to the following conditions:       *
%                                                                            *
% The above copyright notice and this permission notice shall be included in *
% all copies or substantial portions of the Software.                        *
%                                                                            *
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
% IMPLIED, INCLUDING BUT  NOT LIMITED TO THE  WARRANTIES OF MERCHANTABILITY, *
% FITNESS  FOR A PARTICULAR  PURPOSE AND  NONINFRINGEMENT. IN NO EVENT SHALL *
% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
% LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT, TORT  OR OTHERWISE, ARISING *
% FROM,  OUT OF  OR IN  CONNECTION  WITH THE  SOFTWARE OR  THE USE  OR OTHER *
% DEALINGS IN THE SOFTWARE.                                                  *
%                                                                            *
% The SFS Toolbox  allows to simulate and  investigate sound field synthesis *
% methods like wave field synthesis or higher order ambisonics.              *
%                                                                            *
% https://sfs.readthedocs.io                            sfstoolbox@gmail.com *
%*****************************************************************************

%% ===== Checking of input  parameters ==================================
nargmin = 4;
nargmax = 4;
narginchk(nargmin,nargmax);
isargposition(X);
isargxs(xs);
isargchar(src);
isargstruct(conf);

%% ===== Configuration ==================================================
fs = conf.fs;
N = conf.N;
showprogress = conf.showprogress;
useplot = conf.plot.useplot;
% Select secondary source type
if strcmp('2D',conf.dimension)
    greens_function = 'ls';
else
    greens_function = 'ps';
end

%% ===== Computation ====================================================
% Disable progress bar and plotting for sound_field_imp()
conf.showprogress = false;
conf.plot.useplot = false;
% Get the position of the loudspeakers
x0 = secondary_source_positions(conf);
x0 = secondary_source_selection(x0,xs,src);
x0 = secondary_source_tapering(x0,conf);
% Generate time axis
t = (0:N-1)'/fs;
s = zeros(1,length(t));
d = driving_function_imp_localwfs_vss(x0,xs,src,conf);
for ii = 1:length(t)
    if showprogress, progress_bar(ii,length(t)); end
    % Calculate sound field at the listener position
    p = sound_field_imp(X(1),X(2),X(3),x0,greens_function,d,t(ii),conf);
    s(ii) = real(p);
end

% Return parameter
if nargout>0, varargout{1}=s; end
if nargout>1, varargout{2}=t; end

%% ===== Plotting ========================================================
if nargout==0 || useplot
    figure;
    figsize(conf.plot.size(1),conf.plot.size(2),conf.plot.size_unit);
    plot(t*1000,s);
    ylabel('amplitude');
    xlabel('time / ms');
end

author: sfstoolbox

repo: sfs-matlab


text:
function [dataout] = ft_denoise_dssp(cfg, datain)

% FT_DENOISE_DSSP implements a dual signal subspace projection algorithm
% to suppress interference outside a predefined source region of
% interest. It is based on: Sekihara et al. J. Neural Eng. 2016 13(3), and
% Sekihara et al. J. Neural Eng. 2018 15(3).
%
% Use as
%   dataout = ft_denoise_dssp(cfg, datain)
% where cfg is a configuration structure that contains
%   cfg.channel          = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details
%   cfg.trials           = 'all' or a selection given as a 1xN vector (default = 'all')
%   cfg.sourcemodel      = structure, source model with precomputed leadfields, see FT_PREPARE_LEADFIELD
%   cfg.dssp             = structure with parameters that determine the behavior of the algorithm
%   cfg.dssp.n_space     = 'all', or scalar. Number of dimensions for the
%                          initial spatial projection.
%   cfg.dssp.n_in        = 'all', or scalar. Number of dimensions of the
%                          subspace describing the field inside the ROI.
%   cfg.dssp.n_out       = 'all', or scalar. Number of dimensions of the
%                          subspace describing the field outside the ROI.
%   cfg.dssp.n_intersect = scalar (default = 0.9). Number of dimensions (if
%                          value is an integer>=1), or threshold for the
%                          included eigenvalues (if value<1), determining
%                          the dimensionality of the intersection.
%
% See also FT_DENOISE_PCA, FT_DENOISE_SYNTHETIC, FT_DENOISE_TSR

% these are used by the ft_preamble/ft_postamble function and scripts
ft_revision = '$Id$';
ft_nargin   = nargin;
ft_nargout  = nargout;

% do the general setup of the function
ft_defaults
ft_preamble init
ft_preamble debug
ft_preamble loadvar    datain
ft_preamble provenance datain
ft_preamble trackconfig

% the ft_abort variable is set to true or false in ft_preamble_init
if ft_abort
  % do not continue function execution in case the outputfile is present and the user indicated to keep it
  return
end

% check the input data
datain = ft_checkdata(datain, 'datatype', {'raw'}); % FIXME how about timelock and freq?

cfg = ft_checkconfig(cfg, 'renamed', {'hdmfile', 'headmodel'});
cfg = ft_checkconfig(cfg, 'renamed', {'vol',     'headmodel'});
cfg = ft_checkconfig(cfg, 'renamed', {'grid',    'sourcemodel'});

% get the options
cfg.trials       = ft_getopt(cfg, 'trials',  'all', 1);
cfg.channel      = ft_getopt(cfg, 'channel', 'all');
cfg.sourcemodel  = ft_getopt(cfg, 'sourcemodel');
cfg.dssp         = ft_getopt(cfg, 'dssp');         % sub-structure to hold the parameters
cfg.dssp.n_space = ft_getopt(cfg.dssp, 'n_space', 'all'); % number of spatial components to retain from the Gram matrix
cfg.dssp.n_in    = ft_getopt(cfg.dssp, 'n_in', 'all');    % dimensionality of the Bin subspace to be used for the computation of the intersection
cfg.dssp.n_out   = ft_getopt(cfg.dssp, 'n_out', 'all');   % dimensionality of the Bout subspace to be used for the computation of the intersection
cfg.dssp.n_intersect = ft_getopt(cfg.dssp, 'n_intersect', 0.9); % dimensionality of the intersection
cfg.output       = ft_getopt(cfg, 'output', 'original');

% select channels and trials of interest, by default this will select all channels and trials
tmpcfg = keepfields(cfg, {'trials', 'channel', 'showcallinfo'});
datain = ft_selectdata(tmpcfg, datain);
% restore the provenance information
[cfg, datain] = rollback_provenance(cfg, datain);

% match the input data's channels with the labels in the leadfield
sourcemodel = cfg.sourcemodel;
if ~isfield(sourcemodel, 'leadfield')
  ft_error('cfg.sourcemodel needs to contain leadfields');
end
[indx1, indx2] = match_str(datain.label, sourcemodel.label);
if ~isequal(indx1(:),(1:numel(datain.label))')
  ft_error('unsupported mismatch between data channels and leadfields');
end
if islogical(sourcemodel.inside)
  inside = find(sourcemodel.inside);
else
  inside = sourcemodel.inside;
end
for k = inside(:)'
  sourcemodel.leadfield{k} = sourcemodel.leadfield{k}(indx2,:);
end

% compute the Gram-matrix of the supplied forward model
lf = cat(2, sourcemodel.leadfield{:});
G  = lf*lf';

dat     = cat(2,datain.trial{:});
[dum, Ae, N, Nspace, Sout, Sin, Sspace, S] = dssp(dat, G, cfg.dssp.n_in, cfg.dssp.n_out, cfg.dssp.n_space, cfg.dssp.n_intersect);
datAe   = dat*Ae; % the projection is a right multiplication
% with a matrix (eye(size(Ae,1))-Ae*Ae'), since Ae*Ae' can become quite
% sizeable, it's computed slightly differently here.

% put some diagnostic information in the output cfg.
cfg.dssp.S_space        = Sspace;
cfg.dssp.n_space        = Nspace;
cfg.dssp.S_out          = Sout;
cfg.dssp.S_in           = Sin;
cfg.dssp.S_intersect    = S;
cfg.dssp.n_intersect    = N;

% compute the cleaned data and put in a cell-array
nsmp  = cellfun(@numel, datain.time);
csmp  = cumsum([0 nsmp]);
trial = cell(size(datain.trial));
switch cfg.output
  case 'original'
    for k = 1:numel(datain.trial)
      trial{k} = datain.trial{k} - datAe*Ae((csmp(k)+1):csmp(k+1),:)';
    end
  case 'complement'
    for k = 1:numel(datain.trial)
      trial{k} = datAe*Ae((csmp(k)+1):csmp(k+1),:)';
    end
  otherwise
    ft_error(sprintf('cfg.output = ''%s'' is not implemented',cfg.output));
end

% create the output argument
dataout       = keepfields(datain, {'label','time','fsample','trialinfo','sampleinfo','grad', 'elec', 'opto'}); % grad can be kept and does not need to be balanced, since the cleaned data is a mixture over time, not space.
dataout.trial = trial;

ft_postamble debug
ft_postamble trackconfig
ft_postamble previous   datain
ft_postamble provenance dataout
ft_postamble history    dataout
ft_postamble savevar    dataout

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunctions for the computation of the projection matrix
% kindly provided by Kensuke, and adjusted a bit by Jan-Mathijs
function [Bclean, Ae, Nee, Nspace, Sout, Sin, Sspace, S] = dssp(B, G, Nin, Nout, Nspace, Nee)

% Nc: number of sensors
% Nt: number of time points
% inputs
% B(Nc,Nt):  interference overlapped sensor data
% G(Nc,Nc): Gram matrix of voxel lead field
% Nout and Nin: dimensions of the two row spaces
% recom_Nspace: recommended value for the dimension of the pseudo-signal subspace
% outputs
% Bclean(Nc,Nt): cleaned sensor data
% Nee: dimension of the intersection
% Nspace: dimension of the pseudo-signal subspace
%  ------------------------------------------------------------
%  programmed by K. Sekihara,  Signal Analysis Inc.
%  All right reserved by Signal Analysis Inc.
% -------------------------------------------------------------
%
% The code below is modified by Jan-Mathijs, no functional changes
% merely cosmetics

% eigen decomposition of the Gram matrix, matrix describing the spatial
% components
[U,S]   = eig(G);
Sspace  = abs(diag(S));

[Sspace, iorder] = sort(-Sspace);
Sspace           = -Sspace;
U(:,:)           = U(:,iorder);

if isempty(Nspace)
  ttext = 'enter the spatial dimension: ';
  Nspace    = input(ttext);
elseif ischar(Nspace) && isequal(Nspace, 'interactive')
  figure, plot(log10(Sspace),'-o');
  Nspace = input('enter spatial dimension of the ROI subspace: ');
elseif ischar(Nspace) && isequal(Nspace, 'all')
  Nspace = find(Sspace./Sspace(1)>1e5*eps, 1, 'last');
end
fprintf('Using %d spatial dimensions\n', Nspace);

% spatial subspace projector
Us   = U(:,1:Nspace);
USUS = Us*Us';

% Bin and Bout creations
Bin  =                  USUS  * B;
Bout = (eye(size(USUS))-USUS) * B;

% create the temporal subspace projector and apply it to the data
%[AeAe, Nee] = CSP01(Bin, Bout, Nout, Nin, Nee);
%Bclean      = B*(eye(size(AeAe))-AeAe);

[Ae, Nee, Sout, Sin, S] = CSP01(Bin, Bout, Nin, Nout, Nee);
Bclean    = B - (B*Ae)*Ae'; % avoid computation of Ae*Ae'

function [Ae, Nee, Sout, Sin, S] = CSP01(Bin, Bout, Nin, Nout, Nee)
%
% interference rejection by removing the common temporal subspace of the two subspaces
% K. Sekihara,  March 28, 2012
% Golub and Van Loan, Matrix computations, The Johns Hopkins University Press, 1996
%
%  Nc: number of channels
%  Nt: number of time points
% inputs
%  Bout(1:Nc,1:Nt): interference data
%  Bin(1:Nc,1:Nt): signal plus interference data
%  ypost(1:Nc,1:Nt): denoised data
%  Nout: dimension of the interference subspace
%  Nin: dimension of the signal plus interference subspace
%  Nee: dimension of the intersection of the two subspaces
% outputs
% Ae = matrix from which the projector onto the intersection can
%      be obtained:
% AeAe: projector onto the intersection, which is equal to the
%       interference subspace.
% Nee: dimension of the intersection
%  ------------------------------------------------------------
%  programmed by K. Sekihara,  Signal Analysis Inc.
%  All right reserved by Signal Analysis Inc.
% -------------------------------------------------------------
%

[dum,Sout,Vout] = svd(Bout,'econ');
[dum,Sin, Vin]  = svd(Bin, 'econ');
Sout = diag(Sout);
Sin  = diag(Sin);

if isempty(Nout)
  ttext = 'enter the spatial dimension for the outside field: ';
  Nout  = input(ttext);
elseif ischar(Nout) && isequal(Nout, 'interactive')
  figure, plot(Sout,'-o');
  Nout = input('enter dimension of the outside field: ');
elseif ischar(Nout) && isequal(Nout, 'all')
  Nout = find(Sout./Sout(1)>1e5*eps, 1, 'last');
end
fprintf('Using %d spatial dimensions for the outside field\n', Nout);

if isempty(Nin)
  ttext = 'enter the spatial dimension for the inside field: ';
  Nin  = input(ttext);
elseif ischar(Nin) && isequal(Nin, 'interactive')
  figure, plot(log10(Sin),'-o');
  Nin = input('enter dimension of the inside field: ');
elseif ischar(Nin) && isequal(Nin, 'all')
  Nin = find(Sin./Sin(1)>1e5*eps, 1, 'last');
end
fprintf('Using %d spatial dimensions for the inside field\n', Nin);

Qout = Vout(:,1:Nout);
Qin  = Vin(:, 1:Nin);

C     = Qin'*Qout;
[U,S] = svd(C);
S     = diag(S);
if (ischar(Nee) && strcmp(Nee, 'auto'))
  ft_error('automatic determination of intersection dimension is not supported');
elseif ischar(Nee) && strcmp(Nee, 'interactive')
  figure, plot(S,'-o');
  Nee  = input('enter dimension of the intersection: ');
elseif Nee<1
  % treat a numeric value < 1 as a threshold
  Nee = find(S>Nee,1,'last');
  if isempty(Nee), Nee = 1; end
end
fprintf('Using %d dimensions for the interaction\n', Nee);

Ae   = Qin*U;
Ae   = Ae(:,1:Nee);
%AeAe = Ae*Ae';


text:
jobIDs = [2130597 2130598 2130599 2130600 2130601 2130602];
taskIDs = 1:4;

infNames = {'SM+zDD AnnealLIN', 'SM+zDD', 'SM+cDD'};
initNames = {'one', 'seq'};

nn=1;
for aa = 1:length(initNames)
for jj = 1:length(infNames)
    jobNames{nn} = [infNames{jj} ' ' initNames{aa}];
    nn=nn+1;
end
end

plotLogPrVsTime( jobIDs(1:3), taskIDs, jobNames(1:3) );
set(gcf, 'name', 'OneInit' );
ylim( [-6.45 -6.25]*1e5 );

plotLogPrVsTime( jobIDs(4:6), taskIDs, jobNames(4:6) );
set(gcf, 'name', 'SeqInit' );
ylim( [-6.45 -6.25]*1e5 );

author: michaelchughes

repo: NPBayesHMM


text:
% This function will find all subfolders of a directory
function subfolders = findSubfolders(rootdir)

[list ISDIR]= my_dir(rootdir);
subfolders = {};

for i=1:length(list)
    tmp = [rootdir '/' list{i}];
    if ISDIR(i)==1
        subfolders{end+1} = tmp;
        subsubfolders = findSubfolders(subfolders{end});
        subfolders = [subfolders subsubfolders];
    end
end

author: singaxiong

repo: SignalGraph


text:
function [ahm, AHM_rf, AHM_sf, AHM_sk, AHM_sc, AHM_u, AHM_rho] = ...
    retroProjAhmPntFromOmniCamOnRob(Rf, Sf, Sk, Sc, u, n)

% RETROPROJAHMPNTFROMOMNICAMONROB Retro-project ahm from omnicam on robot.
%
%   AHM = RETROPROJAHMPNTINTOOMNICAMONROB(RF, SF, SK, SC, U, N) gives the
%   retroprojected AHM in World Frame from an observed pixel U. RF and SF
%   are Robot and Sensor Frames, Sk and Sc are camera calibration and
%   distortion correction parameters. U is the pixel coordinate and N is
%   the non-observable inverse depth. AHM is a 7-vector :
%     AHM = [X Y Z U V W IDepth]'
%
%   [AHM, AHM_rf, AHM_sf, AHM_k, AHM_c, AHM_u, AHM_n] = ... returns the
%   Jacobians wrt RF.x, SF.x, SK, SC, U and N.
%
%   See also FROMFRAMEAHM.
%

%   Copyright 2012 Grigory Abuladze @ ASL-vision
%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.

% Frame World -> Robot  :  Rf
% Frame Robot -> Sensor :  Sf

  % AHM in Sensor Frame
  [ahms, AHMS_u, AHMS_rho, AHMS_sk, AHMS_sc] = invOmniCamAhm(u, n, Sk, Sc) ;

  [ahmr, AHMR_sf, AHMR_ahms] = fromFrameAhm(Sf,ahms);
  [ahm , AHM_rf , AHM_ahmr]  = fromFrameAhm(Rf,ahmr);

  AHM_ahms = AHM_ahmr*AHMR_ahms;
  AHM_sk   = AHM_ahms*AHMS_sk ;
  AHM_sf   = AHM_ahmr*AHMR_sf;

  AHM_sc  = AHM_ahms*AHMS_sc ;

  AHM_u   = AHM_ahms*AHMS_u ;
  AHM_rho = AHM_ahms*AHMS_rho ;

end

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB 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.
%
%   SLAMTB 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 SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE

author: joansola

repo: slamtb

save_path: github-repos/MATLAB/joansola-slamtb


text:
% Copyright 2017 Lime Microsystems Ltd.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%    http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% 3GPP TS 25.211 7.2.0 r7 p12 Table 3&4
% slots 0-14
% bits 3,4,5,6,7,8
function y=WCDMAULPilots( slot, bits )
	if bits==3 % col 1&2 can be used as FSW
		pilots=[1,1,1;0,0,1;0,1,1;0,0,1; \
		1,0,1;1,1,1;1,1,1;1,0,1; \
		0,1,1;1,1,1;0,1,1;1,0,1; \
		1,0,1;0,0,1;0,0,1];
	elseif bits==4 % col 2&3 can be used as FSW
		pilots=[1,1,1,1;1,0,0,1;1,0,1,1;1,0,0,1; \
		1,1,0,1;1,1,1,1;1,1,1,1;1,1,0,1; \
		1,0,1,1;1,1,1,1;1,0,1,1;1,1,0,1; \
		1,1,0,1;1,0,0,1;1,0,0,1];
	elseif bits==5 % col 1,2 and 4,5 can be used as FSW
		pilots=[1,1,1,1,0;0,0,1,1,0;0,1,1,0,1;0,0,1,0,0; \
		1,0,1,0,1;1,1,1,1,0;1,1,1,0,0;1,0,1,0,0; \
		0,1,1,1,0;1,1,1,1,1;0,1,1,0,1;1,0,1,1,1; \
		1,0,1,0,0;0,0,1,1,1;0,0,1,1,1];
	elseif bits==6 % col 2,3 and 5,6
		pilots=[1,1,1,1,1,0;1,0,0,1,1,0;1,0,1,1,0,1;1,0,0,1,0,0; \
		1,1,0,1,0,1;1,1,1,1,1,0;1,1,1,1,0,0;1,1,0,1,0,0; \
		1,0,1,1,1,0;1,1,1,1,1,1;1,0,1,1,0,1;1,1,0,1,1,1; \
		1,1,0,1,0,0;1,0,0,1,1,1;1,0,0,1,1,1];
	elseif bits==7 % col 2,3 and 5,6
		pilots=[1,1,1,1,1,0,1;1,0,0,1,1,0,1;1,0,1,1,0,1,1;1,0,0,1,0,0,1; \
		1,1,0,1,0,1,1;1,1,1,1,1,0,1;1,1,1,1,0,0,1;1,1,0,1,0,0,1; \
		1,0,1,1,1,0,1;1,1,1,1,1,1,1;1,0,1,1,1,0,1;1,1,0,1,1,1,1; \
		1,1,0,1,0,0,1;1,0,0,1,1,1,1;1,0,0,1,1,1,1];
	else % bits=8 % col 1,3 and 5,7
		pilots=[1,1,1,1,1,1,1,0;1,0,1,0,1,1,1,0;1,0,1,1,1,0,1,1;1,0,1,0,1,0,1,0;
		1,1,1,0,1,0,1,1;1,1,1,1,1,1,1,0;1,1,1,1,1,0,1,0;1,1,1,0,1,0,1,0;
		1,0,1,1,1,1,1,0;1,1,1,1,1,1,1,1;1,0,1,1,1,0,1,1;1,1,1,0,1,1,1,1;
		1,1,1,0,1,0,1,0;1,0,1,0,1,1,1,1;1,0,1,0,1,1,1,1];
	end
	size(pilots);
	y=pilots(slot+1,:);
end

author: myriadrf


text:
clear;
clc;
close all;
format

%% 读取数据

%% 角速度为rad， 加速度为m/s^(2)
load example_ins4.mat

Fs = 100;
N = length(acc);

% 惯导解算, 初始化
p = zeros(3, 1);
v = zeros(3, 1);
q= [1 0 0 0]';

for i=1:N
    [p ,v , q] = ch_nav_equ_local_tan(p, v, q, acc(:,i), gyr(:,i), 1 / Fs, [0, 0, -9.8]');
    h_pos(i,:) = p;
    h_eul(i,:) = ch_q2eul(q);
end

figure;
subplot(2,2,1);
ch_plot_pos3d(h_pos);
subplot(2,2,2);
ch_plot_pos2d(h_pos);
subplot(2,2,3);
ch_plot_att(h_eul);

fprintf("共%d数据，用时:%.3fs\n", N, N/Fs);
fprintf("起始位置:%.3f %.3f, 终点位置%.3f %.3f, 相差:%.3fm\n", h_pos(1,1), h_pos(1,2), h_pos(N,1), h_pos(N,2), norm(h_pos(N,:) - h_pos(1,:)));

author: yandld


text:
function obj = fcn_autonn_custom_fn(block, inputs, ~)
% FCN_AUTONN_CUSTOM_FN autonn custom layer converter
%
% Copyright (C) 2017 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]

  switch class(block)
    case 'dagnn.Crop'
      obj = vl_nncrop_wrapper(inputs{1}, inputs{2}, block.crop) ;
  end

author: albanie

repo: convnet-burden


text:
function modelnet_off2mat(off_path, data_path, classes, volume_size, pad_size, angle_inc)
% Put the mesh object in a volume grid and save the volumetric
% represenation file.
% This is the input volumetric data for 3D ShapeNets.
% off_path: root off data folder
% data_path: destination volumetric data folder

phases = {'train', 'test'};

data_size = pad_size * 2 + volume_size;
for c = 1 : length(classes)
    fprintf('writing the %s category\n', classes{c});
    category_path = [off_path '/' classes{c}];
    dest_path = [data_path '/' classes{c} '/' num2str(data_size)];
    if ~exist(dest_path, 'dir')
        mkdir(dest_path);
    end
    % for train and test phases
    for t = 1 : numel(phases)
        phase = phases{t};
        off_list = [category_path '/' phase];
        dest_tsdf_path = [dest_path '/' phase];
        if ~exist(dest_tsdf_path, 'dir')
            mkdir(dest_tsdf_path);
        end
        files = dir(off_list);
        for i = 1 : length(files)
            if strcmp(files(i).name, '.') || strcmp(files(i).name, '..') || files(i).isdir == 1 || ~strcmp(files(i).name(end-2:end), 'off')
                continue;
            end
%             rnd_Vol = randi([0 4]);
            filename = [off_list '/' files(i).name];
            for viewpoint = 1 : 360/angle_inc
                destname = [dest_tsdf_path '/' files(i).name(1:end-4) '_' num2str(viewpoint) '.mat'];
                off_data = off_loader(filename, (viewpoint-1)*angle_inc);
%                 instance = polygon2voxel(off_data, [volume_size, volume_size, volume_size], 'auto',t,rnd_Vol);
                instance = polygon2voxel(off_data, [volume_size, volume_size, volume_size], 'auto');
                instance = padarray(instance, [pad_size, pad_size, pad_size]);
                instance = int8(instance);
                save(destname, 'instance');
            end
        end
    end
end

function offobj = off_loader(filename, theta, axis, stretch)

offobj = struct();
fid = fopen(filename, 'rb');
OFF_sign = fscanf(fid, '%c', 3);
assert(strcmp(OFF_sign, 'OFF') == 1);

info = fscanf(fid, '%d', 3);
offobj.vertices = reshape(fscanf(fid, '%f', info(1)*3), 3, info(1))';
offobj.faces = reshape(fscanf(fid, '%d', info(2)*4), 4, info(2))';

% do some translation and rotation
center = (max(offobj.vertices) + min(offobj.vertices)) / 2;
offobj.vertices = bsxfun(@minus, offobj.vertices, center);
if exist('axis', 'var')
    switch axis
        case 'x',
            offobj.vertices(:,1) = offobj.vertices(:,1) * stretch;
        case 'y',
            offobj.vertices(:,2) = offobj.vertices(:,2) * stretch;
        case 'z',
            offobj.vertices(:,3) = offobj.vertices(:,3) * stretch;
        otherwise,
            error('off_loader axis set wrong');
    end
end
theta = theta * pi / 180;
R = [cos(theta), -sin(theta), 0;
     sin(theta), cos(theta) , 0;
        0      ,    0       , 1];

offobj.vertices = offobj.vertices * R;

% These vertices to define faces should be offset by one to follow the matlab convention.
offobj.faces = offobj.faces(:,2:end) + 1;

fclose(fid);

author: lmb-freiburg

repo: orion

save_path: github-repos/MATLAB/lmb-freiburg-orion


text:
function [xi,w]=fifthOrderPyramidCubPoints()
%%FIFTHORDERPYRAMIDCUBPOINTS Generate fifth-order cubature points for
%  integration over a 3-dimensional pyramid with a square base with the
%  peak vertex at (0,0,1) and the base vertices at (1,-1,-1), (-1,-1,-1),
%  (-1,1,-1), and (1,1,-1).
%
%INPUTS: None
%
%OUTPUTS: xi This is a 3XnumCubPoints set of points for the standard
%            square pyramid.
%          w A 1XnumCubPoints set of cubature weights. This sums to the
%            volume of the standard square pyramid (8/3).
%
%This function implements the points given in [1] (15 points).
%
%EXAMPLE:
%We compare a 5th-order moment computed using these cubature points
%to one computed using monomialIntPyramid. The results are the same within
%typical finite precision limits.
% [xi,w]=fifthOrderPyramidCubPoints();
% alpha=[2;2;1];
% theMoment=findMomentFromSamp(alpha,xi,w);
% intVal=monomialIntPyramid(alpha);
% RelErr=(theMoment-intVal)/intVal
%
%REFERENCES:
%[1] F. D. Witherden and P. E. Vincent, "On the identification of symmetric
%    quadrature rules for finite element methods," Computer and Mathematics
%    with Applications, vol. 69, no. 10, pp. 1232-1241, May 2015.
%
%October 2022 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

M=[                                     0,                                          0,   0.45971576156501338586164265377920811314,   0.18249431975770692138374895897213800931;
                                        0,                                          0,  -0.39919795837246198593385139590712322914,   0.45172563864726406056400285032640105704;
                                        0,                                          0,  -0.99999998701645569241460017355590234925,   0.15654542887619877154120304977336547704;
 0.70652603154632457420722562974792066862,                                          0,                                      -0.75,   0.20384344839498724639142514342645843799;
                                        0,   0.70652603154632457420722562974792066862,                                      -0.75,   0.20384344839498724639142514342645843799;
-0.70652603154632457420722562974792066862,                                          0,                                      -0.75,   0.20384344839498724639142514342645843799;
                                        0,  -0.70652603154632457420722562974792066862,                                      -0.75,   0.20384344839498724639142514342645843799;
 0.70511712277882760181079385797948261057,   0.70511712277882760181079385797948261057,  -0.87777618587595407108464357252416911085,   0.10578907087905457654220386143818487109;
 0.70511712277882760181079385797948261057,  -0.70511712277882760181079385797948261057,  -0.87777618587595407108464357252416911085,   0.10578907087905457654220386143818487109;
-0.70511712277882760181079385797948261057,   0.70511712277882760181079385797948261057,  -0.87777618587595407108464357252416911085,   0.10578907087905457654220386143818487109;
-0.70511712277882760181079385797948261057,  -0.70511712277882760181079385797948261057,  -0.87777618587595407108464357252416911085,   0.10578907087905457654220386143818487109;
 0.43288286410354097685000790909815143591,   0.43288286410354097685000790909815143591,  -0.15279732576055038842025517341026975071,   0.15934280057233240536079894703404722173;
 0.43288286410354097685000790909815143591,  -0.43288286410354097685000790909815143591,  -0.15279732576055038842025517341026975071,   0.15934280057233240536079894703404722173;
-0.43288286410354097685000790909815143591,   0.43288286410354097685000790909815143591,  -0.15279732576055038842025517341026975071,   0.15934280057233240536079894703404722173;
-0.43288286410354097685000790909815143591,  -0.43288286410354097685000790909815143591,  -0.15279732576055038842025517341026975071,   0.15934280057233240536079894703404722173];

w=M(:,4);
xi=M(:,1:3)';

end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
function [y,varname]=xml2struct(filename_or_xml_string)

%XML2STRUCT reads non-MbML compliant xmlfile into matlab structure
%
% Syntax: [y,varname]=xml2struct(filename_or_xml_string)
%
% Description:
%   1. Convert any non-MbML xml into MbML compliant string
%   2. Stores consecutive structures in the a dimensional strucure
%
% If the non-MbML compliant XML has a consistent internal reference structure
% (those that were derived from explicit data models often do)
% this conversion will produce the best results, by building
%
% Note: if your XML string is MbML compliant use XML2MAT instead
%
% See also: XML2STRUCT
%
% Jonas Almeida, almeidaj@musc.edu, 19 May 2003, MAT4NAT Tbox

[y,varname]=xml2cell(filename_or_xml_string);
y=consolidateall(y);

author: fieldtrip

repo: fieldtrip


text:
function [tSnrImage, fileTsnr, tSnrRatioImage, fileTsnrRatio] = ...
    tapas_physio_compute_tsnr_spm(SPM, iC, iCForRatio, doInvert, doSaveNewContrasts)
% Computes temporal SNR image after correcting for a contrast
% from SPM general linear model
%
%   tSnrImage = compute_tsnr_spm(input)
%
%   This function executes the following steps:
%   1.  Compute F-Contrasts of the kind "All-but-selected regressors"
%      	run spm_write_residuals to retrieve Y-Yc = Y0 + e
%       (note that roles of Y0 and Yc are swapped compared to in spm_spm,
%       since we are interested in Residuals that do *not* stem from our
%       regressors, but the other ones!
%   2.  Compute tSNR images using mean(Residuals)/std(Residuals) from
%       F-contrasts from (1.), save as nii-files tsnr_con<iC>.nii
%   3.  Compute tSNR for contrast of comparison, default:
%       preprocessed time-series, after pre-whitening and
%       highpass-filtering (i.e. K*W*Y), saved as nii-files
%       using a recursive call to this function
%   4.  Compute tSNR ratio images from (3.) and (2.), save as nii-files
%       tsnr_con<iC>vs<iCRatio>.nii
%
% IN
%   SPM     SPM variable (in SPM.mat, or file name) after parameter and
%           contrast estimation
%   iC      Contrast of interest for which tSNR is computed
%           iC = 0 computes tSNR of the raw image time series after
%               pre-whitening and filtering, but without any model
%               confound regressors removed. (default)
%           iC = NaN computes tSNR after removing the full model (including
%               the mean), and is therefore equivalent to sqrt(1/ResMS)
%   iCForRatio
%           For computation of relative tSNR.
%           Contrast index whose tSNR image should be used as a
%           denominator for tSnrRatioImage = tSNRiC./tSNRiCForRatio;
%           tSNR is compared to the tSNR image of the specified contrast
%           (0 for raw tSNR). The corresponding tSNR-image will be created
%           default = 0 (raw tSNR); Leave [] to not compute ratio of tSNRs
%   doInvert true (default for iC > 0 and ~nan) or false
%           typically, one is interested in the tSNR *after* correcting for
%           the contrast in question. To compute this, one has to look at
%           the residuals of the inverse F-contrast that excludes all but
%           the contrast of interest, i.e. eye(nRegressors) - xcon
%           Thus, this function computes this contrast per default and goes
%           from there determining residuals etc.
%   doSaveNewContrasts
%           true or false (default)
%           if true, the temporary contrasts created by inversion of
%           selected columns will be saved into the SPM structure.
%           Otherwise, all temporary data will be removed.
%
% OUT
%   tSnrImage   [nX,nY,nZ] image matrix holding tSNR when only including regressors in
%               contrast iC in design matrix;
%               i.e. gives the effect of
%                       mean(Xc*bc + e)/std(Xc*bc + e)
%               if Xc hold only regressors of iC
%
%               NOTE: If you want to estimate the effect of a noise
%               correction using some regressors, the Contrast with index
%               iC should actually contain an F-contrast *EXCLUDING* these
%               regressors, because everything else constitutes the
%               regressors of interest
%   fileTsnr    tsnr_con<iC>.nii
%               path and file name of tSNR image, if doSave was true
%   tSnrRatioImage
%               tSNR_con<iC>./tSNR_con<iCForRatio>
%               (if iCForRatio was specified)
%   fileTsnrRatio
%               tsnr_con<iC>vs<iCRatio>.nii
%               file where tSnrRatio was saved
%
% EXAMPLE
%   compute_tsnr_spm
%
%   See also spm_write_residuals spm_FcUtil

% Author: Lars Kasper
% Created: 2014-12-10
% Copyright (C) 2014 Institute for Biomedical Engineering, ETH/Uni Zurich.

if nargin < 2
    iC = 0;
end

if nargin < 3
    iCForRatio = 0;
end

if nargin < 4
    doInvert = true;
end

if nargin < 5
    doSaveNewContrasts = false;
end

doComputeRatio = ~isempty(iCForRatio);

% load SPM-variable, if filename given
if ~isstruct(SPM)
    % load SPM variable from file
    if iscell(SPM)
        fileSpm = SPM{1};
    else
        fileSpm = SPM;
    end
    load(fileSpm, 'SPM');
end

oldDirSpm = SPM.swd;

if ~doSaveNewContrasts
    % temporary changes to SPM structure saved in sub-dir, removed later
    newDirSpm = fullfile(SPM.swd, 'tmp');
    mkdir(newDirSpm);
    copyfile(fullfile(SPM.swd, '*.nii'), newDirSpm);
    copyfile(fullfile(SPM.swd, 'SPM.mat'), newDirSpm);
    SPM.swd = newDirSpm;
end

iCIn = iC;

isInvertableContrast = iC > 0 && ~isnan(iC);

if isInvertableContrast && doInvert
    if ~isequal(SPM.xCon(iC).STAT, 'F')
        error('Can only invert F-contrasts');
    end

    idxColumnsContrast = find(sum(SPM.xCon(iC).c));

    Fc = spm_FcUtil('Set', ['All but: ' SPM.xCon(iC).name], 'F', ...
        'iX0', idxColumnsContrast, SPM.xX.xKXs);
    SPM.xCon(end+1) = Fc;
    SPM = spm_contrasts(SPM,numel(SPM.xCon));

    % use this for computation
    iC = numel(SPM.xCon);
end

%% Write residuals Y - Y0 = Yc + e;
VRes        = spm_write_residuals(SPM, iC);
nVolumes    = numel(VRes);
for iVol = 1:nVolumes
    VRes(iVol).fname = fullfile(SPM.swd, VRes(iVol).fname);
end

fileTsnr = fullfile(oldDirSpm, sprintf('tSNR_con%04d.nii', iCIn));

useMrImage = false;

if useMrImage % use toolbox functionality
    ResImage    = MrImage(VRes(1).fname);

    % Create 4D image of contrast-specific "residuals", i.e. Xc*bc + e
    for iVol = 1:nVolumes
        ResImage.append(VRes(iVol).fname);
    end

    % compute tSNR = mean(Xc*bc + e)/std(Xc*bc + e)
    tSnrImage = ResImage.mean./ResImage.std;
    if doSaveNewContrasts
        tSnrImage.save(fileTsnr);
    end
else
    ResImage = spm_read_vols(VRes);
    meanImage = mean(ResImage, 4);
    stdImage = std(ResImage, 0, 4);
    tSnrImage = meanImage./stdImage;
    VTsnr = VRes(1);
    VTsnr.fname = fileTsnr;
    spm_write_vol(VTsnr, tSnrImage);
end

%%
if doComputeRatio
    fileTsnrCompare = fullfile(oldDirSpm, sprintf('tSNR_con%04d.nii', iCForRatio));

    % Load or compute tSNR image for comparison contrast
    if ~exist(fileTsnrCompare, 'file');
        % when computed, don't compute another ratio, and don't delete tmp
        % here! (will be done at the end)
        tSnrCompareImage = tapas_physio_compute_tsnr_spm(...
            fullfile(oldDirSpm, 'SPM.mat'), ...
            iCForRatio, doInvert, [], 1);
    else
        VCompare = spm_vol(fileTsnrCompare);
        tSnrCompareImage = spm_read_vols(VCompare);
    end

    % compute tSNR ratio and save
    tSnrRatioImage = tSnrImage./tSnrCompareImage;

    fileTsnrRatio = fullfile(oldDirSpm, ...
        sprintf('tSNRRatio_con%04dvs%04d.nii', iCIn, iCForRatio));
    VRatio = spm_vol(fileTsnrCompare);
    VRatio.fname = fileTsnrRatio;
    spm_write_vol(VRatio, tSnrRatioImage);
else
    tSnrRatioImage = [];
    fileTsnrRatio = [];
end

%% clean up all created residual files and temporary SPM folder
if ~doSaveNewContrasts
    delete(fullfile(newDirSpm, '*'));
    rmdir(newDirSpm);
else
    % delete at least the Res-images
    delete(fullfile(oldDirSpm, 'Res_*.nii'));
end

author: translationalneuromodeling

repo: tapas


text:
function value = p18_r8vec ( action, name, dim_num, value )

%*****************************************************************************80
%
%% P18_R8VEC sets or gets R8VEC parameters for problem 18.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string ACTION, the action.
%    'D' sets the internal value of the object to a default value.
%    If NAME = '*', then all variables are defaulted.
%    'G' means the current value of the object should be returned.
%    'R' means randomize the object and return it.
%    'S' means the input values of the object and its dimension should
%      be stored.
%
%    Input, string NAME, the name of the parameter.
%    'Z' is the base vector.
%
%    Input, integer DIM_NUM, the dimension of the object.
%
%    Input/output, real VALUE(DIM_NUM), the value of the object.
%
  persistent dim_num_save
  persistent z

  if ( size ( dim_num_save ) == 0 )
    dim_num_save = 0;
  end

  if ( dim_num_save ~= dim_num )
    dim_num_save = 0;
    z = [];
  end

  if ( dim_num_save == 0 )
    dim_num_save = dim_num;
  end

  if ( action == 'D' | action == 'd' )

    if ( name == 'Z' | name == 'z' | name == '*' )
      z(1:dim_num) = 0.5;
    end

  elseif ( action == 'G' | action == 'g' )

    if ( name == 'Z' | name == 'z' )
      value(1:dim_num) = z(1:dim_num);
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P18_R8VEC - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P18_R8VEC - Fatal error!' );
    end

  elseif ( action == 'R' | action == 'r' )

    if ( name == 'Z' | name == 'z' )
      z = rand ( 1, dim_num );
      value(1:dim_num) = z(1:dim_num);
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P18_R8VEC - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P18_R8VEC - Fatal error!' );
    end

  elseif ( action == 'S' | action == 's' )

    if ( name == 'Z' | name == 'z' )
      z(1:dim_num) = value(1:dim_num);
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P18_R8VEC - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P18_R8VEC - Fatal error!' );
    end

  else

    fprintf ( 1, '\n' );
    fprintf ( 1, 'P18_R8VEC - Fatal error!\n' );
    fprintf ( 1, '  Unrecognized action = "%s".\n', action );
    error ( 'P18_R8VEC - Fatal error!' );

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
filename='Throne_Tetrahedra_SYM';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance'};
weights = [1];
constraint = {'volume'};
optimizer = 'SLERP'; incrementFactor = 1;
filterType = 'P1';
constraint_case = 'INEQUALITY';
line_search_initiator = 'INCREASING LAST STEP';

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

printing = false;

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

% plotting = true;
% showBC = true;

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan