text:
function y = In
y = cvxin;

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

author: cvxr

repo: CVX

save_path: github-repos/MATLAB/cvxr-CVX


text:
%
% DESC
%
% COPYRIGHT: Andreas C. Damianou, 2015
%
% SEE ALSO:
%
% DEEPGP

%% ------ CONFIGURING THE DEEP GP
%--- Mandatory configurations
if ~exist('Ytr', 'var'), error('You need to specify your outputs in Ytr{1}=...'); end

%--- Optional configurations: Whatever configuration variable is not already set (ie does not exist
% as a variable in the workspace) is set to a default value.
if ~exist('experimentNo','var'), experimentNo = 404; end
if ~exist('K','var'), K = 30; end
if ~exist('Q','var'), Q = 6; end
if ~exist('baseKern','var'), baseKern = 'rbfardjit'; end % {'rbfard2','white','bias'}; end

hsvargplvm_init;

%%
options = hsvargplvmOptions(globalOpt);
options.optimiser = 'scg2';
initXOptions = hsvargplvmInitXOptions(Ytr, options, globalOpt);

% Create a deepGP model, parametrized by its local options, global options
% and options that say how to initialise the latent spaces X
model = hsvargplvmModelCreate(Ytr, options, globalOpt, initXOptions);
%!!!!!!!!!!!!!!!!!!!!!!!!-----------------------
if exist('DEBUG_entropy','var') && DEBUG_entropy
    model.DEBUG_entropy = true;for itmp=1:model.H, model.layer{itmp}.DEBUG_entropy = true; end
end
params = hsvargplvmExtractParam(model); model = hsvargplvmExpandParam(model, params);

%% Optimise deep GP model
model.globalOpt = globalOpt;
[model,modelPruned, modelInitVardist] = hsvargplvmOptimiseModel(model, true, true);

% Uncomment if you decide to train for more iterations later...
%modelOld = model;
%model = hsvargplvmOptimiseModel(model, true, true, [], {0, [1000 1000 1000]});

author: SheffieldML

repo: deepGP

save_path: github-repos/MATLAB/SheffieldML-deepGP


text:
function [xsecx,xsecy, inde] = mysect(eqlat,eqlon,depth,width,length,lat1,lon1,lat2,lon2)
    % MYSECT to make a cross section of data points on a map
    % Based off of LC_XSECTION
    %
    %LC_XSECT
    %
    %	[xsecx, xsecy] = LC_xsect(eqlat,eqlon,depth,width,length,...
    %                                        lat1,lon1,lat2,lon2)        (1)
    %
    %	[xsecx, xsecy] = LC_xsect(eqlat,eqlon,depth,width,length,...
    %                                        lat0,lon0,azimuth)          (2)
    %
    %	[xsecx, xsecy] = LC_xsect(eqlat,eqlon,depth,width)         (3)
    %
    %	Function to make a cross section of data points on a map
    %	created by LC_MAP (Lambert Conformal).
    %	The WIDTH of the zone from which the data points is given
    %	in "km" and represent the total width (1/2 on one side, 1/2 on
    %	the other side).
    %	The LENGTH of the xsection in "km" is only used in method (2),
    %	but this argument is still neccessary in argument list of
    %	method (1) in order to keep the argument list in the right order.
    %	The data points location are given by EQLAT, EQLON and DEPTH.
    %	The cross section location can be given in any one of three ways:
    %
    %	  (1) given latitudes and longitudes of two points on the map,
    %             using the arguments as described above.
    %
    %	  (2) given latitude and longitude of a center point and an azimuth.
    %
    %	  (3) using the cursor to select two points on the map by clicking
    %	      a mouse button above the desired points.
    %
    %	If the output argument is used, the distance-depth data is kept
    %	in variables for other use; otherwise the xsection will be plotted
    %	on a new figure window.
    %
    %	It is possible to set the symbol type, size and line width by
    %	setting the following global variables:
    %	"symb_type", "symb_size" and "symb_width" respectively. Otherwise
    %	it will use the defaults.
    %
    %	It is also possible to set the minimum and maximum depth of the
    %	cross-section by setting the following global variables:
    %	"mindepth" and "maxdepth".  If either or both are not set, it
    %	will use 0 km as the minimum depth and/or the depth of the deepest
    %	data point as the maximum depth.
    %
    %	NOTE:
    %	It is assumed that LC_MAP was used before using this function!
    %	This is necessary to set global variables used by this function.

    %TODO fix the global situation, incoming parameters cannot match globals directly. -CGR

    report_this_filefun();

    global  torad
    % global lat1 lon1 lat2 lon2
    global leng rbox box
    global sine_phi0 phi0 lambda0 phi1 phi2 pos sw eq1
    global maxlatg minlatg maxlong minlong
    global symb_type symb_size symb_width
    global label1 label2 mapl
    global mindepth maxdepth h2
    global eq0p
    todeg = 180 / pi;
    eq1 =[];

    switch nargin
        case 8 % method 2: given lat & lon of center point and angle

            lat0 = lat1;
            lon0 = lon1;
            [x0, y0] = lc_tocart(lat0,lon0);
            azimuth = lat2;

            if azimuth >= 180, azimuth = azimuth - 180; end
            theta0 = ((lon0*torad - lambda0) * sine_phi0) * todeg;
            alpha = azimuth - theta0;
            beta = (90 - azimuth) + theta0;

            x2 = ((length / 2) * cos(beta*torad));
            y2 = ((length / 2) * sin(beta*torad));
            x1 = x0 - x2;
            y1 = y0 - y2;
            x2 = x0 + x2;
            y2 = y0 + y2;

            [lat1, lon1] = lc_froca(x1,y1);
            [lat2, lon2] = lc_froca(x2,y2);

        case 4	% method 3: selection of the end points by mouse
            [lat1, lon1] = inputm(1);
            h=plotm(lat1, lon1,'rx','MarkerSize',6,'LineWidth',2);
            [lat2, lon2] = inputm(1);

            delete(h)
            h=plotm([lat1 lat2],[lon1 lon2],'rx:','MarkerSize',6,'LineWidth',2);

            [arclen,azimuth] = distance([lat1, lon1] , [lat2, lon2]);
            leng=deg2km(arclen);
            alpha=0;
            %{
            limits = ginput(1);
            x1 = limits(1,1);
            y1 = limits(1,2);
            [lat1, lon1] = lc_froca(x1,y1);
            lc_event(lat1,lon1,'rx',6,2)
            limits = ginput(1);
            x2 = limits(1,1);
            y2 = limits(1,2);

            if x1 > x2
                xtemp = x1; ytemp = y1;
                x1 = x2; y1 = y2;
                x2 = xtemp; y2 = ytemp;
            end

            [lat1, lon1] = lc_froca(x1,y1);
            [lat2, lon2] = lc_froca(x2,y2);
            lc_event(lat2,lon2,'rx',6,2)

            x0 = (x1 + x2) / 2;
            y0 = (y1 + y2) / 2;
            [lat0, lon0] = lc_froca(x0,y0);
            dx = x2 - x1;
            dy = y2 - y1;

            alpha = 90 - (atan(dy/dx)*todeg);
            length = sqrt(dx^2 + dy^2);
            leng = length;
            %}

        case 9	% method 1: given lat & lon of the two end points
            figure(mapl);
            [x1, y1] = lc_tocart(lat1,lon1);
            [x2, y2] = lc_tocart(lat2,lon2);

            if x1 > x2
                xtemp = x1; ytemp = y1;
                x1 = x2; y1 = y2;
                x2 = xtemp; y2 = ytemp;
                sw = 'on'
            else
                sw = 'of'
            end

            x0 = (x1 + x2) / 2;
            y0 = (y1 + y2) / 2;
            [lat0, lon0] = lc_froca(x0,y0);
            dx = x2 - x1;
            dy = y2 - y1;

            alpha = 90 - (atan(dy/dx)*todeg);
            length = sqrt(dx^2 + dy^2);

        otherwise

            disp('ERROR: incompatible number of arguments')
            help mysect
            return
    end

    % correction factor to correct for longitude away from the center meridian
    theta0 = ((lon0*torad - lambda0) * sine_phi0) * todeg;

    % correct the XY azimuth of the Xsection line with the above factor to obtain
    % the true azimuth
    azimuth = alpha + theta0;
    if azimuth < 0, azimuth = azimuth + 180; end

    % convert XY coordinate azimuth to a normal angle like we used to deal with
    sigma = 90 - alpha;

    % transformation matrix to rotate the data coordinate w.r.t the Xsection line
    transf = [cos(sigma*torad) sin(sigma*torad)
        -sin(sigma*torad) cos(sigma*torad)];

    % inverse transformation matrix to rotate the data coordinate back
    invtransf = [cos(-sigma*torad) sin(-sigma*torad)
        -sin(-sigma*torad) cos(-sigma*torad)];

    % convert the map coordinate of the events to cartesian coordinates
    idx_map = find(minlatg < eqlat & eqlat < maxlatg & ...
        minlong < eqlon & eqlon < maxlong);
    [eq(1,:) eq(2,:)] = lc_tocart(eqlat,eqlon);
    % create new coordinate system at center of Xsection line
    eq0(1,:) = eq(1,:) - x0;
    eq0(2,:) = eq(2,:) - y0;

    % rotate this last coordinate system so that X-axis correspond to Xsection line
    eq0p = transf * eq0;
    % project the event data to the Xsection line
    eq1(1,:) = eq0p(1,:);
    eq1(2,:) = eq0p(2,:) ;

    % convert back to the original coordinate system
    eq1p = invtransf * eq1;
    eq2(1,:) = eq1p(1,:) + x0;
    eq2(2,:) = eq1p(2,:) + y0;

    % plot the Xsection line on the map
    plot([x1 x2],[y1 y2],'--','LineWidth',1.5)

    % label the Xsection end points
    xlim = get(gca,'XLim');
    ylim = get(gca,'YLim');
    label_dist = (2 / 100) * sqrt((2*xlim(2))^2 + (2*ylim(2))^2);
    label_pt(1,1) = -(length/2 + label_dist);
    label_pt(2,1) = 0;
    label_pt(1,2) = length/2 + label_dist;
    label_pt(2,2) = 0;
    rlabel_pt = invtransf * label_pt;
    label_pt(1,:) = rlabel_pt(1,:) + x0;
    label_pt(2,:) = rlabel_pt(2,:) + y0;
    if isempty(label1), label1 = 'A'; end
    if isempty(label2), label2 = 'B'; end
    label1 = 'A'; label2 = 'B';
    lbl1_h = text(label_pt(1,1),label_pt(2,1),label1,'FontSize',14,...
        'Vertical','middle','Horizontal','center','FontWeight','bold');
    lbl2_h = text(label_pt(1,2),label_pt(2,2),label2,'FontSize',14,...
        'Vertical','middle','Horizontal','center','FontWeight','bold');

    % create a box of width "width" around the Xsection line and plot it
    box(1,1) = -length/2; box(2,1) = width/2;
    box(1,2) = length/2; box(2,2) = width/2;
    box(1,3) = length/2; box(2,3) = -width/2;
    box(1,4) = -length/2; box(2,4) = -width/2;
    xbox = [box(1,:) box(1,1)];
    ybox = [box(2,:) box(2,1)];
    rbox = invtransf * [xbox ; ybox];
    rbox(1,:) = rbox(1,:) + x0;
    rbox(2,:) = rbox(2,:) + y0;
    plot(rbox(1,:),rbox(2,:),'-y','LineWidth',1.3)

    % check if symbol parameters global variables are set, if not --> defaults
    if isempty(symb_type), symb_type = '+r'; end
    if isempty(symb_size), symb_size = 3; end
    if isempty(symb_width), symb_width = [0.5]; end

    % find index of all events which are within the given box width
    idx_box = find(abs(eq0p(2,:)) <= width/2 & abs(eq0p(1,:)) <= length/2);
    inde = idx_box;

    % plot the events on the map
    plot(eq(1,idx_box),eq(2,idx_box),'mo','MarkerSize',symb_size,...
        'LineWidth',symb_width)

    % Open another graphic window for the cross section

    xsec_fig_h=findobj('Type','Figure','-and','Name','Cross -Section');

    % Set up the Map window Enviroment
    %
    if isempty(xsec_fig_h)
        xsec_fig_h = figure_w_normalized_uicontrolunits( ...
            'Name','Cross -Section',...
            'Tag','xsection',...
            'NumberTitle','off', ...
            'backingstore','on',...
            'Visible','on');

    end

    figure(xsec_fig_h);

    delete(findobj(xsec_fig_h,'Type','axes'));
    set(xsec_fig_h,'PaperPosition',[1 .5 9 6.9545])

    % Plot events on cross section figure
    xdist = eq1(1,idx_box) + (length / 2);
    %eq1(1,:) = eq1(1,:) + (length / 2);

    global Xwbz Ywbz
    Xwbz = xdist;
    Ywbz = depth(idx_box);

    xsecx = xdist;
    xsecy = depth(idx_box);

    plot(xdist,-depth(idx_box),symb_type,'MarkerSize',symb_size,...
        'LineWidth',symb_width);

    set(gca,'Color',color_bg)
    set(gca,'box','on',...
        'SortMethod','childorder','TickDir','out','FontWeight',...
        'normal','FontSize',10,'Linewidth',1,'Ticklength',[0.02 0.02])

    if isempty(maxdepth)
        maxZ = max(depth(idx_box));
    else
        maxZ = maxdepth;
    end

    if isempty(mindepth)
        minZ = min(depth(idx_box));
    else
        minZ = mindepth;
    end

    if length > (maxZ - minZ)*11/8.5
        position = [.1 .1 .7 ((maxZ-minZ)/length)*0.7*11/8.5];
    else
        position = [.1 .1 (length/(maxZ-minZ))*0.7*8.5/11 .7];
    end
    pos = position;
    set(gca,'Position',position,'XLim',[0 length],'Ylim',[-maxZ -minZ],...
        'LineWidth',1)
    h2=gca;
    % Plot labels
    xlabel('Distance [km]');
    ylabel('Depth [km]');

    label_base1 = 1 + .04;
    label_base2 = 1 + .08;
    label_base3 = 1 + .12;
    lbl3_h = text(0,label_base2,label1,'FontSize',12,'Horizontal','center',...
        'FontWeight','bold','Vertical','middle','Units','norm');
    lat1_dm = sprintf("    %2.2i N %4.2f'",fix(lat1),(frac(lat1)*60));
    lon1_dm = sprintf("   %3.3i W %4.2f'",abs(fix(lon1)),abs(frac(lon1)*60));
    lbl5_h = text(0,label_base1+0.00,lat1_dm,'FontSize',10,'Horizontal','left',...
        'Vertical','bottom','Units','norm');
    lbl6_h = text(0,label_base3+0.04,lon1_dm,'FontSize',10,'Horizontal','left',...
        'Vertical','bottom','Units','norm');

    lbl4_h = text(1,label_base2,label2,'FontSize',12,'Horizontal','center',...
        'FontWeight','bold','Vertical','middle','Units','norm');
    lat2_dm = sprintf('%2.2i N %4.2f''    ',fix(lat2),(frac(lat2)*60));
    lon2_dm = sprintf('%3.3i W %4.2f''    ',abs(fix(lon2)),abs(frac(lon2)*60));
    lbl7_h = text(1,label_base1+0.0,lat2_dm,'FontSize',10,...
        'Horizontal','right','Vertical','bottom','Units','norm');
    lbl8_h = text(1,label_base3+0.04,lon2_dm,'FontSize',10,...
        'Horizontal','right','Vertical','bottom','Units','norm');

    set(gcf,'visible','on')
    drawnow
    % Go back to map figure
    %figure(map_fig);

end

author: CelsoReyes


text:
% SUPERGUI - a comprehensive gui automatic builder. This function help
%              to create GUI very fast without bothering about the
%              positions of the elements. After creating a geometry,
%              elements just place themselves into the predefined
%              locations. It is especially useful for figure where you
%              intend to put text button and descriptions.
%
% Usage:
%   >> [handles, height, allhandles ] = ...
%             supergui( 'key1', 'val1', 'key2', 'val2', ... );
%
% Inputs:
%   'fig'       - figure handler, if not given, create a new figure.
%   'geom'      - cell array of cell array of integer vector. Each cell
%               array defines the coordinate of a given input in the following
%               manner: { nb_row nb_col [x_topcorner y_topcorner]
%               [x_bottomcorner y_bottomcorner] };
%   'geomhoriz' - integer vector or cell array of numerical vectors describing the
%               geometry of the elements in the figure.
%               - if integer vector, vector length is the number of rows and vector
%               values are the number of 'uilist' elements in each row.
%               For example, [2 3 2] means that the
%               figures will have 3 rows, with 2 elements in the first
%               and last row and 3 elements in the second row.
%               - if cell array, each vector describes the relative widths
%               of items in each row. For example, { [2 8] [1 2 3] } which means
%               that figures will have 2 rows, the first one with 2
%               elements of relative width 2 and 8 (20% and 80%). The
%               second row will have 3 elements of relative size 1, 2
%               and 3 (1/6 2/6 and 3/6).
%   'geomvert' - describting geometry for the rows. For instance
%               [1 2 1] means that the second row will be twice the height
%               of the other ones. If [], all the lines have the same height.
%   'uilist'   - list of uicontrol lists describing elements properties
%               { { ui1 }, { ui2 }... }, { 'uiX' } being GUI matlab
%               uicontrol arguments such as { 'style', 'radiobutton',
%               'String', 'hello' }. See Matlab function UICONTROL for details.
%   'borders'  - [left right top bottom] GUI internal borders in normalized
%               units (0 to 1). Default values are
%   'title'    - optional figure title
%   'userdata' - optional userdata input for the figure
%   'inseth'   - horizontal space between elements. Default is 2%
%               of window size.
%   'insetv'   - vertical space between elements. Default is 2%
%               of window height.
%   'spacing'  - [horiz vert] spacing in normalized units. Default
%   'spacingtype' - ['absolute'|'proportional'] absolute means that the
%               spacing values are fixed. Proportional means that they
%               depend on the number of element in a line.
%   'minwidth' - [integer] minimal width in pixels. Default is none.
%   'screenpos' - [x y] position of the right top corner of the graphic
%               interface. 'center' may also be used to center the GUI on
%               the screen.
%   'adjustbuttonwidth' - ['on'|'off'] adjust button width in the GUI.
%               Default is 'off'.
%
% Hint:
%    use 'print -mfile filemane' to save a matlab file of the figure.
%
% Output:
%    handles  - all the handles of the elements (in the same order as the
%                uilist input).
%    height    - advised height for the figure (so the text look nice).
%    allhandles - all the handles in object format
%
% Example:
%    figure;
%    supergui( 'geomhoriz', { 1 1 }, 'uilist', { ...
%        { 'style', 'radiobutton', 'string', 'radio' }, ...
%        { 'style', 'pushbutton' , 'string', 'push' } } );
%
% Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 2001-
%
% See also: EEGLAB

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

function [handlers, outheight, allhandlers, alltags] = supergui( varargin);

% handlers cell format
% allhandlers linear format
handlers = {};
outheight = 0;

if nargin < 2
	help supergui;
	return;
end

% get version and
% set additional parameters
% -------------------------
v = version;
indDot  = find(v == '.');
versnum = str2num(v(1:indDot(2)-1));
if versnum >= 7.14
     addParamFont = { 'fontsize' 12 };
else addParamFont = { };
end

warning off MATLAB:hg:uicontrol:ParameterValuesMustBeValid

% decoding input and backward compatibility
% -----------------------------------------
if ischar(varargin{1})
    options = varargin;
else
    options = { 'fig'      varargin{1} 'geomhoriz' varargin{2} ...
                'geomvert' varargin{3} 'uilist'    varargin(4:end) };
end
g = finputcheck(options, { 'geomhoriz' 'cell'   []      {};
                           'fig'       ''       []      0;
                           'geom'      'cell'   []      {};
                           'uilist'    'cell'   []      {};
                           'title'     'string' []      '';
                           'userdata'  ''       []      [];
                           'adjustbuttonwidth' 'string' { 'on' 'off' } 'off';
                           'geomvert'  'real'   []      [];
                           'screenpos' { 'real' 'string' } [] [];
                           'horizontalalignment'  'string'   { 'left','right','center' } 'left';
                           'minwidth'  'real'   []      10;
                           'borders'   'real'   []      [0.05 0.04 0.07 0.06];
                           'spacing'   'real'   []      [0.02 0.01];
                           'inseth'    'real'   []      0.02; % x border absolute (5% of width)
                           'insetv'    'real'   []      0.02 }, 'supergui');
if ischar(g), error(g); end
if ~isempty(g.geomhoriz)
    maxcount = sum(cellfun('length', g.geomhoriz));
    if maxcount ~= length(g.uilist)
        warning('Wrong size for ''geomhoriz'' input');
    end
    if ~isempty(g.geomvert)
        if length(g.geomvert) ~= length(g.geomhoriz)
            warning('Wrong size for ''geomvert'' input');
        end
    end
    g.insetv = g.insetv/length(g.geomhoriz);
end
if ~isempty(g.geom)
    if length(g.geom) ~= length(g.uilist)
        warning('Wrong size for ''geom'' input');
    end
    maxcount = length(g.geom);
end

% create new figure
% -----------------
if g.fig == 0
	g.fig = figure('visible','off');
end

% converting the geometry formats
% -------------------------------
if ~isempty(g.geomhoriz) && ~iscell( g.geomhoriz )
	oldgeom = g.geomhoriz;
	g.geomhoriz = {};
	for row = 1:length(oldgeom)
		g.geomhoriz = { g.geomhoriz{:} ones(1, oldgeom(row)) };
	end
end
if isempty(g.geomvert)
	g.geomvert = ones(1, length(g.geomhoriz));
end

% converting to the new format
% ----------------------------
if isempty(g.geom)
    count = 1;
    incy  = 0;
    sumvert  = sum(g.geomvert);
    maxhoriz = 1;
    for row = 1:length(g.geomhoriz)
        incx = 0;
        maxhoriz = max(maxhoriz, length(g.geomhoriz{row}));
        ratio = length(g.geomhoriz{row})/sum(g.geomhoriz{row});
        for column = 1:length(g.geomhoriz{row})
            g.geom{count} = { length(g.geomhoriz{row}) sumvert [incx incy] [g.geomhoriz{row}(column)*ratio g.geomvert(row)] };
            incx = incx+g.geomhoriz{row}(column)*ratio;
            count = count+1;
        end
        incy = incy+g.geomvert(row);
    end
    g.borders(1:2) = g.borders(1:2)/maxhoriz*5;
    g.borders(3:4) = g.borders(3:4)/sumvert*10;
    g.spacing(1)   = g.spacing(1)/maxhoriz*5;
    g.spacing(2)   = g.spacing(2)/sumvert*10;
end

% disp new geometry
% -----------------
if 0
    fprintf('{ ...\n');
    for index = 1:length(g.geom)
        fprintf('{ %g %g [%g %g] [%g %g] } ...\n', g.geom{index}{1}, g.geom{index}{2}, ...
            g.geom{index}{3}(1), g.geom{index}{3}(2), g.geom{index}{4}(1), g.geom{index}{3}(2));
    end
    fprintf('};\n');
end

% get axis coordinates
% --------------------
try
    set(g.fig, 'menubar', 'none', 'numbertitle', 'off');
catch
end

pos = [0 0 1 1]; % plot relative to current axes
q = [pos(1) pos(2) 0 0];
s = [pos(3) pos(4) pos(3) pos(4)]; % allow to use normalized position [0 100] for x and y
axis('off');

% creating guis
% -------------
row    = 1; % count the elements
column = 1; % count the elements
factmultx = 0;
factmulty = 0; %zeros(length(g.geomhoriz));
transformTextUIList = [];
alltags = [];
for counter = 1:maxcount

	% init
	clear rowhandle;
    gm = g.geom{counter};
    [posx posy width height] = getcoord(gm{1}, gm{2}, gm{3}, gm{4}, g.borders, g.spacing);
%     str1 = sprintf('%d, %d, [%1.2f,%1.2f], [%1.2f,%1.2f]', gm{1}, gm{2}, gm{3}(1), gm{3}(2), gm{4}(1), gm{4}(2));
%     str2 = sprintf('%.4f, ', [posx posy width height]);
%     fprintf('%s -> %s -> %s\n', str1, str2, g.uilist{ counter }{4});

    try
        currentelem = g.uilist{ counter };
    catch
        fprintf('Warning: not all boxes were filled\n');
        return;
    end;
    if ~isempty(currentelem)
        % decode metadata
        % ---------------
        if strcmpi(currentelem{1}, 'link2lines'),
            currentelem(1) = [];
            hf1 = 3.6/2-0.3;
            hf2 = 0.7/2-0.3;
            allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
                                          [posx-width/2 posy+hf1*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', '');
            allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
                                          [posx-width/2 posy+hf2*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', '');
            allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
                                          [posx posy+hf2*height 0.005 (hf1-hf2+0.1)*height].*s+q, 'style', 'pushbutton', 'string', '');
            allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
                                          [posx posy+(hf1+hf2)/2*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', '');
            allhandlers{counter} = nan;
        else

            if strcmpi(currentelem{1}, 'width')
                 curwidth = currentelem{2};
                 currentelem(1:2) = [];
            else curwidth = 0;
            end
            if strcmpi(currentelem{1}, 'align')
                 align = currentelem{2};
                 currentelem(1:2) = [];
            else align = 'right';
            end
            transformText = false;
            if strcmpi(currentelem{2}, 'text2')
                transformTextUIList = [ transformTextUIList counter ];
                currentelem{2} = 'text';
            end
            if strcmpi(currentelem{1}, 'stickto')
                 stickto = currentelem{2};
                 currentelem(1:2) = [];
            else stickto = 'none';
            end
            if strcmpi(currentelem{1}, 'vertshift'), currentelem(1) = []; addvert = -height/2;
            else                                                          addvert = 0;
            end
            if strcmpi(currentelem{1}, 'vertexpand'), heightfactor = currentelem{2}; addvert = -(heightfactor-1)*height; currentelem(1:2) = [];
            else                                      heightfactor = 1;
            end

            % position adjustment depending on GUI type
            if ischar(currentelem{2}) && strcmpi(currentelem{2}, 'popupmenu')
                posy = posy-height/5;
            end
            if ischar(currentelem{2}) && strcmpi(currentelem{2}, 'text')
                posy = posy+height/5;
            end

            if strcmpi(currentelem{1}, 'function')
                % property grid argument
                panel = uipanel('Title','','FontSize',12,'BackgroundColor','white','Position',[posx posy+addvert width height*heightfactor].*s+q);
                allhandlers{counter} = arg_guipanel(panel, currentelem{:});
            elseif strcmpi(currentelem{1}, 'panel')
                % property grid argument
                uipanel(currentelem{2:end},'FontSize',12,'Position',[posx posy+addvert width height*heightfactor].*s+q);
                allhandlers{counter} = nan;
            elseif strcmpi(currentelem{1}, 'uitable')
                uitable(g.fig, currentelem{2:end}, 'unit', 'normalized', 'Position',[posx posy+addvert width height*heightfactor].*s+q);
                allhandlers{counter} = nan;
            else
                if ~isempty(strmatch('fontsize', currentelem(1:2:end)))
                    allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
                        [posx posy+addvert width height*heightfactor].*s+q, currentelem{:});
                else
                    allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
                        [posx posy+addvert width height*heightfactor].*s+q, currentelem{:}, addParamFont{:});
                end

                % this simply compute a factor so that all uicontrol will be visible
                % ------------------------------------------------------------------
                style = get( allhandlers{counter}, 'style');
                set( allhandlers{counter}, 'units', 'pixels');
                curpos = get(allhandlers{counter}, 'position');
                curext = get(allhandlers{counter}, 'extent');
                if curwidth ~= 0
                    curwidth = curwidth/((factmultx-1)/1.85+1);
                    if strcmpi(align, 'right')
                        curpos(1) = curpos(1)+curpos(3)-curwidth;
                    elseif strcmpi(align, 'center')
                        curpos(1) = curpos(1)+curpos(3)/2-curwidth/2;
                    end
                    set(allhandlers{counter}, 'position', [ curpos(1) curpos(2) curwidth curpos(4) ]);
                    if strcmpi(stickto, 'on')
                        set( allhandlers{counter-1}, 'units', 'pixels');
                        curpos2 = get(allhandlers{counter-1}, 'position');
                        set(allhandlers{counter-1}, 'position', [ curpos(1)-curpos2(3)-10 curpos2(2) curpos2(3) curpos2(4) ]);
                        set( allhandlers{counter-1}, 'units', 'normalized');
                    end
                    curext(3) = curwidth;
                end
                set( allhandlers{counter}, 'units', 'normalized');
            end

            if ~strcmp(style, 'edit') && (~strcmp(style, 'pushbutton') || strcmpi(g.adjustbuttonwidth, 'on'))
                if strcmpi( currentelem{3}, 'string') && (~iscell(currentelem{4}) || ...
                        (~isempty(currentelem{4}) && isempty(findstr('html', currentelem{4}{1}))))
                    %tmp = curext(3)/curpos(3);
                    %if tmp > 3*factmultx && factmultx > 0, adsfasd; end
                    if exist('OCTAVE_VERSION','builtin') ~= 0
                      curtxt = get(allhandlers{counter}, 'string');
                      if ischar(curtxt)
                        nLines = length(find(curtxt == 10))+1;
                        curext(3) = curext(3)/nLines;
                      end
                    end

                    if curext(3)/curpos(3) < 3
                        factmultx = max(factmultx, curext(3)/curpos(3));
                    end
                    tmptxt = get(allhandlers{counter}, 'string');
%                   % text to get which UI modify horizontal size
%                    if iscell(tmptxt) fprintf('%s -> %f\n', 'cell', curext(3)/curpos(3));
%                    else              fprintf('%s -> %f\n', tmptxt, curext(3)/curpos(3));
%                    end
                    if strcmp(style, 'pushbutton'), factmultx = factmultx*1.1; end
                end
            end
            if  ~strcmp(style, 'listbox') &&  ~strcmp(style, 'popupmenu')
                factmulty = max(factmulty, curext(4)/curpos(4));
            end

            % Uniformize button text aspect (first letter must be uppercase)
            % -----------------------------
            if strcmp(style, 'pushbutton') && ishandle(allhandlers{counter})
                tmptext = get(allhandlers{counter}, 'string');
                if length(tmptext) > 1
                    if upper(tmptext(1)) ~= tmptext(1) || lower(tmptext(2)) ~= tmptext(2) && ~strcmpi(tmptext, 'STATS')
                        tmptext = lower(tmptext);
                        try, tmptext(1) = upper(tmptext(1)); catch, end
                    end
                end
                set(allhandlers{counter}, 'string', tmptext);
            end

            try
                currentelemstruct = struct(currentelem{:});
                alltags.(currentelemstruct.tag) = allhandlers{counter};
            catch, end
        end
    else
        allhandlers{counter} = nan;
    end
end

% adjustments
% -----------
factmultx = factmultx*1.1;% because some text was still hidden
if factmultx < 0.1
	factmultx = 0.1;
end

% for MAC (magnify figures that have edit fields)
% -------
warning off;
try,
    comp = computer;
	if length(comp) > 2 && strcmpi(comp(1:3), 'MAC')
        factmulty = factmulty*1.5;
	elseif ~isunix % windows
        factmulty = factmulty*1.08;
    end
catch, end
if exist('OCTAVE_VERSION', 'builtin') == 0
    factmulty = factmulty*0.9; % global shinking
else
    factmulty = factmulty*1.5;
end
warning on;

% scale and replace the figure in the screen
% -----------------------------------------
pos = get(g.fig, 'position');
if factmulty > 1
	pos(2) = max(0,pos(2)+pos(4)-pos(4)*factmulty);
end
pos(1) = max(0,pos(1)+pos(3)*(1-factmultx)/2);
pos(3) = max(pos(3)*factmultx, g.minwidth);
pos(4) = pos(4)*factmulty;
set(g.fig, 'position', pos);

% vertical alignment to bottom for text (isnumeric by ishanlde was changed here)
% ---------------------------------------
for index = 1:length(allhandlers)
	if ishandle(allhandlers{index})
		if strcmp(get(allhandlers{index}, 'style'), 'text')
            set(allhandlers{index}, 'unit', 'pixel');
			curpos = get(allhandlers{index}, 'position');
			curext = get(allhandlers{index}, 'extent');
			set(allhandlers{index}, 'position', [curpos(1) curpos(2)-4 curpos(3) curext(4)]);
            set(allhandlers{index}, 'unit', 'normalized');
		end
	end
end

% setting defaults colors
%------------------------
try, icadefs;
catch,
	GUIBACKCOLOR        =  [.8 .8 .8];
	GUIPOPBUTTONCOLOR   = [.8 .8 .8];
	GUITEXTCOLOR        = [0 0 0];
end

numobjects = cellfun(@ishandle, allhandlers); % (isnumeric by ishanlde was changed here)
allhandlersnum = [ allhandlers{numobjects} ];
hh = findobj(allhandlersnum,'flat', 'parent', g.fig, 'style', 'text');
%set(hh, 'BackgroundColor', get(g.fig, 'color'), 'horizontalalignment', 'left');
set(hh, 'Backgroundcolor', GUIBACKCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
try
set(g.fig, 'color',GUIBACKCOLOR );
catch
end
set(hh, 'horizontalalignment', g.horizontalalignment);

hh = findobj(allhandlersnum,'flat', 'style', 'edit');
set(hh, 'BackgroundColor', [1 1 1]); %, 'horizontalalignment', 'right');

hh =findobj(allhandlersnum,'flat', 'parent', g.fig, 'style', 'pushbutton');
comp = computer;
if length(comp) < 3 || ~strcmpi(comp(1:3), 'MAC') % this puts the wrong background on macs
    set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
    set(hh, 'foregroundcolor', GUITEXTCOLOR);
end
hh =findobj(allhandlersnum,'flat', 'parent', g.fig, 'style', 'popupmenu');
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlersnum,'flat', 'parent', g.fig, 'style', 'checkbox');
set(hh, 'backgroundcolor', GUIBACKCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlersnum,'flat', 'parent', g.fig, 'style', 'listbox');
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlersnum,'flat', 'parent', g.fig, 'style', 'radio');
set(hh, 'foregroundcolor', GUITEXTCOLOR);
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(g.fig, 'visible', 'on');

% screen position
% ---------------
if ~isempty(g.screenpos)
    pos = get(g.fig, 'position');
    if isnumeric(g.screenpos)
        set(g.fig, 'position', [ g.screenpos pos(3) pos(4)]);
    else
        screenSize = get(0, 'screensize');
        pos(1) = (screenSize(3)-pos(3))/2;
        pos(2) = (screenSize(4)-pos(4))/2+pos(4);
        set(g.fig, 'position', pos);
    end
end;

% set userdata and title
% ----------------------
if ~isempty(g.userdata), set(g.fig, 'userdata', g.userdata); end
if ~isempty(g.title   ), set(g.fig, 'name',     g.title   ); end

% transform selected text UI
% --------------------------
a = axes('position', [0 0 1 1]);
for iList = transformTextUIList
    set(allhandlers{iList}, 'unit', 'normalized');
    sTmp = get(allhandlers{iList},'string');
    pTmp = get(allhandlers{iList},'position');
    eTmp = get(allhandlers{iList},'extent');
    tTmp = get(allhandlers{iList},'tag');
    % Remove the UICONTROL
    delete(allhandlers{iList});
    % Replace it with a TEXT object
    allhandlers{iList} = text(pTmp(1),pTmp(2),sTmp, 'interpreter','latex', 'tag', tTmp);
end
set(a, 'visible', 'off');

return;

function [posx posy width height] = getcoord(geom1, geom2, coord1, sz, borders, spacing);

    coord2 = coord1+sz;
    borders(1:2) = borders(1:2)-spacing(1);
    borders(3:4) = borders(3:4)-spacing(2);

    % absolute positions
    posx   = coord1(1)/geom1;
    posy   = coord1(2)/geom2;
    posx2  = coord2(1)/geom1;
    posy2  = coord2(2)/geom2;
    width  = posx2-posx;
    height = posy2-posy;

    % add spacing
    posx   = posx+spacing(1)/2;
    width  = max(posx2-posx-spacing(1), 0.001);
    height = max(posy2-posy-spacing(2), 0.001);
    posy   = max(0, 1-posy2)+spacing(2)/2;

    % add border
    posx   = posx*(1-borders(1)-borders(2))+borders(1);
    posy   = posy*(1-borders(3)-borders(4))+borders(4);
    width  = width*( 1-borders(1)-borders(2));
    height = height*(1-borders(3)-borders(4));

function [posx posy width height] = getcoordold(geom1, geom2, coord1, sz);

    coord2 = coord1+sz;
    horiz_space  = 0.05/geom1;
    vert_space   = 0.05/geom2;
    horiz_border = min(0.1, 1/geom1)-horiz_space;
    vert_border  = min(0.2, 1.5/geom2)-vert_space;

    % absolute positions
    posx   = coord1(1)/geom1;
    posy   = coord1(2)/geom2;
    posx2  = coord2(1)/geom1;
    posy2  = coord2(2)/geom2;
    width  = posx2-posx;
    height = posy2-posy;

    % add spacing
    posx   = posx+horiz_space/2;
    width  = max(posx2-posx-horiz_space, 0.001);
    height = max(posy2-posy- vert_space, 0.001);
    posy   = max(0, 1-posy2)+vert_space/2;

    % add border
    posx   = posx*(1-horiz_border)+horiz_border/2;
    posy   = posy*(1- vert_border)+vert_border/2;
    width  = width*(1-horiz_border);
    height = height*(1-vert_border);

    %     posx   = coord1(1)/geom1+horiz_border*1/geom1/2;
%     posy   = 1-(coord1(2)/geom2+vert_border*1/geom2/2)-1/geom2;
%
%     posx2  = coord2(1)/geom1+horiz_border*1/geom1/2;
%     posy2  = 1-(coord2(2)/geom2+vert_border*1/geom2/2)-1/geom2;
%
%     width  = posx2-posx;
%     height = posy-posy2;

    %h = axes('unit', 'normalized', 'position', [ posx posy width height ]);
    %h = axes('unit', 'normalized', 'position', [ coordx/geom1 1-coordy/geom2-1/geom2 1/geom1 1/geom2 ]);

author: sccn

repo: eeglab

save_path: github-repos/MATLAB/sccn-eeglab


text:
clear all; close all; clc;
addpath('./toolbox');

% load feature trajectories
load('./data/homog.mat');

% define some variables
dtrng			= 5:0.5:25;
arng			= 0.45:0.02:0.85;
projmodel = 'homography';
a_con			= [];						% set to a value to constrain a

% run synchronization script
[a,dt] = sync(W1,W2,a_con,projmodel);

author: Sable

repo: mcbench-benchmarks


text:
function title = p01_title ( )

%*****************************************************************************80
%
%% P01_TITLE returns a title for problem 01.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Per-Olof Persson and Gilbert Strang,
%    A Simple Mesh Generator in MATLAB,
%    SIAM Review,
%    Volume 46, Number 2, June 2004, pages 329-345.
%
%  Parameters:
%
%    Output, string TITLE, a title for the problem.
%
  title = '#1: The unit circle.';

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function featAugm = get_augm_spatial_features_same_regr(feat)

% relative coord of 2 detections
deltaX = feat(:, 1);
deltaY = feat(:, 2);

dist_sq = deltaX.^2 +deltaY.^2;
dist = sqrt(dist_sq);

featAugm = cat(2, dist, dist_sq);
end

function angle = compute_angle(deltaX, deltaY)
angle = atan2(deltaY,deltaX);
angle = wrapMinusPiPifast(angle);
assert(all(angle <= pi) && all(angle >= -pi));
end

function a = wrap_angle(a)
larger = a > pi;
smaller = a < -pi;
a(larger)  = a(larger) - 2*pi;
a(smaller) = a(smaller)+ 2*pi;
end

author: eldar

repo: deepcut

save_path: github-repos/MATLAB/eldar-deepcut


text:
function[u] = DxT(v)

  u = DyT(v')';

return

author: xingchenzhang

repo: VIFB

save_path: github-repos/MATLAB/xingchenzhang-VIFB


text:
function test_vbgppcamv_cs(vbpca, ppca)

rand('state', 6);
randn('state', 6);

if nargin < 1
  vbpca = false;
end
if nargin < 2
  ppca = false;
end

inW = 1:200;
inX = 1:100;

M = length(inW);
N = length(inX);
D = 2;
X = zeros(D,N);
W = zeros(M,D);

% Covariance matrices
logthetaW = log(3);
logthetaX = log(3);

% Covariance functions
gpcovW = {@gpcovScale, @gpcovPP}; logthetaW = [3; logthetaW(:)];
%gpcovW = {@gpcovConstScale, 10, @gpcov};
%gpcovW = {@gpcov};
%gpcovX = {@gpcovScale, @gpcov}; logthetaX = [3; logthetaX(:)]
gpcovX = @gpcovPP;

% Generate latent variables
for d=1:D
  lsW = 10*ceil(exp(logthetaW(end)));
  lsX = 1*ceil(exp(logthetaX(end)));
  W(:,d) = filter(hamming(lsW), 1, randn(M,1));
  X(d,:) = filter(hamming(lsX), 1, randn(N,1));
  covfunW{d} = gpcovW;
  covfunX{d} = gpcovX;
  initthetaW{d} = logthetaW;
  initthetaX{d} = logthetaX;
end

W = W * diag( sqrt(M./rowsum(W.^2)) );
X = diag( sqrt(N./colsum(X.^2)) ) * X;

% $$$ tsplot(X)
% $$$ tsplot(W')
% $$$ return

% Generate data
Y = W*X;

% Noise level
s2 = 0.1;

% Make noisy observations
Yn = Y + sqrt(s2)*randn(M,N);  % noise
Ynm = Yn; Ynm(rand(M,N)<0.5) = nan; % missing values
Ytest = Yn; Ytest(~isnan(Ynm)) = nan;

% Learn GP PCA
maxiter = 1e1;
Q = vbgppcamv(Ynm,D,inW,inX,covfunW,initthetaW,covfunX,initthetaX, ...
              'maxiter',maxiter, 'pseudodensityx', 1, 'pseudodensityw', ...
              1, 'loglikelihood', true, 'updatehyper', 5, 'maxsearchx', ...
              3, 'maxsearchw', 3, 'updatepseudow', true, 'updatepseudox', ...
              true, 'checkgradx', true, 'checkgradw', false);

est_noise = 1/Q.tau
real_noise = s2

% Learn other models
if ppca
  Qppca = pca_full(Ynm,D,'maxiters',maxiter,'rotate2pca',true, ...
                   'algorithm','ppca');
  Yh_ppca = Qppca.A * Qppca.S + repmat(Qppca.Mu,1,N);
  testrmse_ppca = rmse(Ytest, Yh_ppca)
  noiselessrmse_ppca = rmse(Y, Yh_ppca)
end
if vbpca
  Qvbpca = vbpcamv(Ynm,M-1,'maxiters',maxiter);
  Yh_vbpca = Qvbpca.W * Qvbpca.X + repmat(Qvbpca.mu,1,N);
  testrmse_vbpca = rmse(Ytest, Yh_vbpca)
  noiselessrmse_vbpca = rmse(Y, Yh_vbpca)
end

Yh_gppca = Q.W * Q.X;
testrmse_gppca = rmse(Ytest, Yh_gppca)
noiselessrmse_gppca = rmse(Y, Yh_gppca)
figure
subplot(5,1,1);
plot(Y');
title('Original noiseless data')
subplot(5,1,2);
plot(Ynm');
title('Observed data')
subplot(5,1,3);
plot(Yh_gppca');
title('Reconstruction of GP VB PCA')
if vbpca
  subplot(5,1,4);
  plot(Yh_vbpca');
  title('Reconstruction of VB PCA')
end
if ppca
  subplot(5,1,5);
  plot(Yh_ppca');
  title('Reconstruction of PPCA')
end

vX = Q.varX;%diag(Q.CovX);
eX = 2*sqrt(vX);%sqrt( vX(reshape(1:(N*D), D, N)) );
vW = Q.varW;%diag(Q.CovW);
eW = 2*sqrt(vW);%sqrt( vW(reshape(1:(M*D), M, D)) );
tsgpplot(inX, Q.X', eX', 'pseudoinputs', {Q.pseudoX});
tsgpplot(inW, Q.W, eW, 'pseudoinputs', {Q.pseudoW});

thetaX1 = exp(Q.logthetaX{1})
thetaX2 = exp(Q.logthetaX{2})

% $$$ exp(Q.logthetaW{1})
% $$$ exp(Q.logthetaW{2})
% $$$
% $$$ exp(Q.logthetaX{1})
% $$$ exp(Q.logthetaX{2})

% $$$ % DEBUG: (test the effect of CovXp)
% $$$ X = zeros(D,N);
% $$$ varX = zeros(D,N);
% $$$ for d=1:D
% $$$   [X(d,:), varX(d,:)] = gppred(Q.pseudoX{d}, Q.Xp{d}, 0, inX, covfunX{d}, ...
% $$$                                Q.logthetaX{d});
% $$$ end
% $$$ varX;
% $$$ tsgpplot(inX, X', 2*sqrt(varX'), 'pseudoinputs', {Q.pseudoX});
% $$$ exp(Q.logthetaX{1})

% $$$ figure
% $$$ pcolor(Q.CovXp{1});
% $$$ figure
% $$$ pcolor(Q.CovWp{1});

return

%inv(funcK_noiseless(D,[10;10;1;10;10]));return
[p, loglike] = gplearn(ymv, @(p) funcK_noisy(D,p), [10;10;1;300;300;0.1])
%[p, loglike] = gplearn(ymv, @(p) funcK_noisy(D,p), [300;300;10;1;1])
%[p, loglike] = gplearn(ymv, @(p) funcK_noisy(D,p), [300;300;10;5;5;10;0.1])
%[p, loglike] = gplearn(ymv, @(p) funcK_noisy(D,p), [1000;100;0.1;3;100;0.059;1;0.1])
%[p, loglike] = gplearn(ymv, @(p) funcK_noisy(D,p), [100;100;3;100;0.059;1;0.1])

%p(1:4) = [2000;30;0.1;10]
%p(3) = 0.1;
[mu,Cov] = gppred(th,tmv,ymv, @(x1,x2) funcK_noiseless(gpdist(x1,x2),p(1:(end-1))), p(end));
yh = mnorm_rnd(mu, Cov, 10);

figure
clf
plot(th, yh, 'r')
figure
clf
gpplot(th,mu,Cov);
hold on
plot(tmv,ymv,'k+')

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function gpmapplot(coord, y)
x = coord';
% Use haversine distance measure
mydist = @(x1,x2) gpdist(x1,x2,@dist_coord);
D = mydist(x,x);
funcK = @(p) gpK(@() gpK_ratquad(D,p(1),p(2),p(3)), ...
                 @() gpK_noise(length(D),p(4)));
[p, loglike] = gplearn(y, funcK, [10;5;1;1e-5])
funcK_noiseless = @(D) gpK(@() gpK_ratquad(D, p(1),p(2),p(3)));
[LONI, LATI] = get_grid(40, 40);
xh = [LONI(:)';LATI(:)'];
[mu,Cov] = gppred(xh,x,y, @(x1,x2) funcK_noiseless(mydist(x1,x2)), p(4));
yh = mu;
ZI = reshape(yh, size(LONI));
plot_map
hold on
m_pcolor(LONI, LATI, ZI);

% Set nice colormap
colormap(climcolmap);
shading flat;
lim = max( -min(yh), max(yh) );
set(gca, 'clim', [-lim lim]);

return

% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ function D = gpdist(x1, x2, funcDist)
% $$$ if isvector(x1)
% $$$   x1 = x1(:)';
% $$$   x2 = x2(:)';
% $$$ end
% $$$ if nargin < 3
% $$$   funcDist = @(z1,z2) abs(z1-z2);
% $$$ end
% $$$ %[X2,X1] = meshgrid(x2,x1);
% $$$ n1 = size(x1,2);
% $$$ n2 = size(x2,2);
% $$$ D = zeros(n1,n2);
% $$$ for i=1:n1
% $$$   for j=1:n2
% $$$     D(i,j) = funcDist(x1(:,i),x2(:,j));
% $$$   end
% $$$ end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function d = dist_coord(coord1, coord2, varargin)
% d = dist(X1, X2)
% returns geographical distance in kilometers
% input vectors must be the same size and shape!!
% Approximates earth as a sphere.
% Distance is calculated for

if nargin > 2
  nargin
end

% Quadratic mean radius from Wikipedia
R_avg = 6372.795477598;

% Convert to radians
q = pi / 180;
lon1 = coord1(1,:) * q;
lat1 = coord1(2,:) * q;
lon2 = coord2(1,:) * q;
lat2 = coord2(2,:) * q;

% Distance calculation (haversine law)
dlat = lat2 - lat1;
dlon = lon2 - lon1;
a = sin(dlat/2).^2 + cos(lat1).*cos(lat2).*(sin(dlon/2).^2);
c = 2 * atan2(sqrt(a), sqrt(1-a));
d = R_avg * c;

return

% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ function [p,loglike] = gplearn(y, funcK, init_p)
% $$$ opts = optimset('GradObj', 'on');
% $$$ [p, negloglike] = fminunc(@(p) cost(y, funcK, p), init_p, opts);
% $$$ loglike = -negloglike;
% $$$
% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ function [mu,Cov] = gppred(xh, x, y, funcK, noise)
% $$$ if nargin == 1
% $$$   x = [];
% $$$   y = [];
% $$$ end
% $$$
% $$$ Kxhx = funcK(xh,x);
% $$$ invKxx = inv(funcK(x,x)+noise^2*eye(length(x)));
% $$$ Kxhxh = funcK(xh,xh);
% $$$ if isempty(Kxhx)
% $$$   Kxhx = 0;
% $$$ end
% $$$ if isempty(invKxx)
% $$$   invKxx = 0;
% $$$ end
% $$$ mu = Kxhx*invKxx*y;
% $$$ if isempty(mu)
% $$$   mu = zeros(size(xh));
% $$$ end
% $$$ Cov = Kxhxh - Kxhx*invKxx*Kxhx';

% $$$ % $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ % $$$ function gpplot(x, mu, Cov)
% $$$ % $$$ e = sqrt(diag(Cov));
% $$$ % $$$ X = [x(1:end); x(end:-1:1)];
% $$$ % $$$ Y = [mu(1:end)+e; mu(end:-1:1)-e(end:-1:1)];
% $$$ % $$$ C = [.65,.65,.65];
% $$$ % $$$ fill(X,Y,C,'EdgeColor',C);
% $$$ % $$$ hold on
% $$$ % $$$ plot(x,mu,'k');
% $$$
% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ function [K, dK] = gpK(varargin)
% $$$ K = 0;
% $$$ dK = [];
% $$$ for i=1:nargin
% $$$   if nargout == 1
% $$$     Knew = varargin{i}();
% $$$   else
% $$$     [Knew,dKnew] = varargin{i}();
% $$$     n = size(dKnew,3);
% $$$     if isempty(dK)
% $$$       dK = dKnew;
% $$$     else
% $$$       dK(:,:,end+(1:n)) = dKnew;
% $$$     end
% $$$   end
% $$$   K = K + Knew;
% $$$ end
% $$$
% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ function [K, dK] = gpK_noise(n, p1);
% $$$ K = p1^2 * eye(n);
% $$$ if nargout >= 2
% $$$   dK = K * 2/p1;
% $$$ end
% $$$
% $$$ % $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ % $$$ function [K, dK] = gpK_sqexp(D, p1, p2)
% $$$ % $$$ K = p1^2*exp(-0.5*D.^2/(p2^2));
% $$$ % $$$
% $$$ % $$$ if nargout >= 2
% $$$ % $$$   dK = zeros([size(D), 2]);
% $$$ % $$$   dK(:,:,1) = K .* 2 / p1;
% $$$ % $$$   dK(:,:,2) = K .* (-0.5*D.^2) .* (-2*p2^(-3));
% $$$ % $$$ end
% $$$
% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ function [K, dK] = gpK_decper(D, p1, p2, p3, p4)
% $$$ K = p1^2*exp(-0.5*(D.^2)/(p2^2)-2*sin(pi*D*p3).^2/(p4^2));
% $$$
% $$$ if nargout >= 2
% $$$   dK = zeros([size(D),4]);
% $$$   dK(:,:,1) = K .* 2 / p1;
% $$$   dK(:,:,2) = K .* (-0.5*D.^2) .* (-2*p2^(-3));
% $$$   dK(:,:,3) = K .* (-2*sin(pi*D*p3)*2) .* cos(pi*D*p3) .* (pi*D);
% $$$   dK(:,:,4) = K .* (-2*sin(pi*D*p3).^2) * (-2)*p4^(-3);
% $$$ end
% $$$
% $$$ % $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ % $$$ function [K,dK] = gpK_ratquad(D, p1, p2, p3)
% $$$ % $$$ %%% p3 = p3^2;
% $$$ % $$$ f = 1 + D.^2/(2*p3^2*p2^2);
% $$$ % $$$ K = p1^2*f.^(-p3^2);
% $$$ % $$$
% $$$ % $$$ if nargout >= 2
% $$$ % $$$   dK = zeros([size(D),3]);
% $$$ % $$$   dK(:,:,1) = K .* 2 / p1;
% $$$ % $$$   dK(:,:,2) = K .* (-p3^2).*f.^(-1) .* (-2).*D.^2/(2*p3^2)*p2^(-3);
% $$$ % $$$   dK(:,:,3) = K .* (-2*p3*log(f) + (-p3^2)./f.*D.^2/(2*p2^2) * (-2) * p3^(-3));
% $$$ % $$$ end
% $$$
% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ function [f, df] = cost(y,funcK,p)
% $$$ [K,dK] = funcK(p);
% $$$ [f,df] = loglikelihood(y,K,dK);
% $$$ f = -f;
% $$$ df = -df;
% $$$
% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ function [loglike, dloglike] = loglikelihood(y,K,dK)
% $$$ invK = inv(K);
% $$$ logdetK = log(det(K));
% $$$ if logdetK < -1e100;
% $$$   logdetK = -1e100;
% $$$ end
% $$$ n = length(y);
% $$$
% $$$ loglike = -0.5*y'*invK*y - 0.5*logdetK - 0.5*n*log(2*pi);
% $$$
% $$$ if nargout >= 2
% $$$   m = size(dK,3);
% $$$   dloglike = zeros(m,1);
% $$$   a = invK * y;
% $$$   W = a*a' - invK;
% $$$   for i = 1:m
% $$$     dloglike(i) = 0.5*sum(sum(W.*dK(:,:,i)));
% $$$   end
% $$$ end
% $$$
% $$$
% $$$ % $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ % $$$ function y = mnorm_rnd(mu, Cov, n)
% $$$ % $$$ m = max(length(mu), length(Cov));
% $$$ % $$$
% $$$ % $$$ opts.issym = true;
% $$$ % $$$ opts.isreal = true;
% $$$ % $$$ [V,D] = svd(Cov);
% $$$ % $$$ D(D<0) = 0;
% $$$ % $$$ D = sqrt(D);
% $$$ % $$$ A = V * D;
% $$$ % $$$
% $$$ % $$$ y = repmat(mu,1,n) + A*randn(m,n);

author: jluttine

repo: matlab

save_path: github-repos/MATLAB/jluttine-matlab


text:
function a = rutis5_eigen_right ( )

%*****************************************************************************80
%
%% RUTIS5_EIGEN_RIGHT returns the right eigenvectors of the RUTIS5 matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 June 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real A(4,4), the right eigenvector matrix.
%
  a = [ ...
   0.356841883715928, ...
   0.382460905084129, ...
   0.718205429169617, ...
   0.458877421126365; ...
  -0.341449101169948, ...
  -0.651660990948502, ...
   0.087555987078632, ...
   0.671628180850787; ...
   0.836677864423576, ...
  -0.535714651223808, ...
  -0.076460316709461, ...
  -0.084461728708607; ...
  -0.236741488801405, ...
  -0.376923628103094, ...
   0.686053008598214, ...
  -0.575511351279045 ]';

  return
end


text:
function hh = rotateXLabels( ax, angle, varargin )
%rotateXLabels: rotate any xticklabels
%
%   hh = rotateXLabels(ax,angle) rotates all XLabels on axes AX by an angle
%   ANGLE (in degrees). Handles to the resulting text objects are returned
%   in HH.
%
%   hh = rotateXLabels(ax,angle,param,value,...) also allows one or more
%   optional parameters to be specified. Possible parameters are:
%     'MaxStringLength'   The maximum length of label to show (default inf)
%
%   Examples:
%   >> bar( hsv(5)+0.05 )
%   >> days = {'Monday','Tuesday','Wednesday','Thursday','Friday'};
%   >> set( gca(), 'XTickLabel', days )
%   >> rotateXLabels( gca(), 45 )
%
%   See also: GCA, BAR

%   Copyright 2006-2013 The MathWorks Ltd.

error( nargchk( 2, inf, nargin ) );
if ~isnumeric( angle ) || ~isscalar( angle )
    error( 'RotateXLabels:BadAngle', 'Parameter ANGLE must be a scalar angle in degrees' )
end
angle = mod( angle, 360 );

[maxStringLength] = parseInputs( varargin{:} );

% Get the existing label texts and clear them
[vals, labels] = findAndClearExistingLabels( ax, maxStringLength );

% Create the new label texts
h = createNewLabels( ax, vals, labels, angle );

% Reposition the axes itself to leave space for the new labels
repositionAxes( ax );

% If an X-label is present, move it too
repositionXLabel( ax );

% Store angle
setappdata( ax, 'RotateXLabelsAngle', angle );

% Only send outputs if requested
if nargout
    hh = h;
end

%-------------------------------------------------------------------------%
    function [maxStringLength] = parseInputs( varargin )
        % Parse optional inputs
        maxStringLength = inf;
        if nargin > 0
            params = varargin(1:2:end);
            values = varargin(2:2:end);
            if numel( params ) ~= numel( values )
                error( 'RotateXLabels:BadSyntax', 'Optional arguments must be specified as parameter-value pairs.' );
            end
            if any( ~cellfun( 'isclass', params, 'char' ) )
                error( 'RotateXLabels:BadSyntax', 'Optional argument names must be specified as strings.' );
            end
            for pp=1:numel( params )
                switch upper( params{pp} )
                    case 'MAXSTRINGLENGTH'
                        maxStringLength = values{pp};

                    otherwise
                        error( 'RotateXLabels:BadParam', 'Optional parameter ''%s'' not recognised.', params{pp} );
                end
            end
        end
    end % parseInputs
%-------------------------------------------------------------------------%
    function [vals,labels] = findAndClearExistingLabels( ax, maxStringLength )
        % Get the current tick positions so that we can place our new labels
        vals = get( ax, 'XTick' );

        % Now determine the labels. We look first at for previously rotated labels
        % since if there are some the actual labels will be empty.
        ex = findall( ax, 'Tag', 'RotatedXTickLabel' );
        if isempty( ex )
            % Store the positions and labels
            labels = get( ax, 'XTickLabel' );
            if isempty( labels )
                % No labels!
                return
            else
                if ~iscell(labels)
                    labels = cellstr(labels);
                end
            end
            % Clear existing labels so that xlabel is in the right position
            set( ax, 'XTickLabel', {}, 'XTickMode', 'Manual' );
            setappdata( ax, 'OriginalXTickLabels', labels );
        else
            % Labels have already been rotated, so capture them
            labels = getappdata( ax, 'OriginalXTickLabels' );
            set(ex, 'DeleteFcn', []);
            delete(ex);
        end
        % Limit the length, if requested
        if isfinite( maxStringLength )
            for ll=1:numel( labels )
                if length( labels{ll} ) > maxStringLength
                    labels{ll} = labels{ll}(1:maxStringLength);
                end
            end
        end

    end % findAndClearExistingLabels
%-------------------------------------------------------------------------%
    function restoreDefaultLabels( ax )
        % Restore the default axis behavior
        removeListeners( ax );

        % Try to restore the tick marks and labels
        set( ax, 'XTickMode', 'auto', 'XTickLabelMode', 'auto' );
        rmappdata( ax, 'OriginalXTickLabels' );

        % Try to restore the axes position
        if isappdata( ax, 'OriginalAxesPosition' )
            set( ax, 'Position', getappdata( ax, 'OriginalAxesPosition' ) );
            rmappdata( ax, 'OriginalAxesPosition' );
        end
    end
%-------------------------------------------------------------------------%
    function textLabels = createNewLabels( ax, vals, labels, angle )
        % Work out the ticklabel positions
        zlim = get(ax,'ZLim');
        z = zlim(1);

        % We want to work in normalised coords, but this doesn't print
        % correctly. Instead we have to work in data units even though it
        % makes positioning hard.
        ylim = get( ax, 'YLim' );
        if strcmpi( get( ax, 'XAxisLocation' ), 'Top' )
            y = ylim(2);
        else
            y = ylim(1);
        end

        % Now create new text objects in similar positions.
        textLabels = -1*ones( numel( vals ), 1 );
        for ll=1:numel(vals)
            textLabels(ll) = text( ...
                'Units', 'Data', ...
                'Position', [vals(ll), y, z], ...
                'String', labels{ll}, ...
                'Parent', ax, ...
                'Clipping', 'off', ...
                'Rotation', angle, ...
                'Tag', 'RotatedXTickLabel', ...
                'UserData', vals(ll));
        end
        % So that we can respond to CLA and CLOSE, attach a delete
        % callback. We only attach it to one label to save massive numbers
        % of callbacks during axes shut-down.
        set(textLabels(end), 'DeleteFcn', @onTextLabelDeleted);

        % Now copy font properties into the texts
        updateFont();
        % Update the alignment of the text
        updateAlignment();

    end % createNewLabels

%-------------------------------------------------------------------------%
    function repositionAxes( ax )
        % Reposition the axes so that there's room for the labels
        % Note that we only do this if the OuterPosition is the thing being
        % controlled
        if ~strcmpi( get( ax, 'ActivePositionProperty' ), 'OuterPosition' )
            return;
        end

        % Work out the maximum height required for the labels
        labelHeight = getLabelHeight(ax);

        % Remove listeners while we mess around with things, otherwise we'll
        % trigger redraws recursively
        removeListeners( ax );

        % Change to normalized units for the position calculation
        oldUnits = get( ax, 'Units' );
        set( ax, 'Units', 'Normalized' );

        % Not sure why, but the extent seems to be proportional to the height of the axes.
        % Correct that now.
        set( ax, 'ActivePositionProperty', 'Position' );
        pos = get( ax, 'Position' );
        axesHeight = pos(4);
        % Make sure we don't adjust away the axes entirely!
        heightAdjust = min( (axesHeight*0.9), labelHeight*axesHeight );

        % Move the axes
        if isappdata( ax, 'OriginalAxesPosition' )
            pos = getappdata( ax, 'OriginalAxesPosition' );
        else
            pos = get(ax,'Position');
            setappdata( ax, 'OriginalAxesPosition', pos );
        end
        if strcmpi( get( ax, 'XAxisLocation' ), 'Bottom' )
            % Move it up and reduce the height
            set( ax, 'Position', pos+[0 heightAdjust 0 -heightAdjust] )
        else
            % Just reduce the height
            set( ax, 'Position', pos+[0 0 0 -heightAdjust] )
        end
        set( ax, 'Units', oldUnits );
        set( ax, 'ActivePositionProperty', 'OuterPosition' );

        % Make sure we find out if axes properties are changed
        addListeners( ax );

    end % repositionAxes

%-------------------------------------------------------------------------%
    function repositionXLabel( ax )
        % Try to work out where to put the xlabel
        removeListeners( ax );
        labelHeight = getLabelHeight(ax);

        % Use the new max extent to move the xlabel. We may also need to
        % move the title
        xlab = get(ax,'XLabel');
        titleh = get( ax, 'Title' );
        set( [xlab,titleh], 'Units', 'Normalized' );
        if strcmpi( get( ax, 'XAxisLocation' ), 'Top' )
            titleExtent = get( xlab, 'Extent' );
            set( xlab, 'Position', [0.5 1+labelHeight-titleExtent(4) 0] );
            set( titleh, 'Position', [0.5 1+labelHeight 0] );
        else
            set( xlab, 'Position', [0.5 -labelHeight 0] );
            set( titleh, 'Position', [0.5 1 0] );
        end
        addListeners( ax );
    end % repositionXLabel

%-------------------------------------------------------------------------%
    function height = getLabelHeight(ax)
        height = 0;
        textLabels = findall( ax, 'Tag', 'RotatedXTickLabel' );
        if isempty(textLabels)
            return;
        end
        oldUnits = get( textLabels(1), 'Units' );
        set( textLabels, 'Units', 'Normalized' );
        for ll=1:numel(vals)
            ext = get( textLabels(ll), 'Extent' );
            if ext(4) > height
                height = ext(4);
            end
        end
        set( textLabels, 'Units', oldUnits );
    end % getLabelExtent

%-------------------------------------------------------------------------%
    function updateFont()
        % Update the rotated text fonts when the axes font changes
        properties = {
            'FontName'
            'FontSize'
            'FontAngle'
            'FontWeight'
            'FontUnits'
            };
        propertyValues = get( ax, properties );
        textLabels = findall( ax, 'Tag', 'RotatedXTickLabel' );
        set( textLabels, properties, propertyValues );
    end % updateFont

    function updateAlignment()
        textLabels = findall( ax, 'Tag', 'RotatedXTickLabel' );
        angle = get( textLabels(1), 'Rotation' );
        % Depending on the angle, we may need to change the alignment. We change
        % alignments within 5 degrees of each 90 degree orientation.
        if strcmpi( get( ax, 'XAxisLocation' ), 'Top' )
            if 0 <= angle && angle < 5
                set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Bottom' );
            elseif 5 <= angle && angle < 85
                set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Bottom' );
            elseif 85 <= angle && angle < 95
                set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Middle' );
            elseif 95 <= angle && angle < 175
                set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Top' );
            elseif 175 <= angle && angle < 185
                set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Top' );
            elseif 185 <= angle && angle < 265
                set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Top' );
            elseif 265 <= angle && angle < 275
                set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Middle' );
            elseif 275 <= angle && angle < 355
                set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Bottom' );
            else % 355-360
                set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Bottom' );
            end
        else
            if 0 <= angle && angle < 5
                set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Top' );
            elseif 5 <= angle && angle < 85
                set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Top' );
            elseif 85 <= angle && angle < 95
                set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Middle' );
            elseif 95 <= angle && angle < 175
                set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Bottom' );
            elseif 175 <= angle && angle < 185
                set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Bottom' );
            elseif 185 <= angle && angle < 265
                set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Bottom' );
            elseif 265 <= angle && angle < 275
                set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Middle' );
            elseif 275 <= angle && angle < 355
                set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Top' );
            else % 355-360
                set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Top' );
            end
        end
    end

%-------------------------------------------------------------------------%
    function onAxesFontChanged( ~, ~ )
        updateFont();
        repositionAxes( ax );
        repositionXLabel( ax );
    end % onAxesFontChanged

%-------------------------------------------------------------------------%
    function onAxesPositionChanged( ~, ~ )
        % We need to accept the new position, so remove the appdata before
        % redrawing
        if isappdata( ax, 'OriginalAxesPosition' )
            rmappdata( ax, 'OriginalAxesPosition' );
        end
        if isappdata( ax, 'OriginalXLabelPosition' )
            rmappdata( ax, 'OriginalXLabelPosition' );
        end
        repositionAxes( ax );
        repositionXLabel( ax );
    end % onAxesPositionChanged

%-------------------------------------------------------------------------%
    function onXAxisLocationChanged( ~, ~ )
        updateAlignment();
        repositionAxes( ax );
        repositionXLabel( ax );
    end % onXAxisLocationChanged

%-------------------------------------------------------------------------%
    function onAxesLimitsChanged( ~, ~ )
        % The limits have moved, so make sure the labels are still ok
        textLabels = findall( ax, 'Tag', 'RotatedXTickLabel' );
        xlim = get( ax, 'XLim' );
        ylim = get( ax, 'YLim' );
        if strcmpi( get( ax, 'XAxisLocation'), 'Bottom' )
            pos = [0 ylim(1)];
        else
            pos = [0 ylim(2)];
        end
        for tt=1:numel( textLabels )
            xval = get( textLabels(tt), 'UserData' );
            pos(1) = xval;
            % If the tick is off the edge, make it invisible
            if xval<xlim(1) || xval>xlim(2)
                set( textLabels(tt), 'Visible', 'off', 'Position', pos )
            elseif ~strcmpi( get( textLabels(tt), 'Visible' ), 'on' )
                set( textLabels(tt), 'Visible', 'on', 'Position', pos )
            else
                % Just set the position
                set( textLabels(tt), 'Position', pos );
            end
        end

        repositionXLabel( ax );
    end % onAxesPositionChanged

%-------------------------------------------------------------------------%
    function onTextLabelDeleted( ~, ~ )
        % The final text label has been deleted. This is likely from a
        % "cla" or "close" call, so we should remove all of our dirty
        % hacks.
        restoreDefaultLabels(ax);
    end

%-------------------------------------------------------------------------%
    function addListeners( ax )
        % Create listeners. We store the array of listeners in the axes to make
        % sure that they have the same life-span as the axes they are listening to.
        axh = handle( ax );
        listeners = [
            handle.listener( axh, findprop( axh, 'FontName' ), 'PropertyPostSet', @onAxesFontChanged )
            handle.listener( axh, findprop( axh, 'FontSize' ), 'PropertyPostSet', @onAxesFontChanged )
            handle.listener( axh, findprop( axh, 'FontWeight' ), 'PropertyPostSet', @onAxesFontChanged )
            handle.listener( axh, findprop( axh, 'FontAngle' ), 'PropertyPostSet', @onAxesFontChanged )
            handle.listener( axh, findprop( axh, 'FontUnits' ), 'PropertyPostSet', @onAxesFontChanged )
            handle.listener( axh, findprop( axh, 'OuterPosition' ), 'PropertyPostSet', @onAxesPositionChanged )
            handle.listener( axh, findprop( axh, 'XLim' ), 'PropertyPostSet', @onAxesLimitsChanged )
            handle.listener( axh, findprop( axh, 'YLim' ), 'PropertyPostSet', @onAxesLimitsChanged )
            handle.listener( axh, findprop( axh, 'XAxisLocation' ), 'PropertyPostSet', @onXAxisLocationChanged )
            ];
        setappdata( ax, 'RotateXLabelsListeners', listeners );
    end % addListeners

%-------------------------------------------------------------------------%
    function removeListeners( ax )
        % Rempove any property listeners whilst we are fiddling with the axes
        if isappdata( ax, 'RotateXLabelsListeners' )
            delete( getappdata( ax, 'RotateXLabelsListeners' ) );
            rmappdata( ax, 'RotateXLabelsListeners' );
        end
    end % removeListeners

end % EOF

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function lam_msg = CPD_to_lambda_msg(CPD, msg_type, n, ps, msg, p)
% CPD_TO_LAMBDA_MSG Compute lambda message (gaussian)
% lam_msg = compute_lambda_msg(CPD, msg_type, n, ps, msg, p)
% Pearl p183 eq 4.52

switch msg_type
 case 'd',
  error('gaussian_CPD can''t create discrete msgs')
 case 'g',
  self_size = CPD.sizes(end);
  if all(msg{n}.lambda.precision == 0) % no info to send on
    lam_msg.precision = zeros(self_size);
    lam_msg.info_state = zeros(self_size, 1);
    return;
  end
  cpsizes = CPD.sizes(CPD.cps);
  dpval = 1;
  Q = CPD.cov(:,:,dpval);
  Sigmai = Q;
  wmu = zeros(self_size, 1);
  for k=1:length(ps)
    pk = ps(k);
    if pk ~= p
      bk = block(k, cpsizes);
      Bk = CPD.weights(:, bk, dpval);
      m = msg{n}.pi_from_parent{k};
      Sigmai = Sigmai + Bk * m.Sigma * Bk';
      wmu = wmu + Bk * m.mu; % m.mu = u(k)
    end
  end
  % Sigmai = Q + sum_{k \neq i} B_k Sigma_k B_k'
  i = find_equiv_posns(p, ps);
  bi = block(i, cpsizes);
  Bi = CPD.weights(:,bi, dpval);

  if 0
  P = msg{n}.lambda.precision;
  if isinf(P) % inv(P)=Sigma_lambda=0
    precision_temp = inv(Sigmai);
    lam_msg.precision = Bi' * precision_temp * Bi;
    lam_msg.info_state = precision_temp * (msg{n}.lambda.mu - wmu);
  else
    A = inv(P + inv(Sigmai));
    precision_temp = P + P*A*P;
    lam_msg.precision = Bi' * precision_temp * Bi;
    self_size = length(P);
    C = eye(self_size) + P*A;
    z = msg{n}.lambda.info_state;
    lam_msg.info_state = C*z - C*P*wmu;
  end
  end

  if isinf(msg{n}.lambda.precision)
    Sigma_lambda = zeros(self_size, self_size); % infinite precision => 0 variance
    mu_lambda = msg{n}.lambda.mu; % observed_value;
  else
    Sigma_lambda = inv(msg{n}.lambda.precision);
    mu_lambda = Sigma_lambda * msg{n}.lambda.info_state;
  end
  precision_temp = inv(Sigma_lambda + Sigmai);
  lam_msg.precision = Bi' * precision_temp * Bi;
  lam_msg.info_state = Bi' * precision_temp * (mu_lambda - wmu);
end

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function gprs = printGPRForRxns(model,rxnIDs, printLevel)
% Print the GPRs (in textual format) for the given RxnIDs
% USAGE:
%
%    gprs = printGPRForRxns(model,rxnID)
%
% INPUTS:
%    model:             The model to retrieve the GPR rules from
%    rxnIDs:            The reaction IDs to obtain the GPR rules for
%
% OPTIONAL INPUTS:
%
%    printLevel:        Whether to print out the GPRs. If printLevel is 0,
%                       the function will only return the Strings in a cell
%                       array.
%
% OUTPUTS:
%
%    gprs:              The textual GPR Rules
%
% Authors:
%
%    Thomas Pfau Dec 2017

if ~isnumeric(rxnIDs)
    rxnPos = findRxnIDs(model,rxnIDs);
else
    %We got a list of positions
    rxnPos = rxnIDs;
    if any(rxnPos > numel(model.rxns))
        error('Some indices provided are larger than the number of reactions.');
    end
end

if any(rxnPos == 0)
    error('The following reaction IDs are not part of this model:\n%s\n',strjoin(rxnIDs(rxnPos==0),'; '));
end

if ~exist('printLevel','var')
    printLevel = 1;
end

if isfield(model,'grRules')
    gprs = model.grRules(rxnPos);
else
    if isfield(model,'rules') && isfield(model,'genes')
        gprs = strrep(model.rules(rxnPos),'|','or');
        gprs = strrep(gprs,'&','and');
        gprs = regexprep(gprs,'x\(([0-9]+)\)','${model.genes{str2num($1)}}');
    else
        gprs = repmat({''},size(rxnPos));
    end
end
rxnNames = model.rxns(rxnPos);
maxRxnLength = num2str(max(cellfun(@length,rxnNames))+2);

if printLevel > 0
    for i = 1:numel(rxnPos)
        fprintf(['%-' maxRxnLength 's:\t%s\n'],rxnNames{i},gprs{i});
    end
end

author: opencobra

repo: cobratoolbox


text:
function [text,AIC,BIC]=igarch_display(parameters,ll,vcv,data,p,q,errorType,igarchType,constant)
% Display parameters, tstats, pvals, log-likelihood and AIC/BIC
% from estimates of a IGARCH(P,O,Q) produced using igarch
%
% USAGE:
%   [TEXT] = igarch_display(PARAMETERS,LL,VCV,DATA,P,Q)
%   [TEXT,AIC,BIC] = igarch_display(PARAMETERS,LL,VCV,DATA,P,Q,ERRORTYPE,IGARCHTYE,CONSTANT)
%
% INPUTS:
%   PARAMETERS    - A CONSTANT+p+q-1 column vector of parameters with
%                   [omega alpha(1) ... alpha(p) beta(1) ... beta(q-1) [nu lambda]]'.
%   LL            - The log likelihood at the optimum
%   VCV           - Non-robust standard errors (inverse Hessian)
%   DATA          - A column of mean zero data
%   P             - Positive, scalar integer representing the number of
%                   symmetric innovations
%   Q             - Non-negative, scalar integer representing the number
%                   of lags of conditional variance (0 for ARCH)
%   ERRORTYPE     - [OPTIONAL] The error distribution used, valid types are:
%                     'NORMAL'    - Gaussian Innovations [DEFAULT]
%                     'STUDENTST' - T distributed errors
%                     'GED'       - Generalized Error Distribution
%                     'SKEWT'     - Skewed T distribution
%   IGARCHTYPE     - [OPTIONAL] The type of variance process, either
%                     1 - Model evolves in absolute values
%                     2 - Model evolves in squares [DEFAULT]
%   CONSTANT      - [OPTIONAL] Logical value indicating whether model
%                     should include a constant.  Default is true
%                     (include)
%
% OUTPUTS:
%   TEXT          - Character matrix with the formatted parameters of the model
%   AIC           - Aikake Information Criteria computed from the LL
%   BIC           - Schwartz/Bayesian Information Criteria computed from the LL
%
%  See also IGARCH

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

%%%%%%%%%%%%%%%%%%%%%%%%%%
% PARAMETER CHECKING
%%%%%%%%%%%%%%%%%%%%%%%%%%
switch nargin
    case 6
        igarchType=2;
        errorType='NORMAL';
        constant = 1;
    case 7
        igarchType=2;
        constant = 1;
    case 8
        constant = 1;
    case 9
        % Nothing
    otherwise
        error('5 to 8 inputs required')
end
if isempty(igarchType)
    igarchType=2;
end
if isempty(errorType)
    errorType='NORMAL';
end
if isempty(constant)
    constant = 1;
end
% parameters, N by 1, real
if any(~isreal(parameters)) || size(parameters,2)~=1
    error('PARAMETERS must be a column vector.')
end
% LL
if ~isscalar(ll) || ~isreal(ll)
    error('LL must be a scalar.')
end
% VCV
if size(vcv,2)~=size(vcv,1) || any(min(eig(vcv))<=0) || size(vcv,1)~=length(parameters)
    error('VCV must be a square positive definite matrix compatible with PARAMETERS.')
end
% data
if any(~isreal(data)) || size(data,2)~=1
    error('DATA must be a T by 1 column vector.')
end
% p
if ~isscalar(p) || p<1 || floor(p)~=p
    error('P must be a postitive scalar integer')
end
% q
if ~isscalar(q) || q<0 || floor(q)~=q
    error('Q must be a positive scalar integer')
end
% errorType
if ~ischar(errorType)
    errorType=[];
end
switch errorType
    case 'NORMAL'
        errorType=1;
        extraP=0;
    case 'STUDENTST'
        errorType=2;
        extraP=1;
    case 'GED'
        errorType=3;
        extraP=1;
    case 'SKEWT'
        errorType=4;
        extraP=2;
    otherwise
        error('ERRORTYPE is not one of the supported distributions')
end
% igarchType
if ~ismember(igarchType,[1 2])
    error('IGARCHTYPE must be either 1 or 2')
end
if length(parameters)~=(constant+p+q-1+extraP)
    error('Size of PARAMETERS is not compatible with input P, O, Q')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%
% PARAMETER CHECKING
%%%%%%%%%%%%%%%%%%%%%%%%%%

if igarchType==1
    model_name = ['IAVARCH(' num2str(p) ',' num2str(q) ')'];
else
    model_name = ['IGARCH(' num2str(p) ',' num2str(q) ')'];
end

parameters_text=num2str(parameters,'%4.4f');
stderr=sqrt(diag(vcv));
stderr_text=num2str(stderr,'%4.4f');
tstats=parameters./stderr;
tstats_text=num2str(tstats,'%4.4f');
pvals=2-2*normcdf(abs(tstats));
pvals_text=num2str(pvals,'%4.4f');

% Add in the extra beta
finalBetaPos = constant+p+q;
archParameters = parameters(constant+1:constant+p+q-1);
finalBeta = 1 - sum(archParameters);

n = length(parameters);

parameters_text=[parameters_text(1:finalBetaPos-1,:);
    num2str(finalBeta,'%4.4f');
    parameters_text(finalBetaPos+1:n,:)];
stderr_text=[stderr_text(1:finalBetaPos-1,:);
    repmat('-',1,size(stderr_text,2));
    stderr_text(finalBetaPos+1:n,:)];
tstats_text=[tstats_text(1:finalBetaPos-1,:);
    repmat('-',1,size(tstats_text,2));
    tstats_text(finalBetaPos+1:n,:)];
pvals_text=[pvals_text(1:finalBetaPos-1,:);
    repmat('-',1,size(pvals_text,2));
    pvals_text(finalBetaPos+1:n,:)];

T=length(data);
AIC = -ll/T+2*length(parameters)/T;
BIC = -ll/T+log(T)*length(parameters)/T;

% Format the output
text=[];
text{1,1}= ' ';
text{2,1}= ' ';
text{3,1}=repmat('-',1,50);
text{4,1}=model_name;
text{5,1}=repmat('-',1,50);
text{6,1}=' ';
text{7,1}=['Loglikelihood: ' sprintf('%1.2f',ll)];
text{8,1}=['AIC: ' sprintf('%1.4f',AIC)];
text{9,1}=['BIC: ' sprintf('%1.4f',BIC)];
text{10,1}=' ';

for i=1:size(text,1);
    disp(text{i,1})
end

% Format the parameter table, need to right align everything
K=size(parameters_text,1);
for i=1:K
    N=size(parameters_text,2);
    if any(parameters_text(i,:)==' ')
        numSpace=sum(parameters_text(i,:)==' ');
        parameters_text(i,:)=[repmat(' ',1,numSpace) parameters_text(i,1:N-numSpace)];
    end
    N=size(stderr_text,2);
    if any(stderr_text(i,:)==' ')
        numSpace=sum(stderr_text(i,:)==' ');
        stderr_text(i,:)=[repmat(' ',1,numSpace) stderr_text(i,1:N-numSpace)];
    end
    N=size(tstats_text,2);
    if any(tstats_text(i,:)==' ')
        numSpace=sum(tstats_text(i,:)==' ');
        tstats_text(i,:)=[repmat(' ',1,numSpace) tstats_text(i,1:N-numSpace)];
    end
    N=size(pvals_text,2);
    if any(pvals_text(i,:)==' ')
        numSpace=sum(pvals_text(i,:)==' ');
        pvals_text(i,:)=[repmat(' ',1,numSpace) pvals_text(i,1:N-numSpace)];
    end
end
% Append column labels
labels={' Parameters','   Std. Err.','     T-stat','      P-val'};
cols = {parameters_text,stderr_text,tstats_text,pvals_text};
for i=1:length(labels);
    text1=labels{i};
    text2=cols{i};
    maxcols=max(size(text1,2),size(text2,2));
    if size(text1,2)<maxcols
        labels{i} = [repmat(' ',1,maxcols-size(text1,2)) text1 ];
    end
    if size(text2,2)<maxcols
        cols{i} = [repmat(' ',size(text2,1),maxcols-size(text2,2)) text2 ];
    end
end

% Finally variable names
variable_names=cell(length(parameters),1);
variable_names{1}='omega';
index=2;
for i=1:p
    variable_names{index}=['alpha(' num2str(i) ')'];
    index=index+1;
end
for i=1:q
    variable_names{index}=['beta(' num2str(i) ')'];
    index=index+1;
end
if errorType>1
    variable_names{index}='nu';
    index=index+1;
end
if errorType==4
    variable_names{index}='lambda';
end

maxVarNameLength=max(cellfun('length',variable_names));
for i=1:length(variable_names)
    variable_names{i} = [repmat(' ',1,maxVarNameLength-length(variable_names{i})) variable_names{i}];
end
variable_names=cell2mat(variable_names(:));

% Output the parameters
outmat=strvcat(' ',variable_names); %#ok<*VCAT>
for i=1:4
    outmat=[outmat repmat('  ',size(outmat,1),1) strvcat(labels{i},cols{i})]; %#ok<AGROW>
end

text2=[];
for i=1:length(text)
    text2=strvcat(text2,text{i});
end
text=strvcat(text2,outmat);

disp(outmat)

author: bashtage

repo: mfe-toolbox


text:
%         TestTags are useful for identifying what kind of test you're coding, as you might only want to run certain tests that are related.
classdef (TestTags = {'T1', 'Demo', 'Integration'}) fitT1_IR_Test < matlab.unittest.TestCase % It's convention to name the test file (filename being tested)_Test.m

    properties % Test class variabes; useful for common parameters between tests.
        IRdata
        Mask
        TI
    end

    methods (TestClassSetup) % Usually used to setup common testing variables, or loading data.
        function load_test_data(testCase)
            testData = load('Data/IR_demo/IR_demo.mat'); % Place full relative path, in case the file goes missing or there is a conflict

            % Set class properties
            testCase.IRdata = testData.IRdata;
            testCase.Mask = testData.Mask;
            testCase.TI = testData.TI;

        end
    end

    methods (TestClassTeardown) % This could be used to delete any files created during the test execution.
    end

    methods (Test) % Each test is it's own method function, and takes testCase as an argument.

        function test_IRfun_returns_near_expected_median_of_test_data(testCase) % Use very descriptive test method names
            %% Prepare for test
            %
            method='Magnitude';

            T1 = zeros(size(testCase.IRdata,1), size(testCase.IRdata,2));

            %% Fit voxels
            %
            for xx = 1:size(testCase.IRdata,1)
                for yy = 1:size(testCase.IRdata,2)

                    if testCase.Mask(xx,yy) % Skip masked voxels
                        [T1(xx, yy), ~, ~, ~] = fitT1_IR(testCase.IRdata(xx, yy, :), testCase.TI, method);
                    end

                end
            end

            %% Check the fit
            %

            % Mask data
            maskedT1 = T1(:).*testCase.Mask(:);
            maskedT1(maskedT1 == 0) =[];

            expectedMedian = 748; % in s, Value was identified under stable working conditions.
            actualMedian = median(maskedT1(:));

            % Assert functions are the core of unit tests; if it fails,
            % test log will return failed tests and details.
            assertTrue(testCase, abs(actualMedian-expectedMedian) < 50); % This will alert us if a code change ever produces a fit
                                                                         % with a median lower than 700 or greater than 800, signaling
                                                                         % a potential bug.
        end
    end

end

author: qMRLab

repo: qMRLab

save_path: github-repos/MATLAB/qMRLab-qMRLab


text:
function [model] = linearsvm(X, Y, C, dual)
  % [model] = linearsvm(X, Y, C, dualparam);
  % Build linear svm using liblinear package
  % X: the instance X feature sparse matrix
  % Y: the label Y each column is  a label, the negative class could be -1 or 0
  % C: the trade-off parameter of SVM
  % dual: whether or not use primal or dual solver (optional)
  %
  %  model: the constructed SVM classifier
  %  to obtain prediction score of test set X of n test instances
  %      prediction_score = X * model.W + repmat(model.bias, n, 1)

  if nargin < 4
	dual = 0;
  end

  param.alpha = C;
  %C = param.alpha;
  [n, T] = size(Y);
  [n, d] = size(X);

%   if issparse(Y)
%     Y = full(Y);
%   end
  if ~issparse(X)
      X = sparse(X);
  end

  %Y(Y==0)=-1;
  if dual==0
  paramstr = sprintf('-s 2 -c %f -B 1 -q', param.alpha)
  else
  paramstr = sprintf('-s 1 -c %f -B 1 -q', param.alpha)
  end

%% ===PLEASE uncomment the following code if you use liblinear <1.5 ======
%   if dual==0
%   	paramstr = sprintf('-s 2 -c %f', param.alpha)
%   else
%   	paramstr = sprintf('-s 1 -c %f', param.alpha)
%   end
%% =======================================================================

  W = zeros(d,T);
  bias = zeros(1,T);

  for t=1:T
    t
    y = -1*ones(n, 1);
    y(Y(:, t)==1)=1;
    mod_ind = train(y, X, paramstr);
    % fprintf('the size of vector w is %d: %d\n', length(mod_ind.w), d);
    W(:, t) = mod_ind.w(1:d);
    bias(t) = mod_ind.w(end);
    if mod_ind.Label(1)==-1
       W(:,t)= -W(:,t);
       bias(t) = -bias(t);
    end
  end
  model.W = W;
  model.bias = bias;
  model.method = 'svm';
  model.param = param;

repo: TADW


text:
function []=olc1()
n1=128;
K=zeros(n1);
for i=1:n1
    for j=i:n1
        K(i,j)=1;
    end
end
for i=2:n1
    K(i,i-1)=(-n1)+(i-1);
end

hgot=getappdata(0,'H_pass');
k1=char(hgot);
msgbox('Click on the folder saved by the name Test S');
pause(2);
TP = uigetdir('C:', 'Select path where Query image is to be searched');
%TP=char(TP);
l3=strcat(TP,'\',k1,'.pgm');
J=imread(l3);
J=imresize(J,[128 128]);
I=zeros(n1);
for i=1:n1
    L=J(:,i);
    L=double(L);
    M=K*L;
    I(:,i)=M;
end
A=K*I*K';
A=mat2gray(A,[0 63]);
%figure, imshow(A);
Y=reshape(A,n1*n1,1);
M=zeros(n1,1);
I1=zeros(n1);
nr=zeros(60,2);
msgbox('Click on the folder saved by the name S');
pause(2);
l32 = uigetdir('C:', 'Select path where Database image is to be searched');
for w=1:100
    w1=num2str(w);
    w2=strcat(l32,'\',w1,'.pgm');
S=imread(w2);
S=imresize(S,[128 128]);

for j=1:n1
    L1=S(:,j);
    L1=double(L1);
    M=K*L1;
    I1(:,j)=M;
end

B=K*I1*K';
B=mat2gray(B,[0 63]);
Z=reshape(B,n1*n1,1);
T=norm(Y-Z);

nr(w,1)=T;
nr(w,2)=w;
end
 [m q]=size(nr);
pa=m+1;
for i1=2:pa
    for i2=(pa-1):-1:i1
     if (nr(i2-1,1)>nr(i2,1))
         l1=nr(i2-1,1);
         l2=nr(i2-1,2);
         nr(i2-1,1)=nr(i2,1);
         nr(i2-1,2)=nr(i2,2);
         nr(i2,1)=l1;
         nr(i2,2)=l2;
     end
    end
end
 figure;
 subplot(1,2,1); imshow(l3); title('Provided Image');

 for i7=1:m
    n12=i7;
    j=nr(i7,2);
    j=num2str(j);
    str=strcat(l32,'\',j,'.pgm');
    I=imread(str);
    %b1=num2str(i7);
    str1=strcat('Image recognized From Database');
    subplot(1,2,2);imshow(I);title(str1);% Displaays Similar images
    if (n12>1)
        break;
    end
 end
return


text:
% ------------------------------------------------------------------------
%  Copyright (C)
%  Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain
%  University of California Berkeley (UCB) - USA
%
%  Jordi Pont-Tuset <jordi.pont@upc.edu>
%  Pablo Arbelaez <arbelaez@berkeley.edu>
%  June 2014
% ------------------------------------------------------------------------
% This file is part of the MCG package presented in:
%    Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J,
%    "Multiscale Combinatorial Grouping,"
%    Computer Vision and Pattern Recognition (CVPR) 2014.
% Please consider citing the paper if you use this code.
% ------------------------------------------------------------------------
function params = sf_mUCM_multi_3sc_u_4r_12k_params(  )

% Pascal database
params.database = 'pascal2012';

% GT sets for training
params.gt_set_pareto  = 'train2012';
params.gt_set_ranking = 'train2012';

% GT set for testing
params.gt_set_test = 'val2012';

% String identifying the raw hierarchy files
params.raw_hiers = 'sf_mUCM';

% String identifying the current setup (hiers and n_r_cand)
% to use at different file names
params.hiers_id = 'multi_3sc_u_4r';  % multi and 3 scales 'up'

% String identifying the current Pareto chosen point
params.pareto_id = '12k';

% Maximum number of regions per candidate
params.n_r_cand = 4;

% Hierarchies to combine
params.hiers    = {'multi','scale_0.50','scale_1.00','scale_2.00'};

% Level of overlap to erase duplicates
params.J_th = 0.95;

% Number of samples per image that the ranking training will get
params.n_samples = 30;

% Max margin parameter
params.theta = 0.7;

%% Do not edit the lines below
% Where to find the hierarchies
for ii=1:length(params.hiers)
    params.hier_dirs{ii} = fullfile(root_dir,'datasets',params.database,params.raw_hiers,params.hiers{ii});
end

% String identifying the current final global setup at MCG
params.mcg_id = [params.raw_hiers '_' params.hiers_id '_' params.pareto_id];

% ----- Results files -----
% Global Pareto file
params.files.pareto_full = fullfile(root_dir,'datasets',params.database,'pareto',[params.raw_hiers '_' params.hiers_id '_nr_' num2str(params.n_r_cand) '_' params.gt_set_pareto '_pareto_full.mat']);

% Single-scale results
for ii=1:length(params.hiers)
    params.files.pareto_singles{ii} = fullfile(root_dir,'results',params.database,'pareto',[params.raw_hiers '_' params.hiers{ii} '_nr_' num2str(params.n_r_cand) '_' params.gt_set_pareto '_pareto_single.mat']);
end

% Parameters of chosen Pareto point
params.files.pareto_point = fullfile(root_dir,'datasets',params.database,'pareto',[params.mcg_id '_' params.gt_set_pareto '_pareto_point.mat']);

% File where full features will be stored
params.files.features_file = fullfile(root_dir,'datasets',params.database,'features',[params.mcg_id '_features_' params.gt_set_ranking  '.mat']);

% File where the trained classifier will be stored
params.files.trained_classifier = fullfile(root_dir,'datasets',params.database,'classifiers',[params.mcg_id '_rand_forest_' params.gt_set_ranking  '.mat']);

% ---- Ensure needed folders ----
if ~exist(fullfile(root_dir,'results',params.database,'pareto'),'dir')
    mkdir(fullfile(root_dir,'results',params.database,'pareto'))
end
if ~exist(fullfile(root_dir,'results',params.database,'cands'),'dir')
    mkdir(fullfile(root_dir,'results',params.database,'cands'))
end
if ~exist(fullfile(root_dir,'datasets',params.database,'classifiers'),'dir')
    mkdir(fullfile(root_dir,'datasets',params.database,'classifiers'));
end
if ~exist(fullfile(root_dir,'datasets',params.database,'features'),'dir')
    mkdir(fullfile(root_dir,'datasets',params.database,'features'));
end

author: s-gupta

repo: rcnn-depth

save_path: github-repos/MATLAB/s-gupta-rcnn-depth


text:
function [output] = ft_transform_geometry(transform, input)

% FT_TRANSFORM_GEOMETRY applies a homogeneous coordinate transformation to a
% structure with geometric information, for example a volume conduction model for the
% head, gradiometer of electrode structure containing EEG or MEG sensor positions and
% MEG coil orientations, a head shape or a source model.
%
% The units in which the transformation matrix is expressed are assumed to be the
% same units as the units in which the geometric object is expressed. Depending on
% the input object, the homogeneous transformation matrix should be limited to a
% rigid-body translation plus rotation (MEG-gradiometer array), or to a rigid-body
% translation plus rotation plus a global rescaling (volume conductor geometry).
%
% Use as
%   output = ft_transform_geometry(transform, input)
% where the transform should be a 4x4 homogenous transformation matrix and the
% input data structure can be any of the FieldTrip data structures that
% describes geometrical data.
%
% See also FT_WARP_APPLY, FT_HEADCOORDINATES, FT_SCALINGFACTOR

% Copyright (C) 2011, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_transform_geometry.m$

% flg rescaling check
allowscaling = ~ft_senstype(input, 'meg');

% determine the rotation matrix
rotation = eye(4);
rotation(1:3,1:3) = transform(1:3,1:3);

if any(abs(transform(4,:)-[0 0 0 1])>100*eps)
  ft_error('invalid transformation matrix');
end

if ~allowscaling
  % allow for some numerical imprecision
  if (abs(det(rotation))-1)>1e-6
    ft_error('only a rigid body transformation without rescaling is allowed');
  end
end

if allowscaling
  % FIXME build in a check for uniform rescaling probably do svd or so
  % FIXME insert check for nonuniform scaling, should give an error
end

tfields   = {'pos' 'pnt' 'o' 'coilpos' 'elecpos' 'optopos' 'chanpos' 'chanposold' 'nas' 'lpa' 'rpa' 'zpoint'}; % apply rotation plus translation
rfields   = {'ori' 'nrm'     'coilori' 'elecori' 'optoori' 'chanori' 'chanoriold'                           }; % only apply rotation
mfields   = {'transform'};           % plain matrix multiplication
recfields = {'fid' 'bnd' 'orig'};    % recurse into these fields
% the field 'r' is not included here, because it applies to a volume
% conductor model, and scaling is not allowed, so r will not change.

fnames = fieldnames(input);
for k = 1:numel(fnames)
  if ~isempty(input.(fnames{k}))
    if any(strcmp(fnames{k}, tfields))
      input.(fnames{k}) = apply(transform, input.(fnames{k}));
    elseif any(strcmp(fnames{k}, rfields))
      input.(fnames{k}) = apply(rotation, input.(fnames{k}));
    elseif any(strcmp(fnames{k}, mfields))
      input.(fnames{k}) = transform*input.(fnames{k});
    elseif any(strcmp(fnames{k}, recfields))
      for j = 1:numel(input.(fnames{k}))
        input.(fnames{k})(j) = ft_transform_geometry(transform, input.(fnames{k})(j));
      end
    else
      % do nothing
    end
  end
end
output = input;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that applies the homogeneous transformation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [new] = apply(transform, old)
old(:,4) = 1;
new = old * transform';
new = new(:,1:3);

author: spm