text:
function obj = updateSpiderPlot(obj,spiderIndex)

    %-------------------------------------------------------------------------%

    %-INITIALIZATIONS-%
    axIndex = obj.getAxisIndex(obj.State.Plot(spiderIndex).AssociatedAxis);
    plotData = obj.State.Plot(spiderIndex).Handle;
    [xSource, ySource] = findSourceAxis(obj, axIndex);

    nTraces = size(plotData.P, 1);
    isLegend = false;

    axesStruct = setAxes(obj, spiderIndex);
    updateSpiderLayout(obj, spiderIndex);
    setAnnotation(obj, axesStruct, spiderIndex);

    if ~isempty(plotData.LegendHandle)
        isLegend = true;
        setLegeng(obj, spiderIndex);
    end

    %-------------------------------------------------------------------------%

    %-set traces-%
    for t = 1:nTraces

        %-get plotIndex-%
        obj.PlotOptions.nPlots = obj.PlotOptions.nPlots + 1;
        plotIndex = obj.PlotOptions.nPlots;

        %-associate axis-%
        obj.data{plotIndex}.xaxis = sprintf('x%d', xSource);
        obj.data{plotIndex}.yaxis = sprintf('y%d', ySource);

        %-trace settings-%
        obj.data{plotIndex}.type = 'scatter';
        obj.data{plotIndex}.mode = 'lines+markers';

        if strcmp(plotData.Marker{t, 1}, 'none')
            obj.data{plotIndex}.mode = 'lines';
        end

        %-set data-%
        [xData, yData] = getCartesianPoints(plotData, axesStruct, t);

        obj.data{plotIndex}.x = xData;
        obj.data{plotIndex}.y = yData;

        %-marker settings-%
        obj.data{plotIndex}.marker = getMarker(plotData, t);

        %-line settings-%
        obj.data{plotIndex}.line = getLine(plotData, t);

        %-fill area-%
        if strcmp(plotData.FillOption{t}, 'on')
            [fillColor, ~] = getColor(plotData.Color, t, ...
                plotData.FillTransparency);
            obj.data{plotIndex}.fillcolor = fillColor;
            obj.data{plotIndex}.fill = 'toself';
        end

        %-legend-%
        if isLegend
            if strcmp(plotData.LegendHandle.Visible, 'on')
                obj.data{plotIndex}.name = plotData.LegendLabels{t};
                obj.data{plotIndex}.showlegend = true;
            end
        end

    end

    %-------------------------------------------------------------------------%
end

function [xData, yData] = getCartesianPoints(plotData, axesStruct, traceIndex)

    %-initializations-%
    rData = plotData.P(traceIndex, :);
    axesAngle = axesStruct.axesAngle;
    nAxes = axesStruct.nAxes;
    nTicks = axesStruct.nTicks;

    for a = 1:nAxes

        %-get axis limits-%
        try
            axesLim = plotData.AxesLimits(:, a)';
        catch
            axesLim = [min(plotData.P(:, a)), max(plotData.P(:, a))];
        end

        %-normalize radial data-%
        rPoint = [rData(a), axesLim];
        if strcmpi(plotData.AxesScaling(a), 'log')
            rPoint = log10(rPoint);
        end
        if strcmpi(plotData.AxesDirection(a), 'reverse');
            rPoint = -rPoint;
        end
        rPoint = rescale(rPoint, 1/nTicks, 1);

        %-convertion-%
        xData(a) = rPoint(1) * cos(axesAngle(a));
        yData(a) = rPoint(1) * sin(axesAngle(a));
    end

    %-return-%
    xData = [xData, xData(1)];
    yData = [yData, yData(1)];
end

function lineStruct = getLine(plotData, traceIndex)
    %-INITIALIZATIONS-%
    lineStruct = struct();

    %-line color-%
    [lineColor, ~] = getColor(plotData.Color, traceIndex, ...
        plotData.LineTransparency);
    lineStruct.color = lineColor;

    %-line width-%
    lineStruct.width = plotData.LineWidth(traceIndex);

    %-line style-%
    switch plotData.LineStyle{traceIndex, 1}
        case '-'
            lineStyle = 'solid';
        case '--'
            lineStyle = 'dash';
        case ':'
            lineStyle = 'dot';
        case '-.'
            lineStyle = 'dashdot';
    end

    lineStruct.dash = lineStyle;
end

function markerStruct = getMarker(plotData, traceIndex)

    %-INITIALIZATIONS-%
    markerStruct = struct();

    %-marker color-%
    [markerColor, ~] = getColor(plotData.Color, traceIndex, ...
        plotData.MarkerTransparency);
    markerStruct.color = markerColor;
    markerStruct.line.color = markerColor;

    %-marker size-%
    markerStruct.size = plotData.MarkerSize(traceIndex, 1) * 0.2;

    %-marker symbol-%
    if ~strcmp(plotData.Marker{traceIndex, 1}, 'none')

        switch plotData.Marker{traceIndex, 1}
            case '.'
                mSymbol = 'circle';
            case 'o'
                mSymbol = 'circle';
            case 'x'
                mSymbol = 'x-thin-open';
            case '+'
                mSymbol = 'cross-thin-open';
            case '*'
                mSymbol = 'asterisk-open';
            case {'s','square'}
                mSymbol = 'square';
            case {'d','diamond'}
                mSymbol = 'diamond';
            case 'v'
                mSymbol = 'triangle-down';
            case '^'
                mSymbol = 'triangle-up';
            case '<'
                mSymbol = 'triangle-left';
            case '>'
                mSymbol = 'triangle-right';
            case {'p','pentagram'}
                mSymbol = 'star';
            case {'h','hexagram'}
                mSymbol = 'hexagram';
        end

        markerStruct.symbol = mSymbol;
    end
end

function setAnnotation(obj, axesStruct, spiderIndex)

    %-------------------------------------------------------------------------%

    %-INITIALIZATIONS-%
    axIndex = obj.getAxisIndex(obj.State.Plot(spiderIndex).AssociatedAxis);
    anIndex = obj.PlotlyDefaults.anIndex;

    plotData = obj.State.Plot(spiderIndex).Handle;
    [xSource, ySource] = findSourceAxis(obj, axIndex);

    axesLabels = plotData.AxesLabels;
    axesLabelsOffset = plotData.AxesLabelsOffset * 0.5;
    axesDisplay = plotData.AxesDisplay;
    axesLim = plotData.AxesLimits;
    axesFontColor = plotData.AxesFontColor;
    axesPrecision = plotData.AxesPrecision;
    axesLabelsEdge = plotData.AxesLabelsEdge;

    nAxes = axesStruct.nAxes;
    axesAngle = axesStruct.axesAngle;
    tickValues = axesStruct.axesAngle;
    nTicks = axesStruct.nTicks;
    if strcmp(axesDisplay, 'data'), nTicks = size(plotData.P, 1); end

    labelColor = 'rgb(0,0,0)';
    labelSize = plotData.LabelFontSize;
    labelFamily = matlab2plotlyfont(plotData.LabelFont);

    nAxesFontColor = size(axesFontColor, 1);
    axesSize = plotData.AxesFontSize;
    axesFamily = matlab2plotlyfont(plotData.AxesFont);

    %-------------------------------------------------------------------------%

    %-set axes labels-%
    for l = 1:nAxes

        %-create annotation-%
        annotations{anIndex}.showarrow = false;
        annotations{anIndex}.xref = sprintf('x%d', xSource);
        annotations{anIndex}.yref = sprintf('y%d', ySource);
        annotations{anIndex}.bgcolor = 'rgba(0,0,0,0)';
        annotations{anIndex}.bordercolor = getLabelEdgeColor(axesLabelsEdge);
        annotations{anIndex}.borderwidth = 1;
        annotations{anIndex}.borderpad = labelSize * 0.5;

        %-text label-%
        textLabel = axesLabels{l};
        if isempty(textLabel), textLabel = parseString(textLabel, 'tex'); end

        annotations{anIndex}.text = textLabel;

        %-location-%
        lastXTick = cos(axesAngle(l));
        lastYTick = sin(axesAngle(l));

        if abs(lastXTick) < 1e-3
            annotations{anIndex}.x = lastXTick;
            annotations{anIndex}.xanchor = 'middle';
        elseif lastXTick > 0
            annotations{anIndex}.x = lastXTick + axesLabelsOffset;
            annotations{anIndex}.xanchor = 'left';
        elseif lastXTick < 0
            annotations{anIndex}.x = lastXTick - axesLabelsOffset;
            annotations{anIndex}.xanchor = 'right';
        end

        if abs(lastYTick) < 1e-3
            annotations{anIndex}.y = lastYTick;
            annotations{anIndex}.yanchor = 'middle';
        elseif lastYTick > 0
            annotations{anIndex}.y = lastYTick + axesLabelsOffset;
            annotations{anIndex}.yanchor = 'bottom';
        elseif lastYTick < 0
            annotations{anIndex}.y = lastYTick - axesLabelsOffset;
            annotations{anIndex}.yanchor = 'top';
        end

        %-font properties-%
        annotations{anIndex}.font.color = labelColor;
        annotations{anIndex}.font.size = labelSize;
        annotations{anIndex}.font.family = labelFamily;

        %-update annotation Index-%
        anIndex = anIndex + 1;
    end

    %-------------------------------------------------------------------------%

    %-set axes tick labels-%
    for t = 1:nTicks

        indexColor = mod(t-1, nAxesFontColor) + 1;
        axesColor = 255*axesFontColor(indexColor, :);
        axesColor = sprintf('rgb(%f,%f,%f)', axesColor);

        for a = 1:nAxes

            %-create annotation-%
            annotations{anIndex}.showarrow = false;
            annotations{anIndex}.xref = sprintf('x%d', xSource);
            annotations{anIndex}.yref = sprintf('y%d', ySource);
            annotations{anIndex}.bgcolor = 'rgba(0,0,0,0)';
            annotations{anIndex}.bordercolor = 'rgba(0,0,0,0)';

            %-get tick label-%
            try
                axesLim = plotData.AxesLimits(:, a)';
            catch
                axesLim = [min(plotData.P(:, a)), max(plotData.P(:, a))];
            end

            if strcmp(axesDisplay, 'data')
                tickLabel = plotData.P(t, a);

            else
                tickLabel = linspace(axesLim(1), axesLim(2), nTicks);
                tickLabel = tickLabel(t);

                if strcmpi(plotData.AxesScaling(a), 'log')
                    tickLabel = 10^(t-1);
                end
            end

            %-get tick value-%
            tickValue = [tickLabel, axesLim];

            if strcmpi(plotData.AxesScaling(a), 'log')
                tickValue = log10(tickValue);
            end

            if strcmpi(plotData.AxesDirection(a), 'reverse');
                tickValue = -1 * tickValue;
            end

            tickValue = rescale(tickValue, 1/axesStruct.nTicks, 1);
            tickValue = tickValue(1);

            %-set tick label-%
            tickLabel = num2str(tickLabel, sprintf('%%.%df', axesPrecision(a)));
            annotations{anIndex}.text = tickLabel;

            %-set tick location-%
            annotations{anIndex}.x = tickValue * cos(axesAngle(a));
            annotations{anIndex}.y = tickValue * sin(axesAngle(a));
            annotations{anIndex}.xanchor = plotData.AxesHorzAlign;
            annotations{anIndex}.yanchor = plotData.AxesVertAlign;
            annotations{anIndex}.align = plotData.AxesHorzAlign;

            if strcmp(axesDisplay, 'data')
                if annotations{anIndex}.y > 0
                    annotations{anIndex}.yanchor = 'bottom';
                elseif annotations{anIndex}.y < 0
                    annotations{anIndex}.yanchor = 'top';
                end

                if abs(annotations{anIndex}.x) < 1e-3
                    annotations{anIndex}.xanchor = 'middle';
                elseif annotations{anIndex}.x > 0
                    annotations{anIndex}.xanchor = 'left';
                elseif annotations{anIndex}.x < 0
                    annotations{anIndex}.xanchor = 'right';
                end
            end

            %-font properties-%
            annotations{anIndex}.font.color = axesColor;
            annotations{anIndex}.font.size = axesSize;
            annotations{anIndex}.font.family = axesFamily;

            %-update annotation Index-%
            anIndex = anIndex + 1;

            %-stop according AxesDisplay-%
            if strcmp(axesDisplay, 'one')
                if a==1, break; end
            elseif strcmp(axesDisplay, 'two')
                if a==2, break; end
            elseif strcmp(axesDisplay, 'three')
                if a==3, break; end
            end
        end

    end

    %-------------------------------------------------------------------------%

    %-set annotations to layout-%
    obj.layout = setfield(obj.layout, 'annotations', annotations);

    %-------------------------------------------------------------------------%

    obj.PlotlyDefaults.anIndex = anIndex;

    %-------------------------------------------------------------------------%
end

function axesStruct = setAxes(obj, spiderIndex)

    %-------------------------------------------------------------------------%

    %-INITIALIZATIONS-%
    axIndex = obj.getAxisIndex(obj.State.Plot(spiderIndex).AssociatedAxis);
    plotData = obj.State.Plot(spiderIndex).Handle;
    [xSource, ySource] = findSourceAxis(obj, axIndex);

    %-------------------------------------------------------------------------%

    %-set axes-%
    nAxes = size(plotData.P,2);
    angleStep = 2*pi/nAxes;
    axesAngle = [pi/2];
    plotIndex = spiderIndex;
    axesColor = sprintf('rgb(%f,%f,%f)', 255*plotData.AxesColor);

    for a = 1:nAxes

        %-get plotIndex-%
        if a > 1
            obj.PlotOptions.nPlots = obj.PlotOptions.nPlots + 1;
            plotIndex = obj.PlotOptions.nPlots;
        end

        %-set axes-%
        obj.data{plotIndex}.xaxis = sprintf('x%d', xSource);
        obj.data{plotIndex}.yaxis = sprintf('y%d', ySource);

        obj.data{plotIndex}.type = 'scatter';
        obj.data{plotIndex}.mode = 'lines';
        obj.data{plotIndex}.line.color = axesColor;
        obj.data{plotIndex}.line.width = 1.75;

        obj.data{plotIndex}.x = [0, cos(axesAngle(a))];
        obj.data{plotIndex}.y = [0, sin(axesAngle(a))];

        %-update axesAngle list-%
        if a ~= nAxes
            if strcmp(plotData.Direction, 'clockwise')
                axesAngle(a+1) = axesAngle(a) - angleStep;
            else
                axesAngle(a+1) = axesAngle(a) + angleStep;
            end
        end

        %-hide associated trace-%
        obj.data{plotIndex}.showlegend = false;

    end

    %-------------------------------------------------------------------------%

    %-set grid-%
    nTicks = plotData.AxesInterval + 1;
    tickValues = linspace(1/nTicks, 1, nTicks);
    xData = cos([axesAngle, axesAngle(1)]);
    yData = sin([axesAngle, axesAngle(1)]);

    for g = 1:nTicks

        %-get plotIndex-%
        obj.PlotOptions.nPlots = obj.PlotOptions.nPlots + 1;
        plotIndex = obj.PlotOptions.nPlots;

        %-set current line grid-%
        obj.data{plotIndex}.xaxis = sprintf('x%d', xSource);
        obj.data{plotIndex}.yaxis = sprintf('y%d', ySource);

        obj.data{plotIndex}.type = 'scatter';
        obj.data{plotIndex}.mode = 'lines';
        obj.data{plotIndex}.line.color = axesColor;
        obj.data{plotIndex}.line.width = 0.4;

        obj.data{plotIndex}.x = tickValues(g)*xData;
        obj.data{plotIndex}.y = tickValues(g)*yData;

        %-hide associated trace-%
        obj.data{plotIndex}.showlegend = false;

    end

    %-------------------------------------------------------------------------%

    %-return-%
    axesStruct.axesAngle = axesAngle;
    axesStruct.nAxes = nAxes;
    axesStruct.nTicks = nTicks;
    axesStruct.tickValues = tickValues;

    %-------------------------------------------------------------------------%
end

function updateSpiderLayout(obj, spiderIndex)

    %-------------------------------------------------------------------------%

    %-INITIALIZATIONS-%
    axIndex = obj.getAxisIndex(obj.State.Plot(spiderIndex).AssociatedAxis);
    plotData = obj.State.Plot(spiderIndex).Handle;
    [xSource, ySource] = findSourceAxis(obj, axIndex);

    xo = plotData.Position(1);
    yo = plotData.Position(2);
    w = plotData.Position(3);
    h = plotData.Position(4);

    %-------------------------------------------------------------------------%

    %-get x axis-%
    xaxis.domain = min([xo xo + w],1);
    xaxis.range = [-1.5, 1.5];
    xaxis.showline = false;
    xaxis.zeroline = false;
    xaxis.showgrid = false;
    xaxis.showticklabels = false;

    %-------------------------------------------------------------------------%

    %-get y axis-%
    yaxis.domain = min([yo yo + h],1);
    yaxis.range = [-1.25, 1.25];
    yaxis.showline = false;
    yaxis.zeroline = false;
    yaxis.showgrid = false;
    yaxis.showticklabels = false;

    %-------------------------------------------------------------------------%

    %-set axis-%
    obj.layout = setfield(obj.layout, sprintf('xaxis%d', xSource), xaxis);
    obj.layout = setfield(obj.layout, sprintf('yaxis%d', ySource), yaxis);

    %-------------------------------------------------------------------------%
end

function setLegeng(obj, spiderIndex)

    %-------------------------------------------------------------------------%

    %-INITIALIZATIONS-%
    axIndex = obj.getAxisIndex(obj.State.Plot(spiderIndex).AssociatedAxis);
    plotData = obj.State.Plot(spiderIndex).Handle;
    [xSource, ySource] = findSourceAxis(obj, axIndex);

    legData = plotData.LegendHandle;
    obj.layout.showlegend = strcmpi(plotData.Visible,'on');

    %-------------------------------------------------------------------------%

    %-legend location-%
    obj.layout.legend.x = legData.Position(1);
    obj.layout.legend.y = legData.Position(2);
    obj.layout.legend.xref = 'paper';
    obj.layout.legend.yref = 'paper';
    obj.layout.legend.xanchor = 'left';
    obj.layout.legend.yanchor = 'top';

    %-------------------------------------------------------------------------%

    %-legend settings-%
    if (strcmp(legData.Box,'on') && strcmp(legData.Visible, 'on'))
        edgeColor = 255*legData.EdgeColor;
        bgColor = 255*legData.Color;
        textColor = 255*legData.TextColor;

        obj.layout.legend.traceorder = 'normal';
        obj.layout.legend.borderwidth = legData.LineWidth;
        obj.layout.legend.bordercolor = sprintf('rgb(%f,%f,%f)', edgeColor);
        obj.layout.legend.bgcolor = sprintf('rgb(%f,%f,%f)', bgColor);
        obj.layout.legend.font.size = legData.FontSize;
        obj.layout.legend.font.family = matlab2plotlyfont(legData.FontName);
        obj.layout.legend.font.color = sprintf('rgb(%f,%f,%f)', textColor);
    end
end

function [strColor, numColor] = getColor(colorMatrix, traceIndex, ...
    colorOpacities)

    colorOpacity = 1;

    if nargin > 2
        colorOpacity = colorOpacities(traceIndex);
    end

    nColors = size(colorMatrix, 1);
    colorIndex = mod(traceIndex-1, nColors) + 1;
    numColor = 255*colorMatrix(colorIndex, :);
    strColor = sprintf('rgba(%f,%f,%f,%f)', numColor, colorOpacity);
end

function edgeColor = getLabelEdgeColor(axesLabelsEdge)
    if isnumeric(axesLabelsEdge)
        edgeColor = sprintf('rgb', 255*axesLabelsEdge);

    elseif strcmp(axesLabelsEdge, 'none')
        edgeColor = 'rgba(0,0,0,0)';

    else
        switch axesLabelsEdge
            case {'b', 'blue'}
                edgeColor = 'rgb(0,0,1)';
            case {'k', 'black'}
                edgeColor = 'rgb(0,0,0)';
            case {'r', 'red'}
                edgeColor = 'rgb(1,0,0)';
            case {'g', 'green'}
                edgeColor = 'rgb(0,1,0)';
            case {'y', 'yellow'}
                edgeColor = 'rgb(1,1,0)';
            case {'c', 'cyan'}
                edgeColor = 'rgb(0,1,1)';
            case {'m', 'magenta'}
                edgeColor = 'rgb(1,0,1)';
            case {'w', 'white'}
                edgeColor = 'rgb(1,1,1)';
        end
    end
end

author: plotly


text:
function p3 = min(p1)
%PREAL/MIN Overloaded MIN function for class preal.
% Note: Unlike datafun/min preal/min returns the smallest single
% element of the array, resulting in one scalar.

global useUnitsFlag

if ~(useUnitsFlag) % If physunits is disabled...
    p3=max(double(p1)); % ... treat as double.
    return
end

p1=preal(p1);
p3=p1(1);
for k=2:numel(p1)
    if p1(k)<p3
        p3=p1(k);
    end
end

author: Sable

repo: mcbench-benchmarks


text:
% =========================================================================
%                 TCDCN face alignment tool (68 points)
% =========================================================================
% The provided tool is a re-implementation of the papers:
%
% [1] Zhanpeng Zhang, Ping Luo, Chen Change Loy, Xiaoou Tang. Facial Landmark Detection
%     by Deep Multi-task Learning, in Proceedings of European Conference on Computer Vision (ECCV), 2014
%
% [2] Zhanpeng Zhang, Ping Luo, Chen Change Loy, Xiaoou Tang. Learning Deep Representation for Face Alignment
%     with Auxiliary Attributes. Technical report, arXiv:1408.3967v2, 2014.
% =========================================================================
% Prerequisites:
% 1. Piotr's Computer Vision Matlab Toolbox (http://vision.ucsd.edu/~pdollar/toolbox/doc/index.html,
%                                            https://github.com/pdollar/toolbox)
%
%Usuage:
%
% IN:
% - "listFileName " is a file that contains the images to be tested.
% OUT:
% - "outputFileName" a file that will be generated by this tool and records the computed facial landmark locations.
% =========================================================================
% Format:
%
% Format of the listfile:
% Each of  line contains the image path, followed by the left, top, width and height of the face bounding boxe.
% (see the example file "list.txt" in the package and "boundingbox.jpg" illusrates how large the bounding box should be.)
%
% Format of the outputFile:
% Each line contrains input image path followed by the 68 facial landmark locations (x1,y1,x2,y2....x68,y68).
% To view the format of the output file, see visualize.m.
% Notice
% 1) This demo has been tested on Windows 7 64 bit, Matlab 2013a.
%
% *More details of our implementation, please feel free to drop me an email, zhzhanp@gmail.com.
% =========================================================================

clear; clc;
addpath('./TCDCN/');

%% paramter setup
listFileName = 'list.txt';
modelFile = 'model.mat';
outputFileName = 'output.txt';

%% run
main(listFileName,modelFile,outputFileName)

author: zhzhanp

repo: TCDCN-face-alignment


text:
function [ n_data, n, c ] = mertens_values ( n_data )

%*****************************************************************************80
%
%% MERTENS_VALUES returns some values of the Mertens function.
%
%  Discussion:
%
%    The Mertens function M(N) is the sum from 1 to N of the Moebius
%    function MU.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    M Deleglise, J Rivat,
%    Computing the Summation of the Moebius Function,
%    Experimental Mathematics,
%    Volume 5, 1996, pages 291-295.
%
%    Eric Weisstein,
%    CRC Concise Encyclopedia of Mathematics,
%    CRC Press, 2002,
%    Second edition,
%    ISBN: 1584883472,
%    LC: QA5.W45.
%
%  Parameters:
%
%    Input, integer N_DATA, indicates the index of the previous test data
%    returned, or is 0 if this is the first call.  For repeated calls,
%    set the input value of N_DATA to the output value of N_DATA
%    from the previous call.
%
%    Output, integer N_DATA, the index of the test data.
%
%    Output, integer N, the argument of the Mertens function.
%
%    Output, integer C, the value of the Mertens function.
%
  n_max = 15;
  c_vec = [ ...
      1,   0,  -1,   -1,  -2,  -1,  -2,  -2,   -2,  -1, ...
     -2,  -2,   1,    2, -23 ];
  n_vec = [ ...
      1,   2,   3,   4,   5,   6,   7,   8,   9,  10, ...
     11,  12,  100, 1000, 10000 ];

  if ( n_data < 0 )
    n_data = 0;
  end

  n_data = n_data + 1;

  if ( n_max < n_data )
    n_data = 0;
    n = 0;
    c = 0;
  else
    n = n_vec(n_data);
    c = c_vec(n_data);
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
classdef VigdergauzParametersFromVolumeAndPhi < handle

    properties (Access = public)
        parameters
    end

    properties (Access = private)
        cx
        cy
        phi
        volume
        ax
        ay
    end

    methods (Access = public)

        function obj = VigdergauzParametersFromVolumeAndPhi(cParams)
            obj.init(cParams);
            obj.checkValidityOfParameters();
        end

        function compute(obj)
            r = obj.computeOptimalR();
            obj.computeAxAy(r)
            obj.computeVigergauzParameters();
        end

    end

    methods (Access = private)

        function init(obj,cParams)
            obj.volume = cParams.volumeMicro;
            obj.phi    = atan(cParams.superEllipseRatio);
            obj.cx     = cParams.cx;
            obj.cy     = cParams.cy;
        end

        function computeAxAy(obj,r)
            s.r = r;
            s.volume = obj.volume;
            s.cx = obj.cx;
            s.cy = obj.cy;
            axay = AxAyComputerFromVolumeAndR(s);
            [obj.ax,obj.ay] = axay.compute();
        end

        function r = computeOptimalR(obj)
            s.x0 = 1;
            s.functionToSolve = @(r) obj.equationForR(r);
            solver = ImplicitEquationSolver(s);
            r = solver.solve();
        end

        function f = equationForR(obj,r)
            obj.computeAxAy(r);
            obj.computeVigergauzParameters();
            mx = obj.parameters.mx;
            my = obj.parameters.my;
            f = tan(obj.phi) - mx/my;
        end

        function computeVigergauzParameters(obj)
            s.ax = obj.ax;
            s.ay = obj.ay;
            s.cx = obj.cx;
            s.cy = obj.cy;
            s.type = 'AxAndAy';
            obj.parameters = VigdergauzParameters.create(s);
        end

        function checkValidityOfParameters(obj)
            if ~obj.isMicroStructureValid()
                error('Not possible axisRatio with this volume')
            end
        end

        function itIs = isMicroStructureValid(obj)
            mMax = 0.99;
            phiMin = atan((1 - obj.volume)/(mMax^2));
            phiMax = atan((mMax^2)/(1 - obj.volume));
            itIs = obj.phi <= phiMax && obj.phi >= phiMin;
        end

    end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function prob_test120 ( )

%*****************************************************************************80
%
%% TEST120 tests PARETO_MEAN, PARETO_SAMPLE, PARETO_VARIANCE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  nsample = 1000;
  seed = 123456789;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST120\n' );
  fprintf ( 1, '  For the Pareto PDF:\n' );
  fprintf ( 1, '  PARETO_MEAN computes the mean;\n' );
  fprintf ( 1, '  PARETO_SAMPLE samples;\n' );
  fprintf ( 1, '  PARETO_VARIANCE computes the variance.\n' );

  a = 2.0;
  b = 3.0;

  check = pareto_check ( a, b );

  if ( ~check );
    fprintf ( 1, '\n' );
    fprintf ( 1, 'TEST120 - Fatal error!\n' );
    fprintf ( 1, '  The parameters are not legal.\n' );
    return
  end

  mean = pareto_mean ( a, b );
  variance = pareto_variance ( a, b );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  PDF parameter A =             %14f\n', a );
  fprintf ( 1, '  PDF parameter B =             %14f\n', b );
  fprintf ( 1, '  PDF mean =                    %14f\n', mean );
  fprintf ( 1, '  PDF variance =                %14f\n', variance );

  for i = 1 : nsample
    [ x(i), seed ] = pareto_sample ( a, b, seed );
  end

  mean = r8vec_mean ( nsample, x );
  variance = r8vec_variance ( nsample, x );
  xmax = max ( x(1:nsample) );
  xmin = min ( x(1:nsample) );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Sample size =     %6d\n', nsample );
  fprintf ( 1, '  Sample mean =     %14f\n', mean );
  fprintf ( 1, '  Sample variance = %14f\n', variance );
  fprintf ( 1, '  Sample maximum =  %14f\n', xmax );
  fprintf ( 1, '  Sample minimum =  %14f\n', xmin );

  return
end


text:
%--------------------------------------------------------------------------------------------------------
% The system is created based on the principles described in the following paper
% Jimmy SJ. Ren and Li Xu, "On Vectorization of Deep Convolutional Neural Networks for Vision Tasks",
% The 29th AAAI Conference on Artificial Intelligence (AAAI-15). Austin, Texas, USA, January 25-30, 2015
% email: jimmy.sj.ren@gmail.com
%--------------------------------------------------------------------------------------------------------
addpath applications/
addpath utils/
addpath cuda/
addpath mem/
addpath layers/
addpath layers_adapters/
addpath pipeline/
addpath data/MNIST/

clearvars -global config;
clearvars -global mem;

global config;
denoise_configure();
init(0);

% for gradient checking
img = im2double(imread('sample1.png'));
startpt = 150;
image = config.NEW_MEM((img(startpt:startpt+config.input_size(1)-1, startpt:startpt+config.input_size(2)-1, :)));
label = config.NEW_MEM((image(1:config.output_size(1), 1:config.output_size(2), :)));

image = repmat(image, 1,1,1,config.batch_size);
label = repmat(label, 1,1,1,config.batch_size);

% gradient checking
op_train_pipe(image, label);
computeNumericalGradient(image, label, 1);

% speed test
loop = 100;
tic
for m = 1:loop
    op_train_pipe(image, label);
end
elapse = toc/loop/config.batch_size;
num = 1 / elapse;
fprintf('Process %f samples per second.\n', num);

author: jimmy-ren


text:
function h = mgaussianNoisePointPlot(noise, X, y, fontName, fontSize, markerSize, lineWidth)

% MGAUSSIANNOISEPOINTPLOT Plot the data-points for the MGAUSSIAN noise model.
% FORMAT
% DESC plots the data point locations for the multiple output Gaussian
%  noise structure.
% ARG noise : the noise structure which is to be plotted.
% ARG X : input locations to be plotted.
% ARG y : target locations to be plotted.
% ARG fontName : name of any fonts to be used.
% ARG fontSize : size of any fonts to be used.
% ARG markerSize : size of the makers to be used.
% ARG lineWidth : size of any lines to be plotted.
%
% SEEALSO : mgaussianNoiseParamInit, noisePointPlot
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005

% NOISE

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
filename='Cantilever_triangle_fine';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance'};
weights = 1;
constraint = {'volume'};
optimizer = 'SLERP';
incrementFactor = 1;
designVariable = 'LevelSet';
filterType = 'P1';
constraint_case = 'INEQUALITY';
line_search_initiator = 'STANDARD';

nsteps = 15;
Vfrac_final = 0.4;
Perimeter_target = 1;
optimality_final = 1e-3;
constr_final =1e-3;

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


text:
function [M,R] = spm_get_closest_affine(x,y,w1,w2)
% Determine the affine transform mapping x to y
% FORMAT [M,R] = spm_get_closest_affine(X,Y,W1,W2)
% X  - n1*n2*n3*3 array of floats representing coordinates.
% Y  - n1*n2*n3*3 array of floats representing coordinates.
% W1 - n1*n2*n3   array of floats representing weights.
% W2 - n1*n2*n3   array of floats representing weights.
%
% M  - an affine transform
% R  - a rigid-body transform
%
% The code treats X and Y as reshaped versions (n1*n2*n3) x 3,
% and W1 and W2 as column vectors.
%
% It generates XX = [diag(W1)*X W1]'*diag(W2)*[diag(W1)*X W1]
% and          XY = [diag(W1)*X W1]'*diag(W2)*[Y W1]
%
% These can then be used to compute an affine transform (M),
% by M = (XX\XY)'
% A weighted procrustes decomposition is also performed,
% so that a rigid-body transform matrix (R) is returned.
%
% If W1 or W2 are empty or not passed, then they are assumed
% to be all ones.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% John Ashburner
% $Id: spm_get_closest_affine.m 6137 2014-08-19 12:43:11Z john $

XX = zeros(4);
XY = zeros(4);
d  = size(x);
o  = ones(d(1)*d(2),1);
for k=1:size(x,3),
    xk  = reshape(x(:,:,k,:),[d(1)*d(2),3]);
    if (nargin<3 || isempty(w1)) && (nargin<4 || isempty(w2)),
        ox = o;
        oy = o;
    else
        if nargin>=4 && ~isempty(w1) && ~isempty(w2),
            oy = reshape(w2(:,:,k), [d(1)*d(2),1]);
            ox = reshape(w1(:,:,k), [d(1)*d(2),1]).*oy;
        elseif nargin>=3 && ~isempty(w1),
            ox = reshape(w1(:,:,k), [d(1)*d(2),1]);
            oy = ox;
        elseif nargin>=4 && ~isempty(w2),
            ox = reshape(w2(:,:,k), [d(1)*d(2),1]);
        end
        xk(:,1) = xk(:,1).*ox;
        xk(:,2) = xk(:,2).*ox;
        xk(:,3) = xk(:,3).*ox;
    end
    yk  = reshape(y(:,:,k,:),[d(1)*d(2),3]);
    msk = find(all(isfinite(xk),2) & all(isfinite(yk),2));
    X   = [xk(msk,:), ox(msk)];
    Y   = [yk(msk,:), oy(msk)];
    XX  = XX + double(X'*X);
    XY  = XY + double(X'*Y);
end
M = (XX\XY)';

if nargout>1,
    % Procrustes decomposition
    XX1 = XX - XX(:,4)*XX(:,4)'/XX(4,4);
    XY1 = XY - XY(:,4)*XY(4,:) /XY(4,4);
    Z   = (XX1(1:3,1:3)\XY1(1:3,1:3))';
    [U,S,V] = svd(Z);                   % Decompose into rotate, zoom and rotate.
    R   = [U*V' zeros(3,1);0 0 0 1];    % Pure rotation (by taking out the zoom)
    T1  = [eye(4,3) -XY(:,4) /XY(4,4)]; % Initial translation of centre of mass to origin.
    T2  = [eye(4,3) -XY(4,:)'/XY(4,4)]; % Final translation of origin to centre of mass.
    R   = T2 * R * T1;
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
classdef VademecumCalculator < handle

    properties (Access = public)
        cellVariables
    end

    properties (Access = private)
        optimalExponent
        qOptimal
    end

    properties (Access = private)
        rho
        xi
        phi
        nCase
    end

    methods (Access = public)

        function obj = VademecumCalculator(cParams)
            obj.init(cParams)
            obj.createOptimalExponentComputer();
        end

        function compute(obj)
            obj.computeOptimalExponent();
            obj.obtainCellVariables(obj.qOptimal);
        end

        function obtainCellVariables(obj,q)
            cVariables = obj.optimalExponent.obtainCellVariables(q);
            cVariables.rho = obj.rho;
            cVariables.xi = obj.xi;
            cVariables.phi = obj.phi;
            cVariables.q = q;
            obj.cellVariables = cVariables;
        end

    end

    methods (Access = private)

        function init(obj,cParams)
            obj.xi  = cParams.xi;
            obj.rho = cParams.rho;
            obj.phi = cParams.phi;
            obj.nCase = cParams.nCase;
        end

        function createOptimalExponentComputer(obj)
            s.fileName = ['OptimaSuperEllipseCase',obj.nCase];
            s.rho   = obj.rho;
            s.txi   = obj.xi;
            s.phi   = obj.phi;
            s.pNorm = 'max';
            s.hMesh = [];
            optimalExp = OneOptimalExponentComputerAndFunctionVariation(s);
            obj.optimalExponent = optimalExp;
        end

        function q = computeOptimalExponent(obj)
             obj.optimalExponent.computeOptimalExponent();
             qMin = obj.optimalExponent.qOptIter();
             fMin = obj.optimalExponent.fOptIter();
             [~,ind] = min(fMin);
             q = qMin(ind);
             obj.qOptimal = q;
        end

    end

end


text:
function [ scimat_out ] = scimat_tformarray( Sci_HR, new_rotmat, new_size, new_spacing, new_min)
%UNTITLED4 transforms a 3D scimat image using tformarray

% new_rotmat = old_rotmat;
% new_size = old_size;
% new_spacing = old_spacing;
% new_min = old_min;

old_rotmat = Sci_HR.rotmat;

old_spacing_x = Sci_HR.axis(1).spacing;
old_spacing_y = Sci_HR.axis(2).spacing;
old_spacing_z = Sci_HR.axis(3).spacing;
old_spacing = [old_spacing_x, old_spacing_y, old_spacing_z];

old_min_x = Sci_HR.axis(1).min;
old_min_y = Sci_HR.axis(2).min;
old_min_z = Sci_HR.axis(3).min;
old_min = [old_min_x, old_min_y, old_min_z];

%%

% tformarray indexes from 0, not 1
T0 = eye(4);
T0(1:3,4) = -1;

% convert to mm:
S1 = diag([old_spacing([2 1 3]) 1]);

% convert the min field, which is the top left coordinate, into voxel
% centers (offset)
% (y, x, z) -> (x, y, z)
old_offset = old_min([2 1 3]) + old_spacing([2 1 3])/2;

% translate to origin:
T1 = eye(4);
T1(1:3, 4) = old_offset;

% rotate input:
R1 = pinv(old_rotmat);
R1(4,4) = 1;

T_old = T1 * R1 * S1 * T0;

%%
% scale of new image:
S2 = diag([new_spacing([2 1 3]) 1]);

% rotate to new plane:
R2 = pinv(new_rotmat);
R2(4,4) = 1;

% new transalation
new_offset = new_min([2 1 3]) + new_spacing([2 1 3])/2;
T2 = eye(4);
T2(1:3, 4) = new_offset;

T_new = T2 * R2 * S2 * T0;

%%
% this assumes multiplying by the left - TF * [i j k 1]'
TF = pinv(T_new) * T_old;

if max(abs(TF(4, 1:3))) > 1E-10
    disp('Transformation function might be broken, T = ')
    disp(TF)
end
TF(end, :) = [0 0 0 1];

% maketform assumes multiplying from the right, so we need to transpose the
% transformation
T = maketform('affine', TF');
Res = makeresampler('nearest','bound');

% the images are stored permuted as YXZ, reverse this
data = permute(Sci_HR.data, [2 1 3]);

rotated_image = tformarray(data, T, Res, [1 2 3], [1 2 3], new_size([2 1 3]), [], []);

% and re-permute when saving again
scimat_out.data = permute(rotated_image, [2 1 3]);
scimat_out.rotmat = new_rotmat;

for i = 1:3
    scimat_out.axis(i).size = new_size(i);
    scimat_out.axis(i).spacing = new_spacing(i);
    scimat_out.axis(i).min = new_min(i);
end

author: vigente

repo: gerardus

save_path: github-repos/MATLAB/vigente-gerardus


text:
function [nodes, edges, values] = createTestGraph01(varargin)
%CREATETESTGRAPH01  One-line description here, please.
%
%   output = createTestGraph01(input)
%
%   Example
%   createTestGraph01
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2011-05-18,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.

nodes = [ ...
    290 250; ...
    200 300; ...
    100 300; ...
    100 200; ...
    200 200; ...
    240 110; ...
    330 160; ...
    420 200];

edges = [...
    1 2; ...
    1 5; ...
    1 7; ...
    2 3; ...
    2 5; ...
    3 4; ...
    4 5; ...
    5 6; ...
    6 7; ...
    7 8];

values = [80;10; 70; 60; 50; 20; 30; 40];

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function quadrule_test09 ( )

%*****************************************************************************80
%
%% QUADRULE_TEST09 tests HERMITE_SET.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 October 2009
%
%  Author:
%
%    John Burkardt
%
  order_max = 20;

  nfunc = func_set ( 'COUNT', 'DUMMY' );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'QUADRULE_TEST09\n' );
  fprintf ( 1, '  HERMITE_SET sets up Gauss-Hermite quadrature;\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  The integration interval is ( -oo, +oo ).\n' );
  fprintf ( 1, '  The weight function is exp ( - x * x ).\n' );
  fprintf ( 1, '\n' );

  for ilo = 1 : 5 : nfunc

    ihi = min ( ilo + 4, nfunc );

    fprintf ( 1, '\n' );
    fprintf ( 1, '    ' );
    for i = ilo : ihi
      fprintf ( '%14s', fname(i) );
    end
    fprintf ( 1, '\n' );
    fprintf ( 1, '\n' );

    for norder = 1 : order_max

      fprintf ( 1, '  %2d', norder );

      for i = ilo : ihi

        func_set ( 'SET', i );

        [ xtab, weight ] = hermite_set ( norder );

        result = 0.0;
        for j = 1 : norder
          result = result + weight(j) * func ( xtab(j) );
        end

        fprintf ( 1, '  %12f', result );

      end

      fprintf ( 1, '\n' );

    end

  end

  return
end


text:
function [bm,env,delay] = gammatoneFast(x,cfs,fs,align)
%GAMMATONEFAST Produce an array of responses from gammatone filters via FFT
%
%   BM = IOSR.AUDITORY.GAMMATONEFAST(X,CFS,FS) passes the vector X through
%   a bank of fourth-order gammatone filters, with centre frequencies
%   specified by CFS. The function returns a matrix, with each row/column
%   corresponding to a filter output with a centre frequency determined by
%   the corresponding element in CFS. The orientation of the output is
%   determined by the orientation of the input: if X is a row vector then
%   the output will contain one row for each filter output, and vice versa.
%
%   Centre frequencies may be any value below the Nyquist rate (determined
%   by the sampling frequency fs). Typically centre frequencies are equally
%   spaced on the ERB-rate scale and may be calculated thus:
%
%       CFS = iosr.auditory.makeErbCFs(LOW_CF,HIGH_CF,NUMCHANS)
%
%   where LOW_CF is the lowest frequency in the bank, HIGH_CF is the
%   highest, and NUMCHANS is the numbers of filters in the bank.
%
%   BM = IOSR.AUDITORY.GAMMATONEFAST(...,ALIGN) allows phase alignment to
%   be applied. With ALIGN=false, no alignment is applied (default). With
%   ALIGN=true, fine structure and envelope alignment is applied so that
%   the impulse response peaks occurs at t=0.
%
%   [BM,ENV] = IOSR.AUDITORY.GAMMATONEFAST(...) returns the instantaneous
%   envelopes ENV for each filter.
%
%   [BM,ENV,DELAY] = IOSR.AUDITORY.GAMMATONEFAST(...) returns the delay
%   DELAY (in samples) removed by the phase alignment of each gammatone
%   filter, i.e. DELAY(n)=0 if ALIGN=true. DELAY is a vector the same size
%   as CFS.
%
%   Based on code written by ZZ Jin, adapted by DLW in Jan'07 and JF
%   Woodruff in Nov'08
%
%   See also IOSR.AUDITORY.MAKEERBCFS.

%   Copyright 2016 University of Surrey.

    if nargin < 3
        fs = 16000; % default sampling frequency
    end
    if nargin < 4
        align = false; % default phase alignment
    end

    % check inputs
    assert(isvector(x) & isnumeric(x), 'iosr:gammatoneFast:invalidX', 'x must be a vector')
    assert(isvector(cfs) & isnumeric(cfs), 'iosr:gammatoneFast:invalidCfs', 'cfs must be a vector')
    assert(isscalar(fs), 'iosr:gammatoneFast:invalidFs', 'fs must be a scalar')
    assert(islogical(align) & numel(align)==1, 'iosr:gammatoneFast:invalidAlign', 'align must be logical')

    % number of frequency channels
    numchans = length(cfs);

    filterOrder = 4; % filter order
    gL = 2^nextpow2(0.128*fs); % gammatone filter length at least 128 ms
    b = 1.019.*24.7.*(4.37.*cfs./1000+1); % rate of decay or bandwidth

    gt = zeros(gL,numchans);  % Initialise IR
    tc = zeros(size(cfs));  % Initialise time lead
    phase = 0;

    tpt=(2*pi)/fs;
    gain=((1.019.*b.*tpt).^filterOrder)./6; % based on integral of impulse

    tmp_t = (0:gL-1)/fs;

    % calculate impulse response
    for i = 1:numchans
        if align
            tc(i) = (filterOrder-1)./(2*pi*b(i));
            phase = -2*pi*cfs(i)*tc(i);
        end
        gt(:,i) = gain(i)*fs^3*tmp_t.^(filterOrder-1).*exp(-2*pi*b(i)*tmp_t).*cos(2*pi*cfs(i)*tmp_t+phase);
    end

    % if input is row vector, transpose to column vector
    rot = false;
    if size(x,1)==1
        x = x';
        rot = true;
    end

    % gammatone filtering using FFTFILT
    bm = fftfilt(gt,repmat(x,1,numchans));

    % Hilbert envelope
    env = abs(hilbert(bm));

    % delay due to time lead
    delay = round(tc.*fs);

    % remove time lead
    for i = 1:numchans
        bm(:,i) = [bm(delay(i)+1:end,i); zeros(delay(i),1)];
        env(:,i) = [env(delay(i)+1:end,i); zeros(delay(i),1)];
    end

    % transpose output if necessary
    if rot
        bm = bm';
        env = env';
    end

end

author: IoSR-Surrey

repo: MatlabToolbox


text:
% compare EEGLAB distributions

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

function compareeeglabdistrib(folder1, folder2)

fileList1 = getmfilelist(folder1);
fileList2 = getmfilelist(folder2);

% strip list from folders
for iFile = 1:length(fileList1), fileList1{iFile} = fileList1{iFile}(length(folder1)+1:end); end
for iFile = 1:length(fileList2), fileList2{iFile} = fileList2{iFile}(length(folder2)+1:end); end

for iFile1 = 1:length(fileList1)
    iFile2 = strmatch(fileList1{iFile1}, fileList2, 'exact');
    if isempty(iFile2)
        fprintf('Missing file %s in folder %s\n', fileList1{iFile1}, folder2);
    else
        dir1 = dir(fullfile(folder1, fileList1{iFile1}));
        dir2 = dir(fullfile(folder2, fileList2{iFile2}));
        if length(dir1) ~= 1 || length(dir2) ~= 1
            error('Size error');
        end
        if dir1.bytes ~= dir2.bytes
            fprintf('Files %s differ\n', fileList2{iFile2});
            %fprintf('---------------------\n');
            %system([ '/usr/bin/diff ' fullfile(folder1, fileList1{iFile1}) ' ' fullfile(folder2, fileList2{iFile2}) ]);
        end
        fileList2(iFile2) = [];
    end
end

for iFile2 = 1:length(fileList2)
    fprintf('Missing file %s in folder %s\n', fileList2{iFile2}, folder1);
end

author: sccn

repo: eeglab

save_path: github-repos/MATLAB/sccn-eeglab


text:
%% Example
% This script is used to initialize the precise hand guiding functionality on KUKA
% robot remotely

% Mohammad SAFEEA, 22nd of Oct  2017

%% Connecting to server
fprintf('Connecting to server....')

ip='172.31.1.147'; % The IP of the controller
% start a connection with the server
t=net_establishConnection( ip );

if ~exist('t','var') || isempty(t)
  warning('Connection could not be establised, script aborted');
  return;
else

%% Start handguiding functionality
wightOfTool=0; % weight of the mounted tool and tool changer (if any)
COMofTool=[0;
    0;
    0]; % coordinates of center of mass of tool and toolcanger (if any) described in reference frame of flange.
startPreciseHandGuiding( t,wightOfTool,COMofTool );

%% turn off the server
net_turnOffServer( t );

fclose(t);
end

repo: KST-Kuka-Sunrise-Toolbox


text:
% --------------------------------------------------------
% ObjectNet3D
% Copyright (c) 2016 CVGL Stanford University
% Licensed under The MIT License [see LICENSE for details]
% Written by Yu Xiang
% --------------------------------------------------------
function opt = globals()

opt.root = '/datasets/ObjectNet3D';
opt.shapenetcore = '/var/Projects/ShapeNetCore.v1';

author: yuxng


text:
function tetrahedron_keast_rule_test07 ( )

%*****************************************************************************80
%
%% TETRAHEDRON_KEAST_RULE_TEST07 tests KEAST_RULE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 June 2007
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TETRAHEDRON_KEAST_RULE_TEST07\n' );
  fprintf ( 1, '  KEAST_RULE returns the points and weights\n' );
  fprintf ( 1, '  of a Keast rule for the tetrahedron.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  In this test, we simply print a rule.\n' );

  rule = 10;
  degree = keast_degree ( rule );
  order_num = keast_order_num ( rule );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Rule index  = %d\n', rule );
  fprintf ( 1, '  Rule degree = %d\n', degree );
  fprintf ( 1, '  Rule order  = %d\n', order_num );

  [ xyz, w ] = keast_rule ( rule, order_num );

  fprintf ( 1, '\n' );
  fprintf ( 1, '         I      W           X           Y           Z\n' );
  fprintf ( 1, '\n' );
  for order = 1 : order_num
    fprintf ( 1, '  %8d  %10f  %10f  %10f  %10f\n', ...
      order, w(order), xyz(1:3,order) );
  end

  return
end


text:
function test_bug1481

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_componentanalysis ft_rejectcomponent ft_apply_montage

load(dccnpath('/home/common/matlab/fieldtrip/data/test/latest/raw/eeg/preproc_brainvision.mat'));

elec = ft_read_sens('standard_1020.elc');
data.elec = elec;

cfg = [];
cfg.reref = 'yes';
cfg.refchannel = 'all';
data_reref = ft_preprocessing(cfg,data);

cfg = [];
cfg.method = 'fastica';
cfg.numcomponent = 10; % to make it go fast
cfg.randomseed = 13; % so we get the same output each time
comp = ft_componentanalysis(cfg,data_reref);

% this step does not add a balancing matrix to the elec-description
cfg = [];
cfg.component = 2; % chosen randomly
rej1 = ft_rejectcomponent(cfg, comp, data_reref);

% create a montage rereference and call cfg.montage, then assess if
% ft_componentanalysis/ft_rejectcomponent still works correctly.
montage = [];
montage.tra = eye(numel(data.label))-ones(numel(data.label))./numel(data.label);
montage.labelold = data.label;
montage.labelnew = data.label;

cfg = [];
cfg.montage = montage;
data_reref2 = ft_preprocessing(cfg,data);


text:
%kkgrayleigh 'Generate Rayleigh Noise Data'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kgrayleigh.pane file
%
% Parameters:
% Integer: wsize 'Width ', default: 512: 'Width size of noise value data'
% Integer: hsize 'Height ', default: 512: 'Height size of noise value data'
% Integer: dsize 'Depth ', default: 1: 'Depth size of noise value data'
% Integer: tsize 'Time ', default: 1: 'Time size of noise value data'
% Integer: esize 'Elements ', default: 1: 'Element dimension size of noise data'
% OutputFile: o 'Output File', required: 'Output file containing noise data'
%
% Example: o = kkgrayleigh( {'wsize',512;'hsize',512;'dsize',1;'tsize',1;'esize',1;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kgrayleigh - Generate Rayleigh Noise Data
%
%  DESCRIPTION
% "kgrayleigh" generates Rayleigh noise of the specified parameters in the
% output data object (-o). The variance (-rvar) must be
% specified for the Rayleigh distribution to be generated.
%
% The size of all five dimensions of the object can be specified. The data type
% of the output object can also be specified. "kgrayleigh" can also generate
% complex valued Rayleigh noise data.
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
%
%  RESTRICTIONS
% DATAMANIP::kgnoise, DATAMANIP::kgexpon, DATAMANIP::kggauss,
% DATAMANIP::kpoisson, DATAMANIP::kguniform
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kkgrayleigh(varargin)
Inputs={};
if nargin ==0
  arglist={'',''};
elseif nargin ==1
  arglist=varargin{1};
else error('Usage: [out1,..] = kkgrayleigh(arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'wsize', 512;'hsize', 512;'dsize', 1;'tsize', 1;'esize', 1;'o', '__output'};
maxval={2,2,2,2,2,0};
minval={2,2,2,2,2,0};
istoggle=[1,1,1,1,1,0];
was_set=istoggle * 0;
paramtype={'Integer','Integer','Integer','Integer','Integer','OutputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; 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(1,1);
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
[varargout{:}]=callKhoros([w 'kgnoise"  -ray'],Inputs,narglist);

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function y = apm_quadprog(H,f,A,b,Aeq,beq,lb,ub,x0)
%apm_quadprog Quadratic programming.
%   y = apm_quadprog(H,f,A,b,Aeq,beq,LB,UB,X0) writes a quadratic
%   programming model in APMonitor Modeling Language and attempts
%   to solve the quadratic programming problem:
%
%            min 0.5*x'*H*x + f'*x   subject to:  A*x <= b, Aeq*x = beq
%             x
%
%   lb and ub are a set of lower and upper bounds on the design variables,
%   x, so that the solution is in the range lb <= x <= ub. Use empty
%   matrices for any of the arguments. Set lb(i) = -1e20 if x(i) has no
%   lower limit and set ub(i) = 1e20 if x(i) has no upper limit. x0 is
%   the initial guess and starting point to x. This is similar to the
%   Matlab quadprog solver but uses different solvers such as IPOPT,
%   APOPT, and BPOPT to solve the QP. Additional nonlinear constraints
%   can be added to the qp.apm model for nonlinear programming solution
%   with support for possible mixed-integer variables.
%
%   The solution is returned in the structure y with y.names (variable
%   names), y.values (variable values), y.nvar (number of variables),
%   and y.x (a structure containing each variable and value).
%
%   Example usage is below:
%
% clear all; close all; clc
% disp('APM MATLAB available for download at http://apmonitor.com')
% addpath('apm')
%
% %% example Quadratic program
% H = [1 -1; -1 2];
% f = [-2; -6];
% A = [1 1; -1 2; 2 1];
% b = [2; 2; 3];
% Aeq = [];
% beq = [];
% lb = zeros(2,1);
% ub = [];
% x0 = [];
%
% %% generate APMonitor QP model
% y1 = apm_quadprog(H,f,A,b,Aeq,beq,lb,ub,x0);
%
% %% compare solution to quadprog (MATLAB)
% y2 = quadprog(H,f,A,b,Aeq,beq,lb,ub,x0)
%
% disp('Validate Results with MATLAB linprog')
% for i = 1:nx,
%     disp(['x[' int2str(i) ']: ' num2str(y1.values(i)) ' = ' num2str(y2(i))])
% end

% filename to write
filename = ['qp.apm'];

% extract H and f in sparse form
if ~isempty(H),
    [mH,nH] = size(H);
    if (mH~=nH),
        error('H must be a square matrix');
    end
    if isempty(f),
        f = zeros(mH,1);
        mf = mH;
    else
        if size(f,1)==1,
            f = f';
        end
        [mf,nf] = size(f);
    end
    if (mH~=mf),
        error('Rows of H and f must agree');
    end

    % convert to sparse form
    [hi,hj,hv] = find(sparse(H));
    h = [hi,hj,hv]';
    [fi,fj,fv] = find(sparse(f));
    f = [fi,fj,fv]';
    if(size(f,2)==0),
        f = [1,1,0]';
    end
    fr = [f(1,:); f(3,:)];
end

% extract A and b in sparse form
if ~isempty(A),
    [mA,nA] = size(A);
    if isempty(b),
        b = zeros(mA,1);
        mB = mA;
    else
        if size(b,1)==1,
            b = b';
        end
        [mB,nB] = size(b);
    end
    if (mA~=mB),
        error('Rows of A and b must agree');
    end

    % convert to sparse form
    [ai,aj,av] = find(sparse(A));
    if (mA==1),
        a = [ai;aj;av];
    else
        a = [ai,aj,av]';
    end
    [bi,bj,bv] = find(sparse(b));
    b = [bi,bj,bv]';
    if(size(b,2)==0),
        b = [1,1,0]';
    end
    br = [b(1,:); b(3,:)];
end

% extract Aeq and beq in sparse form
if ~isempty(Aeq),
    [mAeq,nAeq] = size(Aeq);
    if isempty(beq),
        beq = zeros(mAeq,1);
        mBeq = mAeq;
    else
        if size(beq,1)==1,
            beq = beq';
        end
        [mBeq,nBeq] = size(beq);
    end
    if (mAeq~=mBeq),
        error('Rows of Aeq and beq must agree');
    end

    % convert to sparse form
    [aeqi,aeqj,aeqv] = find(sparse(Aeq));
    if (mAeq==1),
        aeq = [aeqi;aeqj;aeqv];
    else
        aeq = [aeqi,aeqj,aeqv]';
    end
    [beqi,beqj,beqv] = find(sparse(beq));
    beq = [beqi,beqj,beqv]';
    if(size(beq,2)==0),
        beq = [1,1,0]';
    end
    beqr = [beq(1,:); beq(3,:)];
end

disp('Creating Quadratic Programming Model qp.apm');
fid = fopen(filename,'w');
fprintf( fid,'\n');
fprintf( fid,'Objects \n');
if ~isempty(H),
    fprintf( fid,[' h = qobj\n']);
end
if ~isempty(A),
    fprintf( fid,[' a = axb\n']);
end
if ~isempty(Aeq),
    fprintf( fid,[' aeq = axb\n']);
end
fprintf( fid,'End Objects \n');
fprintf( fid,'\n');
fprintf( fid,'Connections\n');
sz = -1;
if ~isempty(H),
    fprintf( fid,['  x[1:%d] = h.x[1:%d]\n'],nH,nH);
    sz = nH;
end
if ~isempty(A),
    fprintf( fid,['  x[1:%d] = a.x[1:%d]\n'],nA,nA);
    if (sz>=0),
        if (nA~=sz),
            error('Variables in Ax < b model must be consistent');
        end
    end
end
if ~isempty(Aeq),
    fprintf( fid,['  x[1:%d] = aeq.x[1:%d]\n'],nAeq,nAeq);
    if (sz>=0),
        if (nAeq~=sz),
            error('Variables in Ax = b model must be consistent');
        end
    end
end
fprintf( fid,'End Connections\n');
fprintf( fid,'\n');
fprintf( fid,'Model \n');
fprintf( fid,'  Variables \n');
if (isempty(x0)&&isempty(lb)&&isempty(ub)),
    % default initial conditions
    fprintf( fid,'    x[1:%d] = 0\n',nH);
else
    % create default values
    if (isempty(x0)),
        x0 = zeros(nH,1);
    end
    if (isempty(lb)),
        lb = -1e10 * ones(nH,1);
    end
    if (isempty(ub)),
        ub = 1e10 * ones(nH,1);
    end
    % generate initial conditions and bounds
    for i = 1:nH,
        fprintf( fid,'    x[%i] > %d = %d < %d\n',i,lb(i),x0(i),ub(i));
    end
end
fprintf( fid,'  End Variables \n');
fprintf( fid,'\n');
fprintf( fid,'  Equations \n');
fprintf( fid,'    ! add any additional equations here \n');
fprintf( fid,'  End Equations \n');
fprintf( fid,'End Model \n');
fprintf( fid,'\n');

if ~isempty(H),
    fprintf( fid,'\n');
    fprintf( fid,['File h.txt\n']);
    fprintf( fid,['  sparse, minimize  ! dense or sparse, minimize or maximize\n']);
    fprintf( fid,'  %d      ! n=number of variables \n',mH);
    fprintf( fid,'End File\n');
    fprintf( fid,'\n');
    fprintf( fid,['File h.a.txt \n']);
    fprintf( fid,'   %d %d %f\n', h );
    fprintf( fid,'End File \n');
    fprintf( fid,'\n');
    fprintf( fid,['File h.b.txt \n']);
    fprintf( fid,'   %d %f\n', fr );
    fprintf( fid,'End File \n');
end

if ~isempty(A),
    fprintf( fid,'\n');
    fprintf( fid,['File a.txt\n']);
    fprintf( fid,['  sparse, Ax<b \n']);
    fprintf( fid,'  %d      ! m=number of rows in A and b \n',mA);
    fprintf( fid,'  %d      ! n=number of columns in A or variables x\n',nA);
    fprintf( fid,'End File\n');
    fprintf( fid,'\n');
    fprintf( fid,['File a.a.txt \n']);
    fprintf( fid,'   %d %d %f\n', a );
    fprintf( fid,'End File \n');
    fprintf( fid,'\n');
    fprintf( fid,['File a.b.txt \n']);
    fprintf( fid,'   %d %f\n', br );
    fprintf( fid,'End File \n');
end

if ~isempty(Aeq),
    fprintf( fid,'\n');
    fprintf( fid,['File aeq.txt\n']);
    fprintf( fid,['  sparse, Ax=b \n']);
    fprintf( fid,'  %d      ! m=number of rows in A and b \n',mAeq);
    fprintf( fid,'  %d      ! n=number of columns in A or variables x\n',nAeq);
    fprintf( fid,'End File\n');
    fprintf( fid,'\n');
    fprintf( fid,['File aeq.a.txt \n']);
    fprintf( fid,'   %d %d %f\n', aeq );
    fprintf( fid,'End File \n');
    fprintf( fid,'\n');
    fprintf( fid,['File aeq.b.txt \n']);
    fprintf( fid,'   %d %f\n', beqr );
    fprintf( fid,'End File \n');
end
fclose(fid);

disp('Solving Quadratic Programming Model qp.apm');
s = 'http://xps.apmonitor.com';
a = 'qp';
apm(s,a,'clear all');
apm_load(s,a,'qp.apm');
% select solver (1=APOPT,2=BPOPT,3=IPOPT)
apm_option(s,a,'nlc.solver',1);
output = apm(s,a,'solve');
disp(output);

% return solution
y = apm_sol(s,a);

end

author: APMonitor

repo: arduino

save_path: github-repos/MATLAB/APMonitor-arduino


text:
function YW_out = YWoutput(cov,par)

%function YW_out = YWoutput(cov,par)
%
%
%See also: FILTERV.
%

s = kingsize(cov);
dim = s(1);
len = s(3);
I = eye(dim);

covneg = transposeLTI(cov);
covs = zeros(dim,dim,2*len-1);
covs(:,:,1:len-1) = covneg(:,:,1:len-1);
covs(:,:,len:end) = cov;
YW_out = armafilterv(covs,I,par);
YW_out = YW_out(:,:,len:end);


text:
function gray = createCombinedSession(newSessDir, srcSessions, keepAll);

% gray = createCombinedSession([newSessDir], [srcSessions], [keepAll=0]);
%
% Create a new mrVista session for the purposes of combining
% data across sessions. This is only for sessions which
% have gray tSeries, and are from the same subject/segmentation.
%
% This session will be distinct from other sessions, in that
% it will only have a gray view, not an inplane view (diff't
% sessions have different inplane Rxs -- it may be possible to
% create an interpolated inplane set but that's way advanced).
% The Gray coords.mat file will contain a union of the coordinates
% from all of the source sessions. In the related functions (see
% importTSeries), any coordinates which lie outside a given
% session's prescription will be assigned NaN.
%
% newSessDir is a path to the new directory to create.
% If it doesn't exist, creates the directory. Creates
% a mrSESSION file for the combined session. If some
% fields in the mrSESSION and dataTYPES variables are
% ambiguous, it will leave them blank or else grab
% them from the first source session. If omitted,
% newSessDir is taken to be the current dir.
%
% srcSessions is a cell of strings, containing paths
% to each of the sessions that will contribute to the
% combined coordinates. If omitted, pops up a prompt.
% (The prompt initially looks at dirs in the parent
% directory, but you can navigate to other dirs by
% selecting the (Find Other Session) option.)
%
% The main effect of the source sessions is to contribute
% relevant gray coordinates. If you create a combined
% session, but later want to add data from another session,
% you may be ok. If the new session doesn't cover any
% new gray matter not covered by the source sessions,
% you can just add the data. Otherwise, you'll need to
% rebuild the combined session and import the data all
% over again.
%
% keepAll is an optional flag indicating that all left and right gray nodes
% should be used in the combined session. The advantages to this are that
% it guarantees no data are missed in any imported session, and mapping
% from the combined session to the input segmentation files is simplified.
% The downside is that there may be much larger data files, many of which
% may be NaNs since there is never data there. [defualt: 0, keep only the
% intersection of the gray nodes with the source sessions.]
%
% Note that this function doesn't take any of the
% scan data yet; it just initializes the session so
% you can add scans to it.
%
%
% ras 03/05
if notDefined('newSessDir'),    newSessDir = pwd;       end
if notDefined('keepAllNodes'),	keepAllNodes = false;	end
callingDir = pwd;

if notDefined('srcSessions')
    % create an interface, get sessions
	studyDir = fileparts(pwd); % guess at study dir
    srcSessions = selectSessions(studyDir);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Create new session dir if it doesn't exist %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[p d] = fileparts(fullpath(newSessDir));
if ~exist(newSessDir,'dir')
    mkdir(p,d);
    fprintf('Made directory %s in parent dir %s.\n',d,p);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check that each source directory exists, and get full paths %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
newSessDir = fullpath(newSessDir);
for i = 1:length(srcSessions)
    if exist(srcSessions{i}, 'dir')
        srcSessions{i} = fullpath(srcSessions{i});
    else
        errmsg = sprintf('Source dir %s not found.', srcSessions{i});
        error(errmsg);
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%
% create mrSESION file %
%%%%%%%%%%%%%%%%%%%%%%%%
cd(newSessDir);
mrGlobals;
mrSESSION = [];
dataTYPES = [];
vANATOMYPATH = '';
tmp = load(fullfile(srcSessions{1},'mrSESSION.mat'));

mrSESSION.mrLoadRetVersion = 3.01;
mrSESSION.sessionCode = d;
desc = 'Combined: coords from ';
for i = 1:length(srcSessions)
    [p f] = fileparts(srcSessions{i});
    desc = [desc f ' '];
end
mrSESSION.description = desc;
mrSESSION.subject = tmp.mrSESSION.subject;
mrSESSION.examNum = 'N/A';
mrSESSION.inplanes = tmp.mrSESSION.inplanes;
% mrSESSION.functionals = [];
mrSESSION.alignment = [];

dataTYPES.name = 'Imported_Original';

% Dilemna: we need various data types fields
% as placeholders to run mrVista, but don't want
% to actually import any tSeries yet (can't have
% a struct of size 0, it seems).
% Solution (Hack): Create a dummy, and label it so:
dataTYPES.scanParams = tmp.dataTYPES(1).scanParams(1);
dataTYPES.blockedAnalysisParams = tmp.dataTYPES(1).blockedAnalysisParams(1);
dataTYPES.eventAnalysisParams = tmp.dataTYPES(1).eventAnalysisParams(1);
dataTYPES.scanParams.annotation = '(Empty Scan)';

if isfield(tmp, 'vANATOMYPATH')
    vANATOMYPATH = tmp.vANATOMYPATH;
else
    vANATOMYPATH = getVAnatomyPath(mrSESSION.subject);
end

HOMEDIR = pwd;

mrSessFile = fullfile(newSessDir,'mrSESSION.mat');
if exist(mrSessFile,'file')
    % confirm to save over
    msg = sprintf('%s already exists. Save over?',mrSessFile);
    response = questdlg(msg,'Confirm','Yes','No','No');
    if isequal(response,'No')
        disp('Aborted createCombinedSession w/o saving.')
        return
    end
end
save(mrSessFile,'mrSESSION','dataTYPES','vANATOMYPATH');
fprintf('Saved new mrSESSSION.mat file.\n');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% create Gray dir, get coords %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ensure a gray dir exists
grayDir = fullfile(HOMEDIR,'Gray');
if ~exist(grayDir)
    mkdir(HOMEDIR,'Gray');
    fprintf('Created Directory: %s \n',fullfile(HOMEDIR,'Gray'));
end

%% get either all gray nodes, or the intersection with the source session
if keepAllNodes
	%% keep all left and right nodes
	% get the left and right paths from the first session
	srcCoordsFile = fullfile(srcSessions{1}, 'Gray', 'coords.mat');
	load(srcCoordsFile, 'leftPath', 'rightPath');

	% load all the nodes
	[allLeftNodes allLeftEdges leftPath] = loadGrayNodes('left', leftPath);
	[allRightNodes allRightEdges rightPath] = loadGrayNodes('right', rightPath);
else
	%% get nodes from each of the source sessions
	for i = 1:length(srcSessions)
		srcCoordsFile = fullfile(srcSessions{i},'Gray','coords.mat');

		if i==1
			% use 1st session gray coords to set fields other than coords.
			% Critical assumption here: the nodes and edges (in the variables
			% 'allLeftNodes' / 'allRightNodes', 'allLeftEdges' /
			% 'allRightEdges') are the same across input sessions. If not, the
			% coords and nodes variables can be out of whack. This is usually
			% the case. (If you used different segmentations for different
			% sessions, obviously, you shouldn't combine those sessions.)
			load(srcCoordsFile);
		end

		srcData{i} = load(srcCoordsFile);
	end

	% Keep nodes that intersect with the coords
	if ~isempty(allLeftNodes)
		[leftCoords, leftIndices, keepLeft] = ...
			intersectCols(coords, allLeftNodes([2 1 3],:));
		[leftNodes, leftEdges, nLeftNotReached] = ...
			keepNodes(allLeftNodes, allLeftEdges, keepLeft);
		fprintf('%i Left nodes kept. \n', length(keepLeft));
		fprintf('%i Left nodes not reached. \n', nLeftNotReached);
	else
		leftNodes = []; leftEdges = [];
	end

	if ~isempty(allRightNodes)
		[rightCoords, rightIndices, keepRight] = ...
			intersectCols(coords, allRightNodes([2 1 3],:));
		[rightNodes, rightEdges, nRightNotReached] = ...
			keepNodes(allRightNodes, allRightEdges, keepRight);
		fprintf('%i Right nodes kept. \n', length(keepRight));
		fprintf('%i Right nodes not reached. \n', nRightNotReached);
	else
		rightNodes = []; rightEdges = [];
	end
end

% Concantenate the left and right gray graphs
if ~isempty(rightNodes) & ~isempty(leftNodes)
	% the 5th row is the edge offset: shift by the # of left edges
    rightNodes(5,:) = rightNodes(5,:) + length(leftEdges);
    rightEdges = rightEdges + size(leftNodes,2);
end
nodes = [leftNodes rightNodes];
edges = [leftEdges rightEdges];

% Sometimes we need to trim back the combined nodes: this can
% happen if some nodes are included in both the left and right
% segmentations. In this case, we warn the user, and properly scale back
overlapCoords = unionCols(leftNodes(1:3,:), rightNodes(1:3,:));
if ~isempty(overlapCoords)
	if prefsVerboseCheck >= 1
		msg = sprintf(['%i nodes overlap between the left and right' ...
					   'hemisphere segmentations. I am removing the ' ...
					   'overlap.'], ...
					   length(overlapCoords));
		fprintf('[%s]: %s.\n', mfilename, msg);
	end

	[nonOverlapNodes keep] = intersectCols(nodes, nodes);
	[nodes edges] = keepNodes(nodes, edges, keep);
end

% force the coords to match the gray nodes
coords = nodes([2 1 3],:);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% save the combined gray nodes %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% (the other variables were loaded from 1st src file)
coordsFile = fullfile(grayDir,'coords.mat');
if exist(coordsFile,'file')
    % confirm to save over
    msg = sprintf('%s already exists. Save over?',coordsFile);
    response = questdlg(msg,'Confirm','Yes','No','No');
    if isequal(response,'No')
        disp('Aborted createCombinedSession w/o saving.')
        return
    end
end
keepLeft = []; keepRight = []; % save memory, inplanes are irrelevant
save(coordsFile, 'coords', 'nodes', 'edges', 'allLeftNodes', ...
    'allLeftEdges', 'allRightNodes', 'allRightEdges',...
    'leftPath', 'rightPath', 'keepLeft', 'keepRight');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% make a Readme.txt file letting people know    %
% this is a combined session.                   %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fid = fopen('Readme.txt', 'w');
if fid > -1
    fprintf(fid, 'This is a mrVista Combined Session, intended \n');
    fprintf(fid, 'to hold data from multiple sessions. \n');
    fprintf(fid, 'It has gray coords that span at least \n');
    fprintf(fid, 'the following sessions: \n');
    for i = 1:length(srcSessions)
        fprintf(fid, '%s \n', srcSessions{i});
    end
    fprintf(fid, '\nPlease use only Volume / Gray / Flat views \n');
    fprintf(fid, 'for this session; Inplanes aren''t defined. \n');
    fprintf(fid, '\nSee createCombinedSession and importTSeries');
    fprintf(fid, 'for more info.\n');
    fclose(fid);
end

%%%%%%%%%%%%%%%%%%%%%%
% That should do it. %
%%%%%%%%%%%%%%%%%%%%%%
if nargout>0, gray = initHiddenGray;    end
cd(callingDir);
fprintf('Finished building %s directory.\n',newSessDir);

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function diameter = polygon_diameter_2d ( n, v )

%*****************************************************************************80
%
%% POLYGON_DIAMETER_2D computes the diameter of a polygon in 2D.
%
%  Discussion:
%
%    The diameter of a polygon is the maximum distance between any
%    two points on the polygon.  It is guaranteed that this maximum
%    distance occurs between two vertices of the polygon.  It is
%    sufficient to check the distance between all pairs of vertices.
%    This is an N^2 algorithm.  There is an algorithm by Shamos which
%    can compute this quantity in order N time instead.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 February 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of vertices of the polygon.
%
%    Input, real V(2,N), the vertices.
%
%    Output, real DIAMETER, the diameter of the polygon.
%
  diameter = 0.0;

  for i = 1 : n

    for j = i + 1 : n
      diameter = max ( diameter, ...
        sqrt ( ( v(1,i) - v(1,j) ).^2 + ( v(2,i) - v(2,j) ).^2 ) );
    end

  end

  return
end


text:
% Copyright (C) 2012, by Arturo Gil Aparicio
%
% This file is part of ARTE (A Robotics Toolbox for Education).
%
% ARTE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% ARTE 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with ARTE.  If not, see <http://www.gnu.org/licenses/>.

%demo file showing the main capabilities of the library
global robot configuration
close all

fprintf('\nROBOT MANUFACTURING AND PROGRAMMING DEMO\n')
manufacturing_demo

spot_welding_demo

fprintf('\nINVERSE AND DIRECT KINEMATICS DEMO\n')
kinematics_demo

fprintf('\nINVERSE DYNAMICS DEMO\n')
inversedynamics_puma560

fprintf('\nFORWARD DYNAMICS DEMO\n')
forwarddynamics_demo

fprintf('\nPRESS ANY KEY TO CONTINUE\n')
pause

fprintf('\nA MITSUBISHI PA-10 FOLLOWING A LINE IN SPACE\n')
follow_line_pa10

fprintf('\nDIRECT JACOBIAN DEMO\n')
direct_jacobian_demo

fprintf('\nNOW WE CAN PLOT SOME OF THE ROBOTS INCLUDED IN THE LIBRARY\n')
fprintf('\nPRESS ANY KEY TO CONTINUE\n')
pause

robot=load_robot('kuka', 'KR5_scara_R350_Z200');
drawrobot3d(robot, [0 0 0 0])
fprintf('\nPRESS ANY KEY TO CONTINUE\n')
pause

robot=load_robot('kuka', 'KR5_sixx_R650');
drawrobot3d(robot, [0 0 0 0 0 0])
fprintf('\nPRESS ANY KEY TO CONTINUE\n')
pause

robot=load_robot('kuka', 'KR90_R2700_pro');
drawrobot3d(robot, [0 0 0 0 0 0])
fprintf('\nPRESS ANY KEY TO CONTINUE\n')
pause

fprintf('\nUSE A TEACHING PENDANT TO PROGRAM THE ROBOT IN RAPID\n')
fprintf('\nOTHER ROBOTS (KUKA, FANUC, MITSUBISHI) CAN ALSO BE PROGRAMMED IN RAPID\n')
robot=load_robot('abb', 'IRB140');
teach

fprintf('\nPRESS ANY KEY TO CONTINUE\n')
pause

fprintf('\nRAPID IS TRANSLATED TO A MATLAB PROGRAM\n')
fprintf('\nYOU CAN SIMULATE A PROGRAM STEP BY STEP\n')
edit test_rapid.m

repo: ARTE


text:
classdef ForceModelsEnum < matlab.mixin.SetGet & matlab.mixin.Heterogeneous
    %ForceModelsEnum Summary of this class goes here
    %   Detailed explanation goes here

    enumeration
        Gravity('Gravity',GravityForceModel(),false, true);
        Drag('Drag Force',DragForceModel(),true, false);
        Thrust('Thrust',ThrustForceModel(),true, false);
        Normal('Normal Force',NormalForceModel(),true, false);
        Lift('Lift Force',LiftForceModel(),true, false);
        Gravity3rdBody('3rd Body Gravity',Gravity3rdBodyForceModel(),true, true);
    end

    properties
        name char
        model AbstractForceModel
        canBeDisabled(1,1) logical = false;
        allowedForSecondOrder(1,1) logical = false
    end

    methods
        function obj = ForceModelsEnum(name, model, canBeDisabled, allowedForSecondOrder)
            obj.name = name;
            obj.model = model;
            obj.canBeDisabled = canBeDisabled;
            obj.allowedForSecondOrder = allowedForSecondOrder;
        end
    end

    methods(Static)
        function m = getEnumsOfDisablableForceModels()
            [m,~] = enumeration('ForceModelsEnum');
            m = m([m.canBeDisabled]);
        end

        function listBoxStrs = getListBoxStrs()
            [m,~] = enumeration('ForceModelsEnum');

            listBoxStrs = {};
            for(i=1:length(m)) %#ok<*NO4LP>
                listBoxStrs{end+1} = m(i).name; %#ok<AGROW>
            end
        end

        function listBoxStrs = getListBoxStrsOfDisablableModels()
            m = ForceModelsEnum.getEnumsOfDisablableForceModels();

            listBoxStrs = {};
            for(i=1:length(m)) %#ok<*NO4LP>
                listBoxStrs{end+1} = m(i).name; %#ok<AGROW>
            end
        end

        function [ind, fmE] = getIndOfListboxStrsForModel(model)
            [m,~] = enumeration('ForceModelsEnum');

            ind = -1;
            for(i=1:length(m))
                if(strcmpi(class(m(i).model),class(model)))
                    ind = i;
                    fmE = m(i);
                    break;
                end
            end
        end

        function [ind, fmE] = getIndOfDisablableListboxStrsForModel(model)
            m = ForceModelsEnum.getEnumsOfDisablableForceModels();

            ind = -1;
            for(i=1:length(m))
                if(strcmpi(class(m(i).model),class(model)))
                    ind = i;
                    fmE = m(i);
                    break;
                end
            end
        end

        function fmArr = getDefaultArrayOfForceModelEnums()
            fmArr = [ForceModelsEnum.Gravity, ForceModelsEnum.Drag, ForceModelsEnum.Thrust];
        end

        function fmArr = getAllForceModelsThatCannotBeDisabled()
            [m,~] = enumeration('ForceModelsEnum');

            fmArr = ForceModelsEnum.empty(1,0);
            for(i=1:length(m))
                if(m(i).canBeDisabled == false)
                    fmArr(end+1) = m(i); %#ok<AGROW>
                end
            end
        end
    end
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function determ = summation_determinant ( n )

%*****************************************************************************80
%
%% SUMMATION_DETERMINANT returns the determinant of the SUMMATION matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of A.
%
%    Output, real DETERM, the determinant.
%
  determ = 1.0;

  return
end


text:
function[h]=vlines(x,sty)
%VLINES   Add vertical lines to a plot.
%
%   VLINES(X,STYLE) puts vertical lines at locations X having style
%   described by the string STYLE.  VLINES draws the lines to fit the
%   current axis.
%
%   The SYTLE strings follow the format specified in LINESTYLE.  Thus
%   STYLE='2b--' draws blue dotted lines of width 2.
%
%   VLINES(X) uses the default STYLE='g--', a green dashed line.
%
%   H=VLINES(...) returns an array of handles H to the lines.
%
%   See also HLINES, DLINES.
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2000--2016 J.M. Lilly --- type 'help jlab_license' for details

if strcmpi(x,'--t')
    return
end

if nargin==1
	sty='g--';
end
hold on

x=x(:)';
ax=axis;
y1=ax(3)*ones(size(x));
y2=ax(4)*ones(size(x));
x=[x;x];
y=[y1;y2];
y(y==0)=1e-16;
h=plot(x,y);
linestyle(h,sty);
axis(ax)

if nargout==0
   clear h
end

author: jonathanlilly

repo: jLab

save_path: github-repos/MATLAB/jonathanlilly-jLab