text:
function w = getw(net)

% GETW
%
% Accessor method returning the weights of a support vector classifier network.
%
%    w = getw(net);

%
% File        : @svc/getw.m
%
% Date        : Tuesday 12th September 2000
%
% Author      : Dr Gavin C. Cawley
%
% Description : Part of an object-oriented implementation of Vapnik's Support
%               Vector Machine, as described in [1].
%
% References  : [1] V.N. Vapnik,
%                   "The Nature of Statistical Learning Theory",
%                   Springer-Verlag, New York, ISBN 0-387-94559-8,
%                   1995.
%
% History     : 07/07/2000 v1.00
%               12/09/2000 v1.01 minor improvements to comments and help
%                                message
%
% Copyright   : (c) Dr Gavin C. Cawley, September 2000
%
%    This program is free software; you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation; either version 2 of the License, or
%    (at your option) any later version.
%
%    This program is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this program; if not, write to the Free Software
%    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%

w = net.w;

% bye bye...

author: vistalab

repo: vistasoft


% 2D Example for Parametric Multilevel Mass-Preserving Image Registration using VAMPIRE
%
% (c) Fabian Gigengack and Lars Ruthotto 2011/02/04, see FAIR.2 and FAIRcopyright.m.
% http://www.uni-muenster.de/EIMI/
% http://www.mic.uni-luebeck.de/
%
%   - data                 synthetic 2D Gaussian blobs (level 3:8, full
%                          resolution: 256x256)
%   - viewer               viewImage2D
%   - interpolation        splineInter
%   - distance             SSD
%   - pre-registration     none
%   - transformation       splineTransformation2Dsparse
%   - regularizer          parametric FAIR regularizer
%   - optimizer            Gauss-Newton with ArmijoBacktrack linesearch

setup2DGaussianData;

% prepare the plot
FAIRplots('clear')
Dshow = @(T,R,omega,m) viewImage2D(128+(T-R)/2,omega,m,'colormap',gray(256));
FAIRplots('set','Dshow',Dshow);

% initialize the regularizer for the non-parametric part
alpha       = 100;
alphaLength = 1;
alphaArea   = 0;
alphaVolume = 1;
[reg,regOptn] = regularizer('reset', 'regularizer', 'mfHyperElastic', ...
    'alpha',alpha, 'alphaLength', alphaLength, 'alphaArea', alphaArea, ...
    'alphaVolume', alphaVolume);

% set the parametric transformation
p = [18 18];
trafo('reset','trafo','splineTransformation2Dsparse','omega',omega,'m',m,'p',p);

% finally: run MLPIR
PIRpara            = optPara('PIR-GN');
PIRpara.solver     = @VAMPIREsolveGN_PCG;

[wc,his] = MLPIR(ML, 'PIRobj', @VAMPIREPIRobjFctn, ...
    'getGrid', @getNodalGrid,'PIRpara',PIRpara);

%% Plot results
yc = trafo(wc,getNodalGrid(omega, m));
% Compute resulting image: dataT(yc) * det(D(yc))
Topt = reshape(linearInter(dataT,omega,center(yc,m)) ...
    .* geometry(yc,m,'Jac','omega',omega), m);
figure;
subplot(2,2,1);
viewImage2D(dataT,omega,m,'colormap', 'gray(256)'); hold on;
plotGrid(center(yc, m), omega, m, 'spacing', [5 5]); axis off; hold off;
title('Template (T) & Grid')
subplot(2,2,2);
viewImage2D(dataR,omega,m,'colormap', 'gray(256)'); axis off;
title('Reference (R)')
subplot(2,2,3);
viewImage2D(Topt,omega,m,'colormap', 'gray(256)'); axis off;
title('VAMPIRE result (Topt)')
subplot(2,2,4);
viewImage2D(abs(Topt-dataR),omega,m,'colormap', 'gray(256)'); axis off;
title('Absolute difference image of R and Topt')


text:
function [tow,prn,P1,Phi1,P2,Phi2,eof] = readGrilR
%READGRIL Reading a binary GRIL files.
%         The following message was sent to receiver:
%             em,,/msg/jps/{GT,SI,R1,P1,R2,P2}
%             dm

%Kai Borre November 12, 2007
%Copyright (c) by Kai Borre
%$Revision: 1.1 $  $Date: 2007/11/12 $

global fidr

% Constants
c = 299792458;  % vacuum speed of light, m/s
f1 = 154*10.23E6;			% L1 frequency Hz
f2 = 120*10.23E6;			% L2 frequency Hz
lambda1 = c/f1;	     % wavelength on L1:  .19029367  m
lambda2 = c/f2;	     % wavelength on L2:  .244210213 m
Pi = 3.1415926535898; % GPS value for pi
eof = 0;

% struct GPSEphemeris
et = fread(fidr,5,'uint8');
if isempty(et) == 1
    eof = 1;
    tow = 0;
    prn = [];
    P1 = [];
    Phi1 = [];
    P2 = P1;
    Phi2 = Phi1;
    return;
end

while strcmp(char(et(1:2)'), 'GE')
    %et2 = hex2dec(et1(3:end));
    sv = fread(fidr,1,'uint8');
    i = 1;% sv;
    eph(1,i) = sv;
    tow = fread(fidr,1,'uint32');
    flags = fread(fidr,1,'uint8');
    iodc = fread(fidr,1,'int16');
    eph(21,i) = fread(fidr,1,'int32'); % toc
    ura = fread(fidr,1,'int8');
    healthS = fread(fidr,1,'uint8');
    wn = fread(fidr,1,'int16');
    tgd = fread(fidr,1,'single');
    eph(2,i) = fread(fidr,1,'single'); % af2
    eph(20,i) = fread(fidr,1,'single'); %af1
    eph(19,i) = fread(fidr,1,'single'); %af0
    eph(18,i) = fread(fidr,1,'int32'); %toe
    iode = fread(fidr,1,'int16');
    eph(4,i) = fread(fidr,1,'double'); %rootA
    eph(6,i) = fread(fidr,1,'double'); %ecc
    eph(3,i) = fread(fidr,1,'double')*Pi; %m0
    eph(16,i) = fread(fidr,1,'double')*Pi; %Omega0
    eph(12,i) = fread(fidr,1,'double')*Pi; %i0
    eph(7,i) = fread(fidr,1,'double')*Pi; %omega
    eph(5,i) = fread(fidr,1,'single')*Pi; %deltan
    eph(17,i) = fread(fidr,1,'single')*Pi; %Omegadot
    eph(13,i) = fread(fidr,1,'single')*Pi; %idot
    eph(10,i) = fread(fidr,1,'single'); %crc
    eph(11,i) = fread(fidr,1,'single'); %crs
    eph(8,i) = fread(fidr,1,'single'); %cuc
    eph(9,i) = fread(fidr,1,'single'); %cus
    eph(14,i) = fread(fidr,1,'single'); %cic
    eph(15,i) = fread(fidr,1,'single'); %cis
    cs = fread(fidr,1,'uint8');
    dummy = fread(fidr,1,'uint8');
    et = fread(fidr,5,'char');
    if ~strcmp(char(et(1:2)'), 'GE'), break; end
end

% struct GPSTime
if ~strcmp(char(et(1:2)'), 'GT')
    gt = fread(fidr,5,'uint8=>char');
else
    gt = et;
end
gt1 = char(gt');
%gt2 = str2num(gt1(3:end));
tow = fread(fidr,1,'uint32')/1000; %211 588 seconds
wn = fread(fidr,1,'uint16'); % 347 correct
cs = fread(fidr,1,'uint8');
dummy = fread(fidr,1,'uint8');

% struct SatIndex
si = fread(fidr,5,'char');
si1 = char(si');
si2 = hex2dec(si1(3:end));
for i = 1:si2-1
    prn(i) = fread(fidr,1,'uint8');
end
cs = fread(fidr,1,'uint8');
dummy = fread(fidr,1,'uint8');
PRN = prn;

% struct PR_P1
pr = fread(fidr,5,'char');
pr1 = char(pr');
pr2 = hex2dec(pr1(3:end));
for i = 1:si2-1
    prange1(i) = fread(fidr,1,'double')*c;
end
cs = fread(fidr,1,'uint8');
dummy = fread(fidr,1,'uint8');
P1 = prange1;

% struct PhaseP1
ph = fread(fidr,5,'char');
ph1 = char(ph');
ph2 = hex2dec(ph1(3:end));
for i = 1:si2-1
    phase1(i) = fread(fidr,1,'double')*lambda1;
end
cs = fread(fidr,1,'uint8');
dummy = fread(fidr,1,'uint8');
Phi1 = phase1;

% struct PR_P2
pr = fread(fidr,5,'char');
pr1 = char(pr');
pr2 = hex2dec(pr1(3:end));
for i = 1:si2-1
    prange2(i) = fread(fidr,1,'double')*c;
end
cs = fread(fidr,1,'uint8');
dummy = fread(fidr,1,'uint8');
P2 = prange2;

% struct PhaseP2
ph = fread(fidr,5,'char');
ph1 = char(ph');
ph2 = hex2dec(ph1(3:end));
for i = 1:si2-1
    phase2(i) = fread(fidr,1,'double')*lambda2;
end
cs = fread(fidr,1,'uint8');
dummy = fread(fidr,1,'uint8');
Phi2 = phase2;
%%%%%%%%% end readGrilR.m %%%%%%%%%%%%%%%%%%%%%%%%

author: yandld


text:
classdef ProposedOptimalSuperEllipse < handle

    properties (Access = private)
       mxV
       myV
       qV
       alpha
       beta
       outputPath
    end

    methods (Access = public)

        function obj = ProposedOptimalSuperEllipse()
            obj.outputPath = '/home/alex/Dropbox/PaperStress/';
            obj.obtainOptimalSuperEllipseValues();
            obj.obtainOptimalCoeficientsForAnalyticalSuperEllipse();
            obj.plotAnalyticalSuperEllipse();
            obj.plotAnalyticalQvsMaxMxMy();
        end

        function obtainOptimalSuperEllipseValues(obj)
            superEllipse = PonderatedOptimalSuperEllipseComputer();
            superEllipse.compute();
            obj.mxV = superEllipse.mxV;
            obj.myV = superEllipse.myV;
            obj.qV  = superEllipse.qMean;
        end

        function obtainOptimalCoeficientsForAnalyticalSuperEllipse(obj)
            qAnalytical = @(alpha,beta) obj.analyticalExponent(alpha,beta,obj.mxV,obj.myV);
            options = optimoptions('fmincon','Display','iter');
            problem.options = options;
            problem.solver = 'fmincon';
            problem.objective = @(x) norm(qAnalytical(x(1),x(2)) - obj.qV)/norm(obj.qV);
            problem.x0 = [6,20];
            problem.ub = [50,50];
            problem.lb = [0,0];
            x = fmincon(problem);
            obj.alpha = x(1);
            obj.beta = x(2);
        end

        function plotAnalyticalSuperEllipse(obj)
            f = obj.plotExponent(obj.alpha,obj.beta);
            p = surfPrinter(f);
            xlabel('$m_1$','Interpreter','latex');
            ylabel('$m_2$','Interpreter','latex');
            zlabel('$q$','Interpreter','latex');
            fName = fullfile(obj.outputPath,'AnalyticalOptimalSuperEllipse');
            p.print(fName)
        end

        function plotAnalyticalQvsMaxMxMy(obj)
            mx = linspace(0.01,0.99,100);
            my = linspace(0.01,0.99,100);
            q = obj.analyticalExponent(obj.alpha,obj.beta,mx,my);
            f = figure();
            h{1} = plot(mx,q,'-+');
            xlabel('$\max(m_1,m_2)$','Interpreter','latex');
            ylabel('$q$','Interpreter','latex');
            fName = fullfile(obj.outputPath,'AnalyticalQvsMaxMxMy');
            p = plotPrinter(f,h);
            p.print(fName);
        end

        function f = plotExponent(obj,alpha,beta)
            f = figure();
            nMx = 100;
            nMy = 100;
            mxv = linspace(0.01,0.99,nMx);
            myv = linspace(0.01,0.99,nMy);
            q = zeros(nMx,nMy);
            for ix = 1:nMx
                for iy = 1:nMy
                    mx = mxv(ix);
                    my = myv(iy);
                    q(ix,iy) = obj.analyticalExponent(alpha,beta,mx,my);
                end
            end
            surf(mxv,myv,q')
        end

    end

    methods (Access = private, Static)

        function q = analyticalExponent(alpha,beta,m1,m2)
            qmin = 2;
            qmax = 32;
            q = max(qmin,min((1./(1-max(m1,m2).^beta)).^alpha,qmax));
        end

    end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function asa136_test01 ( )

%*****************************************************************************80
%
%% TEST01 tries out the ASA136 routine.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  k = 5;
  m = 100;
  n = 2;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST01\n' );
  fprintf ( 1, '  Test the KMNS algorithm.\n' );
  fprintf ( 1, '  Applied Statistics Algorithm 136\n' );
%
%  Read the data.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Reading the data.\n' );

  input_unit = fopen ( 'points_100.txt', 'rt' );

  for i = 1 : m
    x(i,1:n) = fscanf ( input_unit, '%f', n );
  end

  fclose ( input_unit );
%
%  Print a few data values.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  First 5 data values:\n' );
  fprintf ( 1, '\n' );
  for i = 1 : 5
    fprintf ( 1, '  %8d', j );
    for j = 1 : n
      fprintf ( 1, '  %14f', x(i,j) );
    end
    fprintf ( 1, '\n' );
  end
%
%  Initialize the cluster centers.
%  Here, we arbitrarily make the first K data points cluster centers.
%
  for i = 1 : k
    for j = 1 : n
      c(i,j) = x(i,j);
    end
  end
%
%  Compute the clusters.
%
  iter = 50;

 [ c, ic1, nc, wss, ifault ] = kmns ( x, m, n, c, k, iter );

  if ( ifault ~= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'TEST01 - Fatal error!\n' );
    fprintf ( 1, '  KMNS returned IFAULT = %d\n', ifault );
    return
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Cluster  Population  Energy\n' );
  fprintf ( 1, '\n' );

  for i = 1 : k
    fprintf ( 1, '  %8d  %8d  %14f\n', i, nc(i), wss(i) );
  end

  nc_sum = sum ( nc(1:k) );
  wss_sum = sum ( wss(1:k) );
  fprintf ( 1, '\n' );
  fprintf ( 1, '     Total  %8d  %14f\n', nc_sum, wss_sum );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function yms=EWT2D_Curvelet_Scaling(Radius,w1,gamma,W,H)

%==================================================
% function ymw=EWT2D_Curvelet_Scaling(w1,gamma,W,H)
%
% Generate the 1D Littlewood-Paley wavelet in the
% Fourier domain associated to the disk [0,w1]
% with transition ratio gamma
%
% Input parameters:
%   -Radius : matrix giving the radius at each pixel
%   -w1 : boundary
%   -gamma : transition ratio
%   -W : image width
%   -H : image height
%
% Output:
%   -yms: Fourier transform of the scaling function
%
% Author: Jerome Gilles - Giang Tran
% Institution: UCLA - Department of Mathematics
% Year: 2013
% Version: 1.0
%===================================================

an=1/(2*gamma*w1);
pbn=(1+gamma)*w1;
mbn=(1-gamma)*w1;

yms=zeros(H,W);

for i=1:W
   for j=1:H
      if (Radius(j,i)<mbn)
        yms(j,i)=1;
      elseif ((Radius(j,i)>=mbn) && (Radius(j,i)<=pbn))
        yms(j,i)=cos(pi*EWT_beta(an*(Radius(j,i)-mbn))/2);
      end
   end
end

author: Sable

repo: mcbench-benchmarks


text:
function y = sum_square_pos( x, dim )

%SUM_SQUARE_POS   Sum of squares of the positive parts.
%   For vectors, SUM_SQUARE(X) is the sum of the squares of the positive
%   parts of X; i.e., SUM( MAX(X,0)^2 ). X must be real.
%
%   For matrices, SUM_SQUARE_POS(X) is a row vector containing the
%   application of SUM_SQUARE_POS to each column. For N-D arrays, the
%   SUM_SQUARE_POS operation is applied to the first non-singleton
%   dimension of X.
%
%   SUM_SQUARE_POS(X,DIM) takes the sum along the dimension DIM of X.
%
%   Disciplined convex programming information:
%       SUM_SQUARE_POS(X,...) is convex and nondecreasing in X. Thus, when
%       used in CVX expressions, X must be convex (or affine). DIM must
%       always be constant.

narginchk(1,2);
if nargin == 2,
    y = sum( square_pos( x ), dim );
else
    y = sum( square_pos( x ) );
end

% 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:
function M=json2mat(J)

%JSON2MAT converts a javscript data object (JSON) into a Matlab structure
%         using s recursive approach. J can also be a file name.
%
%Example: lala=json2mat('{lele:2,lili:4,lolo:[1,2,{lulu:5,bubu:[[1,2],[3,4],[5,6]]}]}')
%         notice lala.lolo{3}.bubu is read as a 2D matrix.
%
% Jonas Almeida, March 2010

if exist(J)==2 % if J is a filename
    fid=fopen(J,'r');
    J='';
    while ~feof(fid)
        J=[J,fgetl(fid)];
    end
    fclose(fid);
    M=json2mat(J);
else
    J1=regexprep(J(1:min([5,length(J)])),'\s',''); %despaced start of J string
    if J1(1)=='{' %extract structures
        JJ=regexp(J,'\{(.*)\}','tokens');
        M=extract_struct(JJ{1}{1});
    elseif J1(1)=='[' %extract cells
        JJ=regexp(J,'\[(.*)\]','tokens');
        M=extract_cell(JJ{1}{1});
    elseif J1(1)=='"' %literal string
        JJ=regexp(J,'\"(.*)\"','tokens');
        M=JJ{1}{1};
    else %numeric value
        M=str2num(J); % is number
    end
end

function y=extract_struct(x)
%detag arrays first
indOC=extract_embed(x,'[',']');
n=size(indOC,1);
for i=n:-1:1
    tag{i}=json2mat(x(indOC(i,1):indOC(i,2)));
    x=[x(1:indOC(i,1)-1),'tag{',num2str(i),'}',x(indOC(i,2)+1:end)];
end

a=regexp(x,'[^:,]+:[^,]+');
n=length(a);
a=[a,length(x)+2];
for i=1:n
    s=x(a(i):a(i+1)-2);
    t=regexp(s,'([^:]+):(.+)','tokens');
    %t{1}{1}(t{1}{1}==32)=[]; % remove blanks, maybe later do something fancier like replace with underscores
    t{1}{1}=strrep(t{1}{1},' ','_');
    t{1}{1}=strrep(t{1}{1},'"','');
    if t{1}{1}(1)=='_' %JSON allows for fieldnames starting with "_"
        t{1}{1}(1)=''; % this line will cause hard to track problems if the same object has 2 attributes with the same name but one of them starting with "_"
    end
    if regexp(t{1}{2},'tag{\d+}')
        y.(t{1}{1})=eval(t{1}{2});
    else
        y.(t{1}{1})=json2mat(t{1}{2});
    end
    %y.(t{1}{1})=json2mat(t{1}{2});
end

function y=extract_cell(x)

indOC=extract_embed(x,'{','}');
n=size(indOC,1);
for i=n:-1:1
    tag{i}=json2mat(x(indOC(i,1):indOC(i,2)));
    x=[x(1:indOC(i,1)-1),'tag~<',num2str(i),'>~',x(indOC(i,2)+1:end)];
end
indOC=extract_embed(x,'[',']');
m=size(indOC,1);
for j=m:-1:1
    i=n+j;
    tag{i}=json2mat(x(indOC(i,1):indOC(i,2)));
    try;tag{i}=cell2mat(tag{i});end
    x=[x(1:indOC(i,1)-1),'tag{',num2str(i),'}',x(indOC(i,2)+1:end)];
end
x=strrep(x,'~<','{');
x=strrep(x,'>~','}');
if exist('tag') %catching numeric content
    if isnumeric([tag{:}])
        try
            y=eval(['[',strrep(x,'},','};'),']']);
        end
    end
end

if exist('y')~=1
    y=eval(['{',strrep(x,'"',''''),'}']);
end

%look for embeded objects and arrays

function y=extract_embed(x,tagOpen,tagClose)

%EXTRACT_EMBED identifies embeded tagged segments
%Example y=extract_embed(str,'[',']')

indOpen=strfind(x,tagOpen)';
indOpen=[indOpen,ones(length(indOpen),1)];
indClose=strfind(x,tagClose)';
indClose=[indClose,-ones(length(indClose),1)];
indOpenClose=[indOpen;indClose];
[~,Ind]=sort(indOpenClose(:,1));
indOpenClose=indOpenClose(Ind,:);
n=size(indOpenClose,1);
for i=2:n % add one for open, take one for close
    indOpenClose(i,2)=indOpenClose(i-1,2)+indOpenClose(i,2);
end
i=0;
op=0; %open
while i<n
    i=i+1;
    if (indOpenClose(i,2)==1)*(op==0)
        op=1;
    elseif indOpenClose(i,2)==0
        op=0;
    else
        indOpenClose(i,2)=-1;
    end
end
if isempty(indOpenClose)
    y=[];
else
    indOpenClose(indOpenClose(:,2)<0,:)=[];
    y=[indOpenClose(1:2:end,1),indOpenClose(2:2:end,1)];% Open/Close Indexes
end

author: covartech

repo: PRT

save_path: github-repos/MATLAB/covartech-PRT


text:
function differ_test04 ( )

%*****************************************************************************80
%
%% DIFFER_TEST04 tests DIFFER_FORWARD, DIFFER_BACKWARD, DIFFER_CENTRAL.
%
%  Discussion:
%
%    Evaluate the coefficients for uniformly spaced finite difference
%    approximations of derivatives.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 November 2013
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'DIFFER_TEST04\n' );
  fprintf ( 1, '  DIFFER_FORWARD,\n' );
  fprintf ( 1, '  DIFFER_BACKWARD, and\n' );
  fprintf ( 1, '  DIFFER_CENTRAL produce coefficients for difference\n' );
  fprintf ( 1, '  approximations of the O-th derivative, \n' );
  fprintf ( 1, '  with error of order H^P, for a uniform spacing of H.\n' );

  h = 1.0;
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Use a spacing of H = %g for all examples.\n', h );
%
%  Forward difference approximation to the third derivative with error of O(h).
%
  o = 3;
  p = 1;
  n = o + p;
  [ c, x ] = differ_forward ( h, o, p );
  label = sprintf ( '  Forward difference coefficients, O = %d, P = %d', o, p );
  r8vec2_print ( n, x, c, label );
%
%  Backward difference approximation to the third derivative with error of O(h).
%
  o = 3;
  p = 1;
  n = o + p;
  [ c, x ] = differ_backward ( h, o, p );
  label = sprintf ( '  Backward difference coefficients, O = %d, P = %d', o, p );
  r8vec2_print ( n, x, c, label );
%
%  Central difference approximation to the third derivative with error of O(h^2).
%
  o = 3;
  p = 2;
  n = o + p;
  [ c, x ] = differ_central ( h, o, p );
  label = sprintf ( '  Central difference coefficients, O = %d, P = %d', o, p );
  r8vec2_print ( n, x, c, label );
%
%  Central difference approximation to the third derivative with error of O(h^4).
%
  o = 3;
  p = 4;
  n = o + p;
  [ c, x ] = differ_central ( h, o, p );
  label = sprintf ( '  Central difference coefficients, O = %d, P = %d', o, p );
  r8vec2_print ( n, x, c, label );
%
%  Forward difference approximation to the fourth derivative with error of O(h).
%
  o = 4;
  p = 1;
  n = o + p;
  [ c, x ] = differ_forward ( h, o, p );
  label = sprintf ( '  Forward difference coefficients, O = %d, P = %d', o, p );
  r8vec2_print ( n, x, c, label );
%
%  Backward difference approximation to the fourth derivative with error of O(h).
%
  o = 4;
  p = 1;
  n = o + p;
  [ c, x ] = differ_backward ( h, o, p );
  label = sprintf ( '  Backward difference coefficients, O = %d, P = %d', o, p );
  r8vec2_print ( n, x, c, label );
%
%  Central difference approximation to the fourth derivative with error of O(h^3).
%
  o = 4;
  p = 3;
  n = o + p;
  [ c, x ] = differ_central ( h, o, p );
  label = sprintf ( '  Central difference coefficients, O = %d, P = %d', o, p );
  r8vec2_print ( n, x, c, label );

  return
end


text:
function y = cvx_s_banded( m, n, lower, upper )
%CVX_S_BANDED (U,L)-banded matrices.

if nargin < 3,
    error( 'Bandwidth arguments missing.' );
elseif ~isnumeric( lower ) || length( lower ) ~= 1 || lower < 0 || lower ~= floor( lower ),
    error( 'Bandwidth arguments must be nonnegative integers.' );
elseif nargin < 4,
    upper = lower;
elseif ~isnumeric( upper ) || length( upper ) ~= 1 || upper < 0 || upper ~= floor( upper ),
    error( 'Bandwidth arguments must be nonnegative integers.' );
end

c  = 0 : n - 1;
c  = c( ones( 1, m ), : );
r  = ( 0 : m - 1 )';
r  = r( :, ones( 1, n ) );
temp = r - c;
temp = temp <= lower & temp >= -upper;
r  = r( temp );
c  = c( temp );
y = sparse( 1 : length( r ), r + m * c + 1, 1, length( r ), m * n );

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.

repo: REST


text:
function Ar = sladd(A0, As, d)
%SLADD Add a sub-array along some dimensions to an array
%
% $ Syntax $
%   - Ar = sladd(A0, As)
%   - Ar = sladd(A0, As, d)
%
% $ Arguments $
%   - A0:           the original array
%   - v:            the sub-array to be added to the array
%   - Ar:           the resultant array
%   - d:            the dimension along which the vector is added
%
% $ Description $
%   - Ar = sladd(A0, As) adds the sub-array As to the array A0 along
%     auto-selected dimensions. The dimensions are identified by the
%     dimension of As with size larger than 1. If As is a scalar, then
%     all elements of A0 will be added As.
%
%   - Ar = sladd(A0, As, d) adds the sub-array As to the array A0 along
%     the dimensions specified by d.
%
% $ Remarks $
%   # An empty As is allowed. In such case, the original array A0 will
%     be output, i.e. Ar = A0.
%   # The sizes of dimensions along which the sub-array is added should
%     match that of A0, otherwise, an error will be raised.
%   # By specifying the dimensions through d, the speed can be accelerated.
%
% $ Examples $
%   - Add a vector to a matrix.
%     \{
%         A = [1 2 3; 4 5 6];
%         v = [2; 5];
%         Ar = sladd(A, v)
%
%         Ar =
%
%             3     4     5
%             9    10    11
%
%     \}
%     It is equivalent to sladd(A, v, 1).
%
%  - Add a plane to a matrix
%    \{
%        A1 = [1 2 3; 4 5 6];
%        A2 = [7 8 9; 10 11 12];
%        A = cat(3, A1, A2);
%        v1 = [10; 20];
%        v2 = [30; 40];
%        As = cat(3, v1, v2)
%
%        Ar(:, :, 1) =
%
%            11    12    13
%            24    25    26
%
%        Ar(:, :, 2) =
%
%            37    38    39
%            50    51    52
%
%    \}
%
% $ History $
%   - Created by Dahua Lin on Nov 18th, 2005
%

%% parse and verify input
if nargin < 2
    raise_lackinput('sladd', 2);
end
if isempty(As)
    Ar = A0;
    return;
end
if ndims(As) > ndims(A0)
    error('sltoolbox:dimoverflow', ...
        'The dimension of As should not be larger than that of A0');
end
if nargin < 3 || isempty(d)
    % d is not specified, automatically determine d
    d = find(size(As) > 1);
end
siz_A0 = size(A0);
siz_As = size(As);
if ~isequal(siz_A0(d), siz_As(d))
    error('sltoolbox:dimmismatch', ...
        'The dimensions of As does not match that of A0 in the dimensions to be added');
end

%% compute
siz_A0(d) = 1;
Ar = A0 + repmat(As, siz_A0);

author: lmthang


text:
%PNMFILT Pipe image through PNM utility
%
% OUT = PNMFILT(CMD) runs the external program given by the string CMD
% and the output (assumed to be PNM format) is returned as OUT.
%
% OUT = PNMFILT(CMD, IM) pipes the image IM through the external program
% given by the string CMD and the output is returned as OUT.  The external
% program must accept and return images in PNM format.
%
% Examples::
%       im = pnmfilt('ppmforge -cloud');
%       im = pnmfilt('pnmrotate 30', lena);
%
% Notes::
%  - Provides access to a large number of Unix command line utilities such
%    as ImageMagick and netpbm.
%  - The input image is passed as stdin, the output image is assumed to
%    come from stdout.
%  - MATLAB doesn't support i/o to pipes so the image is written to a
%    temporary file, the command run to another temporary file, and that
%    is read into MATLAB.
%
% See also PGMFILT, IREAD.

% Copyright (C) 1993-2011, by Peter I. Corke
%
% This file is part of The Machine Vision Toolbox for Matlab (MVTB).
%
% MVTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% MVTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with MVTB.  If not, see <http://www.gnu.org/licenses/>.

function im2 = pnmfilt(cmd, im)

	% MATLAB doesn't support pipes, so it all has to be done via
	% temp files :-(

    % create temporary output file
	ofile = sprintf('%s.pnm', tempname);

    quiet = '2> /dev/null';

    if nargin < 2
        unix([cmd ' > ' ofile ' ' quiet]);
    else
        % create temporary input file
        ifile = sprintf('%s.pnm', tempname);
        imwrite(im, ifile, 'pnm');
        [s,w] = unix([cmd ' < ' ifile ' > ' ofile ]);
        assert(s == 0, 'MVTB:pnmfilt', 'PNM command non-existent or failed')
    end

	im2 = idouble( imread(ofile) );

    if nargin < 2
        unix(['/bin/rm ' ofile]);
    else
        unix(['/bin/rm ' ifile ' ' ofile]);
    end

author: petercorke

repo: machinevision-toolbox-matlab


text:
function point_num = sphere_llt_point_num ( lat_num, long_num )

%*****************************************************************************80
%
%% SPHERE_LLT_POINT_NUM counts points for an LLT grid on a sphere in 3D.
%
%  Discussion:
%
%    An LLT grid is a grid of triangles defined by latitude and longitude
%    lines over the surface of a sphere in 3D.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 April 2015
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer LAT_NUM, LONG_NUM, the number of latitude
%    and longitude lines to draw.  The latitudes do not include the North and
%    South poles, which will be included automatically, so LAT_NUM = 5, for
%    instance, will result in points along 7 lines of latitude.
%
%    Output, integer POINT_NUM, the number of grid points.
%
  point_num = 2 + lat_num * long_num;

  return
end


text:
function icol = find_eph(Eph, sat, time, override_dtmax)

% SYNTAX:
%   icol = find_eph(Eph, sat, time);
%
% INPUT:
%   Eph = ephemerides matrix
%   sat = satellite index
%   time = GPS time
%
% OUTPUT:
%   icol = column index for the selected satellite
%
% DESCRIPTION:
%   Selection of the column corresponding to the specified satellite
%   (with respect to the specified GPS time) in the ephemerides matrix.

%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:       (C) Kai Borre
%  Contributors:     ...
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   This program is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License
%   along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

isat = find(Eph(30,:) == sat);

n = size(isat,2);
if (n == 0)
    icol = [];
    return
end
icol = isat(1);

delta = 0;

%consider BeiDou time (BDT) for BeiDou satellites
if (strcmp(char(Eph(31)),'C'))
    delta = 14;
    time = time - delta;
end

time_eph = Eph(32,icol);
dtmin = time_eph - time;
for t = isat

    time_eph = Eph(32,t);
    dt = time_eph - time;
    if (abs(dt) < abs(dtmin))
        icol = t;
        dtmin = dt;
    end
end

if nargin == 4
    dtmax = override_dtmax;
else
    %maximum interval from ephemeris reference time
    fit_interval = Eph(29,icol);
    if (fit_interval ~= 0)
        dtmax = fit_interval*3600/2;
    else
        switch (char(Eph(31,icol)))
            case 'R' %GLONASS
                dtmax = 950; %900 + 50 to account for leap seconds difference
            case 'J' %QZSS
                dtmax = 3600;
            otherwise
                dtmax = 7200;
        end
    end
end

%if (fix(abs(dtmin)) - delta > dtmax)
if (fix(abs(dtmin)) > dtmax)
    icol = [];
    return
end

%check satellite health
%the second and third conditions are temporary (QZSS and Galileo health flag is kept on for tests)
if (Eph(27,icol) ~= 0 && ~strcmp(char(Eph(31,icol)),'J') && ~strcmp(char(Eph(31,icol)),'E'))
    icol = [];
    return
end

author: goGPS-Project


text:
function y = daub4_transform ( n, x )

%*****************************************************************************80
%
%% DAUB4_TRANSFORM computes the DAUB4 transform of a vector.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 July 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the dimension of the vector.
%    N must be a power of 2 and at least 4.
%
%    Input, real X(N), the vector to be transformed.
%
%    Output, real Y(N), the transformed vector.
%
  c = [  0.4829629131445341E+00; ...
         0.8365163037378079E+00; ...
         0.2241438680420133E+00; ...
        -0.1294095225512603E+00 ];

  y(1:n,1) = x(1:n);
  z(1:n,1) = 0.0;

  m = n;

  while ( 4 <= m )

    i = 1;

    for j = 1 : 2 : m - 1
      j0 = i4_wrap ( j,     1, m );
      j1 = i4_wrap ( j + 1, 1, m );
      j2 = i4_wrap ( j + 2, 1, m );
      j3 = i4_wrap ( j + 3, 1, m );
      z(i,1)     = c(1) * y(j0) + c(2) * y(j1) + c(3) * y(j2) + c(4) * y(j3);
      z(i+m/2,1) = c(4) * y(j0) - c(3) * y(j1) + c(2) * y(j2) - c(1) * y(j3);
      i = i + 1;
    end

    y(1:m,1) = z(1:m);

    m = floor ( m / 2 );

  end

  return
end


text:
function [iF, IF_f] = invertFrame(F)

% INVERTFRAME  Invert frame.
%   INVERTFRAME(F)  gives the frame iF, inverse of F, so that its
%   composition is the origin frame:
%       O = COMPOSEFRAMES(F,iF) ==> O.x = [0 0 0 1 0 0 0]'
%
%   [iF, IF_f] = INVERTFRAME(F) returns tha Jacobian of the inversion.

if nargout == 1

    q = q2qc(F.q);
    t = -Rtp(F.q,F.t);
    iF.x = [t;q];
    iF = updateFrame(iF);

else

    [q, Q_q] = q2qc(F.q);
    [nt, nT_q, nT_t] = Rtp(F.q,F.t); % this should be -Rtp(). n** means negative.

    iF.x = [-nt;q];
    iF = updateFrame(iF);

%     IF_f = zeros(7);
    IF_f(1:3,1:3) = -nT_t;
    IF_f(1:3,4:7) = -nT_q;
    IF_f(4:7,4:7) = Q_q;

end

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

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   SLAMTB is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License
%   along with SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

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

%   # END GPL LICENSE

author: joansola

repo: slamtb

save_path: github-repos/MATLAB/joansola-slamtb


text:
%
% a script to show and sample default colors on the X windows system
% default colors are read from /usr/lib/X11/rgb.txt if it exists, else from myrgb.txt
% see also ROIcmap
%

Nmax = 2000;
name(Nmax).s = '';
name(Nmax).r = 0;
name(Nmax).g = 0;
name(Nmax).b = 0;
if (exist('/usr/lib/X11/rgb.txt') == 2),
   Colname = '/usr/lib/X11/rgb.txt';
   fprintf(1,'Using %s\n', Colname);
   ColFile = fopen (Colname,'r');
   %skip until first number
   tmp = fgets(ColFile);
   i = 0;
   while (tmp ~= -1 )
      tmp = zdeblank(tmp);
      if (afni_isdigit(tmp(1))),
         i = i + 1;
         [name(i).r,name(i).g,name(i).b,s1,s2,s3,s4] = strread(tmp,'%d%d%d %s %s %s %s');
         if (~isempty(s4)) name(i).s = sprintf('%s %s %s %s', char(s1), char(s2), char(s3), char(s4));
         elseif (~isempty(s3)) name(i).s = sprintf('%s %s %s', char(s1), char(s2), char(s3));
         elseif (~isempty(s2)) name(i).s = sprintf('%s %s', char(s1), char(s2));
         else name(i).s = char(s1);
         end
      end
      tmp = fgets(ColFile);
   end
   fclose (ColFile);
   N = i;
else
   ColFile = fopen ('myrgb.txt', 'r');
   Colname = 'myrgb.txt';
   fprintf(1,'Using %s\n', Colname);
   N = 752;
   for (i=1:1:N),
   name(i).r = fscanf(ColFile, '%g ', 1);
   name(i).g = fscanf(ColFile, '%g ', 1);
   name(i).b = fscanf(ColFile, '%g ', 1);
   name(i).s = fgets(ColFile);
   end
   fclose (ColFile);
end

name = name(1:N);

Mall = zeros (N, 3);
Mall(:,1) = [name(:).r]';
Mall(:,2) = [name(:).g]';
Mall(:,3) = [name(:).b]';
Mall = Mall./255;

if (0),
for (i=6:1:N-5),
   M = zeros (11,3);
   for (j=-5:1:5)
      M(j+6,1) = name(i+j).r./255;
      M(j+6,2) = name(i+j).g./255;
      M(j+6,3) = name(i+j).b./255;
   end
   colormap(M);
   subplot 211;
	image ([1:1:length(M(:,1))]);
   input ('Hit Enter:', 's');
end

end
figure(1), clf;
subplot (211);
str = sprintf('Colors in %s\nPick colors (background then foreground) with mouse\nHit "enter" to quit', Colname);
colormap(Mall); image ([1:1:N]); title (str, 'fontsize',14);
drawnow;
i = 0;
subplot (269);cla

x1 = 1;
while (~isempty(x1)),
   [x1,y] = ginput (1);
   if (~isempty(x1)),
      x1 = floor(x1(1)-0.5)+1;
      subplot (269);
      addsquare([0 i], [2.5 1+i], Mall(x1,:)); hold on
      plot (-0.2, i+0.5, 'k*');
      axis ([-1 3 -1 11]);
      str = sprintf ('back: %s', name(x1).s);
      title (str);
      [x2,y] = ginput (1);
      x2 = floor(x2(1)-0.5)+1;
      subplot (269);
      str = sprintf ('SUMA (%g %g)', x1, x2 );
      ht = text (0.3, 0.3+i, 0, str, 'fontsize',14, 'color', Mall(x2,:));
      str = sprintf ('back: %s (%g), fore: %s (%g)', name(x1).s, x1, name(x2).s, x2);
      title (str);
      i = rem(i +1, 10);
   end
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
% test_all_wls.m

list = {
'ir_pwls_os_lalm test'
'pwls_example'
'pwls_sps_os_test'
'pwls_sps_example'
'pwls_sps_zoom'
'pwls_pcg1 test'
'qpwls_qn_test'
'qpwls_sps_example'
'qpwls_pcg1 test'
'qpwls_pcg1_test'
'wls_grpr_test'
'wls_pcg_test'
'pwls_gca_test'
'pwls_admm2 test'
'qpwls_pcg2_test'
%'qpwls_art2_vs_sps' % very slow!
};

run_mfile_local(list)

author: JeffFessler

repo: mirt

save_path: github-repos/MATLAB/JeffFessler-mirt


text:
function test07 ( input_file_name )

%*****************************************************************************80
%
%% TEST07 tests STLA_SIZE and STLA_SIZE_FAST.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2007
%
%  Author:
%
%     John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST07\n' );
  fprintf ( 1, '  Compare two routines with the same functionality.\n' );
  fprintf ( 1, '  One is designed to run faster than the other,\n' );
  fprintf ( 1, '  especially on large problems with thousands of faces.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  STLA_SIZE determines the size of various objects\n' );
  fprintf ( 1, '    in an ASCII STL file.\n' );
  fprintf ( 1, '  STLA_SIZE_FAST determines the size of various objects\n' );
  fprintf ( 1, '    in an ASCII STL file.\n' );
  fprintf ( 1, '\n' );

  t1 = clock;

  [ solid_num, node_num, face_num, line_num ] = stla_size_fast ( input_file_name );

  t2 = clock;

  diff1 = etime ( t2, t1 );

  fprintf ( 1, '  STLA_SIZE_FAST scanned the file in %f seconds.\n', diff1 );

  t3 = clock;

  [ solid_num, node_num, face_num, line_num ] = stla_size ( input_file_name );

  t4 = clock;

  diff2 = etime ( t4, t3 );

  fprintf ( 1, '  STLA_SIZE      scanned the file in %f seconds.\n', diff2 );

  stla_size_print ( input_file_name, solid_num, node_num, face_num, line_num );

  return
end


text:
function state = sample_mdp(prior, trans, act)
% SAMPLE_MDP Sample a sequence of states from a Markov Decision Process.
% state = sample_mdp(prior, trans, act)
%
% Inputs:
% prior(i) = Pr(Q(1)=i)
% trans{a}(i,j) = Pr(Q(t)=j | Q(t-1)=i, A(t)=a)
% act(a) = A(t), so act(1) is ignored
%
% Output:
% state is a vector of length T=length(act)

len = length(act);
state = zeros(1,len);
state(1) = sample_discrete(prior);
for t=2:len
  state(t) = sample_discrete(trans{act(t)}(state(t-1),:));
end


text:
clear all;
% -------------------------------------------------------------------------
%   Description:
%       Script to demo MS-LapSRN for one image
%
%   Citation:
%       Fast and Accurate Image Super-Resolution with Deep Laplacian Pyramid Networks
%       Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang
%       arXiv, 2017
%
%   Contact:
%       Wei-Sheng Lai
%       wlai24@ucmerced.edu
%       University of California, Merced
% -------------------------------------------------------------------------

img_filename = 'emma.jpg';

%% parameters
%model_name  = 'MSLapSRN_D5R2';
%model_name  = 'MSLapSRN_D5R5';
model_name  = 'MSLapSRN_D5R8';

model_scale = 4; % model SR scale
test_scale  = 4; % testing SR scale
gpu         = 1; % GPU ID

%% setup paths
addpath(genpath('utils'));
addpath(fullfile(pwd, 'matconvnet/matlab'));
vl_setupnn;

%% Load pretrained multi-scale model
model_filename = fullfile('pretrained_models', sprintf('%s.mat', model_name));
fprintf('Load %s\n', model_filename);

net = load(model_filename);
net_trained = dagnn.DagNN.loadobj(net.net);

opts_filename = fullfile('pretrained_models', sprintf('%s_opts.mat', model_name));
fprintf('Load %s\n', opts_filename);

opts = load(opts_filename);
opts = opts.opts;

opts.scales = [model_scale];

%% create single-scale model
net = init_MSLapSRN_model(opts, 'test');

%% copy pretrained weights
fprintf('Copy weights to single scale model...\n');
net = copy_model_weights(net, net_trained);

if( gpu ~= 0 )
    gpuDevice(gpu)
    net.move('gpu');
end

%% Load GT image
fprintf('Load %s\n', img_filename);
img_GT = im2double(imread(img_filename));
img_GT = mod_crop(img_GT, test_scale);

%% Generate LR image
img_LR = imresize(img_GT, 1/test_scale);

%% apply LapSRN
fprintf('Apply MS-LapSRN for %dx SR\n', test_scale);
img_HR = SR_MSLapSRN(img_LR, net, model_scale, test_scale, gpu);

%% show results
img_LR = imresize(img_LR, test_scale);
figure, imshow(cat(2, img_LR, img_HR, img_GT));
title(sprintf('Bicubic %dx    |    MS-LapSRN %dx    |    Ground Truth', test_scale, test_scale));

repo: LapSRN


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

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

% Last Modified by GUIDE v2.5 01-Aug-2020 18:17:55

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

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

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

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

    centerUIFigure(hObject);

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

	populateGUI(handles, fixedSolarPanel);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, fixedSolarPanel)
    lv = fixedSolarPanel.getAttachedStage().launchVehicle;
    [stagesListboxStr, ~] = lv.getStagesListBoxStr();
    ind = lv.getIndOfStage(fixedSolarPanel.stage);

    if(isempty(ind))
        ind = 1;
    end

    set(handles.solarPanelNameText,'String',fixedSolarPanel.getName());

    set(handles.stageCombo,'String',stagesListboxStr);
    set(handles.stageCombo,'Value',ind);

    set(handles.refChargeRateText,'String',fullAccNum2Str(fixedSolarPanel.refChargeRate));
    set(handles.refDistText,'String',fullAccNum2Str(fixedSolarPanel.refChargeRateDist));

    set(handles.panelXText,'String',fullAccNum2Str(fixedSolarPanel.bodyFrameNormVect(1)));
    set(handles.panelYText,'String',fullAccNum2Str(fixedSolarPanel.bodyFrameNormVect(2)));
    set(handles.panelZText,'String',fullAccNum2Str(fixedSolarPanel.bodyFrameNormVect(3)));

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

% Get default command line output from handles structure
    if(isempty(handles))
        varargout{1} = false;
    else
        fixedSolarPanel = getappdata(hObject, 'fixedSolarPanel');
        lv = fixedSolarPanel.getAttachedStage().launchVehicle;

%         fixedSolarPanel.getAttachedStage().removePwrSrc(fixedSolarPanel);

        stage = lv.getStageForInd(handles.stageCombo.Value);

        name = handles.solarPanelNameText.String;
        refChargeRate = str2double(handles.refChargeRateText.String);
        refDist = str2double(handles.refDistText.String);

        xVect = str2double(handles.panelXText.String);
        yVect = str2double(handles.panelYText.String);
        zVect = str2double(handles.panelZText.String);

        fixedSolarPanel.name = name;
        fixedSolarPanel.stage = stage;
        fixedSolarPanel.refChargeRate = refChargeRate;
        fixedSolarPanel.refChargeRateDist = refDist;
        fixedSolarPanel.bodyFrameNormVect = normVector([xVect; yVect; zVect]);

%         fixedSolarPanel.getAttachedStage().addPwrSrc(fixedSolarPanel);
        lv.movePwrSrcToStage(fixedSolarPanel, stage);

        varargout{1} = true;
        close(handles.lvd_EditFixedSolarPanelGUI);
    end

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

    if(isempty(errMsg))
        uiresume(handles.lvd_EditFixedSolarPanelGUI);
    else
        msgbox(errMsg,'Invalid Solar Panel Inputs','error');
    end

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

    chargeRate = str2double(get(handles.refChargeRateText,'String'));
    enteredStr = get(handles.refChargeRateText,'String');
    numberName = 'Ref. Charge Rate';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(chargeRate, numberName, lb, ub, isInt, errMsg, enteredStr);

    dist = str2double(get(handles.refDistText,'String'));
    enteredStr = get(handles.refDistText,'String');
    numberName = 'Ref. Distance';
    lb = 0.001;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(dist, numberName, lb, ub, isInt, errMsg, enteredStr);

    xVect = str2double(get(handles.panelXText,'String'));
    enteredStr = get(handles.panelXText,'String');
    numberName = 'Panel Normal Vector X';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(xVect, numberName, lb, ub, isInt, errMsg, enteredStr);

    yVect = str2double(get(handles.panelYText,'String'));
    enteredStr = get(handles.panelYText,'String');
    numberName = 'Panel Normal Vector Y';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(yVect, numberName, lb, ub, isInt, errMsg, enteredStr);

    zVect = str2double(get(handles.panelZText,'String'));
    enteredStr = get(handles.panelZText,'String');
    numberName = 'Panel Normal Vector Z';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(zVect, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        if(norm([xVect; yVect; zVect]) <= 0)
            errMsg{end+1} = 'Magnitude of the solar panel normal vector must be greater than 0.0.';
        end
    end

% --- Executes on button press in cancelButton.
function cancelButton_Callback(hObject, eventdata, handles)
% hObject    handle to cancelButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    close(handles.lvd_EditFixedSolarPanelGUI);

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

% Hints: get(hObject,'String') returns contents of solarPanelNameText as text
%        str2double(get(hObject,'String')) returns contents of solarPanelNameText as a double

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

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

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

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

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

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

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

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

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

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

% --- Executes on key press with focus on lvd_EditFixedSolarPanelGUI or any of its controls.
function lvd_EditFixedSolarPanelGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditFixedSolarPanelGUI (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
    switch(eventdata.Key)
        case 'return'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'enter'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'escape'
            close(handles.lvd_EditFixedSolarPanelGUI);
    end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
classdef ImprovedInputParser < inputParser
    %

    % This file is part of the Matlab Toolbox TENSALG for Tensor Algebra,
    % developed under the BSD Licence.
    % See the LICENSE file for conditions.

    properties
        unmatchedArgs
    end

    methods
        function p = ImprovedInputParser()
            p@inputParser();
            p.KeepUnmatched = true;
        end
        function parse(p,varargin)
            parse@inputParser(p,varargin{:});
            makeUnmatchedArgs(p);
        end

        function makeUnmatchedArgs(p)
            tmp = [fieldnames(p.Unmatched), ...
                struct2cell(p.Unmatched)];
            p.unmatchedArgs = reshape(tmp',[],1)';
        end

        function obj = passMatchedArgsToProperties(p,obj)
            fNames = fieldnames(p.Results);
            for k = 1:numel(fNames)
                obj.(fNames{k}) = p.Results.(fNames{k});
            end
        end
    end
end

author: baptistar

repo: BOCS

save_path: github-repos/MATLAB/baptistar-BOCS


text:
function a = distance_ld(A,B)

a = sqrt(log(det((A+B)/2))-0.5*log(det(A*B)));

author: alexandrebarachant

repo: covariancetoolbox


text:
function [K, outKern, sumKern, Kgvar] = rbfardjitVardistPsi2Compute(rbfardKern, vardist, Z)

% RBFARDJITVARDISTPSI2COMPUTE one line description
% FORMAT
% DESC description
% RETURN K : description
% RETURN outKern : description
% RETURN sumKern : description
% RETURN Kgvar : description
% ARG rbfardKern : the kernel structure associated with the rbfard2 kernel.
% ARG vardist : description
% ARG Z : description
%
%
% SEEALSO : others
%
%
% COPYRIGHT : Michalis K. Titsias, 2009
%
% COPYRIGHT : Neil D. Lawrence, 2009
%

% VARGPLVM

[K, outKern, sumKern, Kgvar] = rbfard2VardistPsi2Compute(rbfardKern, vardist, Z);

author: SheffieldML

repo: vargplvm


text:
function title = p04_title ( )

%*****************************************************************************80
%
%% P04_TITLE returns the title of problem p04.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 August 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, the title of the problem.
%
  title = 'f(x) = atan ( 40 * x - 15 )';

  return
end


text:
function X = find_line_intersection(P1,V1,P2,V2)

if(length(P1) ~= 2)
    error('This function only works in 2D');
end

A = [V1(1),-V2(1) ; V1(2) -V2(2)];
B = P2-P1;
if(det(A) == 0)
    X = [];
    return;
end

K = inv(A)*B;

X = P1 + K(1)*V1;

author: lmb-freiburg

repo: orion

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


text:
function S = FXLMSinit(w0,mu,est_sec, sec_num, sec_den,leak)

% FXLMSinit     Initialize Parameter Structure for the FXLMS Algorithm
%
% Arguments:
% w0            Coefficients of FIR filter at start (@n=1)
% mu            Step size for the LMS algorithm
% est_sec       Estimated secondary path
% sec_num       Numerator of secondary path
% sec_den       Denomerator of secondary path
% leak          Leaky factor
%                 leak = 0 for the conventional FXLMS
%                 0 < leak <1/step for the leaky FXLMS algorithm
%
% by Lee, Gan, and Kuo, 2008
% Subband Adaptive Filtering: Theory and Implementation
% Publisher: John Wiley and Sons, Ltd

if nargin < 6               % Set default to conventional LMS algorithm
	leak = 0;
end

% Assign structure fields
S.coeffs  = w0(:);          % Weight (column) vector of FIR filter
S.step    = mu;             % Step size of LMS algorithm
S.leakage = leak;           % Leaky factor for the leaky LMS algorithm
S.iter    = 0;              % Iteration count
S.estsec  = est_sec;        % Estimated secondary path (FIR model)
S.sec_num = sec_num;        % Secondary path, numerator
S.sec_den = sec_den;        % Secondary path, denominator
S.AdaptStart = length(w0);  % Running effect of adaptive filter, minimum M

author: CharlesThaCat

repo: acoustic-interference-cancellation


text:
function a = clement1 ( n )

%*****************************************************************************80
%
%% CLEMENT1 returns the CLEMENT1 matrix.
%
%  Formula:
%
%    if ( J = I+1 )
%      A(I,J) = sqrt(I*(N-I))
%    else if ( I = J+1 )
%      A(I,J) = sqrt(J*(N-J))
%    else
%      A(I,J) = 0
%
%  Example:
%
%    N = 5
%
%       .    sqrt(4)    .       .       .
%    sqrt(4)    .    sqrt(6)    .       .
%       .    sqrt(6)    .    sqrt(6)    .
%       .       .    sqrt(6)    .    sqrt(4)
%       .       .       .    sqrt(4)    .
%
%  Properties:
%
%    A is tridiagonal.
%
%    A is banded, with bandwidth 3.
%
%    Because A is tridiagonal, it has property A (bipartite).
%
%    A is symmetric: A' = A.
%
%    Because A is symmetric, it is normal.
%
%    Because A is normal, it is diagonalizable.
%
%    A is persymmetric: A(I,J) = A(N+1-J,N+1-I).
%
%    The diagonal of A is zero.
%
%    A is singular if N is odd.
%
%    About 64 percent of the entries of the inverse of A are zero.
%
%    The eigenvalues are plus and minus the numbers
%
%      N-1, N-3, N-5, ..., (1 or 0).
%
%    If N is even,
%
%      det ( A ) = (-1)^(N/2) * (N-1) * (N+1)^(N/2)
%
%    and if N is odd,
%
%      det ( A ) = 0
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Paul Clement,
%    A class of triple-diagonal matrices for test purposes,
%    SIAM Review,
%    Volume 1, 1959, pages 50-52.
%
%  Parameters:
%
%    Input, integer N, the order of A.
%
%    Output, real A(N,N), the matrix.
%
  for i = 1 : n
    for j = 1 : n

      if ( j == i + 1 )
        a(i,j) = sqrt ( i * ( n - i ) );
      elseif ( i == j + 1 )
        a(i,j) = sqrt ( j * ( n - j ) );
      else
        a(i,j) = 0.0;
      end

    end
  end

  return
end


text:
function colors = getColorSet(numObjs)
% get rgb [0,1] values from id
colors=[
        128 255 255;    %
        255 0 0;        % red           1
        0 255 0;        % green         2
        0 0 255;        % blue          3
        0 255 255;      % cyan          4
        255 0 255;      % magenta       5
        212 212 0;      % yellow        6
        25 25 25;       % black         7
        34,139,34;      % forestgreen   8
        0,191,255;      % deepskyblue   9
        139,0,0 ;       % darkred       10
        218,112,214;    % orchid        11
        244,164,96 ;]/255;  % sandybrown    12
colors = colors / 255;
if(numObjs >= 13)
    load colors.mat
    %morecolors = rand(10000, 3);
    %colors = cat(1,colors,morecolors);
end

author: VisDrone

repo: DroneCrowd

save_path: github-repos/MATLAB/VisDrone-DroneCrowd


text:
function tapas_physio_strip_fields(opts)
% Strips fields of a structure into workspace variables of calling function
%
%   tapas_physio_strip_fields(opts)
%
% IN
%   opts    structure variable
%
% OUT
%
% SIDE EFFECTS
%   creates variables with field names in workspace of calling function
%
% EXAMPLE
%   opts.myString = 'Hello';
%   opts.coolArray = rand(100);
%   strip_fields(opts);
%
%   => command "whos" will show the following workspace variables
%      (stripped fields of structure opts):
%
%       opts        1x1     struct
%       myString    1x5     char
%       coolArray   100x100 double
%
%   See also propval

% Author: Lars Kasper
% Created: 2013-11-13
%
% Copyright (C) 2014 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
%
% This file is part of the TAPAS PhysIO Toolbox, which is released under the terms of the GNU General Public
% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version). For further details, see the file
% COPYING or <http://www.gnu.org/licenses/>.

optsArray = fields(opts);
nOpts = length(optsArray);
for iOpt = 1:nOpts
    assignin('caller', optsArray{iOpt}, opts.(optsArray{iOpt}));
end

author: translationalneuromodeling

repo: tapas


text:
classdef MimPatientBrowserPanel < GemPanel
    % MimPatientBrowserPanel.  Part of the gui for the TD MIM Toolkit.
    %
    %     This class is used internally within the TD MIM Toolkit to help
    %     build the user interface.
    %
    %     MimPatientBrowserPanel represents the main panel of the Patient Browser.
    %
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (Access = private)
        ListOfPatientsPanel
        AllPatientsSlidingPanel
    end

    methods
        function obj = MimPatientBrowserPanel(parent, patient_database, group_patients_with_same_name, gui_callback)
            obj = obj@GemPanel(parent);
            obj.AllPatientsSlidingPanel = MimPatientBrowserAllPatientsSlidingPanel(obj, patient_database, group_patients_with_same_name, gui_callback);
            obj.ListOfPatientsPanel = MimPatientBrowserListOfPatientsPanel(obj, obj.AllPatientsSlidingPanel, patient_database, group_patients_with_same_name, gui_callback);
            obj.AddChild(obj.AllPatientsSlidingPanel);
            obj.AddChild(obj.ListOfPatientsPanel);
        end

        function SelectSeries(obj, patient_id, series_uid, selected)
            obj.ListOfPatientsPanel.SelectPatient(patient_id, selected);
            obj.AllPatientsSlidingPanel.SelectSeries(patient_id, series_uid, selected);
        end

        function DatabaseHasChanged(obj)
            obj.ListOfPatientsPanel.DatabaseHasChanged;
            obj.AllPatientsSlidingPanel.DatabaseHasChanged;
        end

        function Resize(obj, position)
            parent_width_pixels = max(1, position(3));
            parent_height_pixels = max(1, position(4));
            panel_position = [1 1 parent_width_pixels parent_height_pixels];

            % Resize the panel
            Resize@GemPanel(obj, panel_position);

            panel_width_pixels = panel_position(3);
            panel_height_pixels = panel_position(4);

            % We set the patient list to be a fraction of the panel width, with a
            % maximum cutoff
            max_patient_list_width_pixels = 250;
            if max_patient_list_width_pixels < panel_width_pixels/3
                list_panel_width = max_patient_list_width_pixels;
            else
                list_panel_width = max(1, ceil(panel_width_pixels/3));
            end

            % The patient info panel occupies the rest of the width
            info_panel_width = max(1, panel_width_pixels - list_panel_width);

            % Resize the child panels
            obj.ListOfPatientsPanel.Resize([1 1 list_panel_width panel_height_pixels]);
            obj.AllPatientsSlidingPanel.Resize([1+list_panel_width 1 info_panel_width panel_height_pixels]);
        end
    end
end

author: tomdoel

repo: pulmonarytoolkit


text:
function det = r8plu_det ( n, pivot, lu )

%*****************************************************************************80
%
%% R8PLU_DET computes the determinant of an R8PLU matrix.
%
%  Discussion:
%
%    The matrix should have been factored by R8MAT_TO_R8PLU.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 September 2006
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,
%    LINPACK User's Guide,
%    SIAM, 1979,
%    ISBN13: 978-0-898711-72-1.
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.
%    N must be positive.
%
%    Input, integer PIVOT(N), the pivot vector computed by R8MAT_TO_R8PLU.
%
%    Input, real LU(N,N), the LU factors computed by R8MAT_TO_R8PLU.
%
%    Output, real DET, the determinant of the matrix.
%
  det = 1.0;

  for i = 1 : n
    det = det * lu(i,i);
    if ( pivot(i) ~= i )
      det = -det;
    end
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function k = calcWaveNumber(omega,waterDepth,g,deepWater)
% Solves the wave dispersion relation :math:`\omega^2 = g k*tanh(k h)` for
% the wave number
%
% Parameters
% ----------
%     omega : float
%         Wave frequency [rad/s]
%
%     waterDepth : float
%         Water depth [m]
%
%     g : float
%         Gravitational acceleration [m/s^2]
%
%     deepWater : integar
%         waveClass flag inidicating a deep water wave [-]
%
% Returns
% ------------
%    k : float
%        Wave number [m]
%

arguments
    omega
    waterDepth
    g = 9.81;
    deepWater = 0;
end

% Deep water approximation, initial guess
k = omega.^2./g;

% Iterate for shallow and intermediate water, full dispersion relationship
if deepWater == 0
    for i = 1:100
        k = omega.^2./g./tanh(k.*waterDepth);
    end
end

end

author: WEC-Sim

repo: WEC-Sim

save_path: github-repos/MATLAB/WEC-Sim-WEC-Sim


text:
classdef MCMC < BetterHandle
    %%MCMC Simple MH and Gibbs moves for the MotorProgram Class
    %%
    %%   This class provides some simple moves for sampling from
    %%   some variables, with fixed dimension. It does not provide
    %%   a sampler for the entire joint space.
    %%
    properties

       debug_full_score = false;

       %% book-keeping to count the number of times
       %% a move is accepted

       %% parameters that don't call the image evaluation
       accept_shape_type = 0;
       n_shape_type = 0;
       accept_scale_type = 0;
       n_scale_type = 0;
       accept_gpos = 0;
       n_gpos = 0;
       accept_seval = 0;
       n_seval = 0;
       accept_seval_token = 0;
       n_seval_token = 0;
       accept_sid = 0;
       n_sid = 0;
       accept_r = 0;
       n_r = 0;

       %% parameters that call the image evaluation function
       accept_shape_token = 0;
       n_shape_token = 0;
       accept_scale_token = 0;
       n_scale_token = 0;
       accept_pos_token = 0;
       n_pos_token = 0;

    end

    methods

        function this = MCMC(debug_full_score)
            if exist('debug_full_score','var')
                this.debug_full_score = debug_full_score;
            end
        end

        %% print the percent of times various moves are accepted
        function acceptance_ratios(this)
           fprintf(1,'Acceptance ratios\n');
           fprintf(1,' shape type: %s%% (of %d)\n',num2str(this.accept_shape_type/this.n_shape_type*100,3),this.n_shape_type);
           fprintf(1,' scale type: %s%% (of %d)\n',num2str(this.accept_scale_type/this.n_shape_type*100,3),this.n_scale_type);
           fprintf(1,' global pos: %s%% (of %d)\n',num2str(this.accept_gpos/this.n_gpos*100,3),this.n_gpos);
           if this.n_seval > 0
               fprintf(1,' seval type: %s%% (of %d)\n',num2str(this.accept_seval/this.n_seval*100,3),this.n_seval);
               fprintf(1,' seval tokn: %s%% (of %d)\n',num2str(this.accept_seval_token/this.n_seval_token*100,3),this.n_seval_token);
           end
           fprintf(1,' sub-ids   : %s%% (of %d)\n',num2str(this.accept_sid/this.n_sid*100,3),this.n_sid);
           fprintf(1,' R         : %s%% (of %d)\n',num2str(this.accept_r/this.n_r*100,3),this.n_r);

           fprintf(1,' scale tokn: %s%% (of %d)\n',num2str(this.accept_scale_token/this.n_scale_token*100,3),this.n_scale_token);
           fprintf(1,' shape tokn: %s%% (of %d)\n',num2str(this.accept_shape_token/this.n_shape_token*100,3),this.n_shape_token);
           fprintf(1,' pos   tokn: %s%% (of %d)\n',num2str(this.accept_pos_token/this.n_pos_token*100,3),this.n_pos_token);
        end

        %% SHAPE TYPE MOVE
        function [val_new,accept] = mh_shape_type(this,sid,bid,M,lib)
            %% sid: stroke index
            %% bid: sub-stroke index

            %% make proposal
            curr_shape_type = M.S{sid}.shapes_type(:,:,bid);
            prop_shape_type = propose_shape_type(curr_shape_type,M.parameters);

            %% score proposal
            curr_score = score_shape_type(M,sid,bid,lib,M.parameters);
            if this.debug_full_score
               curr_score2 = score_shape_type(M,sid,bid,lib,M.parameters,true);
            end
            M.S{sid}.shapes_type(:,:,bid) = prop_shape_type;
            prop_score = score_shape_type(M,sid,bid,lib,M.parameters);

            if this.debug_full_score %% debug to make sure full-score matches
                prop_score2 = score_shape_type(M,sid,bid,lib,M.parameters,true);
                if ~isinf(prop_score)
                    assert(aeq(prop_score-curr_score,prop_score2-curr_score2));
                    fprintf(1,'DEBUG: MH Shape type passed score test\n');
                end
            end

            %% accept or reject
            accept = mh_accept(prop_score,curr_score);
            if ~accept
                M.S{sid}.shapes_type(:,:,bid) = curr_shape_type;
            end
            val_new = M.S{sid}.shapes_type(:,:,bid);

            this.accept_shape_type = this.accept_shape_type + accept;
            this.n_shape_type = this.n_shape_type + 1;

            if isinf(scoreMP(M,lib))
               error('score should not be negative');
            end
        end

        %% SHAPE TOKEN MOVE
        function [val_new,accept] = mh_shape_token(this,sid,bid,M,lib)
            %% sid: stroke index
            %% bid: sub-stroke index

            %% make proposal
            curr_shape_token = M.S{sid}.shapes_token(:,:,bid);
            prop_shape_token = propose_shape_token(curr_shape_token,M.parameters);

            %% score proposal
            curr_score = score_shape_token(M,sid,bid,lib,M.parameters);
            if this.debug_full_score
               curr_score2 = score_shape_token(M,sid,bid,lib,M.parameters,true);
            end
            M.S{sid}.shapes_token(:,:,bid) = prop_shape_token;
            prop_score = score_shape_token(M,sid,bid,lib,M.parameters);

            if this.debug_full_score %% debug to make sure full-score matches
                prop_score2 = score_shape_token(M,sid,bid,lib,M.parameters,true);
                if ~isinf(prop_score)
                    assert(aeq(prop_score-curr_score,prop_score2-curr_score2));
                    fprintf(1,'DEBUG: MH Shape token passed score test\n');
                end
            end

            %% accept or reject
            accept = mh_accept(prop_score,curr_score);
            if ~accept
                M.S{sid}.shapes_token(:,:,bid) = curr_shape_token;
            end
            val_new = M.S{sid}.shapes_token(:,:,bid);

            this.accept_shape_token = this.accept_shape_token + accept;
            this.n_shape_token = this.n_shape_token + 1;

            if isinf(scoreMP(M,lib))
               error('score should not be negative');
            end
        end

        %% SCALE TYPE MOVE
        function [val_new,accept] = mh_scale_type(this,sid,bid,M,lib)
            %% sid: stroke index
            %% bid: sub-stroke index

            %% make proposal
            curr_invscale_type = M.S{sid}.invscales_type(bid);
            prop_invscale_type = propose_scale_type(curr_invscale_type,M.parameters);

            %% score proposal
            curr_score = score_scale_type(M,sid,bid,lib,M.parameters);
            if this.debug_full_score
                curr_score2 = score_scale_type(M,sid,bid,lib,M.parameters,true);
            end
            M.S{sid}.invscales_type(bid) = prop_invscale_type;
            prop_score = score_scale_type(M,sid,bid,lib,M.parameters);

            if this.debug_full_score %% debug to make sure full-score matches
                prop_score2 = score_scale_type(M,sid,bid,lib,M.parameters,true);
                if ~isinf(prop_score)
                    assert(aeq(prop_score-curr_score,prop_score2-curr_score2));
                    fprintf(1,'DEBUG: MH Scale type passed score test\n');
                end
            end

            %% accept or reject
            accept = mh_accept(prop_score,curr_score);
            if ~accept
               M.S{sid}.invscales_type(bid) = curr_invscale_type;
            end
            val_new = M.S{sid}.invscales_type(bid);

            this.accept_scale_type = this.accept_scale_type + accept;
            this.n_scale_type = this.n_scale_type + 1;

        end

        %% SCALE TOKEN MOVE
        function [val_new,accept] = mh_scale_token(this,sid,bid,M,lib)
            %% sid: stroke index
            %% bid: sub-stroke index

            %% make proposal
            curr_invscale_token = M.S{sid}.invscales_token(bid);
            prop_invscale_token = propose_scale_token(curr_invscale_token,M.parameters);

            %% score proposal
            curr_score = score_scale_token(M,sid,bid,lib,M.parameters);
            if this.debug_full_score
                curr_score2 = score_scale_token(M,sid,bid,lib,M.parameters,true);
            end
            M.S{sid}.invscales_token(bid) = prop_invscale_token;
            prop_score = score_scale_token(M,sid,bid,lib,M.parameters);

            if this.debug_full_score %% debug to make sure full-score matches
                prop_score2 = score_scale_token(M,sid,bid,lib,M.parameters,true);
                if ~isinf(prop_score)
                    assert(aeq(prop_score-curr_score,prop_score2-curr_score2));
                    fprintf(1,'DEBUG: MH Scale token passed score test\n');
                end
            end

            %% accept or reject
            accept = mh_accept(prop_score,curr_score);
            if ~accept
               M.S{sid}.invscales_token(bid) = curr_invscale_token;
            end
            val_new = M.S{sid}.invscales_token(bid);

            this.accept_scale_token = this.accept_scale_token + accept;
            this.n_scale_token = this.n_scale_token + 1;

        end

        %% GLOBAL POSITION FOR UNIHIST RELATION
        function [val_new,accept] = mh_gobal_position(this,sid,M,lib)

            %% sid: stroke index
            assert(strcmp(M.S{sid}.R.type,'unihist'));

            %% make proposal
            curr_gpos = M.S{sid}.R.gpos;
            prop_gpos = propose_global_position(curr_gpos,M.parameters);

            %% score proposal
            curr_score = score_global_position(M,sid,lib);
            if this.debug_full_score
               curr_score2 = score_global_position(M,sid,lib,true);
            end
            M.S{sid}.R.gpos = prop_gpos;
            prop_score = score_global_position(M,sid,lib);

            if this.debug_full_score %% debug to make sure full-score matches
                prop_score2 = score_global_position(M,sid,lib,true);
                if ~isinf(prop_score)
                    assert(aeq(prop_score-curr_score,prop_score2-curr_score2));
                    fprintf(1,'DEBUG: MH position passed score test\n');
                end
            end

            %% accept or reject
            accept = mh_accept(prop_score,curr_score);
            if ~accept
                M.S{sid}.R.gpos = curr_gpos;
            end
            val_new = M.S{sid}.R.gpos;

            this.accept_gpos = this.accept_gpos + accept;
            this.n_gpos = this.n_gpos + 1;

        end

        %% POSITION FOR A STROKE
        function [val_new,accept] = mh_token_position(this,sid,M,lib)
            %% sid: stroke index

            %% make proposal
            curr_pos_token = M.S{sid}.pos_token;
            prop_pos_token = propose_local_position(curr_pos_token,M.parameters);

            %% score proposal
            curr_score = score_local_position(M,sid,lib);
            if this.debug_full_score
               curr_score2 = score_local_position(M,sid,lib,true);
            end
            M.S{sid}.pos_token = prop_pos_token;
            prop_score = score_local_position(M,sid,lib);

            if this.debug_full_score %% debug to make sure full-score matches
                prop_score2 = score_local_position(M,sid,lib,true);
                if ~isinf(prop_score)
                    assert(aeq(prop_score-curr_score,prop_score2-curr_score2));
                    fprintf(1,'DEBUG: MH token position passed score test\n');
                end
            end

            %% accept or reject
            accept = mh_accept(prop_score,curr_score);
            if ~accept
                M.S{sid}.pos_token = curr_pos_token;
            end
            val_new = M.S{sid}.pos_token;

            this.accept_pos_token = this.accept_pos_token + accept;
            this.n_pos_token = this.n_pos_token + 1;
        end

        %% EVAL-SPOT TYPE
        function [val_new,accept] = mh_eval_spot_type(this,sid,M,lib)
            %% sid: stroke index
            assert(strcmp(M.S{sid}.R.type,'mid'));

            %% make proposal
            curr_eval_spot_type = M.S{sid}.R.eval_spot_type;
            assert(~isempty(curr_eval_spot_type));
            prop_eval_spot_type = propose_eval_spot(curr_eval_spot_type,M.parameters);

            %% score proposal
            curr_score = score_eval_spot_type(M,sid,lib,M.parameters);
            if this.debug_full_score
                curr_score2 = score_eval_spot_type(M,sid,lib,M.parameters,true);
            end
            M.S{sid}.R.eval_spot_type = prop_eval_spot_type;
            prop_score = score_eval_spot_type(M,sid,lib,M.parameters);

            if this.debug_full_score %% debug to make sure full-score matches
               prop_score2 = score_eval_spot_type(M,sid,lib,M.parameters,true);
               if ~isinf(prop_score)
                    assert(aeq(prop_score-curr_score,prop_score2-curr_score2));
                    fprintf(1,'DEBUG: MH eval spot type passed score test\n');
                end
            end

            %% accept or reject
            accept = mh_accept(prop_score,curr_score);
            if ~accept
                M.S{sid}.R.eval_spot_type = curr_eval_spot_type;
            end
            val_new = M.S{sid}.R.eval_spot_type;

            this.accept_seval = this.accept_seval + accept;
            this.n_seval = this.n_seval + 1;

        end

        function [val_new,accept] = mh_eval_spot_token(this,sid,M,lib)
            %% sid: stroke index
            assert(strcmp(M.S{sid}.R.type,'mid'));

            %% make proposal
            curr_eval_spot_token = M.S{sid}.R.eval_spot_token;
            prop_eval_spot_token = propose_eval_spot(curr_eval_spot_token,M.parameters);

            %% score proposal
            curr_score = score_eval_spot_token(M,sid,lib,M.parameters);
            if this.debug_full_score
                curr_score2 = score_eval_spot_token(M,sid,lib,M.parameters,true);
            end
            M.S{sid}.R.eval_spot_token = prop_eval_spot_token;
            prop_score = score_eval_spot_token(M,sid,lib,M.parameters);

            if this.debug_full_score %% debug to make sure full-score matches
               prop_score2 = score_eval_spot_token(M,sid,lib,M.parameters,true);
               if ~isinf(prop_score)
                    assert(aeq(prop_score-curr_score,prop_score2-curr_score2));
                    fprintf(1,'DEBUG: MH eval spot token passed score test\n');
                end
            end

            %% accept or reject
            accept = mh_accept(prop_score,curr_score);
            if ~accept
                M.S{sid}.R.eval_spot_token = curr_eval_spot_token;
            end
            val_new = M.S{sid}.R.eval_spot_token;

            this.accept_seval_token = this.accept_seval_token + accept;
            this.n_seval_token = this.n_seval_token + 1;

        end

        %% SUB-STROKE IDS
        function [val_new,accept] = gibbs_substroke_id(this,sid,bid,M,lib)
            % sid: stroke index
            % bid: sub-stroke index
            curr_id = M.S{sid}.ids(bid);
            nclust = lib.N;
            score = score_all_subid(M,sid,bid,lib);

            if this.debug_full_score
                score2 = zeros(nclust,1);
                for c=1:nclust
                    M.S{sid}.ids(bid) = c;
                    score2(c) = scoreMP(M,lib);
                end
                v1 = score-logsumexp(score(:));
                v2 = score2-logsumexp(score2(:));
                v1(isinf(v1)) = [];
                v2(isinf(v2)) = [];
                assert( aeq(v1,v2) );
                fprintf(1,'DEBUG: Gibbs sub-stroke ids passed score test\n');
            end

            %% normalize probability distribution
            score = score - logsumexp(score);
            pvec = exp(score);
            assert(aeq(sum(pvec),1));
            pvec = pvec ./ sum(pvec);

            %% sample the new id
            vr = mnrnd(1,pvec);
            assert(~any(isnan(vr)));
            new_id = find(vr);
            M.S{sid}.ids(bid) = new_id;
            accept = new_id ~= curr_id;

            val_new = M.S{sid}.ids(bid);

            this.accept_sid  = this.accept_sid + accept;
            this.n_sid = this.n_sid + 1;

        end

        %% RELATION (WITH TOKEN PARAMETER FOR ATTACHMENT)
        function [val_new,accept] = mh_relation(this,sid,M,lib)

            %% make proposal
            PM = defaultps;
            curr_R = M.S{sid}.R;
            prop_R = propose_relation(M.S{sid}.pos_token,M.S(1:sid-1),lib,PM);

            %% score proposal
            curr_score = score_relation(M,sid,lib);
            g_prop_to_curr = pp_relation(M,sid,lib,PM);
            if this.debug_full_score
                curr_score2 = score_relation(M,sid,lib,true);
            end
            M.S{sid}.R = prop_R;
            prop_score = score_relation(M,sid,lib);

            g_curr_to_prop = pp_relation(M,sid,lib,PM);
            if this.debug_full_score
               prop_score2 = score_relation(M,sid,lib,true);
               if ~isinf(prop_score)
                    assert(aeq(prop_score-curr_score,prop_score2-curr_score2));
                    fprintf(1,'DEBUG: MH relation passed score test\n');
                end
            end

            %% accept or reject
            accept = mh_accept(prop_score,curr_score,g_curr_to_prop,g_prop_to_curr);
            if ~accept
                M.S{sid}.R = curr_R;
            end
            val_new = M.S{sid}.R;

            %% record keeping
            this.accept_r = this.accept_r + accept;
            this.n_r = this.n_r + 1;

        end

    end
end

%% general MH acceptance function
%%
%% Input
%%  prop_score: log-probability of model with proposal
%%  curr_score: log-probability of current model
%%  g_curr_to_prop: log-prob. of transition from current to proposal model
%%  g_prop_to_curr: reverse log-prob
function accept = mh_accept(prop_score,curr_score,g_curr_to_prop,g_prop_to_curr)
    if exist('g_curr_to_prop','var')
        lr = prop_score - curr_score + g_prop_to_curr - g_curr_to_prop;
    else
        lr = prop_score - curr_score;
    end

    if isinf(prop_score)
       accept = false;
       return
    end

    r = min(1,exp(lr));
    assert(~isinf(curr_score));
    accept = rand < r;
end

function R = propose_relation(pos_token,prev_strokes,lib,PM)
    %% Propose new relation by sampling from prior, except the global
    %% position is sampled from near the token position
    R = CPD.sample_relation_type(lib,prev_strokes);
    if strcmp(R.type,'mid')
        R.eval_spot_token = CPD.sample_relation_token(lib,R.eval_spot_type);
    elseif strcmp(R.type,'unihist')
        R.gpos(1) = pos_token(1) + PM.mcmc_prop_relpos_mlty*lib.rel.sigma_x*randn;
        R.gpos(2) = pos_token(2) + PM.mcmc_prop_relpos_mlty*lib.rel.sigma_y*randn;
    end
end

function ll = pp_relation(M,sid,lib,PM)
    %% The probability of proposing relation M.S{sid}.R
    ll = CPD.score_relation_type(lib,M.S{sid}.R);
    if strcmp(M.S{sid}.R.type,'mid')
       ll = ll + CPD.score_relation_token(lib,M.S{sid}.R.eval_spot_token,...
                                              M.S{sid}.R.eval_spot_type);
    elseif strcmp(M.S{sid}.R.type,'unihist')
       gpos = M.S{sid}.R.gpos;
       pos_token = M.S{sid}.pos_token;
       ll = ll - lib.Spatial.score(gpos,sid); %% since this sample was not used
       ll = ll + mvnormpdfln(gpos(1),pos_token(1),PM.mcmc_prop_relpos_mlty*lib.rel.sigma_x);
       ll = ll + mvnormpdfln(gpos(2),pos_token(2),PM.mcmc_prop_relpos_mlty*lib.rel.sigma_y);
    end
end

%% RELATIONS

function ll = score_relation(M,sid,lib,fullscore)
    if ~exist('fullscore','var')
       fullscore = false;
    end
    if fullscore
        ll = scoreMP(M,lib);
        return
    end

    ll = CPD.score_relation_type(lib,M.S{sid}.R);
    if strcmp(M.S{sid}.R.type,'mid')
       ll = ll + CPD.score_relation_token(lib,M.S{sid}.R.eval_spot_token,...
                                              M.S{sid}.R.eval_spot_type);
    end
    pos = M.S{sid}.pos_token;
    ll = ll + CPD.score_position(lib,pos,M.S{sid}.R,M.S(1:sid-1));
end

%% SHAPE

function shape_type = propose_shape_type(shape_type,PM)
    [~,dim,n] = size(shape_type);
    assert(dim==2 && n==1);
    shape_type = shape_type + PM.mcmc.prop_shape_sd .* randn(size(shape_type));
end

function shape_token = propose_shape_token(shape_token,PM)
    shape_token = propose_shape_type(shape_token,PM);
end

function score = score_shape_type(M,sid,bid,lib,~,fullscore)
    if ~exist('fullscore','var')
       fullscore = false;
    end
    if fullscore
        score = scoreMP(M,lib);
        return
    end
    shape_type = M.S{sid}.shapes_type(:,:,bid);
    shape_token = M.S{sid}.shapes_token(:,:,bid);
    id = M.S{sid}.ids(bid);
    lp = CPD.score_shape_type(lib,shape_type,id);
    ll = CPD.score_shape_token(lib,shape_token,shape_type);
    score = lp + ll;
end

function [score,out] = score_shape_token(M,sid,bid,lib,~,fullscore)
    if ~exist('fullscore','var')
       fullscore = false;
    end
    if fullscore
        [score,out] = scoreMP(M,lib);
        return
    end
    shape_type = M.S{sid}.shapes_type(:,:,bid);
    shape_token = M.S{sid}.shapes_token(:,:,bid);

    %% account for future positions, which this parameter may influence
    ll_next_pos = 0;
    for i=sid+1:M.ns
       nextS = M.S{i};
       ll_next_pos = ll_next_pos + CPD.score_position(lib,nextS.pos_token,nextS.R,M.S(1:i-1));
    end

    %% sum up scores
    score = ll_next_pos + CPD.score_image(M.I,M.pimg) + CPD.score_shape_token(lib,shape_token,shape_type);
end

%% SCALE

function invscales_type = propose_scale_type(invscales_type,PM)
    assert(isscalar(invscales_type));
    invscales_type = invscales_type + PM.mcmc.prop_scale_sd .* randn(size(invscales_type));
end

function invscales_token = propose_scale_token(invscales_token,PM)
    invscales_token = propose_scale_type(invscales_token,PM);
end

function score = score_scale_type(M,sid,bid,lib,~,fullscore)
    if ~exist('fullscore','var')
       fullscore = false;
    end
    if fullscore
        score = scoreMP(M,lib);
        return
    end
    scales_type = M.S{sid}.invscales_type(bid);
    scales_token = M.S{sid}.invscales_token(bid);
    id = M.S{sid}.ids(bid);
    lp = CPD.score_invscale_type(lib,scales_type,id);
    ll = CPD.score_invscale_token(lib,scales_token,scales_type);
    score = lp + ll;
end

function score = score_scale_token(M,sid,bid,lib,~,fullscore)
    if ~exist('fullscore','var')
       fullscore = false;
    end
    if fullscore
        score = scoreMP(M,lib);
        return
    end
    scales_type = M.S{sid}.invscales_type(bid);
    scales_token = M.S{sid}.invscales_token(bid);

    %% account for future positions, which this parameter may influence
    ll_next_pos = 0;
    for i=sid+1:M.ns
       nextS = M.S{i};
       ll_next_pos = ll_next_pos + CPD.score_position(lib,nextS.pos_token,nextS.R,M.S(1:i-1));
    end

    score = ll_next_pos + CPD.score_image(M.I,M.pimg) + CPD.score_invscale_token(lib,scales_token,scales_type);
end

%% POSITION

function pos = propose_local_position(pos,PM)
    pos = propose_global_position(pos,PM);
end

function gpos = propose_global_position(gpos,PM)
    gpos = gpos + PM.mcmc.prop_gpos_sd .* randn(size(gpos));
end

function score = score_global_position(M,sid,lib,fullscore)
    if ~exist('fullscore','var')
       fullscore = false;
    end
    if fullscore
        score = scoreMP(M,lib);
        return
    end
    R = M.S{sid}.R;
    lp = CPD.score_relation_type(lib,R);
    ll = CPD.score_position(lib,M.S{sid}.pos_token,R,M.S(1:sid-1));
    score = lp + ll;
end

function score = score_local_position(M,sid,lib,fullscore)
    if ~exist('fullscore','var')
       fullscore = false;
    end
    if fullscore
        score = scoreMP(M,lib);
        return
    end
    R = M.S{sid}.R;
    ll = CPD.score_position(lib,M.S{sid}.pos_token,R,M.S(1:sid-1));

    %% account for future positions, which this parameter may influence
    ll_next_pos = 0;
    for i=sid+1:M.ns
       nextS = M.S{i};
       ll_next_pos = ll_next_pos + CPD.score_position(lib,nextS.pos_token,nextS.R,M.S(1:i-1));
    end

    score = CPD.score_image(M.I,M.pimg) + ll + ll_next_pos;
end

%% EVALUATION SPOT RELATION

function eval_spot_type = propose_eval_spot(eval_spot_type,PM)
    eval_spot_type = eval_spot_type + PM.mcmc.prop_relmid_sd .* randn;
end

function score = score_eval_spot_type(M,sid,lib,~,fullscore)
    if ~exist('fullscore','var')
       fullscore = false;
    end
    if fullscore
        score = scoreMP(M,lib);
        return
    end
    R = M.S{sid}.R;
    lp = CPD.score_relation_type(lib,R);
    ll = CPD.score_relation_token(lib,R.eval_spot_token,R.eval_spot_type);
    score = lp + ll;
end

function score = score_eval_spot_token(M,sid,lib,~,fullscore)
    if ~exist('fullscore','var')
       fullscore = false;
    end
    if fullscore
        score = scoreMP(M,lib);
        return
    end
    R = M.S{sid}.R;
    lp = CPD.score_relation_token(lib,R.eval_spot_token,R.eval_spot_type);
    ll = CPD.score_position(lib,M.S{sid}.pos_token,R,M.S(1:sid-1));
    score = lp + ll;
end

author: brendenlake

repo: BPL

save_path: github-repos/MATLAB/brendenlake-BPL


text:
function vw = zoomInplane(vw, resetFlag);
% view = zoomInplane(view, <resetFlag=0>);
%
% Zooms the 3-view. Allows the subject to click once (rect or center of
% zooming) on one of the views of the brain, gets the new extent of view,
% and sets the other axes to be consistent with the new zoom extent.
%
% resetFlag: if 1, will reset the zoom to be the whole view size and
% update the axis bounds of the image. If 0 <default>, will get the zoom
% from the user input.
%
% 05/04 ras, from zoom3view.
% 06/02 ras: now just updates zoom w/ AXIS command, rather than
% going through a full refresh. Also added resetFlag, so both
% zoom buttons have callbacks to this function (for Inplane/Flat views).
montageFlag = isequal(vw.viewType, 'Inplane'); % 1 for inplanes, 0 for other

% this should only work on Inplane or Flat views
if ~ismember(vw.viewType,{'Inplane' 'Flat'}),    return;      end

if exist('resetFlag', 'var') && resetFlag==1
    % reset the zoom
    dims = viewGet(vw,'Size');
    zoom = [1 dims(2) 1 dims(1)];
else
    %%%%%%%%%%%%%%%%%%%%
    % Get data from UI %
    %%%%%%%%%%%%%%%%%%%%
    [X, Y] = ginput(2);

    zoom = [X(1) X(2) Y(1) Y(2)];

    % montage views will need some fiddling:
    if isfield(vw.ui,'montageSize') || isfield(vw.ui,'numLevelEdit')
        montageFlag = 1;
        [zoom, rows, cols] = montage2Coords(vw, [Y X]', 1);

        % set to zoom format [xmin xmax ymin ymax], or [cols rows]
        zoom = [zoom(2,1) zoom(2,2) zoom(1,1) zoom(1,2)];

        % get current zoom size
        dims =viewGet(vw,'Size');

        % ensure the zoom values are increasing (if the pts were clipped,
        % this may not be the case)
        if zoom(1) > zoom(2), zoom(1:2) = zoom([2 1]); end
        if zoom(3) > zoom(4), zoom(3:4) = zoom([4 3]); end

    else
        montageFlag = 0;
    end
end

vw.ui.zoom = zoom;

axes(vw.ui.mainAxisHandle);
if montageFlag==1
    % we need to refresh the screen
    vw = refreshScreen(vw);
else
    % we can just use the zoom directly
    axis(zoom);
end

return

% zoom on
%
% waitForClick = ginput(1);
%
% zoom = round(axis);

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft