function kf = linear_correlation(xf, yf)
%LINEAR_CORRELATION Linear Kernel at all shifts, i.e. correlation.
%   Computes the dot-product for all relative shifts between input images
%   X and Y, which must both be MxN. They must also be periodic (ie.,
%   pre-processed with a cosine window). The result is an MxN map of
%   responses.
%
%   Inputs and output are all in the Fourier domain.
%
%   Joao F. Henriques, 2014
%   http://www.isr.uc.pt/~henriques/

	%cross-correlation term in Fourier domain
	kf = sum(xf .* conj(yf), 3) / numel(xf);

end


text:
function f = p15_f ( n, x )

%*****************************************************************************80
%
%% P15_F evaluates the objective function for problem 15.
%
%  Discussion:
%
%    The Hessian matrix is doubly singular at the minimizer,
%    suggesting that most optimization routines will experience
%    a severe slowdown in convergence.
%
%    The problem is usually only defined for N being a multiple of 4.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    05 May 2000
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Richard Brent,
%    Algorithms for Minimization with Derivatives,
%    Dover, 2002,
%    ISBN: 0-486-41998-3,
%    LC: QA402.5.B74.
%
%  Parameters:
%
%    Input, integer N, the number of variables.
%
%    Input, real X(N), the argument of the objective function.
%
%    Output, real F, the value of the objective function.
%
  f = 0.0;

  for j = 1 : 4 : n

    if ( j + 1 <= n )
      xjp1 = x(j+1);
    else
      xjp1 = 0.0;
    end

    if ( j + 2 <= n )
      xjp2 = x(j+2);
    else
      xjp2 = 0.0;
    end

    if ( j + 3 <= n )
      xjp3 = x(j+3);
    else
      xjp3 = 0.0;
    end

    f1 = x(j) + 10.0 * xjp1;

    if ( j + 1 <= n )
      f2 = xjp2 - xjp3;
    else
      f2 = 0.0;
    end

    if ( j + 2 <= n )
      f3 = xjp1 - 2.0 * xjp2;
    else
      f3 = 0.0;
    end

    if ( j + 3 <= n )
      f4 = x(j) - xjp3;
    else
      f4 = 0.0;
    end

    f = f +        f1 * f1 ...
          +  5.0 * f2 * f2 ...
          +        f3 * f3 * f3 * f3 ...
          + 10.0 * f4 * f4 * f4 * f4;

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function rhs = globNedFitRHS3D(fm,fp, mesh, fem, dind, vind)

%% USAGE: generate global load vector on a tetrahedral mesh
%
% INPUTS:
% fun --- the load function from PDE (pde.f)
% mesh --- a struct data contains mesh information.
% fem --- global DoF for test function space
% dind --- derivative info for test function
%            d = [0,0,0]: function value
%            d = [1,0,0]: Dx value
%            d = [0,1,0]: Dy value
%            d = [0,0,1]: Dz value
%
% OUTPUTS:
% rhs --- global rhs vector

% Last Modified: 08/07/2020 by Xu Zhang

%% 1. RHS on non-interface elements
dof = fem.ldof;  nloc = dof; nt = length(mesh.t);
A = fem.area; gw = fem.gw; gx = fem.gx; gy = fem.gy; gz = fem.gz;
X = zeros(nloc*nt, 1);

feEvalBas = @EvalNed1Bas3D;

f = feval(fm,gx,gy,gz);
tId2 = (mesh.tLoc == 2);
f(tId2,:) = feval(fp,gx(tId2,:),gy(tId2,:),gz(tId2,:));
ind = 0;
I = reshape(fem.g2ldof,nloc*nt,1);
for i = 1:dof
    ibas = feEvalBas(fem.bas, ':', gx, gy, gz, i, dind, vind);
    X(ind+1:ind+nt) = A.*sum((ibas.*f).*gw',2).*fem.t_e_orit(:,i);
    ind = ind + nt;
end
rhs = sparse(I,1,X,length(fem.gdof),1);

repo: ifem


text:
function [Psi2, P] = linard2VardistPsi2Compute(linard2kern, vardist, Z)

% LINARD2VARDISTPSI2COMPUTE description.

% VARGPLVM

%Psi1 = linard2KernCompute(linard2kern, vardist.means, Z);
%sqrtAS = sparse(diag(linard2kern.inputScales.*sqrt(sum(vardist.covars,1))));
%Zsc = Z*sqrtAS;
%P = Psi1'*Psi1;
%Psi2 = P + Zsc*Zsc';

ZA = Z*sparse(diag(linard2kern.inputScales));

P = vardist.means'*vardist.means + diag(sum(vardist.covars,1));

Psi2 = ZA*P*ZA';

author: SheffieldML

repo: vargplvm


text:
function Projector = in_projector_fif( SspFiles, ChannelNames )
% IN_PROJECTOR_FIF: Read a FIF file, and return a brainstorm Channel structure.
%
% USAGE:  Projector = in_projector_fif( SspFile, ChannelNames );
%         Projector = in_projector_fif( projs, ChannelNames );

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

global FIFF;

%% ===== PARSE INPUTS =====
if ischar(SspFiles)
    SspFiles = {SspFiles};
end
% Remove spaces in all the channel names
tmp = ChannelNames;
ChannelNames = cellfun(@(c)upper(c(c~=' ')), ChannelNames, 'UniformOutput', 0);

%% ===== READ PROJECTORS =====
projs = [];
% Read files
if iscell(SspFiles)
    % Loop on all files
    for i = 1:length(SspFiles)
        % Open SSP file
        [ fid, tree ]  = fiff_open(SspFiles{i});
        if (fid < 0)
            error(['Cannot open FIFF file : "' SspFiles{i} '"']);
        end
        % Read projectors
        node = fiff_dir_tree_find(tree, FIFF.FIFFB_PROJ);
        newProjs = fiff_read_proj(fid, node);
        % Add projectors to list of all projectors to combine
        if isempty(projs)
            projs = newProjs;
        else
            projs = [projs, newProjs];
        end
        % Close SSP file
        fclose(fid);
    end
% Projectors already loaded
elseif isstruct(SspFiles)
    projs = SspFiles;
else
    error('Invalid input.');
end

%% ====== BUILD PROJECTION MATRIX =====
Projector = repmat(db_template('projector'), 0);
nChannels = length(ChannelNames);
% Collect all the projections from the FIF file
for i = 1:length(projs)
    % Check type of the projector
    if (projs(i).kind ~= FIFF.FIFFV_PROJ_ITEM_FIELD)
        fprintf(1, 'SSP> Unsupported type of projector #%d: "%s". Skipping...\n', projs(i).kind, projs(i).desc);
        continue;
    end
    % Copy basic information
    iNew = length(Projector) + 1;
    Projector(iNew).Comment = projs(i).desc;
    if projs(i).active
        Projector(iNew).Status = 2;  % Recordings in the file saved this way
    else
        Projector(iNew).Status = 1;  % Projector is selected and applied dynamically to the recordings
    end
    % Get the projectors values
    data = projs(i).data;
    % Remove the spaces in the channel names
    data.col_names = cellfun(@(c)upper(c(c~=' ')), data.col_names, 'UniformOutput', 0);
    % Copy the information of each channel
    U = zeros(nChannels, data.nrow);
    for iCol = 1:data.ncol
        iChan = find(strcmpi(data.col_names{iCol}, ChannelNames));
        if isempty(iChan)
            % Channel not found
            continue;
        elseif (length(iChan) > 1)
            disp('IN> Warning: Several channels have the same name, the result might be random...');
            iChan = iChan(1);
        end
        U(iChan,:) = data.data(:,iCol)';
    end
    % Finish filling the entry
    Projector(iNew).Components = U;
    Projector(iNew).CompMask   = ones(1,data.nrow);
end

author: brainstorm-tools


text:
function rs = amutual2(s, len)

%tstoolbox/@signal/amutual2
%   Syntax:
%     * amutual2(s, len)
%
%   Input arguments:
%     * len - maximal lag
%
%   Auto mutual information (average) function for real scalar signals
%   using 128 equidistant partitions.
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt
narginchk(2,2);

    if (ndim(s) > 1) | (~isreal(data(s)))
	help(mfilename)
	return
end

c = amutual2(s.core, len);
rs = signal(c, s);	% special constructor calling syntax for working routines
a = getaxis(s, 1);
dl = delta(a);
a = setfirst(a, 0);
rs = setaxis(rs, 1, a);
rs = setyunit(rs, unit('Bit'));		% acf values are scalars without unit
rs = addhistory(rs, ['Auto mutual information of length ' num2str(len)]);
rs = addcommandlines(rs, 's = amutual(s', len);

author: benfulcher

repo: hctsa

save_path: github-repos/MATLAB/benfulcher-hctsa


text:
function th_img = bayesian_th(inp,s,n)
[row col]=size(inp);
th_img=zeros(row,col);
th_img(1:(row/2^n),1:(col/2^n))=inp(1:(row/2^n),1:(col/2^n));
for i=n:-1:1
    a=inp((row/2^i)+1:(row/2^(i-1)),(col/2^i)+1:(col/2^(i-1))); %diagonal coefficients
    th_img((row/2^i)+1:(row/2^(i-1)),(col/2^i)+1:(col/2^(i-1)))=th(a,s,n);
    a=inp(1:(row/2^(i)),(col/2^i)+1:(col/2^(i-1)));   %horizontal coefficients
    th_img(1:(row/2^(i)),(col/2^i)+1:(col/2^(i-1)))=th(a,s,n);
    a=inp((row/2^i)+1:(row/2^(i-1)),1:(col/2^(i)));     %vertical coefficients
    th_img((row/2^i)+1:(row/2^(i-1)),1:(col/2^(i)))=th(a,s,n);
end
end
function th_subband=th(inp_mtx,s,n)
N=numel(inp_mtx);
c=inp_mtx.^2;
sigmasq_y=(1/N)*sum(c(:));
sigma_x=sqrt(max((sigmasq_y-s),0));
% Tb1=sqrt(log10(N/n))*(s/(sigma_x));
Tb1=(s/(sigma_x));
% th_subband=sign(inp_mtx).*max(0,abs(inp_mtx)-Tb1);
th_subband=inp_mtx.*(abs(inp_mtx)>Tb1);
end

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text:
function varargout = getPrmDflt( prm, dfs, checkExtra )
% Helper to set default values (if not already set) of parameter struct.
%
% Takes input parameters and a list of 'name'/default pairs, and for each
% 'name' for which prm has no value (prm.(name) is not a field or 'name'
% does not appear in prm list), getPrmDflt assigns the given default
% value. If default value for variable 'name' is 'REQ', and value for
% 'name' is not given, an error is thrown. See below for usage details.
%
% USAGE (nargout==1)
%  prm = getPrmDflt( prm, dfs, [checkExtra] )
%
% USAGE (nargout>1)
%  [ param1 ... paramN ] = getPrmDflt( prm, dfs, [checkExtra] )
%
% INPUTS
%  prm          - param struct or cell of form {'name1' v1 'name2' v2 ...}
%  dfs          - cell of form {'name1' def1 'name2' def2 ...}
%  checkExtra   - [0] if 1 throw error if prm contains params not in dfs
%                 if -1 if prm contains params not in dfs adds them
%
% OUTPUTS (nargout==1)
%  prm    - parameter struct with fields 'name1' through 'nameN' assigned
%
% OUTPUTS (nargout>1)
%  param1 - value assigned to parameter with 'name1'
%   ...
%  paramN - value assigned to parameter with 'nameN'
%
% EXAMPLE
%  dfs = { 'x','REQ', 'y',0, 'z',[], 'eps',1e-3 };
%  prm = getPrmDflt( struct('x',1,'y',1), dfs )
%  [ x y z eps ] = getPrmDflt( {'x',2,'y',1}, dfs )
%
% See also INPUTPARSER
%
% Piotr's Image&Video Toolbox      Version 2.60
% Copyright 2012 Piotr Dollar.  [pdollar-at-caltech.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Simplified BSD License [see external/bsd.txt]

if( mod(length(dfs),2) ), error('odd number of default parameters'); end
if nargin<=2, checkExtra = 0; end

% get the input parameters as two cell arrays: prmVal and prmField
if iscell(prm) && length(prm)==1, prm=prm{1}; end
if iscell(prm)
  if(mod(length(prm),2)), error('odd number of parameters in prm'); end
  prmField = prm(1:2:end); prmVal = prm(2:2:end);
else
  if(~isstruct(prm)), error('prm must be a struct or a cell'); end
  prmVal = struct2cell(prm); prmField = fieldnames(prm);
end

% get and update default values using quick for loop
dfsField = dfs(1:2:end); dfsVal = dfs(2:2:end);
if checkExtra>0
  for i=1:length(prmField)
    j = find(strcmp(prmField{i},dfsField));
    if isempty(j), error('parameter %s is not valid', prmField{i}); end
    dfsVal(j) = prmVal(i);
  end
elseif checkExtra<0
  for i=1:length(prmField)
    j = find(strcmp(prmField{i},dfsField));
    if isempty(j), j=length(dfsVal)+1; dfsField{j}=prmField{i}; end
    dfsVal(j) = prmVal(i);
  end
else
  for i=1:length(prmField)
    dfsVal(strcmp(prmField{i},dfsField)) = prmVal(i);
  end
end

% check for missing values
if any(strcmp('REQ',dfsVal))
  cmpArray = find(strcmp('REQ',dfsVal));
  error(['Required field ''' dfsField{cmpArray(1)} ''' not specified.'] );
end

% set output
if nargout==1
  varargout{1} = cell2struct( dfsVal, dfsField, 2 );
else
  varargout = dfsVal;
end

author: zouchuhang

repo: LayoutNet


text:
% long list of the files in reverse time order
ls -lrt

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function im = HOGpicture(w, bs)
% Make picture of positive HOG weights.
%   im = HOGpicture(w, bs)

% AUTORIGHTS
% -------------------------------------------------------
% Copyright (C) 2011-2012 Ross Girshick
% Copyright (C) 2008, 2009, 2010 Pedro Felzenszwalb, Ross Girshick
% Copyright (C) 2007 Pedro Felzenszwalb, Deva Ramanan
%
% This file is part of the voc-releaseX code
% (http://people.cs.uchicago.edu/~rbg/latent/)
% and is available under the terms of an MIT-like license
% provided in COPYING. Please retain this notice and
% COPYING if you use this file (or a portion of it) in
% your project.
% -------------------------------------------------------

% construct a "glyph" for each orientaion
bim1 = zeros(bs, bs);
bim1(:,round(bs/2):round(bs/2)+1) = 1;
bim = zeros([size(bim1) 9]);
bim(:,:,1) = bim1;
for i = 2:9,
  bim(:,:,i) = imrotate(bim1, -(i-1)*20, 'crop');
end

% make pictures of positive weights bs adding up weighted glyphs
s = size(w);
w(w < 0) = 0;
im = zeros(bs*s(1), bs*s(2));
for i = 1:s(1),
  iis = (i-1)*bs+1:i*bs;
  for j = 1:s(2),
    jjs = (j-1)*bs+1:j*bs;
    for k = 1:9,
      im(iis,jjs) = im(iis,jjs) + bim(:,:,k) * w(i,j,k);
    end
  end
end

author: rbgirshick

repo: voc-dpm

save_path: github-repos/MATLAB/rbgirshick-voc-dpm


text:
function C = train_LDA(xTr, yTr, varargin)
% TRAIN_LDA - linear discriminant analysis
%
%Synopsis:
%   C = train_LDA(XTR, YTR)
%   C = train_LDA(XTR, YTR, OPTS)
%
%Arguments:
%   XTR: DOUBLE [NxM] - Data matrix, with N feature dimensions, and M training points/examples.
%   YTR: INT [CxM] - Class membership labels of points in X_TR. C by M matrix of training
%                     labels, with C representing the number of classes and M the number of training examples/points.
%                     Y_TR(i,j)==1 if the point j belongs to class i.
%   OPT: PROPLIST - Structure or property/value list of optional
%                   properties. Options are also passed to clsutil_shrinkage.
%     'ExcludeInfs' - BOOL (default 0): If true, training data points with value 'inf' are excluded from XTR
%     'Prior' - DOUBLE (default ones(nClasses, 1)/nClasses): Empirical class priors
%     'StorePrior' - BOOL (default 0): If true, the prior will be stored with the classifier in C.prior
%     'Scaling' - BOOL (default 0): scale projection vector such that the distance between
%        the projected means becomes 2. Scaling only implemented for 2 classes so far. Using Scaling=1 will disable the use of a prior.
%     'StoreMeans' - BOOL (default 0): If true, the classwise means of the feature vectors
%        are stored in the classifier structure C. This can be used, e.g., for bbci_adaptation_pmean
%     'UsePcov' - BOOL (default 0): If true, the pooled covariance matrix is used instead of the average classwise covariance matrix.
%     'StoreCov',  - BOOL (default 0): If true, the covariance matrix will be stored with the classifier in C.cov
%     'StoreInvcov' - BOOL (default 0): If true, the inverse of the covariance matrix is stored in
%        the classifier structure C. This can be used, e.g., for bbci_adaptation_pcovmean
%     'StoreExtinvcov' - BOOL (default 0): If true, the extended inverse of the covariance will be stored with the classifier in C.extinvcov
%
%Returns:
%   C: STRUCT - Trained classifier structure, with the hyperplane given by
%               fields C.w and C.b.  C includes the fields:
%    'w' : weight matrix
%    'b' : FLOAT bias
%    'prior' : (optional) classwise priors
%    'means' :  (optional) classwise means
%    'cov' :  (optional) covariance matrix
%    'invcov' :  (optional) inverse of the covariance matrix
%    'extinvcov' : (optional) extended inverse of the covariance matrix
%
%Description:
%   TRAIN_RLDA trains a LDA classifier on data X with class
%   labels given in LABELS.
%
%Examples:
%   train_LDA(X, labels)
%
%See also:
%   APPLY_SEPARATINGHYPERPLANE

opt = opt_proplistToStruct(varargin{:});
opt.Gamma = 0;
C = train_RLDAshrink(xTr, yTr, opt);

author: bbci


text:
function [varargout]=graphicsModels(varargin)

% function [F,V]=graphicsModels(modelID)
% ------------------------------------------------------------------------
%
%
% Kevin Mattheus Moerman
% gibbon.toolbox@gmail.com
%
% 2015/04/25 Added to GIBBON
% 2019 added David, dolfin
% 2020 added spine
% 2020/07/28 added zero output mode (show surface)
%------------------------------------------------------------------------

%% Parse input

switch nargin
    case 0
        modelID=1;
    case 1
        modelID=varargin{1};
end

%%
defaultFolder = fileparts(fileparts(mfilename('fullpath')));
pathName=fullfile(defaultFolder,'data','libSurf');

switch modelID
    case {1,'stanford_bunny'}
        fileName=fullfile(pathName,'stanford_bunny_closed.mat');
        meshData=load(fileName);
    case {2,'utah_teapot'}
        fileName=fullfile(pathName,'utah_teapot.mat');
        meshData=load(fileName);
    case {3,'cow'}
        fileName=fullfile(pathName,'cow.mat');
        meshData=load(fileName);
    case {4,'parasaurolophus'}
        fileName=fullfile(pathName,'parasaurolophus.mat');
        meshData=load(fileName);
    case {5,'femur'}
        fileName=fullfile(pathName,'femur.mat');
        meshData=load(fileName);
    case {6,'hip_implant'}
        fileName=fullfile(pathName,'hip_implant.mat');
        meshData=load(fileName);
    case {7,'elephant'}
        fileName=fullfile(pathName,'elephant.mat');
        meshData=load(fileName);
    case {8,'dolphin'}
        fileName=fullfile(pathName,'dolphin.mat');
        meshData=load(fileName);
    case {9,'david'}
        % Reduced density version of a David model from SMK - Statens Museum for Kunst
        fileName=fullfile(pathName,'david.mat');
        meshData=load(fileName);
    case {10,'nefertiti'}
        fileName=fullfile(pathName,'nefertiti.mat');
        meshData=load(fileName);
    case {11,'vertebra'}
        fileName=fullfile(pathName,'vertebra.mat');
        meshData=load(fileName);
    case {12,'suzanne'}
        fileName=fullfile(pathName,'suzanne.mat');
        meshData=load(fileName);
    case {13,'nefertiti_high'}
        % Resampled version of nefertiti model available from:
        % https://www.cs.cmu.edu/~kmcrane/Projects/ModelRepository/
        % The original mesh was scanned by Nora Al-Badri and Jan Nikolai
        % Nelles from the Nefertiti bust, which was created in 1345 BC by
        % Thutmose. Released under creative commons license.
        fileName=fullfile(pathName,'nefertiti_high.mat');
        meshData=load(fileName);
end

F=meshData.F;
V=meshData.V;

switch nargout
    case 0
        cFigure;
        gpatch(F,V,'w','k');
        axisGeom;
        camlight headlight;
        gdrawnow;
    case 1
        varargout{1}=meshData;
    case 2
        varargout{1}=F;
        varargout{2}=V;
    case 3
        varargout{1}=F;
        varargout{2}=V;
        %Get color data
        if isfield(meshData,'C')
            C=meshData.C;
        else
            C=ones(size(F,1),1);
        end
        varargout{3}=C;
end

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% 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/>.

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
% .............................................................
function [weights,locations]=gauss2d(option)
    % Gauss quadrature in 2D
    % option '5x5'
    % ...
    % option '2x2'
    % option '1x1'
    % locations: Gauss point locations
    % weights: Gauss point weights

%% Data Table
switch option
    case '1x1'
        x = 0;
        w = 2;
        pattern = [1];
    case '2x2'
        x = [-sqrt(3)/3,sqrt(3)/3]';
        w = [1,1]';
        pattern = [1 2 4 3];
    case '3x3'
        x = [-sqrt(3/5),0,sqrt(3/5)]';
        w = [5/9,8/9,5/9]';
        pattern = [1 3 9 7 2 6 8 4 5];
    case '4x4'
        x1 = sqrt((3-2*sqrt(6/5))/7);
        x2 = sqrt((3+2*sqrt(6/5))/7);
        x = [-x1,-x2,x2,x1]';
        w1 = (18+sqrt(30))/36;
        w2 = (18-sqrt(30))/36;
        w = [w1,w2,w2,w1]';
        pattern = [1 4 16 13 2 3 8 12 15 14 9 5 6 7 11 10];
    case '5x5'
        x1 = (1/3)*sqrt(5-2*sqrt(10/7));
        x2 = (1/3)*sqrt(5+2*sqrt(10/7));
        x3 = 0;
        x = [-x1,-x2,x3,x2,x1]';
        w1 = (322 + 13*sqrt(70))/900;
        w2 = (322 - 13*sqrt(70))/900;
        w3 = 128/225;
        w = [w1,w2,w3,w2,w1]';
        pattern = [1 5 25 21 2 3 4 10 15 20 24 23 22 16 11 6 7 8 9 14 19 18 17 12 13];
    otherwise
        error('ngp max value = 5')
end

%% Compute Arrays,
[xi1,xi2] = meshgrid(x,x);
[wi1,wi2] = meshgrid(w,w);
n = length(w)^2;
locations = [reshape(xi2,n,1),reshape(xi1,n,1)]; %locations=[x,y]
weights  = reshape(wi1.*wi2,n,1);

%% Arrange gauss points
locations = locations(pattern,:);
weights = weights(pattern,:);

end  % end function gauss2d

repo: Aero-matlab


text:
function smallT = marg_table(bigT, bigdom, bigsz, onto, maximize)
% MARG_TABLE Marginalize a table
% smallT = marg_table(bigT, bigdom, bigsz, onto, maximize)

if nargin < 5, maximize = 0; end

smallT = myreshape(bigT, bigsz); % make sure it is a multi-dim array
sum_over = mysetdiff(bigdom, onto);
ndx = find_equiv_posns(sum_over, bigdom);
if maximize
  for i=1:length(ndx)
    smallT = max(smallT, [], ndx(i));
  end
else
  for i=1:length(ndx)
    smallT = sum(smallT, ndx(i));
  end
end

ns = zeros(1, max(bigdom));
%ns(bigdom) = mysize(bigT); % ignores trailing dimensions of size 1
ns(bigdom) = bigsz;

smallT = squeeze(smallT); % remove all dimensions of size 1
smallT = myreshape(smallT, ns(onto)); % put back relevant dims of size 1

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function z = proj_sdp(z,n)
if n==0
    return;
elseif n==1
    z = max(z,0);
    return;
end

% expand to full size matrix
b = tril(ones(n));
b(b == 1) = z;
z = b;
z = (z + z');
z = z - diag(diag(z)) / 2;

% rescale so projection works, and matrix norm preserved
% see http://www.seas.ucla.edu/~vandenbe/publications/mlbook.pdf pg 3
% scale diags by sqrt(2)
z(eye(n) == 1) = z(eye(n) == 1) .* sqrt(2);

[V,S] = eig(z);
S = diag(S);

idx = find(S>0);
V = V(:,idx);
S = S(idx);
z = V*diag(S)*V';

% scale diags by 1/sqrt(2)
z(eye(n) == 1) = z(eye(n) == 1) ./ sqrt(2);

z = z(tril(ones(n)) == 1);
end

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
function d = month_to_ides_roman ( m )

%*****************************************************************************80
%
%% MONTH_TO_IDES_ROMAN returns the day of the ides of a Roman month.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 March 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the month index.
%
%    Output, integer D, the day of the ides of the month.
%
  ides = [ 13, 13, 15, 13, 15, 13, 15, 13, 13, 15, 13, 13 ];

  if ( m < 1 || 12 < m )
    d = -1;
  else
    d = ides(m);
  end

  return
end


text:
function [visualField,corners,areaROI, retPhases, view] = atlasDefinition(atlasName, scans, fields, view)
%   [visualField,corners,areaROI, retPhases, view] = atlasDefinition(atlasName, scans, fields, view)
%
% Author: Wandell, Brewer
% Purpose:
%    Define the properties of a group of retinotopic visual areas that
%    will serve as an atlas for template matching.
%
%   scans are the scanNums of the ring (scans(1)) and
%   wedge (scans(2)) data.
%
%
% INPUTS:
%	atlasName: name of atlas to fit.
%
%	scans: [2 x 1] vector of [eccentricity, polar angle] scan numbers for
%	the current data type in the flat view.
%
%	fields: {2 x 1} cell array of {eccentricity, polar angle} field names
%	(out of 'ph', 'map', 'amp', 'co') from which to draw the data.
%
%	view: flat view we're using to fit.
%
%
% [visualField,corners,areaROI,retPhases,view] = atlasDefinition('ventralV2V3V4',[2,1],FLAT{2});
%
% History:
% 15/11/04  marking V1/V2/V3 changed by MMS (mark@ski.org) so that you no
% longer mark V1 then V2 then V3 but just mark V1 and V3. V2 is then assumed
% to lie between.
% see line 282, I think this deal with the problems adressed in 272 by
% Wandell or Brewer
%
% ras, 04/09: many changes.
% (1) takes as input parameters the field name, as well of the scan, of the
% ecc / polar angle data (to allow for pRF data fitting).
% (2) broke each atlas type into its own subfunction.
%

%% check we've passed in the proper input arguments
if ~isequal(view.viewType, 'Flat')
	error('Need a flat view.')
end

% show all ROIs
view.ui.showROIs=-2;
view = refreshView(view);

% % for some reason, we need to have the flat not rotated flipped. We should
% % fix this.
% if sum(abs([view.rotateImageDegrees,view.flipLR]))~=0
%     error('The fields ''.rotateImageDegrees'' and ''.flipLR'' of the FLAT structure must be zero.');
% end

% call the appropriate subfunction to fit the specified atlas.
switch lower(atlasName)
    case {'hemifield','hf'},
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitHemifield(view, scans, fields);
    case {'lqf','lowerquarterfield'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitLowerQuarterfield(view, scans, fields);
	case {'uqf','upperquarterfield'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitUpperQuarterfield(view, scans, fields);
    case {'hemiuppervf','hV4V3'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitV3_hV4(view, scans, fields);
    case {'2hemifields','VO1VO2'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitVO1_VO2(view, scans, fields);
    case 'mt/mst circular'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitMT_MST(view, scans, fields);
	case 'v1/v2'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitV1_V2(view, scans, fields);
    case 'v1/v2/v3'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitV1_V2_V3(view, scans, fields);
    case 'v4/v8'
        error('Not yet implemented: v4/v8');
    case {'lo2/to1/to2' '2 hemifields + 2a manual without LO1'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitLO2_TO1_TO2(view, scans, fields);
	case '4 hemifields'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fit4Hemifields(view, scans, fields);
	case '4 hemifields old'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fit4HemifieldsOld(view, scans, fields);
    case 'common atlas with 4 hemifields'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fit4HemifieldsCommonAtlas(view, scans, fields);
    case '2 hemifields + 2a'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fit2HemifieldsPlus2a(view, scans, fields);
    case '2 hemifields + 2a common'
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fit2HemifieldsPlus2aCommon(view, scans, fields);
    case {'v1/v2/v3/lo1/lo2' 'v1ToLO2'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitV1_to_LO2(view, scans, fields);
    case {'v1/v2/v3/lo1/lo22' 'v1ToLO2_alt'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitV1_to_LO2_alt(view, scans, fields);
    case {'v1/v2/v3/lo1/lo2/to1/to2' 'v1ToTO2'}
		 [view, visualField, corners, retPhases, areaROI] = ...
			 fitV1_to_TO2(view, scans, fields);
    case 'ventralv2v3v4'
        [view,visualField,corners,retPhases,areaROI] = ...
			fitVentralV2V3V4(view, scans, fields);
    otherwise
        error(sprintf('Unknown atlas name: %s', atlasName));
end

% Show the user what just happened.
view = refreshView(view);

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitHemifield(view, scans, fields);
% Fit an unspecified hemifield representation.

% set up a string to make the message strings easier.
newline = sprintf('\n');   % this will make the message strings easier.
msg = ['Select Hemifield in the data to which to fit the atlas.' newline ...
	   'Point 1: LOW eccentricity and LOW polar angle.' newline ...
	   'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
	   'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
	   'Point 4: HIGH eccentricity and LOW polar angle. '];

visualField{1} = 'hemifield';   %V1

corners = {};
msgHndl = mrMessage(msg, 'left', [], 9);

[locs, areaROI{1}, view] = atlasGraphicDefinition('quadrilateral',view);
corners{1} = locs.corners;
delete(msgHndl);

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [retPhases] = fitLowerQuarterfield(view, scans, fields);
% Fit an unspecified lower-quarter field representation.
newline = sprintf('\n');   % this will make the message strings easier.
msg = ['Select a Lower Quarter Field Representation in the data.' newline ...
	   'Point 1: LOW eccentricity and LOW polar angle.' newline ...
	   'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
	   'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
	   'Point 4: HIGH eccentricity and LOW polar angle. '];

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'lowerquarterfield';   % Dorsal V3, for example

corners = {};
msgHndl = mrMessage(msg{1},'left',[0.8000    0.1000    0.1800    0.1000]);

[locs, areaROI{1},view] = atlasGraphicDefinition('quadrilateral',view);
corners{1} = locs.corners;
delete(msgHndl);

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [retPhases] = fitUpperQuarterfield(view, scans, fields);
% Fit an unspecified upper-quarter field representation.
newline = sprintf('\n');   % this will make the message strings easier.
msg = ['Select an Upper Quarter Field Representation in the data.' newline ...
	   'Point 1: LOW eccentricity and LOW polar angle.' newline ...
	   'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
	   'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
	   'Point 4: HIGH eccentricity and LOW polar angle. '];

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'upperquarterfield';   % Dorsal V3, for example

corners = {};
msgHndl = mrMessage(msg{1},'left',[0.8000    0.1000    0.1800    0.1000]);

[locs, areaROI{1},view] = atlasGraphicDefinition('quadrilateral',view);
corners{1} = locs.corners;
delete(msgHndl);

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);
return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitV3_hV4(view, scans, fields);
% Fit an upper quarter field, plus a hemifield.
% This fitting was designed to match ventral V3 and hV4.
newline = sprintf('\n');   % this will make the message strings easier.
msg{1} = ['Select the hemifield representation (e.g., hV4).' newline ...
		  'Point 1: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 2: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 3: HIGH eccentricity and LOW polar angle.' newline ...
		  'Point 4: HIGH eccentricity and HIGH polar angle. '];

msg{2}  = ['Select the quarterfield representation (e.g., V3v)' newline ...
		  'Point 1: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 2: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 3: HIGH eccentricity and LOW polar angle.' newline ...
		  'Point 4: HIGH eccentricity and HIGH polar angle. '];

visualField{1} = 'hemifield';           %hV4
visualField{2} = 'upperquarterfield';   %V3 Ventral

% load and display an example image to help guide the user in terms of
% which corners to click in which order:
codeDir = fileparts( which(mfilename) );
imgPath = fullfile(codeDir, 'Atlas_V3v_hV4_order.png');
try
	img = imread(imgPath, 'png');

	hGuide = figure('Color', 'w', 'Name', 'Click in this order', ...
					'Units', 'norm', 'Position', [0 .6 .3 .4], ...
					'NumberTitle', 'off');

	imshow(img);
	title('Select Points in the specified order.', 'FontSize', 18);
end

corners = {};
for ii=1:2

	msgHndl = mrMessage(msg{ii}, 'left', [], 9);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...
corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});

% Now replace the ROIs with the new ROIs with appropriately adjusted corners.
view = selectROI(view,areaROI{2});
view = replaceROIQuadrilateralCoords(view,corners{2});

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitVO1_VO2(view, scans, fields);
% Fit two hemifields (corresponding to VO-1 and VO-2).
newline = sprintf('\n');
msg{1} = ['Select the first hemifield representation (e.g., VO-1).' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

msg{2}  = ['Select the second hemifield representation (e.g., VO-2)' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'hemifield';    %VO-1
visualField{2} = 'hemifield';    %VO-2

corners = {};
for ii=1:2
	msgHndl = mrMessage(msg{ii}, 'left', [], 9);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);
end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...
corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});

% Now replace the ROIs with the new ROIs with appropriately adjusted corners.
view = selectROI(view,areaROI{2});
view = replaceROIQuadrilateralCoords(view,corners{2});

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);
return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitMT_MST(view, scans, fields);
% Fit an atlas to a circular set of visual field representations around areas MT and MST (?).
newline = sprintf('\n');
msg  = ['Select fovea.' newline ...
		'Draw line one through fovea from high to low polar angle.' newline ...
		'Draw line two roughly orthogonal.'];

msgHndl = mrMessage(msg,'left', [], 9);

[x1,y1] = getline;
x1 = x1(1:2); y1 = y1(1:2);

[x2,y2] = getline;
x2 = x2(1:2); y2 = y2(1:2);

locs.x1 = x1; locs.x2 = x2; locs.y1 = y1; locs.y2 = y2;

im=makeCircularMaps(view,locs)

% Now replace the ROIs with the new ROIs with appropriately adjusted corners.
view = selectROI(view,areaROI{2});
view = replaceROIQuadrilateralCoords(view,corners{2});
view = selectROI(view,areaROI{3});
view = replaceROIQuadrilateralCoords(view,corners{3});

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

delete(msgHndl);

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitV1_V2(view, scans, fields);
% Fit V1 (hemifield) and the two quarter fields of V2.
newline = sprintf('\n');
msg{1} = ['Select V1.' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

msg{2}  = ['Select V2d (lower quarter field).' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

msg{3}  = ['Select V2v (upper quarter field).' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

visualField{1} = 'hemifield';   %V1
visualField{2} = 'lowerquarterfield'; %Dorsal V2
visualField{3} = 'upperquarterfield'; %Ventral V2

corners = {};
for ii=1:3

	msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.1800    0.1000]);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

	% Set view to show all ROI perimeters
	view.ui.showROIs=-2;
	view = refreshView(view);

end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...
corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});
corners{3} = atlasMergeAdjacentCorners(corners{1},corners{3});

% Now replace the ROIs with the new ROIs with appropriately adjusted corners.
view = selectROI(view,areaROI{2});
view = replaceROIQuadrilateralCoords(view,corners{2});
view = selectROI(view,areaROI{3});
view = replaceROIQuadrilateralCoords(view,corners{3});

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);
return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitV1_V2_V3(view, scans, fields);
% Fit V1, V2, and V3.
newline = sprintf('\n');
msg{1} = ['Select V1.' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

msg{2}  = ['Select V3v (upper quarter field).' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

msg{3}  = ['Select V3d (lower quarter field).' newline ...
		  'Point 1: LOW eccentricity and LOW polar angle.' newline ...
		  'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
		  'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
		  'Point 4: HIGH eccentricity and LOW polar angle. '];

visualField{1} = 'hemifield';   %V1
visualField{2} = 'lowerquarterfield'; % Ventral V2
visualField{3} = 'upperquarterfield'; % Dorsal V2
visualField{4} = 'lowerquarterfield'; % Ventral V3
visualField{5} = 'upperquarterfield'; % Dorsal V3

% load and display an example image to help guide the user in terms of
% which corners to click in which order:
codeDir = fileparts( which(mfilename) );
imgPath = fullfile(codeDir, 'Atlas_V1-V3_order.png');
try
	img = imread(imgPath, 'png');

	hGuide = figure('Color', 'w', 'Name', 'Click in this order', ...
					'Units', 'norm', 'Position', [0 .6 .3 .4], ...
					'NumberTitle', 'off');

	imshow(img);
	title('Select Points in the specified order.', 'FontSize', 18);
end

% get the corners of the 3 quadrilaterals (V1, V3v, V3d), which will define
% the 5 distinct field maps:
corners = {};
for ii=1:3
	msgHndl = mrMessage(msg{ii},'left',[],9);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

	% Set view to show all ROI perimeters
	view.ui.showROIs=-2;
	view = refreshView(view);
end

% close the guide figure as well
close(hGuide);

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...

% this old merging of corner  becomes obsolet
% corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});
% corners{3} = atlasMergeAdjacentCorners(corners{1},corners{3});
% corners{4} = atlasMergeAdjacentCorners(corners{2},corners{4});
% corners{5} = atlasMergeAdjacentCorners(corners{3},corners{5});

%instead get V2 corners from V1 and V3
%first copy corners of V3ventral and dorsal to pos 4 ad 5
corners{4}=corners{2};
corners{5}=corners{3};

%V2v
corners{2}(1,1:2)=corners{4}(1,1:2); %from V3v
corners{2}(2:3,1:2)=corners{1}(2:3,1:2); %from V1
corners{2}(4,1:2)=corners{4}(4,1:2); %from V3v

%V2d
corners{3}(1,1:2)=corners{1}(1,1:2); %from V1
corners{3}(2:3,1:2)=corners{5}(2:3,1:2); %from V1
corners{3}(4,1:2)=corners{1}(4,1:2);%from V1

%add the ROIS 4 and 5 to the ROI-List and to the "areaROI"-variable
%---- maybe there is a more elegant way to perform this....

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end
roiName = sprintf('Quad-%.0f',num);
view=newROI(view,roiName,1,[0 0 0]);
areaROI=cat(2,areaROI,{roiName});
roiName = sprintf('Quad-%.0f',num+1);
view=newROI(view,roiName,1,[0 0 0]);
areaROI=cat(2,areaROI,{roiName});

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplified...
for jup=2:5
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);
retPhases = [0 pi*2 pi*0.5 pi*1.5];

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitLO2_TO1_TO2(view, scans, fields);
% select MT, MST, LO2 amd the wall of MST
msg{1}  = ['Select hemifield (e.g., TO1)' newline pointSpec];

msg{2}  = sprintf('Select hemifield (e.g., TO2)\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

msg{3}  = sprintf('Select quarterfield next to the first hemifield (e.g., LO2)\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{3},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{3} = addText(msg{3},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{3} = addText(msg{3},newText);

msg{4}  = sprintf('Select quarterfield next to the second hemifield\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{4},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{4} = addText(msg{4},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{4} = addText(msg{4},newText);

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'hemifield';    % TO1
visualField{2} = 'hemifield';    % TO2
visualField{3} = 'hemifield';    % LO2
visualField{4} = 'hemifield';    % wall
visualField{5} = 'hemifield';    % wall
visualField{6} = 'hemifield';    % wall
visualField{7} = 'hemifield';    % LO1

corners = {};
for ii=1:4
	msgHndl = mrMessage(msg{ii}, 'left', [], 9);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);
end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...
%         corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});
%         corners{3} = atlasMergeAdjacentCorners(corners{1},corners{3});
%         corners{4} = atlasMergeAdjacentCorners(corners{2},corners{4});

tmp=round((corners{1}(1,1:2)+corners{3}(1,1:2))/2);
corners{1}(1,1:2)=tmp;
corners{3}(1,1:2)=tmp;
tmp=round((corners{1}(4,1:2)+corners{3}(4,1:2))/2);
corners{1}(4,1:2)=tmp;
corners{3}(4,1:2)=tmp;

corners{7}(2:3,:) = corners{3}(2:3,:);
corners{7}(1,:) = corners{7}(2,:) + (corners{7}(2,:)-corners{3}(1,:));
corners{7}(4,:) = corners{7}(3,:) + (corners{7}(3,:)-corners{3}(4,:));

tmp=round((corners{1}(2:3,1:2)+corners{2}(2:3,1:2))/2);
corners{1}(2:3,1:2)=tmp;
corners{2}(2:3,1:2)=tmp;

tmp=round((corners{2}(1,1:2)+corners{4}(1,1:2))/2);
corners{2}(1,1:2)=tmp;
corners{4}(1,1:2)=tmp;

tmp=round((corners{2}(4,1:2)+corners{4}(4,1:2))/2);
corners{2}(4,1:2)=tmp;
corners{4}(4,1:2)=tmp;

corners{5}(1,1:2)=corners{1}(1,1:2);
corners{5}(2,1:2)=corners{2}(1,1:2);
corners{5}(3:4,1:2)=round([corners{5}(2,1:2); corners{5}(1,1:2)]*1.5-[corners{2}(4,1:2);corners{1}(4,1:2)]*0.5);
corners{5}(1,1:2)=corners{5}(1,1:2)+round((corners{5}(1,1:2)-corners{5}(4,1:2))*0.2);
corners{5}(2,1:2)=corners{5}(2,1:2)+round((corners{5}(2,1:2)-corners{5}(3,1:2))*0.2);

corners{6}(3,1:2)=corners{1}(4,1:2);
corners{6}(4,1:2)=corners{2}(4,1:2);
corners{6}(1:2,1:2)=round([corners{6}(4,1:2); corners{6}(3,1:2)]*1.5-[corners{2}(1,1:2);corners{1}(1,1:2)]*0.5);
corners{6}(3,1:2)=corners{6}(3,1:2)+round((corners{6}(3,1:2)-corners{6}(2,1:2))*0.2);
corners{6}(4,1:2)=corners{6}(4,1:2)+round((corners{6}(4,1:2)-corners{6}(1,1:2))*0.2);

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end

for newroi=1:3
	roiName = sprintf('Quad-%.0f',num+newroi-1);
	view=newROI(view,roiName,1,[0 0 0]);
	areaROI=cat(2,areaROI,{roiName});
end

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplyfied...
for jup=1:7
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

retPhases = [0 pi*2 pi/2 pi];
%         retPhases = [0 pi*2 pi/2 -pi/2];

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fit4HemifieldsOld(view, scans, fields);
% old version of the 4 hemifields fitting code (?).
% select MT, MST, LO2 amd LO1

        msg{1}  = sprintf('Select hemifield (e.g., TO1)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
        newText = sprintf('Continue to complete the quadrilateral');      msg{1} = addText(msg{1},newText);

        msg{2}  = sprintf('Select hemifield (e.g., TO2)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
        newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

        msg{3}  = sprintf('Select hemifield (e.g., LO2)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{3},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{3} = addText(msg{3},newText);
        newText = sprintf('Continue to complete the quadrilateral');  msg{3} = addText(msg{3},newText);

        msg{4}  = sprintf('Select hemifield (e.g., LO1)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{4},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{4} = addText(msg{4},newText);
        newText = sprintf('Continue to complete the quadrilateral');  msg{4} = addText(msg{4},newText);

        % This becomes, say, the V1/V2 function.
        % It gets its own message box and is a template for the creation of other
        % atlas creation routines.
        visualField{1} = 'hemifield';    % TO1
        visualField{2} = 'hemifield';    % TO2
        visualField{3} = 'hemifield';    % LO2
        visualField{4} = 'hemifield';    % wall
        visualField{5} = 'hemifield';    % wall
        visualField{6} = 'hemifield';    % wall
        visualField{7} = 'hemifield';    % LO1

        corners = {};
        for ii=1:4
            msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.1800    0.1000]);

            [locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
            corners{ii} = locs.corners;

            delete(msgHndl);

        end

        % We need a GUI for deciding who goes with what.  This ordering of the code
        % assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
        % We might make sure that we always get a certain corner match.  Sometimes,
        % two corners end up being matched to the same one ...
        %         corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});
        %         corners{3} = atlasMergeAdjacentCorners(corners{1},corners{3});
        %         corners{4} = atlasMergeAdjacentCorners(corners{2},corners{4});

        corners{7}=corners{4};

        % LO1 LO2 border
        tmp=round((corners{7}(2:3,1:2)+corners{3}(2:3,1:2))/2);
        corners{7}(2:3,1:2)=tmp;
        corners{3}(2:3,1:2)=tmp;

        % LO2 MT border
        tmp=round((corners{3}(1,1:2)+corners{1}(1,1:2))/2);
        corners{3}(1,1:2)=tmp;
        corners{1}(1,1:2)=tmp;
        tmp=round((corners{3}(4,1:2)+corners{1}(4,1:2))/2);
        corners{3}(4,1:2)=tmp;
        corners{1}(4,1:2)=tmp;

        % MT MST border
        tmp=round((corners{1}(2:3,1:2)+corners{2}(2:3,1:2))/2);
        corners{1}(2:3,1:2)=tmp;
        corners{2}(2:3,1:2)=tmp;

        % wall of MST
        corners{4}(1,:) = corners{2}(1,:);
        corners{4}(4,:) = corners{2}(4,:);
        corners{4}(2,:) = corners{4}(1,:) + round((corners{2}(1,:)-corners{2}(2,:))*0.3);
        corners{4}(3,:) = corners{4}(4,:) + round((corners{2}(4,:)-corners{2}(3,:))*0.3);

        % wall of MT, MST
        corners{5}(1,1:2)=corners{1}(1,1:2);
        corners{5}(2,1:2)=corners{2}(1,1:2);
        corners{5}(3:4,1:2)=round([corners{5}(2,1:2); corners{5}(1,1:2)]*1.3-[corners{2}(4,1:2);corners{1}(4,1:2)]*0.3);
        corners{5}(1,1:2)=corners{5}(1,1:2)+round((corners{5}(1,1:2)-corners{5}(4,1:2))*0.2);
        corners{5}(2,1:2)=corners{5}(2,1:2)+round((corners{5}(2,1:2)-corners{5}(3,1:2))*0.2);

        % wall of MT, MST
        corners{6}(3,1:2)=corners{1}(4,1:2);
        corners{6}(4,1:2)=corners{2}(4,1:2);
        corners{6}(1:2,1:2)=round([corners{6}(4,1:2); corners{6}(3,1:2)]*1.3-[corners{2}(1,1:2);corners{1}(1,1:2)]*0.3);
        corners{6}(3,1:2)=corners{6}(3,1:2)+round((corners{6}(3,1:2)-corners{6}(2,1:2))*0.2);
        corners{6}(4,1:2)=corners{6}(4,1:2)+round((corners{6}(4,1:2)-corners{6}(1,1:2))*0.2);

        % not to exceed the area
        corners{4}(find(corners{4}<1))=1;
        corners{4}(find(corners{4}>size(view.anat,1)))=size(view.anat,1);
        corners{5}(find(corners{5}<1))=1;
        corners{5}(find(corners{5}>size(view.anat,1)))=size(view.anat,1);
        corners{6}(find(corners{6}<1))=1;
        corners{6}(find(corners{6}>size(view.anat,1)))=size(view.anat,1);

%         for i=1:4
%             if norm(corners{5}(i,:)-(size(view.anat,1)+1)/2)>(size(view.anat,1)-1)/2*sqrt(2);
%                 corners{5}(i,:) = floor(corners{5}(i,:)/norm(corners{5}(i,:)-(size(view.anat,1)-1)/2)*(size(view.anat,1)+1)/2)
%             end
%         end

        found = roiExistName(view,'Quad',0)
        if found == 0, num = 1; else num = length(found)+1; end

        for newroi=1:3
            roiName = sprintf('Quad-%.0f',num+newroi-1);
            view=newROI(view,roiName,1,[0 0 0]);
            areaROI=cat(2,areaROI,{roiName});
        end

        % Now replace the ROIs with the new ROIs with appropriately
        % adjusted corners.  Simplyfied...
        for jup=1:7
            view = selectROI(view,areaROI{jup});
            view = replaceROIQuadrilateralCoords(view,corners{jup});
        end

        retPhases = [0 pi*2 pi/2 pi];
        %         retPhases = [0 pi*2 pi/2 -pi/2];

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view, visualField, corners, retPhases, areaROI] = fit4Hemifields(view, scans, fields)
% Fit 4 adjacent hemifields -- designed as a model for
% TO1, TO2, LO2 amd LO1 + wall of LO1 and MST
        clear msg

        msg{1}  = sprintf('Select hemifield (e.g., LO1)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
        newText = sprintf('Continue to complete the quadrilateral');      msg{1} = addText(msg{1},newText);

        msg{2}  = sprintf('Select hemifield (e.g., LO2)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
        newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

        msg{3}  = sprintf('Select hemifield (e.g., TO1)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{3},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{3} = addText(msg{3},newText);
        newText = sprintf('Continue to complete the quadrilateral');  msg{3} = addText(msg{3},newText);

        msg{4}  = sprintf('Select hemifield (e.g., TO2)\n');
        newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{4},newText);
        newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{4} = addText(msg{4},newText);
        newText = sprintf('Continue to complete the quadrilateral');  msg{4} = addText(msg{4},newText);

        % This becomes, say, the V1/V2 function.
        % It gets its own message box and is a template for the creation of other
        % atlas creation routines.
        visualField{1} = 'hemifield';    % LO1
        visualField{2} = 'hemifield';    % LO2
        visualField{3} = 'hemifield';    % TO1
        visualField{4} = 'hemifield';    % TO2
        visualField{5} = 'upperquarterfield';    % wall of LO1
        visualField{6} = 'upperquarterfield';    % wall of TO2

        corners = {};
        for ii=1:4
            msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.1800    0.1000]);

            [locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
            corners{ii} = locs.corners;

            delete(msgHndl);

        end

        % LO1 LO2 border
        tmp=round((corners{1}(2:3,1:2)+corners{2}(2:3,1:2))/2);
        corners{1}(2:3,1:2)=tmp;
        corners{2}(2:3,1:2)=tmp;

        % LO2 TO1 border
        tmp=round((corners{2}(1,1:2)+corners{3}(1,1:2))/2);
        corners{2}(1,1:2)=tmp;
        corners{3}(1,1:2)=tmp;
        tmp=round((corners{2}(4,1:2)+corners{3}(4,1:2))/2);
        corners{2}(4,1:2)=tmp;
        corners{3}(4,1:2)=tmp;

        % TO1 TO2 border
        tmp=round((corners{3}(2:3,1:2)+corners{4}(2:3,1:2))/2);
        corners{3}(2:3,1:2)=tmp;
        corners{4}(2:3,1:2)=tmp;

        % wall of LO1
        corners{5}(1,:) = corners{1}(1,:);
        corners{5}(4,:) = corners{1}(4,:);
        corners{5}(2,:) = corners{5}(1,:) + round((corners{1}(1,:)-corners{1}(2,:))*0.5);
        corners{5}(3,:) = corners{5}(4,:) + round((corners{1}(4,:)-corners{1}(3,:))*0.5);

        % wall of TO2
        corners{6}(1,:) = corners{4}(1,:);
        corners{6}(4,:) = corners{4}(4,:);
        corners{6}(2,:) = corners{6}(1,:) + round((corners{4}(1,:)-corners{4}(2,:))*0.5);
        corners{6}(3,:) = corners{6}(4,:) + round((corners{4}(4,:)-corners{4}(3,:))*0.5);

        % not to exceed the area
        corners{5}(find(corners{5}<1))=1;
        corners{5}(find(corners{5}>size(view.anat,1)))=size(view.anat,1);
        corners{6}(find(corners{6}<1))=1;
        corners{6}(find(corners{6}>size(view.anat,1)))=size(view.anat,1);

        found = roiExistName(view,'Quad',0)
        if found == 0, num = 1; else num = length(found)+1; end

        for newroi=1:2
            roiName = sprintf('Quad-%.0f',num+newroi-1);
            view=newROI(view,roiName,1,[0 0 0]);
            areaROI=cat(2,areaROI,{roiName});
        end

        % Now replace the ROIs with the new ROIs with appropriately
        % adjusted corners.  Simplyfied...
        for jup=1:6
            view = selectROI(view,areaROI{jup});
            view = replaceROIQuadrilateralCoords(view,corners{jup});
        end

        retPhases = [0 pi*2 pi/2 pi];
        %         retPhases = [0 pi*2 pi/2 -pi/2];

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fit4HemifieldsCommonAtlas(view, scans, fields);

        % select MT, MST, LO2 amd LO1

        visualField{1} = 'hemifield';    % TO1
        visualField{2} = 'hemifield';    % TO2
        visualField{3} = 'hemifield';    % LO2
        visualField{4} = 'hemifield';    % wall
        visualField{5} = 'hemifield';    % wall
        visualField{6} = 'hemifield';    % wall
        visualField{7} = 'hemifield';    % LO1

        corners = {};

        corners{1} = [40 50; 40 65; 80 65; 80 50];
        corners{2} = [40 80; 40 65; 80 65; 80 80];
        corners{3} = [40 50; 40 35; 80 35; 80 50];
        corners{4} = [40 80; 40 95; 80 95; 80 80];
        corners{5} = [40 50; 40 80; 20 80; 20 50];
        corners{6} = [100 80; 100 50; 80 50; 80 80];
        corners{7} = [40 20; 40 35; 80 35; 80 20];

        num=1;
        areaROI=[];
        for newroi=1:7
            roiName = sprintf('Quad-%.0f',num+newroi-1);
            view=newROI(view,roiName,1,[0 0 0]);
            areaROI=cat(2,areaROI,{roiName});
        end

        % Now replace the ROIs with the new ROIs with appropriately
        % adjusted corners.  Simplyfied...
        for jup=1:7
            view = selectROI(view,areaROI{jup});
            view = replaceROIQuadrilateralCoords(view,corners{jup});
        end

        retPhases = [0 pi*2 pi/2 pi];

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fit2HemifieldsPlus2a(view, scans, fields);
% Don't know what this means. It was specified as case '2 hemifields +  2a'
% at top. I'm guessing it's just TO-1 and TO-2?
msg{1}  = sprintf('Select hemifield (e.g., TO1)\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
newText = sprintf('Continue to complete the quadrilateral');      msg{1} = addText(msg{1},newText);

msg{2}  = sprintf('Select hemifield (e.g., TO2)\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'hemifield';    %TO-1
visualField{2} = 'hemifield';    %TO-2
visualField{3} = 'upperquarterfield';    %LO2
visualField{4} = 'upperquarterfield';    %MST2
%         visualField{3} = 'hemifield';    %LO2
%         visualField{4} = 'hemifield';    %MST2
visualField{5} = 'hemifield';    %V3d
visualField{6} = 'hemifield';    %MST2

corners = {};
for ii=1:2
	msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.1800    0.1000]);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...
%         corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});
%         corners{3} = atlasMergeAdjacentCorners(corners{1},corners{3});
%         corners{4} = atlasMergeAdjacentCorners(corners{2},corners{4});

tmp=round((corners{1}(2:3,1:2)+corners{2}(2:3,1:2))/2);
corners{1}(2:3,1:2)=tmp;
corners{2}(2:3,1:2)=tmp;

%         corners{1}(2,1:2)=corners{1}(2,1:2)+abs(corners{1}(2,1:2)-corners{1}(3,1:2));
%         corners{1}(3,1:2)=corners{1}(3,1:2)+abs(corners{1}(3,1:2)-corners{1}(2,1:2));
%         corners{2}(2,1:2)=corners{2}(2,1:2)+abs(corners{2}(2,1:2)-corners{2}(3,1:2));
%         corners{2}(3,1:2)=corners{2}(3,1:2)+abs(corners{2}(3,1:2)-corners{2}(2,1:2));

corners{3}(1,1:2)=corners{1}(1,1:2);
corners{3}(4,1:2)=corners{1}(4,1:2);
corners{3}(2:3,1:2)=[corners{1}(1,1:2);corners{1}(4,1:2)]*2-corners{1}(2:3,1:2);

corners{4}(1,1:2)=corners{2}(1,1:2);
corners{4}(4,1:2)=corners{2}(4,1:2);
corners{4}(2:3,1:2)=[corners{2}(1,1:2);corners{2}(4,1:2)]*2-corners{2}(2:3,1:2);

corners{5}(1,1:2)=corners{1}(1,1:2);
corners{5}(2,1:2)=corners{2}(1,1:2);
corners{5}(3:4,1:2)=round([corners{5}(2,1:2); corners{5}(1,1:2)]*1.5-[corners{2}(4,1:2);corners{1}(4,1:2)]*0.5);
corners{5}(1,1:2)=corners{5}(1,1:2)+round((corners{5}(1,1:2)-corners{5}(4,1:2))*0.2);
corners{5}(2,1:2)=corners{5}(2,1:2)+round((corners{5}(2,1:2)-corners{5}(3,1:2))*0.2);

corners{6}(3,1:2)=corners{1}(4,1:2);
corners{6}(4,1:2)=corners{2}(4,1:2);
corners{6}(1:2,1:2)=round([corners{6}(4,1:2); corners{6}(3,1:2)]*1.5-[corners{2}(1,1:2);corners{1}(1,1:2)]*0.5);
corners{6}(3,1:2)=corners{6}(3,1:2)+round((corners{6}(3,1:2)-corners{6}(2,1:2))*0.2);
corners{6}(4,1:2)=corners{6}(4,1:2)+round((corners{6}(4,1:2)-corners{6}(1,1:2))*0.2);

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end

for newroi=1:4
	roiName = sprintf('Quad-%.0f',num+newroi-1);
	view=newROI(view,roiName,1,[0 0 0]);
	areaROI=cat(2,areaROI,{roiName});
end

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplyfied...
for jup=1:6
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

retPhases = [0 pi*2 pi/2 pi];

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fit2HemifieldsPlus2aCommon(view, scans, fields);
% Don't know what this means. It was specified as case '2 hemifields +  2a common'
% at top. I'm guessing it's just TO-1 and TO-2, sharing a common boundary?
msg{1}  = sprintf('Select hemifield (e.g., TO1)\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
newText = sprintf('Continue to complete the quadrilateral');      msg{1} = addText(msg{1},newText);

msg{2}  = sprintf('Select hemifield (e.g., TO2)\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'hemifield';    %TO-1
visualField{2} = 'hemifield';    %TO-2
visualField{3} = 'upperquarterfield';    %LO2
visualField{4} = 'upperquarterfield';    %MST2
visualField{5} = 'hemifield';    %V3d
visualField{6} = 'hemifield';    %MST2

corners = {};
for ii=1:2
	msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.1800    0.1000]);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

end

corners{1}=[50 50; 50 65; 70 65; 70 50];
corners{2}=[50 80; 50 65; 70 65; 70 80];

corners{3}(1,1:2)=corners{1}(1,1:2);
corners{3}(4,1:2)=corners{1}(4,1:2);
corners{3}(2:3,1:2)=[corners{1}(1,1:2);corners{1}(4,1:2)]*2-corners{1}(2:3,1:2);

corners{4}(1,1:2)=corners{2}(1,1:2);
corners{4}(4,1:2)=corners{2}(4,1:2);
corners{4}(2:3,1:2)=[corners{2}(1,1:2);corners{2}(4,1:2)]*2-corners{2}(2:3,1:2);

corners{5}(1,1:2)=corners{1}(1,1:2);
corners{5}(2,1:2)=corners{2}(1,1:2);
corners{5}(3:4,1:2)=round([corners{5}(2,1:2); corners{5}(1,1:2)]*1.5-[corners{2}(4,1:2);corners{1}(4,1:2)]*0.5);
%         corners{5}(1,1:2)=corners{5}(1,1:2)+round((corners{5}(1,1:2)-corners{5}(4,1:2))*0.2);
%         corners{5}(2,1:2)=corners{5}(2,1:2)+round((corners{5}(2,1:2)-corners{5}(3,1:2))*0.2);

corners{6}(3,1:2)=corners{1}(4,1:2);
corners{6}(4,1:2)=corners{2}(4,1:2);
corners{6}(1:2,1:2)=round([corners{6}(4,1:2); corners{6}(3,1:2)]*1.5-[corners{2}(1,1:2);corners{1}(1,1:2)]*0.5);
%         corners{6}(3,1:2)=corners{6}(3,1:2)+round((corners{6}(3,1:2)-corners{6}(2,1:2))*0.2);
%         corners{6}(4,1:2)=corners{6}(4,1:2)+round((corners{6}(4,1:2)-corners{6}(1,1:2))*0.2);

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end

for newroi=1:4
	roiName = sprintf('Quad-%.0f',num+newroi-1);
	view=newROI(view,roiName,1,[0 0 0]);
	areaROI=cat(2,areaROI,{roiName});
end

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplyfied...
for jup=1:6
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

retPhases = [0 pi*2 pi/2 pi];
%         retPhases = [0 pi*2 pi/2 -pi/2];

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitV1_to_TO2(view, scans, fields);
% Fit 7 visual field maps: V1, V2, V3, LO-1, LO-2, TO-1, TO-2.
clear msg

newline = sprintf('\n');
pointsOrder = ['Point 1: LOW eccentricity and LOW polar angle.' newline ...
				'Point 2: LOW eccentricity and HIGH polar angle.' newline ...
				'Point 3: HIGH eccentricity and HIGH polar angle.' newline ...
				'Point 4: HIGH eccentricity and LOW polar angle. '];

msg{1}  = ['Select V1.' newline pointsOrder];
msg{2}  = ['Select V3v.' newline pointsOrder];
msg{3}  = ['Select V3d.' newline pointsOrder];
msg{4}  = ['Select LO2.' newline pointsOrder];
msg{5}  = ['Select TO2.' newline pointsOrder]

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'hemifield';   % V1
visualField{2} = 'lowerquarterfield'; % V3v
visualField{3} = 'upperquarterfield'; % V3d
visualField{4} = 'hemifield';   % LO2
visualField{5} = 'hemifield';   % TO2
visualField{6} = 'lowerquarterfield'; % V2v
visualField{7} = 'upperquarterfield'; % V2d
visualField{8} = 'hemifield';   %LO1
visualField{9} = 'hemifield';   %TO1

corners = {};
for ii=1:5
	msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.200    0.1200]);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

	% Set view to show all ROI perimeters
	view.ui.showROIs=-2;
	view = refreshView(view);
end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...

%V2v
corners{6}(1,1:2)=corners{2}(1,1:2); %from V3v
corners{6}(2:3,1:2)=corners{1}(2:3,1:2); %from V1
corners{6}(4,1:2)=corners{2}(4,1:2); %from V3v

%V2d
corners{7}(1,1:2)=corners{1}(1,1:2); %from V1
corners{7}(2:3,1:2)=corners{3}(2:3,1:2); %from V3d
corners{7}(4,1:2)=corners{1}(4,1:2);%from V1

%LO1
corners{8}(1,1:2)=corners{3}(1,1:2); %from V3d
corners{8}(2:3,1:2)=corners{4}(2:3,1:2); %from LO2
corners{8}(4,1:2)=corners{3}(4,1:2);%from V3d

%TO1
corners{9}(1,1:2)=corners{4}(1,1:2); %from LO2
corners{9}(2:3,1:2)=corners{5}(2:3,1:2); %from TO2
corners{9}(4,1:2)=corners{4}(4,1:2);%from LO2

%add the ROIS 6-9 to the ROI-List and to the "areaROI"-variable
%---- maybe there is a more elegante way to perform this....

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end

for newroi=1:4
	roiName = sprintf('Quad-%.0f',num+newroi-1);
	view=newROI(view,roiName,1,[0 0 0]);
	areaROI=cat(2,areaROI,{roiName});
end

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplyfied...
for jup=2:9
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitV1_to_LO2_alt(view, scans, fields);
% I'm guessing this is an alternate version of the V1->LO2 fitting?
% It fits v1/v2/v3/lo1/lo2.
msg{1}  = sprintf('Select V1.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
newText = sprintf('Continue to complete the quadrilateral.\n');      msg{1} = addText(msg{1},newText);
newText = sprintf('NEW: After marking V1, continue with marking V3v, just with the same scheme.\n');msg{1} = addText(msg{1},newText);

msg{2}  = sprintf('Select V3v.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

msg{3}  = sprintf('Select V3d.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{3} = addText(msg{3},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{3} = addText(msg{3},newText);
newText = sprintf('Continue to complete the quadrilateral');   msg{3} = addText(msg{3},newText);

msg{4}  = sprintf('Select LO2.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{4} = addText(msg{4},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{4} = addText(msg{4},newText);
newText = sprintf('Continue to complete the quadrilateral');   msg{4} = addText(msg{4},newText);

visualField{1} = 'hemifield';   % V1
visualField{2} = 'lowerquarterfield'; % V3v
visualField{3} = 'upperquarterfield'; % V3d
visualField{4} = 'hemifield';   % LO2
visualField{5} = 'lowerquarterfield'; % V2v
visualField{6} = 'upperquarterfield'; % V2d
visualField{7} = 'hemifield';   %LO1

corners = {};
for ii=1:4
	msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.200    0.1200]);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

	% Set view to show all ROI perimeters
	view.ui.showROIs=-2;
	view = refreshView(view);
end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...

%V2v
corners{5}(1,1:2)=corners{2}(1,1:2); %from V3v
corners{5}(2:3,1:2)=corners{1}(2:3,1:2); %from V1
corners{5}(4,1:2)=corners{2}(4,1:2); %from V3v

%V2d
corners{6}(1,1:2)=corners{1}(1,1:2); %from V1
corners{6}(2:3,1:2)=corners{3}(2:3,1:2); %from V3d
corners{6}(4,1:2)=corners{1}(4,1:2);%from V1

%LO1
corners{7}(1,1:2)=corners{3}(1,1:2); %from V3d
corners{7}(2:3,1:2)=corners{4}(2:3,1:2); %from LO2
corners{7}(4,1:2)=corners{3}(4,1:2);%from V3d

%add the ROIS 6-9 to the ROI-List and to the "areaROI"-variable
%---- maybe there is a more elegante way to perform this....

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end

for newroi=1:3
	roiName = sprintf('Quad-%.0f',num+newroi-1);
	view=newROI(view,roiName,1,[0 0 0]);
	areaROI=cat(2,areaROI,{roiName});
end

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplyfied...
for jup=2:9
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);
return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view visualField corners retPhases areaROI] = fitV1_to_LO2(view, scans, fields);
% fits V1, V2, V3, LO1, and LO2.
msg{1}  = sprintf('Select V1.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
newText = sprintf('Continue to complete the quadrilateral.\n');      msg{1} = addText(msg{1},newText);
newText = sprintf('NEW: After marking V1, continue with marking V3v, just with the same scheme.\n');msg{1} = addText(msg{1},newText);

msg{2}  = sprintf('Select lower quarter field of V3.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

msg{3}  = sprintf('Select upper quarter field of V3.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{3} = addText(msg{3},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{3} = addText(msg{3},newText);
newText = sprintf('Continue to complete the quadrilateral');   msg{3} = addText(msg{3},newText);

msg{4}  = sprintf('Select LO2.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');msg{4} = addText(msg{4},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{4} = addText(msg{4},newText);
newText = sprintf('Continue to complete the quadrilateral');   msg{4} = addText(msg{4},newText);

% This becomes, say, the V1/V2 function.
% It gets its own message box and is a template for the creation of other
% atlas creation routines.
visualField{1} = 'hemifield';   % V1
visualField{2} = 'lowerquarterfield'; % V3v
visualField{3} = 'upperquarterfield'; % V3d
visualField{4} = 'hemifield';   % LO2
visualField{5} = 'lowerquarterfield'; % V2v
visualField{6} = 'upperquarterfield'; % V2d
visualField{7} = 'hemifield';   %LO1

corners = {};
for ii=1:4
	msgHndl = mrMessage(msg{ii}, 'left', [], 9);

	[locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
	corners{ii} = locs.corners;

	delete(msgHndl);

	% Set view to show all ROI perimeters
	view.ui.showROIs=-2;
	view = refreshView(view);

end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...

%V2v
corners{5}(1,1:2)=corners{2}(1,1:2); %from V3v
corners{5}(2:3,1:2)=corners{1}(2:3,1:2); %from V1
corners{5}(4,1:2)=corners{2}(4,1:2); %from V3v

%V2d
corners{6}(1,1:2)=corners{1}(1,1:2); %from V1
corners{6}(2:3,1:2)=corners{3}(2:3,1:2); %from V3d
corners{6}(4,1:2)=corners{1}(4,1:2);%from V1

%LO1
corners{7}(1,1:2)=corners{3}(1,1:2); %from V3d
corners{7}(2:3,1:2)=corners{4}(2:3,1:2); %from LO2
corners{7}(4,1:2)=corners{3}(4,1:2);%from V3d

%add the ROIS 6-9 to the ROI-List and to the "areaROI"-variable
%---- maybe there is a more elegante way to perform this....

found = roiExistName(view,'Quad',0)
if found == 0, num = 1; else num = length(found)+1; end

for newroi=1:3
	roiName = sprintf('Quad-%.0f',num+newroi-1);
	view=newROI(view,roiName,1,[0 0 0]);
	areaROI=cat(2,areaROI,{roiName});
end

% Now replace the ROIs with the new ROIs with appropriately
% adjusted corners.  Simplyfied...
for jup=2:7
	view = selectROI(view,areaROI{jup});
	view = replaceROIQuadrilateralCoords(view,corners{jup});
end

% Use the data to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

return
% /-----------------------------------------------------------------/ %

% /-----------------------------------------------------------------/ %
function [view, visualField, corners, retPhases, areaROI] = fitVentralV2V3V4(view, scans, fields)
% Fit the ventral V2/V3/hV4 atlas.

msg{1}  = sprintf('Select ventral V2.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n');  msg{1} = addText(msg{1},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{1} = addText(msg{1},newText);
newText = sprintf('Continue to complete the quadrilateral');      msg{1} = addText(msg{1},newText);

msg{2}  = sprintf('Select ventral V3.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n'); msg{2} = addText(msg{2},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n');msg{2} = addText(msg{2},newText);
newText = sprintf('Continue to complete the quadrilateral');  msg{2} = addText(msg{2},newText);

msg{3}  = sprintf('Select ventral V4.\n');
newText = sprintf('Point 1: low eccentricity and angle phases.\n'); msg{3} = addText(msg{3},newText);
newText = sprintf('Point 2: low eccentricity phase and high angle phase.\n'); msg{3} = addText(msg{3},newText);
newText = sprintf('Continue to complete the quadrilateral');   msg{3} = addText(msg{3},newText);

visualField{1} = 'upperquarterfield';   % Ventral V2
visualField{2} = 'upperquarterfield';   %Ventral V3
visualField{3} = 'upperquarterfield';   %Ventral V4

corners = {};

% Set view to show all ROI perimeters
view.ui.showROIs=-2;
view = refreshView(view);
for ii=1:3
    msgHndl = mrMessage(msg{ii},'left',[0.8000    0.1000    0.1800    0.1000]);

    [locs, areaROI{ii},view] = atlasGraphicDefinition('quadrilateral',view);
    corners{ii} = locs.corners;

    delete(msgHndl);
    view = refreshView(view);
end

% We need a GUI for deciding who goes with what.  This ordering of the code
% assumes that visualArea{1} is in the middle and 2 and 3 are surrounding it.
% We might make sure that we always get a certain corner match.  Sometimes,
% two corners end up being matched to the same one ...
corners{2} = atlasMergeAdjacentCorners(corners{1},corners{2});
corners{3} = atlasMergeAdjacentCorners(corners{2},corners{3});

% Now replace the ROIs with the new ROIs with appropriately adjusted corners.
view = selectROI(view,areaROI{2});
view = replaceROIQuadrilateralCoords(view,corners{2});
view = selectROI(view,areaROI{3});
view = replaceROIQuadrilateralCoords(view,corners{3});

% Use the data in the first one to estimate the phases
c{1} = corners{1};
retPhases = atlasEstimatePhases(view, c, scans, fields);

return;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   PARAMETERS Returns a data structure containing the parameters of the
%   ABB IRB2400.
%
%   Author: Arturo Gil. Universidad Miguel Hern�ndez de Elche.
%   email: arturo.gil@umh.es date:   09/01/2012
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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

robot.name= 'ABB_IRB2400';

%Path where everything is stored for this robot
robot.path = 'robots/abb/IRB2400';

robot.DH.theta= '[q(1) q(2)-pi/2 q(3) q(4) q(5) q(6)+pi]';
robot.DH.d='[0.615 0 0 0.755 0 0.085]';
robot.DH.a='[0.100 0.705 0.135 0 0 0]';
robot.DH.alpha= '[-pi/2 0 -pi/2 pi/2 -pi/2 0]';

robot.J=[];

robot.inversekinematic_fn = 'inversekinematic_irb2400(robot, T)';

%number of degrees of freedom
robot.DOF = 6;

%rotational: 0, translational: 1
robot.kind=['R' 'R' 'R' 'R' 'R' 'R'];

%minimum and maximum rotation angle in rad
robot.maxangle =[deg2rad(-180) deg2rad(180); %Axis 1, minimum, maximum
                deg2rad(-105) deg2rad(105); %Axis 2, minimum, maximum
                deg2rad(-62.5) deg2rad(62.5); %Axis 3
                deg2rad(-200) deg2rad(200); %Axis 4:
                deg2rad(-120) deg2rad(120); %Axis 5
                deg2rad(-400) deg2rad(400)]; %Axis 6:

%maximum absolute speed of each joint rad/s or m/s
robot.velmax = [deg2rad(150); %Axis 1, rad/s
                deg2rad(150); %Axis 2, rad/s
                deg2rad(150); %Axis 3, rad/s
                deg2rad(360); %Axis 4, rad/s
                deg2rad(360); %Axis 5, rad/s
                deg2rad(450)];%Axis 6, rad/s

robot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time
            % end effectors maximum velocity
robot.linear_velmax = 1.0; %m/s, unavailable from datasheet

%base reference system
robot.T0 = eye(4);

%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION
%position, velocity and acceleration
robot=init_sim_variables(robot);

% GRAPHICS
robot.graphical.has_graphics=1;
robot.graphical.color = [255 20 20]./255;
%for transparency
robot.graphical.draw_transparent=0;
%draw DH systems
robot.graphical.draw_axes=1;
%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for
%bigger robots
robot.graphical.axes_scale=1;
%adjust for a default view of the robot
robot.axis=[-2 2 -2 2 0 2.5];
%read graphics files
robot = read_graphics(robot);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%DYNAMIC PARAMETERS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

robot.has_dynamics=1;

%link masses (kg)
robot.dynamics.masses=[0 269 60 30 20 1];

%COM of each link with respect to own reference system
robot.dynamics.r_com=[0       0.05          0; %(rx, ry, rz) link 1
    -0.550	0	 0.020; %(rx, ry, rz) link 2
    0       0       0;  %(rx, ry, rz) link 3
    0       -0.3775       0;%(rx, ry, rz) link 4
    0       0           0;%(rx, ry, rz) link 5
    0       0         0.032];%(rx, ry, rz) link 6

%Inertia matrices of each link with respect to its D-H reference system.
% Ixx	Iyy	Izz	Ixy	Iyz	Ixz, for each row
robot.dynamics.Inertia=[0      0.35	0   	0	0	0;
    .13     .524	.539	0	0	0;
    .066	.086	.0125	0	0	0;
    1.8e-3	1.3e-3	1.8e-3	0	0	0;
    .3e-3	.4e-3	.3e-3	0	0	0;
    .15e-3	.15e-3	.04e-3	0	0	0];

robot.motors=load_motors([5 5 5 4 4 4]);
%Speed reductor at each joint
robot.motors.G=[300 300 300 300 300 300];

repo: ARTE


text:
function complex_image = bpBasic(data)
%BPBASIC This function performs a basic backprojection operation.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The following fields need to be populated:                           %
% data.deltaF:  Vector containing the step size of frequency data (Hz) %
% data.minF:  Vector containing the start frequency of each pulse (Hz) %
% data.x_mat:  The x-position of each pixel (m)                        %
% data.y_mat:  The y-position of each pixel (m)                        %
% data.z_mat:  The z-position of each pixel (m)                        %
% data.Tx.X:  The transmit x-position of the sensor at each pulse (m)  %
% data.Tx.Y:  The transmit y-position of the sensor at each pulse (m)  %
% data.Tx.Z:  The transmit z-position of the sensor at each pulse (m)  %
% data.R0:  The (bistatic) range to motion-comp point (m)              %
% data.phdata:  Phase history data (frequency domain)                  %
%               Fast time in rows, slow time in columns                %
%                                                                      %
% The following fields are optional:                                   %
% data.Rcv.X:  The receive x-position of the sensor at each pulse (m)  %
% data.Rcv.Y:  The receive y-position of the sensor at each pulse (m)  %
% data.Rcv.Z:  The receive z-position of the sensor at each pulse (m)  %
%              If no Rcv field is given, the monostataic case          %
%              (Rcv = Tx) is assumed.                                  %
% data.Nfft:  Size of the FFT to form the range profile                %
% data.hide_waitbar: Whether to suppress display of waitbar or not.    %
%                    If you call bpBasic from within a loop, you will  %
%                    probably want to use this.  Default is false.     %
%                                                                      %
% The output is:                                                       %
% complex_image:  The complex image value at each pixel                %
%                                                                      %
% History:                                                             %
%    Original code                                                     %
%       LeRoy Gorham, Air Force Research Laboratory, WPAFB, OH         %
%       leroy.gorham@wpafb.af.mil                                      %
%       Original Date Released:  8 Apr 2010                            %
%    Modified by Wade Schwartzkopf, NGA/IDT                            %
%       Wade.C.Schwartzkopf.ctr@nga.mil                                %
%       Structural changes to handle CPHD                              %
%    Modified by Daniel Andre, Dstl, Porton Down, UK                   %
%       dandre@dstl.gov.uk                                             %
%       Extension of the code to the bistatic case (1 Sep 2011)        %
%                                                                      %
% Gorham, L.A. and Moore, L.J., "SAR image formation toolbox for       %
%   MATLAB,"  Algorithms for Synthetic Aperture Radar Imagery XVII     %
%   7669, SPIE (2010).                                                 %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

%% Setup input parameters
% Determine the size of the phase history data for easier to read code
num_pulses = size(data.phdata,2);

% Maximum scene extent in range (m)
c = 299792458; % Speed of light (m/s)
max_extent_range=c/mean(data.deltaF); % Two-way range (transmitter, target, receiver)

% Setup reasonable default value for Nfft if none passed in
if ~isfield(data,'Nfft')
    data.Nfft = 2^(3+nextpow2(size(data.phdata,1))); % Use power-of-2 FFT
    % The linear interolation in the interp1 below causes cross-range
    % artifacts unless we sinc interpolate first with a much larger FFT size
    % than necessary.  Thus the "3+" in the line above.
end

% Assume monostatic case if bistatic info is not given
if ~isfield(data,'Rcv')
    data.Rcv = data.Tx;
end

show_waitbar = ~(isfield(data,'hide_waitbar')&&data.hide_waitbar);

%% Do actual backprojection computation
% Calculate the range to every bin in the range profile (m)
range_vector = linspace(-data.Nfft/2,data.Nfft/2-1,data.Nfft)*max_extent_range/data.Nfft;

% Initialize the image with all zero values
complex_image = zeros(size(data.x_mat));

if show_waitbar
    wb = waitbar(0);
    tic;
end
% Loop through every pulse
for ii = 1:num_pulses
    % Form the range profile with zero padding added
    rc = fftshift(ifft(data.phdata(:,ii),data.Nfft));

    % Calculate differential (bistatic) range for each pixel in the image (m)
    dR = sqrt((data.Tx.X(ii)-data.x_mat).^2 + ... % Range from transmit to pixel
              (data.Tx.Y(ii)-data.y_mat).^2 + ...
              (data.Tx.Z(ii)-data.z_mat).^2) + ...
         sqrt((data.Rcv.X(ii)-data.x_mat).^2 + ... % Range from receive to pixel
              (data.Rcv.Y(ii)-data.y_mat).^2 + ...
              (data.Rcv.Z(ii)-data.z_mat).^2) - ...
         (2*data.R0(ii)); % Range from transmit to motion-comp point to receive

    % Calculate phase correction for image
    phCorr = exp(1i*2*pi*data.minF(ii)/c*dR);

    % Determine which pixels fall within the range swath
    I = find(and(dR > min(range_vector), dR < max(range_vector)));

    % Update the image using linear interpolation
    complex_image(I) = complex_image(I) + interp1(range_vector,rc,dR(I),'linear') .* phCorr(I);

    if show_waitbar
        % Determine remaining execution time and display
        t_sofar = toc;
        t_est = (t_sofar*num_pulses/ii)-t_sofar;
        wb_message=sprintf('Pulse %d of %d, Time remaining: %s',ii,...
            num_pulses,datestr(datenum(0,0,0,0,0,t_est),13));
        waitbar(ii/num_pulses,wb,wb_message);
    end
end
if show_waitbar
    close(wb);
end

end

% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

author: ngageoint


text:
function  jc = findobject(fields, query, method)
% Utility function.
%
% fields is a cell array
% query is produced by query = parseContent(content);
% This function is called from several functions in the toolbox.
%
% You are probably looking for the function 'LMobjectindex'
%
% Methods:
%   [] = default = substring matching (air => chair)
%   'exact' = strings should match exactly
%   'word'  = the field should match the beggining (car => cars, air ~=> chair)

if nargin < 3
    method = '';
end

method = lower(method);
Nobjects = length(fields); jc = [];

exactFlag = 0;
if (nargin == 3)
    if strcmp(method, 'exact')% && length(query)<2
        for m = 1:length(query)
            jjc = strmatch(query{m}{1}(2:end), fields, 'exact');
            if strcmp(query{m}{1}(1), '-')
                jjc = setdiff(1:length(fields), jc);
            end
            if m == 1; jc = jjc; else jc = union(jc, jjc); end
        end
        return
    end
end

if strcmp(method, 'exact')
    exactFlag = 1;
end

% Loop on all the objects in the current image.
for m = 1:Nobjects
    %keyboard
    if isnumeric(fields{m})
        f{m} = fields{m};
    else
        f{m}=lower(strtrim(char(fields{m})));
    end

    % Find the elements that match the query and that are not deleted
    queryresult = logical(0);

    if ~isempty(f{m})
        if strcmp(method, 'word')
            w = getwords(f{m});
        end

        % this is an OR loop for all the possible queries.
        for n = 1:length(query)
            Q = (strtrim(query{n}));
            found = logical(1);
            % this is an AND loop for all the words that have to be part of the
            % content of the field.
            for q = 1:length(Q)
                switch method
                    case '<'
                        try
                            % for dates:
                            j = datenum(f{m})<datenum(Q{q}(2:end));
                        catch
                            % for other strings:
                            j = f{m}<Q{q}(2:end); j = j(1);
                        end
                    case '>'
                        try
                            % for dates:
                            j = datenum(f{m})>datenum(Q{q}(2:end));
                        catch
                            if isnumeric(f{m}); ff = f{m}; else ff = str2num(f{m}); end
                            if isnumeric(Q{q}); qq = Q{q}; else qq = str2num(Q{q}); end
                            j = ff>=qq;
                            if length(j)>0
                                j = j(1);
                            else
                                j = [];
                            end
                        end
                    case 'exact'
                        % the field content must match the search exactly
                        j = strcmp(f{m}, Q{q}(2:end));
                    case 'complementary'
                        % the field content must match the search exactly
                        j = strcmp(f{m}, Q{q}(2:end));
                    case 'word'
                        % search for exact words
                        j = strmatch(Q{q}(2:end), w, 'exact');
                    otherwise
                        % here just look if the chain is anywhere in the field
                        j = strfind(f{m}, Q{q}(2:end));
                end

                if j==0;
                    j = [];
                end

                if Q{q}(1)=='+' || ismember(method, {'<', '>'})
                    found = found & (~isempty(j));
                else
                    found = found & (isempty(j));
                end
            end
            queryresult = queryresult | found;
        end
    end
    jc(m) = queryresult;
end
jc = find(jc);

if strcmp(method, 'complementary')
    jc = setdiff(1:Nobjects, jc);
end

author: CSAILVision

repo: LabelMeToolbox


text:
function meta = get_metadata(filename, pattern)
% Read a BIDS's file metadata according to the inheritance principle
% FORMAT meta = get_metadata(filename, pattern)
% filename    - name of file following BIDS standard
% pattern     - regular expression matching metadata file
% meta        - metadata structure
%__________________________________________________________________________

% Copyright (C) 2016-2018, Guillaume Flandin, Wellcome Centre for Human Neuroimaging
% Copyright (C) 2018--, BIDS-MATLAB developers

if nargin == 1, pattern = '^.*_%s\\.json$'; end
pth = fileparts(filename);
p = parse_filename(filename);

meta = struct();

N = 3;
if isfield(p,'ses') && ~isempty(p.ses)
    N = N + 1; % there is a session level in the hierarchy
end

for n=1:N
    metafile = file_utils('FPList',pth, sprintf(pattern,p.type));
    if isempty(metafile), metafile = {}; else metafile = cellstr(metafile); end
    for i=1:numel(metafile)
        p2 = parse_filename(metafile{i});
        fn = setdiff(fieldnames(p2),{'filename','ext','type'});
        ismeta = true;
        for j=1:numel(fn)
            if ~isfield(p,fn{j}) || ~strcmp(p.(fn{j}),p2.(fn{j}))
                ismeta = false;
                break;
            end
        end
        if ismeta
            if strcmp(p2.ext,'.json')
                meta = update_metadata(meta,bids.util.jsondecode(metafile{i}));
            else
                meta.filename = metafile{i};
            end
        end
    end
    pth = fullfile(pth,'..');
end

%==========================================================================
%-Inheritance principle
%==========================================================================
function s1 = update_metadata(s1,s2)
fn = fieldnames(s2);
for i=1:numel(fn)
    if ~isfield(s1,fn{i})
        s1.(fn{i}) = s2.(fn{i});
    end
end

author: qMRLab

repo: qMRLab

save_path: github-repos/MATLAB/qMRLab-qMRLab